aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/MachineStudio/Modules/Tango.MachineStudio.UsersAndRoles/Views/UserManagementView.xaml
blob: 2a8621e5c7b57819ada5735146b461a6602ce641 (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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
<UserControl x:Class="Tango.MachineStudio.UsersAndRoles.Views.UserManagementView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
              xmlns:global="clr-namespace:Tango.MachineStudio.UsersAndRoles"
             xmlns:vm="clr-namespace:Tango.MachineStudio.UsersAndRoles.ViewModels"
             xmlns:providers="clr-namespace:Tango.MachineStudio.UsersAndRoles.Providers"
             xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
             xmlns:dragAndDrop="clr-namespace:Tango.DragAndDrop;assembly=Tango.DragAndDrop"
             xmlns:autoComplete="clr-namespace:Tango.AutoComplete.Editors;assembly=Tango.AutoComplete"
             xmlns:controls="clr-namespace:Tango.SharedUI.Controls;assembly=Tango.SharedUI"
             xmlns:mahApps="http://metro.mahapps.com/winfx/xaml/controls"
             xmlns:entities="clr-namespace:Tango.BL.Entities;assembly=Tango.BL"
             xmlns:local="clr-namespace:Tango.MachineStudio.UsersAndRoles.Views"
             xmlns:converters="clr-namespace:Tango.SharedUI.Converters;assembly=Tango.SharedUI"
              xmlns:localconverters="clr-namespace:Tango.MachineStudio.UsersAndRoles.Converters"
             mc:Ignorable="d" 
             d:DesignHeight="1080" d:DesignWidth="1920" d:DataContext="{d:DesignInstance Type=vm:MainViewVM, IsDesignTimeCreatable=False}" DataContext="{x:Static global:ViewModelLocator.MainViewVM}">

    <UserControl.Resources>
        <providers:PlacesProvider x:Key="PlacesProvider" />
        <converters:BooleanToVisibilityConverter x:Key="BoolToVisibilityConverter"></converters:BooleanToVisibilityConverter>
        <converters:BooleanToVisibilityInverseConverter x:Key="BooleanToVisibilityInverseConverter"></converters:BooleanToVisibilityInverseConverter>
        <localconverters:RoleEnumToVisibleConverter x:Key="RoleEnumToVisibleConverter"/>
    </UserControl.Resources>
    
    <Grid>
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="1*"/>
                <ColumnDefinition Width="400"/>
            </Grid.ColumnDefinitions>

            <Grid Margin="10">
                <DockPanel Margin="100" MaxWidth="1200">
                    <Grid DockPanel.Dock="Top">
                        <Grid>
                            <StackPanel>
                                <StackPanel Orientation="Horizontal">
                                    <Button MinWidth="160" Height="50" Command="{Binding BackToManagedOrganizationCommand}" HorizontalAlignment="Left">
                                        <StackPanel Orientation="Horizontal">
                                            <materialDesign:PackIcon Kind="KeyboardBackspace" Width="20" Height="20" />
                                            <TextBlock Margin="5 0 0 0" FontSize="16">BACK</TextBlock>
                                        </StackPanel>
                                    </Button>
                                    <Image Source="../Images/user.png" Width="100" RenderOptions.BitmapScalingMode="Fant" Margin="130 0 0 0"></Image>
                                    <TextBlock Text="{Binding ManagedUser.Contact.FullName,FallbackValue='Roy Ben Shabat'}" VerticalAlignment="Center" FontSize="25" Margin="10 0 0 0"></TextBlock>
                                </StackPanel>

                                <StackPanel Orientation="Horizontal" Margin="0 20 0 0" HorizontalAlignment="Right">
                                    <StackPanel>
                                        <TextBlock FontSize="16" FontWeight="SemiBold">LOGIN</TextBlock>
                                        <Border Width="300" BorderThickness="1" BorderBrush="Gray" Margin="0 5 0 0" Padding="15 5" Height="150" Background="{StaticResource TransparentBackgroundBrush500}">
                                            <local:UserView VerticalAlignment="Top" Margin="0 15 0 0" FontSize="10" DataContext="{Binding ManagedUser}" />
                                        </Border>
                                    </StackPanel>
                                    <StackPanel Margin="10 0 0 0">
                                        <TextBlock FontSize="16" FontWeight="SemiBold">CONTACT</TextBlock>
                                        <Border Width="300" BorderThickness="1" BorderBrush="Gray" Margin="0 5 0 0" Padding="15 5" Height="250" Background="{StaticResource TransparentBackgroundBrush500}">
                                            <local:ContactView FontSize="10" DataContext="{Binding ManagedUser.Contact}" />
                                        </Border>
                                    </StackPanel>
                                    <StackPanel Margin="10 0 0 0">
                                        <TextBlock FontSize="16" FontWeight="SemiBold">ADDRESS</TextBlock>
                                        <Border Width="300" BorderThickness="1" BorderBrush="Gray" Margin="0 5 0 0" Padding="15 5" Height="300" Background="{StaticResource TransparentBackgroundBrush500}">
                                            <DockPanel>
                                                <DockPanel DockPanel.Dock="Top">
                                                    <materialDesign:PackIcon Kind="Magnify" DockPanel.Dock="Left" Width="24" Height="24" />
                                                    <autoComplete:AutoCompleteTextBox x:Name="address_auto" Margin="5 0 0 0" Delay="500" DisplayMember="DisplayName" SelectedItem="{Binding SelectedUserPlace,Mode=OneWayToSource}" Provider="{StaticResource PlacesProvider}" materialDesign:HintAssist.Hint="Find address" />
                                                </DockPanel>
                                                <local:AddressView FontSize="10" DataContext="{Binding ManagedUser.Address}" />
                                            </DockPanel>
                                        </Border>
                                    </StackPanel>
                                </StackPanel>
                            </StackPanel>
                        </Grid>
                    </Grid>
                    <Grid DockPanel.Dock="Bottom">
                        <Button Margin="0 10 0 0" MinWidth="200" Height="60" Command="{Binding SaveManagedUserCommand}" HorizontalAlignment="Right" Visibility="{Binding Path=ManagedUser.Deleted, Converter={StaticResource BooleanToVisibilityInverseConverter}}">
                            <StackPanel Orientation="Horizontal">
                                <TextBlock FontSize="18" VerticalAlignment="Center">SAVE</TextBlock>
                                <materialDesign:PackIcon Margin="5 0 0 0" Kind="ContentSave" Width="30" Height="30" />
                            </StackPanel>
                        </Button>
                        <Button Margin="0 10 0 0" MinWidth="200" Height="60" Background="{StaticResource OrangeBrush300}" BorderBrush="{StaticResource OrangeBrush300}" Command="{Binding RestoreAndSaveManagedUserCommand}" HorizontalAlignment="Right" Visibility="{Binding Path=ManagedUser.Deleted, Converter={StaticResource BoolToVisibilityConverter}}">
                            <StackPanel Orientation="Horizontal">
                                <TextBlock FontSize="18" VerticalAlignment="Center" Text="RESTORE &amp; SAVE"/>
                                <materialDesign:PackIcon Margin="5 0 0 0" Kind="ContentSave" Width="30" Height="30" />
                            </StackPanel>
                        </Button>
                    </Grid>
                    <Grid>
                        <DockPanel Margin="0 20 0 0">
                            <TextBlock DockPanel.Dock="Top" FontSize="16" FontWeight="SemiBold">ROLES</TextBlock>
                            <Grid Margin="0 5 0 0" Style="{StaticResource droppableGrid}" dragAndDrop:DragAndDropService.Drop="OnDropRole" Background="{StaticResource TransparentBackgroundBrush420}">
                                <TextBlock HorizontalAlignment="Center" VerticalAlignment="Top" Foreground="Silver" FontSize="20">DRAG &amp; DROP ROLES</TextBlock>
                                <Border BorderBrush="{StaticResource borderBrush}" BorderThickness="1" Padding="10">
                                    <ListBox ItemsSource="{Binding ManagedUserRoles}" ItemContainerStyle="{StaticResource basicListBoxItem}" ScrollViewer.HorizontalScrollBarVisibility="Disabled" ScrollViewer.VerticalScrollBarVisibility="Disabled">
                                        <ListBox.ItemsPanel>
                                            <ItemsPanelTemplate>
                                                <WrapPanel Orientation="Horizontal" />
                                            </ItemsPanelTemplate>
                                        </ListBox.ItemsPanel>
                                        <ListBox.ItemTemplate>
                                            <DataTemplate DataType="{x:Type entities:Role}">
                                                <Grid Visibility="{Binding RoleEnum, Converter={StaticResource RoleEnumToVisibleConverter}}">
                                                    <Grid.ToolTip>
                                                        <StackPanel Background="Transparent">
                                                            <TextBlock Text="{Binding Description}" FontSize="10" Margin="0 0 0 10"></TextBlock>
                                                            <ItemsControl ItemsSource="{Binding RolesPermissions}">
                                                                <ItemsControl.ItemTemplate>
                                                                    <DataTemplate>
                                                                        <Grid>
                                                                            <StackPanel Orientation="Horizontal">
                                                                                <materialDesign:PackIcon Kind="Security" Width="12" />
                                                                                <TextBlock Margin="5 0 0 0" FontSize="10" Text="{Binding Permission.Name}"></TextBlock>
                                                                            </StackPanel>
                                                                        </Grid>
                                                                    </DataTemplate>
                                                                </ItemsControl.ItemTemplate>
                                                            </ItemsControl>
                                                        </StackPanel>
                                                    </Grid.ToolTip>
                                                    <Border Margin="5" CornerRadius="5" Width="100" Height="100" BorderThickness="1" Padding="2" Background="{StaticResource UserRoles.Background}">
                                                        <Border.Style>
                                                            <Style TargetType="Border">
                                                                <Setter Property="BorderBrush" Value="{StaticResource borderBrush}"></Setter>
                                                                <Style.Triggers>
                                                                    <DataTrigger Binding="{Binding RelativeSource={RelativeSource AncestorType=ListBoxItem},Path=IsSelected}" Value="True">
                                                                        <Setter Property="BorderBrush" Value="{StaticResource AccentColorBrush}"></Setter>
                                                                    </DataTrigger>
                                                                </Style.Triggers>
                                                            </Style>
                                                        </Border.Style>
                                                        <Grid>
                                                            <StackPanel VerticalAlignment="Center" HorizontalAlignment="Center">
                                                                <Image Source="../Images/roles.png" Width="32" RenderOptions.BitmapScalingMode="Fant"></Image>
                                                                <TextBlock Text="{Binding Name}" TextWrapping="Wrap" HorizontalAlignment="Center" TextAlignment="Center" FontSize="13" Margin="5"></TextBlock>
                                                            </StackPanel>
                                                        </Grid>
                                                    </Border>

                                                    <Button HorizontalAlignment="Right" VerticalAlignment="Top" Margin="10" Cursor="Hand" ToolTip="Remove Role" Command="{Binding RelativeSource={RelativeSource AncestorType=UserControl},Path=DataContext.RemoveRoleCommand}" CommandParameter="{Binding}">
                                                        <Button.Style>
                                                            <Style TargetType="Button" BasedOn="{StaticResource emptyButton}">
                                                                <Setter Property="Visibility" Value="Hidden"></Setter>
                                                                <Style.Triggers>
                                                                    <DataTrigger Binding="{Binding RelativeSource={RelativeSource AncestorType=Grid},Path=IsMouseOver}" Value="True">
                                                                        <Setter Property="Visibility" Value="Visible"></Setter>
                                                                    </DataTrigger>
                                                                </Style.Triggers>
                                                            </Style>
                                                        </Button.Style>
                                                        <materialDesign:PackIcon Kind="Delete" Foreground="{StaticResource RedBrush100}" Width="16" Height="16" />
                                                    </Button>
                                                </Grid>
                                            </DataTemplate>
                                        </ListBox.ItemTemplate>
                                    </ListBox>
                                </Border>
                            </Grid>
                        </DockPanel>
                    </Grid>
                </DockPanel>
            </Grid>

            <Grid Grid.Column="1" Background="{StaticResource WhiteBackgroundBrush}">
                <DockPanel Margin="10">
                    <StackPanel Orientation="Horizontal" DockPanel.Dock="Top">
                        <Image Source="../Images/roles.png" Width="70" RenderOptions.BitmapScalingMode="Fant"></Image>
                        <TextBlock FontSize="16" FontWeight="SemiBold" VerticalAlignment="Center" Margin="10 0 0 0">AVAILABLE ROLES</TextBlock>
                    </StackPanel>

                    <Grid>
                        <ListBox ItemsSource="{Binding Roles}" ItemContainerStyle="{StaticResource basicListBoxItem}" HorizontalContentAlignment="Stretch" Background="Transparent">
                            <ListBox.ItemTemplate>
                                <DataTemplate>
                                    <Grid Background="Transparent" IsHitTestVisible="True" Style="{StaticResource draggableGrid}" dragAndDrop:DragAndDropService.DraggableBorderBrush="{StaticResource AccentColorBrush}" dragAndDrop:DragAndDropService.Draggable="True" dragAndDrop:DragAndDropService.DraggingSurface="{Binding RelativeSource={RelativeSource AncestorType=UserControl},Path=DraggingSurface}" Visibility="{Binding RoleEnum, Converter={StaticResource RoleEnumToVisibleConverter}}">
                                        <Grid.ToolTip>
                                            <StackPanel Background="Transparent">
                                                <TextBlock Text="{Binding Description}" FontSize="10" Margin="0 0 0 10"></TextBlock>
                                                <ItemsControl ItemsSource="{Binding RolesPermissions}">
                                                    <ItemsControl.ItemTemplate>
                                                        <DataTemplate>
                                                            <StackPanel Orientation="Horizontal"
                                                                        Background="Transparent">
                                                                <materialDesign:PackIcon Kind="Security" Width="12" />
                                                                <TextBlock Margin="5 0 0 0"
                                                                           FontSize="10"
                                                                           Text="{Binding Permission.Name}"
                                                                           ></TextBlock>
                                                            </StackPanel>
                                                        </DataTemplate>
                                                    </ItemsControl.ItemTemplate>
                                                </ItemsControl>
                                            </StackPanel>
                                        </Grid.ToolTip>
                                        <DockPanel>
                                            <Border DockPanel.Dock="Left" Width="100" Height="100" IsHitTestVisible="False" BorderBrush="{StaticResource borderBrush}" BorderThickness="1" CornerRadius="5" Margin="5" Padding="2" Background="{StaticResource UserRoles.Background}">
                                                <Grid>
                                                    <StackPanel VerticalAlignment="Center" HorizontalAlignment="Center">
                                                        <Image Source="../Images/roles.png" Width="32" RenderOptions.BitmapScalingMode="Fant"></Image>
                                                        <TextBlock Text="{Binding Name}" TextWrapping="Wrap" HorizontalAlignment="Center" TextAlignment="Center" FontSize="13" Margin="5"></TextBlock>
                                                    </StackPanel>
                                                </Grid>
                                            </Border>

                                            <Grid MaxHeight="85"
                                                  HorizontalAlignment="Left"
                                                  Margin="20 0 0 0"
                                                  Width="200">
                                                <ItemsControl ItemsSource="{Binding RolesPermissions}" Foreground="{StaticResource MainWindow.Foreground}">
                                                    <ItemsControl.ItemTemplate>
                                                        <DataTemplate>
                                                            <StackPanel Orientation="Horizontal">
                                                                <materialDesign:PackIcon Kind="Security" Width="12" />
                                                                <TextBlock Margin="5 0 0 0" FontSize="10" TextTrimming="CharacterEllipsis" MaxWidth="150" Text="{Binding Permission.Name}"></TextBlock>
                                                            </StackPanel>
                                                        </DataTemplate>
                                                    </ItemsControl.ItemTemplate>
                                                </ItemsControl>

                                                <Grid Background="{StaticResource UserRoles.GridBackground}">
                                                </Grid>
                                            </Grid>
                                        </DockPanel>
                                    </Grid>
                                </DataTemplate>
                            </ListBox.ItemTemplate>
                        </ListBox>
                    </Grid>
                </DockPanel>

                <Rectangle HorizontalAlignment="Left" Stroke="#BBBBBB" StrokeThickness="1"></Rectangle>
            </Grid>
        </Grid>

        <dragAndDrop:DraggingSurface x:Name="dragSurface" />
    </Grid>
</UserControl>
cu).Version; } } catch (Exception ex) { throw new FileLoadException("Could extract the firmware version from the TFP package.", ex); } LogManager.Log($"Backup file generated:\n{backupFile.ToJsonString()}"); if (settings.Mode == BackupMode.Jobs) { //Jobs LogManager.Log("Starting jobs backup..."); OnProgress(BackupRestoreStage.BackingupJobs); using (ObservablesContext db = ObservablesContext.CreateDefault()) { var jobs = db.Jobs.ToList(); foreach (var job in jobs) { try { LogManager.Log($"Backing up job '{job.Name}'..."); var jobFile = job.ToJobFile().Result; backupFile.JobFiles.Add(jobFile); OnProgress(BackupRestoreStage.BackingupJobs, jobs.IndexOf(job) + 1, jobs.Count, false); } catch (Exception ex) { throw new InvalidOperationException($"Error extracting job {job.Name}.", ex); } } } LogManager.Log("Jobs backup completed."); } else { //User Settings LogManager.Log("Backing up application settings..."); OnProgress(BackupRestoreStage.BackingupSettings); backupFile.SettingsFile = File.ReadAllText(SettingsManager.Default.FilePath); //Application Version LogManager.Log("Backing up application files..."); OnProgress(BackupRestoreStage.BackingupApplication); try { PathHelper.CopyDirectory(AssemblyHelper.GetCurrentAssemblyFolder(), tempFolder, true, (current, total) => { OnProgress(BackupRestoreStage.BackingupApplication, current, total, false); }); } catch (Exception ex) { throw new IOException($"Error occurred while copying application files.", ex); } //Database LogManager.Log("Backing up database..."); OnProgress(BackupRestoreStage.BackingupDatabase); try { var dataSource = ObservablesContext.GetActualDataSource(); using (var dbManager = DbManager.FromDataSource(dataSource)) { Directory.CreateDirectory("C:\\Backups"); var dbBackupFile = $"C:\\Backups\\{DATABASE_FILE_NAME}"; if (File.Exists(dbBackupFile)) { File.Delete(dbBackupFile); } dbManager.Backup(dataSource.Catalog, dbBackupFile); File.Move(dbBackupFile, Path.Combine(tempFolder, DATABASE_FILE_NAME)); } } catch (Exception ex) { throw new IOException("Error creating database backup", ex); } LogManager.Log("Database backup completed."); } //Backup.json try { OnProgress(BackupRestoreStage.WritingConfiguration); var backupFilePath = Path.Combine(tempFolder, BACKUP_FILE_NAME); LogManager.Log($"Writing backup configuration file '{backupFilePath}'..."); File.WriteAllText(backupFilePath, backupFile.ToJsonString()); } catch (Exception ex) { throw new IOException("Error writing backup configuration file.", ex); } //Compression LogManager.Log($"Generating {filePath}..."); using (ZipFile zip = new ZipFile()) { zip.Password = PASSWORD; zip.AddDirectory(tempFolder); zip.SaveProgress += (x, e) => { if (e.EventType == ZipProgressEventType.Saving_AfterWriteEntry) { LogManager.Log($"Compressing '{e.CurrentEntry.FileName}'..."); OnProgress(BackupRestoreStage.CompressingFiles, e.EntriesSaved + 1, e.EntriesTotal, false); } }; zip.ParallelDeflateThreshold = -1; zip.Save(filePath); } //Done LogManager.Log("Backup operation completed!!!"); OnProgress(BackupRestoreStage.Done, 100, 100, false); tempFolder.Delete(); } catch (Exception ex) { tempFolder.Delete(); OnProgress(BackupRestoreStage.Error, 100, 100, false); LogManager.Log(ex, "Could not complete the backup operation."); throw ex; } }); } /// <summary> /// Extracts the backup configuration from the specified backup file. /// </summary> /// <param name="filePath">The file path.</param> /// <returns></returns> public Task<BackupFile> ExtractBackupConfiguration(string filePath) { return Task.Factory.StartNew<BackupFile>(() => { using (ZipFile zip = ZipFile.Read(filePath)) { zip.Password = PASSWORD; var reader = zip.Entries.SingleOrDefault(x => x.FileName == BACKUP_FILE_NAME).OpenReader(); String json = String.Empty; using (StreamReader stReader = new StreamReader(reader)) { json = stReader.ReadToEnd(); } var backupFile = BackupFile.FromJson(json); reader.Close(); reader.Dispose(); return backupFile; } }); } public Task<RestoreResult> Restore(string filePath, RestoreSettings settings) { TaskCompletionSource<RestoreResult> completionSource = new TaskCompletionSource<RestoreResult>(); String dbRollbackFile = null; bool shouldRollback = false; Task.Factory.StartNew(() => { LogManager.Log($"Starting restore operation from file '{filePath}'..."); OnProgress(BackupRestoreStage.Initializing); var tempFolder = TemporaryManager.CreateFolder(); tempFolder.Persist = true; var restoreResult = new RestoreResult() { FolderPath = tempFolder }; try { LogManager.Log("Extracting backup file configuration..."); BackupFile backupFile = null; //Extract Configuration try { OnProgress(BackupRestoreStage.ExtractingBackupConfiguration); backupFile = ExtractBackupConfiguration(filePath).Result; restoreResult.BackupFile = backupFile; LogManager.Log($"Backup settings:\n{backupFile.Settings.ToJsonString()}"); } catch (Exception ex) { throw new IOException("Error extracting backup configuration.", ex); } //Validate Version if (backupFile.Version > VERSION) { throw new NotSupportedException($"Backup file version {backupFile} is not supported."); } //Validate Machine Serial Number if (backupFile.Settings.Mode == BackupMode.Full && backupFile.MachineSerialNumber != _machineProvider.Machine.SerialNumber) { throw new InvalidOperationException($"The specified backup file targets machine '{backupFile.MachineSerialNumber}'. Cannot perform the restore operation."); } //Validate Machine State LogManager.Log("Validating machine state..."); OnProgress(BackupRestoreStage.ValidatingMachineState); if (_machineProvider.MachineOperator.IsPrinting) { LogManager.Log("The machine is currently printing. Aborting!"); throw new InvalidOperationException("Cannot perform restore operation while machine is dyeing."); } if (backupFile.Settings.Mode == BackupMode.Full && _machineProvider.MachineOperator.State != Transport.TransportComponentState.Connected) { LogManager.Log("Backup is configured to restore the firmware but machine is not connected!"); throw new InvalidOperationException("The restore operation is configured to restore the firmware version but the machine is currently disconnected."); } //Create Restore Point try { LogManager.Log("Creating database rollback file..."); var dataSource = ObservablesContext.GetActualDataSource(); using (var dbManager = DbManager.FromDataSource(dataSource)) { Directory.CreateDirectory("C:\\Backups"); dbRollbackFile = $"C:\\Backups\\{Path.GetRandomFileName()}.bak"; LogManager.Log($"Creating database rollback to '{dbRollbackFile}'..."); dbManager.Backup(dataSource.Catalog, dbRollbackFile); LogManager.Log("Database rollback created successfully."); shouldRollback = true; } } catch (Exception ex) { throw new InvalidDataException("Error creating database rollback file.", ex); } if (backupFile.Settings.Mode == BackupMode.Jobs) { //Restore Jobs OnProgress(BackupRestoreStage.RestoringJobs); LogManager.Log("Starting jobs restore..."); using (ObservablesContext db = ObservablesContext.CreateDefault()) { var jobs = db.Jobs.ToList(); var jobFiles = backupFile.JobFiles; if (settings.AllowDeleteJobs) { try { LogManager.Log("Removing existing jobs..."); foreach (var job in jobs.ToList()) { LogManager.Log($"Removing job '{job.Name}'..."); job.Delete(db); jobs.Remove(job); } db.SaveChanges(); } catch (Exception ex) { throw new Exception("Error removing existing jobs from database.", ex); } } foreach (var jobFile in jobFiles) { LogManager.Log($"Importing job '{jobFile.Name}'..."); try { var existingJob = jobs.FirstOrDefault(x => x.Name == jobFile.Name); if (existingJob != null) { if (settings.OverwriteExistingJobs) { try { LogManager.Log("Job already exist, overwriting..."); var newJob = Job.FromJobFile(jobFile, _machineProvider.Machine.Guid, _authenticationProvider.CurrentUser.Guid).Result; newJob.Guid = existingJob.Guid; existingJob.Delete(db); jobs.Remove(existingJob); db.SaveChanges(); db.Jobs.Add(newJob); db.SaveChanges(); } catch (Exception ex) { throw new InvalidOperationException("Error overwriting job.", ex); } } } else { var newJob = Job.FromJobFile(jobFile, _machineProvider.Machine.Guid, _authenticationProvider.CurrentUser.Guid).Result; db.Jobs.Add(newJob); } } catch (Exception ex) { throw new InvalidOperationException("Error importing job.", ex); } OnProgress(BackupRestoreStage.RestoringJobs, jobFiles.IndexOf(jobFile) + 1, jobFiles.Count, false); } OnProgress(BackupRestoreStage.RestoringJobs); db.SaveChanges(); } LogManager.Log("Jobs restored successfully."); OnProgress(BackupRestoreStage.Done, 100, 100, false); completionSource.SetResult(restoreResult); } else { //Extract zip file LogManager.Log("Starting backup file extraction..."); OnProgress(BackupRestoreStage.ExtractingContent); try { using (ZipFile zip = new ZipFile(filePath)) { zip.Password = PASSWORD; zip.ExtractProgress += (x, e) => { if (e.EventType == ZipProgressEventType.Extracting_AfterExtractEntry) { LogManager.Log($"Extracting '{e.CurrentEntry.FileName}'..."); OnProgress(BackupRestoreStage.ExtractingContent, e.EntriesExtracted + 1, e.EntriesTotal, false); } }; zip.ParallelDeflateThreshold = -1; zip.ExtractAll(tempFolder); } } catch (Exception ex) { throw new IOException("Error extracting backup content.", ex); } //Overwrite settings LogManager.Log("Validating user settings..."); if (backupFile.SettingsFile != null) { try { LogManager.Log("Overwriting settings file..."); OnProgress(BackupRestoreStage.RestoringSettings); File.WriteAllText(SettingsManager.Default.FilePath, backupFile.SettingsFile); } catch (Exception ex) { throw new IOException("Error overwriting user settings.", ex); } } else { LogManager.Log("No user settings, skipping..."); } //Restore database var backupFilePath = Path.Combine(tempFolder, DATABASE_FILE_NAME); LogManager.Log($"Looking for file database backup on '{backupFilePath}'..."); if (File.Exists(backupFilePath)) { LogManager.Log("Restoring database..."); OnProgress(BackupRestoreStage.RestoringDatabase); try { var dataSource = ObservablesContext.GetActualDataSource(); using (var dbManager = DbManager.FromDataSource(dataSource)) { Directory.CreateDirectory("C:\\Backups"); var dbBackupFile = $"C:\\Backups\\{DATABASE_FILE_NAME}"; File.Copy(backupFilePath, dbBackupFile, true); dbManager.Restore(dataSource.Catalog, dbBackupFile); File.Delete(dbBackupFile); } } catch (Exception ex) { throw new IOException("Error restoring database backup", ex); } LogManager.Log("Database backup completed."); } else { LogManager.Log("Database backup file not found, skipping..."); } //Remove extra files from application temp folder OnProgress(BackupRestoreStage.RemovingTemporaryFiles); LogManager.Log("Removing redundant files from temp folder..."); try { File.Delete(backupFilePath); } catch { } try { File.Delete(Path.Combine(tempFolder, BACKUP_FILE_NAME)); } catch { } //Update firmware var tfpFile = Path.Combine(tempFolder, "firmware_package.tfp"); LogManager.Log($"Looking for tfp file on '{tfpFile}'..."); if (File.Exists(tfpFile)) { OnProgress(BackupRestoreStage.RestoringFirmware); LogManager.Log("Restoring firmware version..."); var stream = new FileStream(tfpFile, FileMode.Open); if (_machineProvider.Machine.IsDemo) { _machineProvider.MachineOperator.FirmwareUpgradeMode = FirmwareUpgradeModes.TFP_PACKAGE; } else { _machineProvider.MachineOperator.FirmwareUpgradeMode = FirmwareUpgradeModes.DFU | FirmwareUpgradeModes.TFP_PACKAGE; } var handler = _machineProvider.MachineOperator.UpgradeFirmware(stream).Result; handler.Failed += (_, ex) => { stream.Dispose(); OnRestoreException(ex, completionSource, shouldRollback, dbRollbackFile, tempFolder); }; handler.Completed += (_, __) => { OnProgress(BackupRestoreStage.RestoringFirmware, 100, 100, false); stream.Dispose(); LogManager.Log("Full backup restored successfully."); OnProgress(BackupRestoreStage.Done, 100, 100, false); completionSource.SetResult(restoreResult); }; handler.Canceled += (_, __) => { stream.Dispose(); OnRestoreException(new Exception("The operation has been canceled."), completionSource, shouldRollback, dbRollbackFile, tempFolder); }; handler.Progress += (_, e) => { OnProgress(BackupRestoreStage.RestoringFirmware, e.Current, e.Total, false); }; } else { LogManager.Log("Firmware package file not found, skipping..."); OnProgress(BackupRestoreStage.Done, 100, 100, false); completionSource.SetResult(restoreResult); } } } catch (Exception ex) { OnRestoreException(ex, completionSource, shouldRollback, dbRollbackFile, tempFolder); } }); return completionSource.Task; } private void OnRestoreException(Exception ex, TaskCompletionSource<RestoreResult> completionSource, bool shouldRollback, String dbRollbackFile, TemporaryFolder tempFolder) { if (shouldRollback) { LogManager.Log("Rolling back database changes..."); var dataSource = ObservablesContext.GetActualDataSource(); using (var dbManager = DbManager.FromDataSource(dataSource)) { try { OnProgress(BackupRestoreStage.RollingBackChanges); dbManager.Restore(dataSource.Catalog, dbRollbackFile); LogManager.Log("Database restored successfully."); } catch (Exception e) { LogManager.Log(e, "Error rolling back database."); } finally { try { File.Delete(dbRollbackFile); } catch { } } } } tempFolder.Delete(); OnProgress(BackupRestoreStage.Error, 100, 100, false); LogManager.Log(ex, "Could not complete the restore operation."); completionSource.SetException(ex); } protected virtual void OnProgress(BackupRestoreStage stage, double progress = 0, double maxProgress = 100, bool isIntermediate = true) { Progress?.Invoke(this, new BackupRestoreProgressEventArgs() { Stage = stage, Progress = progress, MaxProgress = maxProgress, IsIntermediate = isIntermediate, }); } } }