forked from canneverbe/Ketarin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ApplicationJob.cs
2151 lines (1888 loc) · 90.2 KB
/
ApplicationJob.cs
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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
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
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SQLite;
using System.IO;
using System.Net;
using System.Text.RegularExpressions;
using System.Security.Cryptography;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Serialization;
using CDBurnerXP;
using CDBurnerXP.IO;
using Ketarin.Forms;
using System.Reflection;
using System.Collections;
using System.Linq;
using CodeProject.ReiMiyasaka;
namespace Ketarin
{
/// <summary>
/// Represents an application which can be kept up
/// to date according to user defined rules.
/// It is the main object of Ketarin.
/// </summary>
[XmlRoot("ApplicationJob")]
public class ApplicationJob
{
private string m_Name;
private string m_TargetPath = string.Empty;
private DateTime? m_LastUpdated;
private UrlVariableCollection m_Variables;
private bool m_ShareApplication;
private string m_VariableChangeIndicator = string.Empty;
private string m_VariableChangeIndicatorLastContent;
private string m_PreviousRelativeLocation = string.Empty;
private List<SetupInstruction> setupInstructions;
private static PropertyInfo[] applicationJobProperties;
private string cachedCurrentLocation;
private string previousLocation = string.Empty;
/// <summary>
/// Cached list of public properties of the type ApplicationJob.
/// </summary>
private static PropertyInfo[] ApplicationJobProperties
{
get {
return applicationJobProperties ??
(applicationJobProperties =
typeof (ApplicationJob).GetProperties(BindingFlags.Public | BindingFlags.Instance));
}
}
public enum SourceType
{
FixedUrl,
FileHippo
}
public enum DownloadBetaType
{
Default = 0,
Avoid,
AlwaysDownload
}
#region Properties
/// <summary>
/// Gets or sets the template from which the application has been created.
/// </summary>
[XmlIgnore()]
public string SourceTemplate { get; set; }
/// <summary>
/// Source template property for XML serialization as CDATA.
/// </summary>
[XmlElement("SourceTemplate", typeof(XmlCDataSection))]
public XmlCDataSection SourceTemplateCdata
{
get
{
// Prevent unnecessary CDATA elements
if (string.IsNullOrEmpty(this.SourceTemplate))
{
return null;
}
XmlDocument doc = new XmlDocument();
return doc.CreateCDataSection(this.SourceTemplate);
}
set
{
if (value == null)
{
this.SourceTemplate = string.Empty;
}
else
{
XmlDocument doc = new XmlDocument {PreserveWhitespace = true};
if (string.IsNullOrEmpty(value.InnerText))
{
this.SourceTemplate = string.Empty;
return;
}
doc.LoadXml(value.InnerText);
// Make sure that no nested source templates are saved
foreach (XmlElement e in doc.GetElementsByTagName("SourceTemplate"))
{
e.ParentNode.RemoveChild(e);
break;
}
if (doc.FirstChild is XmlDeclaration)
{
doc.RemoveChild(doc.FirstChild);
}
this.SourceTemplate = doc.OuterXml.Trim();
}
}
}
/// <summary>
/// Gets or sets the website of the application.
/// </summary>
public string WebsiteUrl { get; set; }
/// <summary>
/// Gets the website of an application with all variables replaced.
/// </summary>
public string ExpandedWebsiteUrl => this.m_Variables.ReplaceAllInString(this.WebsiteUrl);
/// <summary>
/// Gets or sets a custom user agent to use for downloads.
/// </summary>
public string UserAgent { get; set; }
/// <summary>
/// Gets or sets the custom notes for an application.
/// </summary>
public string UserNotes { get; set; }
/// <summary>
/// Gets or sets the last size of the file which
/// has been downloaded for the application.
/// </summary>
public long LastFileSize { get; set; }
/// <summary>
/// Gets or sets the number of revisions of a file that should be stored.
/// If > 1, revisions will be saved as FileName.1.ext in the same location.
/// </summary>
public int NumberOfRevisions { get; set; }
/// <summary>
/// Gets or sets the last write time of the file which
/// has been downloaded for the application.
/// </summary>
public DateTime? LastFileDate { get; set; }
/// <summary>
/// Specifies whether or not to ignore the file based information.
/// If true, only the information in database will be compared, and Ketarin
/// will not re-download if the file is missing.
/// </summary>
public bool IgnoreFileInformation { get; set; }
public DownloadBetaType DownloadBeta { get; set; }
/// <summary>
/// Gets or sets the version information
/// scraped from a PAD file.
/// </summary>
[XmlIgnore()]
internal string CachedPadFileVersion { get; set; }
/// <summary>
/// The last updated date of the application
/// in the online database.
/// </summary>
public DateTime? DownloadDate { get; set; }
/// <summary>
/// Gets or sets whether or not the application should
/// not be downloaded.
/// For example, you might not want to include downloading
/// huge applications.
/// </summary>
public bool CheckForUpdatesOnly { get; set; }
/// <summary>
/// Gets or sets the variable, which is used as change indicator.
/// If this value is not set, the file modification date / size is used.
/// </summary>
public string VariableChangeIndicator
{
get { return this.m_VariableChangeIndicator; }
set
{
if (this.m_VariableChangeIndicator != value)
{
this.m_VariableChangeIndicator = value;
this.m_VariableChangeIndicatorLastContent = null;
}
}
}
/// <summary>
/// Gets or sets the variable which contains the hash value.
/// </summary>
public string HashVariable { get; set; }
/// <summary>
/// Gets or sets the kind of hash used for change detection.
/// </summary>
public HashType HashType { get; set; }
/// <summary>
/// Determines whether or not a user can
/// share this application online.
/// This is the case for all applications a user
/// downloaded, which are not his own.
/// </summary>
/// <remarks>The actual permission check is done on the
/// remote server, so this is not a security measure.</remarks>
public bool CanBeShared { get; set; } = true;
public bool ShareApplication
{
get { return this.m_ShareApplication; }
set
{
this.m_ShareApplication = value && this.CanBeShared;
}
}
/// <summary>
/// Gets or sets whether or not the application
/// may be downloaded simultaneously with other
/// applications.
/// </summary>
public bool ExclusiveDownload { get; set; }
/// <summary>
/// Gets or sets a referer which is used
/// for HTTP requests when downloading
/// the application.
/// </summary>
public string HttpReferer { get; set; } = string.Empty;
/// <summary>
/// Gets or sets the globally unique identifier
/// of this application.
/// </summary>
[XmlAttribute("Guid")]
public Guid Guid { get; set; } = Guid.Empty;
/// <summary>
/// Gets the list of setup instructions that need to be executed in order to install the application.
/// </summary>
public List<SetupInstruction> SetupInstructions
{
get
{
if (this.setupInstructions == null)
{
this.setupInstructions = new List<SetupInstruction>();
using (IDbCommand command = DbManager.Connection.CreateCommand())
{
command.CommandText = "SELECT * FROM setupinstructions WHERE JobGuid = @JobGuid ORDER BY Position";
command.Parameters.Add(new SQLiteParameter("@JobGuid", DbManager.FormatGuid(this.Guid)));
using (IDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
string xmlInstructions = reader["Data"] as string;
if (string.IsNullOrEmpty(xmlInstructions)) continue;
// Needed to determine appropriate type
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlInstructions);
using (StringReader xmlReader = new StringReader(xmlInstructions))
{
XmlSerializer serializer = new XmlSerializer(Type.GetType("Ketarin." + doc.DocumentElement.Name));
SetupInstruction instruction = (SetupInstruction)serializer.Deserialize(xmlReader);
instruction.Application = this;
this.setupInstructions.Add(instruction);
}
}
}
}
}
return this.setupInstructions;
}
set
{
this.setupInstructions = value;
}
}
#region UrlVariableCollection
public class UrlVariableCollection : SerializableDictionary<string, UrlVariable>
{
private bool m_VersionDownloaded;
private FileInfo cachedInfo;
#region Properties
/// <summary>
/// Gets or sets the application to which the collection belongs.
/// </summary>
[XmlIgnore()]
public ApplicationJob Parent { get; set; }
#endregion
public UrlVariableCollection()
{
}
public UrlVariableCollection(ApplicationJob parent)
{
this.Parent = parent;
}
/// <summary>
/// Resets the download count of all variables to 0.
/// </summary>
public void ResetDownloadCount()
{
foreach (UrlVariable var in this.Values)
{
var.DownloadCount = 0;
}
this.m_VersionDownloaded = false;
}
/// <summary>
/// Determines whether or not a certain variable has
/// been downloaded.
/// </summary>
/// <param name="name">Name of the variable, { and }.</param>
public bool HasVariableBeenDownloaded(string name)
{
if (name == "version") return this.m_VersionDownloaded;
if (!this.ContainsKey(name)) return false;
UrlVariable var = this[name];
return (var.DownloadCount > 0);
}
public virtual string ReplaceAllInString(string value)
{
return this.ReplaceAllInString(value, DateTime.MinValue, null, false);
}
public virtual string ReplaceAllInString(string value, DateTime fileDate, string filename, bool onlyCachedContent, bool skipGlobalVariables = false)
{
if (value == null) return null;
if (this.Parent != null && !string.IsNullOrEmpty(this.Parent.CurrentLocation))
{
try
{
if (!this.ContainsKey("file"))
{
value = UrlVariable.Replace(value, "file", this.Parent.CurrentLocation, this.Parent);
}
if (this.cachedInfo == null || this.cachedInfo.FullName != this.Parent.CurrentLocation)
{
this.cachedInfo = new FileInfo(this.Parent.CurrentLocation);
}
// Try to provide file date if missing
if (fileDate == DateTime.MinValue)
{
fileDate = this.cachedInfo.LastWriteTime;
}
// Provide file size
if (this.cachedInfo.Exists)
{
value = UrlVariable.Replace(value, "filesize", this.cachedInfo.Length.ToString(), this.Parent);
}
}
catch (Exception)
{
// Ignore all errors. If no information can be retrieved,
// only expand the usual variables.
}
}
// Ignore invalid dates
if (fileDate > DateTime.MinValue)
{
// Some date/time variables, only if they were not user defined
string[] dateTimeVars = { "dd", "ddd", "dddd", "hh", "HH", "mm", "MM", "MMM", "MMMM", "ss", "tt", "yy", "yyyy", "zz", "zzz" };
foreach (string dateTimeVar in dateTimeVars)
{
if (!this.ContainsKey(dateTimeVar))
{
value = value.Replace("{f:" + dateTimeVar + "}", fileDate.ToString(dateTimeVar));
}
}
}
// Provide {url:ext} and {url:basefile}
try
{
if (filename != null)
{
value = value.Replace("{url:ext}", Path.GetExtension(filename).TrimStart('.'));
value = value.Replace("{url:basefile}", Path.GetFileNameWithoutExtension(filename));
value = value.Replace("{url:filename}", Path.GetFileName(filename));
}
}
catch (ArgumentException ex)
{
LogDialog.Log("Could not determine {url:*} variables", ex);
}
value = UrlVariable.Replace(value, "startuppath", PathEx.QualifyPath(Application.StartupPath), this.Parent);
// Some date/time variables, only if they were not user defined
string[] dateTimeVariables = { "dd", "ddd", "dddd", "hh", "HH", "mm", "MM", "MMM", "MMMM", "ss", "tt", "yy", "yyyy", "zz", "zzz" };
foreach (string dateTimeVar in dateTimeVariables)
{
if (!this.ContainsKey(dateTimeVar))
{
value = value.Replace("{" + dateTimeVar + "}", DateTime.Now.ToString(dateTimeVar));
}
}
// Unix timestamp
value = UrlVariable.Replace(value, "time", RpcApplication.DotNetToUnix(DateTime.Now).ToString(), this.Parent);
for (int i = 1; i <= 12; i++)
{
value = UrlVariable.Replace(value, "time-" + i, RpcApplication.DotNetToUnix(DateTime.Now.AddHours(-i)).ToString(), this.Parent);
}
for (int i = 1; i <= 12; i++)
{
value = UrlVariable.Replace(value, "time+" + i, RpcApplication.DotNetToUnix(DateTime.Now.AddHours(+i)).ToString(), this.Parent);
}
// Job-specific data / non global variables
if (this.Parent != null)
{
if (!string.IsNullOrEmpty(this.Parent.Category))
{
value = UrlVariable.Replace(value, "category", this.Parent.Category, this.Parent);
}
value = UrlVariable.Replace(value, "appname", this.Parent.Name, this.Parent);
value = UrlVariable.Replace(value, "appguid", DbManager.FormatGuid(this.Parent.Guid), this.Parent);
// Allow to access all public properties of the object per "property:X" variable.
foreach (PropertyInfo property in ApplicationJobProperties)
{
// Only make effort if variable is used
string varname = "property:" + property.Name;
if (UrlVariable.IsVariableUsedInString(varname, value))
{
if (!typeof(IEnumerable).IsAssignableFrom(property.PropertyType) || property.PropertyType == typeof(string))
{
value = UrlVariable.Replace(value, varname, Convert.ToString(property.GetValue(this.Parent, null)), this.Parent);
}
}
}
if (!this.ContainsKey("version"))
{
// FileHippo version
if (this.Parent.DownloadSourceType == SourceType.FileHippo && UrlVariable.IsVariableUsedInString("version", value))
{
if (!onlyCachedContent)
{
this.Parent.FileHippoVersion = ExternalServices.FileHippoVersion(this.Parent.FileHippoId, this.Parent.AvoidDownloadBeta);
this.m_VersionDownloaded = true;
}
value = UrlVariable.Replace(value, "version", this.Parent.FileHippoVersion, this.Parent);
}
else if (!string.IsNullOrEmpty(this.Parent.CachedPadFileVersion))
{
// or PAD file version as alternative
value = UrlVariable.Replace(value, "version", this.Parent.CachedPadFileVersion, this.Parent);
}
}
}
foreach (UrlVariable var in this.Values)
{
var.Parent = this; // make sure that value is set correctly
value = var.ReplaceInString(value, fileDate, onlyCachedContent);
}
// Global variables
if (!skipGlobalVariables)
{
value = UrlVariable.GlobalVariables.ReplaceAllInString(value, fileDate, null, true, skipGlobalVariables);
}
return value;
}
}
#endregion
[XmlElement("Variables")]
public UrlVariableCollection Variables
{
get => this.m_Variables;
set
{
if (value != null)
{
this.m_Variables = value;
this.m_Variables.Parent = this;
}
}
}
/// <summary>
/// A command to be executed after downloading.
/// {file} is a placeholder for PreviousLocation.
/// </summary>
[XmlElement("ExecuteCommand")]
public string ExecuteCommand
{
get;
set;
}
/// <summary>
/// A command to be executed before downloading.
/// {file} is a placeholder for PreviousLocation.
/// </summary>
[XmlElement("ExecutePreCommand")]
public string ExecutePreCommand
{
get;
set;
}
/// <summary>
/// Gets or sets the type of the post download command.
/// </summary>
[XmlElement("ExecuteCommandType")]
public ScriptType ExecuteCommandType
{
get;
set;
}
/// <summary>
/// Gets or sets the type of the pre download command.
/// </summary>
[XmlElement("ExecutePreCommandType")]
public ScriptType ExecutePreCommandType
{
get;
set;
}
[XmlElement("Category")]
public string Category
{
get;
set;
}
[XmlElement("SourceType")]
public SourceType DownloadSourceType { get; set; } = SourceType.FixedUrl;
/// <summary>
/// Gets or sets the last location the application has been downloaded to.
/// </summary>
public string PreviousLocation
{
get => this.previousLocation;
set
{
if (this.previousLocation != value)
{
this.previousLocation = value;
this.cachedCurrentLocation = null;
}
}
}
/// <summary>
/// Determines whether or not the file exists.
/// </summary>
public bool FileExists => !string.IsNullOrEmpty(this.CurrentLocation) && PathEx.TryGetFileSize(this.CurrentLocation) > 0;
/// <summary>
/// Determines the current location of the file, using the relative URI if necessary.
/// </summary>
[XmlIgnore()]
public string CurrentLocation
{
get
{
if (this.cachedCurrentLocation != null)
{
return this.cachedCurrentLocation;
}
string result;
if (!string.IsNullOrEmpty(this.PreviousLocation) && PathEx.TryGetFileSize(this.PreviousLocation) > 0)
{
result = this.PreviousLocation;
}
else if (!string.IsNullOrEmpty(this.m_PreviousRelativeLocation))
{
try
{
result = Path.GetFullPath(Path.Combine(Application.StartupPath, this.m_PreviousRelativeLocation));
}
catch (NotSupportedException)
{
result = string.Empty;
}
}
else
{
result = string.Empty;
}
this.cachedCurrentLocation = result;
return result;
}
}
/// <summary>
/// Gets or sets if the previously downloaded file should be deleted
/// when downloading a new update.
/// </summary>
[XmlElement("DeletePreviousFile")]
public bool DeletePreviousFile
{
get; set;
}
[XmlElement("Enabled")]
public bool Enabled { get; set; }
public bool TargetIsFolder
{
get
{
if (string.IsNullOrEmpty(this.TargetPath)) return false;
return this.TargetPath.EndsWith(Path.DirectorySeparatorChar.ToString(), StringComparison.Ordinal);
}
}
[XmlElement("FileHippoId")]
public string FileHippoId { get; set; }
/// <summary>
/// Contains the cached version information
/// on FileHippo.
/// </summary>
[XmlIgnore()]
public string FileHippoVersion { get; set; }
[XmlElement("LastUpdated")]
public DateTime? LastUpdated
{
get { return this.m_LastUpdated; }
set
{
if (this.m_LastUpdated != value)
{
this.m_LastUpdated = value;
this.cachedCurrentLocation = null;
}
}
}
[XmlElement("TargetPath")]
public string TargetPath
{
get => m_TargetPath;
set { m_TargetPath = PathEx.FixDirectorySeparator(value); }
}
[XmlElement("FixedDownloadUrl")]
public string FixedDownloadUrl { get; set; } = string.Empty;
[XmlElement("Name")]
public string Name
{
get => this.m_Name;
set
{
this.m_Name = value.Length > 255 ? value.Substring(0, 255) : value;
}
}
/// <summary>
/// Determines whether or not to download beta versions
/// of this application by using the default and per
/// application setting.
/// </summary>
public bool AvoidDownloadBeta
{
get
{
bool defaultValue = (bool)Settings.GetValue("AvoidFileHippoBeta", false);
if (this.DownloadBeta == DownloadBetaType.Default)
{
return defaultValue;
}
return (this.DownloadBeta == DownloadBetaType.Avoid);
}
}
#endregion
/// <summary>
/// Creates a new instance of an application job.
/// </summary>
public ApplicationJob()
{
this.Enabled = true;
this.FileHippoId = string.Empty;
this.FileHippoVersion = string.Empty;
this.m_Variables = new UrlVariableCollection(this);
this.ExecuteCommandType = ScriptType.Batch;
this.ExecutePreCommandType = ScriptType.Batch;
}
/// <summary>
/// Deletes this job from the database.
/// </summary>
public void Delete()
{
SQLiteTransaction transaction = DbManager.Connection.BeginTransaction();
using (IDbCommand command = DbManager.Connection.CreateCommand())
{
command.Transaction = transaction;
command.CommandText = @"DELETE FROM jobs WHERE JobGuid = @JobGuid";
command.Parameters.Add(new SQLiteParameter("@JobGuid", DbManager.FormatGuid(this.Guid)));
command.ExecuteNonQuery();
}
// Delete variables
using (IDbCommand command = DbManager.Connection.CreateCommand())
{
command.Transaction = transaction;
command.CommandText = "DELETE FROM variables WHERE JobGuid = @JobGuid";
command.Parameters.Add(new SQLiteParameter("@JobGuid", DbManager.FormatGuid(this.Guid)));
command.ExecuteNonQuery();
}
transaction.Commit();
}
/// <summary>
/// Deletes this job from the database.
/// </summary>
public static void DeleteAll()
{
SQLiteTransaction transaction = DbManager.Connection.BeginTransaction();
using (IDbCommand command = DbManager.Connection.CreateCommand())
{
command.Transaction = transaction;
command.CommandText = @"DELETE FROM jobs";
command.ExecuteNonQuery();
}
// Delete variables
using (IDbCommand command = DbManager.Connection.CreateCommand())
{
command.Transaction = transaction;
command.CommandText = "DELETE FROM variables";
command.ExecuteNonQuery();
}
transaction.Commit();
}
/// <summary>
/// Updates an application downloaded from the online
/// database based on the return value of the web service.
/// </summary>
/// <returns>true, if the applciation has been updated</returns>
public bool UpdateFromXml(string[] xmlValues)
{
// No update possible
if (this.CanBeShared) return false;
foreach (string xml in xmlValues)
{
ApplicationJob job = LoadOneFromXml(xml);
if (job.Guid == this.Guid)
{
this.UpdateTemplatePropertiesFromApp(job);
return true;
}
}
return false;
}
/// <summary>
/// Transfers all download relevant properties of an application
/// to the current application and saves it.
/// </summary>
private void UpdateTemplatePropertiesFromApp(ApplicationJob job)
{
// Basically, we are only interested in properties
// that change if a different method needs to be used
// in order to download the file (changed website for example).
this.DownloadDate = DateTime.Now;
this.DownloadSourceType = job.DownloadSourceType;
this.FileHippoId = job.FileHippoId;
this.FixedDownloadUrl = job.FixedDownloadUrl;
this.HttpReferer = job.HttpReferer;
this.UserAgent = job.UserAgent;
this.Name = job.Name;
this.VariableChangeIndicator = job.VariableChangeIndicator;
this.Variables = job.Variables;
this.SetupInstructions = job.SetupInstructions;
this.Save();
}
/// <summary>
/// Updates the application based on a new version of its template.
/// </summary>
private void UpdateFromTemplate(string xml)
{
if (string.IsNullOrEmpty(this.SourceTemplate)) return;
Dictionary<string, string> previousValues = new Dictionary<string, string>();
// Extract previously used values
XmlDocument sourceTemplateXml = new XmlDocument();
sourceTemplateXml.LoadXml(this.SourceTemplate);
XmlNodeList placeholdersList = sourceTemplateXml.GetElementsByTagName("placeholder");
foreach (XmlElement element in placeholdersList)
{
previousValues[element.GetAttribute("name")] = element.GetAttribute("value");
}
XmlDocument newTemplate = new XmlDocument();
newTemplate.LoadXml(xml);
SetPlaceholders(newTemplate, previousValues);
// Any placeholders left? Template cannot be applied
placeholdersList = newTemplate.GetElementsByTagName("placeholder");
if (placeholdersList.Count > 0)
{
throw new ApplicationException("The new template does not use the same placeholders.\r\n\r\nThe application cannot be updated.");
}
ApplicationJob newAppDefinition = LoadOneFromXml(newTemplate.OuterXml);
this.UpdateTemplatePropertiesFromApp(newAppDefinition);
}
/// <summary>
/// Imports one (incomplete) ApplicationJob from a HTTP WebRequest.
/// </summary>
/// <returns>The incomplete ApplicationJob. Completiton by user required.</returns>
public static ApplicationJob ImportFromPad(HttpWebResponse response)
{
using (Stream sourceFile = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(sourceFile))
{
return ImportFromPadXml(reader.ReadToEnd());
}
}
}
/// <summary>
/// Imports one (incomplete) ApplicationJob from a PAD file.
/// </summary>
/// <returns>The incomplete ApplicationJob. Completiton by user required.</returns>
public static ApplicationJob ImportFromPad(string fileName)
{
return ImportFromPadXml(File.ReadAllText(fileName));
}
/// <summary>
/// Imports one (incomplete) ApplicationJob from a PAD file.
/// </summary>
/// <returns>null, if no application could be extracted</returns>
private static ApplicationJob ImportFromPadXml(string xml)
{
XmlDocument doc = new XmlDocument();
try
{
doc.LoadXml(xml);
}
catch (XmlException)
{
return null;
}
XmlNodeList progNames = doc.GetElementsByTagName("Program_Name");
XmlNodeList downloadUrls = doc.GetElementsByTagName("Primary_Download_URL");
XmlNodeList versionInfos = doc.GetElementsByTagName("Program_Version");
XmlNodeList versionInfos2 = doc.GetElementsByTagName("Filename_Versioned");
if (progNames.Count == 0 && downloadUrls.Count == 0) return null;
ApplicationJob job = new ApplicationJob {DownloadSourceType = SourceType.FixedUrl};
if (progNames.Count > 0)
{
job.Name = doc.GetElementsByTagName("Program_Name")[0].InnerText;
}
if (downloadUrls.Count > 0)
{
job.FixedDownloadUrl = doc.GetElementsByTagName("Primary_Download_URL")[0].InnerText;
}
if (versionInfos.Count > 0)
{
job.CachedPadFileVersion = doc.GetElementsByTagName("Program_Version")[0].InnerText;
}
else if (versionInfos2.Count > 0)
{
job.CachedPadFileVersion = doc.GetElementsByTagName("Filename_Versioned")[0].InnerText;
}
return job;
}
/// <summary>
/// Imports one or more ApplicationJobs from an XML file.
/// </summary>
/// <returns>List of imported ApplicationJobs</returns>
public static ApplicationJob[] ImportFromXml(string fileName)
{
return ImportFromXmlString(File.ReadAllText(fileName), true);
}
/// <summary>
/// Imports one or more ApplicationJobs from a piece of XML.
/// </summary>
/// <returns>List of imported ApplicationJobs</returns>
public static ApplicationJob[] ImportFromXmlString(string xml, bool save)
{
using (StringReader textReader = new StringReader(xml))
{
using (XmlReader reader = XmlReader.Create(textReader))
{
return ImportFromXml(reader, save);
}
}
}
/// <summary>
/// Returns an XML document containing this application job.
/// </summary>
public string GetXml()
{
return GetXml(new[] { this }, false, Encoding.UTF8);
}
/// <summary>
/// Returns an XML document containing this application job,
/// but replaces all global variables with the actual values.
/// </summary>
public string GetXmlWithoutGlobalVariables()
{
// Replace global variables
XmlDocument doc = new XmlDocument();
doc.LoadXml(this.GetXml());
// Adjust download URL
XmlNodeList downloadUrlElements = doc.GetElementsByTagName("FixedDownloadUrl");
if (downloadUrlElements.Count > 0)
{
XmlElement downloadUrlElement = downloadUrlElements[0] as XmlElement;
downloadUrlElement.InnerText = UrlVariable.GlobalVariables.ReplaceAllInString(downloadUrlElement.InnerText);
}
// Adjust variables
XmlNodeList urlVariableElements = doc.GetElementsByTagName("UrlVariable");
foreach (XmlElement urlVariable in urlVariableElements)
{
foreach (XmlElement subElement in urlVariable.ChildNodes)
{
if (subElement.Name == "Url" || subElement.Name == "TextualContent")
{