Пример #1
0
        public AccessionWizard(string pKeys, SharedUtils sharedUtils)
        {
            InitializeComponent();

            _accessionBindingSource = new BindingSource();
            _accessionBindingSource.ListChanged += new ListChangedEventHandler(_mainBindingSource_ListChanged);
            _accessionBindingSource.CurrentChanged += new EventHandler(_mainBindingSource_CurrentChanged);
            _accessionNameBindingSource = new BindingSource();
            _accessionSourceBindingSource = new BindingSource();
            _accessionSourceBindingSource.CurrentChanged += new EventHandler(_accessionSourceBindingSource_CurrentChanged);
            _accessionSourceCooperatorBindingSource = new BindingSource();
            _accessionSourceDescObservationBindingSource = new BindingSource();
            _accessionAnnotationBindingSource = new BindingSource();
            _accessionVoucherBindingSource = new BindingSource();
            _accessionIPRBindingSource = new BindingSource();
            _accessionQuarantineBindingSource = new BindingSource();
            _accessionPedigreeBindingSource = new BindingSource();
            _accessionActionBindingSource = new BindingSource();
            _sharedUtils = sharedUtils;
            _originalPKeys = pKeys;
            // Ignore all pkey tokens except the accession_id pkeys...
            foreach (string pkeyToken in pKeys.Split(';'))
            {
                if (pkeyToken.Split('=')[0].Trim().ToUpper() == ":ACCESSIONID") _accessionPKeys = pkeyToken;
            }
        }
Пример #2
0
        public CooperatorWizard(string pKeys, SharedUtils sharedUtils)
        {
            InitializeComponent();

            _cooperatorBindingSource = new BindingSource();
            _webCooperatorBindingSource = new BindingSource();
            _sharedUtils = sharedUtils;
            _originalPKeys = pKeys;
        }
Пример #3
0
        public InventoryImageLoader(SharedUtils sharedUtils, DataGridView imageDGV, string[] filePaths, string inventoryIDs)
        {
            InitializeComponent();

            _sharedUtils = sharedUtils;
            _imageDGV = imageDGV;
            _filePaths = filePaths;
            _inventoryIDs = inventoryIDs;
        }
Пример #4
0
        public AccessionForm(BindingSource bindingSource, bool performLookups, SharedUtils sharedUtils, bool editMode)
        {
            InitializeComponent();

            _bindingSource = bindingSource;
            _bindingSource.ListChanged += new ListChangedEventHandler(bindingSource_ListChanged);
            _sharedUtils = sharedUtils;
            _performLookups = performLookups;
            _editMode = editMode;
        }
Пример #5
0
        public SecurityWizard(string tableName, string pkeyColumnName, string pkeyCollection, SharedUtils sharedUtils)
        {
            InitializeComponent();

            _tableName = tableName;
            _pkeyColumnName = pkeyColumnName;
            _pkeyCollection = pkeyCollection;
            _sharedUtils = sharedUtils;
            _cooperatorID = _sharedUtils.UserCooperatorID;
        }
Пример #6
0
 public FKeyPicker(SharedUtils sharedUtils, string columnNameToLookup, DataRow parentRow, string currentValue)
 {
     InitializeComponent();
     // Initialize new objects to access the local lookup tables...
     _sharedUtils = sharedUtils;
     // Save the key for the cell that is being edited...
     _currentKey = parentRow[columnNameToLookup].ToString();
     _newKey = _currentKey;
     ux_textboxAccessionNumber.Text = currentValue;
     // Set event handler for timer to wait a brief time before refreshing data (afte text has been typed)...
     textChangeDelayTimer.Tick += new EventHandler(timerDelay_Tick);
 }
Пример #7
0
 public ChangePassword(string webServiceURL, string userName, string password, SharedUtils sharedUtils)
 {
     InitializeComponent();
     _webServiceURL = webServiceURL;
     _userName = userName;
     _password = password;
     _site = "";
     if (sharedUtils != null)
     {
         _sharedUtils = sharedUtils;
         _sharedUtils.UpdateControls(this.Controls, this.Name);
         _site = sharedUtils.UserSite;
     }
 }
Пример #8
0
        public CooperatorWizard(string pKeys, SharedUtils sharedUtils)
        {
            InitializeComponent();

            _cooperatorBindingSource = new BindingSource();
            _webCooperatorBindingSource = new BindingSource();
            _sharedUtils = sharedUtils;
            _originalPKeys = pKeys;
            // Ignore all pkey tokens except the cooperator_id pkeys...
            foreach (string pkeyToken in pKeys.Split(';'))
            {
                if (pkeyToken.Split('=')[0].Trim().ToUpper() == ":COOPERATORID") _cooperatorPKeys = pkeyToken;
            }
        }
Пример #9
0
        public TreeviewNodeProperties(SharedUtils sharedUtils, TreeNode currentNode)
        {
            if (sharedUtils != null)
            {
                _sharedUtils = sharedUtils;

                if (currentNode != null)
                {
                    // Remember the current node passed into this dialog...
                    _currentNode = currentNode;
                    _newProperties = _currentNode.Tag.ToString();
                }
                else
                {
                    return;
                }
            }
            InitializeComponent();
        }
Пример #10
0
        public ChangeOwnership(DataSet ownedDataset, SharedUtils sharedUtils)
        {
            InitializeComponent();
            _sharedUtils = sharedUtils;
            _ownedDataset = ownedDataset;
            DataTable cooperatorTable = _sharedUtils.GetLocalData("SELECT * FROM cooperator_lookup WHERE account_is_enabled = @accountisenabled", "@accountisenabled=Y;");
            if (cooperatorTable.Columns.Contains("display_member")) cooperatorTable.DefaultView.Sort = "display_member ASC";

            // Bind the control to the data in grinLookups...
            // WARNING!!!: You must set DisplayMember and ValueMember properties BEFORE setting
            //             DataSource - otherwise the cbCooperators.SelectedValue.ToString() method
            //             will return an object of DataRowView instead of the CNO value
            ux_comboboxNewOwner.DisplayMember = "display_member";
            ux_comboboxNewOwner.ValueMember = "value_member";
            ux_comboboxNewOwner.DataSource = cooperatorTable;
            sharedUtils.UpdateControls(this.Controls, this.Name);
            ux_radiobuttonSelectedRowsOnly.Checked = false;
            ux_radiobuttonSelectedRowsAndChildren.Checked = false;
            ux_buttonOk.Enabled = false;
            ux_comboboxNewOwner.SelectedIndex = -1;
        }
Пример #11
0
        public bool ProcessDGVEditShortcutKeys(DataGridView dgv, KeyEventArgs e, string cno, LookupTables lookupTables, AppSettings appSettings)
        {
            bool keyProcessed = false;

            // Change cursor to the wait cursor...
            Cursor origCursor = Cursor.Current;
            Cursor.Current = Cursors.WaitCursor;

            if (e.KeyCode == Keys.D && e.Control)
            {
                Dictionary<int, int> selectedColumnMinRow = new Dictionary<int, int>();

                // Processing keystroke...
                keyProcessed = true;

                foreach (DataGridViewCell cell in dgv.SelectedCells)
                {
                    // If the min selected row has not been found for this column - find it now...
                    if (!selectedColumnMinRow.ContainsKey(cell.ColumnIndex))
                    {
                        int minRow = dgv.Rows.Count; ;
                        // Find the minimum row index in this column's selected cells...
                        minRow = cell.RowIndex;
                        for (int i = minRow; i > -1; i--)
                        {
                            if (dgv.SelectedCells.Contains(dgv[cell.ColumnIndex, i])) minRow = i;
                        }
                        // If the user is trying to perform a copy down (CTRL+D) using the row for adding a new row as the source row - bail out now...
                        if (dgv.Rows[minRow].IsNewRow) return false;

                        //Save the min row for this column in the dictionary
                        selectedColumnMinRow.Add(cell.ColumnIndex, minRow);
                    }

                    //
                    object newValue = ((DataRowView)dgv.Rows[selectedColumnMinRow[cell.ColumnIndex]].DataBoundItem)[cell.ColumnIndex];
                    DataRowView dr = (DataRowView)cell.OwningRow.DataBoundItem;
                    if (dr == null) //if (dgv.Rows[row].IsNewRow)
                    {
                        // Couldn't find a bound row so this must be the 'new row' row in the datagrid...
                        dgv[cell.ColumnIndex, cell.RowIndex].Value = newValue;
                        dgv.UpdateCellValue(cell.ColumnIndex, cell.RowIndex);
                    }
                    else
                    {
                        if (!dr[cell.ColumnIndex].Equals(newValue))
                        {
                            // Edit the DataRow (not the DataRowView) so that row state is changed...
                            dr.Row[cell.ColumnIndex] = newValue;
                        }
                    }
                }
            }

            if (e.KeyCode == Keys.E && e.Control)
            {
                // Processing keystroke...
                keyProcessed = true;

                DataRow dr = ((DataRowView)dgv.CurrentCell.OwningRow.DataBoundItem).Row;
                string columnName = dgv.CurrentCell.OwningColumn.Name;
                if (dr.Table.Columns[columnName].ExtendedProperties.ContainsKey("gui_hint") &&
                    dr.Table.Columns[columnName].ExtendedProperties["gui_hint"].ToString().ToUpper() == "TEXT_CONTROL")
                {
                    string currentCellValue = dr[columnName].ToString();
                    RichTextEditor rte = new RichTextEditor(currentCellValue, false);
                    if (rte.ShowDialog() == DialogResult.OK)
                    {
                        dr[columnName] = rte.RichTextMessage;
                    }
                }
            }

            if (e.KeyCode == Keys.N && e.Control)
            {
                if (dgv.CurrentRow != null &&
                    dgv.CurrentRow.Selected &&
                    !dgv.CurrentRow.IsNewRow)
                {
                    DataTable dt = (DataTable)((BindingSource)dgv.DataSource).DataSource;
                    DataRow sourceRow = null;
                    DataRow destRow = null;

                    // Processing keystroke...
                    keyProcessed = true;

                    if (dt != null)
                    {
                        sourceRow = dt.DefaultView[dgv.CurrentRow.Index].Row;
                        destRow = dt.NewRow();
                    }
                    if (sourceRow != null)
                    {
                        foreach (DataColumn dc in dt.Columns)
                        {
                            if (!dt.PrimaryKey.Contains(dc) &&
                                !dc.ReadOnly)
                            {
                                switch (dc.ColumnName)
                                {
                                    case "created_by":
                                    case "owned_by":
                                        if (string.IsNullOrEmpty(cno))
                                        {
                                            destRow[dc] = sourceRow[dc];
                                        }
                                        else
                                        {
                                            destRow[dc] = cno;
                                        }
                                        break;
                                    case "created_date":
                                    case "owned_date":
                                        destRow[dc] = DateTime.Now;
                                        break;
                                    case "modified_by":
                                    case "modified_date":
                                        break;
                                    default:
                                        // Column is not a required field (or is a boolean field that only allows Y or N)
                                        destRow[dc] = sourceRow[dc];
                                        break;
                                }
                            }
                        }
                        dt.Rows.InsertAt(destRow, dgv.CurrentRow.Index + 1);
            //RefreshDGVRowFormatting(dgv.Rows[dgv.CurrentRow.Index + 1], ux_checkboxHighlightChanges.Checked);
                    }
                }
            }

            if (e.KeyCode == Keys.OemQuotes && e.Control)
            {
                if (dgv.CurrentRow != null &&
                    dgv.CurrentRow.Index > 0)
                {
                    int sourceRowIndex;
                    DataRow sourceRow;
                    DataRow destinationRow;

                    // Processing keystroke...
                    keyProcessed = true;

                    if (dgv.CurrentRow.IsNewRow)
                    {
                        dgv.BeginEdit(true);
                        sourceRowIndex = dgv.CurrentRow.Index - 1;
                        sourceRow = ((DataRowView)dgv.Rows[sourceRowIndex].DataBoundItem).Row;
                        destinationRow = ((DataRowView)dgv.CurrentRow.DataBoundItem).Row;
                    }
                    else
                    {
                        sourceRowIndex = dgv.CurrentRow.Index - 1;
                        sourceRow = ((DataRowView)dgv.Rows[sourceRowIndex].DataBoundItem).Row;
                        destinationRow = ((DataRowView)dgv.CurrentRow.DataBoundItem).Row;
                    }

                    if (sourceRow != null && destinationRow != null)
                    {
                        if (!destinationRow[dgv.CurrentCell.ColumnIndex].Equals(sourceRow[dgv.CurrentCell.ColumnIndex]))
                        {
                            if (!dgv.Columns[dgv.CurrentCell.ColumnIndex].ReadOnly)
                            {
                                destinationRow[dgv.CurrentCell.ColumnIndex] = sourceRow[dgv.CurrentCell.ColumnIndex];
                            }
                        }
                    }
            //RefreshDGVRowFormatting(dgv.CurrentCell.OwningRow, ux_checkboxHighlightChanges.Checked);
                }
            }

            if (e.KeyCode == Keys.V && e.Control)
            {
                IDataObject dataObj = Clipboard.GetDataObject();
                string pasteText = "";
                //string[] junk = dataObj.GetFormats();
                if (dataObj.GetDataPresent(System.Windows.Forms.DataFormats.UnicodeText))
                {
                    char[] rowDelimiters = new char[] { '\r', '\n' };
                    char[] columnDelimiters = new char[] { '\t' };
                    int badRows = 0;
                    int missingRows = 0;
                    bool importSuccess = false;

                    // Processing keystroke...
                    keyProcessed = true;

                    pasteText = dataObj.GetData(DataFormats.UnicodeText).ToString();
                    DataTable dt = (DataTable)((BindingSource)dgv.DataSource).DataSource;
                    importSuccess = ImportTextToDataTableUsingKeys(pasteText, dt, rowDelimiters, columnDelimiters, out badRows, out missingRows, lookupTables, appSettings);
                    if (!importSuccess)
                    {
                        // Paste the text into the DGV in 'block style'
                        importSuccess = ImportTextToDataTableUsingBlockStyle(pasteText, dgv, rowDelimiters, columnDelimiters, out badRows, out missingRows, lookupTables, appSettings);
                    }
            //RefreshMainDGVFormatting();
            //RefreshForm();
                }
            }

            if (e.KeyCode == Keys.C && e.Control)
            {
                string copyString = "";
                // First we need to get the min/max rows and columns for the selected cells...
                int minCol = dgv.Columns.Count;
                int maxCol = -1;
                int minRow = dgv.Rows.Count;
                int maxRow = -1;

                // Processing keystroke...
                keyProcessed = true;

                foreach (DataGridViewCell dgvc in dgv.SelectedCells)
                {
                    if (dgvc.ColumnIndex < minCol) minCol = dgvc.ColumnIndex;
                    if (dgvc.ColumnIndex > maxCol) maxCol = dgvc.ColumnIndex;
                    if (dgvc.RowIndex < minRow) minRow = dgvc.RowIndex;
                    if (dgvc.RowIndex > maxRow) maxRow = dgvc.RowIndex;
                }

                // First, gather the column headers (but only if the entire row was selected)...
                if (dgv.SelectedRows.Count != 0)
                {
                    for (int i = minCol; i <= maxCol; i++)
                    {
                        copyString += dgv.Columns[i].HeaderText + '\t';
                        //copyString += dgv.Columns[i].Name + '\t';
                    }

                    // Strip the last tab and insert a newline...
                    copyString = copyString.TrimEnd('\t');
                    copyString += "\r\n";
                }
                // Now build the string to pass to the clipboard...
                for (int i = minRow; i <= maxRow; i++)
                {
                    for (int j = minCol; j <= maxCol; j++)
                    {
                        switch (dgv[j, i].FormattedValueType.Name)
                        {
                            case "Boolean":
                                copyString += dgv[j, i].Value.ToString() + '\t';
                                break;
                            default:
                                if (dgv[j, i].FormattedValue == null || dgv[j, i].FormattedValue.ToString().ToLower() == "[null]")
                                {
                                    copyString += "" + '\t';
                                }
                                else
                                {
                                    copyString += dgv[j, i].FormattedValue.ToString() + '\t';
                                }
                                break;
                        }
                    }
                    copyString = copyString.TrimEnd('\t');
                    copyString += "\r\n";
                }
                copyString = copyString.TrimEnd('\n');
                copyString = copyString.TrimEnd('\r');

                // Pass the new string to the clipboard...
                Clipboard.SetDataObject(copyString, false, 1, 1000);

            //RefreshMainDGVFormatting();
            //RefreshForm();
            }

            if (e.KeyCode == Keys.Delete)
            {
                // Processing keystroke...
                keyProcessed = true;

                if (dgv.SelectedRows.Count == 0)
                {
                    // The user is deleting values from individual selected cells (not entire rows)...
                    foreach (DataGridViewCell dgvc in dgv.SelectedCells)
                    {
                        DataRowView drv = (DataRowView)dgvc.OwningRow.DataBoundItem;
                        if (drv == null) //if (dgv.Rows[row].IsNewRow)
                        {
                            dgvc.Value = "";
                            dgv.UpdateCellValue(dgvc.ColumnIndex, dgvc.RowIndex);
                            //dgv[dgvc.ColumnIndex, dgvc.RowIndex].Style.BackColor = Color.Yellow;
                        }
                        else
                        {
                            if (!drv[dgvc.OwningColumn.Index].Equals(DBNull.Value))
                            {
                                if (!dgvc.ReadOnly)
                                {
                                    // Edit the DataRow (not the DataRowView) so that row state is changed...
                                    drv.Row[dgvc.OwningColumn.Index] = DBNull.Value;
                                    // For unbound text cells we have to manually clear the cell's text...
                                    if (string.IsNullOrEmpty(dgvc.OwningColumn.DataPropertyName)) dgvc.Value = "";
                                    dgv.UpdateCellValue(dgvc.ColumnIndex, dgvc.RowIndex);
                                    //dgv[dgvc.ColumnIndex, dgvc.RowIndex].Style.BackColor = Color.Yellow;
                                }
                            }
                        }
            //RefreshDGVRowFormatting(dgvc.OwningRow, ux_checkboxHighlightChanges.Checked);
                    }
                }
                else
                {
                    // The user is attempting to delete entire rows from the datagridview...
            //SharedUtils sharedUtils = new SharedUtils(lookupTables.WebServiceURL, lookupTables.Username, lookupTables.Password_ClearText, true);
            SharedUtils sharedUtils = new SharedUtils(_webServices.Url, _webServices.Username, _webServices.Password_ClearText, true, "");
            GRINGlobal.Client.Common.GGMessageBox ggMessageBox = new GRINGlobal.Client.Common.GGMessageBox("WARNING!!!  You are about to permanently delete {0} records from the central database!\n\nAre you sure you want to do this?", "Record Delete Confirmation", MessageBoxButtons.OKCancel, MessageBoxDefaultButton.Button2);
            ggMessageBox.Name = "UserInterfaceUtils_ProcessDGVEditShortcutKeysMessage1";
            if (sharedUtils != null && sharedUtils.IsConnected) sharedUtils.UpdateControls(ggMessageBox.Controls, ggMessageBox.Name);
            //if (ggMessageBox.MessageText.Contains("{0}")) ggMessageBox.MessageText = string.Format(ggMessageBox.MessageText, dgv.SelectedRows.Count.ToString());
            string[] argsArray = new string[100];
            argsArray[0] = dgv.SelectedRows.Count.ToString();
            ggMessageBox.MessageText = string.Format(ggMessageBox.MessageText, argsArray);
            //if (DialogResult.OK == MessageBox.Show("WARNING!!!  You are about to permanently delete " + dgv.SelectedRows.Count.ToString() + " records from the central database!\n\nAre you sure you want to do this?", "Record delete confirmation", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2))
            if (DialogResult.OK == ggMessageBox.ShowDialog())
                    {
                        foreach (DataGridViewRow dgvr in dgv.SelectedRows)
                        {
                            dgv.Rows.Remove(dgvr);
                        }
                    }
            e.Handled = true;
                }
            }

            // Restore cursor to default cursor...
            Cursor.Current = origCursor;

            return keyProcessed;
        }
Пример #12
0
        public bool ImportTextToDataTableUsingKeys(string rawImportText, DataTable destinationTable, char[] rowDelimiters, char[] columnDelimiters, out int badRows, out int missingRows, LookupTables lookupTables, AppSettings appSettings)
        {
            string replacementTextForEmbeddedNewLines = "<br>";
            if (!string.IsNullOrEmpty(appSettings.GetAppSettingValue("GrinGlobalClient_replacementTextForEmbeddedNewLines")))
            {
            replacementTextForEmbeddedNewLines = appSettings.GetAppSettingValue("GrinGlobalClient_replacementTextForEmbeddedNewLines");
            }
            string scrubbedRawImportText = "";
            // Attempting to remove new lines with no matching carriage return (ex. \n with no leading \r) and vice versa (ex. \r with no trailing \n)...
            // First protect the well-formed carriage return line feed (\r\n) by temp. removing it and substituting a placeholder (to aid in weeding out lone \n and \r)...
            scrubbedRawImportText = rawImportText.Replace("\r\n", "***well-formed carriage return line feed***").Replace("\n\r", "***well-formed carriage return line feed***");
            // Now remove any remaining lone \n or \r that cannot be processed properly...
            scrubbedRawImportText = scrubbedRawImportText.Replace("\r", replacementTextForEmbeddedNewLines).Replace("\n", replacementTextForEmbeddedNewLines);
            // Next return the well-formed carriage return line feeds back where they belong...
            scrubbedRawImportText = scrubbedRawImportText.Replace("***well-formed carriage return line feed***", "\r\n");
            //string[] rawImportRows = rawImportText.Split(rowDelimiters, StringSplitOptions.RemoveEmptyEntries);
            string[] rawImportRows = scrubbedRawImportText.Split(rowDelimiters, StringSplitOptions.RemoveEmptyEntries);
            string[] uniqueKeyColumnNames = null;
            bool primaryKeyFound = false;
            System.Collections.Generic.List<DataColumn> uniqueKeys = new System.Collections.Generic.List<DataColumn>();
            bool processedImportSuccessfully = false;
            badRows = 0;
            missingRows = 0;
            // Make sure there is text to process - if not bail out now...
            if (rawImportRows == null || rawImportRows.Length <= 0) return false;
            // Begin looking for a row of raw text that contains the column headers for the destination datatable...
            // This is a 2 phase approach that first looks for a row that contains all of the primary key column names
            // But if that is not found - try again to find a row of raw text that contains all of the column names for the unique compound key
            int columnHeaderRowIndex = -1;
            // PHASE 1:
            // Look for a raw text line that contains the full text name of the primary key columns (they must all be on the same line of raw text)...
            if (destinationTable.PrimaryKey.Length > 0)
            {
                // Look through all of the rows of raw text for a single row that contains all of the primary key column names
                for (int i = 0; i < rawImportRows.Length && columnHeaderRowIndex == -1; i++)
                {
                    columnHeaderRowIndex = i; // Start out ASSUMING this is the 'right' row...
                    foreach (DataColumn pKeyColumn in destinationTable.PrimaryKey)
                    {
                        if (!FindText(GetFriendlyFieldName(pKeyColumn, pKeyColumn.ColumnName), rawImportRows[i], false, rowDelimiters, columnDelimiters))
                        {
                            // If the column header was not matched using case sensitive - try matching again (case insensitive)...
                            if (!FindText(GetFriendlyFieldName(pKeyColumn, pKeyColumn.ColumnName), rawImportRows[i], true, rowDelimiters, columnDelimiters))
                            {
                                // If the column header was still not matched - try the raw table field name...
                                if (!FindText(pKeyColumn.ColumnName, rawImportRows[i], true, rowDelimiters, columnDelimiters))
                                {
                                    // The ASSUMPTION was wrong because the header text for one of the required primary key columns is missing in this raw text row...
                                    columnHeaderRowIndex = -1;
                                }
                            }
                        }
                    }
                }
                if (columnHeaderRowIndex != -1) primaryKeyFound = true;
                // Check to see if we need to move on to PHASE 2...
                if (!primaryKeyFound)
                {
                    // PHASE 2:
                    // Didn't find the primary key column in any text row in the import data - so try again, but this time looking for the alternate unique key...
                    if (destinationTable.PrimaryKey[0].ExtendedProperties.Contains("alternate_key_fields") &&
                        destinationTable.PrimaryKey[0].ExtendedProperties["alternate_key_fields"].ToString().Length > 0)
                    {
                        uniqueKeyColumnNames = destinationTable.PrimaryKey[0].ExtendedProperties["alternate_key_fields"].ToString().Split(',');
                        // Make sure the destination datatable has all of the columns specified in the alternate_key_fields ext. prop...
                        foreach (string uniqueColumnName in uniqueKeyColumnNames)
                        {
                            if (destinationTable.Columns.Contains(uniqueColumnName.Trim().ToLower()))
                            {
                                uniqueKeys.Add(destinationTable.Columns[uniqueColumnName.Trim().ToLower()]);
                            }
                        }
                        // The destination datatable does not have all of the columns specified in the compound unique key so bail out now...
                        if (uniqueKeys.Count != uniqueKeyColumnNames.Length) return false;
                        // Look through all of the rows of raw text for a single row that contains all of the unique key column names
                        for (int i = 0; i < rawImportRows.Length && columnHeaderRowIndex == -1; i++)
                        {
                            columnHeaderRowIndex = i; // Start out assuming the row has all of the unique key column headers...
                            foreach (DataColumn uKeyColumn in uniqueKeys)
                            {
                                if (!FindText(GetFriendlyFieldName(uKeyColumn, uKeyColumn.ColumnName), rawImportRows[i], false, rowDelimiters, columnDelimiters))
                                {
                                    // If the column header was not matched using case sensitive - try matching again (case insensitive)...
                                    if (!FindText(GetFriendlyFieldName(uKeyColumn, uKeyColumn.ColumnName), rawImportRows[i], true, rowDelimiters, columnDelimiters))
                                    {
                                        // If the column header was still not matched - try the raw table field name...
                                        if (!FindText(uKeyColumn.ColumnName, rawImportRows[i], true, rowDelimiters, columnDelimiters))
                                        {
                                            // The ASSUMPTION was wrong because the header text for one of the required unique key columns is missing in this raw text row...
                                            columnHeaderRowIndex = -1;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                // Check to see if a column header was found for the psuedo-primary key of the destinationTable...
                if (columnHeaderRowIndex == -1)
                {
                    // Still cannot find an import row with column text that contains a collection of unique key columns - ask the user if they want to bail out now...
            string uniqueKeyColumnFriendlyNames = "";
            foreach (DataColumn dc in uniqueKeys)
            {
            uniqueKeyColumnFriendlyNames += GetFriendlyFieldName(dc, dc.ColumnName) + ", ";
            }
            uniqueKeyColumnFriendlyNames = uniqueKeyColumnFriendlyNames.Trim().TrimEnd(',');
            //SharedUtils sharedUtils = new SharedUtils(lookupTables.WebServiceURL, lookupTables.Username, lookupTables.Password_ClearText, true);
            SharedUtils sharedUtils = new SharedUtils(_webServices.Url, _webServices.Username, _webServices.Password_ClearText, true, "");
            GRINGlobal.Client.Common.GGMessageBox ggMessageBox = new GRINGlobal.Client.Common.GGMessageBox("WARNING!!!  You are pasting data in to this dataview without column headers that include: \n   1) The primary key column ({0}) OR \n   2) A combination of all of the columns ({1}) that will uniquely identify a single record in this dataview.\n\nWould you like to paste the data directly to the dataview starting at the selected cell?", "Missing Columns", MessageBoxButtons.YesNo, MessageBoxDefaultButton.Button1);
            ggMessageBox.Name = "UserInterfaceUtils_ImportTextToDataTableUsingKeysMessage1";
            if (sharedUtils != null && sharedUtils.IsConnected) sharedUtils.UpdateControls(ggMessageBox.Controls, ggMessageBox.Name);
            //if (ggMessageBox.MessageText.Contains("{0}") &&
            //    ggMessageBox.MessageText.Contains("{1}"))
            //{
            //    ggMessageBox.MessageText = string.Format(ggMessageBox.MessageText, GetFriendlyFieldName(destinationTable.PrimaryKey[0], destinationTable.PrimaryKey[0].ColumnName), uniqueKeyColumnFriendlyNames);
            //}
            //else if (ggMessageBox.MessageText.Contains("{0}"))
            //{
            //    ggMessageBox.MessageText = string.Format(ggMessageBox.MessageText, GetFriendlyFieldName(destinationTable.PrimaryKey[0], destinationTable.PrimaryKey[0].ColumnName));
            //}
            //else if (ggMessageBox.MessageText.Contains("{1}"))
            //{
            //    ggMessageBox.MessageText = string.Format(ggMessageBox.MessageText, uniqueKeyColumnFriendlyNames);
            //}
            string[] argsArray = new string[100];
            argsArray[0] = GetFriendlyFieldName(destinationTable.PrimaryKey[0], destinationTable.PrimaryKey[0].ColumnName);
            argsArray[1] = uniqueKeyColumnFriendlyNames;
            ggMessageBox.MessageText = string.Format(ggMessageBox.MessageText, argsArray);
            // Ask the user if they wish to perform a 'block paste' of the data...
            if (DialogResult.Yes == ggMessageBox.ShowDialog())
            {
            return false;
            }
            else
            {
            return true;
            }
                }

                // Since we made it here, it looks like we found a row in the import text that contains the column names for the destination tables primary/unique key...
                string[] importColumnNames = rawImportRows[columnHeaderRowIndex].Split(columnDelimiters, StringSplitOptions.None);
                System.Collections.Generic.Dictionary<string, int> columnNameMap = new System.Collections.Generic.Dictionary<string, int>();
                // So now we need to build a map of datatable columns in import text columns (because they may not be in the same order)...
                for (int i = 0; i < importColumnNames.Length; i++)
                {
                    // Map the friendly field name from the incoming text to the matching column in the datatable (case sensitive)...
                    foreach (DataColumn dc in destinationTable.Columns)
                    {
                        if (GetFriendlyFieldName(dc, dc.ColumnName) == importColumnNames[i])
                        {
                            columnNameMap.Add(dc.ColumnName, i);
                        }
                    }
                    // If the column header was not matched - try matching again (case insensitive)...
                    if (!columnNameMap.ContainsValue(i))
                    {
                        // Map the friendly field name from the incoming text to the matching column in the datatable (case insensitive)...
                        foreach (DataColumn dc in destinationTable.Columns)
                        {
                            if (GetFriendlyFieldName(dc, dc.ColumnName).ToLower() == importColumnNames[i].ToLower())
                            {
                                columnNameMap.Add(dc.ColumnName, i);
                            }
                        }
                    }
                    // If the column header was still not matched - try the raw table field name...
                    if (!columnNameMap.ContainsValue(i))
                    {
                        // Map the friendly field name from the incoming text to the matching column in the datatable (case insensitive)...
                        foreach (DataColumn dc in destinationTable.Columns)
                        {
                            if (dc.ColumnName.ToLower() == importColumnNames[i].ToLower())
                            {
                                columnNameMap.Add(dc.ColumnName, i);
                            }
                        }
                    }
                }

                // Now that we have the column map, start processing the rows (starting with the one right after the column header row)...
                for (int i = columnHeaderRowIndex + 1; i < rawImportRows.Length; i++)
                {
                    DataRow dr = null;
                    string[] rawFieldData = rawImportRows[i].Split(columnDelimiters, StringSplitOptions.None);
                    if (primaryKeyFound)
                    {
                        System.Collections.Generic.List<object> rowKeys = new System.Collections.Generic.List<object>();
                        // Build the primary key to get the row to edit...
                        foreach (DataColumn pKeyColumn in destinationTable.PrimaryKey)
                        {
                            object keyValue;
                            if (string.IsNullOrEmpty(rawFieldData[columnNameMap[pKeyColumn.ColumnName]].ToString()))
                            {
                                keyValue = DBNull.Value;
                            }
                            else
                            {
                                keyValue = rawFieldData[columnNameMap[pKeyColumn.ColumnName]];
                            }
                            rowKeys.Add(keyValue);
                        }
                        // Get the row to update (or create a new one for insert if an existing one is not found)...
                        // First - attempt to find a row in the DataTable that matches the primary key(s)...
                        try
                        {
                            dr = destinationTable.Rows.Find(rowKeys.ToArray());
                        }
                        catch
                        {
                            // There was an error in the row key data - so bail out and do nothing...
                        }
                        if (dr == null)
                        {
                            // No row exists in this DataTable for the given primary key(s), so create a new blank row to fill...
                            dr = destinationTable.NewRow();
                            // and add it to the DataTable...
                            destinationTable.Rows.Add(dr);
                        }
                    }
                    else // Find the row using the unique keys...
                    {
                        DataRow[] matchingRows = null;
                        string rowFilter = "";
                        foreach (DataColumn uKeyColumn in uniqueKeys)
                        {
                            if (columnNameMap[uKeyColumn.ColumnName] >= 0 &&
                                columnNameMap[uKeyColumn.ColumnName] <= (rawFieldData.Length - 1) &&
                                !string.IsNullOrEmpty(rawFieldData[columnNameMap[uKeyColumn.ColumnName]]))
                            {
                                string newValue = "";
                                // Perform a reverse lookup to get the key if this is a ForeignKey field...
                                if (lookupTables.IsValidFKField(uKeyColumn))
                                {
                                    if (!string.IsNullOrEmpty(rawFieldData[columnNameMap[uKeyColumn.ColumnName]].ToString().Trim()))
                                    {
                                        newValue = lookupTables.GetPKeyValueMember(dr, uKeyColumn.ExtendedProperties["foreign_key_dataview_name"].ToString(),
                                                                                   rawFieldData[columnNameMap[uKeyColumn.ColumnName]].ToString().Trim(),
                                                                                    -1).ToString();
                                        // If the lookup attempt returned the default value - indicate to the user that the lookup failed...
                                        if (newValue.Equals("-1"))
                                        {
                                            dr.SetColumnError(uKeyColumn.ColumnName, "\tCould not find lookup value: " + rawFieldData[columnNameMap[uKeyColumn.ColumnName]].ToString());
                                        }
                                    }
                                }
                                // Perform a reverse lookup to get the value if this is a Code_Value field...
                                else if (lookupTables.IsValidCodeValueField(uKeyColumn))
                                {
                                    if (!string.IsNullOrEmpty(rawFieldData[columnNameMap[uKeyColumn.ColumnName]].ToString().Trim()))
                                    {
                                        newValue = lookupTables.GetCodeValueValueMember(rawFieldData[columnNameMap[uKeyColumn.ColumnName]].ToString(),
                                                                                        uKeyColumn.ExtendedProperties["group_name"].ToString(),
                                                                                        "!Error! - GetValueMember method failed to find display member");
                                        // If the lookup attempt returned the default value - indicate to the user that the lookup failed...
                                        if (newValue.Equals("!Error! - GetValueMember method failed to find display member"))
                                        {
                                            dr.SetColumnError(uKeyColumn.ColumnName, "\tCould not find lookup value: " + rawFieldData[columnNameMap[uKeyColumn.ColumnName]].ToString());
                                        }
                                    }
                                }
                                // Doesn't require a lookup...
                                else
                                {
                                    newValue = rawFieldData[columnNameMap[uKeyColumn.ColumnName]];
                                }

                                if (uKeyColumn.DataType == typeof(string))
                                {
                                    rowFilter += uKeyColumn.ColumnName + "='" + newValue + "' AND ";
                                }
                                else
                                {
                                    rowFilter += uKeyColumn.ColumnName + "=" + newValue + " AND ";
                                }
                            }
                            else
                            {
                                rowFilter += uKeyColumn.ColumnName + " IS NULL AND ";
                            }
                        }
                        rowFilter = rowFilter.Substring(0, rowFilter.LastIndexOf(" AND "));
                        try
                        {
                            matchingRows = destinationTable.Select(rowFilter);
                        }
                        catch
                        {
                            matchingRows = new DataRow[] { };
                        }

                        if (matchingRows.Length > 0)
                        {
                            dr = matchingRows[0];
                        }
                        else
                        {
                            // Could not find a matching row, so set the dr to null (this will effectively ignore this import record)
                            //dr = null;
                            // No row exists in this DataTable for the given primary key(s), so create a new blank row to fill...
                            dr = destinationTable.NewRow();
                            // and add it to the DataTable...
                            destinationTable.Rows.Add(dr);
                        }
                    }
                    if (dr != null)
                    {
                        populateRowWithImportData(dr, rawFieldData, columnNameMap, lookupTables);
                    }
                    else
                    {
                        missingRows++;
                    }
                }
            }
            processedImportSuccessfully = true;

            return processedImportSuccessfully;
        }
Пример #13
0
        public bool ImportTextToDataTableUsingBlockStyle(string rawImportText, DataGridView dgv, char[] rowDelimiters, char[] columnDelimiters, out int badRows, out int missingRows, LookupTables lookupTables, AppSettings appSettings)
        {
            bool processedImportSuccessfully = true;
            DataTable destinationTable = (DataTable)((BindingSource)dgv.DataSource).DataSource;
            string replacementTextForEmbeddedNewLines = "<br>";
            if (!string.IsNullOrEmpty(appSettings.GetAppSettingValue("GrinGlobalClient_replacementTextForEmbeddedNewLines")))
            {
            replacementTextForEmbeddedNewLines = appSettings.GetAppSettingValue("GrinGlobalClient_replacementTextForEmbeddedNewLines");
            }
            string scrubbedRawImportText = "";
            // Attempting to remove new lines with no matching carriage return (ex. \n with no leading \r) and vice versa (ex. \r with no trailing \n)...
            // First protect the well-formed carriage return line feed (\r\n) by temp. removing it and substituting a placeholder (to aid in weeding out lone \n and \r)...
            scrubbedRawImportText = rawImportText.Replace("\r\n", "***well-formed carriage return line feed***").Replace("\n\r", "***well-formed carriage return line feed***");
            // Now remove any remaining lone \n or \r that cannot be processed properly...
            scrubbedRawImportText = scrubbedRawImportText.Replace("\r", replacementTextForEmbeddedNewLines).Replace("\n", replacementTextForEmbeddedNewLines);
            // Next return the well-formed carriage return line feeds back where they belong...
            scrubbedRawImportText = scrubbedRawImportText.Replace("***well-formed carriage return line feed***", "\r\n");
            // Finally strip off leading and trailing double quotes - typically added by Excel when it embeds a new line character using the ALT-Enter keystroke...
            if (scrubbedRawImportText.Trim().StartsWith("\"") && scrubbedRawImportText.Trim().EndsWith("\""))
            {
            scrubbedRawImportText = scrubbedRawImportText.Trim().TrimStart('"').TrimEnd('"');
            }
            //string[] rawImportRows = rawImportText.Split(rowDelimiters, StringSplitOptions.RemoveEmptyEntries);
            //string[] rawImportRows = scrubbedRawImportText.Split(rowDelimiters, StringSplitOptions.RemoveEmptyEntries);
            string[] rawImportRows = scrubbedRawImportText.Split(new string[] { "\r\n" }, StringSplitOptions.None);
            string[] tempColumns = null;
            string newImportText = "";
            string newImportRowText = "";
            badRows = 0;
            missingRows = 0;

            // If the DGV does not have a currently active cell bail out now...
            if (dgv.CurrentCell == null) return false;
            // If the import string is empty bail out now...
            if (string.IsNullOrEmpty(rawImportText) || rawImportRows.Length < 1) return false;

            // Okay we need to build a new importText string that has column headers that include the friendly names for the primary key columns
            // and the friendly names for the dgv columns starting at the currenly active cell in the dgv...  Why are we doing this?  Because
            // we are going to pass this new importText string off to the 'ImportTextToDataTableUsingKeys' method, and since that method
            // requires a primary key or alternate pkey we are going to get them from the dgv starting at the current row of the current cell...

            // Step 1 - Determine the number of rows and columns in the incoming rawImportText (to use later for building the new ImportText string)...
            int rawImportRowCount = 0;
            int rawImportColCount = 0;
            // Estimate the number of rows and columns in the import text (assumes a rectangular shape)
            if (rawImportRows != null && rawImportRows.Length > 0)
            {
                rawImportRowCount = rawImportRows.Length;
                tempColumns = rawImportRows[0].Split(columnDelimiters, StringSplitOptions.None);
                if (tempColumns != null && tempColumns.Length > 0)
                {
                    rawImportColCount = tempColumns.Length;
                }
            }

            int minSelectedCol = dgv.Columns.Count;
            int maxSelectedCol = -1;
            int minSelectedRow = dgv.Rows.Count;
            int maxSelectedRow = -1;
            // Check to see if the datagridview's selected cells contains the CurrentCell
            // and if so use the selected cells as the destination cells...

            // If no cells were selected for pasting the data bail out now...
            if (dgv.SelectedCells.Count == 0)
            {
            //SharedUtils sharedUtils = new SharedUtils(lookupTables.WebServiceURL, lookupTables.Username, lookupTables.Password_ClearText, true);
            SharedUtils sharedUtils = new SharedUtils(_webServices.Url, _webServices.Username, _webServices.Password_ClearText, true, "");
            GRINGlobal.Client.Common.GGMessageBox ggMessageBox = new GRINGlobal.Client.Common.GGMessageBox("WARNING!!!  You must select the destination cell(s) in this dataview before pasting data without column headers", "No Destination Cells Selected", MessageBoxButtons.OK, MessageBoxDefaultButton.Button1);
            ggMessageBox.Name = "UserInterfaceUtils_ImportTextToDataTableUsingBlockStyleMessage1";
            if (sharedUtils != null && sharedUtils.IsConnected) sharedUtils.UpdateControls(ggMessageBox.Controls, ggMessageBox.Name);
            ggMessageBox.ShowDialog();
            return false;
            }
            // Find the bounding rectangle for the selected cells...
            if (dgv.SelectedCells.Count == 1)
            {
                minSelectedCol = dgv.CurrentCell.ColumnIndex;
                maxSelectedCol = dgv.CurrentCell.ColumnIndex + rawImportColCount - 1;
                minSelectedRow = dgv.CurrentCell.RowIndex;
                maxSelectedRow = dgv.CurrentCell.RowIndex + rawImportRowCount - 1;
            }
            else
            {
                foreach (DataGridViewCell dgvc in dgv.SelectedCells)
                {
                    if (dgvc.ColumnIndex < minSelectedCol) minSelectedCol = dgvc.ColumnIndex;
                    if (dgvc.ColumnIndex > maxSelectedCol) maxSelectedCol = dgvc.ColumnIndex;
                    if (dgvc.RowIndex < minSelectedRow) minSelectedRow = dgvc.RowIndex;
                    if (dgvc.RowIndex > maxSelectedRow) maxSelectedRow = dgvc.RowIndex;
                }
                if ((maxSelectedCol - minSelectedCol) < (rawImportColCount - 1)) maxSelectedCol = minSelectedCol + rawImportColCount - 1;
                if ((maxSelectedRow - minSelectedRow) < (rawImportRowCount - 1)) maxSelectedRow = minSelectedRow + rawImportRowCount - 1;
            }

            string modifiedImportText = "";
            // Now fill (or clip) the import data to fit the selected cells...
            for (int iSelectedRow = 0; iSelectedRow <= (maxSelectedRow - minSelectedRow); iSelectedRow++)
            {
                //
                tempColumns = rawImportRows[iSelectedRow % rawImportRowCount].Split(columnDelimiters, StringSplitOptions.None);
                for (int iSelectedCol = 0; iSelectedCol <= (maxSelectedCol - minSelectedCol); iSelectedCol++)
                {
                    //
                    modifiedImportText += tempColumns[iSelectedCol % rawImportColCount] + "\t";
                }
                // Strip the last tab character and add a CR LF...
                modifiedImportText = modifiedImportText.Substring(0, modifiedImportText.Length - 1) + "\r\n";
            }

            // Step 2 - Get the primary key column names for the new column header row text...
            if (destinationTable.PrimaryKey.Length > 0)
            {
                foreach (DataColumn pKeyColumn in destinationTable.PrimaryKey)
                {
                    newImportText += GetFriendlyFieldName(pKeyColumn, pKeyColumn.ColumnName) + "\t";
                }
            }

            // Step 3 - Continue adding friendly column names to the import text (starting with the column name of the current cell's column HeaderText)...
            //DataGridViewColumn currColumn = dgv.CurrentCell.OwningColumn;
            DataGridViewColumn currColumn = dgv.Columns[minSelectedCol];
            // Step 4 - Now repeat this process for each additional column in the rawImportText...
            //foreach(string tempCol in tempColumns)
            for (int i = 0; i < Math.Max(rawImportColCount, maxSelectedCol - minSelectedCol + 1); i++)
            {
                if (currColumn != null)
                {
                    newImportText += currColumn.HeaderText + "\t";
                }
                else
                {
                    newImportText += "\t";
                }
                // Try to find the next visible column...
                currColumn = dgv.Columns.GetNextColumn(currColumn, DataGridViewElementStates.Visible, DataGridViewElementStates.Frozen);
            }
            // Strip the last tab character and add a CR LF...
            newImportText = newImportText.Substring(0, newImportText.Length - 1) + "\r\n";

            // Step 5 - Get the primary key for each row receiving pasted text and prepend it to the orginal import raw text...
            //string[] modifiedImportRows = modifiedImportText.Split(rowDelimiters, StringSplitOptions.RemoveEmptyEntries);
            string[] modifiedImportRows = modifiedImportText.Split(new string[] { "\r\n" }, StringSplitOptions.None);
            ////DataGridViewRow currRow = dgv.CurrentCell.OwningRow;
            DataGridViewRow currRow = dgv.Rows[minSelectedRow];
            int nextRowIndex = currRow.Index;
            for (int i = 0; i < modifiedImportRows.Length; i++)
            {
                newImportRowText = "";
                if (currRow != null)
                {
                    if (destinationTable.PrimaryKey.Length > 0)
                    {
                        foreach (DataColumn pKeyColumn in destinationTable.PrimaryKey)
                        {
                            newImportRowText += ((DataRowView)currRow.DataBoundItem).Row[pKeyColumn].ToString() + "\t";
                        }
                    }
                    // Now add the original import row text to the new import row text...
                    //newImportRowText += rawImportRows[i] + "\r\n";
                    newImportRowText += modifiedImportRows[i] + "\r\n";
                    // And now add it to the new import text string...
                    newImportText += newImportRowText;
                }

                // Finally, try to find the next visible row...
                nextRowIndex = dgv.Rows.GetNextRow(currRow.Index, DataGridViewElementStates.Visible);
                if (nextRowIndex != -1 &&
                    !dgv.Rows[nextRowIndex].IsNewRow &&
                    nextRowIndex >= minSelectedRow &&
                    nextRowIndex <= maxSelectedRow)
                {
                    currRow = dgv.Rows[nextRowIndex];
                }
                else
                {
                    // Looks like we hit the end of the rows in the DGV - bailout now...
                    //currRow = null;
                    break;
                }
            }

            // Step 6 - Now that we have built a new ImportText string that contains pkeys, we can pass it off to the 'ImportTextToDataTableUsingKeys'
            processedImportSuccessfully = ImportTextToDataTableUsingKeys(newImportText, destinationTable, rowDelimiters, columnDelimiters, out badRows, out missingRows, lookupTables, appSettings);

            return processedImportSuccessfully;
        }
Пример #14
0
        public void Save()
        {
            DataSet modifiedData = new DataSet();
            DataSet saveErrors;
            //bool dataReloadNeeded = false;

            // Make a copy of the current user settings...
            DataTable currentUserSettings = _userSettings.Copy();
            // Reload the user settings from the remote database...
            Load();
            // Syncronize the current user settings with the settings retrieved from the remote DB...
            foreach (DataRow dr in currentUserSettings.Rows)
            {
                if (dr.RowState == DataRowState.Deleted)
                {
                    Delete(dr["form_name", DataRowVersion.Original].ToString(), dr["resource_name", DataRowVersion.Original].ToString(), dr["resource_key", DataRowVersion.Original].ToString());
                }
                else
                {
                    this[dr["form_name"].ToString(), dr["resource_name"].ToString(), dr["resource_key"].ToString()] = dr["resource_value"].ToString();
                }
            }

            // Get just the rows that have changed and put them in to a new dataset...
            if (_userSettings.GetChanges() != null)
            {
                modifiedData.Tables.Add(_userSettings.GetChanges());
            }
            // Call the web method to update the syncronized user settings data...
            saveErrors = _webServices.SaveData(modifiedData);

            if (saveErrors != null &&
                saveErrors.Tables.Contains("ExceptionTable") &&
                saveErrors.Tables["ExceptionTable"].Rows.Count > 0)
            {
                //System.Windows.Forms.MessageBox.Show("There were errors saving user settings.\n\nFull error message:\n" + saveErrors.Tables["ExceptionTable"].Rows[0]["Message"].ToString());
                SharedUtils sharedUtils = new SharedUtils(_webServices.Url, _webServices.Username, _webServices.Password_ClearText, true, "");
                GRINGlobal.Client.Common.GGMessageBox ggMessageBox = new GRINGlobal.Client.Common.GGMessageBox("There were errors saving user settings.\n\nFull error message:\n{0}", "Save User Settings Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxDefaultButton.Button1);
                ggMessageBox.Name = "UserSettings_SaveMessage1";
                if (sharedUtils != null && sharedUtils.IsConnected) sharedUtils.UpdateControls(ggMessageBox.Controls, ggMessageBox.Name);
            //if (ggMessageBox.MessageText.Contains("{0}")) ggMessageBox.MessageText = string.Format(ggMessageBox.MessageText, saveErrors.Tables["ExceptionTable"].Rows[0]["Message"].ToString());
            string[] argsArray = new string[100];
            argsArray[0] = saveErrors.Tables["ExceptionTable"].Rows[0]["Message"].ToString();
            ggMessageBox.MessageText = string.Format(ggMessageBox.MessageText, argsArray);
                ggMessageBox.ShowDialog();
            }
            else
            {
                Load();
            }
        }
Пример #15
0
        public void LoadTableFromDatabase(object objDataviewName)
        {
            string dataviewName = (string)objDataviewName;
            int pageSize = _pageSize;
            int pageOffset = 0;
            DataSet dataPage = new DataSet();
            DataTable dataviewTable = null;
            //string unusedParameters = ":createddate=" + DateTime.Today.AddYears(1) + "; :modifieddate=" + DateTime.Today.AddYears(1) + "; :valuemember=; :displaymember;";
            //string unusedParameters = ":createddate=" + DateTime.Today.AddYears(1).ToString("u") + "; :modifieddate=" + DateTime.Today.AddYears(1).ToString("u") + "; :valuemember=; :displaymember;";
            string unusedParameters = ":createddate=" + DateTime.Today.AddYears(1).ToString("s") + "; :modifieddate=" + DateTime.Today.AddYears(1).ToString("s") + "; :valuemember=; :displaymember;";
            string startAndStopPKeys = "";
            // Add this to the loadingQueue list (so that no more threads get started to build this table)...
            if (!_loadingQueue.Contains(dataviewName))
            {
                _loadingQueue.Add(dataviewName);
            }
            else
            {
                // There is already a thread to load this table running so bail out now...
                return;
            }

            DataTable localLookupTableStats = new DataTable("lookup_table_status");
            // If the lookup_table_status table has been built get the row for the table to be loaded (otherwise call sync to build the table)...
            if (!_localData.TableExists("lookup_table_status"))
            {
                GetSynchronizationStats();
            }
            localLookupTableStats = _localData.GetData("SELECT * FROM lookup_table_status WHERE dataview_name=@dataviewname", new string[1] { "@dataviewname=" + dataviewName });

            // Get the statistics row for this table...
            DataRow localLookupTableStatsRow = localLookupTableStats.Rows.Find(dataviewName);
            if (localLookupTableStatsRow != null)
            {
                // Change the status of the lookup table statistics to 'Loading'...
                localLookupTableStatsRow["status"] = "Loading";
                SaveDataPageToLocalDB(localLookupTableStats);
                // Begin loading the lookup table page by page...
                pageOffset = (int)localLookupTableStatsRow["current_pk"];
                for (int i = pageOffset; i <= (int)localLookupTableStatsRow["max_pk"]; i += pageSize)
                {
                    startAndStopPKeys = " :startpkey=" + i.ToString() + "; :stoppkey=" + (i + pageSize - 1).ToString();
                    try
                    {
            //MessageBox.Show("Getting data for: " + localLookupTableStatsRow["dataview_name"].ToString() + " with Params: " + unusedParameters + startAndStopPKeys);
                        dataPage = _webServices.GetData(localLookupTableStatsRow["dataview_name"].ToString(), unusedParameters + startAndStopPKeys, 0, 0);
                        if (!dataPage.Tables.Contains(localLookupTableStatsRow["dataview_name"].ToString()))
                        {
            //System.Windows.Forms.MessageBox.Show("Error retrieving data for lookup table: '" + dataviewName.ToUpper() + "' --- Retrying from PKEY=" + i.ToString(), "Lookup Table Load Error");
            //GRINGlobal.Client.Common.GGMessageBox ggMessageBox = new GRINGlobal.Client.Common.GGMessageBox("Exception Message: " + dataPage.Tables["ExceptionTable"].Rows[0]["Message"].ToString(), "Lookup Table Load Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxDefaultButton.Button1);
            //ggMessageBox.ShowDialog();
                            i -= pageSize;
                            continue;
                        }
                        if (dataviewTable == null)
                        {
                            // Create an empty copy of the lookup table...
                            dataviewTable = dataPage.Tables[localLookupTableStatsRow["dataview_name"].ToString()].Clone();
            //// Apply any column constraints (indicated in the column extended properties) to the table...
            //ApplyColumnConstraints(dataviewTable);
                        }
                        dataviewTable.Rows.Clear();
                        dataviewTable.AcceptChanges();
                        dataviewTable.Load(dataPage.Tables[localLookupTableStatsRow["dataview_name"].ToString()].CreateDataReader(), LoadOption.Upsert);
                        SaveDataPageToLocalDB(dataviewTable);
                        localLookupTableStatsRow["current_pk"] = Math.Min((int)localLookupTableStatsRow["max_pk"], i + pageSize - 1);
                        localLookupTableStatsRow["status"] = "Loading";
                        SaveDataPageToLocalDB(localLookupTableStats);
                    }
                    catch (Exception err)
                    {
                        if (dataPage.Tables.Contains("ExceptionTable") &&
                            dataPage.Tables["ExceptionTable"].Rows.Count > 0)
                        {
            //System.Windows.Forms.MessageBox.Show("Error retrieving data for lookup table: '" + dataviewName.ToUpper() + "' --- Aborting this background task.\n\nFull Server Error Message:\n\n" + dataPage.Tables["ExceptionTable"].Rows[0]["Message"].ToString(), "Lookup Table Load Error");
            SharedUtils sharedUtils = new SharedUtils(_webServices.Url, _webServices.Username, _webServices.Password_ClearText, true, "");
            GRINGlobal.Client.Common.GGMessageBox ggMessageBox = new GRINGlobal.Client.Common.GGMessageBox("Error retrieving data for lookup table: '{0}' --- Aborting this background task.\n\nFull Server Error Message:\n\n{1}", "Lookup Table Load Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxDefaultButton.Button1);
            ggMessageBox.Name = "LookupTables_LoadTableFromDatabaseMessage1";
            if (sharedUtils != null && sharedUtils.IsConnected) sharedUtils.UpdateControls(ggMessageBox.Controls, ggMessageBox.Name);
            //if (ggMessageBox.MessageText.Contains("{0}") &&
            //    ggMessageBox.MessageText.Contains("{1}"))
            //{
            //    ggMessageBox.MessageText = string.Format(ggMessageBox.MessageText, dataviewName.ToUpper(), dataPage.Tables["ExceptionTable"].Rows[0]["Message"].ToString());
            //}
            //else if (ggMessageBox.MessageText.Contains("{0}"))
            //{
            //    ggMessageBox.MessageText = string.Format(ggMessageBox.MessageText, dataviewName.ToUpper());
            //}
            //else if (ggMessageBox.MessageText.Contains("{1}"))
            //{
            //    ggMessageBox.MessageText = string.Format(ggMessageBox.MessageText, dataPage.Tables["ExceptionTable"].Rows[0]["Message"].ToString());
            //}
            string[] argsArray = new string[100];
            argsArray[0] = dataviewName.ToUpper();
            argsArray[1] = dataPage.Tables["ExceptionTable"].Rows[0]["Message"].ToString();
            ggMessageBox.MessageText = string.Format(ggMessageBox.MessageText, argsArray);
            ggMessageBox.ShowDialog();
                        }
                        else
                        {
            //System.Windows.Forms.MessageBox.Show("Error retrieving data for lookup table: '" + dataviewName.ToUpper() + "' --- Aborting this background task.\n\nFull Internal Error Message:\n\n" + err.Message, "Lookup Table Load Error");
            SharedUtils sharedUtils = new SharedUtils(_webServices.Url, _webServices.Username, _webServices.Password_ClearText, true, "");
            GRINGlobal.Client.Common.GGMessageBox ggMessageBox = new GRINGlobal.Client.Common.GGMessageBox("Error retrieving data for lookup table: '{0}' --- Aborting this background task.\n\nFull Internal Error Message:\n\n{1}", "Lookup Table Load Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxDefaultButton.Button1);
            ggMessageBox.Name = "LookupTables_LoadTableFromDatabaseMessage2";
            if (sharedUtils != null && sharedUtils.IsConnected) sharedUtils.UpdateControls(ggMessageBox.Controls, ggMessageBox.Name);
            //if (ggMessageBox.MessageText.Contains("{0}") &&
            //    ggMessageBox.MessageText.Contains("{1}"))
            //{
            //    ggMessageBox.MessageText = string.Format(ggMessageBox.MessageText, dataviewName.ToUpper(), err.Message);
            //}
            //else if (ggMessageBox.MessageText.Contains("{0}"))
            //{
            //    ggMessageBox.MessageText = string.Format(ggMessageBox.MessageText, dataviewName.ToUpper());
            //}
            //else if (ggMessageBox.MessageText.Contains("{1}"))
            //{
            //    ggMessageBox.MessageText = string.Format(ggMessageBox.MessageText, err.Message);
            //}
            string[] argsArray = new string[100];
            argsArray[0] = dataviewName.ToUpper();
            argsArray[1] = err.Message;
            ggMessageBox.MessageText = string.Format(ggMessageBox.MessageText, argsArray);
            ggMessageBox.ShowDialog();
                        }
                        // Update the status of the LU table load on the local DB lookup_table_status table...
                        localLookupTableStatsRow["status"] = "Failed";
                        SaveDataPageToLocalDB(localLookupTableStats);
                        break;
                    }
                }
                // Looks like we were successful in loading this LU table so if this table is cached - clear it from cache...
                if (_pkeyLUTCacheCollection.ContainsKey(dataviewName))
                {
                    UpdatePKeyLUTDictionary(dataviewName, _pkeyLUTCacheCollection[dataviewName]);
                }
                else if (dataviewName.ToLower().Trim() == "code_value_lookup")
                {
                    UpdateCodeValueLUTDictionary("code_value_lookup", _codevalueLUTCache);
                }
                // Update the status of the LU table load on the local DB lookup_table_status table...
                localLookupTableStatsRow["status"] = "Completed";
            localLookupTableStatsRow["sync_date"] = DateTime.UtcNow;
                SaveDataPageToLocalDB(localLookupTableStats);
            }
            // Finished adding the lookup table - remove the name from the loadingQueue list...
            _loadingQueue.Remove(dataviewName);
            // Clear the lookup table status cache (so that it can be refreshed for each lookup table on demand)...
            _lookupTableStatus.Clear();
        }
Пример #16
0
        //public DataviewTabProperties(SharedUtils sharedUtils, DataviewProperties dataviewProperties, FormsData[] formsList)
        public DataviewTabProperties(WebServices webServices, DataviewProperties dataviewProperties)
        {
            InitializeComponent();

            // Create a SharedUtils object...
            SharedUtils sharedUtils = new SharedUtils(webServices.Url, webServices.Username, webServices.Password_ClearText, true);

            // Get the list of dataviews...
            DataSet _dataviewData = sharedUtils.GetWebServiceData("get_dataview_list", "", 0, 0);
            // Populate the combobox with the list of available dataviews...
            if (_dataviewData.Tables.Contains("get_dataview_list"))
            {
                _dataviewList = _dataviewData.Tables["get_dataview_list"].Copy();
                _dataviewList.Columns.Add("display_member", typeof(string));
                _dataviewList.Columns.Add("category_name", typeof(string));
                _dataviewList.Columns.Add("database_area", typeof(string));
                foreach (DataRow dr in _dataviewList.Rows)
                {
                    string friendlyName = "";
                    if (dr.Table.Columns.Contains("title")) friendlyName += dr["title"].ToString().Trim();
                    dr["display_member"] = friendlyName;
                    if (!string.IsNullOrEmpty(dr["category_code"].ToString()))
                    {
                        dr["category_name"] = sharedUtils.GetLookupDisplayMember("code_value_lookup", dr["category_code"].ToString(), dr.Table.Columns["category_code"].ExtendedProperties["group_name"].ToString(), dr["category_code"].ToString());
                    }
                    else
                    {
                        dr["category_name"] = "";
                    }

                    if (!string.IsNullOrEmpty(dr["database_area_code"].ToString()))
                    {
                        dr["database_area"] = sharedUtils.GetLookupDisplayMember("code_value_lookup", dr["database_area_code"].ToString(), dr.Table.Columns["database_area_code"].ExtendedProperties["group_name"].ToString(), dr["database_area_code"].ToString());
                    }
                    else
                    {
                        dr["database_area"] = "";
                    }
                }
                // Build the distinct list of categories and bind it to the combobox...
                _category = _dataviewList.DefaultView.ToTable(true, new string[] { "category_name" });
                _category.DefaultView.Sort = "category_name asc";
                ux_comboboxDataviewCategory.DisplayMember = "category_name";
                ux_comboboxDataviewCategory.ValueMember = "category_name";
                ux_comboboxDataviewCategory.DataSource = _category;

                // Bind the list to the dropdown combobox...
                if (_dataviewList.Columns.Contains("display_member")) _dataviewList.DefaultView.Sort = "display_member asc";
                ux_comboboxDataviews.DisplayMember = "display_member";
                ux_comboboxDataviews.ValueMember = "dataview_name";
                ux_comboboxDataviews.DataSource = _dataviewList;
            }
            else
            {
                // Did not return the dataview list - bail out now...
                return;
            }

            // Get the dataview record that matches what is in the dataviewProperties.dataviewname property (there should only be one with this name)...
            DataRow[] currentDataviewRows = _dataviewList.Select("is_enabled='Y' AND dataview_name='" + dataviewProperties.DataviewName + "'");
            DataRow currentDataviewRow = null;
            if (currentDataviewRows.Length > 0) currentDataviewRow = currentDataviewRows[0];

            // Build the list of compatible forms and bind it to the combobox...
            FormsData[] formsDataList = sharedUtils.GetDataviewFormsData();

            if (formsDataList != null &&
                formsDataList.Length > 0)
            {
                _formsList.Columns.Add("DisplayMember", typeof(string));
                _formsList.Columns.Add("ValueMember", typeof(string));
                _formsList.Columns.Add("PreferredDataviewName", typeof(string));
                //_formsList.PrimaryKey = new DataColumn[] { _formsList.Columns["ValueMember"] };
                foreach (FormsData fd in formsDataList)
                {
                    if (!string.IsNullOrEmpty(fd.PreferredDataviewName))
                    {
                        string[] preferredDataviews = fd.PreferredDataviewName.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                        foreach (string preferredDataview in preferredDataviews)
                        {
                            if (fd.ConstInfo != null &&
                                !string.IsNullOrEmpty(fd.StrongFormName))
                            {
                                DataRow newRow = _formsList.NewRow();
                                newRow["DisplayMember"] = fd.FormName + "   (" + fd.ConstInfo.Module.Name + ")";
                                newRow["ValueMember"] = fd.StrongFormName;
                                newRow["PreferredDataviewName"] = preferredDataview.Trim().ToLower();
                                _formsList.Rows.Add(newRow);
                            }
                        }
                    }
                }
            }
            // Set the tab properties to the values passed into the dialog...
            this.TabProperties = dataviewProperties;

            // Populate the controls with the currently chosen dataview (if this is not a brand new dataview)...
            // (order matters here - first choose category, then DB area, and finally dataview)
            // STEP 1 - Catetory
            if (currentDataviewRow != null &&
                ux_comboboxDataviewCategory.Items.Count > 0)
            {
                ux_comboboxDataviewCategory.SelectedValue = currentDataviewRow["category_name"].ToString();
            }
            // STEP 2 - Database Area
            if (currentDataviewRow != null &&
                ux_comboboxDataviewCategory.Items.Count > 0)
            {
                ux_comboboxDatabaseArea.SelectedValue = currentDataviewRow["database_area"].ToString();
            }
            // STEP 3 - Dataview
            if (currentDataviewRow != null &&
                ux_comboboxDataviewCategory.Items.Count > 0)
            {
                ux_comboboxDataviews.SelectedValue = currentDataviewRow["dataview_name"].ToString();
            }

            // Disable the OK button and the radio buttons for forms viewer (by default)...
            if (ux_comboboxDataviews.SelectedValue == null)
            {
                ux_buttonOK.Enabled = false;
                ux_radiobuttonFormStyle.Enabled = false;
                ux_radiobuttonBothStyle.Enabled = false;
                ux_comboboxForm.Enabled = false;
                ux_checkboxAlwayOnTop.Enabled = false;
                ux_checkboxAlwayOnTop.Hide();
            }
            sharedUtils.UpdateControls(this.Controls, this.Name);
        }
Пример #17
0
 public GRINGlobalClientSearchTool(string[] args)
 {
     InitializeComponent();
     // Parse through the commandline parameters...
     _user = GetCommandLineParameter(args, "-user", "");
     _password = GetCommandLineParameter(args, "-password", "");
     _url = GetCommandLineParameter(args, "-url", "");
     _sharedUtils = new GRINGlobal.Client.Common.SharedUtils(_url, _user, _password, false);
     //// Pre-load the code value table into memory...
     //if (_sharedUtils.IsConnected &&
     //    _sharedUtils.LocalDatabaseTableExists("code_value_lookup"))
     //{
     //    //DataTable localDBCodeValueLookupTable = _sharedUtils.GetLocalData("SELECT * FROM code_value_lookup");
     //    DataTable localDBCodeValueLookupTable = _sharedUtils.GetLocalData("SELECT * FROM code_value_lookup", "");
     //    if (localDBCodeValueLookupTable.Rows.Count > 0)
     //    {
     //        // Since the MRU tables are never saved to the local database, we need to add them to the memory dataset each time...
     //        _sharedUtils.LookupTablesCacheMRUTable(localDBCodeValueLookupTable);
     //    }
     //}
 }
Пример #18
0
        private void GrinGlobalClient_Load(object sender, EventArgs e)
        {
            bool validLogin = false;
            //            bool connectedToWebService = false;
            //            int selectedCNOIndex = -1;
            //string selectedNodeFullPath = "";
            //username = "";
            //password = "";
            _usernameCooperatorID = "";// "117534";
            _currentCooperatorID = "";// "117534";
            site = "";// "NC7";
            languageCode = "";
            lastFullPath = "";
            lastTabName = "";
            commonUserApplicationDataPath = System.Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + @"\GRIN-Global\Curator Tool";
            roamingUserApplicationDataPath = System.Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\GRIN-Global\Curator Tool";
            userSettingsXMLFilePath = roamingUserApplicationDataPath + @"\UserSettings_v" + System.Reflection.Assembly.GetEntryAssembly().GetName().Version.Build.ToString() + ".xml";

            // Wireup the binding navigator and the Main datagridview...
            // NOTE:(right now the binding source is empty - but later on it will get bound to a data table)...
            defaultBindingSource = new BindingSource();
            defaultBindingSource.DataSource = new DataTable();
            ux_bindingnavigatorMain.BindingSource = defaultBindingSource;
            ux_datagridviewMain.DataSource = defaultBindingSource;

            //// Load the images for the tree view(s)...
            //navigatorTreeViewImages.ColorDepth = ColorDepth.Depth32Bit;
            //navigatorTreeViewImages.Images.Add("active_folder", Icon.ExtractAssociatedIcon(@"Images\active_Folder.ico"));
            //navigatorTreeViewImages.Images.Add("inactive_folder", Icon.ExtractAssociatedIcon(@"Images\inactive_Folder.ico"));
            //navigatorTreeViewImages.Images.Add("active_INVENTORY_ID", Icon.ExtractAssociatedIcon(@"Images\active_INVENTORY_ID.ico"));
            //navigatorTreeViewImages.Images.Add("inactive_INVENTORY_ID", Icon.ExtractAssociatedIcon(@"Images\inactive_INVENTORY_ID.ico"));
            //navigatorTreeViewImages.Images.Add("active_ACCESSION_ID", Icon.ExtractAssociatedIcon(@"Images\active_ACCESSION_ID.ico"));
            //navigatorTreeViewImages.Images.Add("inactive_ACCESSION_ID", Icon.ExtractAssociatedIcon(@"Images\inactive_ACCESSION_ID.ico"));
            //navigatorTreeViewImages.Images.Add("active_ORDER_REQUEST_ID", Icon.ExtractAssociatedIcon(@"Images\active_ORDER_REQUEST_ID.ico"));
            //navigatorTreeViewImages.Images.Add("inactive_ORDER_REQUEST_ID", Icon.ExtractAssociatedIcon(@"Images\inactive_ORDER_REQUEST_ID.ico"));
            //navigatorTreeViewImages.Images.Add("active_COOPERATOR_ID", Icon.ExtractAssociatedIcon(@"Images\active_COOPERATOR_ID.ico"));
            //navigatorTreeViewImages.Images.Add("inactive_COOPERATOR_ID", Icon.ExtractAssociatedIcon(@"Images\inactive_COOPERATOR_ID.ico"));

            //navigatorTreeViewImages.Images.Add("active_GEOGRAPHY_ID", Icon.ExtractAssociatedIcon(@"Images\active_GEOGRAPHY_ID.ico"));
            //navigatorTreeViewImages.Images.Add("inactive_GEOGRAPHY_ID", Icon.ExtractAssociatedIcon(@"Images\inactive_GEOGRAPHY_ID.ico"));
            //navigatorTreeViewImages.Images.Add("active_TAXONOMY_GENUS_ID", Icon.ExtractAssociatedIcon(@"Images\active_TAXONOMY_GENUS_ID.ico"));
            //navigatorTreeViewImages.Images.Add("inactive_TAXONOMY_GENUS_ID", Icon.ExtractAssociatedIcon(@"Images\inactive_TAXONOMY_GENUS_ID.ico"));
            //navigatorTreeViewImages.Images.Add("active_CROP_ID", Icon.ExtractAssociatedIcon(@"Images\active_CROP_ID.ico"));
            //navigatorTreeViewImages.Images.Add("inactive_CROP_ID", Icon.ExtractAssociatedIcon(@"Images\inactive_CROP_ID.ico"));
            //navigatorTreeViewImages.Images.Add("active_CROP_TRAIT_ID", Icon.ExtractAssociatedIcon(@"Images\active_CROP_TRAIT_ID.ico"));
            //navigatorTreeViewImages.Images.Add("inactive_CROP_TRAIT_ID", Icon.ExtractAssociatedIcon(@"Images\inactive_CROP_TRAIT_ID.ico"));

            //navigatorTreeViewImages.Images.Add("new_tab", Icon.ExtractAssociatedIcon(@"Images\GG_newtab.ico"));
            //navigatorTreeViewImages.Images.Add("search", Icon.ExtractAssociatedIcon(@"Images\GG_search.ico"));

            try
            {
                // Load the wizards from the same directory (and all subdirectories) where the Curator Tool was launched...
                System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(System.IO.Directory.GetCurrentDirectory());
                System.IO.FileInfo[] dllFiles = di.GetFiles("Wizards\\*.dll", System.IO.SearchOption.AllDirectories);
                if (dllFiles != null && dllFiles.Length > 0)
                {
                    for (int i = 0; i < dllFiles.Length; i++)
                    {
                        System.Reflection.Assembly newAssembly = System.Reflection.Assembly.LoadFile(dllFiles[i].FullName);
                        foreach (System.Type t in newAssembly.GetTypes())
                        {
                            if (t.GetInterface("IGRINGlobalDataWizard", true) != null)
                            {
                                System.Reflection.ConstructorInfo constInfo = t.GetConstructor(new Type[] { typeof(string), typeof(SharedUtils) });

                                if (constInfo != null)
                                {
                                    string pkeyCollection = ":accessionid=; :inventoryid=; :orderrequestid=; :cooperatorid=; :geographyid=; :taxonomygenusid=; :cropid=";
                                    // Instantiate an object of this type to load...
                                    Form wizardForm = (Form)constInfo.Invoke(new object[] { pkeyCollection, _sharedUtils });
                                    // Get the Form Name and button with this name...
                                    System.Reflection.PropertyInfo propInfo = t.GetProperty("FormName", typeof(string));
                                    string formName = (string)propInfo.GetValue(wizardForm, null);
                                    if (string.IsNullOrEmpty(formName)) formName = t.Name;
                                    ToolStripButton tsbWizard = new ToolStripButton(formName, Icon.ExtractAssociatedIcon(newAssembly.ManifestModule.FullyQualifiedName).ToBitmap(), ux_buttonWizard_Click, "toolStripButton" + newAssembly.ManifestModule.Name);
                                    tsbWizard.Tag = "Wizards\\" + newAssembly.ManifestModule.Name;
                                    toolStrip1.Items.Add(tsbWizard);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception err)
            {
            GRINGlobal.Client.Common.GGMessageBox ggMessageBox = new GRINGlobal.Client.Common.GGMessageBox("Error binding to Wizard Form.\nError Message: {0}", "Wizard Binding Error", MessageBoxButtons.OK, MessageBoxDefaultButton.Button1);
            ggMessageBox.Name = "GrinGlobalClient_LoadMessage2";
            _sharedUtils.UpdateControls(ggMessageBox.Controls, ggMessageBox.Name);
            if (ggMessageBox.MessageText.Contains("{0}")) ggMessageBox.MessageText = string.Format(ggMessageBox.MessageText, err.Message);
            ggMessageBox.ShowDialog();
            }

            // Create the middle tier utilities class and connect to the web services...
            _sharedUtils = new SharedUtils(url, username, passwordClearText, false);

            // Display the splash page to let the user know that things are happening...
            Splash splash = new Splash();
            splash.StartPosition = FormStartPosition.CenterScreen;
            splash.Show();
            splash.Update();

            //if (validLogin)
            if (_sharedUtils.IsConnected)
            {
                localDBInstance = _sharedUtils.Url.ToLower().Replace("http://", "").Replace("/gringlobal/gui.asmx", "").Replace('-', '_').Replace('.', '_').Replace(':', '_');
                localDBInstance = "GRINGlobal_" + localDBInstance;
            //_sharedUtils = new SharedUtils(GRINGlobalWebServices.Url, username, password, localDBInstance, cno);
                username = _sharedUtils.Username;
                password = _sharedUtils.Password;
                passwordClearText = _sharedUtils.Password_ClearText;
                url = _sharedUtils.Url;
                _usernameCooperatorID = _sharedUtils.UserCooperatorID;
            //_currentCooperatorID = _sharedUtils.UserCooperatorID;
                site = _sharedUtils.UserSite;
                languageCode = _sharedUtils.UserLanguageCode.ToString();

                // Load the application data...
                LoadApplicationData();

            // Check the status of lookup tables and warn the user if some tables are missing data...
            LookupTableStatusCheck();

                // Wire up the list of valid GG servers to the combobox...
                ux_comboboxActiveWebService.DataSource = new BindingSource(_sharedUtils.WebServiceURLs, null);
                ux_comboboxActiveWebService.DisplayMember = "Key";
                ux_comboboxActiveWebService.ValueMember = "Value";
                ux_comboboxActiveWebService.SelectedValue = _sharedUtils.Url;
            // Indicate to the user which URL is the active GG server...
            if (ux_statusCenterMessage.Tag != null)
            {
            if (ux_statusCenterMessage.Tag.ToString().Contains("{0}"))
            {
            ux_statusCenterMessage.Text = string.Format(ux_statusCenterMessage.Tag.ToString(), _sharedUtils.Url);
            }
            else
            {
            ux_statusCenterMessage.Text = ux_statusCenterMessage.Tag.ToString() + " (" + _sharedUtils.Url + ")";
            }
            }
            else
            {
            ux_statusCenterMessage.Text = ux_statusCenterMessage.Text + " (" + _sharedUtils.Url + ")";
            }

            // Get the list of Dataview Forms embedded in assemblies in the CT Forms directiory...
            localFormsAssemblies = _sharedUtils.GetDataviewFormsData();

                // Save the list of valid web service urls...
                // But first make sure the roaming profile directory exists...
                if (!System.IO.Directory.Exists(roamingUserApplicationDataPath)) System.IO.Directory.CreateDirectory(roamingUserApplicationDataPath);
                // Now save the list of GRIN-Global servers...
                System.IO.StreamWriter sw = new System.IO.StreamWriter(roamingUserApplicationDataPath + @"\WebServiceURL.txt");
                foreach (KeyValuePair<string, string> kv in ux_comboboxActiveWebService.Items)
                {
                    if (kv.Key != "New...")
                    {
                        sw.WriteLine(kv.Key + "\t" + kv.Value);
                    }
                }
                sw.Close();
                sw.Dispose();

                // Load the cursors for the DGV...
                _cursorGG = _sharedUtils.LoadCursor(@"Images\cursor_GG.cur");
                if (_cursorGG == null) _cursorGG = Cursors.Default;
                _cursorLUT = _sharedUtils.LoadCursor(@"Images\cursor_LUT.cur");
                if (_cursorLUT == null) _cursorLUT = Cursors.Default;
                _cursorREQ = _sharedUtils.LoadCursor(@"Images\cursor_REQ.cur");
                if (_cursorREQ == null) _cursorREQ = Cursors.Default;
            //this.Cursor = _cursorGG;
            ux_datagridviewMain.Cursor = _cursorGG;
            }
            else
            {
                // Login aborted - disable controls...
                ux_tabcontrolDataviewOptions.Enabled = false;
                ux_tabcontrolCTDataviews.Enabled = false;
                ux_datagridviewMain.Enabled = false;
                ux_comboboxCNO.Enabled = false;
                ux_buttonEditData.Enabled = false;
                // Close the application???
                this.Close();
            }

            // Close the splash page...
            splash.Close();
        }
Пример #19
0
 private void ux_menuitemChangePassword_Click(object sender, EventArgs e)
 {
     ChangePassword cp = new ChangePassword(_sharedUtils.Url, _sharedUtils.Username, "", _sharedUtils);
     cp.StartPosition = FormStartPosition.CenterParent;
     if (DialogResult.OK == cp.ShowDialog(this))
     {
         _sharedUtils = new SharedUtils(_sharedUtils.Url, _sharedUtils.Username, cp.Password, true);
     }
 }
Пример #20
0
        private void ux_comboboxActiveWebService_SelectedIndexChanged(object sender, EventArgs e)
        {
            // Remember the URL that the user is currently using (in case we need to revert)...
            //string originalURL = GRINGlobalWebServices.Url;

            // Save the GUI settings for the user...
            SetAllUserSettings();
            //userSettings.Save();
            _sharedUtils.SaveAllUserSettings();

            // Now try to establish a new web service connection...
            try
            {
            //                GRINGlobalWebServices.Url = ux_comboboxActiveWebService.SelectedValue.ToString();
            //                string webserviceVersion = GRINGlobalWebServices.GetVersion();
            ////Login loginDialog = new Login(username, password, GUIWebServices.Url, null);
            //                Login loginDialog = new Login(GRINGlobalWebServices, GRINGlobalWebServices.Url, null);
            //                loginDialog.UserName = username;
            //                loginDialog.Password = password;
            //                loginDialog.StartPosition = FormStartPosition.CenterScreen;
            //                loginDialog.ShowDialog();
            SharedUtils tempSharedUtils = new SharedUtils(ux_comboboxActiveWebService.SelectedValue.ToString(), username, passwordClearText, true);

                //if (DialogResult.OK == loginDialog.DialogResult)
                if (tempSharedUtils.IsConnected)
                {
                    // Set the new global SharedUtils global variable to the newly created tempSharedUtils...
                    _sharedUtils = tempSharedUtils;
                    // Get the user login details for this user...
                    username = _sharedUtils.Username;
                    password = _sharedUtils.Password;
                    passwordClearText = _sharedUtils.Password_ClearText;
                    _usernameCooperatorID = _sharedUtils.UserCooperatorID;
                    _currentCooperatorID = _sharedUtils.UserCooperatorID;
                    site = _sharedUtils.UserSite;
                    languageCode = _sharedUtils.UserLanguageCode.ToString();
                    // Create new instance of shared utilities...
            //_sharedUtils = new SharedUtils(GRINGlobalWebServices.Url, username, password, localDBInstance, cno);

                    // Set the global variable for the localDBInstance...
                    //localDBInstance = GRINGlobalWebServices.Url.ToLower().Replace("http://", "").Replace("/gringlobal/gui.asmx", "").Replace('-', '_').Replace('.', '_').Replace(':', '_');
                    localDBInstance = _sharedUtils.Url.ToLower().Replace("http://", "").Replace("/gringlobal/gui.asmx", "").Replace('-', '_').Replace('.', '_').Replace(':', '_');
                    localDBInstance = "GRINGlobal_" + localDBInstance;
                    // Reload/rebuild the interface...
                    LoadApplicationData();
                    // Check the status of lookup tables and warn the user if some tables are missing data...
                    LookupTableStatusCheck();
                    // Indicate the web service connection...
                    ux_statusCenterMessage.Text = "Connected to: " + _sharedUtils.Url;
                }
                else
                {
            //MessageBox.Show("Unable to connect to " + ux_comboboxActiveWebService.Text + "\nAborting connection request.");
            GRINGlobal.Client.Common.GGMessageBox ggMessageBox = new GRINGlobal.Client.Common.GGMessageBox("Unable to connect to {0}\nAborting connection request.", "Connection Error", MessageBoxButtons.OK, MessageBoxDefaultButton.Button1);
            ggMessageBox.Name = "ux_comboboxActiveWebServiceMessage1";
            _sharedUtils.UpdateControls(ggMessageBox.Controls, ggMessageBox.Name);
            if (ggMessageBox.MessageText.Contains("{0}")) ggMessageBox.MessageText = string.Format(ggMessageBox.MessageText, ux_comboboxActiveWebService.Text);
            ggMessageBox.ShowDialog();
            ux_comboboxActiveWebService.SelectedValue = _sharedUtils.Url;
            //GRINGlobalWebServices.Url = originalURL;
                }
            }
            catch
            {
            //GRINGlobalWebServices.Url = originalURL;
            }
        }
Пример #21
0
        public LookupTablePicker(SharedUtils sharedUtils, string columnNameToLookup, DataRow parentRow, string currentValue)
        {
            InitializeComponent();
            // Initialize new objects to access the local lookup tables...
            _sharedUtils = sharedUtils;
            // Save the key for the cell that is being edited...
            _currentKey = parentRow[columnNameToLookup].ToString();
            _newKey = _currentKey;
            // Create new filter dictionary...
            _filters = new Dictionary<string, string>();
            // Get the table for the datarow being edited...
            DataTable dt = parentRow.Table;
            // Get the column for the cell being edited...
            DataColumn dc = parentRow.Table.Columns[columnNameToLookup];
            // Make sure this is an FK column and if so inspect the fields available
            // in the lookup table that might match fields in the parentRow's table
            // If there are matches - wire them up as filters to restrict the number
            // of rows returned to the dialog box that the user chooses from...
            if (_sharedUtils.LookupTablesIsValidFKField(dc))
            {
                //_lookupTableName = dc.ExtendedProperties["foreign_key_resultset_name"].ToString().Trim();
                _lookupTableName = dc.ExtendedProperties["foreign_key_dataview_name"].ToString().Trim();
                if (_sharedUtils.LocalDatabaseTableExists(_lookupTableName))
                {
                    // This is a query to 1) get data for the current FK and also 2) get the schema for the lookup table...
                    _boundTable = _sharedUtils.GetLocalData("SELECT TOP 1000 * FROM " + _lookupTableName + " WHERE value_member = @valuemember" + " ORDER BY display_member ASC", "@valuemember=" + _currentKey);
                }
                else
                {
            //MessageBox.Show("Warning!!!\n\nYour computer does not have a local copy of this lookup table.  Until this lookup table is downloaded, the Curator Tool will connect to the central database to retrieve lookup values.\n\nTIP:  To maximize performance of the Curator Tool please download all lookup tables to your local computer.", "Missing Lookup Table", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
            GRINGlobal.Client.Common.GGMessageBox ggMessageBox = new GRINGlobal.Client.Common.GGMessageBox("Warning!!!\n\nYour computer does not have a local copy of this lookup table.  Until this lookup table is downloaded, the Curator Tool will connect to the central database to retrieve lookup values.\n\nTIP:  To maximize performance of the Curator Tool please download all lookup tables to your local computer.", "Missing Lookup Table", MessageBoxButtons.OK, MessageBoxDefaultButton.Button1);
            ggMessageBox.Name = "LookupTablePicker_LookupTablePickerMessage1";
            if (_sharedUtils != null) _sharedUtils.UpdateControls(ggMessageBox.Controls, ggMessageBox.Name);
            ggMessageBox.ShowDialog();
            //_boundTable = _lookupTables.GetFilteredLookupTableRows(_lookupTableName, ux_textboxFind.Text, 1000);
            _boundTable = _sharedUtils.LookupTablesGetMatchingRows(_lookupTableName, currentValue, 1000);
                    ux_buttonRefresh.Enabled = false;
                }

                if (_boundTable != null)
                {
                    foreach (DataColumn luColumn in _boundTable.Columns)
                    {
                        if (luColumn.ColumnName != "value_member" &&
                            luColumn.ColumnName != "display_member" &&
                            luColumn.ColumnName != "created_date" &&
                            luColumn.ColumnName != "modified_date")
                        {
                            if (dt.Columns.Contains(luColumn.ColumnName) &&
            //parentRow[luColumn.ColumnName] != null &&
            parentRow[luColumn.ColumnName] != DBNull.Value &&
                                !luColumn.ColumnName.StartsWith("is_")) _filters.Add(luColumn.ColumnName, parentRow[luColumn.ColumnName].ToString().Trim());
                            if (luColumn.ColumnName.StartsWith("is_") &&
                                !_filters.ContainsKey(luColumn.ColumnName)) _filters.Add(luColumn.ColumnName, "Y");
                        }
                    }
                }
            }
            textChangeDelayTimer.Tick += new EventHandler(timerDelay_Tick);
            ux_textboxFind.Text = currentValue;
            ux_textboxFind.Focus();
            ux_textboxFind.SelectionStart = ux_textboxFind.Text.Length;
            sharedUtils.UpdateControls(this.Controls, this.Name);
        }
Пример #22
0
 public void Load()
 {
     DataSet remoteDBUserSettings = new DataSet();
     // Get the user settings from the remote DB for the current user's CNO...
     remoteDBUserSettings = _webServices.GetData("get_user_settings", ":cooperatorid=" + _cno, 0, 0);
     if (remoteDBUserSettings.Tables.Contains("get_user_settings"))
     {
         _userSettings.Clear();
         remoteDBUserSettings.Tables["get_user_settings"].DefaultView.RowFilter = "app_name='" + _app.Replace("'", "''") + "'";
         _userSettings = remoteDBUserSettings.Tables["get_user_settings"].DefaultView.ToTable();
         _userSettings.AcceptChanges();
     }
     else if (remoteDBUserSettings.Tables.Contains("ExceptionTable") &&
             remoteDBUserSettings.Tables["ExceptionTable"].Rows.Count > 0)
     {
     //System.Windows.Forms.MessageBox.Show("There were errors retrieving user settings.\n\nFull error message:\n" + remoteDBUserSettings.Tables["ExceptionTable"].Rows[0]["Message"].ToString());
     SharedUtils sharedUtils = new SharedUtils(_webServices.Url, _webServices.Username, _webServices.Password_ClearText, true, "");
     GRINGlobal.Client.Common.GGMessageBox ggMessageBox = new GRINGlobal.Client.Common.GGMessageBox("There were errors retrieving user settings.\n\nFull error message:\n{0}", "Load User Settings Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxDefaultButton.Button1);
     ggMessageBox.Name = "UserSettings_LoadMessage1";
     if (sharedUtils != null && sharedUtils.IsConnected) sharedUtils.UpdateControls(ggMessageBox.Controls, ggMessageBox.Name);
     //if (ggMessageBox.MessageText.Contains("{0}")) ggMessageBox.MessageText = string.Format(ggMessageBox.MessageText, remoteDBUserSettings.Tables["ExceptionTable"].Rows[0]["Message"].ToString());
     string[] argsArray = new string[100];
     argsArray[0] = remoteDBUserSettings.Tables["ExceptionTable"].Rows[0]["Message"].ToString();
     ggMessageBox.MessageText = string.Format(ggMessageBox.MessageText, argsArray);
     ggMessageBox.ShowDialog();
     }
     // Clean up...
     remoteDBUserSettings.Dispose();
 }
Пример #23
0
        public LookupTableLoader(string localDBInstance, SharedUtils sharedUtils)
        {
            _sharedUtils = sharedUtils;

            InitializeComponent();
        }
Пример #24
0
        public void buildDataviewTabControl(TabControl ux_tabcontrolDataview, SharedUtils sharedUtils)
        {
            int numDataviewTabs = -1;

            // Clear the dataview tabs...
            ux_tabcontrolDataview.TabPages.Clear();

            // Now add back in the tabpage for adding new tabpages...
            if (!ux_tabcontrolDataview.TabPages.ContainsKey("ux_tabpageDataviewNewTab"))
            {
                ux_tabcontrolDataview.TabPages.Add("ux_tabpageDataviewNewTab", "...");
            }

            // Get the number of tabpages saved in the current user's settings...
            int.TryParse(sharedUtils.GetUserSetting("", ux_tabcontrolDataview.Name, "TabPages.Count", "-1"), out numDataviewTabs);

            // Create the user's saved dataview tabs...
            if (numDataviewTabs > 0)
            {
                for (int i = 0; i < numDataviewTabs; i++)
                {
                    DataviewProperties dp = new DataviewProperties();
                    dp.TabName = sharedUtils.GetUserSetting("", ux_tabcontrolDataview.Name, "TabPages[" + i.ToString() + "].TabName", "");
                    dp.DataviewName = sharedUtils.GetUserSetting("", ux_tabcontrolDataview.Name, "TabPages[" + i.ToString() + "].DataviewName", "");
                    dp.StrongFormName = sharedUtils.GetUserSetting("", ux_tabcontrolDataview.Name, "TabPages[" + i.ToString() + "].FormName", "");
                    dp.ViewerStyle = sharedUtils.GetUserSetting("", ux_tabcontrolDataview.Name, "TabPages[" + i.ToString() + "].ViewerStyle", "");
                    dp.AlwaysOnTop = sharedUtils.GetUserSetting("", ux_tabcontrolDataview.Name, "TabPages[" + i.ToString() + "].AlwaysOnTop", "");
                    ux_tabcontrolAddTab(ux_tabcontrolDataview, dp.TabName, dp, Math.Min(i, ux_tabcontrolDataview.TabPages.IndexOfKey("ux_tabpageDataviewNewTab")));
                }
            }
            else
            {
                // Make the default Accession dataview tab...
                DataviewProperties dp = new DataviewProperties();
                dp.TabName = "Accessions";
                dp.DataviewName = "get_accession";
                dp.StrongFormName = "";
                dp.ViewerStyle = "Spreadsheet";
                dp.AlwaysOnTop = "false";
                ux_tabcontrolAddTab(ux_tabcontrolDataview, dp.TabName, dp, Math.Min(0, ux_tabcontrolDataview.TabPages.IndexOfKey("ux_tabpageDataviewNewTab")));
                // Make the default Inventory dataview tab...
                dp = new DataviewProperties();
                dp.TabName = "Inventory";
                dp.DataviewName = "get_inventory";
                dp.StrongFormName = "";
                dp.ViewerStyle = "Spreadsheet";
                dp.AlwaysOnTop = "false";
                ux_tabcontrolAddTab(ux_tabcontrolDataview, dp.TabName, dp, Math.Min(1, ux_tabcontrolDataview.TabPages.IndexOfKey("ux_tabpageDataviewNewTab")));
                // Make the default Orders dataview tab...
                dp = new DataviewProperties();
                dp.TabName = "Orders";
                dp.DataviewName = "get_order_request";
                dp.StrongFormName = "";
                dp.ViewerStyle = "Spreadsheet";
                dp.AlwaysOnTop = "false";
                ux_tabcontrolAddTab(ux_tabcontrolDataview, dp.TabName, dp, Math.Min(2, ux_tabcontrolDataview.TabPages.IndexOfKey("ux_tabpageDataviewNewTab")));
                // Make the default Cooperators dataview tab...
                dp = new DataviewProperties();
                dp.TabName = "Cooperators";
                dp.DataviewName = "get_cooperator";
                dp.StrongFormName = "";
                dp.ViewerStyle = "Spreadsheet";
                dp.AlwaysOnTop = "false";
                ux_tabcontrolAddTab(ux_tabcontrolDataview, dp.TabName, dp, Math.Min(3, ux_tabcontrolDataview.TabPages.IndexOfKey("ux_tabpageDataviewNewTab")));
            }
            // Make the first tab active...
            ux_tabcontrolDataview.SelectedTab = ux_tabcontrolDataview.TabPages[0];
        }
Пример #25
0
        public void UpdateTable(object objDataviewName)
        {
            string dataviewName = (string)objDataviewName;
            bool updateStatus = false;
            DataTable lookupTableStatus = new DataTable("lookup_table_status");
            DataRow lookupTableStatusRow = null;
            if (_localData.TableExists("lookup_table_status"))
            {
                lookupTableStatus = _localData.GetData("SELECT * FROM lookup_table_status WHERE dataview_name=@dataviewname", new string[1] { "@dataviewname=" + dataviewName });
            }

            if (lookupTableStatus != null &&
                lookupTableStatus.Rows.Count > 0)
            {
                lookupTableStatusRow = lookupTableStatus.Rows[0];
            }

            if (lookupTableStatusRow != null &&
                (lookupTableStatusRow["status"].ToString().Trim().ToUpper() == "COMPLETED" ||
                lookupTableStatusRow["status"].ToString().Trim().ToUpper() == "UPDATED"))
            {
                // Use the last sync date for the remote database query...
                DateTime lastSyncDate = new DateTime();
                lastSyncDate = Convert.ToDateTime(lookupTableStatus.Rows[0]["sync_date"].ToString());

                if (lastSyncDate.AddSeconds(5) < DateTime.UtcNow)
                {
                    int pageSize = 100000;
            //string selectParams = ":createddate=" + lastSyncDate.ToString("u") + "; :modifieddate=" + lastSyncDate.ToString("u") + "; :valuemember=; :startpkey=; :stoppkey=; :displaymember;";
            string selectParams = ":createddate=" + lastSyncDate.ToString("s") + "; :modifieddate=" + lastSyncDate.ToString("s") + "; :valuemember=; :startpkey=; :stoppkey=; :displaymember;";

                    // Go get the records from the remote database that are newer than the lastSyncDate...
                    DataSet tempSync = _webServices.GetData(dataviewName, selectParams, 0, pageSize);
                    if (tempSync.Tables.Contains(dataviewName))
                    {
                        DataTable syncTable = tempSync.Tables[dataviewName].Clone();
                        //// Apply any column constraints (indicated in the column extended properties) to the table...
                        //ApplyColumnConstraints(syncTable);
                        syncTable.Rows.Clear();
                        syncTable.AcceptChanges();
                        syncTable.Load(tempSync.Tables[dataviewName].CreateDataReader(), LoadOption.Upsert);
                        if (syncTable.Rows.Count == 0)
                        {
                            lookupTableStatusRow["current_pk"] = lookupTableStatusRow["max_pk"];
                            lookupTableStatusRow["status"] = "Updated";
                            lookupTableStatusRow["sync_date"] = DateTime.UtcNow;
                            updateStatus = true;
                        }
                        else if (syncTable.Rows.Count > 0 &&
                            syncTable.Rows.Count < pageSize)
                        {
                            // Check to make sure the user wants to update this table...
                            if (lookupTableStatusRow["auto_update"].ToString().Trim().ToUpper() == "Y")
                            {
                                // Save the new lookup table rows to the local database...
                                SaveDataPageToLocalDB(syncTable);
                                // Update the dictionary if one is being used...
                                if (_pkeyLUTCacheCollection.ContainsKey(dataviewName))
                                {
                                    UpdatePKeyLUTDictionary(dataviewName, _pkeyLUTCacheCollection[dataviewName]);
                                }
                                else if (dataviewName.ToLower().Trim() == "code_value_lookup")
                                {
                                    UpdateCodeValueLUTDictionary("code_value_lookup", _codevalueLUTCache);
                                }

                                // Update the stats for this lookup table in the lookup_table_status table on the local database...
                                lookupTableStatusRow["current_pk"] = lookupTableStatusRow["max_pk"];
                                lookupTableStatusRow["status"] = "Updated";
                                lookupTableStatusRow["sync_date"] = DateTime.UtcNow;
                                updateStatus = true;
                            }
                            else
                            {
                                // If the user does not want to update this table but there are less than 1000 new records that need to be downloaded
                                // mark its status as 'PARTIAL' so that the LUT maint. dialog displays warnings properly
                                Int64 max = pageSize + 1;
                                Int64 current = 0;
                                if (Int64.TryParse(lookupTableStatusRow["max_pk"].ToString(), out max) &&
                                    Int64.TryParse(lookupTableStatusRow["current_pk"].ToString(), out current) &&
                                    (max - current) > pageSize)
                                {
                                    lookupTableStatusRow["status"] = "Partial";
                                }
                                updateStatus = false;
                            }
                        }
                        else
                        {
                            lookupTableStatusRow["status"] = "Failed";
                            lookupTableStatusRow["sync_date"] = DateTime.UtcNow;
                            updateStatus = true;
                        }
                        SaveDataPageToLocalDB(lookupTableStatus);
                    }
                    else
                    {
                        // No dataview named 'XXX' exists in the sys_dataview table.
                        // Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.
                        if (tempSync.Tables.Contains("ExceptionTable") &&
                            tempSync.Tables["ExceptionTable"].Rows.Count > 0 &&
                            !tempSync.Tables["ExceptionTable"].Rows[0]["Message"].ToString().Contains("Timeout expired"))
                        {
                            // There appears to be a problem getting data for this lookup table (most likely the LU dataview is missing/broken)...
            //lookupTableStatusRow.Delete();
            //SaveDataPageToLocalDB(lookupTableStatus);
            //if (_localData.TableExists(dataviewName)) _localData.Remove(dataviewName);
                            updateStatus = true;
                        }
                    }
                }
                else
                {
                    // This table was successfully updated in the last 10 seconds so
                    // skip the update and return successful status...
                    updateStatus = true;
                }
            }
            else
            {
            //System.Windows.Forms.MessageBox.Show("WARNING!\nThe system can not perform Update for '" + dataviewName + "' until the table has been successfully downloaded", "Partially Loaded Lookup Table", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Exclamation);
            SharedUtils sharedUtils = new SharedUtils(_webServices.Url, _webServices.Username, _webServices.Password_ClearText, true, "");
            GRINGlobal.Client.Common.GGMessageBox ggMessageBox = new GRINGlobal.Client.Common.GGMessageBox("WARNING!\nThe system can not perform Update for '{0}' until the table has been successfully downloaded.\n\nWould you like to do this now?", "Partially Loaded Lookup Table", System.Windows.Forms.MessageBoxButtons.YesNo, System.Windows.Forms.MessageBoxDefaultButton.Button1);
            ggMessageBox.Name = "LookupTables_LoadTableFromDatabaseMessage3";
            if (sharedUtils != null && sharedUtils.IsConnected) sharedUtils.UpdateControls(ggMessageBox.Controls, ggMessageBox.Name);
            //if (ggMessageBox.MessageText.Contains("{0}")) ggMessageBox.MessageText = string.Format(ggMessageBox.MessageText, dataviewName.ToUpper());
            string[] argsArray = new string[100];
            argsArray[0] = dataviewName.ToUpper();
            ggMessageBox.MessageText = string.Format(ggMessageBox.MessageText, argsArray);
            //ggMessageBox.ShowDialog();
            if (System.Windows.Forms.DialogResult.Yes == ggMessageBox.ShowDialog())
            {
            // Start the LUT maintenance dialog...
            //LookupTableLoader ltl = new LookupTableLoader(localDBInstance, _sharedUtils);
            LookupTableLoader ltl = new LookupTableLoader(_localData.ConnectionString, sharedUtils);
            ltl.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
            ltl.ShowDialog();
            }
            updateStatus = false;

            }

            // Clear the lookup table status cache (so that it can be refreshed for each lookup table on demand)...
            _lookupTableStatus.Clear();
            //return updateStatus;
        }
Пример #26
0
        public OrderWizard(string pKeys, SharedUtils sharedUtils)
        {
            InitializeComponent();

            // Wire up the event handlers for Order Request binding source...
            _orderRequestBindingSource = new BindingSource();
            _orderRequestBindingSource.ListChanged += new ListChangedEventHandler(_orderRequestBindingSource_ListChanged);
            _orderRequestBindingSource.CurrentChanged += new EventHandler(_orderRequestBindingSource_CurrentChanged);
            _orderRequestItemBindingSource = new BindingSource();
            _orderRequestActionBindingSource = new BindingSource();
            _sharedUtils = sharedUtils;
            _originalPKeys = pKeys;
            foreach (string pkeyToken in pKeys.Split(';'))
            {
                if (pkeyToken.Split('=')[0].Trim().ToUpper() == ":ORDERREQUESTID") _selectionList = pkeyToken.Split('=')[1];
            }

            // Wire up the event handlers for Web Order Request binding source...
            _webOrderRequestBindingSource = new BindingSource();
            _webOrderRequestBindingSource.CurrentChanged += new EventHandler(_webOrderRequestBindingSource_CurrentChanged);
            _webOrderRequestItemBindingSource = new BindingSource();

            // Make the filter groupboxes the same size and location...
            ux_groupboxWebOrderFilters.Size = ux_groupboxOrderFilters.Size;
            ux_groupboxWebOrderFilters.Location = ux_groupboxOrderFilters.Location;
            ux_groupboxWebOrderFilters.Visible = false;
            ux_groupboxOrderFilters.Visible = true;
        }