Projekt

Obecné

Profil

Stáhnout (4.96 KB) Statistiky
| Větev: | Tag: | Revize:
1 68087f99 Pultak
using System;
2
using System.Collections.Generic;
3
using System.Linq;
4
using System.Text;
5
using System.Threading.Tasks;
6
using LDClient.utils;
7
8
namespace LDClient.detection; 
9
10
/// <summary>
11
/// This abstract class implements the common functions of the IInfoFetcher interface
12
/// which defines the functionality of an info fetcher.
13
/// </summary>
14
public abstract class AInfoFetcher : IInfoFetcher {
15
16
    /// <summary>
17
    /// Default value of a serial number (undefined).
18
    /// </summary>
19
    private const string UndefinedSerialNumber = "number";
20
21
    /// <summary>
22
    /// Returns the head serial number of the debugger.
23
    /// </summary>
24
    public string HeadSerialNumber { get; set; } = UndefinedSerialNumber;
25
26
    /// <summary>
27
    /// Returns the body serial number of the debugger.
28
    /// </summary>
29
    public string BodySerialNumber { get; set; } = UndefinedSerialNumber;
30
31
    /// <summary>
32
    /// Instance of FileUtils which encapsulates common functionality
33
    /// when it comes to dealing with files (limited by the needs of this application).
34
    /// </summary>
35
    public IFileUtils FileUtils;
36
37
    /// <summary>
38
    /// Maximum number of attempts to locate and parse the .txt file.
39
    /// </summary>
40
    protected readonly uint _maxAttempts;
41
42
    /// <summary>
43
    /// Period (how often) the application tries to locate and parse the .txt file.
44
    /// </summary>
45
    protected readonly uint _waitPeriodMs;
46
47
    /// <summary>
48
    /// Path to the .txt file which is generated from the debugger.
49
    /// </summary>
50
    protected readonly string _infoFilePath;
51
52
    /// <summary>
53
    /// Abstract constructor of this class 
54
    /// </summary>
55
    /// <param name="maxAttempts">Maximum number of attempts to locate and parse the .txt file</param>
56
    /// <param name="waitPeriodMs">Period (how often) the application tries to locate and parse the .txt file</param>
57
    /// <param name="infoFilePath">Path to the .txt file which is generated from the debugger</param>
58
59
    protected AInfoFetcher(uint maxAttempts, uint waitPeriodMs, string infoFilePath) {
60
        this.FileUtils = new FileUtils();
61
        this._maxAttempts = maxAttempts;
62
        this._waitPeriodMs = waitPeriodMs;
63
        this._infoFilePath = infoFilePath;
64
    }
65
66
    /// <summary>
67
    /// Abstract definition of the data fetching function
68
    /// Function should send the commands to the debugger.
69
    /// </summary>
70
    /// <returns>true on success</returns>
71
    protected abstract bool FetchData();
72
73
    /// <summary>
74
    /// Fetches data from the debugger. It sends the commands defined
75
    /// in the appsettings.json file to the debugger and tries to
76
    /// parse the .txt (contains the serial numbers).
77
    /// </summary>
78
    /// <returns>True, if data was fetched successfully. False otherwise.</returns>
79
    public async Task<bool> FetchDataAsync() {
80
        Program.DefaultLogger.Info("Fetching data from the debugger.");
81
        // Send the commands to the debugger.
82
        var success = FetchData();
83
84
        // Make sure that all commands were sent and executed successfully.
85
        if (!success) {
86
            Program.DefaultLogger.Error("Failed to fetch data from the debugger.");
87
            return false;
88
        }
89
        // Periodically try to parse the .txt file. 
90
        for (var i = 0; i < _maxAttempts; i++) {
91
            Program.DefaultLogger.Info($"{i}. attempt to parse the info file.");
92
            // Try to parse .txt file.
93
            if (RetrieveDebuggerInfo(_infoFilePath)) {
94
                Program.DefaultLogger.Info($"Info file has been parsed successfully.");
95
                return true;
96
            }
97
            // Wait for a specified number of milliseconds.
98
            await Task.Delay((int)_waitPeriodMs);
99
        }
100
        Program.DefaultLogger.Error("Failed to parse the into file. It may have not been created.");
101
        return false;
102
    }
103
104
    /// <summary>
105
    /// Tries to retrieve information from the debugger.
106
    /// </summary>
107
    /// <param name="filePath">path to the .txt file that contains all information</param>
108
    /// <returns>True if the information was retrieved successfully. False, otherwise.</returns>
109
110
    protected bool RetrieveDebuggerInfo(string filePath) {
111
        try {
112
            // Read the content of the .txt file.
113
            var fileContent = FileUtils.ReadFileAllLines(filePath).Aggregate("", (current, line) => $"{current}{line}\n");
114
115
            // Parse it (try to find the serial numbers)
116
            var (headSerialNumber, bodySerialNumber) = DebuggerInfoParser.Parse(fileContent);
117
118
            // Store the serial numbers into class variables (properties)
119
            HeadSerialNumber = headSerialNumber;
120
            BodySerialNumber = bodySerialNumber;
121
122
            // Finally, delete the file.
123
            //File.Delete(filePath);
124
        } catch (Exception exception) {
125
            Program.DefaultLogger.Error($"Failed to retrieve debugger info. File {filePath} may not exist or it does not have the right format. {exception.Message}");
126
            return false;
127
        }
128
        return true;
129
    }
130
}