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;
2using System.Collections.Generic;
3using System.IO;
4using System.Text;
5using System.Threading.Tasks;
6using System.Xml;
7using System.Xml.Xsl;
8using Waher.Content;
12using 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 throw new BadRequestException();
70
71 object Obj = await Request.DecodeDataAsync();
72 if (!(Obj is Dictionary<string, object> Parameters))
73 throw new BadRequestException();
74
75 if (!Parameters.TryGetValue("repair", out Obj) || !(Obj is bool Repair))
76 throw new BadRequestException();
77
78 if (!CanStartAnalyzeDB())
79 {
80 Response.StatusCode = 409;
81 Response.StatusMessage = "Conflict";
82 Response.ContentType = PlainTextCodec.DefaultContentType;
83 await Response.Write("Analysis is underway.");
84 }
85
86 string BasePath = await Export.GetFullExportFolderAsync();
87 if (!Directory.Exists(BasePath))
88 Directory.CreateDirectory(BasePath);
89
90 BasePath += Path.DirectorySeparatorChar;
91
92 string FullFileName = Path.Combine(BasePath, "DBReport " + DateTime.Now.ToString("yyyy-MM-dd HH_mm_ss"));
93 FullFileName = StartExport.GetUniqueFileName(FullFileName, ".xml");
94 FileStream fs = null;
95
96 try
97 {
98 fs = new FileStream(FullFileName, FileMode.Create, FileAccess.Write);
99 DateTime Created = File.GetCreationTime(FullFileName);
100 XmlWriter XmlOutput = XmlWriter.Create(fs, XML.WriterSettings(true, false));
101 string FileName = FullFileName.Substring(BasePath.Length);
102
103 Task _ = Task.Run(() => DoAnalyze(FullFileName, FileName, Created, XmlOutput, fs, Repair));
104
105 Response.StatusCode = 200;
106 Response.ContentType = PlainTextCodec.DefaultContentType;
107 await Response.Write(FileName);
108 await Response.SendResponse();
109 }
110 catch (Exception ex)
111 {
112 if (!(fs is null))
113 {
114 fs.Dispose();
115 File.Delete(FullFileName);
116 }
117
118 await Response.SendResponse(ex);
119 }
120 }
121
126 public static bool CanStartAnalyzeDB()
127 {
128 lock (synchObject)
129 {
130 if (analyzing)
131 return false;
132
133 analyzing = true;
134 }
135
136 return true;
137 }
138
139 private static bool analyzing = false;
140 private static readonly object synchObject = new object();
141 private static XslCompiledTransform xslt = null;
142 internal static System.Text.Encoding utf8Bom = new UTF8Encoding(true);
143
154 public static async Task<string[]> DoAnalyze(string FullPath, string FileName, DateTime Created, XmlWriter XmlOutput, FileStream fs, bool Repair)
155 {
156 string[] Collections = null;
157
158 try
159 {
160 Log.Informational("Starting analyzing database.", FileName);
161
162 ExportFormats.ExportFormat.UpdateClientsFileUpdated(FileName, 0, Created);
163
164 Collections = await Database.Analyze(XmlOutput, Path.Combine(Gateway.AppDataFolder, "Transforms", "DbStatXmlToHtml.xslt"),
165 Gateway.AppDataFolder, false, Repair);
166
167 XmlOutput.Flush();
168 fs.Flush();
169
170 ExportFormats.ExportFormat.UpdateClientsFileUpdated(FileName, fs.Length, Created);
171
172 XmlOutput.Dispose();
173 XmlOutput = null;
174
175 fs.Dispose();
176 fs = null;
177
178 if (xslt is null)
179 xslt = XSL.LoadTransform(typeof(Gateway).Namespace + ".Transforms.DbStatXmlToHtml.xslt");
180
181 string s = await Resources.ReadAllTextAsync(FullPath);
182 s = XSL.Transform(s, xslt);
183 byte[] Bin = utf8Bom.GetBytes(s);
184
185 string FullPath2 = FullPath.Substring(0, FullPath.Length - 4) + ".html";
186 await Resources.WriteAllBytesAsync(FullPath2, Bin);
187
188 ExportFormats.ExportFormat.UpdateClientsFileUpdated(FileName.Substring(0, FileName.Length - 4) + ".html", Bin.Length, Created);
189
190 Log.Informational("Database analysis successfully completed.", FileName);
191 }
192 catch (Exception ex)
193 {
194 Log.Exception(ex);
195
196 string[] Tabs = ClientEvents.GetTabIDsForLocation("/Settings/Backup.md");
197 await ClientEvents.PushEvent(Tabs, "BackupFailed", "{\"fileName\":\"" + CommonTypes.JsonStringEncode(FileName) +
198 "\", \"message\": \"" + CommonTypes.JsonStringEncode(ex.Message) + "\"}", true, "User");
199 }
200 finally
201 {
202 try
203 {
204 XmlOutput?.Dispose();
205 fs?.Dispose();
206 }
207 catch (Exception ex)
208 {
209 Log.Exception(ex);
210 }
211
212 lock (synchObject)
213 {
214 analyzing = false;
215 }
216 }
217
218 return Collections;
219 }
220
221 }
222}
Helps with parsing of commong data types.
Definition: CommonTypes.cs:13
static string JsonStringEncode(string s)
Encodes a string for inclusion in JSON.
Definition: CommonTypes.cs:803
Static class managing loading of resources stored as embedded resources or in content files.
Definition: Resources.cs:15
static Task WriteAllBytesAsync(string FileName, byte[] Data)
Creates a binary file asynchronously.
Definition: Resources.cs:216
static async Task< string > ReadAllTextAsync(string FileName)
Reads a text file asynchronously.
Definition: Resources.cs:205
Plain text encoder/decoder.
const string DefaultContentType
text/plain
Helps with common XML-related tasks.
Definition: XML.cs:19
static XmlWriterSettings WriterSettings(bool Indent, bool OmitXmlDeclaration)
Gets an XML writer settings object.
Definition: XML.cs:1177
Static class managing loading of XSL resources stored as embedded resources or in content files.
Definition: XSL.cs:15
static XslCompiledTransform LoadTransform(string ResourceName)
Loads an XSL transformation from an embedded resource.
Definition: XSL.cs:70
static string Transform(string XML, XslCompiledTransform Transform)
Transforms an XML document using an XSL transform.
Definition: XSL.cs:162
Static class managing the application event log. Applications and services log events on this static ...
Definition: Log.cs:13
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:1647
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:334
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:19
static async Task< string > GetFullExportFolderAsync()
Full path to export folder.
Definition: Export.cs:23
Static class managing the runtime environment of the IoT Gateway.
Definition: Gateway.cs:126
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:3041
static string AppDataFolder
Application data folder.
Definition: Gateway.cs:2369
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 string GetUniqueFileName(string Base, string Extension)
Gets a unique filename.
Definition: StartExport.cs:283
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:18
bool HasData
If the request has data.
Definition: HttpRequest.cs:74
async Task< object > DecodeDataAsync()
Decodes data sent in request.
Definition: HttpRequest.cs:95
Represets a response of an HTTP client request.
Definition: HttpResponse.cs:21
async Task SendResponse()
Sends the response back to the client. If the resource is synchronous, there's no need to call this m...
async 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:19
static Task< string[]> Analyze(XmlWriter Output, string XsltPath, string ProgramDataFolder, bool ExportData)
Analyzes the database and exports findings to XML.
Definition: Database.cs:1237
POST Interface for HTTP resources.