public static int GetAccountId(string userName)
 {
     using (ActionTrackerEntities db = new ActionTrackerEntities())
     {
         return db.Accounts.Single(x => x.UserName == userName).AccountId;
     }
 }
 public static ActionItem Get(int actionItemId)
 {
     using (ActionTrackerEntities db = new ActionTrackerEntities())
     {
         return db.ActionItems.Find(actionItemId);
     }
 }
 public static string GetDisplayName(int id)
 {
     using (ActionTrackerEntities db = new ActionTrackerEntities())
     {
         Account acc = db.Accounts.Find(id);
         return acc.FirstName + " " + acc.LastName;
     }
 }
 public static bool RequestTransition(int id, int requestedBy)
 {
     using (ActionTrackerEntities db = new ActionTrackerEntities())
     {
         ActionItem item = db.ActionItems.Find(id);
         ActionItemWorkflow wf = new ActionItemWorkflow((Guid)item.InstanceId);
         wf.TryAdvance(requestedBy);
     }
     return true;
 }
 public static List<Account> Search(string term)
 {
     using (ActionTrackerEntities db = new ActionTrackerEntities())
     {
         List<Account> users = db.Accounts
             .Where(x => ((x.UserName.Contains(term)) || (x.FirstName.Contains(term)) || (x.LastName.Contains(term))))
             .ToList();
         return users;
     }
 }
        public static List<MergedItem> GetItems(int actionListId)
        {
            using (ActionTrackerEntities db = new ActionTrackerEntities())
            {
                List<ActionItem> items = db.ActionItems
                    .Where(x => x.ActionListId == actionListId)
                    .ToList();

                List<MergedItem> mergedItems = new List<MergedItem>();
                foreach (ActionItem item in items)
                {
                    mergedItems.Add(new MergedItem(item));
                }
                return mergedItems;
            }
        }
 public static int GetNumOverDueItems(int listId)
 {
     using (ActionTrackerEntities db = new ActionTrackerEntities())
     {
         List<ActionItem> listActions = db.ActionItems
             .Where(x => x.ActionListId == listId)
             .ToList();
         int numOverDue = 0;
         foreach (ActionItem item in listActions)
         {
             if (item.DueDate < DateTime.Now)
             {
                 numOverDue++;
             }
         }
         return numOverDue;
     }
 }
 public static int GetNumOpenItems(int listId)
 {
     using (ActionTrackerEntities db = new ActionTrackerEntities())
     {
         List<ActionItem> listActions = db.ActionItems
             .Where(x => x.ActionListId == listId)
             .ToList();
         int numOpen=0;
         foreach (ActionItem item in listActions)
         {
             if(ActionItemWorkflow.IsOpen((Guid)item.InstanceId))
             {
                 numOpen++;
             }
         }
         return numOpen;
     }
 }
 public static string CreateUserName(string firstName, string lastName)
 {
     int index = 0;
     using (ActionTrackerEntities db = new ActionTrackerEntities())
     {
         List<string> usernames = db.Accounts.Select(x => x.UserName).ToList();
         bool IsAvailable = false;
         IsAvailable = !(usernames.Contains(lastName + firstName.Substring(0, 2)));
         if (IsAvailable)
             return lastName + firstName.Substring(0, 2);
         while (!IsAvailable)
         {
             index++;
             IsAvailable = (!(usernames.Contains(lastName + firstName.Substring(0, 2) + index)));
         }
         return lastName + firstName.Substring(0, 2) + index;
     }
 }
        public static bool CanUserRequestTransition(int id, int requestedBy)
        {
            using (ActionTrackerEntities db = new ActionTrackerEntities())
            {
                ActionItem item = db.ActionItems.Find(id);
                ActionList list = db.ActionLists.Find(item.ActionListId);
                ActionItemWorkflow wf = new ActionItemWorkflow((Guid)item.InstanceId);

                if (wf.CurrentState.Name.ToLower() == "open")
                {
                    return true;
                }
                else if (requestedBy == item.AssignedTo || requestedBy == list.CreatedBy || wf.IsCompleted == false)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }
        public static bool Save(string userName, ElSignatureType sigType, ActionItem cachedItem)
        {
            try
            {
                //get audit trail items
                List<AuditTrail> atItems = new List<AuditTrail>();
                if(cachedItem.ActionItemId>0)
                    atItems = getAuditTrailItems(cachedItem);

                //If Create/Edit/Remove
                int recordId = 0;
                if (sigType == ElSignatureType.Record_Create || sigType == ElSignatureType.Record_Edit || sigType == ElSignatureType.Record_Remove)
                {
                    //SaveRecordData
                    recordId = saveRecordData(cachedItem, sigType);
                }

                //trap null value error;
                if (recordId == 0)
                    throw new NullReferenceException();

                if (sigType == ElSignatureType.Record_Create || sigType == ElSignatureType.Workflow_Create || sigType == ElSignatureType.Workflow_Transition)
                {
                    //SaveWorkflowData
                    using (ActionTrackerEntities db = new ActionTrackerEntities())
                    {
                        ActionItem loadedItem = db.ActionItems.Find(recordId);
                        ActionItemWorkflow aiwf = new ActionItemWorkflow();
                        Guid instanceId = aiwf.CreateInstance(loadedItem.ActionItemId, AccountRepos.GetAccountId(userName));

                        //update record with instanceId
                        loadedItem.InstanceId = instanceId;
                        db.Entry(loadedItem).State = EntityState.Modified;
                        db.SaveChanges();
                    }
                }

                //SaveESig();
                ESig es = new ESig()
                {
                    RecordId = recordId,
                    SignedBy = AccountRepos.GetAccountId(userName),
                    SignedDate = DateTime.Now,
                    TableName = typeof(ActionItem).Name,
                    IsComplete = true,
                    SignatureRole = enumToString(sigType)
                };
                using (ActionTrackerEntities db = new ActionTrackerEntities())
                {
                    db.Entry(es).State = EntityState.Added;
                    db.SaveChanges();

                    //update and save audit trail items with ESig and RecordIds, and changetype
                    foreach (AuditTrail item in atItems)
                    {
                        item.ESigId = es.ESigId;
                        item.RecordId = recordId;
                        item.ChangeType = es.SignatureRole;
                        db.Entry(item).State = EntityState.Added;
                        db.SaveChanges();
                    }
                }
            }
            catch (Exception Ex)
            {
                throw Ex;
                //TODO:
                //return false;
            }
            return true;
        }
        private static int saveRecordData(ActionItem cachedItem, ElSignatureType sigType)
        {
            using (ActionTrackerEntities db = new ActionTrackerEntities())
            {
                switch (sigType)
                {
                    case ElSignatureType.Record_Create:
                        db.Entry(cachedItem).State = EntityState.Added;
                        break;
                    case ElSignatureType.Record_Edit:
                        db.Entry(cachedItem).State = EntityState.Modified;
                        break;
                    case ElSignatureType.Record_Remove:
                        db.Entry(cachedItem).State = EntityState.Deleted;
                        break;
                }

                try
                {
                    db.SaveChanges();
                }
                catch (Exception ex)
                {
                    throw ex;
                    //TODO: remove the below
                    //return false;
                }
                return cachedItem.ActionItemId;
            }
        }
 private static List<AuditTrail> getAuditTrailItems(ActionItem cachedItem)
 {
     ActionItem oItem = new ActionItem();
     List<AuditTrail> atItems = new List<AuditTrail>();
     using(ActionTrackerEntities db = new ActionTrackerEntities())
     {
         oItem = db.ActionItems.Find(cachedItem.ActionItemId);
         foreach (PropertyInfo opi in oItem.GetType().GetProperties())
         {
             if (opi.PropertyType.IsPrimitive || opi.PropertyType.Equals(typeof(string)))
             {
                 var oVal = opi.GetValue(oItem,null).ToString();
                 var cVal = typeof(ActionItem).GetProperty(opi.Name).GetValue(cachedItem,null).ToString();
                 if (oVal != cVal)
                 {
                     atItems.Add(new AuditTrail()
                     {
                         FieldName = opi.Name,
                         FieldValueNew = cVal,
                         FieldValueOld = oVal,
                         TableName = typeof(AuditTrail).Name
                     });
                 }
             }
         }
         return atItems;
     }
 }
        public ActionResult Login(LoginModel model, string returnUrl)
        {
            using (ActionTrackerEntities db = new ActionTrackerEntities())
            {
                Account acc = db.Accounts.Single(x => x.Email == model.Email);
                if (!(bool)acc.IsEnabled)
                {
                    ModelState.AddModelError("", "Your account was blocked. Please contact the site administrator.");
                    return View(model);
                }

                bool AdminLoginOnlyAllowed = bool.Parse(System.Configuration.ConfigurationManager.AppSettings["AdminLoginOnlyAllowed"]);

                //TODO: import usersinroles table
                //TODO: check if user is an admin and check flag above and block if required

                if (ModelState.IsValid)
                {
                    bool ConfirmationRequired = bool.Parse(System.Configuration.ConfigurationManager.AppSettings["RegistrationRequiresConfirmation"]);
                    if (ConfirmationRequired)
                    {
                        if ((bool)db.webpages_Membership.Single(x => x.UserId == acc.AccountId).IsConfirmed)
                        {
                            if (WebSecurity.Login(acc.UserName, model.Password, persistCookie: model.RememberMe))
                            {
                                return RedirectToAction("MemberHome","Home");
                            }
                            else
                            {
                                ModelState.AddModelError("", "Your username or password is not correct");
                                return View(model);
                            }
                        }
                        else
                        {
                            ModelState.AddModelError("", "Your account is not activated. Please Check Your email and activate your account.");
                            return View(model);
                        }
                    }
                    else        //Confirmation Not Required
                    {
                        if (WebSecurity.Login(acc.UserName, model.Password, persistCookie: model.RememberMe))
                        {
                            return RedirectToAction("MemberHome","Home");
                        }
                        else
                        {
                            ModelState.AddModelError("", "Your username or password is not correct");
                            return View(model);
                        }
                    }
                }

                int maxBadLogins = int.Parse(System.Configuration.ConfigurationManager.AppSettings["MaxBadLogins"]);
                if (db.webpages_Membership.Single(x => x.UserId == acc.AccountId).PasswordFailuresSinceLastSuccess >= maxBadLogins)
                {
                    acc.IsEnabled = false;
                    db.Entry(acc).State = EntityState.Modified;
                    db.SaveChanges();
                    ModelState.AddModelError("", "Max Bad Login attempts reached. Your account has been blocked. Please reset your password");
                    //TODO: Notify User by email
                }
            }
            return View(model);
        }