コード例 #1
0
ファイル: FrmMain.cs プロジェクト: HVPA/VariantExporter
        public FrmMain()
        {
            InitializeComponent();
            
            // ******* testing - backgroundworkers
            init_backgroundWorkers();
            // ******* testing - backgroundworkers

            // Display loading splash screen while app init all vars
            //SplashScreen ss = new SplashScreen();
            ss = new SplashScreen();
            ss.Show();
            
            m_previousWindowState = (this.WindowState == FormWindowState.Minimized ? FormWindowState.Normal : this.WindowState);

            context = new DefaultExtractorContext();
            
            // get conf
            conf = context.GetConfiguration();

            // init logger
            log = new Log(bool.Parse(conf.VerboseLogEnable), txtStatusLog);
            
            // get webproxy and set webproxy
            ReloadProxy();

            // get orgSite
            bool RESTError = false;
            bool retry = true;

            // A loop that checks connection to the web, if unable to connect it allows user to jump into proxy
            // settings and retry connecting until either a connection can be established or user kills it.
            while (retry)
            {
                try
                {
                    // try to get orgsite via REST calls if this fails then close app.
                    _orgSite = DataLoader.GetOrgSite("OrgHashCode", conf.OrganisationHashCode);
                    retry = false;
                    RESTError = false;
                }
                catch (Exception ex)
                {
                    // close the splash screen
                    ss.Close();

                    RESTError = true;
                    // write debug message to log
                    log.write(ex.ToString());

                    // rename buttons to messagebox
                    MessageBoxManager.Yes = "Retry";
                    MessageBoxManager.No = "Settings";
                    MessageBoxManager.Cancel = "Quit";
                    // registers the buttons renamed
                    MessageBoxManager.Register();

                    DialogResult result = MessageBox.Show("Could not connect to HVP servers, there maybe issues with your current connection or the server maybe down please try again. \nIf you are connected to the internet via proxies please click on settings to configure your web proxies.",
                        "Error! Could not connect to HVP servers", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Error);
                    
                    // unregisters the naming back to default
                    MessageBoxManager.Unregister();

                    // no == settings
                    if (result == DialogResult.No)
                    {
                        // open settings frm
                        FrmConf frmConf = new FrmConf(conf, context, this, true);
                        frmConf.ShowDialog();
                    }
                    
                    // cancel == cancel
                    if (result == DialogResult.Cancel)
                    {
                        // kill loop
                        retry = false;
                        // exit app
                        System.Environment.Exit(0);
                    }
                }
            }

            // close loading splash screen
            ss.Close();

            // if no error from REST
            if (RESTError == false)
            {
                // nibhernate factory for sqlite db connection
                _slFactory = new SQLiteDBFactory();
            
                // Clear Cache
                ClearCache = bool.Parse(conf.ClearCache);

                // start the file watcher if there are any uploads that require it.
                _watcher = new Util.FileWatcher(this);
                
                // check if there is an update when program loads up
                AutoUpdater.Start(conf.AutoUpdateLink);

                // set the timer for auto update in milliseconds
                CheckForUpdatesTimedEvent(3600000); // every 1 hour

                // get the commonAppPath, if release version then should be under user data
                _commonAppPath = CommonAppPath.GetCommonAppPath();

                // start with the modal upload form on screen first
                FrmUpload frmUpload = new FrmUpload(this, conf.OrganisationHashCode);
                frmUpload.Focus();
                frmUpload.ShowDialog();
            }

            // get the build version from the assembly
            _Version = Assembly.GetExecutingAssembly().GetName().Version.ToString();

            // display the version number in the form window text
            // remove the last 2 chars from version since we dont display that to the user
            this.Text = "HVP - Variant Exporter (" + _Version.Remove(_Version.Length - 2) + ")";

            // display notes on icon hover
            notifyIcon1.Icon = this.Icon;
        }
コード例 #2
0
ファイル: FrmConf.cs プロジェクト: HVPA/VariantExporter
        private void btnSave_Click(object sender, EventArgs e)
        {
            SplashScreen ss = new SplashScreen();

            try
            {
                // wait while do stuff
                ss.Show();

                // disable controls for this form and frmMain
                DisableAllControls();
                _frmMain.DisableAllControls();

                // checked if proxy settings have changed
                bool proxyChang = HasProxyChanged();

                // write changes to config.xml
                SaveControls();

                // reload fields into main form
                if (proxyChang)
                    _frmMain.ReloadProxy();

                ss.Close();

                // close this dialogue form
                this.Close();
            }
            catch(Exception ex)
            {
                ss.Close();
                Log log = new Log(true);
                log.write(ex.ToString());
                MessageBox.Show("Something went wrong while saving. Please try again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                // re-enable all controls again
                EnableAllControls();
                _frmMain.EnableAllControls();
            }
        }
コード例 #3
0
ファイル: FrmMain.cs プロジェクト: HVPA/VariantExporter
        /// <summary>
        /// Process data from datagrid which includes encrypting and zipping data and
        /// sending data to the specified destination
        /// </summary>
        /// <param name="serverAddress">Destination server data is sent to</param>
        /// <param name="audit">Log data sent in the internal audit database</param>
        private void ProcessAndSendData(string serverAddress, bool audit, bool isTest)
        {
            bool DataSuccessfullySent = false;

            int sentVariants = 0;

            Cursor.Current = Cursors.WaitCursor;
            SplashScreen ss = new SplashScreen();
            ss.Show();
            DisableAllControls();

            // if data is read from a data source file check if file is in use by another
            // process, otherwise file can not be moved to the "sent" subdirectory.
            if (_spreadsheetPath != string.Empty)
            {
                try
                {
                    using (System.IO.Stream stream = new System.IO.FileStream(_spreadsheetPath, System.IO.FileMode.Open))
                    {
                        // Nothing to see here. Just testing to see if file is not opened or in use by another process.
                    }
                }
                catch (Exception ex)
                {
                    ss.Close();
                    EnableAllControls();
                    
                    // alert user file is being used by another process
                    MessageBox.Show("The current file: " + _spreadsheetPath +
                                            " is being used by another process. " +
                                            "\n" +
                                            "\nIf you have the file open in an application, please close the application before continuing.",
                                            "File in use:  " + _spreadsheetPath,
                                            MessageBoxButtons.OK, MessageBoxIcon.Asterisk);

                    // log error exception
                    log.write("The file: " + _spreadsheetPath + " is being used by another process.");
                    log.write(ex.ToString());
                    log.write("No data was sent!");

                    // end this function
                    return;
                }
            }

            if (dgVariant.Rows.Count != 0)
            {
                DataTable original = (DataTable)dgVariant.DataSource;
                DataTable yesOnly = original.Clone();

                SiteConf.Upload.Object upload = ExporterCommon.DataLoader.GetUpload(_uploadID);
                // get all the genes with the disease tags
                IList<SiteConf.Gene.Object> geneList = ExporterCommon.DataLoader.GetGeneList(upload.ID);

                // sorting data to send
                log.write("======= Begin Data Transfer =======");
                log.write("Sorting data for sending....");
                foreach (DataGridViewRow row in dgVariant.Rows)
                {
                    if (Convert.ToBoolean(row.Cells[0].Value))
                    {
                        yesOnly.ImportRow(((DataRowView)row.DataBoundItem).Row);
                    }
                }

                sentVariants = yesOnly.Rows.Count;

                if (yesOnly.Rows.Count > 0)
                {
                    // timestamp for use in the xml and zip file names
                    DateTime dt = DateTime.Now;
                    string timestamp = String.Format("{0:yyyyMMddHHmmss}", dt);

                    XmlOutput output = new XmlOutput();

                    string xmlFileName = timestamp + ".xml";

                    CommonAppPath.CreateDirectory("raw");
                    string xmlFilePath = _commonAppPath + "\\raw\\" + xmlFileName;

                    // hash table to store the refseq names and versions
                    Hashtable refSeqNameHT = new Hashtable();
                    Hashtable refSeqVerHT = new Hashtable();

                    // hash tables to store patient grhanite hashes
                    getHashTableRefSeq(refSeqNameHT, refSeqVerHT, upload);

                    // generate xml file
                    log.write("Writing to xml...");
                    output.Generate(conf.PortalWebSite, xmlFilePath, yesOnly, refSeqNameHT,
                        refSeqVerHT, _OrgHashCode, geneList);

                    // send xml to server
                    try
                    {
                        string encryptedFile = timestamp + ".txt";

                        CommonAppPath.CreateDirectory("temp");
                        string encryptedFilePath = _commonAppPath + "\\temp\\" + encryptedFile;

                        // start the encryption executable
                        log.write("Encrypting data....");

                        // location of HVP_Encryption executable
                        string appPath = System.IO.Path.GetDirectoryName(
                            System.Reflection.Assembly.GetEntryAssembly().Location)
                            + "\\Executables\\HVP_Encryption.exe";

                        // Encrypt file
                        Encryption.HVP_EncryptFile(appPath, xmlFilePath, encryptedFilePath, _commonAppPath + "\\keys\\",
                            conf.PrivateKey, conf.PublicKey, log);

                        // zip file name is combination of org hash code and date
                        string zippedFileName = _orgSite.OrgHashCode + "_" + DateTime.Now.ToString("yyyyMMddHHmmss");
                        string zippedFilePath = _commonAppPath + "\\temp\\" + zippedFileName;

                        // zip files
                        Decompression.ZippUpTransferFiles(zippedFileName, encryptedFilePath, _commonAppPath + "\\temp\\", conf.PrivateKey.Replace(".private", ""), log);

                        // send the zip file to destination server
                        log.write("Sending data to: " + serverAddress);

                        // webclient for uploading data
                        WebClient client = new WebClient();
                        // set proxy to webclient if any
                        client.Proxy = _proxy;

                        // send zipped file
                        string sent = Transmit.SendData(zippedFilePath + ".zip", serverAddress, client, log);

                        if (_CancelledAuth)
                        {
                            log.write("User cancelled proxy auth login");
                            return;
                        }

                        // sent ok we should get a post
                        if (sent == "<HTML>POST OK.</HTML>")
                        {
                            log.write("Data successfully sent!!! " + sentVariants + " variants sent.");

                            // only log data sent to db if sending to live server and not the test server
                            if (audit)
                            {
                                // save the transaction of each instance to the auditdb
                                log.write("Saving transaction to db...");
                                SaveAuditTransaction(yesOnly, xmlFilePath);
                            }

                            // clear the Invalid results table and disable the invalid data button
                            invalidResults = null;
                            btnErrors.Enabled = false;

                            // rename the sent xls and move to folder called "sent", creates folder if not exist
                            if (rbnSpreadsheet.Checked == true && isTest != true)
                            {
                                if (!System.IO.File.Exists(upload.DataSourceName + "\\sent"))
                                {
                                    // create new directory called sent in the source location of xls
                                    System.IO.Directory.CreateDirectory(upload.DataSourceName + "\\sent");
                                }

                                // get the source file extension
                                string sourceFileExt = System.IO.Path.GetExtension(_spreadsheetPath);

                                // set the name of file to the datee/time sent
                                string renamedFile = "(" + timestamp + ")" + sourceFileExt;

                                // move spreadsheet to directory called sent
                                bool fileMoved = false;
                                // loop to check if file is in use by another process, will continue to loop
                                // until file can be moved to the sent folder or user acknowledges it can't 
                                // be moved by the program and user should move it themselves manually to 
                                // avoid sending data from the file again.
                                while (!fileMoved)
                                {
                                    try
                                    {
                                        System.IO.File.Move(_spreadsheetPath, upload.DataSourceName +
                                            "\\sent\\" + System.IO.Path.GetFileName(_spreadsheetPath).Replace(sourceFileExt, "") + renamedFile);
                                        fileMoved = true;

                                    }
                                    catch (System.IO.IOException ioEx)
                                    {
                                        // if unable to rename/move file
                                        var result = MessageBox.Show("Unable to access file: " + _spreadsheetPath +
                                            "\n" +
                                            "\nThe exporter has successfully uploaded the data, however it is unable to move the file from datasource folder to the sent sub folder." +
                                            "\n" +
                                            "\nIf you have the file open in an application, please close the application and click Retry." +
                                            "\n" +
                                            "\nOr click Cancel and the file will remain in your datasource folder, you will need to manually move that file out of the datasource folder otherwise you may end up resending the data again.",
                                            "Can not access file:  " + _spreadsheetPath,
                                            MessageBoxButtons.RetryCancel, MessageBoxIcon.Asterisk);

                                        if (result == DialogResult.Cancel)
                                        {
                                            // if cancel exit loop with error
                                            fileMoved = true;

                                            // log error
                                            log.write("Unable to access the file: " + _spreadsheetPath);
                                            log.write(ioEx.ToString());
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        ss.Close();
                                        EnableAllControls();

                                        // log error
                                        log.write("The data has been successfully uploaded however the Variant Exporter has encountered an error.");
                                        log.write(ex.ToString());

                                        // set to true to exit out of the loop
                                        fileMoved = true;
                                    }
                                }
                            }

                            // Data has been successfully sent
                            DataSuccessfullySent = true;

                            // clear the datagrid
                            dgVariant.DataSource = null;

                            // clear the spreadsheet path now that it has been sent
                            // keep the path if it was only a test send
                            if (!isTest)
                                _spreadsheetPath = "";
                        }
                        else
                        {
                            ss.Close();
                            EnableAllControls();
                            log.write("Error connecting to server!!!!");
                            MessageBox.Show("Error connecting to server, please try again.", "Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error); ;
                        }
                    }
                    catch (WebException ex)
                    {
                        ss.Close();
                        EnableAllControls();
                        log.write("Unexpected error!!!");
                        log.write(ex.ToString());
                        MessageBox.Show("Error connecting to server, please try again.", "Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    finally
                    {
                        Cursor.Current = Cursors.Default;
                        ss.Close();
                        EnableAllControls();

                        if (ClearCache)
                        {
                            // always clear the contents in the temp
                            log.write("Clearing contents from temp folder....");
                            System.IO.DirectoryInfo temp = new System.IO.DirectoryInfo(_commonAppPath + "\\temp");
                            foreach (System.IO.FileInfo file in temp.GetFiles())
                            {
                                file.Delete();
                            }

                            // remove the raw xml files
                            log.write("Clearing the contents from raw folder....");
                            System.IO.DirectoryInfo raw = new System.IO.DirectoryInfo(_commonAppPath + " \\raw");
                            foreach (System.IO.FileInfo file in raw.GetFiles())
                            {
                                file.Delete();
                            }
                        }

                        // clear the filename from title
                        lblTitle.Text = upload.Name;
                    }
                }
                else
                {
                    ss.Close();
                    EnableAllControls();
                    MessageBox.Show("You have not selected any rows!!!", "Export Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                ss.Close();
                EnableAllControls();
                MessageBox.Show("There is nothing to send", "No Data selected");
            }

            log.write("======= Data Transfer Complete =======");

            if (DataSuccessfullySent)
                MessageBox.Show("Data Successfully sent. " + sentVariants + " variants sent.", "Data sent", MessageBoxButtons.OK);

        }