Neuron®
The Neuron® is the basis for the creation of open and secure federated networks for smart societies.
Loading...
Searching...
No Matches
StartAnalyze.cs
1using System;
3using System.IO;
4using System.Threading.Tasks;
5using System.Xml;
6using System.Xml.Xsl;
7using Waher.Content;
11using Waher.Events;
15
17{
22 {
26 public StartAnalyze()
27 : base("/StartAnalyze")
28 {
29 }
30
34 public override bool HandlesSubPaths
35 {
36 get
37 {
38 return false;
39 }
40 }
41
45 public override bool UserSessions
46 {
47 get
48 {
49 return true;
50 }
51 }
52
56 public bool AllowsPOST => true;
57
64 public async Task POST(HttpRequest Request, HttpResponse Response)
65 {
66 Gateway.AssertUserAuthenticated(Request, "Admin.Data.Backup");
67
68 if (!Request.HasData)
69 {
70 await Response.SendResponse(new BadRequestException());
71 return;
72 }
73
74 ContentResponse Content = await Request.DecodeDataAsync();
75 if (Content.HasError || !(Content.Decoded is Dictionary<string, object> Parameters))
76 {
77 await Response.SendResponse(new BadRequestException());
78 return;
79 }
80
81 if (!Parameters.TryGetValue("repair", out object Obj) || !(Obj is bool Repair))
82 {
83 await Response.SendResponse(new BadRequestException());
84 return;
85 }
86
87 if (!CanStartAnalyzeDB())
88 {
89 Response.StatusCode = 409;
90 Response.StatusMessage = "Conflict";
91 Response.ContentType = PlainTextCodec.DefaultContentType;
92 await Response.Write("Analysis is underway.");
93 }
94
95 string BasePath = await Export.GetFullExportFolderAsync();
96 if (!Directory.Exists(BasePath))
97 Directory.CreateDirectory(BasePath);
98
99 BasePath += Path.DirectorySeparatorChar;
100
101 string FullFileName = Path.Combine(BasePath, "DBReport " + DateTime.Now.ToString("yyyy-MM-dd HH_mm_ss"));
102 FullFileName = await StartExport.GetUniqueFileName(FullFileName, ".xml");
103 FileStream fs = null;
104
105 try
106 {
107 fs = new FileStream(FullFileName, FileMode.Create, FileAccess.Write);
108 DateTime Created = File.GetCreationTime(FullFileName);
109 XmlWriter XmlOutput = XmlWriter.Create(fs, XML.WriterSettings(true, false));
110 string FileName = FullFileName[BasePath.Length..];
111
112 Task _ = Task.Run(() => DoAnalyze(FullFileName, FileName, Created, XmlOutput, fs, Repair));
113
114 Response.StatusCode = 200;
115 Response.StatusMessage = "OK";
116 Response.ContentType = PlainTextCodec.DefaultContentType;
117 await Response.Write(FileName);
118 await Response.SendResponse();
119 }
120 catch (Exception ex)
121 {
122 if (!(fs is null))
123 {
124 fs.Dispose();
125 File.Delete(FullFileName);
126 }
127
128 await Response.SendResponse(ex);
129 }
130 }
131
136 public static bool CanStartAnalyzeDB()
137 {
138 lock (synchObject)
139 {
140 if (analyzing)
141 return false;
142
143 analyzing = true;
144 }
145
146 return true;
147 }
148
149 private static bool analyzing = false;
150 private static readonly object synchObject = new object();
151 private static XslCompiledTransform xslt = null;
152
163 public static async Task<string[]> DoAnalyze(string FullPath, string FileName, DateTime Created, XmlWriter XmlOutput, FileStream fs, bool Repair)
164 {
165 string[] Collections = null;
166
167 try
168 {
169 Log.Informational("Starting analyzing database.", FileName);
170
171 ExportFormats.ExportFormat.UpdateClientsFileUpdated(FileName, 0, Created);
172
173 Collections = await Database.Analyze(XmlOutput, Path.Combine(Gateway.AppDataFolder, "Transforms", "DbStatXmlToHtml.xslt"),
174 Gateway.AppDataFolder, false, Repair);
175
176 XmlOutput.Flush();
177 fs.Flush();
178
179 ExportFormats.ExportFormat.UpdateClientsFileUpdated(FileName, fs.Length, Created);
180
181 XmlOutput.Dispose();
182 XmlOutput = null;
183
184 fs.Dispose();
185 fs = null;
186
187 xslt ??= XSL.LoadTransform(typeof(Gateway).Namespace + ".Transforms.DbStatXmlToHtml.xslt");
188
189 string s = await Files.ReadAllTextAsync(FullPath);
190 s = XSL.Transform(s, xslt);
191 byte[] Bin = Strings.Utf8WithBom.GetBytes(s);
192
193 string FullPath2 = FullPath[..^4] + ".html";
194 await Files.WriteAllBytesAsync(FullPath2, Bin);
195
196 ExportFormats.ExportFormat.UpdateClientsFileUpdated(FileName[..^4] + ".html", Bin.Length, Created);
197
198 Log.Informational("Database analysis successfully completed.", FileName);
199 }
200 catch (Exception ex)
201 {
202 Log.Exception(ex);
203
204 string[] Tabs = ClientEvents.GetTabIDsForLocation("/Settings/Backup.md");
205 await ClientEvents.PushEvent(Tabs, "BackupFailed", "{\"fileName\":\"" + CommonTypes.JsonStringEncode(FileName) +
206 "\", \"message\": \"" + CommonTypes.JsonStringEncode(ex.Message) + "\"}", true, "User");
207 }
208 finally
209 {
210 try
211 {
212 XmlOutput?.Dispose();
213 fs?.Dispose();
214 }
215 catch (Exception ex)
216 {
217 Log.Exception(ex);
218 }
219
220 lock (synchObject)
221 {
222 analyzing = false;
223 }
224 }
225
226 return Collections;
227 }
228
229 }
230}
Helps with parsing of commong data types.
Definition: CommonTypes.cs:15
static string JsonStringEncode(string s)
Encodes a string for inclusion in JSON.
Definition: CommonTypes.cs:805
Contains information about a response to a content request.
bool HasError
If an error occurred.
object Decoded
Decoded object.
Plain text encoder/decoder.
const string DefaultContentType
text/plain
Helps with common XML-related tasks.
Definition: XML.cs:21
static XmlWriterSettings WriterSettings(bool Indent, bool OmitXmlDeclaration)
Gets an XML writer settings object.
Definition: XML.cs:1351
Static class managing loading of XSL resources stored as embedded resources or in content files.
Definition: XSL.cs:16
static XslCompiledTransform LoadTransform(string ResourceName)
Loads an XSL transformation from an embedded resource.
Definition: XSL.cs:86
static string Transform(string XML, XslCompiledTransform Transform)
Transforms an XML document using an XSL transform.
Definition: XSL.cs:197
Static class managing the application event log. Applications and services log events on this static ...
Definition: Log.cs:14
static void Exception(Exception Exception, string Object, string Actor, string EventId, EventLevel Level, string Facility, string Module, params KeyValuePair< string, object >[] Tags)
Logs an exception. Event type will be determined by the severity of the exception.
Definition: Log.cs:1657
static void Informational(string Message, string Object, string Actor, string EventId, EventLevel Level, string Facility, string Module, string StackTrace, params KeyValuePair< string, object >[] Tags)
Logs an informational event.
Definition: Log.cs:344
The ClientEvents class allows applications to push information asynchronously to web clients connecte...
Definition: ClientEvents.cs:51
static string[] GetTabIDsForLocation(string Location)
Gets the Tab IDs of all tabs that display a particular resource.
static Task< int > PushEvent(string[] TabIDs, string Type, object Data)
Puses an event to a set of Tabs, given their Tab IDs.
Static class managing data export.
Definition: Export.cs:18
static async Task< string > GetFullExportFolderAsync()
Full path to export folder.
Definition: Export.cs:22
Static class managing the runtime environment of the IoT Gateway.
Definition: Gateway.cs:147
static IUser AssertUserAuthenticated(HttpRequest Request, string Privilege)
Makes sure a request is being made from a session with a successful user login.
Definition: Gateway.cs:3868
static string AppDataFolder
Application data folder.
Definition: Gateway.cs:3132
Starts analyzing the database
Definition: StartAnalyze.cs:22
override bool UserSessions
If the resource uses user sessions.
Definition: StartAnalyze.cs:46
static bool CanStartAnalyzeDB()
Checks to see if analyzing the database can start.
StartAnalyze()
Starts analyzing the database
Definition: StartAnalyze.cs:26
static async Task< string[]> DoAnalyze(string FullPath, string FileName, DateTime Created, XmlWriter XmlOutput, FileStream fs, bool Repair)
Analyzes the object database
bool AllowsPOST
If the POST method is allowed.
Definition: StartAnalyze.cs:56
override bool HandlesSubPaths
If the resource handles sub-paths.
Definition: StartAnalyze.cs:35
async Task POST(HttpRequest Request, HttpResponse Response)
Executes the POST method on the resource.
Definition: StartAnalyze.cs:64
static async Task< string > GetUniqueFileName(string Base, string Extension)
Gets a unique filename.
Definition: StartExport.cs:321
The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repe...
Represents an HTTP request.
Definition: HttpRequest.cs:22
bool HasData
If the request has data.
Definition: HttpRequest.cs:113
async Task< ContentResponse > DecodeDataAsync()
Decodes data sent in request.
Definition: HttpRequest.cs:139
Represets a response of an HTTP client request.
Definition: HttpResponse.cs:23
async Task SendResponse()
Sends the response back to the client. If the resource is synchronous, there's no need to call this m...
Task Write(byte[] Data)
Returns binary data in the response.
Base class for all synchronous HTTP resources. A synchronous resource responds within the method hand...
Static interface for database persistence. In order to work, a database provider has to be assigned t...
Definition: Database.cs:21
static Task< string[]> Analyze(XmlWriter Output, string XsltPath, string ProgramDataFolder, bool ExportData)
Analyzes the database and exports findings to XML.
Definition: Database.cs:1985
Contains static methods
Definition: Files.cs:14
static Task WriteAllBytesAsync(string FileName, byte[] Data)
Creates a binary file asynchronously.
Definition: Files.cs:33
static async Task< string > ReadAllTextAsync(string FileName)
Reads a text file asynchronously.
Definition: Files.cs:84
Static class managing binary representations of strings.
Definition: Strings.cs:10
static Encoding Utf8WithBom
UTF-8 encoding with Byte Order Mark (BOM)
Definition: Strings.cs:231
POST Interface for HTTP resources.
Definition: ImplTypes.g.cs:58