aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/PPC/Tango.PPC.UI/ViewModelLocator.cs
blob: 4ab3f26bd6e3e2107a3e4a9c5e0110f45c75f675 (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
using FluentFTP;
using Ionic.Zip;
using Microsoft.Win32;
using Microsoft.WindowsAzure.Storage.Blob;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Data;
using Tango.BL;
using Tango.BL.Entities;
using Tango.Core.Commands;
using Tango.Core.Cryptography;
using Tango.Core.Helpers;
using Tango.Core.IO;
using Tango.PPC.Common.Update;
using Tango.SharedUI;
using Tango.SQLExaminer;

namespace Tango.PPC.Publisher
{
    public class MainWindowVM : ViewModel
    {
        private IPPCUpdateService _client;

        private BasicHashGenerator _hashGenerator;

        private List<MachineVersion> _machineVersions;
        public List<MachineVersion> MachineVersions
        {
            get { return _machineVersions; }
            set { _machineVersions = value; RaisePropertyChangedAuto(); }
        }

        private MachineVersion _selectedMachineVersion;
        public MachineVersion SelectedMachineVersion
        {
            get { return _selectedMachineVersion; }
            set { _selectedMachineVersion = value; RaisePropertyChangedAuto(); OnSelectedMachineVersionChanged(); }
        }

        private String _selectedBuildConfiguration;
        public String SelectedBuildConfiguration
        {
            get { return _selectedBuildConfiguration; }
            set { _selectedBuildConfiguration = value; RaisePropertyChangedAuto(); }
        }

        private String _localVersion;
        public String LocalVersion
        {
            get { return _localVersion; }
            set { _localVersion = value; RaisePropertyChangedAuto(); }
        }

        private String _currentVersion;
        public String CurrentVersion
        {
            get { return _currentVersion; }
            set { _currentVersion = value; RaisePropertyChangedAuto(); }
        }

        private ObservableCollection<SequenceItem> _provisionSequenceItems;
        public ObservableCollection<SequenceItem> ProvisionSequenceItems
        {
            get { return _provisionSequenceItems; }
            set { _provisionSequenceItems = value; RaisePropertyChangedAuto(); }
        }

        private ICollectionView _provisionSequenceItemsView;
        public ICollectionView ProvisionSequenceItemsView
        {
            get { return _provisionSequenceItemsView; }
            set { _provisionSequenceItemsView = value; RaisePropertyChangedAuto(); }
        }

        private ObservableCollection<SequenceItem> _updateSequenceItems;
        public ObservableCollection<SequenceItem> UpdateSequenceItems
        {
            get { return _updateSequenceItems; }
            set { _updateSequenceItems = value; RaisePropertyChangedAuto(); }
        }

        private ICollectionView _updateSequenceItemsView;
        public ICollectionView UpdateSequenceItemsView
        {
            get { return _updateSequenceItemsView; }
            set { _updateSequenceItemsView = value; RaisePropertyChangedAuto(); }
        }


        private String _email;
        public String Email
        {
            get { return _email; }
            set { _email = value; RaisePropertyChangedAuto(); }
        }

        private String _password;
        public String Password
        {
            get { return _password; }
            set { _password = value; RaisePropertyChangedAuto(); }
        }

        private String _comments;
        public String Comments
        {
            get { return _comments; }
            set { _comments = value; RaisePropertyChangedAuto(); }
        }

        private double _maxProgress;
        public double MaxProgress
        {
            get { return _maxProgress; }
            set { _maxProgress = value; RaisePropertyChangedAuto(); }
        }

        private double _progress;
        public double Progress
        {
            get { return _progress; }
            set { _progress = value; RaisePropertyChangedAuto(); }
        }

        private bool _isUpdating;
        public bool IsUpdating
        {
            get { return _isUpdating; }
            set { _isUpdating = value; RaisePropertyChangedAuto(); }
        }

        public RelayCommand PublishCommand { get; set; }

        public MainWindowVM()
        {
            SelectedBuildConfiguration = "Release";

            _hashGenerator = new BasicHashGenerator();

            ProvisionSequenceItems = new ObservableCollection<SequenceItem>();
            ProvisionSequenceItemsView = CollectionViewSource.GetDefaultView(ProvisionSequenceItems);
            ProvisionSequenceItemsView.SortDescriptions.Add(new SortDescription(nameof(SequenceItem.Index), ListSortDirection.Ascending));

            UpdateSequenceItems = new ObservableCollection<SequenceItem>();
            UpdateSequenceItemsView = CollectionViewSource.GetDefaultView(UpdateSequenceItems);
            UpdateSequenceItemsView.SortDescriptions.Add(new SortDescription(nameof(SequenceItem.Index), ListSortDirection.Ascending));

            using (ObservablesContext db = ObservablesContext.CreateDefault("localhost\\SQLEXPRESS"))
            {
                db.Configuration.LazyLoadingEnabled = false;
                MachineVersions = db.MachineVersions.ToList();
                SelectedMachineVersion = MachineVersions.OrderBy(x => x.Version).LastOrDefault();
            }

            LocalVersion = FileVersionInfo.GetVersionInfo(Core.Helpers.AssemblyHelper.GetCurrentAssemblyFolder() + "\\Tango.PPC.UI.exe").ProductVersion;

            PublishCommand = new RelayCommand(Publish);
        }

        private async void OnSelectedMachineVersionChanged()
        {
            if (SelectedMachineVersion != null)
            {
                if (_client == null)
                {
                    _client = new PPCUpdateService();
                }

                var response = await _client.GetLatestVersion(new LatestVersionRequest()
                {
                    MachineVersionGuid = SelectedMachineVersion.Guid,
                });

                CurrentVersion = response.Version;
            }
        }

        private void Publish()
        {
            String _appPath = String.Format(AppDomain.CurrentDomain.BaseDirectory + "..\\{0}", SelectedBuildConfiguration);

            Task.Factory.StartNew(async () =>
                {
                    IsUpdating = true;
                    String tempFile = String.Empty;

                    try
                    {
                        var response = await _client.UploadVersion(new UploadVersionRequest()
                        {
                            Comments = Comments,
                            Email = Email,
                            Password = _hashGenerator.Encrypt(Password),
                            Version = LocalVersion,
                            MachineVersionGuid = SelectedMachineVersion.Guid
                        });

                        tempFile = TemporaryManager.Default.CreateFile(".zip");

                        using (ZipFile zip = new ZipFile())
                        {
                            String provision_dir = "Provision Scripts";

                            zip.AddDirectoryByName(provision_dir);

                            ExaminerSequenceConfiguration provision_config = new ExaminerSequenceConfiguration();

                            foreach (var item in ProvisionSequenceItems)
                            {
                                provision_config.Items.Add(new ExaminerSequenceItem()
                                {
                                    Direction = item.Direction,
                                    FileName = item.FileName,
                                    Index = item.Index,
                                    Name = item.Name,
                                    Type = item.Type,
                                    RequiresSerialNumber = item.RequiresSerialNumber
                                });

                                zip.AddFile(item.FilePath, provision_dir);
                            }

                            String provision_config_file = TemporaryManager.Default.CreateFile(".zip");
                            provision_config.ToFile(provision_config_file);

                            var cf = zip.AddFile(provision_config_file, provision_dir);
                            cf.FileName = provision_dir + "\\config.xml";



                            String update_dir = "Update Scripts";

                            zip.AddDirectoryByName(update_dir);

                            ExaminerSequenceConfiguration update_config = new ExaminerSequenceConfiguration();

                            foreach (var item in UpdateSequenceItems)
                            {
                                update_config.Items.Add(new ExaminerSequenceItem()
                                {
                                    Direction = item.Direction,
                                    FileName = item.FileName,
                                    Index = item.Index,
                                    Name = item.Name,
                                    Type = item.Type,
                                    RequiresSerialNumber = item.RequiresSerialNumber
                                });

                                zip.AddFile(item.FilePath, update_dir);
                            }

                            String update_config_file = TemporaryManager.Default.CreateFile(".zip");
                            update_config.ToFile(update_config_file);

                            var cuf = zip.AddFile(update_config_file, update_dir);
                            cuf.FileName = update_dir + "\\config.xml";

                            foreach (var file in Directory.GetFiles(_appPath, "*.*", SearchOption.TopDirectoryOnly))
                            {
                                zip.AddFile(file, "/");
                            }

                            zip.SaveProgress += (x, e) =>
                            {
                                MaxProgress = e.EntriesTotal;
                                Progress = e.EntriesSaved;
                            };

                            zip.Save(tempFile);
                        }

                        Progress = 0;
                        MaxProgress = 100;

                        CloudBlockBlob blob = new CloudBlockBlob(new Uri(response.BlobAddress));

                        FileStreamWrapper fs = null;

                        using (fs = new FileStreamWrapper(tempFile, FileMode.Open, (current) =>
                        {
                            InvokeUINow(() =>
                            {
                                Thread.Sleep(10);
                                Progress = ((double)current / (double)fs.Length) * 100d;
                            });
                        }))
                        {
                            await blob.UploadFromStreamAsync(fs);
                        }

                        await _client.NotifyUploadCompleted(new UploadCompletedRequest()
                        {
                            Token = response.Token,
                        });

                        Progress = 0;
                        OnSelectedMachineVersionChanged();
                        ShowInfo("Version published successfully!");
                    }
                    catch (Exception ex)
                    {
                        ShowError(ex.Message);
                    }
                    finally
                    {
                        IsUpdating = false;
                    }
                });
        }

        private void ShowError(String error)
        {
            MessageBox.Show(error, "PPC Publisher", MessageBoxButton.OK, MessageBoxImage.Error);
        }

        private void ShowInfo(String message)
        {
            MessageBox.Show(message, "PPC Publisher", MessageBoxButton.OK, MessageBoxImage.Information);
        }

        private bool ShowQuestion(String message)
        {
            return MessageBox.Show(message, "PPC Publisher", MessageBoxButton.YesNo, MessageBoxImage.Information) == MessageBoxResult.Yes;
        }

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