aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/MachineStudio/Modules/Tango.MachineStudio.UsersAndRoles/ViewModels/MainViewVM.cs
blob: 16395d6bc85336c30877a4ad6e984013e43c7e6f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
pre { line-height: 125%; }
td.linenos .normal { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
span.linenos { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
td.linenos .special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
span.linenos.special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
.highlight .hll { background-color: #ffffcc }
.highlight .c { color: #888888 } /* Comment */
.highlight .err { color: #a61717; background-color: #e3d2d2 } /* Error */
.highlight .k { color: #008800; font-weight: bold } /* Keyword */
.highlight .ch { color: #888888 } /* Comment.Hashbang */
.highlight .cm { color: #888888 } /* Comment.Multiline */
.highlight .cp { color: #cc0000; font-weight: bold } /* Comment.Preproc */
.highlight .cpf { color: #888888 } /* Comment.PreprocFile */
.highlight .c1 { color: #888888 } /* Comment.Single */
.highlight .cs { color: #cc0000; font-weight: bold; background-color: #fff0f0 } /* Comment.Special */
.highlight .gd { color: #000000; background-color: #ffdddd } /* Generic.Deleted */
.highlight .ge { font-style: italic } /* Generic.Emph */
.highlight .ges { font-weight: bold; font-style: italic } /* Generic.EmphStrong */
.highlight .gr { color: #aa0000 } /* Generic.Error */
.highlight .gh { color: #333333 } /* Generic.Heading */
.highlight .gi { color: #000000; background-color: #ddffdd } /* Generic.Inserted */
.highlight .go { color: #888888 } /* Generic.Output */
.highlight .gp { color: #555555 } /* Generic.Prompt */
.highlight .gs { font-weight: bold } /* Generic.Strong */
.highlight .gu { color: #666666 } /* Generic.Subheading */
.highlight .gt { color: #aa0000 } /* Generic.Traceback */
.highlight .kc { color: #008800; font-weight: bold } /* Keyword.Constant */
.highlight .kd { color: #008800; font-weight: bold } /* Keyword.Declaration */
.highlight .kn { color: #008800; font-weight: bold } /* Keyword.Namespace */
.highlight .kp { color: #008800 } /* Keyword.Pseudo */
.highlight .kr { color: #008800; font-weight: bold } /* Keyword.Reserved */
.highlight .kt { color: #888888; font-weight: bold } /* Keyword.Type */
.highlight .m { color: #0000DD; font-weight: bold } /* Literal.Number */
.highlight .s { color: #dd2200; background-color: #fff0f0 } /* Literal.String */
.highlight .na { color: #336699 } /* Name.Attribute */
.highlight .nb { color: #003388 } /* Name.Builtin */
.highlight .nc { color: #bb0066; font-weight: bold } /* Name.Class */
.highlight .no { color: #003366; font-weight: bold } /* Name.Constant */
.highlight .nd { color: #555555 } /* Name.Decorator */
.highlight .ne { color: #bb0066; font-weight: bold } /* Name.Exception */
.highlight .nf { color: #0066bb; font-weight: bold } /* Name.Function */
.highlight .nl { color: #336699; font-style: italic } /* Name.Label */
.highlight .nn { color: #bb0066; font-weight: bold } /* Name.Namespace */
.highlight .py { color: #336699; font-weight: bold } /* Name.Property */
.highlight .nt { color: #bb0066; font-weight: bold } /* Name.Tag */
.highlight .nv { color: #336699 } /* Name.Variable */
.highlight .ow { color: #008800 } /* Operator.Word */
.highlight .w { color: #bbbbbb } /* Text.Whitespace */
.highlight .mb { color: #0000DD; font-weight: bold } /* Literal.Number.Bin */
.highlight .mf { color: #0000DD; font-weight: bold } /* Literal.Number.Float */
.highlight .mh { color: #0000DD; font-weight: bold } /* Literal.Number.Hex */
.highlight .mi { color: #0000DD; font-weight: bold } /* Literal.Number.Integer */
.highlight .mo { color: #0000DD; font-weight: bold } /* Literal.Number.Oct */
.highlight .sa { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Affix */
.highlight .sb { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Backtick */
.highlight .sc { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Char */
.highlight .dl { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Delimiter */
.highlight .sd { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Doc */
.highlight .s2 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Double */
.highlight .se { color: #0044dd; background-color: #fff0f0 } /* Literal.String.Escape */
.highlight .sh { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Heredoc */
.highlight .si { color: #3333bb; background-color: #fff0f0 } /* Literal.String.Interpol */
.highlight .sx { color: #22bb22; background-color: #f0fff0 } /* Literal.String.Other */
.highlight .sr { color: #008800; background-color: #fff0ff } /* Literal.String.Regex */
.highlight .s1 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Single */
.highlight .ss { color: #aa6600; background-color: #fff0f0 } /* Literal.String.Symbol */
.highlight .bp { color: #003388 } /* Name.Builtin.Pseudo */
.highlight .fm { color: #0066bb; font-weight: bold } /* Name.Function.Magic */
.highlight .vc { color: #336699 } /* Name.Variable.Class */
.highlight .vg { color: #dd7700 } /* Name.Variable.Global */
.highlight .vi { color: #3333bb } /* Name.Variable.Instance */
.highlight .vm { color: #336699 } /* Name.Variable.Magic */
.highlight .il { color: #0000DD; font-weight: bold } /* Literal.Number.Integer.Long */
using System;
using System.Runtime;
using System.Runtime.InteropServices;

namespace System.Windows.Media.Imaging
{
    internal static class NativeMethods
    {
        [TargetedPatchingOptOut("Internal method only, inlined across NGen boundaries for performance reasons")]
        internal static unsafe void CopyUnmanagedMemory(byte* srcPtr, int srcOffset, byte* dstPtr, int dstOffset, int count)
        {
            srcPtr += srcOffset;
            dstPtr += dstOffset;

            memcpy(dstPtr, srcPtr, count);
        }

        [TargetedPatchingOptOut("Internal method only, inlined across NGen boundaries for performance reasons")]
        internal static void SetUnmanagedMemory(IntPtr dst, int filler, int count)
        {
            memset(dst, filler, count);
        }

        // Win32 memory copy function
        //[DllImport("ntdll.dll")]
        [DllImport("msvcrt.dll", EntryPoint = "memcpy", CallingConvention = CallingConvention.Cdecl, SetLastError = false)]
        private static extern unsafe byte* memcpy(
            byte* dst,
            byte* src,
            int count);
        
        // Win32 memory set function
        //[DllImport("ntdll.dll")]
        //[DllImport("coredll.dll", EntryPoint = "memset", SetLastError = false)]
        [DllImport("msvcrt.dll", EntryPoint = "memset", CallingConvention = CallingConvention.Cdecl, SetLastError = false)]
        private static extern void memset(
            IntPtr dst,
            int filler,
            int count);
    }
}
f='#n391'>391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using Tango.BL;
using Tango.BL.Entities;
using Tango.Core.Commands;
using Tango.MachineStudio.Common;
using Tango.MachineStudio.Common.Notifications;
using Tango.MachineStudio.UsersAndRoles.Navigation;
using Tango.MachineStudio.UsersAndRoles.Providers;
using Tango.SharedUI;
using System.Data.Entity;
using Tango.BL.Builders;
using Tango.BL.ActionLogs;
using Tango.BL.DTO;
using Tango.BL.Enumerations;
using Tango.MachineStudio.Common.Authentication;

namespace Tango.MachineStudio.UsersAndRoles.ViewModels
{
    public class MainViewVM : StudioViewModel
    {
        private ObservablesContext _organizationsContext;
        private ObservablesContext _manageContext;
        private ObservablesContext _userContext;
        private UsersAndRolesNavigationManager _navigation;
        private INotificationProvider _notification;
        private IActionLogManager _actionLogManager;
        private OrganizationDTO _organizationBeforeSave;
        private IAuthenticationProvider _authenticationProvider;
        private UserDTO _userBeforeSave;

        private ObservableCollection<Organization> _organizations;
        public ObservableCollection<Organization> Organizations
        {
            get { return _organizations; }
            set { _organizations = value; RaisePropertyChangedAuto(); }
        }

        private Organization _selectedOrganization;
        public Organization SelectedOrganization
        {
            get { return _selectedOrganization; }
            set { _selectedOrganization = value; RaisePropertyChangedAuto(); }
        }

        private Organization _managedOrganization;
        public Organization ManagedOrganization
        {
            get { return _managedOrganization; }
            set { _managedOrganization = value; RaisePropertyChangedAuto(); }
        }

        private ObservableCollection<Role> _roles;
        public ObservableCollection<Role> Roles
        {
            get { return _roles; }
            set { _roles = value; RaisePropertyChangedAuto(); }
        }

        private ObservableCollection<Role> _managedUserRoles;
        public ObservableCollection<Role> ManagedUserRoles
        {
            get { return _managedUserRoles; }
            set { _managedUserRoles = value; RaisePropertyChangedAuto(); }
        }

        private User _selectedUser;
        public User SelectedUser
        {
            get { return _selectedUser; }
            set { _selectedUser = value; RaisePropertyChangedAuto(); }
        }

        private User _managedUser;
        public User ManagedUser
        {
            get { return _managedUser; }
            set { _managedUser = value; RaisePropertyChangedAuto(); }
        }

        private Place _selectedUserPlace;
        public Place SelectedUserPlace
        {
            get { return _selectedUserPlace; }
            set
            {
                _selectedUserPlace = value;

                if (_selectedUserPlace != null && _selectedUserPlace.Address != null)
                {
                    SetUserPlace(value);
                }
            }
        }

        private Place _selectedOrganizationPlace;
        public Place SelectedOrganizationPlace
        {
            get { return _selectedOrganizationPlace; }
            set
            {
                _selectedOrganizationPlace = value;

                if (_selectedOrganizationPlace != null && _selectedOrganizationPlace.Address != null)
                {
                    SetOrganizationPlace(value);
                }
            }
        }

        private bool _showDeleted;
        public bool ShowDeleted
        {
            get { return _showDeleted; }
            set
            {
                _showDeleted = value;
                if (_showDeleted)
                {
                    //ShowDeletedUsers();
                }
            }
        }


        public RelayCommand ManageOrganizationCommand { get; set; }

        public RelayCommand BackToOrganizationsCommand { get; set; }

        public RelayCommand ManageUserCommand { get; set; }

        public RelayCommand SaveOrganizationCommand { get; set; }

        public RelayCommand AddOrganizationCommand { get; set; }

        public RelayCommand RemoveOrganizationCommand { get; set; }

        public RelayCommand BackToManagedOrganizationCommand { get; set; }

        public RelayCommand<Role> RemoveRoleCommand { get; set; }

        public RelayCommand SaveManagedUserCommand { get; set; }

        public RelayCommand RestoreAndSaveManagedUserCommand { get; set; }

        public RelayCommand AddUserCommand { get; set; }

        public RelayCommand RemoveUserCommand { get; set; }

        public MainViewVM(UsersAndRolesNavigationManager navigation, INotificationProvider notification, IActionLogManager actionLogManager, IAuthenticationProvider authenticationProvider)
        {
            _navigation = navigation;
            _notification = notification;
            _actionLogManager = actionLogManager;
            _authenticationProvider = authenticationProvider;

            ManageOrganizationCommand = new RelayCommand(LoadSelectedOrganization, () => SelectedOrganization != null);
            BackToOrganizationsCommand = new RelayCommand(BackToOrganizations);
            ManageUserCommand = new RelayCommand(LoadSelectedUser, () => SelectedUser != null);
            SaveOrganizationCommand = new RelayCommand(SaveOrganization);
            AddOrganizationCommand = new RelayCommand(AddOrganization);
            RemoveOrganizationCommand = new RelayCommand(RemoveOrganization, () => SelectedOrganization != null);
            BackToManagedOrganizationCommand = new RelayCommand(BackToManagedOrganization);
            RemoveRoleCommand = new RelayCommand<Role>(RemoveUserRole);
            SaveManagedUserCommand = new RelayCommand(SaveManagedUser);
            RestoreAndSaveManagedUserCommand = new RelayCommand(RestoreAndSaveManagedUser);
            AddUserCommand = new RelayCommand(AddNewUser);
            RemoveUserCommand = new RelayCommand(RemoveSelectedUser, () => SelectedUser != null);
            _showDeleted = false;
        }

        public override void OnApplicationReady()
        {
            LoadOrganizations();
        }

        private async void AddOrganization()
        {
            String name = _notification.ShowTextInput("Enter organization name", "Name");

            if (!String.IsNullOrWhiteSpace(name))
            {
                using (_notification.PushTaskItem("Adding new organization..."))
                {
                    Organization org = new Organization();
                    org.Name = name;
                    org.Address = new Address();
                    org.Contact = new Contact();
                    _organizationsContext.Organizations.Add(org);
                    await org.SaveAsync(_organizationsContext);
                    _actionLogManager.InsertLog(ActionLogType.OrganizationCreated, _authenticationProvider.CurrentUser, org.Name, org, "Organization created using Machine Studio.");
                    Organizations = _organizationsContext.Organizations.ToObservableCollection();
                    SelectedOrganization = org;
                    LoadSelectedOrganization();
                }
            }
        }

        private async void RemoveOrganization()
        {
            if (_notification.ShowQuestion("Are you sure you want to remove " + SelectedOrganization.Name + " organization?"))
            {
                using (_notification.PushTaskItem("Removing organization..."))
                {
                    await SelectedOrganization.DeleteCascadeAsync(_organizationsContext);
                    _actionLogManager.InsertLog(ActionLogType.OrganizationDeleted, _authenticationProvider.CurrentUser, SelectedOrganization.Name, SelectedOrganization, "Organization deleted using Machine Studio.");
                    await LoadOrganizations();
                }
            }
        }

        private async void SaveOrganization()
        {
            using (_notification.PushTaskItem("Saving organization address and contact..."))
            {
                var organizationAfter = OrganizationDTO.FromObservable(ManagedOrganization);

                await ManagedOrganization.SaveAsync(_manageContext);
                _actionLogManager.InsertLog(ActionLogType.OrganizationSaved, _authenticationProvider.CurrentUser, ManagedOrganization.Name, _organizationBeforeSave, organizationAfter, "Organization saved using Machine Studio.");

                _organizationBeforeSave = organizationAfter;

                await LoadOrganizations();
                SelectedOrganization = Organizations.SingleOrDefault(x => x.Guid == ManagedOrganization.Guid);
            }
        }

        private async void LoadSelectedUser()
        {
            using (_notification.PushTaskItem("Loading user details..."))
            {
                await Task.Factory.StartNew(() =>
                {
                    _userContext = ObservablesContext.CreateDefault();

                    Roles = new RolesCollectionBuilder(_userContext).SetAll().WithPermission().Build();
                    ManagedUser = new UserBuilder(_userContext).WithDeleted().Set(SelectedUser.Guid).WithRolesAndPermissions().Build();
                    ManagedUserRoles = ManagedUser.Roles.ToObservableCollection();

                    _userBeforeSave = UserDTO.FromObservable(ManagedUser);
                });

                _navigation.NavigateTo(UsersAndRolesNavigationView.UserManagementView);
            }
        }

        private void BackToOrganizations()
        {
            _navigation.NavigateTo(UsersAndRolesNavigationView.OrganizationSelectionView);
        }

        private void BackToManagedOrganization()
        {
            _navigation.NavigateTo(UsersAndRolesNavigationView.OrganizationManagementView);
        }

        private void RemoveUserRole(Role role)
        {
            ManagedUserRoles.Remove(role);

            foreach (var userRole in ManagedUser.UsersRoles.Where(x => x.Role == role).ToList())
            {
                _userContext.UsersRoles.Remove(userRole);
            }
        }

        private async void SaveManagedUser()
        {
            try
            {
                ManagedUser.Validate(_userContext);

                if (ManagedUser.Roles.GroupBy(x => x.RoleEnum).Any(x => x.Count() > 1))
                {
                    throw new InvalidOperationException("Cannot save user with duplicate roles.");
                }
            }
            catch (Exception ex)
            {
                _notification.ShowError(ex.Message);
                return;
            }

            using (_notification.PushTaskItem("Saving user details..."))
            {
                var userAfter = UserDTO.FromObservable(ManagedUser);
                await ManagedUser.SaveAsync(_userContext);
                _actionLogManager.InsertLog(ActionLogType.UserSaved, _authenticationProvider.CurrentUser, ManagedUser.Email, _userBeforeSave, userAfter, "User saved using Machine Studio.");
                _userBeforeSave = userAfter;
                LoadSelectedOrganization();
            }
        }

        private async void RestoreAndSaveManagedUser()
        {
            try
            {
                ManagedUser.Validate(_userContext);

                if (ManagedUser.Roles.GroupBy(x => x.RoleEnum).Any(x => x.Count() > 1))
                {
                    throw new InvalidOperationException("Cannot save user with duplicate roles.");
                }
            }
            catch (Exception ex)
            {
                _notification.ShowError(ex.Message);
                return;
            }
            if (_notification.ShowQuestion("Are you sure you wish to re-activate this account?"))
            {
                using (_notification.PushTaskItem("Saving user details..."))
                {
                    ManagedUser.Deleted = false;

                    var userAfter = UserDTO.FromObservable(ManagedUser);
                    await ManagedUser.SaveAsync(_userContext);
                    _actionLogManager.InsertLog(ActionLogType.UserRestored, _authenticationProvider.CurrentUser, ManagedUser.Email, _userBeforeSave, userAfter, "User restored using Machine Studio.");
                    _userBeforeSave = userAfter;
                    LoadSelectedOrganization();
                }
            }
        }

        private async void LoadSelectedOrganization()
        {
            using (_notification.PushTaskItem("Loading organization..."))
            {
                await Task.Factory.StartNew(() =>
                {
                    _manageContext = ObservablesContext.CreateDefault();

                    ManagedOrganization = new OrganizationBuilder(_manageContext).Set(SelectedOrganization.Guid).WithUsers(true).Build();

                    _organizationBeforeSave = OrganizationDTO.FromObservable(ManagedOrganization);
                });

                _navigation.NavigateTo(UsersAndRolesNavigationView.OrganizationManagementView);
            }
        }

        private Task LoadOrganizations()
        {
            return Task.Factory.StartNew(() =>
            {
                _organizationsContext = ObservablesContext.CreateDefault();

                Organizations = new OrganizationsCollectionBuilder(_organizationsContext).SetAll().WithUsers().WithMachines().Build();
            });
        }

        public void OnDropRole(Role role)
        {
            ManagedUser.UsersRoles.Add(new UsersRole()
            {
                Role = role,
                RoleGuid = role.Guid,
                User = ManagedUser,
                UserGuid = ManagedUser.Guid,
            });

            ManagedUserRoles.Add(role);
        }

        private async void RemoveSelectedUser()
        {
            if (_notification.ShowQuestion("Are you sure you want to remove the selected user?"))
            {
                using (_notification.PushTaskItem("Removing user..."))
                {
                    await SelectedUser.DeleteCascadeAsync(_manageContext);
                    _actionLogManager.InsertLog(ActionLogType.UserDeleted, _authenticationProvider.CurrentUser, SelectedUser.Email, SelectedUser, "User deleted using Machine Studio.");
                    LoadSelectedOrganization();
                }
            }
        }

        private void AddNewUser()
        {
            _notification.ShowModalDialog<UserCreationDialogVM>(async (vm) =>
            {
                User user = new User();
                user.Email = vm.Email;
                user.Password = User.GetPasswordHash(vm.Password);
                user.PasswordChangeRequired = true;
                user.Contact = new Contact()
                {
                    FirstName = vm.FirstName,
                    LastName = vm.LastName,
                    Email = vm.Email,
                };

                user.Address = new Address();

                user.UsersRoles.Add(new UsersRole()
                {
                    User = user,
                    Role = _manageContext.Roles.SingleOrDefault(x => x.Code == (int)BL.Enumerations.Roles.User)
                });

                user.UsersRoles.Add(new UsersRole()
                {
                    User = user,
                    Role = _manageContext.Roles.SingleOrDefault(x => x.Code == (int)BL.Enumerations.Roles.MachineStudioUser)
                });

                user.UsersRoles.Add(new UsersRole()
                {
                    User = user,
                    Role = _manageContext.Roles.SingleOrDefault(x => x.Code == (int)BL.Enumerations.Roles.PPCUser)
                });

                try
                {
                    if (!user.Validate(_manageContext))
                    {
                        _notification.ShowError(String.Join(Environment.NewLine, user.ValidationErrors));
                        return;
                    }
                }
                catch (Exception ex)
                {
                    _notification.ShowError(ex.Message);
                    return;
                }

                ManagedOrganization.Users.Add(user);

                using (_notification.PushTaskItem("Adding new user..."))
                {
                    await ManagedOrganization.SaveAsync(_manageContext);
                    _actionLogManager.InsertLog(ActionLogType.UserCreated, _authenticationProvider.CurrentUser, user.Email, user, "User created using Machine Studio.");
                    await LoadOrganizations();
                    SelectedOrganization = Organizations.SingleOrDefault(x => x.Guid == ManagedOrganization.Guid);
                    SelectedUser = user;
                    LoadSelectedUser();
                }
            });
        }

        private void SetUserPlace(Place place)
        {
            ManagedUser.Address.AddressString = place.Address.Road;
            ManagedUser.Address.City = place.Address.City;
            ManagedUser.Address.Country = place.Address.Country;
            ManagedUser.Address.CountryCode = place.Address.CountryCode;
            ManagedUser.Address.Locality = place.Address.CountryCode;
            ManagedUser.Address.PostalCode = place.Address.PostalCode;
            ManagedUser.Address.State = place.Address.State;
        }

        private void SetOrganizationPlace(Place place)
        {
            ManagedOrganization.Address.AddressString = place.Address.Road;
            ManagedOrganization.Address.City = place.Address.City;
            ManagedOrganization.Address.Country = place.Address.Country;
            ManagedOrganization.Address.CountryCode = place.Address.CountryCode;
            ManagedOrganization.Address.Locality = place.Address.CountryCode;
            ManagedOrganization.Address.PostalCode = place.Address.PostalCode;
            ManagedOrganization.Address.State = place.Address.State;
        }

        protected override void RaisePropertyChangedAuto([CallerMemberName] string caller = null)
        {
            base.RaisePropertyChangedAuto(caller);
            InvalidateRelayCommands();
        }
    }
}