Ejemplo n.º 1
0
        private void subscribeButton_Click(object sender, EventArgs e)
        {
            using (UserDataEntities dc = new UserDataEntities())
            {
                var users     = from user in dc.Users where user.UserName == userName select user;
                var userPages = from pages in dc.Pages where pages.UserName == userName select pages;
                var count     = userPages.Count();
                if (users.FirstOrDefault().MaxPageNumber > count)
                {
                    // newWikipediaPageTextBox, sensitivityNumericBox, refreshRateNumericBox értékét  kiovlassuk, és beszúrunk egy új sort a Pages táblába, majd meghívjuk a refreshDataGridet
                    string subscribePageName    = newWikipediaPageTextBox.Text;
                    int    subscribeSensitivity = (int)sensitivityNumericBox.Value;
                    int    subscriberefreshRate = (int)refreshRateNumericBox.Value;

                    Page newPage = new Page();
                    newPage.UserName     = this.userName;
                    newPage.WikiPage     = subscribePageName;
                    newPage.Sensitivity  = subscribeSensitivity;
                    newPage.RefreshRate  = subscriberefreshRate;
                    newPage.LastRevision = -1;

                    dc.Pages.Add(newPage);
                    dc.SaveChanges();

                    refreshDataGrid();
                }
                else
                {
                    MessageBox.Show("You can not subscribe");
                }
            }
        }
        private void refreshDatabase(PageReadData data, bool notified = false, int revID = -1)
        {
            using (UserDataEntities dc = new UserDataEntities())
            {
                var currentPage = from page in dc.Pages
                                  where page.Id == data.PageId
                                  select page;
                try
                {
                    var page = currentPage.First();
                    if (notified)
                    {
                        // If user has been notified
                        page.LastRevision = revID;
                        page.LastNotified = DateTime.Now;
                    }
                    page.LastRefreshed = DateTime.Now;

                    dc.SaveChanges();
                }
                catch (ArgumentNullException exp)
                {
                    Console.WriteLine("Error: " + exp.Message + "\n\t Possibly wrong page id.");
                }
            }
        }
Ejemplo n.º 3
0
        public HttpResponseMessage Put(int id, [FromBody] User user)
        {
            using (UserDataEntities userEntities = new UserDataEntities())
            {
                try
                {
                    User userEntity = userEntities.Users.FirstOrDefault(e => e.UserId == id);
                    if (userEntity == null)
                    {
                        return(Request.CreateErrorResponse(HttpStatusCode.NotFound, "The user with the id of " + id.ToString() + " was not found."));
                    }
                    else
                    {
                        userEntity.UserPassword = user.UserPassword;
                        userEntity.UserEmail    = user.UserEmail;

                        userEntities.SaveChanges();
                        return(Request.CreateResponse(HttpStatusCode.OK, userEntities));
                    }
                }
                catch (Exception ex)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex));
                }
            }
        }
        private void modifyButton_Click(object sender, EventArgs e)
        {
            string selected = usersComboBox.SelectedItem.ToString();

            using (UserDataEntities dc = new UserDataEntities())
            {
                Object selecteduserName = usersComboBox.SelectedItem;
                var    users            = from user in dc.Users where user.UserName == selecteduserName.ToString()
                                          select user;

                foreach (var user in users)
                {
                    user.MaxPageNumber      = (int)modifySubscriptionNumericBox.Value;
                    user.NotificationPerDay = (int)modifyRefreshRate.Value;
                    if (userName != user.UserName || user.IsAdmin == admin_check.Checked)
                    {
                        user.IsAdmin = admin_check.Checked;
                    }
                    else
                    {
                        MessageBox.Show("Cannot change admin permission for yourself!");
                    }
                }

                try
                {
                    dc.SaveChanges();
                }
                catch (Exception exp)
                {
                    Console.WriteLine(exp);
                }
            }
        }
Ejemplo n.º 5
0
 public void Post([FromBody] User user)
 {
     using (var entities = new UserDataEntities())
     {
         user.DateCreated = DateTime.Now;
         entities.Users.Add(user);
         entities.SaveChanges();
     }
 }
        public ActionResult Registration([Bind(Exclude = "IsEmailVerified,ActivationCode")] RegistrationDetail registrationDetail)
        {
            bool   Status  = false;
            string message = "";

            //
            // Model Validation
            if (ModelState.IsValid)
            {
                #region
                // Email already Exist
                var isExist = IsEmailExist(registrationDetail.EmailID);
                if (isExist)
                {
                    ModelState.AddModelError("EmailExist", "Email already exist");
                    return(View(registrationDetail));
                }
                #endregion
                #region
                //Generate Activation Code
                registrationDetail.ActivationCode = Guid.NewGuid();
                #endregion

                #region
                // Password Hashing
                registrationDetail.Password        = Crypto.Hash(registrationDetail.Password);
                registrationDetail.ConfirmPassword = Crypto.Hash(registrationDetail.ConfirmPassword); //
                #endregion
                registrationDetail.IsEmailVerified = false;

                #region
                //Save to Database
                using (UserDataEntities dc = new UserDataEntities())
                {
                    dc.RegistrationDetails.Add(registrationDetail);
                    dc.SaveChanges();

                    //Send Email to User
                    SendVerificationLinkEmail(registrationDetail.EmailID, registrationDetail.ActivationCode.ToString());
                    message = "Registration successfully done. Account activation link " +
                              " has been sent to your email id:" + registrationDetail.EmailID;
                    Status = true;
                }
                #endregion
            }
            else
            {
                message = "Invalid Request";
            }

            ViewBag.Message = message;
            ViewBag.Status  = Status;
            return(View(registrationDetail));
        }
Ejemplo n.º 7
0
 public IHttpActionResult Add(User user)
 {
     if (user != null)
     {
         UserDataEntities entities = new UserDataEntities();
         var response = entities.Users.Add(user);
         entities.SaveChanges();
         return(Ok(response));
     }
     else
     {
         return(BadRequest());
     }
 }
        private void updateNotifications()
        {
            using (UserDataEntities dc = new UserDataEntities())
            {
                var pages = from page in dc.Pages
                            select page;
                foreach (var page in pages)
                {
                    page.Notified = 0;
                }

                dc.SaveChanges();
            }

            date = DateTime.Today;
        }
 public WikipediaPoller()
 {
     using (UserDataEntities dc = new UserDataEntities())
     {
         var pages = from page in dc.Pages
                     where page.LastNotified == null ||
                     page.LastNotified.Value != DateTime.Today
                     select page;
         foreach (var page in pages)
         {
             page.Notified = 0;
         }
         date = DateTime.Today;
         dc.SaveChanges();
     }
 }
Ejemplo n.º 10
0
 public HttpResponseMessage Delete(int id)
 {
     using (UserDataEntities userEntities = new UserDataEntities())
     {
         var entity = userEntities.Users.FirstOrDefault(e => e.UserId == id);
         if (entity == null)
         {
             return(Request.CreateErrorResponse(HttpStatusCode.NotFound, "The product with the id of " + id.ToString() + " was not found."));
         }
         else
         {
             userEntities.Users.Remove(entity);
             userEntities.SaveChanges();
             return(Request.CreateResponse(HttpStatusCode.OK));
         }
     }
 }
Ejemplo n.º 11
0
 public HttpResponseMessage Post([FromBody] User user)
 {
     using (UserDataEntities userEntities = new UserDataEntities())
     {
         try
         {
             userEntities.Users.Add(user);
             userEntities.SaveChanges();
             var message = Request.CreateResponse(HttpStatusCode.Created, user);
             message.Headers.Location = new Uri(Request.RequestUri + user.UserId.ToString());
             return(message);
         }
         catch (Exception ex)
         {
             return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex));
         }
     }
 }
Ejemplo n.º 12
0
        private void unsubscribeButton_Click(object sender, EventArgs e)
        {
            Object selectedItem = unsubscribeComboBox1.SelectedItem;

            // username és a kiválasztott wikipedia oldal függvényében kitöröljük a Pages táblából a sort, majd meghívjuk a refreshDataGridet
            using (UserDataEntities dc = new UserDataEntities())
            {
                var itemToRemove = (from s1 in dc.Pages
                                    where s1.WikiPage == selectedItem.ToString() && s1.UserName == userName
                                    select s1).FirstOrDefault();

                if (itemToRemove != null)
                {
                    dc.Pages.Remove(itemToRemove);
                    dc.SaveChanges();
                }
            }

            refreshDataGrid();
        }
        public ActionResult VerifyAccount(string id)
        {
            bool Status = false;

            using (UserDataEntities dc = new UserDataEntities())
            {
                dc.Configuration.ValidateOnSaveEnabled = false; // This line I have added here to avoid
                                                                // Confirm password does not match issue on save changes
                var v = dc.RegistrationDetails.Where(a => a.ActivationCode == new Guid(id)).FirstOrDefault();
                if (v != null)
                {
                    v.IsEmailVerified = true;
                    dc.SaveChanges();
                    Status = true;
                }
                else
                {
                    ViewBag.Message = "Invalid Request";
                }
            }
            ViewBag.Status = Status;
            return(View());
        }
Ejemplo n.º 14
0
        private void modifyButton_Click(object sender, EventArgs e)
        {
            // username és a kiválasztott wikipedia oldal függvényében kitöröljük a Pages táblából a sort és egy új sort szúrúnk be a módosított értékeknek megfelelően, majd meghívjuk a refreshDataGridet

            Object selectedItem = unsubscribeComboBox1.SelectedItem;

            // username és a kiválasztott wikipedia oldal függvényében kitöröljük a Pages táblából a sort, majd meghívjuk a refreshDataGridet
            using (UserDataEntities dc = new UserDataEntities())
            {
                var itemToChange = (from s1 in dc.Pages
                                    where s1.WikiPage == selectedItem.ToString() && s1.UserName == userName
                                    select s1).FirstOrDefault();

                if (itemToChange != null)
                {
                    itemToChange.Sensitivity = (int)modifySensitivityNumericBox.Value;
                    itemToChange.RefreshRate = (int)modifyRefreshRate.Value;
                    // dc.Pages.Remove(itemToRemove);
                    dc.SaveChanges();
                }
            }

            refreshDataGrid();
        }
Ejemplo n.º 15
0
        public IHttpActionResult Post(BloodPressure value)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (value.source == null || value.humanId == null)
            {
                return(BadRequest());
            }

            using (var dbContextTransaction = db.Database.BeginTransaction())
            {
                try
                {
                    tSourceService sourceServiceObj = db.tSourceServices
                                                      .SingleOrDefault(x => x.ServiceName == value.source && x.SourceID == 5);

                    if (sourceServiceObj == null)
                    {
                        sourceServiceObj             = new tSourceService();
                        sourceServiceObj.ServiceName = value.source;
                        sourceServiceObj.TypeID      = 2; //Wellness
                        sourceServiceObj.SourceID    = 5; //HumanAPI

                        db.tSourceServices.Add(sourceServiceObj);
                    }

                    tUserSourceService userSourceServiceObj = null;

                    //Get credentials
                    tCredential credentialObj =
                        db.tCredentials.SingleOrDefault(x => x.SourceID == 5 && x.SourceUserID == value.humanId &&
                                                        x.SystemStatusID == 1);
                    if (credentialObj == null)
                    {
                        throw new NoUserCredentialsException("Unable to find any matching HAPI user credentials");
                    }
                    else
                    {
                        userSourceServiceObj = db.tUserSourceServices.SingleOrDefault(
                            x => x.SourceServiceID == sourceServiceObj.ID &&
                            x.CredentialID == credentialObj.ID &&
                            x.SystemStatusID == 1);

                        if (userSourceServiceObj == null)
                        {
                            userSourceServiceObj = new tUserSourceService();
                            userSourceServiceObj.SourceServiceID     = sourceServiceObj.ID;
                            userSourceServiceObj.UserID              = credentialObj.UserID;
                            userSourceServiceObj.CredentialID        = credentialObj.ID;
                            userSourceServiceObj.ConnectedOnDateTime = DateTime.Now;
                            userSourceServiceObj.LastSyncDateTime    = DateTime.Now;
                            userSourceServiceObj.LatestDateTime      = value.updatedAt;
                            userSourceServiceObj.StatusID            = 3; //connected
                            userSourceServiceObj.SystemStatusID      = 1; //valid
                            userSourceServiceObj.tCredential         = credentialObj;

                            db.tUserSourceServices.Add(userSourceServiceObj);
                        }
                        else
                        {
                            //update LatestDateTime to the most recent datetime
                            if (userSourceServiceObj.LatestDateTime == null ||
                                userSourceServiceObj.LatestDateTime < value.updatedAt)
                            {
                                userSourceServiceObj.LatestDateTime = value.updatedAt;
                            }
                        }
                    }

                    string[]          vitalNameArray  = { "Systolic Blood Pressure", "Diastolic Blood Pressure", "Heart Rate" };
                    List <tUserVital> userVitalsArray = new List <tUserVital>();

                    foreach (string vitalNameItem in vitalNameArray)
                    {
                        tUserVital userVital = null;
                        userVital = db.tUserVitals
                                    .SingleOrDefault(x => x.SourceObjectID == value.id && x.Name == vitalNameItem);

                        if (userVital == null)
                        {
                            userVital = new tUserVital();
                            userVital.tUserSourceService  = userSourceServiceObj;
                            userVital.UserID              = credentialObj.UserID;
                            userVital.SourceObjectID      = value.id;
                            userVital.UserSourceServiceID = sourceServiceObj.ID;
                            userVital.Name = vitalNameItem;

                            switch (vitalNameItem)
                            {
                            case "Systolic Blood Pressure":
                                userVital.Value = decimal.Parse(value.systolic);
                                userVital.UOMID = 470;    //mmHg
                                break;

                            case "Diastolic Blood Pressure":
                                userVital.Value = decimal.Parse(value.diastolic);
                                userVital.UOMID = 470;    //mmHg
                                break;

                            case "Heart Rate":
                                userVital.Value = decimal.Parse(value.heartRate);
                                userVital.UOMID = 30;    //bpm
                                break;
                            }

                            //Dates
                            DateTimeOffset dtoStart;
                            if (RESTfulBAL.Models.DynamoDB.Utilities.ConvertToDateTimeOffset(value.timestamp,
                                                                                             value.tzOffset,
                                                                                             out dtoStart))
                            {
                                userVital.ResultDateTime = dtoStart;
                            }
                            else
                            {
                                userVital.ResultDateTime = value.timestamp;
                            }

                            userVital.SystemStatusID = 1;

                            db.tUserVitals.Add(userVital);
                        }
                        else
                        {
                            userVital.Name = vitalNameItem;

                            switch (vitalNameItem)
                            {
                            case "Systolic Blood Pressure":
                                userVital.Value = decimal.Parse(value.systolic);
                                userVital.UOMID = 470;    //mm[Hg]
                                break;

                            case "Diastolic Blood Pressure":
                                userVital.Value = decimal.Parse(value.diastolic);
                                userVital.UOMID = 470;    //mm[Hg]
                                break;

                            case "Heart Rate":
                                userVital.Value = decimal.Parse(value.heartRate);
                                userVital.UOMID = 30;    //bpm
                                break;
                            }

                            //Dates
                            DateTimeOffset dtoStart;
                            if (RESTfulBAL.Models.DynamoDB.Utilities.ConvertToDateTimeOffset(value.timestamp,
                                                                                             value.tzOffset,
                                                                                             out dtoStart))
                            {
                                userVital.ResultDateTime = dtoStart;
                            }
                            else
                            {
                                userVital.ResultDateTime = value.timestamp;
                            }

                            userVital.LastUpdatedDateTime = DateTime.Now;
                            userVital.tUserSourceService  = userSourceServiceObj;
                        }
                        userVitalsArray.Add(userVital);
                    }

                    db.SaveChanges();

                    dbContextTransaction.Commit();

                    return(Ok(userVitalsArray));
                }
                catch (Exception ex)
                {
                    dbContextTransaction.Rollback();

                    //Insert Error Log
                    tUserDataErrLog userErrorLog = new tUserDataErrLog();

                    userErrorLog.ErrTypeID   = (int)ErrorLogging.enumErrorType.Application;
                    userErrorLog.ErrSourceID = (int)AuditLogging.enumApplication.SFCBAL;
                    userErrorLog.Code        = ex.HResult.ToString();
                    userErrorLog.Description = ex.Message;
                    userErrorLog.Trace       = ex.StackTrace;

                    dbErr.tUserDataErrLogs.Add(userErrorLog);
                    dbErr.SaveChanges();

                    string ErrMsg = "An error occured and we have logged the error. Please try again later.";

                    Exception Err = new Exception(ErrMsg, ex);

                    return(InternalServerError(Err));
                }
            }
        }
Ejemplo n.º 16
0
        public IHttpActionResult Post(SleepSummaries value)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (value.source == null || value.humanId == null)
            {
                return(BadRequest());
            }

            using (var dbContextTransaction = db.Database.BeginTransaction())
            {
                try
                {
                    tSourceService sourceServiceObj = db.tSourceServices
                                                      .SingleOrDefault(x => x.ServiceName == value.source && x.SourceID == 5);

                    if (sourceServiceObj == null)
                    {
                        sourceServiceObj             = new tSourceService();
                        sourceServiceObj.ServiceName = value.source;
                        sourceServiceObj.TypeID      = 2; //Wellness
                        sourceServiceObj.SourceID    = 5; //HumanAPI

                        db.tSourceServices.Add(sourceServiceObj);
                    }

                    tUserSourceService userSourceServiceObj = null;

                    //Get credentials
                    tCredential credentialObj =
                        db.tCredentials.SingleOrDefault(x => x.SourceID == 5 && x.SourceUserID == value.humanId &&
                                                        x.SystemStatusID == 1);
                    if (credentialObj == null)
                    {
                        throw new NoUserCredentialsException("Unable to find any matching HAPI user credentials");
                    }
                    else
                    {
                        userSourceServiceObj = db.tUserSourceServices.SingleOrDefault(
                            x => x.SourceServiceID == sourceServiceObj.ID &&
                            x.CredentialID == credentialObj.ID &&
                            x.SystemStatusID == 1);

                        if (userSourceServiceObj == null)
                        {
                            userSourceServiceObj = new tUserSourceService();
                            userSourceServiceObj.SourceServiceID     = sourceServiceObj.ID;
                            userSourceServiceObj.UserID              = credentialObj.UserID;
                            userSourceServiceObj.CredentialID        = credentialObj.ID;
                            userSourceServiceObj.ConnectedOnDateTime = DateTime.Now;
                            userSourceServiceObj.LastSyncDateTime    = DateTime.Now;
                            userSourceServiceObj.LatestDateTime      = value.updatedAt;
                            userSourceServiceObj.StatusID            = 3; //connected
                            userSourceServiceObj.SystemStatusID      = 1; //valid
                            userSourceServiceObj.tCredential         = credentialObj;

                            db.tUserSourceServices.Add(userSourceServiceObj);
                        }
                        else
                        {
                            //update LatestDateTime to the most recent datetime
                            if (userSourceServiceObj.LatestDateTime == null ||
                                userSourceServiceObj.LatestDateTime < value.updatedAt)
                            {
                                userSourceServiceObj.LatestDateTime = value.updatedAt;
                            }
                        }
                    }

                    tUserSleep userSleep = db.tUserSleeps
                                           .SingleOrDefault(x => x.SourceObjectID == value.id);

                    if (userSleep == null)
                    {
                        //insert
                        userSleep = new tUserSleep();
                        userSleep.SourceObjectID      = value.id;
                        userSleep.UserID              = credentialObj.UserID;
                        userSleep.tUserSourceService  = userSourceServiceObj;
                        userSleep.UserSourceServiceID = userSourceServiceObj.ID;

                        userSleep.SystemStatusID    = 1;
                        userSleep.PrimarySleepEvent = Convert.ToByte(value.mainSleep);
                        userSleep.TimeAsleep        = value.timeAsleep;
                        userSleep.TimeAwake         = value.timeAwake;
                        userSleep.StartDateTime     = value.endTime;
                        userSleep.EndDateTime       = value.endTime;

                        db.tUserSleeps.Add(userSleep);
                    }
                    else
                    {
                        //update
                        userSleep.PrimarySleepEvent = Convert.ToByte(value.mainSleep);
                        userSleep.TimeAsleep        = value.timeAsleep;
                        userSleep.TimeAwake         = value.timeAwake;
                        userSleep.StartDateTime     = value.endTime;
                        userSleep.EndDateTime       = value.endTime;

                        userSleep.LastUpdatedDateTime = DateTime.Now;
                        userSleep.tUserSourceService  = userSourceServiceObj;
                    }

                    db.SaveChanges();

                    dbContextTransaction.Commit();

                    return(Ok(userSleep));
                }
                catch (Exception ex)
                {
                    dbContextTransaction.Rollback();

                    //Insert Error Log
                    tUserDataErrLog userErrorLog = new tUserDataErrLog();

                    userErrorLog.ErrTypeID   = (int)ErrorLogging.enumErrorType.Application;
                    userErrorLog.ErrSourceID = (int)AuditLogging.enumApplication.SFCBAL;
                    userErrorLog.Code        = ex.HResult.ToString();
                    userErrorLog.Description = ex.Message;
                    userErrorLog.Trace       = ex.StackTrace;

                    dbErr.tUserDataErrLogs.Add(userErrorLog);
                    dbErr.SaveChanges();

                    string ErrMsg = "An error occured and we have logged the error. Please try again later.";

                    Exception Err = new Exception(ErrMsg, ex);

                    return(InternalServerError(Err));
                }
            }
        }
Ejemplo n.º 17
0
        public IHttpActionResult Post(Narratives value)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (value.source == null || value.access_token == null)
            {
                return(BadRequest());
            }

            using (var dbContextTransaction = db.Database.BeginTransaction())
            {
                try
                {
                    tSourceService sourceServiceObj = db.tSourceServices
                                                      .SingleOrDefault(x => x.ServiceName == value.source && x.SourceID == 5);

                    if (sourceServiceObj == null)
                    {
                        sourceServiceObj             = new tSourceService();
                        sourceServiceObj.ServiceName = value.source;
                        sourceServiceObj.TypeID      = 1; //Medical
                        sourceServiceObj.SourceID    = 5; //HumanAPI

                        db.tSourceServices.Add(sourceServiceObj);
                    }

                    tUserSourceService userSourceServiceObj = null;

                    //Get credentials
                    tCredential credentialObj =
                        db.tCredentials.SingleOrDefault(x => x.SourceID == 5 &&
                                                        x.AccessToken == value.access_token &&
                                                        x.SystemStatusID == 1);
                    if (credentialObj == null)
                    {
                        throw new NoUserCredentialsException("Unable to find any matching HAPI user credentials");
                    }
                    else
                    {
                        userSourceServiceObj = db.tUserSourceServices.SingleOrDefault(
                            x => x.SourceServiceID == sourceServiceObj.ID &&
                            x.CredentialID == credentialObj.ID &&
                            x.SystemStatusID == 1);

                        if (userSourceServiceObj == null)
                        {
                            userSourceServiceObj = new tUserSourceService();
                            userSourceServiceObj.SourceServiceID     = sourceServiceObj.ID;
                            userSourceServiceObj.UserID              = credentialObj.UserID;
                            userSourceServiceObj.CredentialID        = credentialObj.ID;
                            userSourceServiceObj.ConnectedOnDateTime = DateTime.Now;
                            userSourceServiceObj.LastSyncDateTime    = DateTime.Now;
                            userSourceServiceObj.LatestDateTime      = value.updatedAt;
                            userSourceServiceObj.StatusID            = 3; //connected
                            userSourceServiceObj.SystemStatusID      = 1; //valid
                            userSourceServiceObj.tCredential         = credentialObj;

                            db.tUserSourceServices.Add(userSourceServiceObj);
                        }
                        else
                        {
                            //update LatestDateTime to the most recent datetime
                            if (userSourceServiceObj.LatestDateTime == null ||
                                userSourceServiceObj.LatestDateTime < value.updatedAt)
                            {
                                userSourceServiceObj.LatestDateTime = value.updatedAt;
                            }
                        }
                    }

                    tSourceOrganization userSourceOrganization = null;
                    if (value.organization != null)
                    {
                        //Get source org
                        userSourceOrganization =
                            db.tSourceOrganizations.SingleOrDefault(x => x.SourceObjectID == value.organization.id);
                        if (userSourceOrganization == null)
                        {
                            //create org
                            tOrganization userOrganization = new tOrganization();
                            userOrganization.Name = value.organization.name;

                            //create new source org entry
                            userSourceOrganization = new tSourceOrganization();
                            userSourceOrganization.SourceObjectID  = value.organization.id;
                            userSourceOrganization.tOrganization   = userOrganization;
                            userSourceOrganization.OrganizationID  = userOrganization.ID;
                            userSourceOrganization.SourceServiceID = sourceServiceObj.ID;

                            db.tSourceOrganizations.Add(userSourceOrganization);
                        }
                    }

                    tProvider userProvider = new tProvider();
                    if (value.author != null)
                    {
                        userProvider.Name = value.author;
                        if (userSourceOrganization != null)
                        {
                            userProvider.tOrganization  = userSourceOrganization.tOrganization;
                            userProvider.OrganizationID = userSourceOrganization.OrganizationID;
                        }

                        db.tProviders.Add(userProvider);
                    }

                    tUserNarrative userNarrative = null;
                    userNarrative = db.tUserNarratives
                                    .SingleOrDefault(x => x.SourceObjectID == value.Id);

                    if (userNarrative == null)
                    {
                        //insert
                        userNarrative = new tUserNarrative();
                        userNarrative.SourceObjectID = value.Id;
                        userNarrative.UserID         = credentialObj.UserID;
                        if (userSourceOrganization != null)
                        {
                            userNarrative.tSourceOrganization  = userSourceOrganization;
                            userNarrative.SourceOrganizationID = userSourceOrganization.ID;
                        }
                        userNarrative.tUserSourceService  = userSourceServiceObj;
                        userNarrative.UserSourceServiceID = userSourceServiceObj.ID;

                        if (value.author != null)
                        {
                            userNarrative.tProvider  = userProvider;
                            userNarrative.ProviderID = userProvider.ID;
                        }

                        userNarrative.StartDateTime  = value.dateTime;
                        userNarrative.SystemStatusID = 1;

                        int seqNum = 0;
                        foreach (entries narrativeEntry in value.entries)
                        {
                            tUserNarrativeEntry userNarrativeEntry = new tUserNarrativeEntry();
                            userNarrativeEntry.SectionSeqNum  = seqNum++;
                            userNarrativeEntry.SectionText    = narrativeEntry.text;
                            userNarrativeEntry.SectionTitle   = narrativeEntry.title;
                            userNarrativeEntry.NarrativeID    = userNarrative.ID;
                            userNarrativeEntry.SystemStatusID = 1;
                            userNarrative.tUserNarrativeEntries.Add(userNarrativeEntry);
                        }

                        db.tUserNarratives.Add(userNarrative);
                    }
                    else
                    {
                        //update
                        if (userSourceOrganization != null)
                        {
                            userNarrative.tSourceOrganization  = userSourceOrganization;
                            userNarrative.SourceOrganizationID = userSourceOrganization.ID;
                        }
                        userNarrative.tUserSourceService  = userSourceServiceObj;
                        userNarrative.UserSourceServiceID = userSourceServiceObj.ID;

                        if (value.author != null)
                        {
                            userNarrative.tProvider  = userProvider;
                            userNarrative.ProviderID = userProvider.ID;
                        }

                        userNarrative.StartDateTime = value.dateTime;

                        List <tUserNarrativeEntry> existingEntries = db.tUserNarrativeEntries
                                                                     .Where(x => x.NarrativeID == userNarrative.ID).ToList();
                        existingEntries.ForEach(e => e.SystemStatusID = 4);

                        int seqNum = 0;
                        foreach (entries narrativeEntry in value.entries)
                        {
                            tUserNarrativeEntry userNarrativeEntry = new tUserNarrativeEntry();
                            userNarrativeEntry.SectionSeqNum  = seqNum++;
                            userNarrativeEntry.SectionText    = narrativeEntry.text;
                            userNarrativeEntry.SectionTitle   = narrativeEntry.title;
                            userNarrativeEntry.NarrativeID    = userNarrative.ID;
                            userNarrativeEntry.SystemStatusID = 1;
                            userNarrative.tUserNarrativeEntries.Add(userNarrativeEntry);
                        }

                        userNarrative.LastUpdatedDateTime = DateTime.Now;
                    }

                    db.SaveChanges();

                    dbContextTransaction.Commit();

                    return(Ok(userNarrative));
                }
                catch (Exception ex)
                {
                    dbContextTransaction.Rollback();

                    //Insert Error Log
                    tUserDataErrLog userErrorLog = new tUserDataErrLog();

                    userErrorLog.ErrTypeID   = (int)ErrorLogging.enumErrorType.Application;
                    userErrorLog.ErrSourceID = (int)AuditLogging.enumApplication.SFCBAL;
                    userErrorLog.Code        = ex.HResult.ToString();
                    userErrorLog.Description = ex.Message;
                    userErrorLog.Trace       = ex.StackTrace;

                    dbErr.tUserDataErrLogs.Add(userErrorLog);
                    dbErr.SaveChanges();

                    string ErrMsg = "An error occured and we have logged the error. Please try again later.";

                    Exception Err = new Exception(ErrMsg, ex);

                    return(InternalServerError(Err));
                }
            }
        }
Ejemplo n.º 18
0
        public IHttpActionResult Post(Sources value)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (value.source == null || value.access_token == null)
            {
                return(BadRequest());
            }

            using (var dbContextTransaction = db.Database.BeginTransaction())
            {
                try
                {
                    tSourceService sourceServiceObj = db.tSourceServices
                                                      .SingleOrDefault(x => x.ServiceName == value.source && x.SourceID == 5);

                    if (sourceServiceObj == null)
                    {
                        sourceServiceObj             = new tSourceService();
                        sourceServiceObj.ServiceName = value.source;
                        if (value.organization == null)
                        {
                            sourceServiceObj.TypeID = 2; //Wellness
                        }
                        else
                        {
                            sourceServiceObj.TypeID = 1; //Medical
                        }

                        sourceServiceObj.SourceID = 5; //HumanAPI

                        db.tSourceServices.Add(sourceServiceObj);
                    }

                    //get user source service status
                    tUserSourceServiceStatus statusObj = null;
                    string strStatus = "";
                    if (value.syncStatus != null) //for wellness
                    {
                        strStatus = value.syncStatus.status;
                    }
                    else if (value.historySync != null) //for medical
                    {
                        strStatus = value.historySync.status;
                    }

                    statusObj = db.tUserSourceServiceStatuses.SingleOrDefault(x => x.Status == strStatus);

                    if (statusObj == null)
                    {
                        statusObj        = new tUserSourceServiceStatus();
                        statusObj.Status = strStatus;

                        db.tUserSourceServiceStatuses.Add(statusObj);
                    }

                    //Get credentials
                    tUserSourceService userSourceServiceObj = null;

                    tCredential credentialObj =
                        db.tCredentials.SingleOrDefault(x => x.SourceID == 5 &&
                                                        x.AccessToken == value.access_token &&
                                                        x.SystemStatusID == 1);
                    if (credentialObj == null)
                    {
                        throw new NoUserCredentialsException("Unable to find any matching HAPI user credentials");
                    }
                    else
                    {
                        userSourceServiceObj = db.tUserSourceServices.SingleOrDefault(
                            x => x.SourceServiceID == sourceServiceObj.ID &&
                            x.CredentialID == credentialObj.ID &&
                            x.SystemStatusID == 1);

                        if (userSourceServiceObj == null)
                        {
                            userSourceServiceObj = new tUserSourceService();
                            userSourceServiceObj.SourceServiceID     = sourceServiceObj.ID;
                            userSourceServiceObj.UserID              = credentialObj.UserID;
                            userSourceServiceObj.CredentialID        = credentialObj.ID;
                            userSourceServiceObj.ConnectedOnDateTime = value.connectedSince;
                            userSourceServiceObj.LastSyncDateTime    = DateTime.Now.AddDays(-30d);
                            userSourceServiceObj.LatestDateTime      = DateTime.Now;
                            userSourceServiceObj.StatusID            = statusObj.ID;
                            userSourceServiceObj.SystemStatusID      = 1; //valid
                            userSourceServiceObj.tCredential         = credentialObj;

                            db.tUserSourceServices.Add(userSourceServiceObj);
                        }
                    }

                    foreach (string device in value.devices)
                    {
                        tSourceServiceDevice sourceServiceDevices = db.tSourceServiceDevices.SingleOrDefault(
                            x => x.Name == device);
                        if (sourceServiceDevices == null)
                        {
                            sourceServiceDevices      = new tSourceServiceDevice();
                            sourceServiceDevices.Name = device;

                            db.tSourceServiceDevices.Add(sourceServiceDevices);
                        }

                        tXrefUserSourceServiceDevice userdevices = db.tXrefUserSourceServiceDevices.SingleOrDefault(
                            x => x.UserSourceServiceID == userSourceServiceObj.ID &&
                            x.SourceServiceDeviceID == sourceServiceDevices.ID);
                        if (userdevices == null)
                        {
                            userdevices = new tXrefUserSourceServiceDevice();
                            userdevices.UserSourceServiceID   = userSourceServiceObj.ID;
                            userdevices.SourceServiceDeviceID = sourceServiceDevices.ID;

                            userdevices.tSourceServiceDevice = sourceServiceDevices;
                            userdevices.tUserSourceService   = userSourceServiceObj;

                            db.tXrefUserSourceServiceDevices.Add(userdevices);
                        }
                    }

                    tSourceOrganization userSourceOrganization = null;
                    if (value.organization != null)
                    {
                        //Get source org
                        userSourceOrganization = db.tSourceOrganizations
                                                 .Include("tOrganization")
                                                 .SingleOrDefault(x => x.SourceObjectID == value.organization.id);

                        if (userSourceOrganization == null)
                        {
                            //create org
                            tOrganization userOrganization = new tOrganization();
                            userOrganization.Name = value.organization.name;

                            //create new source org entry
                            userSourceOrganization = new tSourceOrganization();
                            userSourceOrganization.SourceObjectID  = value.organization.id;
                            userSourceOrganization.tOrganization   = userOrganization;
                            userSourceOrganization.OrganizationID  = userOrganization.ID;
                            userSourceOrganization.SourceServiceID = sourceServiceObj.ID;

                            db.tSourceOrganizations.Add(userSourceOrganization);
                        }
                    }

                    db.SaveChanges();

                    dbContextTransaction.Commit();

                    return(Ok(userSourceServiceObj));
                }
                catch (Exception ex)
                {
                    dbContextTransaction.Rollback();

                    //Insert Error Log
                    tUserDataErrLog userErrorLog = new tUserDataErrLog();

                    userErrorLog.ErrTypeID   = (int)ErrorLogging.enumErrorType.Application;
                    userErrorLog.ErrSourceID = (int)AuditLogging.enumApplication.SFCBAL;
                    userErrorLog.Code        = ex.HResult.ToString();
                    userErrorLog.Description = ex.Message;
                    userErrorLog.Trace       = ex.StackTrace;

                    dbErr.tUserDataErrLogs.Add(userErrorLog);
                    dbErr.SaveChanges();

                    string ErrMsg = "An error occured and we have logged the error. Please try again later.";

                    Exception Err = new Exception(ErrMsg, ex);

                    return(InternalServerError(Err));
                }
            }
        }
Ejemplo n.º 19
0
        public IHttpActionResult Post(BloodOxygen value)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (value.source == null || value.humanId == null)
            {
                return(BadRequest());
            }

            using (var dbContextTransaction = db.Database.BeginTransaction())
            {
                try
                {
                    tSourceService sourceServiceObj = db.tSourceServices
                                                      .SingleOrDefault(x => x.ServiceName == value.source && x.SourceID == 5);

                    if (sourceServiceObj == null)
                    {
                        sourceServiceObj             = new tSourceService();
                        sourceServiceObj.ServiceName = value.source;
                        sourceServiceObj.TypeID      = 2; //Wellness
                        sourceServiceObj.SourceID    = 5; //HumanAPI

                        db.tSourceServices.Add(sourceServiceObj);
                    }

                    tUserSourceService userSourceServiceObj = null;

                    //Get credentials
                    tCredential credentialObj =
                        db.tCredentials.SingleOrDefault(x => x.SourceID == 5 && x.SourceUserID == value.humanId &&
                                                        x.SystemStatusID == 1);
                    if (credentialObj == null)
                    {
                        throw new NoUserCredentialsException("Unable to find any matching HAPI user credentials");
                    }
                    else
                    {
                        userSourceServiceObj = db.tUserSourceServices.SingleOrDefault(
                            x => x.SourceServiceID == sourceServiceObj.ID &&
                            x.CredentialID == credentialObj.ID &&
                            x.SystemStatusID == 1);

                        if (userSourceServiceObj == null)
                        {
                            userSourceServiceObj = new tUserSourceService();
                            userSourceServiceObj.SourceServiceID     = sourceServiceObj.ID;
                            userSourceServiceObj.UserID              = credentialObj.UserID;
                            userSourceServiceObj.CredentialID        = credentialObj.ID;
                            userSourceServiceObj.ConnectedOnDateTime = DateTime.Now;
                            userSourceServiceObj.LastSyncDateTime    = DateTime.Now;
                            userSourceServiceObj.LatestDateTime      = value.updatedAt;
                            userSourceServiceObj.StatusID            = 3; //connected
                            userSourceServiceObj.SystemStatusID      = 1; //valid
                            userSourceServiceObj.tCredential         = credentialObj;

                            db.tUserSourceServices.Add(userSourceServiceObj);
                        }
                        else
                        {
                            //update LatestDateTime to the most recent datetime
                            if (userSourceServiceObj.LatestDateTime == null ||
                                userSourceServiceObj.LatestDateTime < value.updatedAt)
                            {
                                userSourceServiceObj.LatestDateTime = value.updatedAt;
                            }
                        }
                    }

                    tUserTestResult userTestResult = null;
                    userTestResult = db.tUserTestResults
                                     .SingleOrDefault(x => x.SourceObjectID == value.id);

                    if (userTestResult == null)
                    {
                        //insert
                        userTestResult = new tUserTestResult();
                        userTestResult.SourceObjectID      = value.id;
                        userTestResult.UserID              = credentialObj.UserID;
                        userTestResult.tUserSourceService  = userSourceServiceObj;
                        userTestResult.UserSourceServiceID = userSourceServiceObj.ID;
                        userTestResult.Name           = "Blood Oxygen";
                        userTestResult.StatusID       = 3; //captured
                        userTestResult.SystemStatusID = 1;

                        //Dates
                        DateTimeOffset dtoStart;
                        if (RESTfulBAL.Models.DynamoDB.Utilities.ConvertToDateTimeOffset(value.timestamp,
                                                                                         value.tzOffset,
                                                                                         out dtoStart))
                        {
                            userTestResult.ResultDateTime = dtoStart;
                        }
                        else
                        {
                            userTestResult.ResultDateTime = value.timestamp;
                        }

                        tUserTestResultComponent userTestResultComponent = new tUserTestResultComponent();
                        userTestResultComponent.SystemStatusID = 1;
                        userTestResultComponent.Name           = "Blood Oxygen";
                        userTestResultComponent.Value          = value.value.ToString();

                        //UOM
                        if (value.unit != null)
                        {
                            tUnitsOfMeasure uom = null;
                            uom = db.tUnitsOfMeasures.SingleOrDefault(x => x.UnitOfMeasure == value.unit);
                            if (uom == null)
                            {
                                uom = new tUnitsOfMeasure();
                                uom.UnitOfMeasure = value.unit;

                                db.tUnitsOfMeasures.Add(uom);
                            }

                            userTestResultComponent.tUnitsOfMeasure = uom;
                            userTestResultComponent.UOMID           = uom.ID;
                        }
                        userTestResult.tUserTestResultComponents.Add(userTestResultComponent);

                        tXrefUserTestResultComponentsCode xRefComponentCode = new tXrefUserTestResultComponentsCode();
                        xRefComponentCode.UserTestResultComponentID = userTestResultComponent.ID;
                        xRefComponentCode.CodeID = 6720;
                        userTestResultComponent.tXrefUserTestResultComponentsCodes.Add(xRefComponentCode);

                        userTestResult.tUserSourceService = userSourceServiceObj;

                        db.tUserTestResults.Add(userTestResult);
                    }
                    else
                    {
                        //update

                        //Dates
                        DateTimeOffset dtoStart;
                        if (RESTfulBAL.Models.DynamoDB.Utilities.ConvertToDateTimeOffset(value.timestamp,
                                                                                         value.tzOffset,
                                                                                         out dtoStart))
                        {
                            userTestResult.ResultDateTime = dtoStart;
                        }
                        else
                        {
                            userTestResult.ResultDateTime = value.timestamp;
                        }


                        tUserTestResultComponent userTestResultComponent = db.tUserTestResultComponents
                                                                           .SingleOrDefault(x => x.TestResultID == userTestResult.ID);
                        if (userTestResultComponent != null)
                        {
                            userTestResultComponent.Value = value.value.ToString();

                            //UOM
                            if (value.unit != null)
                            {
                                tUnitsOfMeasure uom = null;
                                uom = db.tUnitsOfMeasures.SingleOrDefault(x => x.UnitOfMeasure == value.unit);
                                if (uom == null)
                                {
                                    uom = new tUnitsOfMeasure();
                                    uom.UnitOfMeasure = value.unit;

                                    db.tUnitsOfMeasures.Add(uom);
                                }

                                if (!uom.UnitOfMeasure.Equals(value.unit))
                                {
                                    userTestResultComponent.tUnitsOfMeasure = uom;
                                    userTestResultComponent.UOMID           = uom.ID;
                                }
                            }

                            userTestResult.tUserTestResultComponents.Add(userTestResultComponent);
                        }

                        userTestResult.LastUpdatedDateTime = DateTime.Now;
                        userTestResult.tUserSourceService  = userSourceServiceObj;
                    }

                    db.SaveChanges();

                    dbContextTransaction.Commit();

                    return(Ok(userTestResult));
                }
                catch (Exception ex)
                {
                    dbContextTransaction.Rollback();

                    //Insert Error Log
                    tUserDataErrLog userErrorLog = new tUserDataErrLog();

                    userErrorLog.ErrTypeID   = (int)ErrorLogging.enumErrorType.Application;
                    userErrorLog.ErrSourceID = (int)AuditLogging.enumApplication.SFCBAL;
                    userErrorLog.Code        = ex.HResult.ToString();
                    userErrorLog.Description = ex.Message;
                    userErrorLog.Trace       = ex.StackTrace;

                    dbErr.tUserDataErrLogs.Add(userErrorLog);
                    dbErr.SaveChanges();

                    string ErrMsg = "An error occured and we have logged the error. Please try again later.";

                    Exception Err = new Exception(ErrMsg, ex);

                    return(InternalServerError(Err));
                }
            }
        }
Ejemplo n.º 20
0
        public IHttpActionResult Post(Activities value)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (value.source == null || value.humanId == null)
            {
                return(BadRequest());
            }

            using (var dbContextTransaction = db.Database.BeginTransaction())
            {
                try
                {
                    tActivity activityObj = db.tActivities.SingleOrDefault(x => x.Name == value.type);

                    if (activityObj == null)
                    {
                        activityObj      = new tActivity();
                        activityObj.Name = value.type;

                        db.tActivities.Add(activityObj);
                    }

                    tSourceService sourceServiceObj = db.tSourceServices
                                                      .SingleOrDefault(x => x.ServiceName == value.source && x.SourceID == 5);

                    if (sourceServiceObj == null)
                    {
                        sourceServiceObj             = new tSourceService();
                        sourceServiceObj.ServiceName = value.source;
                        sourceServiceObj.TypeID      = 2; //Wellness
                        sourceServiceObj.SourceID    = 5; //HumanAPI

                        db.tSourceServices.Add(sourceServiceObj);
                    }

                    tUserSourceService userSourceServiceObj = null;

                    //Get credentials
                    tCredential credentialObj =
                        db.tCredentials.SingleOrDefault(x => x.SourceID == 5 &&
                                                        x.SourceUserID == value.humanId &&
                                                        x.SystemStatusID == 1);
                    if (credentialObj == null)
                    {
                        throw new NoUserCredentialsException("Unable to find any matching HAPI user credentials");
                    }
                    else
                    {
                        userSourceServiceObj = db.tUserSourceServices.SingleOrDefault(
                            x => x.SourceServiceID == sourceServiceObj.ID &&
                            x.CredentialID == credentialObj.ID &&
                            x.SystemStatusID == 1);

                        if (userSourceServiceObj == null)
                        {
                            userSourceServiceObj = new tUserSourceService();
                            userSourceServiceObj.SourceServiceID     = sourceServiceObj.ID;
                            userSourceServiceObj.UserID              = credentialObj.UserID;
                            userSourceServiceObj.CredentialID        = credentialObj.ID;
                            userSourceServiceObj.ConnectedOnDateTime = DateTime.Now;
                            userSourceServiceObj.LastSyncDateTime    = DateTime.Now;
                            userSourceServiceObj.LatestDateTime      = value.updatedAt;
                            userSourceServiceObj.StatusID            = 3; //connected
                            userSourceServiceObj.SystemStatusID      = 1; //valid
                            userSourceServiceObj.tCredential         = credentialObj;

                            db.tUserSourceServices.Add(userSourceServiceObj);
                        }
                        else
                        {
                            //update LatestDateTime to the most recent datetime
                            if (userSourceServiceObj.LatestDateTime == null ||
                                userSourceServiceObj.LatestDateTime < value.updatedAt)
                            {
                                userSourceServiceObj.LatestDateTime = value.updatedAt;
                            }
                        }
                    }

                    tUserActivity userActivity = null;
                    userActivity = db.tUserActivities
                                   .SingleOrDefault(x => x.SourceObjectID == value.id);

                    if (userActivity == null)
                    {
                        userActivity                     = new tUserActivity();
                        userActivity.UserID              = credentialObj.UserID;
                        userActivity.SourceObjectID      = value.id;
                        userActivity.UserSourceServiceID = sourceServiceObj.ID;
                        userActivity.ActivityID          = activityObj.ID;

                        //Dates
                        DateTimeOffset dtoStart, dtoEnd;
                        if (RESTfulBAL.Models.DynamoDB.Utilities.ConvertToDateTimeOffset(value.startTime,
                                                                                         value.tzOffset,
                                                                                         out dtoStart))
                        {
                            userActivity.StartDateTime = dtoStart;
                        }
                        else
                        {
                            userActivity.StartDateTime = value.startTime;
                        }

                        if (RESTfulBAL.Models.DynamoDB.Utilities.ConvertToDateTimeOffset(value.endTime, value.tzOffset,
                                                                                         out dtoEnd))
                        {
                            userActivity.EndDateTime = dtoEnd;
                        }
                        else
                        {
                            userActivity.EndDateTime = value.endTime;
                        }

                        userActivity.Duration           = value.duration;
                        userActivity.DurationUOMID      = 8;
                        userActivity.Distance           = value.distance;
                        userActivity.DistanceUOMID      = 9;
                        userActivity.Steps              = value.steps;
                        userActivity.Calories           = value.calories;
                        userActivity.SystemStatusID     = 1;
                        userActivity.tUserSourceService = userSourceServiceObj;

                        db.tUserActivities.Add(userActivity);
                    }
                    else
                    {
                        userActivity.ActivityID = activityObj.ID;

                        //Dates
                        DateTimeOffset dtoStart, dtoEnd;
                        if (RESTfulBAL.Models.DynamoDB.Utilities.ConvertToDateTimeOffset(value.startTime,
                                                                                         value.tzOffset,
                                                                                         out dtoStart))
                        {
                            userActivity.StartDateTime = dtoStart;
                        }
                        else
                        {
                            userActivity.StartDateTime = value.startTime;
                        }

                        if (RESTfulBAL.Models.DynamoDB.Utilities.ConvertToDateTimeOffset(value.endTime, value.tzOffset,
                                                                                         out dtoEnd))
                        {
                            userActivity.EndDateTime = dtoEnd;
                        }
                        else
                        {
                            userActivity.EndDateTime = value.endTime;
                        }

                        userActivity.Duration            = value.duration;
                        userActivity.DurationUOMID       = 8;
                        userActivity.Distance            = value.distance;
                        userActivity.DistanceUOMID       = 9;
                        userActivity.Steps               = value.steps;
                        userActivity.Calories            = value.calories;
                        userActivity.SystemStatusID      = 1;
                        userActivity.tUserSourceService  = userSourceServiceObj;
                        userActivity.LastUpdatedDateTime = DateTime.Now;
                    }

                    db.SaveChanges();

                    dbContextTransaction.Commit();

                    return(Ok(userActivity));
                }
                catch (Exception ex)
                {
                    dbContextTransaction.Rollback();

                    //Insert Error Log
                    tUserDataErrLog userErrorLog = new tUserDataErrLog();

                    userErrorLog.ErrTypeID   = (int)ErrorLogging.enumErrorType.Application;
                    userErrorLog.ErrSourceID = (int)AuditLogging.enumApplication.SFCBAL;
                    userErrorLog.Code        = ex.HResult.ToString();
                    userErrorLog.Description = ex.Message;
                    userErrorLog.Trace       = ex.StackTrace;

                    dbErr.tUserDataErrLogs.Add(userErrorLog);
                    dbErr.SaveChanges();

                    string ErrMsg = "An error occured and we have logged the error. Please try again later.";

                    Exception Err = new Exception(ErrMsg, ex);

                    return(InternalServerError(Err));
                }
            }
        }
Ejemplo n.º 21
0
        public IHttpActionResult Post(Allergies value)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (value.source == null || value.access_token == null)
            {
                return(BadRequest());
            }

            using (var dbContextTransaction = db.Database.BeginTransaction())
            {
                try
                {
                    tSourceService sourceServiceObj = db.tSourceServices
                                                      .SingleOrDefault(x => x.ServiceName == value.source && x.SourceID == 5);

                    if (sourceServiceObj == null)
                    {
                        sourceServiceObj             = new tSourceService();
                        sourceServiceObj.ServiceName = value.source;
                        sourceServiceObj.TypeID      = 1; //Medical
                        sourceServiceObj.SourceID    = 5; //HumanAPI

                        db.tSourceServices.Add(sourceServiceObj);
                    }

                    tUserSourceService userSourceServiceObj = null;

                    //Get credentials
                    tCredential credentialObj =
                        db.tCredentials.SingleOrDefault(x => x.SourceID == 5 &&
                                                        x.AccessToken == value.access_token &&
                                                        x.SystemStatusID == 1);
                    if (credentialObj == null)
                    {
                        throw new NoUserCredentialsException("Unable to find any matching HAPI user credentials");
                    }
                    else
                    {
                        userSourceServiceObj = db.tUserSourceServices.SingleOrDefault(
                            x => x.SourceServiceID == sourceServiceObj.ID &&
                            x.CredentialID == credentialObj.ID &&
                            x.SystemStatusID == 1);

                        if (userSourceServiceObj == null)
                        {
                            userSourceServiceObj = new tUserSourceService();
                            userSourceServiceObj.SourceServiceID     = sourceServiceObj.ID;
                            userSourceServiceObj.UserID              = credentialObj.UserID;
                            userSourceServiceObj.CredentialID        = credentialObj.ID;
                            userSourceServiceObj.ConnectedOnDateTime = DateTime.Now;
                            userSourceServiceObj.LastSyncDateTime    = DateTime.Now;
                            userSourceServiceObj.LatestDateTime      = value.updatedAt;
                            userSourceServiceObj.StatusID            = 3; //connected
                            userSourceServiceObj.SystemStatusID      = 1; //valid
                            userSourceServiceObj.tCredential         = credentialObj;

                            db.tUserSourceServices.Add(userSourceServiceObj);
                        }
                        else
                        {
                            //update LatestDateTime to the most recent datetime
                            if (userSourceServiceObj.LatestDateTime == null ||
                                userSourceServiceObj.LatestDateTime < value.updatedAt)
                            {
                                userSourceServiceObj.LatestDateTime = value.updatedAt;
                            }
                        }
                    }

                    tSourceOrganization userSourceOrganization = null;
                    if (value.organization != null)
                    {
                        //Get source org
                        userSourceOrganization = db.tSourceOrganizations
                                                 .Include("tOrganization")
                                                 .SingleOrDefault(x => x.SourceObjectID == value.organization.id);

                        if (userSourceOrganization == null)
                        {
                            //create org
                            tOrganization userOrganization = new tOrganization();
                            userOrganization.Name = value.organization.name;

                            //create new source org entry
                            userSourceOrganization = new tSourceOrganization();
                            userSourceOrganization.SourceObjectID  = value.organization.id;
                            userSourceOrganization.tOrganization   = userOrganization;
                            userSourceOrganization.OrganizationID  = userOrganization.ID;
                            userSourceOrganization.SourceServiceID = sourceServiceObj.ID;

                            db.tSourceOrganizations.Add(userSourceOrganization);
                        }
                    }

                    List <tUserAllergy> userAllergies = db.tUserAllergies
                                                        .Include("tReaction")
                                                        .Where(x => x.SourceObjectID == value.Id).ToList() ?? new List <tUserAllergy>();

                    tUserAllergy newUserAllergy = new tUserAllergy();

                    //matching records for the SourceObjectID provided - do update & possibly insert
                    if (userAllergies.Count > 0)
                    {
                        //if reactions
                        if (value.reactionsFull != null)
                        {
                            foreach (Reaction allergyReaction in value.reactionsFull)
                            {
                                bool foundMatch = false;
                                //loop to find existing allergy with current reaction
                                foreach (tUserAllergy userAllergy in userAllergies)
                                {
                                    if (userAllergy.tReaction != null &&
                                        userAllergy.tReaction.Name == allergyReaction.name)
                                    {
                                        //update allergy/reaction with new data
                                        UpdateAllergy(newUserAllergy, value, allergyReaction, credentialObj, userSourceOrganization);

                                        foundMatch = true;
                                    }
                                }

                                //insert new allergy/reaction
                                if (foundMatch == false)
                                {
                                    newUserAllergy = CreateAllergy(newUserAllergy, value, null, credentialObj,
                                                                   userSourceServiceObj, userSourceOrganization);

                                    userAllergies.Add(newUserAllergy);
                                }
                            }
                        }
                        else if (userAllergies.Count == 1 && value.reactionsFull == null) //one allergen and no reactions
                        {
                            //update allergy with new data
                            UpdateAllergy(userAllergies[0], value, null, credentialObj, userSourceOrganization);
                        }
                        else
                        {
                            //this means multiple entries were made for same allergy with each reaction previously,
                            //but now no reactions are listed in new values. We cant do anything because we dont know
                            //which to invalidate or update.
                        }
                    }
                    //no existing entries - do insert
                    else
                    {
                        //if reactions
                        if (value.reactionsFull != null)
                        {
                            foreach (Reaction allergyReaction in value.reactionsFull)
                            {
                                newUserAllergy = CreateAllergy(newUserAllergy, value, allergyReaction, credentialObj, userSourceServiceObj, userSourceOrganization);
                            }

                            userAllergies.Add(newUserAllergy);
                        }
                        else //no reactions
                        {
                            newUserAllergy = CreateAllergy(newUserAllergy, value, null, credentialObj, userSourceServiceObj, userSourceOrganization);

                            userAllergies.Add(newUserAllergy);
                        }
                    }

                    db.SaveChanges();

                    dbContextTransaction.Commit();

                    return(Ok(userAllergies));
                }
                catch (Exception ex)
                {
                    dbContextTransaction.Rollback();

                    //Insert Error Log
                    tUserDataErrLog userErrorLog = new tUserDataErrLog();

                    userErrorLog.ErrTypeID   = (int)ErrorLogging.enumErrorType.Application;
                    userErrorLog.ErrSourceID = (int)AuditLogging.enumApplication.SFCBAL;
                    userErrorLog.Code        = ex.HResult.ToString();
                    userErrorLog.Description = ex.Message;
                    userErrorLog.Trace       = ex.StackTrace;

                    dbErr.tUserDataErrLogs.Add(userErrorLog);
                    dbErr.SaveChanges();

                    string ErrMsg = "An error occured and we have logged the error. Please try again later.";

                    Exception Err = new Exception(ErrMsg, ex);

                    return(InternalServerError(Err));
                }
            }
        }
Ejemplo n.º 22
0
        public IHttpActionResult Post(GeneticTrait value)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (value.humanId == null)
            {
                return(BadRequest());
            }

            using (var dbContextTransaction = db.Database.BeginTransaction())
            {
                try
                {
                    tUserSourceService userSourceServiceObj = null;

                    //Get credentials
                    tCredential credentialObj =
                        db.tCredentials.SingleOrDefault(x => x.SourceID == 5 && x.SourceUserID == value.humanId &&
                                                        x.SystemStatusID == 1);
                    if (credentialObj == null)
                    {
                        throw new NoUserCredentialsException("Unable to find any matching HAPI user credentials");
                    }
                    else
                    {
                        userSourceServiceObj = db.tUserSourceServices
                                               .SingleOrDefault(x => x.SourceServiceID == 1 && x.CredentialID == credentialObj.ID &&
                                                                x.SystemStatusID == 1);

                        if (userSourceServiceObj == null)
                        {
                            userSourceServiceObj = new tUserSourceService();
                            userSourceServiceObj.SourceServiceID     = 1;
                            userSourceServiceObj.UserID              = credentialObj.UserID;
                            userSourceServiceObj.CredentialID        = credentialObj.ID;
                            userSourceServiceObj.ConnectedOnDateTime = DateTime.Now;
                            userSourceServiceObj.LastSyncDateTime    = DateTime.Now;
                            userSourceServiceObj.LatestDateTime      = DateTime.Now;
                            userSourceServiceObj.StatusID            = 3; //connected
                            userSourceServiceObj.SystemStatusID      = 1; //valid
                            userSourceServiceObj.tCredential         = credentialObj;

                            db.tUserSourceServices.Add(userSourceServiceObj);
                        }
                        else
                        {
                            //update LatestDateTime to the most recent datetime
                            userSourceServiceObj.LatestDateTime = DateTime.Now;
                        }
                    }

                    tGeneticTrait geneticTrait = db.tGeneticTraits
                                                 .SingleOrDefault(x => x.Description == value.description && x.Trait == value.trait);
                    if (geneticTrait == null)
                    {
                        geneticTrait             = new tGeneticTrait();
                        geneticTrait.Description = value.description;
                        geneticTrait.Trait       = value.trait;

                        db.tGeneticTraits.Add(geneticTrait);
                        db.SaveChanges();
                    }

                    tUserGeneticTrait userGeneticTrait = db.tUserGeneticTraits
                                                         .SingleOrDefault(x => x.UserID == credentialObj.UserID && x.GeneticTraitID == geneticTrait.ID);

                    if (userGeneticTrait == null)
                    {
                        //insert
                        userGeneticTrait                     = new tUserGeneticTrait();
                        userGeneticTrait.UserID              = credentialObj.UserID;
                        userGeneticTrait.tUserSourceService  = userSourceServiceObj;
                        userGeneticTrait.UserSourceServiceID = userSourceServiceObj.ID;
                        userGeneticTrait.tGeneticTrait       = geneticTrait;

                        userGeneticTrait.SystemStatusID = 1;

                        userGeneticTrait.GeneticTraitID = geneticTrait.ID;

                        db.tUserGeneticTraits.Add(userGeneticTrait);
                    }

                    db.SaveChanges();

                    dbContextTransaction.Commit();

                    return(Ok(userGeneticTrait));
                }
                catch (Exception ex)
                {
                    dbContextTransaction.Rollback();

                    //Insert Error Log
                    tUserDataErrLog userErrorLog = new tUserDataErrLog();

                    userErrorLog.ErrTypeID   = (int)ErrorLogging.enumErrorType.Application;
                    userErrorLog.ErrSourceID = (int)AuditLogging.enumApplication.SFCBAL;
                    userErrorLog.Code        = ex.HResult.ToString();
                    userErrorLog.Description = ex.Message;
                    userErrorLog.Trace       = ex.StackTrace;

                    dbErr.tUserDataErrLogs.Add(userErrorLog);
                    dbErr.SaveChanges();

                    string ErrMsg = "An error occured and we have logged the error. Please try again later.";

                    Exception Err = new Exception(ErrMsg, ex);

                    return(InternalServerError(Err));
                }
            }
        }
Ejemplo n.º 23
0
        public IHttpActionResult Post(Meals value)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (value.source == null || value.humanId == null)
            {
                return(BadRequest());
            }
            using (var dbContextTransaction = db.Database.BeginTransaction())
            {
                try
                {
                    tDietCategory dietCategoryObj = db.tDietCategories.SingleOrDefault(x => x.Name == value.type);

                    if (dietCategoryObj == null)
                    {
                        dietCategoryObj      = new tDietCategory();
                        dietCategoryObj.Name = value.type;

                        db.tDietCategories.Add(dietCategoryObj);
                    }

                    tSourceService sourceServiceObj = db.tSourceServices
                                                      .SingleOrDefault(x => x.ServiceName == value.source && x.SourceID == 5);

                    if (sourceServiceObj == null)
                    {
                        sourceServiceObj             = new tSourceService();
                        sourceServiceObj.ServiceName = value.source;
                        sourceServiceObj.TypeID      = 2; //Wellness
                        sourceServiceObj.SourceID    = 5; //HumanAPI

                        db.tSourceServices.Add(sourceServiceObj);
                    }

                    tUserSourceService userSourceServiceObj = null;

                    //Get credentials
                    tCredential credentialObj = db.tCredentials.SingleOrDefault(x => x.SourceID == 5 &&
                                                                                x.SourceUserID == value.humanId &&
                                                                                x.SystemStatusID == 1);
                    if (credentialObj == null)
                    {
                        throw new NoUserCredentialsException("Unable to find any matching HAPI user credentials");
                    }
                    else
                    {
                        userSourceServiceObj = db.tUserSourceServices.SingleOrDefault(
                            x => x.SourceServiceID == sourceServiceObj.ID &&
                            x.CredentialID == credentialObj.ID &&
                            x.SystemStatusID == 1);

                        if (userSourceServiceObj == null)
                        {
                            userSourceServiceObj = new tUserSourceService();
                            userSourceServiceObj.SourceServiceID     = sourceServiceObj.ID;
                            userSourceServiceObj.UserID              = credentialObj.UserID;
                            userSourceServiceObj.CredentialID        = credentialObj.ID;
                            userSourceServiceObj.ConnectedOnDateTime = DateTime.Now;
                            userSourceServiceObj.LastSyncDateTime    = DateTime.Now;
                            userSourceServiceObj.LatestDateTime      = value.updatedAt;
                            userSourceServiceObj.StatusID            = 3; //connected
                            userSourceServiceObj.SystemStatusID      = 1; //valid
                            userSourceServiceObj.tCredential         = credentialObj;

                            db.tUserSourceServices.Add(userSourceServiceObj);
                        }
                        else
                        {
                            //update LatestDateTime to the most recent datetime
                            if (userSourceServiceObj.LatestDateTime == null ||
                                userSourceServiceObj.LatestDateTime < value.updatedAt)
                            {
                                userSourceServiceObj.LatestDateTime = value.updatedAt;
                            }
                        }
                    }

                    tUserDiet userDiet = null;
                    userDiet = db.tUserDiets
                               .SingleOrDefault(x => x.SourceObjectID == value.id);

                    if (userDiet == null)
                    {
                        userDiet = new tUserDiet();
                        userDiet.tUserSourceService  = userSourceServiceObj;
                        userDiet.tDietCategory       = dietCategoryObj;
                        userDiet.UserID              = credentialObj.UserID;
                        userDiet.SourceObjectID      = value.id;
                        userDiet.UserSourceServiceID = sourceServiceObj.ID;
                        userDiet.Name = value.name;
                        if (value.amount != null)
                        {
                            userDiet.Servings = value.amount.value;

                            //UOM
                            if (value.amount.unit != null)
                            {
                                tUnitsOfMeasure uom = null;
                                uom = db.tUnitsOfMeasures.SingleOrDefault(x => x.UnitOfMeasure == value.amount.unit);
                                if (uom == null)
                                {
                                    uom = new tUnitsOfMeasure();
                                    uom.UnitOfMeasure = value.amount.unit;

                                    db.tUnitsOfMeasures.Add(uom);
                                    //db.SaveChanges();
                                }

                                userDiet.tUnitsOfMeasure = uom;
                                userDiet.ServingUOMID    = uom.ID;
                            }
                        }
                        userDiet.DietCategoryID = dietCategoryObj.ID;

                        //Dates
                        DateTimeOffset dtoStart;
                        if (RESTfulBAL.Models.DynamoDB.Utilities.ConvertToDateTimeOffset(value.timestamp,
                                                                                         value.tzOffset,
                                                                                         out dtoStart))
                        {
                            userDiet.EnteredDateTime = dtoStart;
                        }
                        else
                        {
                            userDiet.EnteredDateTime = value.timestamp;
                        }

                        userDiet.SystemStatusID = 1;

                        db.tUserDiets.Add(userDiet);
                    }
                    else
                    {
                        userDiet.tUserSourceService = userSourceServiceObj;
                        userDiet.Name = value.name;
                        if (value.amount != null)
                        {
                            userDiet.Servings = value.amount.value;

                            //UOM
                            if (value.amount.unit != null)
                            {
                                tUnitsOfMeasure uom = null;
                                uom = db.tUnitsOfMeasures.SingleOrDefault(x => x.UnitOfMeasure == value.amount.unit);
                                if (uom == null)
                                {
                                    uom = new tUnitsOfMeasure();
                                    uom.UnitOfMeasure = value.amount.unit;

                                    db.tUnitsOfMeasures.Add(uom);
                                    //db.SaveChanges();
                                }

                                userDiet.tUnitsOfMeasure = uom;
                                userDiet.ServingUOMID    = uom.ID;
                            }
                        }
                        userDiet.DietCategoryID = dietCategoryObj.ID;

                        //Dates
                        DateTimeOffset dtoStart;
                        if (RESTfulBAL.Models.DynamoDB.Utilities.ConvertToDateTimeOffset(value.timestamp,
                                                                                         value.tzOffset,
                                                                                         out dtoStart))
                        {
                            userDiet.EnteredDateTime = dtoStart;
                        }
                        else
                        {
                            userDiet.EnteredDateTime = value.timestamp;
                        }

                        userDiet.LastUpdatedDateTime = DateTime.Now;
                    }

                    AddorUpdateNutrients(userDiet.ID, 170, value.calories, 460);
                    AddorUpdateNutrients(userDiet.ID, 161, value.carbohydrate, 5);
                    AddorUpdateNutrients(userDiet.ID, 248, value.fat, 5);
                    AddorUpdateNutrients(userDiet.ID, 209, value.protein, 5);
                    AddorUpdateNutrients(userDiet.ID, 214, value.sodium, 5);
                    AddorUpdateNutrients(userDiet.ID, 218, value.sugar, 5);
                    AddorUpdateNutrients(userDiet.ID, 177, value.fiber, 5);
                    AddorUpdateNutrients(userDiet.ID, 173, value.saturatedFat, 5);
                    AddorUpdateNutrients(userDiet.ID, 171, value.monounsaturatedFat, 5);
                    AddorUpdateNutrients(userDiet.ID, 172, value.polyunsaturatedFat, 5);
                    AddorUpdateNutrients(userDiet.ID, 164, value.cholesterol, 7);
                    AddorUpdateNutrients(userDiet.ID, 233, value.vitaminA, 7);
                    AddorUpdateNutrients(userDiet.ID, 238, value.vitaminC, 7);
                    AddorUpdateNutrients(userDiet.ID, 159, value.calcium, 7);
                    AddorUpdateNutrients(userDiet.ID, 190, value.iron, 7);
                    AddorUpdateNutrients(userDiet.ID, 207, value.potassium, 7);

                    db.SaveChanges();

                    dbContextTransaction.Commit();

                    return(Ok(userDiet));
                }
                catch (Exception ex)
                {
                    dbContextTransaction.Rollback();

                    //Insert Error Log
                    tUserDataErrLog userErrorLog = new tUserDataErrLog();

                    userErrorLog.ErrTypeID   = (int)ErrorLogging.enumErrorType.Application;
                    userErrorLog.ErrSourceID = (int)AuditLogging.enumApplication.SFCBAL;
                    userErrorLog.Code        = ex.HResult.ToString();
                    userErrorLog.Description = ex.Message;
                    userErrorLog.Trace       = ex.StackTrace;

                    dbErr.tUserDataErrLogs.Add(userErrorLog);
                    dbErr.SaveChanges();

                    string ErrMsg = "An error occured and we have logged the error. Please try again later.";

                    Exception Err = new Exception(ErrMsg, ex);

                    return(InternalServerError(Err));
                }
            }
        }
Ejemplo n.º 24
0
        public IHttpActionResult Post(Instructions value)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (value.source == null || value.access_token == null)
            {
                return(BadRequest());
            }

            using (var dbContextTransaction = db.Database.BeginTransaction())
            {
                try
                {
                    tSourceService sourceServiceObj = db.tSourceServices
                                                      .SingleOrDefault(x => x.ServiceName == value.source && x.SourceID == 5);

                    if (sourceServiceObj == null)
                    {
                        sourceServiceObj             = new tSourceService();
                        sourceServiceObj.ServiceName = value.source;
                        sourceServiceObj.TypeID      = 1; //Medical
                        sourceServiceObj.SourceID    = 5; //HumanAPI

                        db.tSourceServices.Add(sourceServiceObj);
                    }

                    tUserSourceService userSourceServiceObj = null;

                    //Get credentials
                    tCredential credentialObj =
                        db.tCredentials.SingleOrDefault(x => x.SourceID == 5 &&
                                                        x.AccessToken == value.access_token &&
                                                        x.SystemStatusID == 1);
                    if (credentialObj == null)
                    {
                        throw new NoUserCredentialsException("Unable to find any matching HAPI user credentials");
                    }
                    else
                    {
                        userSourceServiceObj = db.tUserSourceServices.SingleOrDefault(
                            x => x.SourceServiceID == sourceServiceObj.ID &&
                            x.CredentialID == credentialObj.ID &&
                            x.SystemStatusID == 1);

                        if (userSourceServiceObj == null)
                        {
                            userSourceServiceObj = new tUserSourceService();
                            userSourceServiceObj.SourceServiceID     = sourceServiceObj.ID;
                            userSourceServiceObj.UserID              = credentialObj.UserID;
                            userSourceServiceObj.CredentialID        = credentialObj.ID;
                            userSourceServiceObj.ConnectedOnDateTime = DateTime.Now;
                            userSourceServiceObj.LastSyncDateTime    = DateTime.Now;
                            userSourceServiceObj.LatestDateTime      = value.updatedAt;
                            userSourceServiceObj.StatusID            = 3; //connected
                            userSourceServiceObj.SystemStatusID      = 1; //valid
                            userSourceServiceObj.tCredential         = credentialObj;

                            db.tUserSourceServices.Add(userSourceServiceObj);
                        }
                        else
                        {
                            //update LatestDateTime to the most recent datetime
                            if (userSourceServiceObj.LatestDateTime == null ||
                                userSourceServiceObj.LatestDateTime < value.updatedAt)
                            {
                                userSourceServiceObj.LatestDateTime = value.updatedAt;
                            }
                        }
                    }

                    tSourceOrganization userSourceOrganization = null;
                    //Get source org via sourceserviceid [hack]
                    userSourceOrganization =
                        db.tSourceOrganizations.SingleOrDefault(x => x.SourceServiceID == sourceServiceObj.ID);

                    tUserInstruction userInstruction = null;
                    userInstruction = db.tUserInstructions
                                      .SingleOrDefault(x => x.SourceObjectID == value.Id);

                    if (userInstruction == null)
                    {
                        //insert
                        userInstruction = new tUserInstruction();
                        userInstruction.SourceObjectID = value.Id;
                        userInstruction.UserID         = credentialObj.UserID;
                        if (userSourceOrganization != null)
                        {
                            userInstruction.tSourceOrganization  = userSourceOrganization;
                            userInstruction.SourceOrganizationID = userSourceOrganization.ID;
                        }
                        userInstruction.tUserSourceService  = userSourceServiceObj;
                        userInstruction.UserSourceServiceID = userSourceServiceObj.ID;

                        userInstruction.Name = value.name;
                        userInstruction.Text = value.text;

                        userInstruction.StartDateTime  = value.dateTime;
                        userInstruction.SystemStatusID = 1;

                        db.tUserInstructions.Add(userInstruction);
                    }
                    else
                    {
                        //update
                        if (userSourceOrganization != null)
                        {
                            userInstruction.tSourceOrganization  = userSourceOrganization;
                            userInstruction.SourceOrganizationID = userSourceOrganization.ID;
                        }
                        userInstruction.tUserSourceService  = userSourceServiceObj;
                        userInstruction.UserSourceServiceID = userSourceServiceObj.ID;

                        userInstruction.Name = value.name;
                        userInstruction.Text = value.text;

                        userInstruction.StartDateTime       = value.dateTime;
                        userInstruction.LastUpdatedDateTime = DateTime.Now;
                    }

                    //codes
                    if (value.codes != null)
                    {
                        foreach (Codes code in value.codes)
                        {
                            if (code.code != null && code.codeSystem != null)
                            {
                                tCode instructionCode = null;
                                instructionCode = db.tCodes
                                                  .SingleOrDefault(x => x.Code == code.code && x.CodeSystem == code.codeSystem);
                                if (instructionCode == null)
                                {
                                    instructionCode                = new tCode();
                                    instructionCode.Code           = code.code;
                                    instructionCode.CodeSystem     = code.codeSystem;
                                    instructionCode.CodeSystemName = code.codeSystemName;
                                    instructionCode.Name           = code.name;

                                    db.tCodes.Add(instructionCode);
                                    db.SaveChanges();
                                }

                                tXrefUserInstructionsCode userXrefInsCodes = null;
                                userXrefInsCodes = db.tXrefUserInstructionsCodes
                                                   .SingleOrDefault(x => x.CodeID == instructionCode.ID &&
                                                                    x.UserInstructionID == userInstruction.ID);

                                if (userXrefInsCodes == null)
                                {
                                    userXrefInsCodes = new tXrefUserInstructionsCode();
                                    userXrefInsCodes.tUserInstruction  = userInstruction;
                                    userXrefInsCodes.tCode             = instructionCode;
                                    userXrefInsCodes.CodeID            = instructionCode.ID;
                                    userXrefInsCodes.UserInstructionID = userInstruction.ID;

                                    userInstruction.tXrefUserInstructionsCodes.Add(userXrefInsCodes);
                                }
                            }
                        }
                    }

                    db.SaveChanges();

                    dbContextTransaction.Commit();

                    return(Ok(userInstruction));
                }
                catch (Exception ex)
                {
                    dbContextTransaction.Rollback();

                    //Insert Error Log
                    tUserDataErrLog userErrorLog = new tUserDataErrLog();

                    userErrorLog.ErrTypeID   = (int)ErrorLogging.enumErrorType.Application;
                    userErrorLog.ErrSourceID = (int)AuditLogging.enumApplication.SFCBAL;
                    userErrorLog.Code        = ex.HResult.ToString();
                    userErrorLog.Description = ex.Message;
                    userErrorLog.Trace       = ex.StackTrace;

                    dbErr.tUserDataErrLogs.Add(userErrorLog);
                    dbErr.SaveChanges();

                    string ErrMsg = "An error occured and we have logged the error. Please try again later.";

                    Exception Err = new Exception(ErrMsg, ex);

                    return(InternalServerError(Err));
                }
            }
        }