Loading data via Excel to SQL












0















I am loading data from a excel file to sql, I added comments to the code to further clarify what each lines purpose is.



    private void Events_Click(object sender, RoutedEventArgs e)
{
//open dialog for file select of event file
string filePath = OpenFileDialogParameters.FileDialog("", "", "", 2);
//if file select is not null
if (filePath != null)
{
//catch errors in this block
try
{
//begin a transaction
using (var transaction = Context.Database.BeginTransaction())
{
//parse file into dataset
Events_DataSet = ReadExcel.OpenExcel(filePath);
int Drivecode = 0;
DBEVENT Events = //get all rows in table 0
(from x in Events_DataSet.Tables[0].Select()
//last row must be drivecode, test to ensure it is not empty string
where x.ItemArray[x.ItemArray.Length - 1].ToString() != string.Empty
let dc = Drivecode = int.Parse(x.ItemArray[x.ItemArray.Length - 1].ToString())
//join Session Drive status on drivecode
join sds in Context.SDS on dc.ToString() equals sds.DriveCode into hasSD
//ensure there is a drive loaded for this file and that the file hasnt already been processed
where hasSD.Count() == 1 & hasSD.First().Events == false
//select all items that fit these parameters to a array
select new DBEVENT(x)).ToArray();
//if duplicates found fail with error message
if (Context.DBEVENTS.Where(x => x.קוד_נסיעה == Drivecode).Count() != 0)
{

StatusBox.Text += "קובץ אירועי נסיעה כבר נטען למסד הנתונים עבור " + Environment.NewLine + "נסיעה " + Events[0].קוד_נסיעה + Environment.NewLine;
button2s.Fill = Brushes.IndianRed;
return;
}
else
{
//ensure there are events to add
if (Events.Count() > 0)
{
//add each event to the table
foreach (var Event in Events)
{
Context.DBEVENTS.Add(Event);
}
//start inner try catch to handle saving
try
{
//Save Data
Context.SaveChanges();
//After Save add Completion to SessionDriveTable
var sdcompletion = (from sda in Context.SDS
where Drivecode.ToString() == sda.DriveCode
where sda != null
select sda).First().Events = true;
//save completion
Context.SaveChanges();
//commit
transaction.Commit();
button2s.Fill = Brushes.LawnGreen;
}
catch (Exception ex)
{
//rollback changes
transaction.Rollback();
//throw this error to the outer exception handler
//to ensure the entities are removed from the change tracker
throw ex;
}
}
//no events created could be drive doesn't exist or events already added
else
{
button2s.Fill = Brushes.IndianRed;
DataRow dr = Events_DataSet.Tables[0].Rows[1];
var DriveCode = dr[dr.ItemArray.Count() - 1].ToString();
StatusBox.Text += "מספר הנסיעה " + DriveCode + " לא קיים במסד הנתונים." + Environment.NewLine + "אנא השלם פרטי נסיעה טרם טעינת קובץ." + Environment.NewLine;
return;
}
}
}
}
//main exception handler
//rolls back any tracked changes in entity framework
//unwraps exceptions to the most relevant inner exception
catch (Exception ex)
{
ExceptionRollback();
while (ex.InnerException != null)
{
ex = ex.InnerException;
}
button2s.Fill = Brushes.IndianRed;
StatusBox.Text += ex.Message + Environment.NewLine;
}
}
}


Exception roll back simply removes any items added modified deleted using entity framework change tracker.



    public void ExceptionRollback()
{
if (Context.ChangeTracker.HasChanges())
{
foreach (var entry in Context.ChangeTracker.Entries()
.Where(entry => entry.State == EntityState.Added ||
entry.State == EntityState.Modified ||
entry.State == EntityState.Deleted))
{
entry.State = EntityState.Detached;
}
}
}


Really looking for ideas on how to abstract the functionality away from the UI code...









share



























    0















    I am loading data from a excel file to sql, I added comments to the code to further clarify what each lines purpose is.



        private void Events_Click(object sender, RoutedEventArgs e)
    {
    //open dialog for file select of event file
    string filePath = OpenFileDialogParameters.FileDialog("", "", "", 2);
    //if file select is not null
    if (filePath != null)
    {
    //catch errors in this block
    try
    {
    //begin a transaction
    using (var transaction = Context.Database.BeginTransaction())
    {
    //parse file into dataset
    Events_DataSet = ReadExcel.OpenExcel(filePath);
    int Drivecode = 0;
    DBEVENT Events = //get all rows in table 0
    (from x in Events_DataSet.Tables[0].Select()
    //last row must be drivecode, test to ensure it is not empty string
    where x.ItemArray[x.ItemArray.Length - 1].ToString() != string.Empty
    let dc = Drivecode = int.Parse(x.ItemArray[x.ItemArray.Length - 1].ToString())
    //join Session Drive status on drivecode
    join sds in Context.SDS on dc.ToString() equals sds.DriveCode into hasSD
    //ensure there is a drive loaded for this file and that the file hasnt already been processed
    where hasSD.Count() == 1 & hasSD.First().Events == false
    //select all items that fit these parameters to a array
    select new DBEVENT(x)).ToArray();
    //if duplicates found fail with error message
    if (Context.DBEVENTS.Where(x => x.קוד_נסיעה == Drivecode).Count() != 0)
    {

    StatusBox.Text += "קובץ אירועי נסיעה כבר נטען למסד הנתונים עבור " + Environment.NewLine + "נסיעה " + Events[0].קוד_נסיעה + Environment.NewLine;
    button2s.Fill = Brushes.IndianRed;
    return;
    }
    else
    {
    //ensure there are events to add
    if (Events.Count() > 0)
    {
    //add each event to the table
    foreach (var Event in Events)
    {
    Context.DBEVENTS.Add(Event);
    }
    //start inner try catch to handle saving
    try
    {
    //Save Data
    Context.SaveChanges();
    //After Save add Completion to SessionDriveTable
    var sdcompletion = (from sda in Context.SDS
    where Drivecode.ToString() == sda.DriveCode
    where sda != null
    select sda).First().Events = true;
    //save completion
    Context.SaveChanges();
    //commit
    transaction.Commit();
    button2s.Fill = Brushes.LawnGreen;
    }
    catch (Exception ex)
    {
    //rollback changes
    transaction.Rollback();
    //throw this error to the outer exception handler
    //to ensure the entities are removed from the change tracker
    throw ex;
    }
    }
    //no events created could be drive doesn't exist or events already added
    else
    {
    button2s.Fill = Brushes.IndianRed;
    DataRow dr = Events_DataSet.Tables[0].Rows[1];
    var DriveCode = dr[dr.ItemArray.Count() - 1].ToString();
    StatusBox.Text += "מספר הנסיעה " + DriveCode + " לא קיים במסד הנתונים." + Environment.NewLine + "אנא השלם פרטי נסיעה טרם טעינת קובץ." + Environment.NewLine;
    return;
    }
    }
    }
    }
    //main exception handler
    //rolls back any tracked changes in entity framework
    //unwraps exceptions to the most relevant inner exception
    catch (Exception ex)
    {
    ExceptionRollback();
    while (ex.InnerException != null)
    {
    ex = ex.InnerException;
    }
    button2s.Fill = Brushes.IndianRed;
    StatusBox.Text += ex.Message + Environment.NewLine;
    }
    }
    }


    Exception roll back simply removes any items added modified deleted using entity framework change tracker.



        public void ExceptionRollback()
    {
    if (Context.ChangeTracker.HasChanges())
    {
    foreach (var entry in Context.ChangeTracker.Entries()
    .Where(entry => entry.State == EntityState.Added ||
    entry.State == EntityState.Modified ||
    entry.State == EntityState.Deleted))
    {
    entry.State = EntityState.Detached;
    }
    }
    }


    Really looking for ideas on how to abstract the functionality away from the UI code...









    share

























      0












      0








      0








      I am loading data from a excel file to sql, I added comments to the code to further clarify what each lines purpose is.



          private void Events_Click(object sender, RoutedEventArgs e)
      {
      //open dialog for file select of event file
      string filePath = OpenFileDialogParameters.FileDialog("", "", "", 2);
      //if file select is not null
      if (filePath != null)
      {
      //catch errors in this block
      try
      {
      //begin a transaction
      using (var transaction = Context.Database.BeginTransaction())
      {
      //parse file into dataset
      Events_DataSet = ReadExcel.OpenExcel(filePath);
      int Drivecode = 0;
      DBEVENT Events = //get all rows in table 0
      (from x in Events_DataSet.Tables[0].Select()
      //last row must be drivecode, test to ensure it is not empty string
      where x.ItemArray[x.ItemArray.Length - 1].ToString() != string.Empty
      let dc = Drivecode = int.Parse(x.ItemArray[x.ItemArray.Length - 1].ToString())
      //join Session Drive status on drivecode
      join sds in Context.SDS on dc.ToString() equals sds.DriveCode into hasSD
      //ensure there is a drive loaded for this file and that the file hasnt already been processed
      where hasSD.Count() == 1 & hasSD.First().Events == false
      //select all items that fit these parameters to a array
      select new DBEVENT(x)).ToArray();
      //if duplicates found fail with error message
      if (Context.DBEVENTS.Where(x => x.קוד_נסיעה == Drivecode).Count() != 0)
      {

      StatusBox.Text += "קובץ אירועי נסיעה כבר נטען למסד הנתונים עבור " + Environment.NewLine + "נסיעה " + Events[0].קוד_נסיעה + Environment.NewLine;
      button2s.Fill = Brushes.IndianRed;
      return;
      }
      else
      {
      //ensure there are events to add
      if (Events.Count() > 0)
      {
      //add each event to the table
      foreach (var Event in Events)
      {
      Context.DBEVENTS.Add(Event);
      }
      //start inner try catch to handle saving
      try
      {
      //Save Data
      Context.SaveChanges();
      //After Save add Completion to SessionDriveTable
      var sdcompletion = (from sda in Context.SDS
      where Drivecode.ToString() == sda.DriveCode
      where sda != null
      select sda).First().Events = true;
      //save completion
      Context.SaveChanges();
      //commit
      transaction.Commit();
      button2s.Fill = Brushes.LawnGreen;
      }
      catch (Exception ex)
      {
      //rollback changes
      transaction.Rollback();
      //throw this error to the outer exception handler
      //to ensure the entities are removed from the change tracker
      throw ex;
      }
      }
      //no events created could be drive doesn't exist or events already added
      else
      {
      button2s.Fill = Brushes.IndianRed;
      DataRow dr = Events_DataSet.Tables[0].Rows[1];
      var DriveCode = dr[dr.ItemArray.Count() - 1].ToString();
      StatusBox.Text += "מספר הנסיעה " + DriveCode + " לא קיים במסד הנתונים." + Environment.NewLine + "אנא השלם פרטי נסיעה טרם טעינת קובץ." + Environment.NewLine;
      return;
      }
      }
      }
      }
      //main exception handler
      //rolls back any tracked changes in entity framework
      //unwraps exceptions to the most relevant inner exception
      catch (Exception ex)
      {
      ExceptionRollback();
      while (ex.InnerException != null)
      {
      ex = ex.InnerException;
      }
      button2s.Fill = Brushes.IndianRed;
      StatusBox.Text += ex.Message + Environment.NewLine;
      }
      }
      }


      Exception roll back simply removes any items added modified deleted using entity framework change tracker.



          public void ExceptionRollback()
      {
      if (Context.ChangeTracker.HasChanges())
      {
      foreach (var entry in Context.ChangeTracker.Entries()
      .Where(entry => entry.State == EntityState.Added ||
      entry.State == EntityState.Modified ||
      entry.State == EntityState.Deleted))
      {
      entry.State = EntityState.Detached;
      }
      }
      }


      Really looking for ideas on how to abstract the functionality away from the UI code...









      share














      I am loading data from a excel file to sql, I added comments to the code to further clarify what each lines purpose is.



          private void Events_Click(object sender, RoutedEventArgs e)
      {
      //open dialog for file select of event file
      string filePath = OpenFileDialogParameters.FileDialog("", "", "", 2);
      //if file select is not null
      if (filePath != null)
      {
      //catch errors in this block
      try
      {
      //begin a transaction
      using (var transaction = Context.Database.BeginTransaction())
      {
      //parse file into dataset
      Events_DataSet = ReadExcel.OpenExcel(filePath);
      int Drivecode = 0;
      DBEVENT Events = //get all rows in table 0
      (from x in Events_DataSet.Tables[0].Select()
      //last row must be drivecode, test to ensure it is not empty string
      where x.ItemArray[x.ItemArray.Length - 1].ToString() != string.Empty
      let dc = Drivecode = int.Parse(x.ItemArray[x.ItemArray.Length - 1].ToString())
      //join Session Drive status on drivecode
      join sds in Context.SDS on dc.ToString() equals sds.DriveCode into hasSD
      //ensure there is a drive loaded for this file and that the file hasnt already been processed
      where hasSD.Count() == 1 & hasSD.First().Events == false
      //select all items that fit these parameters to a array
      select new DBEVENT(x)).ToArray();
      //if duplicates found fail with error message
      if (Context.DBEVENTS.Where(x => x.קוד_נסיעה == Drivecode).Count() != 0)
      {

      StatusBox.Text += "קובץ אירועי נסיעה כבר נטען למסד הנתונים עבור " + Environment.NewLine + "נסיעה " + Events[0].קוד_נסיעה + Environment.NewLine;
      button2s.Fill = Brushes.IndianRed;
      return;
      }
      else
      {
      //ensure there are events to add
      if (Events.Count() > 0)
      {
      //add each event to the table
      foreach (var Event in Events)
      {
      Context.DBEVENTS.Add(Event);
      }
      //start inner try catch to handle saving
      try
      {
      //Save Data
      Context.SaveChanges();
      //After Save add Completion to SessionDriveTable
      var sdcompletion = (from sda in Context.SDS
      where Drivecode.ToString() == sda.DriveCode
      where sda != null
      select sda).First().Events = true;
      //save completion
      Context.SaveChanges();
      //commit
      transaction.Commit();
      button2s.Fill = Brushes.LawnGreen;
      }
      catch (Exception ex)
      {
      //rollback changes
      transaction.Rollback();
      //throw this error to the outer exception handler
      //to ensure the entities are removed from the change tracker
      throw ex;
      }
      }
      //no events created could be drive doesn't exist or events already added
      else
      {
      button2s.Fill = Brushes.IndianRed;
      DataRow dr = Events_DataSet.Tables[0].Rows[1];
      var DriveCode = dr[dr.ItemArray.Count() - 1].ToString();
      StatusBox.Text += "מספר הנסיעה " + DriveCode + " לא קיים במסד הנתונים." + Environment.NewLine + "אנא השלם פרטי נסיעה טרם טעינת קובץ." + Environment.NewLine;
      return;
      }
      }
      }
      }
      //main exception handler
      //rolls back any tracked changes in entity framework
      //unwraps exceptions to the most relevant inner exception
      catch (Exception ex)
      {
      ExceptionRollback();
      while (ex.InnerException != null)
      {
      ex = ex.InnerException;
      }
      button2s.Fill = Brushes.IndianRed;
      StatusBox.Text += ex.Message + Environment.NewLine;
      }
      }
      }


      Exception roll back simply removes any items added modified deleted using entity framework change tracker.



          public void ExceptionRollback()
      {
      if (Context.ChangeTracker.HasChanges())
      {
      foreach (var entry in Context.ChangeTracker.Entries()
      .Where(entry => entry.State == EntityState.Added ||
      entry.State == EntityState.Modified ||
      entry.State == EntityState.Deleted))
      {
      entry.State = EntityState.Detached;
      }
      }
      }


      Really looking for ideas on how to abstract the functionality away from the UI code...







      c# entity-framework





      share












      share










      share



      share










      asked 14 mins ago









      BanMeBanMe

      415




      415






















          0






          active

          oldest

          votes











          Your Answer





          StackExchange.ifUsing("editor", function () {
          return StackExchange.using("mathjaxEditing", function () {
          StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
          StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
          });
          });
          }, "mathjax-editing");

          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "196"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f211451%2floading-data-via-excel-to-sql%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes
















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Code Review Stack Exchange!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          Use MathJax to format equations. MathJax reference.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f211451%2floading-data-via-excel-to-sql%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Create new schema in PostgreSQL using DBeaver

          Deepest pit of an array with Javascript: test on Codility

          Costa Masnaga