Ejemplo n.º 1
0
        public ActionResult Datumi() //[Microsoft.AspNetCore.Mvc.FromBody] DatumiUlazniPodaci par
        {
            var query = _session.CreateSQLQuery("exec datumi");

            //query.SetParameter("period", par?.Period, NHibernateUtil.Int32);
            //query.SetParameter("zavrsen", par?.Zavrsen, NHibernateUtil.Boolean);
            query.SetResultTransformer(new AliasToBeanResultTransformer(typeof(DatumiIzlazniPodaci)));
            var res = query.List <DatumiIzlazniPodaci>();

            return(Ok(res));
        }
Ejemplo n.º 2
0
        /// <getTasksByUserwithDetail>
        /// Get Tasks By User with Detail
        /// </summary>
        /// <param name="USerId">User id.(Guid)</param>
        /// <param name="days">Number of Days.(int)</param>
        /// <returns>Return values in the form of array list.(ArrayList)</returns>
        public ArrayList getTasksByUserwithDetail(Guid USerId, int days, Guid GroupId)
        {
            //Creates a database connection and opens up a session
            using (NHibernate.ISession session = SessionFactory.GetNewSession())
            {
                //After Session creation, start Transaction.
                using (NHibernate.ITransaction transaction = session.BeginTransaction())
                {
                    //Proceed action, to get details of task. //ts.UserId=:userid and //.SetParameter("userid", USerId)
                    //var queryString = @"SELECT * FROM Tasks ts LEFT JOIN User u on ts.AssignTaskTo=u.Id where ts.UserId=:userid and AssignDate>=DATE_ADD(NOW(),INTERVAL -" + days + " DAY)";
                    //var queryString = @"SELECT * FROM Tasks ts LEFT JOIN User u on ts.AssignTaskTo=u.Id where ts.GroupId=:GroupId and  AssignDate>=DATE_ADD(NOW(),INTERVAL -" + days + " DAY)";
                    try
                    {
                        var queryString = @"select * from tasks where (AssignTaskTo =:userid or UserId =:userid) and GroupId =:GroupId and  AssignDate>=DATE_ADD(NOW(),INTERVAL -" + days + " DAY)";
                        var query       = session.CreateSQLQuery(queryString)
                                          .SetParameter("userid", USerId)
                                          .SetParameter("GroupId", GroupId);
                        //.SetParameter("GroupId", GroupId);

                        ArrayList alstTask = new ArrayList();

                        foreach (var item in query.List())
                        {
                            alstTask.Add(item);
                        }
                        return(alstTask);
                    }
                    catch (Exception)
                    {
                        throw;
                    }
                } //End Transaction
            }     //End Session
        }
Ejemplo n.º 3
0
        public ActionResult Rekapitulacija(DateTime?dat1, DateTime?dat2, int klijentid, int ponudaid, int radninalogid)
        {
            try
            {
                var upit = _session.CreateSQLQuery("exec rekapitulacija :dat1, :dat2, :klijentid, :ponudaid, :radninalogid")
                           .SetParameter("dat1", null, NHibernateUtil.Date)
                           .SetParameter("dat2", null, NHibernateUtil.Date)
                           .SetParameter("klijentid", null, NHibernateUtil.Int32)
                           .SetParameter("ponudaid", null, NHibernateUtil.Int32)
                           .SetParameter("radninalogid", null, NHibernateUtil.Int32);

                if (dat1.HasValue)
                {
                    upit.SetParameter("dat1", dat1.Value, NHibernateUtil.Date);
                }
                if (dat2.HasValue)
                {
                    upit.SetParameter("dat2", dat2.Value, NHibernateUtil.Date);
                }
                if (klijentid != 0)
                {
                    upit.SetParameter("klijentid", klijentid, NHibernateUtil.Int32);
                }
                if (ponudaid != 0)
                {
                    upit.SetParameter("ponudaid", ponudaid, NHibernateUtil.Int32);
                }
                if (radninalogid != 0)
                {
                    upit.SetParameter("radninalogid", radninalogid, NHibernateUtil.Int32);
                }
                var rekap = upit.SetResultTransformer(new AliasToBeanResultTransformer(typeof(Rekapitulacija)))
                            .UniqueResult <Rekapitulacija>();



                return(Json(new { Success = true, Message = "", obj = rekap }));
            }

            catch (Exception ex)
            {
                _logger.LogError(ex.Message);
                return(Json(new { Success = false, Message = ex.Message }));
            }
        }
Ejemplo n.º 4
0
        public void Drop()
        {
            SqlConnection.ClearAllPools();

            using (ISessionFactory sessionFactory = masterConfiguration.BuildSessionFactory())
            {
                using (INHSession session = sessionFactory.OpenSession())
                {
                    var query  = session.CreateSQLQuery("DROP DATABASE ContactBook;");
                    var result = query.ExecuteUpdate();
                }
            }
        }
Ejemplo n.º 5
0
        public Korisnik KorisnikPostoji(string korisnickoIme)
        {
            var query = _session.CreateSQLQuery("exec KorisnikPostoji :korisnickoime");

            query.SetParameter("korisnickoime", korisnickoIme, NHibernateUtil.String);
            query.AddEntity(typeof(Korisnik));
            return(query.UniqueResult <Korisnik>());
        }
Ejemplo n.º 6
0
        public void Create()
        {
            using (ISessionFactory sessionFactory = masterConfiguration.BuildSessionFactory())
            {
                using (INHSession session = sessionFactory.OpenSession())
                {
                    var query  = session.CreateSQLQuery("CREATE DATABASE ContactBook;");
                    var result = query.ExecuteUpdate();
                }
            }

            var schemaExport = new SchemaExport(configuration);

            schemaExport.Create(false, true);
        }
Ejemplo n.º 7
0
        public ActionResult Brisi(int id)
        {
            //this.repo.find("Dokument?entitet=" + entitet + "&entitetopis=" + entitetoipis + "&entitetid" + entitet)
            try
            {
                var sql = _session.CreateSQLQuery("exec BrisiDokument :id");
                sql.SetParameter("id", id, NHibernateUtil.Int32);
                var ret = sql.ExecuteUpdate();
                return(Json(new { Success = true, Message = "", obj = ret }));
            }

            catch (Exception ex)
            {
                _logger.LogError(ex.Message);
                return(Json(new { Success = false, Message = ex.Message }));
            }
        }
Ejemplo n.º 8
0
 public void DeleteSelectRows(GroupCampaign ObjGrpCamp)
 {
     try
     {
         using (NHibernate.ISession session = SessionFactory.GetNewSession())
         {
             using (NHibernate.ITransaction transaction = session.BeginTransaction())
             {
                 var query = session.CreateSQLQuery("delete from GroupCampaign WHERE GroupCampaignName = :CampaignName and Module =:module").SetParameter("CampaignName", ObjGrpCamp.GroupCampaignName).SetParameter("module", ObjGrpCamp.Module);
                 int res   = query.ExecuteUpdate();
                 transaction.Commit();
             }
         }
     }
     catch (Exception ex)
     {
         GlobusLogHelper.log.Error("Error : " + ex.StackTrace);
     }
 }
Ejemplo n.º 9
0
 public ArrayList UnPaidUserCountByMonth()
 {
     using (NHibernate.ISession session = SessionFactory.GetNewSession())
     {
         using (NHibernate.ITransaction transaction = session.BeginTransaction())
         {
             ArrayList alstUser = new ArrayList();
             try
             {
                 NHibernate.IQuery query = session.CreateSQLQuery("Select month(CreateDate),Count(*) from User where PaymentStatus='unpaid' group by month(CreateDate)");
                 foreach (var item in query.List())
                 {
                     alstUser.Add(item);
                 }
                 return(alstUser);
             }
             catch (Exception Err)
             {
                 Console.Write(Err.StackTrace);
                 return(alstUser);
             }
         }
     }
 }
Ejemplo n.º 10
0
 public ISQLQuery CreateSQLQuery(string q)
 {
     return(_session.CreateSQLQuery(q));
 }
        void setData(object sender, DoWorkEventArgs e)
        {
            try
            {
                Map <int, List <PSMRow> > precursorMassErrorsByCharge = new Map <int, List <PSMRow> >();;
                IDictionary <int, int>    spectralCountByChargeState;
                lock (session)
                {
                    var randomIds = session.CreateQuery("SELECT psm.Id " + viewFilter.GetFilteredQueryString(DataFilter.FromPeptideSpectrumMatch))
                                    .List <long>()
                                    .Shuffle()
                                    .Take(50000)
                                    .OrderBy(o => o);
                    string randomIdSet = String.Join(",", randomIds.Select(o => o.ToString()).ToArray());
                    var    query       = session.CreateSQLQuery("SELECT psm.ObservedNeutralMass, psm.MonoisotopicMassError, psm.MolecularWeightError, s.ScanTimeInSeconds, psm.Charge " +
                                                                "FROM PeptideSpectrumMatch psm " +
                                                                "JOIN Spectrum s ON psm.Spectrum=s.Id " +
                                                                "WHERE psm.Id IN (" + randomIdSet + ") " +
                                                                "GROUP BY psm.Id");
                    query.List <object[]>().ForEach(o =>
                                                    precursorMassErrorsByCharge[Convert.ToInt32(o[4])].Add(new PSMRow
                    {
                        ObservedNeutralMass = Convert.ToDouble(o[0]),
                        MassError           = PeptideSpectrumMatch.GetSmallerMassError(Convert.ToDouble(o[1]), Convert.ToDouble(o[2])),
                        ScanTime            = Convert.ToDouble(o[3]) / 60, // convert to minutes
                        Charge = Convert.ToInt32(o[4])
                    }));

                    var query2 = session.CreateQuery("SELECT psm.Charge, COUNT(DISTINCT psm.Spectrum.id) " +
                                                     dataFilter.GetFilteredQueryString(DataFilter.FromPeptideSpectrumMatch) +
                                                     "GROUP BY psm.Charge");
                    spectralCountByChargeState = query2.List <object[]>().ToDictionary(o => Convert.ToInt32(o[0]), o => Convert.ToInt32(o[1]));
                }

                Map <int, List <List <PSMRow> > > clusteredPrecursorMassErrorsByCharge = clusterMassErrors(precursorMassErrorsByCharge);

                // convert to PPM if the user requested it
                if (!ppmMassErrorMenuItem.Text.Contains("PPM"))
                {
                    clusteredPrecursorMassErrorsByCharge.Values.ForEach(o3 => o3.ForEach(o2 => o2.ForEach(o => o.MassError = o.MassError / o.ObservedNeutralMass * 1e6)));
                }

                {
                    var csr = new ColorSymbolRotator();
                    precursorMassErrorForm.ZedGraphControl.GraphPane.CurveList.Clear();
                    foreach (var kvp in clusteredPrecursorMassErrorsByCharge)
                    {
                        bool firstCluster = true;
                        var  color        = csr.NextColor;
                        foreach (var precursorMassErrorCluster in kvp.Value)
                        {
                            var precursorMassErrors      = precursorMassErrorCluster;
                            var precursorMassErrorValues = precursorMassErrors.Select(o => o.MassError).ToArray();
                            var densityCurve             = new LineItem(firstCluster ? kvp.Key.ToString() : "", getDensityCurve(precursorMassErrorValues, 0), color, SymbolType.None);
                            var grassPlot = new LineItem("", precursorMassErrorValues, Enumerable.Repeat(0.0, precursorMassErrorValues.Length).ToArray(), color, SymbolType.VDash)
                            {
                                Tag = kvp.Key
                            };
                            densityCurve.Line.IsAntiAlias = true;
                            precursorMassErrorForm.ZedGraphControl.GraphPane.CurveList.Add(densityCurve);
                            precursorMassErrorForm.ZedGraphControl.GraphPane.CurveList.Add(grassPlot);
                            firstCluster = false;
                        }
                    }
                }

                {
                    var csr = new ColorSymbolRotator();
                    scanTimeDistributionForm.ZedGraphControl.GraphPane.CurveList.Clear();
                    foreach (var kvp in precursorMassErrorsByCharge)
                    {
                        var precursorMassErrors = kvp.Value;
                        var scanTimeValues      = precursorMassErrors.Select(o => o.ScanTime).ToList();
                        var color = csr.NextColor;
                        if (scanTimeValues.Max() > 0)
                        {
                            var densityCurve = new LineItem(kvp.Key.ToString(), getDensityCurve(scanTimeValues, 0), color, SymbolType.None);
                            var grassPlot    = new LineItem("", scanTimeValues.ToArray(), Enumerable.Repeat(0.0, scanTimeValues.Count).ToArray(), color, SymbolType.VDash);
                            densityCurve.Line.IsAntiAlias = true;
                            scanTimeDistributionForm.ZedGraphControl.GraphPane.CurveList.Add(densityCurve);
                            scanTimeDistributionForm.ZedGraphControl.GraphPane.CurveList.Add(grassPlot);
                        }
                    }

                    if (scanTimeDistributionForm.ZedGraphControl.GraphPane.CurveList.IsNullOrEmpty())
                    {
                        scanTimeDistributionForm.ZedGraphControl.GraphPane.GraphObjList.Add(
                            new TextObj("No scan time information present.\r\nUse File/Embed to import scan times from raw data.",
                                        0.5, 0.5, CoordType.ChartFraction, AlignH.Center, AlignV.Center)
                        {
                            FontSpec = new FontSpec("monospace", 18.0f, Color.Black, true, false, false)
                        });
                    }
                }

                var colorRotator = new ColorSymbolRotator();
                var colors       = new List <Color>();
                foreach (var kvp in spectralCountByChargeState)
                {
                    colors.Add(colorRotator.NextColor);
                }

                chargeStatesForm.ZedGraphControl.GraphPane.CurveList.Clear();
                chargeStatesForm.ZedGraphControl.GraphPane.BarSettings.MinClusterGap = 8;
                var barItem = chargeStatesForm.ZedGraphControl.GraphPane.AddBar("", spectralCountByChargeState.Keys.Select(o => (double)o).ToArray(), spectralCountByChargeState.Values.Select(o => (double)o).ToArray(), Color.White) as BarItem;
                for (int i = 0; i < barItem.Points.Count; ++i)
                {
                    barItem.Points[i].ColorValue = (double)i + 1;
                }
                barItem.Bar.Fill = new Fill(colors.ToArray())
                {
                    Type     = FillType.GradientByColorValue,
                    RangeMin = 1,
                    RangeMax = colors.Count
                };
                chargeStatesForm.ZedGraphControl.GraphPane.XAxis.Scale.TextLabels = spectralCountByChargeState.Keys.Select(o => o.ToString()).ToArray();
            }
            catch (Exception ex)
            {
                e.Result = ex;
            }
        }
Ejemplo n.º 12
0
        private static void TestIdentityOff(NHibernate.ISession session, string tableName)
        {
            var sqlQry = session.CreateSQLQuery(@"SET IDENTITY_INSERT TestService.dbo." + tableName + " OFF");

            sqlQry.UniqueResult();
        }
Ejemplo n.º 13
0
        public void ApplyQonverterSettings(IDictionary<Analysis, QonverterSettings> qonverterSettings)
        {
            clearData();
            setControlsWhenDatabaseLocked(true);

            var workerThread = new BackgroundWorker()
            {
                WorkerReportsProgress = true,
                WorkerSupportsCancellation = true
            };

            workerThread.DoWork += (s, e) =>
            {
                var qonverter = new Qonverter();
                qonverter.QonversionProgress += progressMonitor.UpdateProgress;
                foreach (var item in qonverterSettings)
                    qonverter.SettingsByAnalysis[(int) item.Key.Id] = item.Value.ToQonverterSettings();

                //qonverter.LogQonversionDetails = true;
                qonverter.Reset(Text);
                qonverter.Qonvert(Text);
            };

            workerThread.RunWorkerCompleted += (s, e) =>
            {
                if (e.Result is Exception)
                {
                    Program.HandleException(e.Result as Exception);
                    setControlsWhenDatabaseLocked(false);
                    return;
                }

                lock (session)
                {
                    var sessionFactory = DataModel.SessionFactoryFactory.CreateSessionFactory(Text, new SessionFactoryConfig { WriteSqlToConsoleOut = true });
                    session = sessionFactory.OpenSession();
                    //session.CreateSQLQuery("PRAGMA temp_store=MEMORY").ExecuteUpdate();
                    _layoutManager.SetSession(session);

                    // delete old filters since they are not valid with different qonverter settings
                    session.CreateSQLQuery("DELETE FROM FilterHistory").ExecuteUpdate();
                    session.Clear();

                    if (basicFilter == null)
                        basicFilter = new DataFilter()
                        {
                            MaximumQValue = 0.02,
                            MinimumDistinctPeptides = 2,
                            MinimumSpectra = 2,
                            MinimumAdditionalPeptides = 1,
                            GeneLevelFiltering = false,
                            DistinctMatchFormat = new DistinctMatchFormat
                            {
                                IsChargeDistinct = true,
                                IsAnalysisDistinct = false,
                                AreModificationsDistinct = true,
                                ModificationMassRoundToNearest = 1.0m
                            }
                        };

                    basicFilterControl.DataFilter = basicFilter;

                    viewFilter = basicFilter;

                    session.Close();
                    sessionFactory.Close();
                }

                progressMonitor = new ProgressMonitor();
                progressMonitor.ProgressUpdate += progressMonitor_ProgressUpdate;
                basicFilterControl = new BasicFilterControl();
                basicFilterControl.BasicFilterChanged += basicFilterControl_BasicFilterChanged;
                basicFilterControl.ShowQonverterSettings += ShowQonverterSettings;
                dataFilterPopup = new Popup(basicFilterControl) { FocusOnOpen = true };
                dataFilterPopup.Closed += dataFilterPopup_Closed;
                new Thread(() => OpenFiles(new List<string> { Text }, null)).Start();
            };

            workerThread.RunWorkerAsync();
        }
Ejemplo n.º 14
0
        void OpenFiles (IList<string> filepaths, TreeNode rootNode = null)
        {
            try
            {
                var xml_filepaths = filepaths.Where(filepath => !filepath.EndsWith(".idpDB"));
                var idpDB_filepaths = filepaths.Where(filepath => filepath.EndsWith(".idpDB"));
                bool openSingleFile = xml_filepaths.Count() + idpDB_filepaths.Count() == 1;

                if (xml_filepaths.Count() + idpDB_filepaths.Count() == 0)
                {
                    if (Program.IsHeadless)
                    {
                        Console.Error.WriteLine("Headless mode must be passed some idpDB files to merge.");
                        Close();
                        return;
                    }
                    else
                        throw new Exception("no filepaths to open");
                }

                if (Program.IsHeadless && xml_filepaths.Any())
                    Program.HandleUserError(new Exception("headless mode only supports merging and filtering idpDB files"));

                // warn if idpDBs already exist
                bool warnOnce = false, skipReconvert = false;
                var skipFiles = new List<string>();
                foreach (string filepath in xml_filepaths)
                {
                    string idpDB_filepath = Path.ChangeExtension(filepath.Replace(".pep.xml", ".pepXML"), ".idpDB");
                    if (File.Exists(idpDB_filepath))
                    {
                        if (!warnOnce && MessageBox.Show("Some of these files have already been converted. Do you want to reconvert them?",
                                                         "Result already converted",
                                                         MessageBoxButtons.YesNo,
                                                         MessageBoxIcon.Exclamation,
                                                         MessageBoxDefaultButton.Button2) != DialogResult.Yes)
                            skipReconvert = true;
                        warnOnce = true;
                        if (skipReconvert)
                            skipFiles.Add(filepath);
                        else
                            File.Delete(idpDB_filepath);
                    }
                }
                xml_filepaths = xml_filepaths.Where(o => !skipFiles.Contains(o));
                idpDB_filepaths = idpDB_filepaths.Union(skipFiles.Select(o => Path.ChangeExtension(o.Replace(".pep.xml", ".pepXML"), ".idpDB")));


                // determine if merged filepath exists and that it's a valid idpDB
                var potentialPaths = filepaths.Select(item =>
                                                      Path.Combine(Path.GetDirectoryName(item) ?? string.Empty,
                                                                   Path.GetFileNameWithoutExtension(item) ??

                                                                   string.Empty) + ".idpDB").ToList();

                // for Mascot files (*.dat), use parseSource() to get the real filename, else save time by just using filename without extension
                var sourceNames = filepaths.Select(o => Path.Combine(Path.GetDirectoryName(o), o.ToLower().EndsWith(".dat") ? Parser.ParseSource(o) : Path.GetFileNameWithoutExtension(o.Replace(".pep.xml", ".pepXML")) + Path.GetExtension(o)));

                string commonFilepath = Util.GetCommonFilename(sourceNames);
                if (!openSingleFile && potentialPaths.Contains(commonFilepath))
                    commonFilepath = commonFilepath.Replace(".idpDB", " (merged).idpDB");
                string mergeTargetFilepath = defaultMergedOutputFilepath ?? commonFilepath;
                if (!openSingleFile && File.Exists(mergeTargetFilepath) && Program.IsHeadless)
                    File.Delete(mergeTargetFilepath);
                else
                {
                    // check that the single idpDB is writable; if not, it needs to be copied
                    if (openSingleFile)
                    {
                        // sanity check that file exists after the path manipulation above
                        if (idpDB_filepaths.Count() == 1 && !File.Exists(mergeTargetFilepath))
                            throw new Exception(String.Format("error in internal path manipulation for opening single idpDB: {0} transformed to {1} which does not exist", sourceNames.First(), mergeTargetFilepath));

                        string oldFilename = mergeTargetFilepath;

                        while (true)
                        {
                            if (canReadWriteInDirectory(Path.GetDirectoryName(mergeTargetFilepath)))
                                break;

                            MessageBox.Show("IDPicker files cannot be opened from a read-only location, pick a writable path to copy it to.");

                            if (!saveFileDialog(ref mergeTargetFilepath))
                                return;
                        }

                        // if location was changed, copy to the new location
                        if (oldFilename != mergeTargetFilepath)
                        {
                            toolStripStatusLabel.Text = "Copying idpDB...";
                            File.Copy(oldFilename, mergeTargetFilepath, true);
                        }
                    }
                    else
                    {
                        // if not headless and MergedOutputFilepath is unset,
                        // then give the user a chance to override the merge target location
                        if (!Program.IsHeadless &&
                            defaultMergedOutputFilepath == null &&
                            !saveFileDialog(ref mergeTargetFilepath, "Choose where to create the merged idpDB"))
                            return;

                        while (true)
                        {
                            if (!canReadWriteInDirectory(Path.GetDirectoryName(mergeTargetFilepath)))
                            {
                                MessageBox.Show("IDPicker files cannot be merged to a read-only location, pick a writable path.");

                                if (Program.IsHeadless || !saveFileDialog(ref mergeTargetFilepath, "Pick a writable path in which to create the merged idpDB"))
                                    return;

                                continue;
                            }

                            // the SaveFileDialog already asked the user to confirm overwriting an existing file
                            if (File.Exists(mergeTargetFilepath))
                                File.Delete(mergeTargetFilepath);

                            break;
                        }
                    }
                }

                // set main window title
                BeginInvoke(new MethodInvoker(() => Text = mergeTargetFilepath));

                //set up delayed messages so non-fatal errors that occur at the end arent lost
                var delayedMessages = new List<string[]>();
                if (xml_filepaths.Count() > 0)
                {
                    importCancelled = false;

                    // loop until the import settings don't result in any fatal errors, or user cancels
                    while (!importCancelled)
                    {
                        Parser parser = new Parser();
                        Invoke(new MethodInvoker(() => parser.ImportSettings += importSettingsHandler));

                        var ilr = new IterationListenerRegistry();

                        var progressForm = new ProgressForm(xml_filepaths, ilr)
                        {
                            Text = "Import Progress",
                            StartPosition = FormStartPosition.CenterParent,
                        };

                        Invoke(new MethodInvoker(() => progressForm.Show(this)));

                        try
                        {
                            parser.Parse(xml_filepaths, ilr);

                            // read log for non-fatal errors
                            //string log = Logger.Reader.ReadToEnd().Trim();
                            //if (log.Length > 0)
                            //    Invoke(new MethodInvoker(() => UserDialog.Show(this, "Log Messages", new TextBox {Multiline = true, Text = log.Replace("\n", "\r\n"), ReadOnly = true, Size = new Size(800, 600),  ScrollBars = ScrollBars.Both}, MessageBoxButtons.OK)));

                            break; // no fatal errors, break the loop
                        }
                        catch (Exception ex)
                        {
                            if (ex.Message.Contains("no peptides found mapping to a decoy protein") ||
                                ex.Message.Contains("peptides did not map to the database") ||
                                ex.Message.Contains("duplicate protein id"))
                                Program.HandleUserError(ex);
                            else
                                throw;
                        }
                        finally
                        {
                            importCancelled |= progressForm.Cancelled;
                            Invoke(new MethodInvoker(() => progressForm.Close()));
                        }
                    }

                    if (importCancelled)
                        return;

                    idpDB_filepaths = idpDB_filepaths.Union(xml_filepaths.Select(o => Path.ChangeExtension(o.Replace(".pep.xml", ".pepXML"), ".idpDB")));
                }

                if (idpDB_filepaths.Count() > 1)
                {
                    var merger = new MergerWrapper(mergeTargetFilepath, idpDB_filepaths);
                    toolStripStatusLabel.Text = "Merging results...";
                    merger.MergingProgress += progressMonitor.UpdateProgress;
                    merger.Start();

                    idpDB_filepaths = new List<string>() {mergeTargetFilepath};
                }

                // HACK: this needs to be handled more gracefully
                if (!IsHandleCreated)
                    return;

                if (Properties.GUI.Settings.Default.WarnAboutNonFixedDrive && !Util.IsPathOnFixedDrive(mergeTargetFilepath))
                {
                    string oldFilename = mergeTargetFilepath;
                    bool copyLocal = true;
                    Invoke(new MethodInvoker(() =>
                                                 {
                                                     var form = new NonFixedDriveWarningForm();
                                                     if (form.ShowDialog(this) == DialogResult.Ignore)
                                                         copyLocal = false;
                                                 }));

                    if (copyLocal)
                    {
                        string newFilename = Path.GetFileName(mergeTargetFilepath);
                        if (!saveFileDialog(ref newFilename, "Pick a local path to copy the idpDB to"))
                            return;

                        toolStripStatusLabel.Text = "Copying idpDB...";
                        File.Copy(oldFilename, newFilename, true);
                        mergeTargetFilepath = newFilename;

                        // set main window title
                        BeginInvoke(new MethodInvoker(() => Text = mergeTargetFilepath));
                    }
                }

                if (!IsHandleCreated)
                    return;

                Util.PrecacheFile(mergeTargetFilepath, progressMonitor.UpdateProgress);

                if (!IsHandleCreated)
                    return;

                BeginInvoke(new MethodInvoker(() =>
                {
                    clearProgress();
                    toolStripStatusLabel.Text = "Upgrading schema and creating session factory...";
                    statusStrip.Refresh();
                }));

                var sessionFactory = DataModel.SessionFactoryFactory.CreateSessionFactory(mergeTargetFilepath, new SessionFactoryConfig { WriteSqlToConsoleOut = true });
                if (logForm != null) logForm.SetSessionFactory(sessionFactory);

                BeginInvoke(new MethodInvoker(() =>
                {
                    // reload qonverter settings because the ids may change after merging
                    toolStripStatusLabel.Text = "Loading qonverter settings...";
                    statusStrip.Refresh();
                    session = sessionFactory.OpenSession();
                    session.DefaultReadOnly = true;

                    session.CreateSQLQuery("PRAGMA temp_store=MEMORY; PRAGMA mmap_size=70368744177664; -- 2^46").ExecuteUpdate();

                    toolStripStatusLabel.Text = "Refreshing group structure...";
                    statusStrip.Refresh();
                    var usedGroups = GroupingControlForm.SetInitialStructure(rootNode, session, defaultApplySourceGroupHierarchy);
                    if (usedGroups != null && usedGroups.Any())
                    {
                        var allGroupsByName = session.Query<SpectrumSourceGroup>().ToDictionary(o => o.Name);
                        var usedGroupsByName = usedGroups.ToDictionary(o => o.Name);

                        // if usedGroupsByName does not contain a key from allGroupsByName, delete the group
                        foreach (var unusedGroup in allGroupsByName.Where(o => !usedGroupsByName.ContainsKey(o.Key)))
                            session.Delete(unusedGroup);
                    }
                    session.Flush();

                    // check for embedded gene metadata;
                    // if it isn't there, ask the user if they want to embed it;
                    // if not, disable gene-related features
                    if (!Program.IsHeadless && !Embedder.HasGeneMetadata(mergeTargetFilepath) && Properties.GUI.Settings.Default.WarnAboutNoGeneMetadata)
                    {
                        bool embedGeneMetadata = true;
                        Invoke(new MethodInvoker(() =>
                                                     {
                                                         var form = new EmbedGeneMetadataWarningForm();
                                                         if (form.ShowDialog(this) == DialogResult.Ignore)
                                                             embedGeneMetadata = false;
                                                     }));

                        if (embedGeneMetadata)
                        {
                            loadRefSeqGeneMetadata(); // will call OpenFiles() after embedding, so return immediately
                            return;
                        }
                    }
                    else
                    {
                        // disable gene-related features
                    }


                    qonverterSettingsByAnalysis = session.Query<QonverterSettings>().ToDictionary(o => session.Get<Analysis>(o.Id));

                    _layoutManager.SetSession(session);

                    //set or save default layout
                    dockPanel.Visible = true;
                    _layoutManager.CurrentLayout = _layoutManager.GetCurrentDefault();

                    //breadCrumbControl.BreadCrumbs.Clear();

                    // pick a default RoundToNearest based on number of distinct modifications
                    decimal roundToNearest = 1m;
                    var distinctModificationFormat = new DistinctMatchFormat();
                    var modMasses = session.CreateQuery("SELECT DISTINCT mod.MonoMassDelta FROM Modification mod").List<double>();
                    for (int i = 4; i > 0; --i)
                    {
                        distinctModificationFormat.ModificationMassRoundToNearest = (decimal) (1.0 / Math.Pow(10, i));
                        if (modMasses.Select(o => distinctModificationFormat.Round(o)).Distinct().Count() < 30)
                        {
                            roundToNearest = distinctModificationFormat.ModificationMassRoundToNearest.Value;
                            break;
                        }
                    }
                    modificationTableForm.RoundToNearest = roundToNearest;

                    basicFilter = DataFilter.LoadFilter(session);

                    // if user has overridden filters from the command-line, make sure to reapply the filter
                    if (!defaultDataFilter.PersistentDataFilter.Equals(defaultDataFilter.OriginalPersistentDataFilter))
                        basicFilter = null;

                    if (basicFilter == null)
                    {
                        basicFilter = new DataFilter(defaultDataFilter);
                        basicFilterControl.DataFilter = basicFilter;

                        viewFilter = basicFilter;

                        ApplyBasicFilter();
                    }
                    else
                    {
                        basicFilterControl.DataFilter = basicFilter;

                        viewFilter = basicFilter;

                        try
                        {
                            // check that the unfiltered tables exist
                            session.CreateSQLQuery("SELECT COUNT(*) FROM UnfilteredProtein").UniqueResult();

                            setData();
                        }
                        catch
                        {
                            ApplyBasicFilter();
                        }
                    }

                    if (TestUILayout)
                    {
                        int i = 0;
                        foreach(var form in dockPanel.Contents)
                        {
                            ++i;
                            form.DockingHandler.DockAreas = (form.DockingHandler.DockAreas | DockAreas.Float);
                            var rect = dockPanel.ClientRectangle;
                            rect.Offset(i * 15, i * 15);
                            rect.Size = new System.Drawing.Size(960, 600);
                            form.DockingHandler.Show(dockPanel, rect);
                        }
                    }

                    toolStripStatusLabel.Text = "Ready";
                    Activate();
                }));

                //show list of delayed non-fatal errors
                if (delayedMessages.Any())
                {
                    var sb = new StringBuilder();
                    foreach (var message in delayedMessages)
                        sb.AppendLine(string.Format("{0}:{1}{2}{1}", message[0], Environment.NewLine, message[1]));
                    var messageString = sb.ToString();

                    ShowExpandedMessageBox(messageString);
                }
            }
            catch (Exception ex)
            {
                Program.HandleException(ex);
            }
        }