Пример #1
0
        public MyProfileViewModel(User user)
        {
            mUser = user;

            if (user.UserPreference == null)
            {
                const int width = 315;
                user.UserPreference = new UserPreference();
                user.UserPreference.AdminPanelWidth = width;
                user.UserPreference.ControlPanelWidth = width;
                user.UserPreference.DocumentPanelWidth = 630;
                user.UserPreference.ElectricalPanelWidth = width;
                user.UserPreference.InstrumentPanelWidth = width;
                user.UserPreference.IssuePanelWidth = width;
                user.UserPreference.MechanicalPanelWidth = width;
                user.UserPreference.MobilePanelWidth = width;
                user.UserPreference.PipePanelWidth = width;
            }

            CmsWebServiceClient cmsWebServiceClient = new CmsWebServiceClient(Utils.WcfBinding, Utils.WcfEndPoint);

            cmsWebServiceClient.UserIsADefaultUserCompleted +=
                (s1, e1) =>
                {
                    UserIsADefaultUser = e1.Result;
                };

            cmsWebServiceClient.UserIsADefaultUserAsync(mUser.Id);
        }
Пример #2
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="user">Optional paramete. If not specified logged in user will be used</param>
        /// <returns></returns>
        public bool CanViewSensitiveIssues(Issue issue, User user = null)
        {
            if (user == null)
            {
                user = CMS.User;
            }

            return true;
        }
        public AddDistributionListUsersModel(int distributionListId)
        {
            mdistributionListId = distributionListId;

            var getDistributionListUsersTask = DatabaseLoader.GetDistributionListUsers(distributionListId);

            var tasks = new List<Task>
            {
                getDistributionListUsersTask
            };

            Task.Factory.ContinueWhenAll(tasks.ToArray(), x =>
            {
                CMS.UiFactory.StartNew(() =>
                {
                    List<int> distUserIds = (from c in getDistributionListUsersTask.Result select c.Id).ToList();

                    List<QuickUser> notInListUsers = (from u in CMS.Cache.ActiveUsers where !distUserIds.Contains(u.Id) select u).ToList();

                    foreach (QuickUser quickUser in notInListUsers)
                    {
                        User u = new User
                        {
                            RoleId = quickUser.RoleId,
                            Role = (from r in CMS.Cache.Roles where r.Id == quickUser.RoleId select r).FirstOrDefault(),
                            Id = quickUser.Id,
                            FirstName = quickUser.FirstName,
                            LastName = quickUser.LastName,
                            ActiveUser = quickUser.ActiveUser,
                            Checked = false

                        };

                        mUsers.Add(u);
                    }

                    SelectedUsers = new List<User>(); //clears the selection...
                    OkButtonCommand = new DelegateCommand<object>(OkButtonHander, CanExecuteOkButtonHandler);

                    OnDataSourceLoaded();
                    RaisePropertyChanged("Users");

                });
            });
        }
Пример #4
0
        private void CheckClientServerVersions(User user, string clientAssemblyFileversion)
        {
            if (user != null)
            {
                var wcfAssemblyFileVersion = CommonUtils.GetAssemblyFileVersion();

                if (wcfAssemblyFileVersion != clientAssemblyFileversion)
                {
                    log.Error("", "Client version '{0}' for User '{1}' is not the same as server version '{2}'",
                        clientAssemblyFileversion, user.FirstLastName, wcfAssemblyFileVersion);
                }
            }
        }
Пример #5
0
        ///// <summary>
        /////   Return list of Users
        ///// </summary>
        ///// <returns></returns>
        //public List<User> GetUsers(CmsEntities cee)
        //{
        //    var users = (from x in cee.Users orderby x.UserName select x).ToList();
        //    return users;
        //}
        /// <summary>
        ///     Save/Update User
        /// </summary>
        /// <param name="loggedInUserId"></param>
        /// <param name="user">The user.</param>
        /// <returns></returns>
        public DbOperationResult<User> SaveUser(int loggedInUserId, User user)
        {
            try
            {
                DbOperationResult<User> result = new DbOperationResult<User>();

                using (CmsEntities cee = new CmsEntities())
                {
                    var loggedInUserName = (from x in cee.Users where x.Id == loggedInUserId select x.FirstName + " " + x.LastName).FirstOrDefault();

                    //Check if the user exist
                    var originalUser = (from x in cee.Users.Include("Role").Include("UserPreference") where x.Id == user.Id select x).FirstOrDefault();

                    if (originalUser == null)
                    {
                        //Add new User
                        user.Role = null;
                        user.LastModified = String.Format("Last modified {0} by {1}", DateTime.Now, loggedInUserName);
                        cee.Users.Add(user);

                        cee.SaveChanges();
                        result.EntityResult = user;
                    }
                    else
                    {
                        //Update existing
                        originalUser.ActiveUser = user.ActiveUser;
                        originalUser.UserName = user.UserName;
                        originalUser.FirstName = user.FirstName;
                        originalUser.LastName = user.LastName;
                        originalUser.Password = user.Password;
                        originalUser.RoleId = user.Role.Id;
                        originalUser.Department = user.Department;

                        originalUser.JobTitle = user.JobTitle;
                        originalUser.BusinessPhone = user.BusinessPhone;
                        originalUser.MobilePhone = user.MobilePhone;
                        originalUser.EmailAddress = user.EmailAddress;

                        originalUser.LastModified = String.Format("Last modified {0} by {1}", DateTime.Now, loggedInUserName);

                        if (originalUser.UserPreference == null)
                        {
                            originalUser.UserPreference = new UserPreference();
                        }

                        originalUser.UserPreference.SummaryTabsExpanded = user.UserPreference.SummaryTabsExpanded;
                        originalUser.UserPreference.RevisionHistoryExpanded = user.UserPreference.RevisionHistoryExpanded;
                        originalUser.UserPreference.ShowDocumentPreview = user.UserPreference.ShowDocumentPreview;
                        originalUser.UserPreference.LoadDefaultSearchFilterAtStart = user.UserPreference.LoadDefaultSearchFilterAtStart;
                        originalUser.UserPreference.IgnoreCCEmail = user.UserPreference.IgnoreCCEmail;
                        originalUser.UserPreference.OpenMyIntrayFromEmailLinks = user.UserPreference.OpenMyIntrayFromEmailLinks;
                        originalUser.UserPreference.IncludeOnHoldRejectedInMyInTray = user.UserPreference.IncludeOnHoldRejectedInMyInTray;
                        originalUser.UserPreference.MyFavouriteNotifcationEmailOn = user.UserPreference.MyFavouriteNotifcationEmailOn;

                        originalUser.UserPreference.IssuePanelWidth = user.UserPreference.IssuePanelWidth;
                        originalUser.UserPreference.ControlPanelWidth = user.UserPreference.ControlPanelWidth;
                        originalUser.UserPreference.ElectricalPanelWidth = user.UserPreference.ElectricalPanelWidth;
                        originalUser.UserPreference.InstrumentPanelWidth = user.UserPreference.InstrumentPanelWidth;
                        originalUser.UserPreference.MechanicalPanelWidth = user.UserPreference.MechanicalPanelWidth;
                        originalUser.UserPreference.MobilePanelWidth = user.UserPreference.MobilePanelWidth;
                        originalUser.UserPreference.PipePanelWidth = user.UserPreference.PipePanelWidth;
                        originalUser.UserPreference.DocumentPanelWidth = user.UserPreference.DocumentPanelWidth;
                        originalUser.UserPreference.AdminPanelWidth = user.UserPreference.AdminPanelWidth;

                        cee.SaveChanges();
                        result.EntityResult = originalUser;
                    }
                }

                return result;
            }
            catch (Exception ex)
            {
                log.Error("", ex, ex.ToString());

                return BuildOperationalErrorResults<User>(ex);
            }
        }
Пример #6
0
        private List<IssueCategory> GetUserApprovalCategories(User user)
        {
            var categoriesIds = user.Role.RoleApprovalCategories.Select(x => x.IssueCategoryId).ToList();

            var categories = new List<IssueCategory>(CMS.Cache.IssueCategories.Where(x => categoriesIds.Contains(x.Id)));

            return categories;
        }
Пример #7
0
        public TimesheetListViewModel(int userId, TimesheetListView view)
        {
            mView = view;
            mUserId = userId;
            mCanExecuteOpenTimesheetButton = true;

            mYear = DateTime.Now.Year;

            mWeek = Weeks.FirstOrDefault();

            mMonth = DateTimeFormatInfo.CurrentInfo.GetMonthName(DateTime.Now.Month);

            mStatus = Statuses.FirstOrDefault();

            if (CMS.User.Id == userId)
            {
                mUser = CMS.User;

                Categories = GetUserApprovalCategories(CMS.User);

                DatabaseLoader.GetDefaultRoleApprovalCategoriesUsers(Categories.Select(x => x.Id).ToList()).ContinueWith(x =>
                {
                    CMS.UiFactory.StartNew(() =>
                    {
                        Users = x.Result;
                        RaisePropertyChanged("Users");
                        RaisePropertyChanged("SelectedUser");
                        RaisePropertyChanged("CategoriesString");

                        AddTimesheetButton.RaiseCanExecuteChanged();
                        ProcessSearchFilter();
                    });
                });
            }
            else
            {
                Task<User> getUserWithApprovalCategoriesTask = DatabaseLoader.GetUserWithApprovalCategories(userId);

                List<Task> tasks = new List<Task>
                {
                    getUserWithApprovalCategoriesTask
                };

                Task.Factory.ContinueWhenAll(tasks.ToArray(), x =>
                {
                    mUser = getUserWithApprovalCategoriesTask.Result;

                    Categories = GetUserApprovalCategories(mUser);

                    DatabaseLoader.GetDefaultRoleApprovalCategoriesUsers(Categories.Select(y => y.Id).ToList()).ContinueWith(y =>
                    {
                        CMS.UiFactory.StartNew(() =>
                        {
                            Users = y.Result;
                            RaisePropertyChanged("Users");
                            RaisePropertyChanged("SelectedUser");
                            RaisePropertyChanged("CategoriesString");

                            AddTimesheetButton.RaiseCanExecuteChanged();
                            ProcessSearchFilter();
                        });
                    });
                });
            }

            AddTimesheetButton = new DelegateCommand<object>(AddTimesheetButtonHandler, CanExecuteAddTimesheetButtonHandler);
            OpenTimesheetButton = new DelegateCommand<object>(OpenTimesheetButtonHandler, CanExecuteOpenTimesheetButtonHandler);
            CategoriesPickerButton = new DelegateCommand<object>(CategoriesPickerButtonHandler, xx => (CMS.EffectivePrivileges.AdminTab.CanModify && SelectedUser != null && SelectedUser.Id < 0));

            ExportButton = new DelegateCommand<object>(ExportButtonHandler, x => true);
        }
Пример #8
0
        public void ImportUsers()
        {
            mForm.AddMessage(MessageType.Info, "-------------------- Importing Users --------------------");
            List<User> users = (from x in mOldIssuesDataContext.Users select x).ToList();
            List<CmsEquipmentDatabase.CmsWebService.User> existingUsers = (from x in mCee.Users select x).ToList();
            List<CmsEquipmentDatabase.CmsWebService.Role> existingRoles = (from x in mCee.Roles select x).ToList();

            //mCee.ExecuteStoreCommand("SET IDENTITY_INSERT [Security].[User] ON");
            var identityOn = "SET IDENTITY_INSERT [Security].[User] ON;";
            var identityOff = "SET IDENTITY_INSERT [Security].[User] OFF;";

            foreach (var user in users)
            {
                CmsEquipmentDatabase.CmsWebService.User newUser = new CmsEquipmentDatabase.CmsWebService.User();

                var role = (from x in existingRoles where x.Name == user.SecurityLevel.Name select x).FirstOrDefault();

                var sql = "INSERT [security].[User] ([Id], [RoleId], [UserName], [FirstName], [LastName], [JobTitle], [Department], [BusinessPhone]," +
                          " [MobilePhone], [Password], [EmailAddress], [ActiveUser])" +
                          " VALUES ({0}, {1}, '{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}',{11});";

                sql = string.Format(sql,
                                user.Id,
                                role.Id,
                                user.UserName,
                                user.FirstName.Replace("'", "''"),
                                user.LastName.Replace("'","''"),
                                user.JobTitle.Replace("'", "''"),
                                user.Department.Replace("'", "''"),
                                user.BusinessPhone,
                                user.MobilePhone,
                                user.Password,
                                user.EmailAddress == null ? "" : user.EmailAddress.Replace("'", "''"),
                                user.ActiveUser == true ? "1" : "0");

                sql = string.Format("{0}{1}{2}", identityOn, sql, identityOff);

                mCee.ExecuteStoreCommand(sql);

            }

            mCee.SaveChanges();

            //mCee.ExecuteStoreCommand("SET IDENTITY_INSERT [Security].[User] OFF");

            //Assign default User to Category
            var categories = (from x in mCee.IssueCategories select x).ToList();
        }
Пример #9
0
        public override DbImportResult Import(bool canCreateProperties = false)
        {
            DbImportResult = new DbImportResult();

            if (MetaData.ImportType != CommonUtils.ImportType.CreateTuningProperties && MetaData.ImportType != CommonUtils.ImportType.UpdateTuningProperties)
            {
                DbImportResult.ErrorMessages.Add(IMPORT_TYPE_NOT_COMPATIBLE);
                return DbImportResult;
            }

            CanCreateProperties = false;

            mUser = (from x in Cee.Users where x.Id == MetaData.UserId select x).FirstOrDefault();

            if (mUser == null)
            {
                DbImportResult.ErrorMessages.Add(string.Format(BuildItemNotFoundInDatabaseMessage("UserId", MetaData.UserId.ToString())));
                return DbImportResult;
            }

            IList<TuningPropertiesDataAdapter> importData = new List<TuningPropertiesDataAdapter>();

            string connString = BuildConnectionString(MetaData.FullFileName);

            using (var excelConn = new OleDbConnection(connString))
            {
                try
                {
                    using (var cmd = new OleDbCommand())
                    {
                        cmd.CommandTimeout = 600;
                        cmd.Connection = excelConn;
                        cmd.CommandText = string.Format(@"SELECT * FROM [{0}$] WHERE [{1}] IS NOT NULL", WorkSheetName, TuningPropertyColumn.ControlSystemName);

                        excelConn.Open();

                        if (!WorkSheetCheckColumnNamesAreValid<TuningPropertyColumn>(GetColumnHeadersFromDataSet(cmd, (int)TuningPropertyColumn.ComponentName)))
                        {
                            DbImportResult.ErrorMessages.Add(ExcelWorkSheetColumnsNotValidMessage());
                            return DbImportResult;
                        }

                        const int STARTCOLUMN = (int)TuningPropertyColumn.ComponentName;
                        List<string> dynamicProperyNames = GetDynamicProperties(cmd, STARTCOLUMN);

                        int k = 1;
                        using (OleDbDataReader dr = cmd.ExecuteReader())
                        {
                            while (dr.Read())
                            {
                                k++;

                                try
                                {
                                    var adapter = new TuningPropertiesDataAdapter(dr, dynamicProperyNames, STARTCOLUMN + 1);
                                    importData.Add(adapter);
                                }
                                catch (Exception ex)
                                {
                                    DbImportResult.ErrorMessages.Add(string.Format("EngineeringPropertyDataAdapter row {0} - {1}", k, ex.Message));
                                }
                            }

                            excelConn.Close();
                        }
                    }

                    if (MetaData.ImportType == CommonUtils.ImportType.CreateTuningProperties)
                    {
                        InsertData(importData);
                    }
                    else if (MetaData.ImportType == CommonUtils.ImportType.UpdateTuningProperties)
                    {
                        UpdateData(importData);
                    }

                    DbImportResult.ImportedCount = mSavedResults.Count;
                    return DbImportResult;
                }
                catch (OleDbException ex)
                {
                    DbImportResult.ErrorMessages.Add(ex.ToString());

                    return DbImportResult;
                }

                finally
                {
                    if (excelConn.State == ConnectionState.Open)
                    {
                        excelConn.Close();
                    }
                }
            }
        }
Пример #10
0
        private EmailNotification GetEmailNotificationObject(IssueModifications issueModifications, User user, CmsEntities cee)
        {
            log.Verbose("GetEmailNotificationObject()");
            //Process only if its enable in web.config
            string emailEnabledSettingValue = CommonUtils.GetAppSettingValue(CommonUtils.AppSettingKey.EmailSendEnabled);

            string disableEmailUpdatesFromAdminUserSettingValue = "false";

            int sysAdminRoleId = (from x in cee.Roles where x.Name.Equals("SYS-ADMIN", StringComparison.CurrentCultureIgnoreCase) select x.Id).FirstOrDefault();

            if (user.RoleId == sysAdminRoleId)
            {
                disableEmailUpdatesFromAdminUserSettingValue = CommonUtils.GetAppSettingValue(CommonUtils.AppSettingKey.DisableEmailUpdatesFromAdminUser);
            }

            if (emailEnabledSettingValue.ToLower() == "true" && disableEmailUpdatesFromAdminUserSettingValue.ToLower() == "false")
            {
                IEnumerable<IEmailNotificatonPlugin> plugins = Util.GetIssueEmailNotificatonPlugins();

                // ReSharper disable once PossibleMultipleEnumeration
                if (plugins.Any())
                {
                    //take first we find.
                    // ReSharper disable once PossibleMultipleEnumeration
                    IEmailNotificatonPlugin plugin = (from x in plugins select x).FirstOrDefault();
                    if (plugin != null)
                    {
                        return plugin.GetEmailNotificationObject(issueModifications);
                    }
                    else
                    {
                        log.Warning("", "GetEmailNotificationObject - no plugins found!");
                    }
                }
                else
                {
                    log.Warning("", "GetEmailNotificationObject - no plugins found!");
                }
            }
            else
            {
                if (emailEnabledSettingValue.ToLower() != "true") log.Info("Send Email Setting is set to False. Will not send email.");
                else if (disableEmailUpdatesFromAdminUserSettingValue.ToLower() != "false") log.Info("Disable Updates From Admin User Setting is set to True. Will not send email.");
            }
            return null;
        }
Пример #11
0
        private static bool MatchTestebByUserFailed(CmsEntities cee, OldCmsEntities old, Alarm oldAlarm, out User matchedTestedUser)
        {
            matchedTestedUser = null;

            if (oldAlarm.TestedUserId.HasValue)
            {
                matchedTestedUser = (from x in cee.Users
                                     where x.Id == oldAlarm.TestedUserId.Value
                                     select x).FirstOrDefault();

                if (matchedTestedUser == null)
                {
                    Logger.Out(string.Format("MatchTestebByUserFailed on Alarm ID {0}:- failed to match 'TestedUserId' in NEW CMS by id '{1}'. ", oldAlarm.Id, oldAlarm.TestedUserId.Value));
                    return true;
                }
            }
            return false;
        }
Пример #12
0
        public override DbImportResult Import(bool canCreateProperties = false)
        {
            DbImportResult = new DbImportResult();

            if (MetaData.ImportType != CommonUtils.ImportType.CreateInterlockRisks && MetaData.ImportType != CommonUtils.ImportType.UpdateInterlockRisks)
            {
                DbImportResult.ErrorMessages.Add(IMPORT_TYPE_NOT_COMPATIBLE);
                return DbImportResult;
            }

            CanCreateProperties = false;

            mExistingInterlockRiskCategorys = Cee.InterlockRiskCategories.ToList();
            mExistInterlockTypes = Cee.InterlockTypes.ToList();

            mUser = (from x in Cee.Users where x.Id == MetaData.UserId select x).FirstOrDefault();

            if (mUser == null)
            {
                DbImportResult.ErrorMessages.Add(string.Format(BuildItemNotFoundInDatabaseMessage("UserId", MetaData.UserId.ToString(CultureInfo.CurrentCulture))));

                return DbImportResult;
            }

            IList<InterlockRiskDataAdapter> importData = new List<InterlockRiskDataAdapter>();
            string connString = BuildConnectionString(MetaData.FullFileName);

            using (var excelConn = new OleDbConnection(connString))
            {
                try
                {
                    using (var cmd = new OleDbCommand())
                    {
                        cmd.CommandTimeout = 600;
                        cmd.Connection = excelConn;
                        cmd.CommandText = string.Format(@"SELECT * FROM [{0}$] WHERE [{1}] IS NOT NULL", WorkSheetName, InterlockRiskColumn.ControlSystemName);

                        excelConn.Open();

                        if (!WorkSheetCheckColumnNamesAreValid<InterlockRiskColumn>(GetColumnHeadersFromDataSet(cmd, (int) InterlockRiskColumn.Description)))
                        {
                            DbImportResult.ErrorMessages.Add(ExcelWorkSheetColumnsNotValidMessage());
                            return DbImportResult;
                        }

                        int k = 1;
                        using (OleDbDataReader dr = cmd.ExecuteReader())
                        {
                            while (dr.Read())
                            {
                                k++;

                                try
                                {
                                    var adapter = new InterlockRiskDataAdapter(dr);
                                    importData.Add(adapter);
                                }
                                catch (Exception ex)
                                {
                                    DbImportResult.ErrorMessages.Add(string.Format("InterlockDataAdapter row {0} - {1}", k, ex.Message));
                                }
                            }

                            excelConn.Close();
                        }
                    }

                    if (MetaData.ImportType == CommonUtils.ImportType.CreateInterlockRisks)
                    {
                        InsertData(importData);
                    }
                    else if (MetaData.ImportType == CommonUtils.ImportType.UpdateInterlockRisks)
                    {
                        UpdateData(importData);
                    }

                    DbImportResult.ImportedCount = mOutPutResults.Count;
                    return DbImportResult;
                }
                catch (OleDbException ex)
                {
                    DbImportResult.ErrorMessages.Add(ex.ToString());

                    return DbImportResult;
                }

                finally
                {
                    if (excelConn.State == ConnectionState.Open)
                    {
                        excelConn.Close();
                    }
                }
            }
        }