/// <summary>
        /// Reads an excel sheet dependent on wheter it is an old or a new version
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="sheetName"></param>
        /// <param name="old"></param>
        /// <returns></returns>
        public static DataSet LoadWorksheetsInDataSheets(string fileName, bool old, string sheetName = "")
        {
            DataTable sheetData = new DataTable();
            DataSet   ds        = new DataSet();

            try
            {
                using (OleDbConnection conn = returnExcelConnection(fileName, old))
                {
                    conn.Open();

                    if (sheetName == "")
                    {
                        // Get the data table containg the schema guid.
                        sheetData = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

                        if (sheetData == null)
                        {
                            return(null);
                        }

                        int      i           = 0;
                        String[] excelSheets = new String[sheetData.Rows.Count];

                        foreach (DataRow row in sheetData.Rows)
                        {
                            excelSheets[i] = sheetData.Rows[i]["TABLE_NAME"].ToString();
                            // retrieve the data using data adapter
                            OleDbDataAdapter sheetAdapter = new OleDbDataAdapter("SELECT * FROM [" + excelSheets[i] + "]", conn);

                            DataTable dt = new DataTable();
                            dt.TableName = excelSheets[i];

                            //Filling a data sheet
                            sheetAdapter.Fill(dt);
                            //Adding the data sheet to the collection
                            ds.Tables.Add(dt);
                            i++;
                        }
                    }
                    else
                    {
                        // retrieve the data using data adapter
                        OleDbDataAdapter sheetAdapter = new OleDbDataAdapter("select * from [" + sheetName + "]", conn);
                        //Filling a data sheet
                        sheetAdapter.Fill(sheetData);
                        //Adding the data sheet to the collection
                        ds.Tables.Add(sheetData);
                    }
                }
            }
            catch (Exception e)
            {
                MessageBox.ShowError(UserMessageValueConverter.ConvertBack(1));

                return(null);
            }

            return(ds);
        }
Exemple #2
0
        /// <summary>
        /// Checking the uniqueness of the name in the database
        /// </summary>
        public void CheckUniqueness()
        {
            int count;

            try
            {
                using (var db = new ApirsRepository <tblBasin>())
                {
                    count = db.GetModelByExpression(rs => rs.basName == SelectedBasin.basName &&
                                                    rs.basIdPk != SelectedBasin.basIdPk).Count();

                    if (count == 0)
                    {
                        return;
                    }

                    char a = 'A';

                    while (count > 0)
                    {
                        SelectedBasin.basName = SelectedBasin.basName + a.ToString();

                        count = db.GetModelByExpression(rs => rs.basName == SelectedBasin.basName).Count();
                        a++;
                    }

                    ((ShellViewModel)IoC.Get <IShell>()).ShowInformation("The name was already in use. We provided a valid alternative for it:" + Environment.NewLine
                                                                         + SelectedBasin.basName);
                }
            }
            catch (Exception e)
            {
                _events.PublishOnUIThreadAsync(new MessageBoxMessage(UserMessageValueConverter.ConvertBack(1), "", MessageBoxViewType.Error, MessageBoxViewButton.Ok));;
            }
        }
        /// <summary>
        /// Checking the uniqueness of the name in the database
        /// </summary>
        public void CheckUniqueness()
        {
            int count;

            try
            {
                using (var db = new ApirsRepository <tblUnionLithostratigraphy>())
                {
                    if (SelectedLithostratigraphy.Id == 0)
                    {
                        count = db.GetModelByExpression(x => x.grName == SelectedLithostratigraphy.grName).Count();
                    }
                    else
                    {
                        count = db.GetModelByExpression(x => x.grName == SelectedLithostratigraphy.grName && x.ID != SelectedLithostratigraphy.Id).Count();
                    }

                    if (count == 0)
                    {
                        return;
                    }

                    ((ShellViewModel)IoC.Get <IShell>()).ShowInformation("The name was already in use. Please provide another name.");
                }
            }
            catch (Exception e)
            {
                _events.PublishOnUIThreadAsync(new MessageBoxMessage(UserMessageValueConverter.ConvertBack(1), "", MessageBoxViewType.Error, MessageBoxViewButton.Ok));;
            }
        }
        ///Event that gets fired if the filter text was changed
        private void OnTextFilterChanged()
        {
            if (TextFilter == "")
            {
                Lithostratigraphies = new BindableCollection <LithostratigraphyUnion>(this.allLithostratigraphies.Where(x => x.Hierarchy == Hierarchy.ToString()).ToList());
            }

            if (Lithostratigraphies.Count == 0)
            {
                return;
            }

            BackgroundWorker bw = new BackgroundWorker();

            bw.DoWork += ((sender1, args) =>
            {
                new DispatchService().Invoke(
                    () =>
                {
                    if (cts != null)
                    {
                        cts.Cancel();
                        cts = null;
                    }
                    cts = new CancellationTokenSource();

                    //Filtering data based on the selection
                    try
                    {
                        //Filtering outcrops
                        Lithostratigraphies = new BindableCollection <LithostratigraphyUnion>(CollectionHelper.Filter <LithostratigraphyUnion>(allLithostratigraphies, TextFilter).Where(x => x.Hierarchy == hierarchy));
                    }
                    catch (Exception e)
                    {
                        _events.PublishOnUIThreadAsync(new MessageBoxMessage(UserMessageValueConverter.ConvertBack(1), "", MessageBoxViewType.Error, MessageBoxViewButton.Ok));;
                    }
                });
            });

            bw.RunWorkerCompleted += ((sender1, args) =>
            {
                if (args.Error != null) // if an exception occurred during DoWork,
                {
                    ((ShellViewModel)IoC.Get <IShell>()).ShowInformation(args.Error.ToString());
                }
            });

            bw.RunWorkerAsync(); // start the background worker
        }
Exemple #5
0
        //Adding a default lithostratigraphic unit
        public void AddLithostratigraphicUnit()
        {
            try
            {
                if (!DataValidation.CheckPrerequisites(CRUD.AddToObject, SelectedBasin, (int)SelectedBasin.basUserIdFk, SelectedBasin.basIdPk))
                {
                    return;
                }
            }
            catch
            {
                return;
            }

            //Only accessible if current user uploaded the object
            try
            {
                if (SelectedBasin == null || SelectedBasin.basUserIdFk != (int)((ShellViewModel)IoC.Get <IShell>()).UserId)
                {
                    ((ShellViewModel)IoC.Get <IShell>()).ShowInformation("Only the uploader can make changes to the object. Please contact him via message service.");
                    return;
                }
            }
            catch
            {
                return;
            }

            try
            {
                using (var db = new ApirsRepository <tblBasinLithoUnit>())
                {
                    db.InsertModel(new tblBasinLithoUnit()
                    {
                        basIdFk = SelectedBasin.basIdPk, lithID = 55
                    });
                    db.Save();
                    BasLithostrat = new BindableCollection <tblBasinLithoUnit>((db.GetModelByExpression(x => x.basIdFk == SelectedBasin.basIdPk).OrderBy(x => x.baslitIdPk).ToList()));
                }
            }
            catch
            {
                _events.PublishOnUIThreadAsync(new MessageBoxMessage(UserMessageValueConverter.ConvertBack(1), "", MessageBoxViewType.Error, MessageBoxViewButton.Ok));;
            }
            finally
            {
                Refresh();
            }
        }
        /// <summary>
        /// Dynamically filtering the Persons
        /// </summary>
        /// <param name="value"></param>
        private void OnFilterTextChanged()
        {
            if (TextFilter == "")
            {
                FilteredPersons = new BindableCollection <tblPerson>((Persons).ToList());
            }

            if (FilteredPersons.Count == 0)
            {
                return;
            }

            BackgroundWorker bw = new BackgroundWorker();

            bw.DoWork += ((sender1, args) =>
            {
                new DispatchService().Invoke(
                    () =>
                {
                    if (cts != null)
                    {
                        cts.Cancel();
                        cts = null;
                    }
                    cts = new CancellationTokenSource();

                    try
                    {
                        FilteredPersons = new BindableCollection <tblPerson>(CollectionHelper.Filter <tblPerson>(Persons, TextFilter));
                    }
                    catch (Exception e)
                    {
                        _events.PublishOnUIThreadAsync(new MessageBoxMessage(UserMessageValueConverter.ConvertBack(1), "", MessageBoxViewType.Error, MessageBoxViewButton.Ok));;
                    }
                });
            });

            bw.RunWorkerCompleted += ((sender1, args) =>
            {
                if (args.Error != null)  // if an exception occurred during DoWork,
                {
                    ((ShellViewModel)IoC.Get <IShell>()).ShowInformation(args.Error.ToString());
                }
            });

            bw.RunWorkerAsync(); // start the background worker
        }
Exemple #7
0
        // Commit changes from the new rock sample form
        // or edits made to the existing rock sample form.
        public void Update()
        {
            if (!(bool)((ShellViewModel)IoC.Get <IShell>()).LocalMode)
            {
                if (!DataValidation.CheckPrerequisites(CRUD.Update, SelectedAnalyticalInstrument, (int)SelectedAnalyticalInstrument.mdUploaderId))
                {
                    return;
                }
            }

            try
            {
                using (var db = new ApirsRepository <tblMeasuringDevice>())
                {
                    if (SelectedAnalyticalInstrument.mdIdPk == 0)
                    {
                        db.InsertModel(SelectedAnalyticalInstrument);
                    }
                    else
                    {
                        db.UpdateModel(SelectedAnalyticalInstrument, SelectedAnalyticalInstrument.mdIdPk);
                    }
                }

                Refresh();
            }
            catch (SqlException ex)
            {
                ((ShellViewModel)IoC.Get <IShell>()).ShowInformation("Please provide valid input parameters");
            }
            catch (Exception e)
            {
                if (e.Message.Contains("EntityValidation"))
                {
                    ((ShellViewModel)IoC.Get <IShell>()).ShowError("Please provide a name for the instrument.");
                }
                else
                {
                    _events.PublishOnUIThreadAsync(new MessageBoxMessage(UserMessageValueConverter.ConvertBack(1), "", MessageBoxViewType.Error, MessageBoxViewButton.Ok));
                };
            }
            finally
            {
            }
        }
Exemple #8
0
        ///Event that gets fired if the filter text was changed
        private void OnTextFilterChanged()
        {
            if (TextFilter == "")
            {
                AnalyticalInstruments = this.allAnalyticalInstruments;
            }

            BackgroundWorker bw = new BackgroundWorker();

            bw.DoWork += ((sender1, args) =>
            {
                new DispatchService().Invoke(
                    () =>
                {
                    if (cts != null)
                    {
                        cts.Cancel();
                        cts = null;
                    }
                    cts = new CancellationTokenSource();

                    //Filtering data based on the selection
                    try
                    {
                        //Filtering
                        AnalyticalInstruments = new BindableCollection <tblMeasuringDevice>(CollectionHelper.Filter <tblMeasuringDevice>(allAnalyticalInstruments, TextFilter).ToList());
                    }
                    catch (Exception e)
                    {
                        _events.PublishOnUIThreadAsync(new MessageBoxMessage(UserMessageValueConverter.ConvertBack(1), "", MessageBoxViewType.Error, MessageBoxViewButton.Ok));;
                    }
                });
            });

            bw.RunWorkerCompleted += ((sender1, args) =>
            {
                if (args.Error != null)  // if an exception occurred during DoWork,
                {
                    ((ShellViewModel)IoC.Get <IShell>()).ShowError("An unexpeced error occured.");
                }
            });

            bw.RunWorkerAsync(); // start the background worker
        }
 public void Update()
 {
     using (var db = new ApirsRepository <tblOutcrop>())
     {
         try
         {
             if (SelectedOutcrop.outIdPk == 0)
             {
                 try
                 {
                     db.InsertModel(SelectedOutcrop);
                     db.Save();
                 }
                 catch
                 {
                     ((ShellViewModel)IoC.Get <IShell>()).ShowInformation("Object can't be added. Please check every field again.");
                     return;
                 }
             }
             else
             {
                 tblOutcrop result = db.GetModelById(SelectedOutcrop.outIdPk);
                 if (result != null)
                 {
                     db.UpdateModel(SelectedOutcrop, SelectedOutcrop.outIdPk);
                 }
             }
         }
         catch (SqlException ex)
         {
             ((ShellViewModel)IoC.Get <IShell>()).ShowInformation("Please provide valid input parameters");
         }
         catch (Exception e)
         {
             _events.PublishOnUIThreadAsync(new MessageBoxMessage(UserMessageValueConverter.ConvertBack(1), "", MessageBoxViewType.Error, MessageBoxViewButton.Ok));;
         }
         finally
         {
         }
     }
 }
Exemple #10
0
        private void MenuItem_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog saveFileDialog1 = new SaveFileDialog();

            saveFileDialog1.Filter           = "PNG (*.png)|*.png|BMP (*.bmp)|*.bmp|EMF (*.emf)|*.emf|PDF (*.pdf)|*.pdf";
            saveFileDialog1.RestoreDirectory = true;

            saveFileDialog1.ShowDialog();

            if (saveFileDialog1.FileName != "")
            {
                //Getting the extension
                var ext = saveFileDialog1.FileName.Substring(saveFileDialog1.FileName.LastIndexOf(".")).ToLower();

                try
                {
                    //Getting the extension
                    var ext1 = saveFileDialog1.FileName.Substring(saveFileDialog1.FileName.LastIndexOf(".")).ToLower();

                    switch (ext1.ToString())
                    {
                    case ".png":
                        //Downloading to the specific folder
                        ImageCapturer.SaveToPng((FrameworkElement)this, saveFileDialog1.FileName);
                        break;

                    case ".bmp":
                        ImageCapturer.SaveToBmp((FrameworkElement)this, saveFileDialog1.FileName);
                        break;

                    case ".emf":
                        ImageCapturer.SaveToEmf(textCanvas, saveFileDialog1.FileName);
                        break;
                    }
                }
                catch
                {
                    ((ShellViewModel)IoC.Get <IShell>()).ShowError(UserMessageValueConverter.ConvertBack(1));
                }
            }
        }
Exemple #11
0
        /// <summary>
        /// Reading a CSV file into a data table
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="isFirstRowHeader"></param>
        /// <returns></returns>
        public static DataTable CsvToDataTable(string filePath, bool isFirstRowHeader)
        {
            try
            {
                string fileName = Path.GetFileName(filePath);

                string sql = @"SELECT * FROM [" + fileName + "]";

                string      CultureName = Thread.CurrentThread.CurrentCulture.Name;
                CultureInfo ci          = new CultureInfo(CultureName);
                if (ci.NumberFormat.NumberDecimalSeparator != ".")
                {
                    // Forcing use of decimal separator for numerical values
                    ci.NumberFormat.NumberDecimalSeparator = ".";
                    ci.NumberFormat.NumberGroupSeparator   = ",";
                    Thread.CurrentThread.CurrentCulture    = ci;
                }

                using (OleDbConnection conn = returnCsvConnection(filePath, isFirstRowHeader))
                {
                    using (OleDbCommand command = new OleDbCommand(sql, conn))
                        using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
                        {
                            DataTable dataTable = new DataTable();
                            dataTable.Locale = Thread.CurrentThread.CurrentCulture;
                            adapter.Fill(dataTable);
                            return(dataTable);
                        }
                }
            }
            catch (Exception e)
            {
                ((ShellViewModel)IoC.Get <IShell>()).ShowError(UserMessageValueConverter.ConvertBack(1));
                return(null);
            }
        }
        /// <summary>
        /// Uploading a filestream to the server
        /// </summary>
        /// <param name="fileStreamByte"></param>
        /// <returns></returns>
        public static Guid UploadFile(string filePath)
        {
            if (filePath != "")
            {
                //Getting file information
                FileInfo   fi = new FileInfo(filePath);
                FileStream fs;

                try
                {
                    //Implementing a new filestream
                    fs = new FileStream(fi.FullName, FileMode.Open, FileAccess.Read);
                }
                catch
                {
                    MessageBox.ShowError("File is being used by another process.");
                    return(new Guid());
                }

                //Transfering filestream into binary format
                BinaryReader rdr      = new BinaryReader(fs);
                byte[]       fileData = rdr.ReadBytes((int)fs.Length);

                //Closing filestream
                rdr.Close();
                fs.Close();

                try
                {
                    //Instantiate database
                    using (ApirsDatabase db = new ApirsDatabase())
                    {
                        //Retrieving file meta data
                        string fileName = fi.Name;
                        string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileName);
                        string extension = fi.Extension;
                        char   charac    = 'a';

                        //Changing File name based on the count of occurences
                        while (db.v_FileStore.Where(x => x.name == fileName).Count() > 0)
                        {
                            fileName = fileNameWithoutExtension + charac + extension;
                            charac++;
                        }

                        //Establishing a sql connection
                        using (SqlConnection SqlConn = new SqlConnection(db.Database.Connection.ConnectionString.ToString()))
                        {
                            SqlCommand spAddFile = new SqlCommand("dbo.spAddFile", SqlConn);
                            //Testing if a connection is established
                            //Normally: if (sv.IsNetworkAvailable() && sv.IsServerConnected("130.83.96.87"))
                            if (ServerInteractionHelper.IsNetworkAvailable())
                            {
                                //Preparing the stored procedure
                                spAddFile.CommandType = CommandType.StoredProcedure;

                                //Adding the parameters
                                spAddFile.Parameters.Add("@pName", SqlDbType.NVarChar, 255).Value = fileName;
                                spAddFile.Parameters.Add("@pFile_Stream", SqlDbType.Image, fileData.Length).Value = fileData;

                                //Opening the connection
                                SqlConn.Open();

                                Guid result = (Guid)spAddFile.ExecuteScalar();

                                SqlConn.Close();

                                db.SaveChanges();

                                return(result);
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    MessageBox.ShowError(UserMessageValueConverter.ConvertBack(1));
                    return(new Guid());
                }
            }

            return(new Guid());
        }
        // Commit changes from the new rock sample form
        // or edits made to the existing rock sample form.
        public void Update()
        {
            try
            {
                if (!DataValidation.CheckPrerequisites(CRUD.Update, Lithostratigraphies, SelectedLithostratigraphy.UploaderId))
                {
                    return;
                }
                else if (SelectedLithostratigraphy.grName == null)
                {
                    return;
                }
            }
            catch
            {
                return;
            }

            try
            {
                if (SelectedLithostratigraphy.Id == 0)
                {
                    try
                    {
                        SelectedLithostratigraphy.UploaderId = (int)((ShellViewModel)IoC.Get <IShell>()).UserId;
                        new ApirsRepository <tblUnionLithostratigraphy>().InsertModel(new tblUnionLithostratigraphy()
                        {
                            grName = SelectedLithostratigraphy.grName,
                            unionLithUploaderIdFk = SelectedLithostratigraphy.UploaderId,
                            chronostratNameFk     = SelectedLithostratigraphy.Chronostratigraphy
                        });

                        switch (SelectedLithostratigraphy.Hierarchy)
                        {
                        case "Group":
                            new ApirsRepository <tblGroup>().InsertModel(new tblGroup()
                            {
                                grName                       = SelectedLithostratigraphy.grName,
                                grBaseBoundary               = SelectedLithostratigraphy.BaseBoundary,
                                grTopBoundary                = SelectedLithostratigraphy.TopBoundary,
                                grCountries                  = SelectedLithostratigraphy.Countries,
                                grDateDocumentation          = SelectedLithostratigraphy.DateDocumentation,
                                grLiterature                 = SelectedLithostratigraphy.Literature,
                                grLithologicDescriptionShort = SelectedLithostratigraphy.LithologicDescriptionShort,
                                grMaxThickness               = SelectedLithostratigraphy.MaxThickness,
                                grMeanThickness              = SelectedLithostratigraphy.MeanThickness,
                                grNotes                      = SelectedLithostratigraphy.Notes,
                                grStates                     = SelectedLithostratigraphy.States,
                                grTypeLocality               = SelectedLithostratigraphy.TypeLocality
                            });
                            break;

                        case "Subgroup":
                            new ApirsRepository <tblSubgroup>().InsertModel(new tblSubgroup()
                            {
                                sgName                       = SelectedLithostratigraphy.grName,
                                sggrIdFk                     = new ApirsRepository <tblGroup>().GetModelByExpression(strat => strat.grName == SelectedLithostratigraphy.ParentName).Select(strat => strat.grIdPk).FirstOrDefault(),
                                sgBaseBoundary               = SelectedLithostratigraphy.BaseBoundary,
                                sgTypeLocality               = SelectedLithostratigraphy.TypeLocality,
                                sgTopBoundary                = SelectedLithostratigraphy.TopBoundary,
                                sgCountries                  = SelectedLithostratigraphy.Countries,
                                sgDateOfDocumentation        = SelectedLithostratigraphy.DateDocumentation,
                                sgLiterature                 = SelectedLithostratigraphy.Literature,
                                sgLithologicDescriptionShort = SelectedLithostratigraphy.LithologicDescriptionShort,
                                sgMaxThickness               = SelectedLithostratigraphy.MaxThickness,
                                sgMeanThickness              = SelectedLithostratigraphy.MeanThickness,
                                sgNotes                      = SelectedLithostratigraphy.Notes,
                                sgStates                     = SelectedLithostratigraphy.States,
                                sgDescription                = SelectedLithostratigraphy.TypeLocality
                            });
                            break;

                        case "Formation":
                            new ApirsRepository <tblFormation>().InsertModel(new tblFormation()
                            {
                                fmName                = SelectedLithostratigraphy.grName,
                                fmsgIdFk              = new ApirsRepository <tblSubgroup>().GetModelByExpression(strat => strat.sgName == SelectedLithostratigraphy.ParentName).Select(strat => strat.sgIdPk).FirstOrDefault(),
                                fmBaseBoundary        = SelectedLithostratigraphy.BaseBoundary,
                                fmTopBoundary         = SelectedLithostratigraphy.TopBoundary,
                                fmCountries           = SelectedLithostratigraphy.Countries,
                                fmLiterature          = SelectedLithostratigraphy.Literature,
                                fmDescription         = SelectedLithostratigraphy.LithologicDescriptionShort,
                                fmMaxThickness        = SelectedLithostratigraphy.MaxThickness,
                                fmMeanThickness       = SelectedLithostratigraphy.MeanThickness,
                                fmNotes               = SelectedLithostratigraphy.Notes,
                                fmStates              = SelectedLithostratigraphy.States,
                                fmDateOfDocumentation = DateTime.Now,
                                fmTypeLocality        = SelectedLithostratigraphy.TypeLocality
                            });
                            break;

                        case "Subformation":
                            new ApirsRepository <tblSubformation>().InsertModel(new tblSubformation()
                            {
                                sfName                = SelectedLithostratigraphy.grName,
                                sffmId                = new ApirsRepository <tblFormation>().GetModelByExpression(strat => strat.fmName == SelectedLithostratigraphy.ParentName).Select(strat => strat.fmIdPk).FirstOrDefault(),
                                sfBaseBoundary        = SelectedLithostratigraphy.BaseBoundary,
                                sfTopBoundary         = SelectedLithostratigraphy.TopBoundary,
                                sfLiterature          = SelectedLithostratigraphy.Literature,
                                sfDescription         = SelectedLithostratigraphy.LithologicDescriptionShort,
                                sfMaxThickness        = SelectedLithostratigraphy.MaxThickness,
                                sfMeanThickness       = SelectedLithostratigraphy.MeanThickness,
                                sfNotes               = SelectedLithostratigraphy.Notes,
                                sfCountries           = SelectedLithostratigraphy.Countries,
                                sfDateOfDocumentation = DateTime.Now,
                                sfTypeLocality        = SelectedLithostratigraphy.TypeLocality
                            });
                            break;
                        }
                    }
                    catch (Exception e)
                    {
                        if (!e.InnerException.ToString().Contains("entries"))
                        {
                            ((ShellViewModel)IoC.Get <IShell>()).ShowInformation("Lithostratigraphic unit can't be added. Please check every field again.");
                        }
                    }
                }
                else
                {
                    string tempName = "";
                    tblUnionLithostratigraphy result0 = new ApirsRepository <tblUnionLithostratigraphy>().GetModelByExpression(b => b.ID == SelectedLithostratigraphy.Id).First();
                    if (result0 != null)
                    {
                        tempName = result0.grName;
                        var a = new ApirsRepository <tblUnionLithostratigraphy>().GetModelById(SelectedLithostratigraphy.Id);
                        a.ID     = SelectedLithostratigraphy.Id;
                        a.grName = SelectedLithostratigraphy.grName;
                        a.unionLithUploaderIdFk = SelectedLithostratigraphy.UploaderId;
                        a.chronostratNameFk     = SelectedLithostratigraphy.Chronostratigraphy;

                        new ApirsRepository <tblUnionLithostratigraphy>().UpdateModel(a, a.ID);
                    }

                    switch (SelectedLithostratigraphy.Hierarchy)
                    {
                    case "Group":
                        using (var db1 = new ApirsRepository <tblGroup>())
                        {
                            tblGroup result = db1.GetModelByExpression(b => b.grName == tempName).First();
                            if (result != null)
                            {
                                result.grName                       = SelectedLithostratigraphy.grName;
                                result.grBaseBoundary               = SelectedLithostratigraphy.BaseBoundary;
                                result.grTopBoundary                = SelectedLithostratigraphy.TopBoundary;
                                result.grCountries                  = SelectedLithostratigraphy.Countries;
                                result.grDateDocumentation          = SelectedLithostratigraphy.DateDocumentation;
                                result.grLiterature                 = SelectedLithostratigraphy.Literature;
                                result.grLithologicDescriptionShort = SelectedLithostratigraphy.LithologicDescriptionShort;
                                result.grMaxThickness               = SelectedLithostratigraphy.MaxThickness;
                                result.grMeanThickness              = SelectedLithostratigraphy.MeanThickness;
                                result.grNotes                      = SelectedLithostratigraphy.Notes;
                                result.grStates                     = SelectedLithostratigraphy.States;
                                result.grTypeLocality               = SelectedLithostratigraphy.TypeLocality;
                            }
                            ;

                            db1.UpdateModel(result, result.grIdPk);
                        }

                        break;

                    case "Subgroup":
                        using (var db1 = new ApirsRepository <tblSubgroup>())
                        {
                            tblSubgroup result1 = db1.GetModelByExpression(b => b.sgName == tempName).First();
                            if (result1 != null)
                            {
                                result1.sgName                       = SelectedLithostratigraphy.grName;
                                result1.sgBaseBoundary               = SelectedLithostratigraphy.BaseBoundary;
                                result1.sgTopBoundary                = SelectedLithostratigraphy.TopBoundary;
                                result1.sgTypeLocality               = SelectedLithostratigraphy.TypeLocality;
                                result1.sgCountries                  = SelectedLithostratigraphy.Countries;
                                result1.sgDateOfDocumentation        = SelectedLithostratigraphy.DateDocumentation;
                                result1.sgLiterature                 = SelectedLithostratigraphy.Literature;
                                result1.sgLithologicDescriptionShort = SelectedLithostratigraphy.LithologicDescriptionShort;
                                result1.sgMaxThickness               = SelectedLithostratigraphy.MaxThickness;
                                result1.sgMeanThickness              = SelectedLithostratigraphy.MeanThickness;
                                result1.sgNotes                      = SelectedLithostratigraphy.Notes;
                                result1.sgStates                     = SelectedLithostratigraphy.States;
                                result1.sgDescription                = SelectedLithostratigraphy.TypeLocality;

                                db1.UpdateModel(result1, result1.sgIdPk);
                            }
                        }
                        break;

                    case "Formation":
                        using (var db1 = new ApirsRepository <tblFormation>())
                        {
                            tblFormation result2 = db1.GetModelByExpression(b => b.fmName == tempName).First();
                            if (result2 != null)
                            {
                                result2.fmName                = SelectedLithostratigraphy.grName;
                                result2.fmBaseBoundary        = SelectedLithostratigraphy.BaseBoundary;
                                result2.fmTopBoundary         = SelectedLithostratigraphy.TopBoundary;
                                result2.fmCountries           = SelectedLithostratigraphy.Countries;
                                result2.fmDateOfDocumentation = SelectedLithostratigraphy.DateDocumentation;
                                result2.fmLiterature          = SelectedLithostratigraphy.Literature;
                                result2.fmDescription         = SelectedLithostratigraphy.LithologicDescriptionShort;
                                result2.fmMaxThickness        = SelectedLithostratigraphy.MaxThickness;
                                result2.fmMeanThickness       = SelectedLithostratigraphy.MeanThickness;
                                result2.fmNotes               = SelectedLithostratigraphy.Notes;
                                result2.fmStates              = SelectedLithostratigraphy.States;
                                result2.fmTypeLocality        = SelectedLithostratigraphy.TypeLocality;

                                db1.UpdateModel(result2, result2.fmIdPk);
                            }
                        }

                        break;

                    case "Subformation":
                        using (var db1 = new ApirsRepository <tblSubformation>())
                        {
                            tblSubformation result3 = db1.GetModelByExpression(b => b.sfName == tempName).First();
                            if (result3 != null)
                            {
                                result3.sfName                = SelectedLithostratigraphy.grName;
                                result3.sfBaseBoundary        = SelectedLithostratigraphy.BaseBoundary;
                                result3.sfTopBoundary         = SelectedLithostratigraphy.TopBoundary;
                                result3.sfLiterature          = SelectedLithostratigraphy.Literature;
                                result3.sfDescription         = SelectedLithostratigraphy.LithologicDescriptionShort;
                                result3.sfMaxThickness        = SelectedLithostratigraphy.MaxThickness;
                                result3.sfMeanThickness       = SelectedLithostratigraphy.MeanThickness;
                                result3.sfNotes               = SelectedLithostratigraphy.Notes;
                                result3.sfCountries           = SelectedLithostratigraphy.Countries;
                                result3.sfDateOfDocumentation = DateTime.Now;
                                result3.sfTypeLocality        = SelectedLithostratigraphy.TypeLocality;

                                db1.UpdateModel(result3, result3.sfIdPk);
                            }
                        }
                        break;
                    }
                }
            }
            catch (SqlException ex)
            {
                ((ShellViewModel)IoC.Get <IShell>()).ShowInformation("Please provide valid input parameters");
            }
            catch (Exception e)
            {
                if (e.Message.Contains("Sequence"))
                {
                    return;
                }

                _events.PublishOnUIThreadAsync(new MessageBoxMessage(UserMessageValueConverter.ConvertBack(1), "", MessageBoxViewType.Error, MessageBoxViewButton.Ok));;
            }
        }
        /// <summary>
        /// Deleting the currently viewed rock sample
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void Delete()
        {
            try
            {
                if (!DataValidation.CheckPrerequisites(CRUD.Delete, SelectedLithostratigraphy, SelectedLithostratigraphy.UploaderId))
                {
                    return;
                }
            }
            catch
            {
                return;
            }


            if (((ShellViewModel)IoC.Get <IShell>()).ShowQuestion("Are you sure to delete the record?",
                                                                  "You won't be able to retrieve the related measurement data after deleting this sample.") == MessageBoxViewResult.No)
            {
                return;
            }
            try
            {
                switch (SelectedLithostratigraphy.Hierarchy)
                {
                case "Group":
                    tblGroup result = new ApirsRepository <tblGroup>().GetModelByExpression(b => b.grName == SelectedLithostratigraphy.grName).First();

                    if (result != null)
                    {
                        new ApirsRepository <tblGroup>().DeleteModelById(result.grIdPk);
                    }
                    break;

                case "Subgroup":
                    tblSubgroup result1 = new ApirsRepository <tblSubgroup>().GetModelByExpression(b => b.sgName == SelectedLithostratigraphy.grName).First();

                    if (result1 != null)
                    {
                        new ApirsRepository <tblSubgroup>().DeleteModelById(result1.sgIdPk);
                    }
                    break;

                case "Formation":
                    tblFormation result2 = new ApirsRepository <tblFormation>().GetModelByExpression(b => b.fmName == SelectedLithostratigraphy.grName).First();

                    if (result2 != null)
                    {
                        new ApirsRepository <tblFormation>().DeleteModelById(result2.fmIdPk);
                    }
                    break;

                case "Subformation":
                    tblSubformation result3 = new ApirsRepository <tblSubformation>().GetModelByExpression(b => b.sfName == SelectedLithostratigraphy.grName).First();

                    if (result3 != null)
                    {
                        new ApirsRepository <tblSubformation>().DeleteModelById(result3.sfIdPk);
                    }
                    break;
                }

                tblUnionLithostratigraphy result4 = new ApirsRepository <tblUnionLithostratigraphy>().GetModelByExpression(b => b.grName == SelectedLithostratigraphy.grName).First();

                if (result4 != null)
                {
                    new ApirsRepository <tblUnionLithostratigraphy>().DeleteModelById(result4.ID);
                }

                Lithostratigraphies.Remove(SelectedLithostratigraphy);
                allLithostratigraphies.Remove(SelectedLithostratigraphy);
                SelectedLithostratigraphy = Lithostratigraphies.FirstOrDefault();
            }
            catch (Exception ex)
            {
                _events.PublishOnUIThreadAsync(new MessageBoxMessage(UserMessageValueConverter.ConvertBack(1), "", MessageBoxViewType.Error, MessageBoxViewButton.Ok));;
            }
            finally
            {
            }
        }
        /// <summary>
        /// Attempts to log the user in
        /// </summary>
        /// <param name="parameter">The SecureString passed in from the view for the users password</param>
        /// <returns></returns>
        public async void Login(PasswordBox parameter)
        {
            CommandHelper ch = new CommandHelper();

            await ch.RunBackgroundWorkerWithFlagHelperAsync(() => IsLoginRunning, async() =>
            {
                try
                {
                    //var pwBox = (PasswordBox)parameter;
                    string username = this.Email ?? "";

                    using (var db = new ApirsDatabase())
                    {
                        var paramLoginName = new SqlParameter
                        {
                            ParameterName = "pLoginName",
                            Value         = username,
                            Direction     = ParameterDirection.Input
                        };

                        var paramPass = new SqlParameter
                        {
                            ParameterName = "pPassword",
                            Value         = parameter.Password,
                            Direction     = ParameterDirection.Input
                        };

                        var paramResponse = new SqlParameter
                        {
                            ParameterName = "responseMessage",
                            Size          = 250,
                            SqlDbType     = SqlDbType.NVarChar,
                            Direction     = ParameterDirection.Output
                        };


                        string par = db.Database.SqlQuery <string>("exec dbo.spUserLogin @pLoginName, @pPassword, @responseMessage", paramLoginName, paramPass, paramResponse).First();

                        //Forward the user to the home view or denying the login based on the response of the server
                        switch (par)
                        {
                        case "Invalid login":
                        case "Incorrect password":
                            _events.PublishOnUIThreadAsync(new MessageBoxMessage("Wrong password. Please try it again", "", MessageBoxViewType.Information, MessageBoxViewButton.Ok));
                            break;

                        case "User successfully logged in":
                            //Get the actual user id and set it as a property in the shellview
                            tblPerson result = (from p in db.tblPersons
                                                where p.persUserName == username.ToString()
                                                select p).First();
                            _events.PublishOnUIThreadAsync(new ChangeUserMessage(Convert.ToInt32(result.persIdPk), result.persFullName));
                            //Changing the viewmodel to the homeview
                            _events.PublishOnUIThreadAsync(new ChangeViewModelMessage("HomeView"));
                            break;

                        default:
                            break;
                        }
                    }

                    return;
                }
                catch (Exception e)
                {
                    _events.PublishOnUIThreadAsync(new MessageBoxMessage(UserMessageValueConverter.ConvertBack(1), "", MessageBoxViewType.Error, MessageBoxViewButton.Ok));
                }
            });
        }