diff --git a/Src/A69WD/.vs/A69WD.csproj.dtbcache.json b/Src/A69WD/.vs/A69WD.csproj.dtbcache.json index 2e178ed..e9b8bfe 100644 --- a/Src/A69WD/.vs/A69WD.csproj.dtbcache.json +++ b/Src/A69WD/.vs/A69WD.csproj.dtbcache.json @@ -1 +1 @@ -{"RootPath":"C:\\Commesse\\_zPrivate\\A69WD\\Src\\A69WD","ProjectFileName":"A69WD.csproj","Configuration":"Debug|AnyCPU","FrameworkPath":"","Sources":[{"SourceFile":"App.cs"},{"SourceFile":"Data\\DBTools.cs"},{"SourceFile":"Net\\ATLink.cs"},{"SourceFile":"Net\\ATLinkState.cs"},{"SourceFile":"Net\\cA69Engine.cs"},{"SourceFile":"Net\\DownloadClient.cs"},{"SourceFile":"Net\\frmDownloader.cs"},{"SourceFile":"Net\\frmDownloader.Designer.cs"},{"SourceFile":"Data\\eLinkState.cs"},{"SourceFile":"General\\Cfg.cs"},{"SourceFile":"General\\cTools.cs"},{"SourceFile":"Logger.cs"},{"SourceFile":"Properties\\AssemblyInfo.cs"},{"SourceFile":"Properties\\Resources.Designer.cs"},{"SourceFile":"Properties\\Settings.Designer.cs"},{"SourceFile":"obj\\Debug\\.NETFramework,Version=v4.8.AssemblyAttributes.cs"}],"References":[{"Reference":"C:\\Commesse\\_zPrivate\\A69WD\\Src\\_Lib\\HtmlAgilityPack.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.8\\Microsoft.CSharp.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.8\\mscorlib.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.8\\System.Core.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.8\\System.Data.DataSetExtensions.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.8\\System.Data.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Commesse\\_zPrivate\\A69WD\\Src\\_Lib\\System.Data.SQLite.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.8\\System.Deployment.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.8\\System.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.8\\System.Drawing.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.8\\System.Net.Http.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.8\\System.Windows.Forms.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.8\\System.Xml.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.8\\System.Xml.Linq.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""}],"Analyzers":[],"Outputs":[{"OutputItemFullPath":"C:\\Commesse\\_zPrivate\\A69WD\\Src\\A69WD\\bin\\Debug\\A69WD.exe","OutputItemRelativePath":"A69WD.exe"},{"OutputItemFullPath":"","OutputItemRelativePath":""}],"CopyToOutputEntries":[]} \ No newline at end of file +{"RootPath":"C:\\Commesse\\_zPrivate\\A69WD\\Src\\A69WD","ProjectFileName":"A69WD.csproj","Configuration":"Debug|AnyCPU","FrameworkPath":"","Sources":[{"SourceFile":"App.cs"},{"SourceFile":"Data\\cNota.cs"},{"SourceFile":"Data\\cRac.cs"},{"SourceFile":"Data\\DBTools.cs"},{"SourceFile":"Net\\eLinkState.cs"},{"SourceFile":"Net\\cLink_A69.cs"},{"SourceFile":"Service\\Service_Crawler.cs"},{"SourceFile":"Site\\cSite_A69.cs"},{"SourceFile":"UI\\frmDownloader.cs"},{"SourceFile":"UI\\frmDownloader.Designer.cs"},{"SourceFile":"General\\Cfg.cs"},{"SourceFile":"General\\cTools.cs"},{"SourceFile":"General\\Logger.cs"},{"SourceFile":"Net\\iLink.cs"},{"SourceFile":"Properties\\AssemblyInfo.cs"},{"SourceFile":"Site\\iSiteType.cs"},{"SourceFile":"Properties\\Resources.Designer.cs"},{"SourceFile":"Properties\\Settings.Designer.cs"},{"SourceFile":"obj\\Debug\\.NETFramework,Version=v4.8.AssemblyAttributes.cs"}],"References":[{"Reference":"C:\\Commesse\\_zPrivate\\A69WD\\Src\\_Lib\\HtmlAgilityPack.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.8\\Microsoft.CSharp.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.8\\mscorlib.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.8\\System.Core.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.8\\System.Data.DataSetExtensions.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.8\\System.Data.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Commesse\\_zPrivate\\A69WD\\Src\\_Lib\\System.Data.SQLite.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.8\\System.Deployment.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.8\\System.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.8\\System.Drawing.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.8\\System.Net.Http.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.8\\System.Windows.Forms.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.8\\System.Xml.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""},{"Reference":"C:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.8\\System.Xml.Linq.dll","ResolvedFrom":"","OriginalItemSpec":"","Name":"","EmbedInteropTypes":false,"CopyLocal":false,"IsProjectReference":false,"ProjectPath":""}],"Analyzers":[],"Outputs":[{"OutputItemFullPath":"C:\\Commesse\\_zPrivate\\A69WD\\Src\\A69WD\\bin\\Debug\\A69WD.exe","OutputItemRelativePath":"A69WD.exe"},{"OutputItemFullPath":"","OutputItemRelativePath":""}],"CopyToOutputEntries":[]} \ No newline at end of file diff --git a/Src/A69WD/A69WD.csproj b/Src/A69WD/A69WD.csproj index 7aad2c7..c18b60b 100644 --- a/Src/A69WD/A69WD.csproj +++ b/Src/A69WD/A69WD.csproj @@ -59,10 +59,13 @@ + + + Form diff --git a/Src/A69WD/Data/DBTools.cs b/Src/A69WD/Data/DBTools.cs index 816b6b0..e0b4cff 100644 --- a/Src/A69WD/Data/DBTools.cs +++ b/Src/A69WD/Data/DBTools.cs @@ -3,6 +3,8 @@ using System.Collections.Generic; using System.Text; using System.Data.SQLite; using A69WD.Net; +using System.Drawing; +using A69WD.Data; namespace A69WD { @@ -77,17 +79,62 @@ namespace A69WD { if (cn == null) cn = new System.Data.SQLite.SQLiteConnection("data source=:memory:"); cn.Open(); // Creo tabelle in uso - SQLiteCommand cmd = new SQLiteCommand(CreaA69DB(), cn); + SQLiteCommand cmd = new SQLiteCommand(CreaA69DB(false), cn); int res = cmd.ExecuteNonQuery(); if (res > 1) Logger.Log(new object[] { "Error Code: ER01022", string.Format("Possibile errore in DBTools() - cmd.ExecuteNonQuery(CreaA69DB())={0}", res) }); // Attach DB A69DB su File cmd = new SQLiteCommand(string.Format("ATTACH '{0}' AS A69DBfile", System.IO.Path.Combine(Cfg.Settings.PathDB, Cfg.Settings.DBName)), cn); res = cmd.ExecuteNonQuery(); - if (res > 1) Logger.Log(new object[] { "Error Code: ER01026b", string.Format("Possibile errore in DBTools() - cmd.ExecuteNonQuery(ATTACH {0} AS DBfile)", res) }); + if (res > 1) Logger.Log(new object[] { "Error Code: ER01026b", string.Format("Possibile errore in DBTools() - cmd.ExecuteNonQuery(ATTACH {0} AS A69DBfile)", res) }); // Copio i dati cmd = new SQLiteCommand("INSERT INTO [LinksLog] SELECT * FROM A69DBfile.LinksLog", cn); res = cmd.ExecuteNonQuery(); if (res < 1) Logger.Information(string.Format("Info Code: IN01001 - Nessun LinksLog riportato sul DB in memoria.", res)); + cmd = new SQLiteCommand("INSERT INTO [Voti] SELECT * FROM A69DBfile.Voti", cn); + res = cmd.ExecuteNonQuery(); + if (res < 1) Logger.Information(string.Format("Info Code: IN01002 - Nessun Voti riportato sul DB in memoria.", res)); + cmd = new SQLiteCommand("INSERT INTO [Racconti] SELECT * FROM A69DBfile.Racconti", cn); + res = cmd.ExecuteNonQuery(); + if (res < 1) Logger.Information(string.Format("Info Code: IN01003 - Nessun Racconti riportato sul DB in memoria.", res)); + cmd = new SQLiteCommand("INSERT INTO [Autori] SELECT * FROM A69DBfile.Autori", cn); + res = cmd.ExecuteNonQuery(); + if (res < 1) Logger.Information(string.Format("Info Code: IN01004 - Nessun Autori riportato sul DB in memoria.", res)); + cmd = new SQLiteCommand("INSERT INTO [Origini] SELECT * FROM A69DBfile.Origini", cn); + res = cmd.ExecuteNonQuery(); + if (res < 1) Logger.Information(string.Format("Info Code: IN01005 - Nessun Origini riportato sul DB in memoria.", res)); + cmd = new SQLiteCommand("INSERT INTO [Tags] SELECT * FROM A69DBfile.Tags", cn); + res = cmd.ExecuteNonQuery(); + if (res < 1) Logger.Information(string.Format("Info Code: IN01006 - Nessun Tags riportato sul DB in memoria.", res)); + cmd = new SQLiteCommand("INSERT INTO [Notes] SELECT * FROM A69DBfile.Notes", cn); + res = cmd.ExecuteNonQuery(); + if (res < 1) Logger.Information(string.Format("Info Code: IN01007 - Nessun Notes riportato sul DB in memoria.", res)); + cmd = new SQLiteCommand("INSERT INTO [Trame] SELECT * FROM A69DBfile.Trame", cn); + res = cmd.ExecuteNonQuery(); + if (res < 1) Logger.Information(string.Format("Info Code: IN01008 - Nessun Trame riportato sul DB in memoria.", res)); + cmd = new SQLiteCommand("INSERT INTO [Segnalini] SELECT * FROM A69DBfile.Segnalini", cn); + res = cmd.ExecuteNonQuery(); + if (res < 1) Logger.Information(string.Format("Info Code: IN01009 - Nessun Segnalini riportato sul DB in memoria.", res)); + cmd = new SQLiteCommand("INSERT INTO [Users] SELECT * FROM A69DBfile.Users", cn); + res = cmd.ExecuteNonQuery(); + if (res < 1) Logger.Information(string.Format("Info Code: IN01009 - Nessun Users riportato sul DB in memoria.", res)); + cmd = new SQLiteCommand("INSERT INTO [Links_Rac_Aut] SELECT * FROM A69DBfile.Links_Rac_Aut", cn); + res = cmd.ExecuteNonQuery(); + if (res < 1) Logger.Information(string.Format("Info Code: IN01009 - Nessun Links_Rac_Aut riportato sul DB in memoria.", res)); + cmd = new SQLiteCommand("INSERT INTO [Links_Rac_Not] SELECT * FROM A69DBfile.Links_Rac_Not", cn); + res = cmd.ExecuteNonQuery(); + if (res < 1) Logger.Information(string.Format("Info Code: IN01009 - Nessun Links_Rac_Not riportato sul DB in memoria.", res)); + cmd = new SQLiteCommand("INSERT INTO [Links_Rac_Tag] SELECT * FROM A69DBfile.Links_Rac_Tag", cn); + res = cmd.ExecuteNonQuery(); + if (res < 1) Logger.Information(string.Format("Info Code: IN01009 - Nessun Links_Rac_Tag riportato sul DB in memoria.", res)); + cmd = new SQLiteCommand("INSERT INTO [Links_Rac_Ori] SELECT * FROM A69DBfile.Links_Rac_Ori", cn); + res = cmd.ExecuteNonQuery(); + if (res < 1) Logger.Information(string.Format("Info Code: IN01009 - Nessun Links_Rac_Ori riportato sul DB in memoria.", res)); + cmd = new SQLiteCommand("INSERT INTO [Links_Rac_Vot] SELECT * FROM A69DBfile.Links_Rac_Vot", cn); + res = cmd.ExecuteNonQuery(); + if (res < 1) Logger.Information(string.Format("Info Code: IN01009 - Nessun Links_Rac_Vot riportato sul DB in memoria.", res)); + cmd = new SQLiteCommand("INSERT INTO [Links_Rac_Sng] SELECT * FROM A69DBfile.Links_Rac_Sng", cn); + res = cmd.ExecuteNonQuery(); + if (res < 1) Logger.Information(string.Format("Info Code: IN01009 - Nessun Links_Rac_Sng riportato sul DB in memoria.", res)); // Detach del DB su File } catch (Exception ex) { Logger.Log(new object[] { "Error Code: ER01020", "Errore in ATLib.Data.DBtools() durante il trasferimento in memoria del DB", ex }); @@ -107,16 +154,86 @@ namespace A69WD { // Copio i valori creati: solo se il DB è OK: if (!DB_ok) return Res; try { - // Copio i dati saltando i doppioni - // Elimino i dati vecchi in A69DB: - SQLiteCommand cmd = new SQLiteCommand("DELETE FROM A69DBfile.LinksLog", cn); - int res = cmd.ExecuteNonQuery(); - if (res < 1) Logger.Information(string.Format("Info Code: IN03001 - Nessun LinksLog cancellato dal file del DB.", res)); - // Inserisco i nuovi dati in A69DB: + // Detach del DB su File + SQLiteCommand cmd = new SQLiteCommand("DETACH DATABASE A69DBfile", cn); + int res = cmd.ExecuteNonQuery(); + if (res > 1) Logger.Log(new object[] { "Error Code: ER01026", string.Format("Possibile errore in DBTools() - cmd.ExecuteNonQuery(DETACH {0} AS A69DBfile)", res) }); + + // Elimino il file rinominandolo per backup + string FullNameDB = System.IO.Path.Combine(Cfg.Settings.PathDB,Cfg.Settings.DBName); + string FullNameBkDB = FullNameDB.Replace(".db","_BK_" + DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss") + ".db"); + System.IO.File.Move(FullNameDB, FullNameBkDB); + + // Creo nuovo file vuoto su cui riportare i dati dalla memoria: + using (SQLiteConnection cnTmp = new SQLiteConnection(Cfg.Settings.DBConnectionString)) { + cnTmp.Open(); + cmd = new SQLiteCommand(CreaA69DB(false), cnTmp); + res = cmd.ExecuteNonQuery(); + if (res < 0) Logger.Log(new object[] { "Error Code: ER03011", string.Format("Possibile errore in DBTools() - cmd.ExecuteNonQuery(CreaDB(false, false))={0}", res) }); + cnTmp.Close(); + cnTmp.Dispose(); + } + + // Attach DB su File + cmd = new SQLiteCommand(string.Format("ATTACH '{0}' AS A69DBfile", System.IO.Path.Combine(Cfg.Settings.PathDB, Cfg.Settings.DBName)), cn); + res = cmd.ExecuteNonQuery(); + if (res > 1) Logger.Log(new object[] { "Error Code: ER03026", string.Format("Possibile errore in DBTools() - cmd.ExecuteNonQuery(ATTACH {0} AS A69DBfile)", res) }); + + // Copio i dati cmd = new SQLiteCommand("INSERT INTO A69DBfile.LinksLog SELECT * FROM LinksLog", cn); res = cmd.ExecuteNonQuery(); if (res < 1) Logger.Information(string.Format("Info Code: IN03002 - Nessun LinksLog riportato sul file del DB.", res)); + cmd = new SQLiteCommand("INSERT INTO A69DBfile.Voti SELECT * FROM Voti", cn); + res = cmd.ExecuteNonQuery(); + if (res < 1) Logger.Information(string.Format("Info Code: IN03002 - Nessun Voti riportato sul file DB.", res)); + cmd = new SQLiteCommand("INSERT INTO A69DBfile.Racconti SELECT * FROM [Racconti]", cn); + res = cmd.ExecuteNonQuery(); + if (res < 1) Logger.Information(string.Format("Info Code: IN03003 - Nessun Racconti riportato sul file DB.", res)); + cmd = new SQLiteCommand("INSERT INTO A69DBfile.Autori SELECT * FROM [Autori]", cn); + res = cmd.ExecuteNonQuery(); + if (res < 1) Logger.Information(string.Format("Info Code: IN03004 - Nessun Autori riportato sul file DB.", res)); + cmd = new SQLiteCommand("INSERT INTO A69DBfile.Origini SELECT * FROM [Origini]", cn); + res = cmd.ExecuteNonQuery(); + if (res < 1) Logger.Information(string.Format("Info Code: IN03005 - Nessun Origini riportato sul file DB.", res)); + cmd = new SQLiteCommand("INSERT INTO A69DBfile.Tags SELECT * FROM [Tags]", cn); + res = cmd.ExecuteNonQuery(); + if (res < 1) Logger.Information(string.Format("Info Code: IN03006 - Nessun Tags riportato sul file DB.", res)); + cmd = new SQLiteCommand("INSERT INTO A69DBfile.Notes SELECT * FROM [Notes]", cn); + res = cmd.ExecuteNonQuery(); + if (res < 1) Logger.Information(string.Format("Info Code: IN03007 - Nessun Notes riportato sul file DB.", res)); + cmd = new SQLiteCommand("INSERT INTO A69DBfile.Trame SELECT * FROM [Trame]", cn); + res = cmd.ExecuteNonQuery(); + if (res < 1) Logger.Information(string.Format("Info Code: IN03008 - Nessun Trame riportato sul file DB.", res)); + cmd = new SQLiteCommand("INSERT INTO A69DBfile.Segnalini SELECT * FROM [Segnalini]", cn); + res = cmd.ExecuteNonQuery(); + if (res < 1) Logger.Information(string.Format("Info Code: IN03009 - Nessun Segnalini riportato sul file DB.", res)); + cmd = new SQLiteCommand("INSERT INTO A69DBfile.Users SELECT * FROM [Users]", cn); + res = cmd.ExecuteNonQuery(); + if (res < 1) Logger.Information(string.Format("Info Code: IN03010 - Nessun Users riportato sul file DB.", res)); + cmd = new SQLiteCommand("INSERT INTO A69DBfile.Links_Rac_Aut SELECT * FROM [Links_Rac_Aut]", cn); + res = cmd.ExecuteNonQuery(); + if (res < 1) Logger.Information(string.Format("Info Code: IN03011 - Nessun Links_Rac_Aut riportato sul file DB.", res)); + cmd = new SQLiteCommand("INSERT INTO A69DBfile.Links_Rac_Not SELECT * FROM [Links_Rac_Not]", cn); + res = cmd.ExecuteNonQuery(); + if (res < 1) Logger.Information(string.Format("Info Code: IN03012 - Nessun Links_Rac_Not riportato sul file DB.", res)); + cmd = new SQLiteCommand("INSERT INTO A69DBfile.Links_Rac_Tag SELECT * FROM [Links_Rac_Tag]", cn); + res = cmd.ExecuteNonQuery(); + if (res < 1) Logger.Information(string.Format("Info Code: IN03013 - Nessun Links_Rac_Tag riportato sul file DB.", res)); + cmd = new SQLiteCommand("INSERT INTO A69DBfile.Links_Rac_Ori SELECT * FROM [Links_Rac_Ori]", cn); + res = cmd.ExecuteNonQuery(); + if (res < 1) Logger.Information(string.Format("Info Code: IN03014 - Nessun Links_Rac_Ori riportato sul file DB.", res)); + cmd = new SQLiteCommand("INSERT INTO A69DBfile.Links_Rac_Vot SELECT * FROM [Links_Rac_Vot]", cn); + res = cmd.ExecuteNonQuery(); + if (res < 1) Logger.Information(string.Format("Info Code: IN03015 - Nessun Links_Rac_Vot riportato sul file DB.", res)); + cmd = new SQLiteCommand("INSERT INTO A69DBfile.Links_Rac_Sng SELECT * FROM [Links_Rac_Sng]", cn); + res = cmd.ExecuteNonQuery(); + if (res < 1) Logger.Information(string.Format("Info Code: IN03016 - Nessun Links_Rac_Sng riportato sul file DB.", res)); + + // Detach del DB su File + cmd = new SQLiteCommand("DETACH DATABASE A69DBfile", cn); + res = cmd.ExecuteNonQuery(); + if (res > 1) Logger.Log(new object[] { "Error Code: ER01026", string.Format("Possibile errore in DBTools() - cmd.ExecuteNonQuery(DETACH {0} AS A69DBfile)", res) }); Res = true; } catch (Exception ex) { @@ -135,6 +252,7 @@ namespace A69WD { if (res > 1) Logger.Log(new object[] { "Error Code: IN03027", string.Format("Possibile errore in ATLib.Data.Dispose() - cmd.ExecuteNonQuery(VACUUM)={0}", res) }); conn.Close(); conn.Dispose(); + conn = null; Res = Res && true; } catch (Exception ex) { Logger.Log(new object[] { "Error Code: ER03003", "Errore in ATLib.Data.Dispose() durante la compressione del DB", ex }); @@ -146,7 +264,7 @@ namespace A69WD { } } - private string CreaA69DB() { + private string CreaA69DB(bool FixedData = true) { StringBuilder sb = new StringBuilder(); @@ -167,6 +285,425 @@ namespace A69WD { sb.AppendLine("-- "); sb.AppendLine("-- "); sb.AppendLine("------------------------------------------------------------------------------"); + sb.AppendLine(" -- "); + sb.AppendLine(" CREATE TABLE [Racconti] ( -- COMMENT "); + sb.AppendLine(" [IDrac] INTEGER PRIMARY KEY AUTOINCREMENT, -- COMMENT 'Identificativo del racconto' "); + sb.AppendLine(" [Title] TEXT NOT NULL DEFAULT 'Unknown', -- COMMENT 'Titolo del racconto' "); + sb.AppendLine(" [SubTitle] TEXT NOT NULL DEFAULT '', -- COMMENT 'Sottotitolo del racconto' "); + sb.AppendLine(" [Creato] TEXT NOT NULL DEFAULT '2000/12/31', -- COMMENT 'Data di creazione del racconto' "); + sb.AppendLine(" [Aggiornato] TEXT NOT NULL DEFAULT '2000/12/31' -- COMMENT 'Data dell''ultima modifica al racconto' "); + sb.AppendLine(" ); "); + sb.AppendLine(" CREATE TABLE [Autori] ( -- COMMENT='Tabella con tutti gli Autori dei Racconti dell''archivio.' "); + sb.AppendLine(" [IDaut] INTEGER PRIMARY KEY AUTOINCREMENT, -- COMMENT 'Identificativo del racconto' "); + sb.AppendLine(" [Autore] TEXT NON NULL DEFAULT 'Unknown', -- COMMENT 'Nickname dell autore', "); + sb.AppendLine(" UNIQUE(Autore) "); + sb.AppendLine(" ); "); + sb.AppendLine(" CREATE TABLE [Notes] ( -- COMMENT 'Tabella per rappresentare tramite coppia key-value delle note da associare ad un racconto. Da utilizzare per salvare il link da cui ho downloadato il racconto, oppure l''eventuale riassunto, o altro.' "); + sb.AppendLine(" [IDnot] INTEGER PRIMARY KEY, -- COMMENT 'Identificativo della nota' "); + sb.AppendLine(" [NKey] TEXT NON NULL DEFAULT 'Nota', -- COMMENT 'Nota Key: Identificativo del tipo di nota: Resume, Link, OriginalID, ...' "); + sb.AppendLine(" [NVal] TEXT NON NULL DEFAULT '', -- COMMENT 'Nota Value: valore della nota' "); + sb.AppendLine(" UNIQUE(NKey, NVal) "); + sb.AppendLine(" ); "); + sb.AppendLine(" CREATE TABLE [Origini] ( -- COMMENT 'Tabella con tutte le possibili Origini dei racconti.' "); + sb.AppendLine(" [IDori] INTEGER PRIMARY KEY, -- COMMENT 'Identificativo del origine' "); + sb.AppendLine(" [Origine] TEXT NON NULL DEFAULT 'Unknown', -- COMMENT 'Origine da cui ho preso il racconto' "); + sb.AppendLine(" UNIQUE(Origine) "); + sb.AppendLine(" ); "); + sb.AppendLine(" CREATE TABLE [Segnalini] ( -- COMMENT "); + sb.AppendLine(" [IDsng] INTEGER PRIMARY KEY, -- COMMENT 'Identificativo del segnalino' "); + sb.AppendLine(" [Linea] INTEGER NOT NULL DEFAULT 0, -- COMMENT 'Indice della linea che si vuole segnalare (0 inizio racconto)' "); + sb.AppendLine(" [Segnalino] TEXT NON NULL DEFAULT 'Read', -- COMMENT 'Descrizione del segnalino per semplice comprensione (Read pe ril segnalino automatico con il punto di lettura)' "); + sb.AppendLine(" UNIQUE(Linea, Segnalino) "); + sb.AppendLine(" ); "); + sb.AppendLine(" CREATE TABLE [Tags] ( -- COMMENT 'Tabella con tutte i tag che vogliamo associare ai Racconti.' "); + sb.AppendLine(" [IDtag] INTEGER PRIMARY KEY, -- COMMENT 'Identificativo del Tag' "); + sb.AppendLine(" [Tag] TEXT NON NULL COLLATE NOCASE, -- COMMENT 'Nome descrittivo del Tag' "); + sb.AppendLine(" UNIQUE(Tag) "); + sb.AppendLine(" ); "); + sb.AppendLine(" CREATE TABLE [Trame] ( -- COMMENT 'Tabella con tutte le Trame dei Racconti.' "); + sb.AppendLine(" [IDtra] INTEGER PRIMARY KEY, -- COMMENT 'Identificativo della trama' "); + sb.AppendLine(" [IDrac] INTEGER NON NULL, -- COMMENT 'Identificativo del racconto a cui la trama corrisponde (univoco perchè solo una trama per racconto). Rappresenta la relazione 1-1 fra Racconti-Trame' "); + sb.AppendLine(" [Trama] TEXT NON NULL, -- COMMENT 'Trama del racconto' "); + sb.AppendLine(" UNIQUE(IDrac), "); + sb.AppendLine(" FOREIGN KEY(`IDrac`) REFERENCES `Racconti`(`IDrac`) ON DELETE CASCADE ON UPDATE CASCADE "); + sb.AppendLine(" ); "); + sb.AppendLine(" CREATE TABLE [Voti] ( -- COMMENT 'Tabella con tutti i possibili Voti associabili ai Racconti.' "); + sb.AppendLine(" [IDvot] INTEGER PRIMARY KEY, -- COMMENT 'Identificativo del voto' "); + sb.AppendLine(" [Rating] INTEGER CHECK (Rating>-1 AND Rating<11), -- COMMENT 'Valore del voto per statistiche' "); + sb.AppendLine(" [Voto] TEXT NON NULL COLLATE NOCASE, -- COMMENT 'Voto da attribuire ad un racconto' "); + sb.AppendLine(" UNIQUE(Voto) "); + sb.AppendLine(" ); "); + sb.AppendLine(" CREATE TABLE [Users] ( -- COMMENT 'Elenco degli utenti abilitati della web application' "); + sb.AppendLine(" [IDusr] INTEGER PRIMARY KEY AUTOINCREMENT, -- COMMENT 'Identificativo dell''utente' "); + sb.AppendLine(" [Username] TEXT NOT NULL, -- COMMENT 'Username di identificazione dell''utente. Viene scelto dall''utente stesso al momento della registrazione' "); + sb.AppendLine(" [Password] TEXT NOT NULL, -- COMMENT 'Hash della password scelta dall''utente' "); + sb.AppendLine(" [Level] INTEGER NOT NULL DEFAULT 0, -- COMMENT 'Livello dell''utente nella web application. Di default è posto a 0 e solo l''amministratore può variarlo' "); + sb.AppendLine(" UNIQUE(Username) "); + sb.AppendLine(" ); "); + sb.AppendLine(" -- "); + sb.AppendLine(" -- Creazione delle tabelle per rappresentare i link fra i record "); + sb.AppendLine(" -- "); + sb.AppendLine(" CREATE TABLE [Links_Rac_Aut] ( -- COMMENT 'Tabella per rappresentare la relazione Molti-Molti fra i Racconti e i propri Autori.' "); + sb.AppendLine(" [IDlnk] INTEGER PRIMARY KEY, -- COMMENT 'Identificativo del link fra Racconti-Autori' "); + sb.AppendLine(" [IDrac] INTEGER NOT NULL, -- COMMENT 'Identificativo del racconto' "); + sb.AppendLine(" [IDaut] INTEGER NOT NULL, -- COMMENT 'Identificativo dell''autore' "); + sb.AppendLine(" UNIQUE(IDrac, IDaut), "); + sb.AppendLine(" FOREIGN KEY(`IDrac`) REFERENCES `Racconti`(`IDrac`) ON DELETE CASCADE ON UPDATE CASCADE, "); + sb.AppendLine(" FOREIGN KEY(`IDaut`) REFERENCES `Autori`(`IDaut`) ON DELETE CASCADE ON UPDATE CASCADE "); + sb.AppendLine(" ); "); + sb.AppendLine(" CREATE TABLE Links_Rac_Not ( -- COMMENT 'Tabella per rappresentare la relazione Molti-Molti fra i Racconti e le note (coppie key-Value).' "); + sb.AppendLine(" [IDlnk] INTEGER PRIMARY KEY, -- COMMENT 'Identificativo del link fra Racconti-Notes' "); + sb.AppendLine(" [IDrac] INTEGER NOT NULL, -- COMMENT 'Identificativo del racconto' "); + sb.AppendLine(" [IDnot] INTEGER NOT NULL, -- COMMENT 'Identificativo della nota' "); + sb.AppendLine(" UNIQUE(IDrac, IDnot), "); + sb.AppendLine(" FOREIGN KEY(`IDrac`) REFERENCES `Racconti`(`IDrac`) ON DELETE CASCADE ON UPDATE CASCADE, "); + sb.AppendLine(" FOREIGN KEY(`IDnot`) REFERENCES `Notes`(`IDnot`) ON DELETE CASCADE ON UPDATE CASCADE "); + sb.AppendLine(" ); "); + sb.AppendLine(" CREATE TABLE [Links_Rac_Tag] ( -- COMMENT 'Tabella per rappresentare la relazione Molti-Molti fra i Racconti e le propietà.' "); + sb.AppendLine(" [IDlnk] INTEGER PRIMARY KEY, -- COMMENT 'Identificativo del link fra Racconti-Tags' "); + sb.AppendLine(" [IDrac] INTEGER NOT NULL, -- COMMENT 'Identificativo del racconto' "); + sb.AppendLine(" [IDtag] INTEGER NOT NULL, -- COMMENT 'Identificativo della propietà' "); + sb.AppendLine(" UNIQUE(IDrac, IDtag), "); + sb.AppendLine(" FOREIGN KEY(`IDrac`) REFERENCES `Racconti`(`IDrac`) ON DELETE CASCADE ON UPDATE CASCADE, "); + sb.AppendLine(" FOREIGN KEY(`IDtag`) REFERENCES `Tags`(`IDtag`) ON DELETE CASCADE ON UPDATE CASCADE "); + sb.AppendLine(" ); "); + sb.AppendLine(" CREATE TABLE [Links_Rac_Ori] ( -- COMMENT 'Tabella per rappresentare la relazione Molti-1 fra i Racconti e le origini.' "); + sb.AppendLine(" [IDlnk] INTEGER PRIMARY KEY, -- COMMENT 'Identificativo del link fra Racconti-Origini' "); + sb.AppendLine(" [IDrac] INTEGER NOT NULL, -- COMMENT 'Identificativo del racconto' "); + sb.AppendLine(" [IDori] INTEGER NOT NULL, -- COMMENT 'Identificativo dell'' origine' "); + sb.AppendLine(" UNIQUE(IDrac, IDori), "); + sb.AppendLine(" FOREIGN KEY(`IDrac`) REFERENCES `Racconti`(`IDrac`) ON DELETE CASCADE ON UPDATE CASCADE, "); + sb.AppendLine(" FOREIGN KEY(`IDori`) REFERENCES `Origini`(`IDori`) ON DELETE CASCADE ON UPDATE CASCADE "); + sb.AppendLine(" ); "); + sb.AppendLine(" CREATE TABLE [Links_Rac_Vot] ( -- COMMENT 'Tabella per rappresentare la relazione Molti-1 fra i Racconti e i voti.' "); + sb.AppendLine(" [IDlnk] INTEGER PRIMARY KEY, -- COMMENT 'Identificativo del link fra Racconti-Voti' "); + sb.AppendLine(" [IDrac] INTEGER NOT NULL, -- COMMENT 'Identificativo del racconto' "); + sb.AppendLine(" [IDvot] INTEGER NOT NULL, -- COMMENT 'Identificativo del voto' "); + sb.AppendLine(" UNIQUE(IDrac), "); + sb.AppendLine(" FOREIGN KEY(`IDrac`) REFERENCES `Racconti`(`IDrac`) ON DELETE CASCADE ON UPDATE CASCADE, "); + sb.AppendLine(" FOREIGN KEY(`IDvot`) REFERENCES `Voti`(`IDvot`) ON DELETE CASCADE ON UPDATE CASCADE "); + sb.AppendLine(" ); "); + sb.AppendLine(" CREATE TABLE [Links_Rac_Sng] ( -- COMMENT 'Tabella per rappresentare la relazione 1-Molti fra i Racconti e i segnalini.' "); + sb.AppendLine(" [IDlnk] INTEGER PRIMARY KEY, -- COMMENT 'Identificativo del link fra Racconti-Segnalini' "); + sb.AppendLine(" [IDrac] INTEGER NOT NULL, -- COMMENT 'Identificativo del racconto' "); + sb.AppendLine(" [IDsng] INTEGER NOT NULL, -- COMMENT 'Identificativo del segnalino' "); + sb.AppendLine(" UNIQUE(IDsng), "); + sb.AppendLine(" FOREIGN KEY(`IDrac`) REFERENCES `Racconti`(`IDrac`) ON DELETE CASCADE ON UPDATE CASCADE, "); + sb.AppendLine(" FOREIGN KEY(`IDsng`) REFERENCES `Segnalini`(`IDsng`) ON DELETE CASCADE ON UPDATE CASCADE "); + sb.AppendLine(" ); "); + sb.AppendLine(" -- "); + sb.AppendLine(" -- Creazione degli indici: "); + sb.AppendLine(" -- "); + sb.AppendLine(" CREATE INDEX IDX_Voti ON Voti ( Voto COLLATE NOCASE ); "); + if (FixedData) { + sb.AppendLine(" -- "); + sb.AppendLine(" -- Inserimento dei dati iniziali noti: "); + sb.AppendLine(" -- "); + sb.AppendLine(" INSERT INTO `origini` (`IDori`, `Origine`) VALUES "); + sb.AppendLine(" (1, 'Unknown'), "); + sb.AppendLine(" (2, 'Autocreazione'), "); + sb.AppendLine(" (3, 'A69'), "); + sb.AppendLine(" (4, 'eRac'), "); + sb.AppendLine(" (5, 'Mil'); "); + sb.AppendLine(" INSERT INTO `users` (`IDusr`, `Username`, `Password`, `Level`) VALUES "); + sb.AppendLine(" (1, 'root', 'e10adc3949ba59abbe56e057f20f883e', 9), "); + sb.AppendLine(" (2, 'Mrk', 'ABC', 8), "); + sb.AppendLine(" (3, 'reader', 'A', 5), "); + sb.AppendLine(" (4, 'guest', 'A', 0); "); + sb.AppendLine(" INSERT INTO `voti` (`IDvot`, `Rating`, `Voto`) VALUES "); + sb.AppendLine(" (0, 0, 'Non Letto'), "); + sb.AppendLine(" (1, 1, 'Da Cancellare'), "); + sb.AppendLine(" (2, 2, 'Pessimo'), "); + sb.AppendLine(" (3, 3, 'Brutto'), "); + sb.AppendLine(" (4, 4, 'Scarso'), "); + sb.AppendLine(" (5, 5, 'Insufficiente'), "); + sb.AppendLine(" (6, 6, 'Sufficiente'), "); + sb.AppendLine(" (7, 7, 'Carino'), "); + sb.AppendLine(" (8, 8, 'Bello'), "); + sb.AppendLine(" (9, 9, 'Ottimo'), "); + sb.AppendLine(" (10, 10, 'Da Collezione'); "); + } + sb.AppendLine(" -- "); + sb.AppendLine(" -- Creazione dei trigger: "); + sb.AppendLine(" -- "); + sb.AppendLine(" --- Triggers sulla tabella Racconti: --- "); + sb.AppendLine(" CREATE TRIGGER TRG_Racconti_Delete "); + sb.AppendLine(" AFTER DELETE ON Racconti "); + sb.AppendLine(" BEGIN "); + sb.AppendLine(" "); + sb.AppendLine(" DELETE FROM Links_Rac_Aut WHERE IDrac=OLD.IDrac; "); + sb.AppendLine(" DELETE FROM Links_Rac_Ori WHERE IDrac=OLD.IDrac; "); + sb.AppendLine(" DELETE FROM Links_Rac_Tag WHERE IDrac=OLD.IDrac; "); + sb.AppendLine(" DELETE FROM Links_Rac_Not WHERE IDrac=OLD.IDrac; "); + sb.AppendLine(" DELETE FROM Links_Rac_Vot WHERE IDrac=OLD.IDrac; "); + sb.AppendLine(" DELETE FROM Links_Rac_Sng WHERE IDrac=OLD.IDrac; "); + sb.AppendLine(" DELETE FROM Trame WHERE IDrac=OLD.IDrac; "); + sb.AppendLine(" DELETE FROM Notes WHERE IDnot NOT IN(SELECT Notes.IDnot FROM Notes, Links_Rac_not WHERE Notes.IDnot = Links_Rac_Not.IDnot); "); + sb.AppendLine(" DELETE FROM Segnalini WHERE IDsng NOT IN(SELECT Segnalini.IDsng FROM Segnalini, Links_Rac_Sng WHERE Segnalini.IDsng = Links_Rac_Sng.IDsng); "); + sb.AppendLine(" END; "); + sb.AppendLine(" --- CREATE TRIGGER TRG_Racconti_Insert ... END; "); + sb.AppendLine(" --- CREATE TRIGGER TRG_Racconti_Update ... END; "); + sb.AppendLine(" --- Triggers sulla tabella Autori: --- "); + sb.AppendLine(" CREATE TRIGGER TRG_Autori_Delete "); + sb.AppendLine(" BEFORE DELETE ON Autori "); + sb.AppendLine(" BEGIN "); + sb.AppendLine(" SELECT CASE "); + sb.AppendLine(" WHEN (SELECT COUNT(IDlnk) FROM Links_Rac_Aut WHERE IDaut=OLD.IDaut) > 0 "); + sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Autore ancora riferito a dei racconti.') "); + sb.AppendLine(" END; "); + sb.AppendLine(" END; "); + sb.AppendLine(" --- CREATE TRIGGER TRG_Autori_Insert ... END; "); + sb.AppendLine(" --- CREATE TRIGGER TRG_Autori_Update ... END; "); + sb.AppendLine(" --- Triggers sulla tabella Origini: --- "); + sb.AppendLine(" CREATE TRIGGER TRG_Origini_Delete "); + sb.AppendLine(" BEFORE DELETE ON Origini "); + sb.AppendLine(" BEGIN "); + sb.AppendLine(" SELECT CASE "); + sb.AppendLine(" WHEN (SELECT COUNT(IDlnk) FROM Links_Rac_Ori WHERE IDori=OLD.IDori) > 0 "); + sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Origine ancora riferita a dei racconti.') "); + sb.AppendLine(" END; "); + sb.AppendLine(" END; "); + sb.AppendLine(" --- CREATE TRIGGER TRG_Origini_Insert_Origine ... END; "); + sb.AppendLine(" --- CREATE TRIGGER TRG_Origini_Update_Origine ... END; "); + sb.AppendLine(" --- Triggers sulla tabella Tags: --- "); + sb.AppendLine(" CREATE TRIGGER TRG_Tags_Delete "); + sb.AppendLine(" BEFORE DELETE ON Tags "); + sb.AppendLine(" BEGIN "); + sb.AppendLine(" SELECT CASE "); + sb.AppendLine(" WHEN (SELECT COUNT(IDlnk) FROM Links_Rac_Tag WHERE IDtag=OLD.IDtag) > 0 "); + sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Propietà ancora riferita a dei racconti.') "); + sb.AppendLine(" END; "); + sb.AppendLine(" END; "); + sb.AppendLine(" --- CREATE TRIGGER TRG_Tags_Insert ... END; "); + sb.AppendLine(" --- CREATE TRIGGER TRG_Tags_Update ... END; "); + sb.AppendLine(" --- Triggers sulla tabella Notes: --- "); + sb.AppendLine(" CREATE TRIGGER TRG_Notes_Delete "); + sb.AppendLine(" BEFORE DELETE ON Notes "); + sb.AppendLine(" BEGIN "); + sb.AppendLine(" SELECT CASE "); + sb.AppendLine(" WHEN (SELECT COUNT(IDlnk) FROM Links_Rac_Not WHERE IDnot=OLD.IDnot) > 0 "); + sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Nota ancora riferita a dei racconti.') "); + sb.AppendLine(" END; "); + sb.AppendLine(" END; "); + sb.AppendLine(" --- CREATE TRIGGER TRG_Notes_Insert ... END; "); + sb.AppendLine(" --- CREATE TRIGGER TRG_Notes_Update ... END; "); + sb.AppendLine(" --- Triggers sulla tabella Trame: --- "); + sb.AppendLine(" --- CREATE TRIGGER TRG_Trama_Delete ... END; "); + sb.AppendLine(" CREATE TRIGGER TRG_Trama_Insert "); + sb.AppendLine(" BEFORE INSERT ON Trame "); + sb.AppendLine(" BEGIN "); + sb.AppendLine(" SELECT CASE "); + sb.AppendLine(" WHEN (SELECT IDrac from Racconti WHERE IDrac=NEW.IDrac) IS NULL "); + sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Racconto associato alla trama non presente in ATDB.') "); + sb.AppendLine(" END; "); + sb.AppendLine(" END; "); + sb.AppendLine(" CREATE TRIGGER TRG_Trama_Update_Trama "); + sb.AppendLine(" BEFORE UPDATE OF IDrac ON Trame "); + sb.AppendLine(" BEGIN "); + sb.AppendLine(" SELECT CASE "); + sb.AppendLine(" WHEN (SELECT IDrac from Racconti WHERE IDrac=NEW.IDrac) IS NULL "); + sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Racconto associato alla trama non presente in ATDB.') "); + sb.AppendLine(" END; "); + sb.AppendLine(" END; "); + sb.AppendLine(" --- Triggers sulla tabella Segnalini: --- "); + sb.AppendLine(" CREATE TRIGGER TRG_Segnalini_Delete "); + sb.AppendLine(" BEFORE DELETE ON Segnalini "); + sb.AppendLine(" BEGIN "); + sb.AppendLine(" SELECT CASE "); + sb.AppendLine(" WHEN (SELECT COUNT(IDlnk) FROM Links_Rac_Sng WHERE IDsng=OLD.IDsng) > 0 "); + sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Segnalino ancora riferito a dei racconti.') "); + sb.AppendLine(" END; "); + sb.AppendLine(" END; "); + sb.AppendLine(" --- CREATE TRIGGER TRG_Segnalini_Insert ... END; "); + sb.AppendLine(" --- CREATE TRIGGER TRG_Segnalini_Update ... END; "); + sb.AppendLine(" --- Triggers sulla tabella Links_Rac_Aut: --- "); + sb.AppendLine(" --- CREATE TRIGGER TRG_Links_Rac_Aut_Delete ... END; "); + sb.AppendLine(" CREATE TRIGGER TRG_Links_Rac_Aut_Insert "); + sb.AppendLine(" BEFORE INSERT ON Links_Rac_Aut "); + sb.AppendLine(" BEGIN "); + sb.AppendLine(" SELECT CASE "); + sb.AppendLine(" WHEN (SELECT IDrac from Racconti WHERE IDrac=NEW.IDrac) IS NULL "); + sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Racconto, associato all autore, non presente in ATDB.') "); + sb.AppendLine(" WHEN (SELECT IDaut from Autori WHERE IDaut=NEW.IDaut) IS NULL "); + sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Autore, da associare al racconto, non presente in ATDB') "); + sb.AppendLine(" END; "); + sb.AppendLine(" END; "); + sb.AppendLine(" CREATE TRIGGER TRG_Links_Rac_Aut_Update_a "); + sb.AppendLine(" BEFORE UPDATE OF IDrac ON Links_Rac_Aut "); + sb.AppendLine(" BEGIN "); + sb.AppendLine(" SELECT CASE "); + sb.AppendLine(" WHEN (SELECT IDrac from Racconti WHERE IDrac=NEW.IDrac) IS NULL "); + sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Racconto, associato all autore, non presente in ATDB.') "); + sb.AppendLine(" END; "); + sb.AppendLine(" END; "); + sb.AppendLine(" CREATE TRIGGER TRG_Links_Rac_Aut_Update_b "); + sb.AppendLine(" BEFORE UPDATE OF IDaut ON Links_Rac_Aut "); + sb.AppendLine(" BEGIN "); + sb.AppendLine(" SELECT CASE "); + sb.AppendLine(" WHEN (SELECT IDaut from Autori WHERE IDaut=NEW.IDaut) IS NULL "); + sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Autore, da associare al racconto, non presente in ATDB') "); + sb.AppendLine(" END; "); + sb.AppendLine(" END; "); + sb.AppendLine(" --- Triggers sulla tabella Links_Rac_Ori: --- "); + sb.AppendLine(" --- CREATE TRIGGER TRG_Links_Rac_Ori_Delete ... END; "); + sb.AppendLine(" CREATE TRIGGER TRG_Links_Rac_Ori_Insert "); + sb.AppendLine(" BEFORE INSERT ON Links_Rac_Ori "); + sb.AppendLine(" BEGIN "); + sb.AppendLine(" SELECT CASE "); + sb.AppendLine(" WHEN (SELECT IDrac from Racconti WHERE IDrac=NEW.IDrac) IS NULL "); + sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Racconto, associato all origine, non presente in ATDB.') "); + sb.AppendLine(" WHEN (SELECT IDori from Origini WHERE IDori=NEW.IDori) IS NULL "); + sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Origine, da associare al racconto, non presente in ATDB') "); + sb.AppendLine(" END; "); + sb.AppendLine(" END; "); + sb.AppendLine(" CREATE TRIGGER TRG_Links_Rac_Ori_Update_a "); + sb.AppendLine(" BEFORE UPDATE OF IDrac ON Links_Rac_Ori "); + sb.AppendLine(" BEGIN "); + sb.AppendLine(" SELECT CASE "); + sb.AppendLine(" WHEN (SELECT IDrac from Racconti WHERE IDrac=NEW.IDrac) IS NULL "); + sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Racconto, associato all origine, non presente in ATDB.') "); + sb.AppendLine(" END; "); + sb.AppendLine(" END; "); + sb.AppendLine(" CREATE TRIGGER TRG_Links_Rac_Ori_Update_b "); + sb.AppendLine(" BEFORE UPDATE OF IDori ON Links_Rac_Ori "); + sb.AppendLine(" BEGIN "); + sb.AppendLine(" SELECT CASE "); + sb.AppendLine(" WHEN (SELECT IDori from Origini WHERE IDori=NEW.IDori) IS NULL "); + sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Origine, da associare al racconto, non presente in ATDB') "); + sb.AppendLine(" END; "); + sb.AppendLine(" END; "); + sb.AppendLine(" --- Triggers sulla tabella Links_Rac_Tag: --- "); + sb.AppendLine(" --- CREATE TRIGGER TRG_Links_Rac_Tag_Delete ... END; "); + sb.AppendLine(" CREATE TRIGGER TRG_Links_Rac_Tag_Insert "); + sb.AppendLine(" BEFORE INSERT ON Links_Rac_Tag "); + sb.AppendLine(" BEGIN "); + sb.AppendLine(" SELECT CASE "); + sb.AppendLine(" WHEN (SELECT IDrac from Racconti WHERE IDrac=NEW.IDrac) IS NULL "); + sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Racconto, associato alla propietà, non presente in ATDB.') "); + sb.AppendLine(" WHEN (SELECT IDtag from Tags WHERE IDtag=NEW.IDtag) IS NULL "); + sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Propietà, da associare al racconto, non presente in ATDB') "); + sb.AppendLine(" END; "); + sb.AppendLine(" END; "); + sb.AppendLine(" CREATE TRIGGER TRG_Links_Rac_Tag_Update_a "); + sb.AppendLine(" BEFORE UPDATE OF IDrac ON Links_Rac_Tag "); + sb.AppendLine(" BEGIN "); + sb.AppendLine(" SELECT CASE "); + sb.AppendLine(" WHEN (SELECT IDrac from Racconti WHERE IDrac=NEW.IDrac) IS NULL "); + sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Racconto, associato alla propietà, non presente in ATDB.') "); + sb.AppendLine(" END; "); + sb.AppendLine(" END; "); + sb.AppendLine(" CREATE TRIGGER TRG_Links_Rac_Tag_Update_b "); + sb.AppendLine(" BEFORE UPDATE OF IDtag ON Links_Rac_Tag "); + sb.AppendLine(" BEGIN "); + sb.AppendLine(" SELECT CASE "); + sb.AppendLine(" WHEN (SELECT IDtag from Tags WHERE IDtag=NEW.IDtag) IS NULL "); + sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Propietà, da associare al racconto, non presente in ATDB') "); + sb.AppendLine(" END; "); + sb.AppendLine(" END; "); + sb.AppendLine(" --- Triggers sulla tabella Links_Rac_Not: --- "); + sb.AppendLine(" --- CREATE TRIGGER TRG_Links_Rac_Not_Delete ... END; "); + sb.AppendLine(" CREATE TRIGGER TRG_Links_Rac_Not_Insert "); + sb.AppendLine(" BEFORE INSERT ON Links_Rac_Not "); + sb.AppendLine(" BEGIN "); + sb.AppendLine(" SELECT CASE "); + sb.AppendLine(" WHEN (SELECT IDrac from Racconti WHERE IDrac=NEW.IDrac) IS NULL "); + sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Racconto, associato alla nota, non presente in ATDB.') "); + sb.AppendLine(" WHEN (SELECT IDnot from Notes WHERE IDnot=NEW.IDnot) IS NULL "); + sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Nota, da associare al racconto, non presente in ATDB') "); + sb.AppendLine(" END; "); + sb.AppendLine(" END; "); + sb.AppendLine(" CREATE TRIGGER TRG_Links_Rac_Not_Update_a "); + sb.AppendLine(" BEFORE UPDATE OF IDrac ON Links_Rac_Not "); + sb.AppendLine(" BEGIN "); + sb.AppendLine(" SELECT CASE "); + sb.AppendLine(" WHEN (SELECT IDrac from Racconti WHERE IDrac=NEW.IDrac) IS NULL "); + sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Racconto, associato alla nota, non presente in ATDB.') "); + sb.AppendLine(" END; "); + sb.AppendLine(" END; "); + sb.AppendLine(" CREATE TRIGGER TRG_Links_Rac_Not_Update_b "); + sb.AppendLine(" BEFORE UPDATE OF IDnot ON Links_Rac_Not "); + sb.AppendLine(" BEGIN "); + sb.AppendLine(" SELECT CASE "); + sb.AppendLine(" WHEN (SELECT IDnot from Notes WHERE IDnot=NEW.IDnot) IS NULL "); + sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Nota, da associare al racconto, non presente in ATDB') "); + sb.AppendLine(" END; "); + sb.AppendLine(" END; "); + sb.AppendLine(" --- Triggers sulla tabella Links_Rac_Sng: --- "); + sb.AppendLine(" --- CREATE TRIGGER TRG_Links_Rac_Sng_Delete ... END; "); + sb.AppendLine(" CREATE TRIGGER TRG_Links_Rac_Sng_Insert "); + sb.AppendLine(" BEFORE INSERT ON Links_Rac_Sng "); + sb.AppendLine(" BEGIN "); + sb.AppendLine(" SELECT CASE "); + sb.AppendLine(" WHEN (SELECT IDrac from Racconti WHERE IDrac=NEW.IDrac) IS NULL "); + sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Racconto, associato al Segnalino, non presente in ATDB.') "); + sb.AppendLine(" WHEN (SELECT IDsng from Segnalini WHERE IDsng=NEW.IDsng) IS NULL "); + sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Segnalino, da associare al racconto, non presente in ATDB') "); + sb.AppendLine(" END; "); + sb.AppendLine(" END; "); + sb.AppendLine(" CREATE TRIGGER TRG_Links_Rac_Sng_Update_a "); + sb.AppendLine(" BEFORE UPDATE OF IDrac ON Links_Rac_Sng "); + sb.AppendLine(" BEGIN "); + sb.AppendLine(" SELECT CASE "); + sb.AppendLine(" WHEN (SELECT IDrac from Racconti WHERE IDrac=NEW.IDrac) IS NULL "); + sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Racconto, associato all Segnalino, non presente in ATDB.') "); + sb.AppendLine(" END; "); + sb.AppendLine(" END; "); + sb.AppendLine(" CREATE TRIGGER TRG_Links_Rac_Sng_Update_b "); + sb.AppendLine(" BEFORE UPDATE OF IDsng ON Links_Rac_Sng "); + sb.AppendLine(" BEGIN "); + sb.AppendLine(" SELECT CASE "); + sb.AppendLine(" WHEN (SELECT IDsng from Segnalini WHERE IDsng=NEW.IDsng) IS NULL "); + sb.AppendLine(" THEN RAISE(ABORT, 'Foreign key violation: Segnalino, da associare al racconto, non presente in ATDB') "); + sb.AppendLine(" END; "); + sb.AppendLine(" END; "); + sb.AppendLine(" CREATE VIEW Autore_Browser_Autori AS "); + sb.AppendLine(" SELECT "); + sb.AppendLine(" IDaut, "); + sb.AppendLine(" Autore, "); + sb.AppendLine(" ( "); + sb.AppendLine(" SELECT COUNT(IDaut) "); + sb.AppendLine(" FROM Links_Rac_Aut "); + sb.AppendLine(" WHERE Links_Rac_Aut.IDaut = Autori.IDaut "); + sb.AppendLine(" ) AS Num, "); + sb.AppendLine(" ( "); + sb.AppendLine(" SELECT AVG(Voti.IDvot) "); + sb.AppendLine(" FROM Links_Rac_Aut, "); + sb.AppendLine(" Links_Rac_Vot, "); + sb.AppendLine(" Voti "); + sb.AppendLine(" WHERE Links_Rac_Aut.IDaut = Autori.IDaut AND "); + sb.AppendLine(" Links_Rac_Vot.IDrac = Links_Rac_Aut.IDrac AND "); + sb.AppendLine(" Voti.IDvot = Links_Rac_Vot.IDvot AND "); + sb.AppendLine(" Voti.IDvot <> 0 "); + sb.AppendLine(" ) AS Rate "); + sb.AppendLine(" FROM Autori "); + sb.AppendLine(" ORDER BY Num DESC, Rate DESC; "); + sb.AppendLine(" -- "); + sb.AppendLine(" -- Inserimento delle viste: "); + sb.AppendLine(" -- "); + sb.AppendLine(" CREATE VIEW Tag_Browser_Tags AS "); + sb.AppendLine(" SELECT "); + sb.AppendLine(" IDtag, "); + sb.AppendLine(" Tag, "); + sb.AppendLine(" ( "); + sb.AppendLine(" SELECT COUNT(IDtag) "); + sb.AppendLine(" FROM Links_Rac_Tag "); + sb.AppendLine(" WHERE Links_Rac_Tag.IDtag = Tags.IDtag "); + sb.AppendLine(" ) AS Num, "); + sb.AppendLine(" ( "); + sb.AppendLine(" SELECT AVG(Voti.IDvot) "); + sb.AppendLine(" FROM Links_Rac_Tag, "); + sb.AppendLine(" Links_Rac_Vot, "); + sb.AppendLine(" Voti "); + sb.AppendLine(" WHERE Links_Rac_Tag.IDtag = Tags.IDtag AND "); + sb.AppendLine(" Links_Rac_Vot.IDrac = Links_Rac_Tag.IDrac AND "); + sb.AppendLine(" Voti.IDvot = Links_Rac_Vot.IDvot AND "); + sb.AppendLine(" Voti.IDvot <> 0 "); + sb.AppendLine(" ) AS Rate "); + sb.AppendLine(" FROM Tags "); + sb.AppendLine(" ORDER BY Num DESC, Rate DESC; "); + sb.AppendLine("-- "); + sb.AppendLine("-- "); + sb.AppendLine("------------------------------------------------------------------------------"); #endregion return sb.ToString(); @@ -176,120 +713,13 @@ namespace A69WD { #endregion - - public int LoadData(List allLinks, List toDownload, List downloaded, List racLinks) { - //object obj = new Object(); - //lock (obj) { - // int Res = 0; - // try { - - // // Carico tutti i racconti non ancora downloadati completamente: - // System.Data.SQLite.SQLiteCommand cmd = new SQLiteCommand("SELECT [URL], [Tipo], [Status], [LastUp] FROM [LinksLog] WHERE [Tipo]='Rac' AND [Status]<>4", cn); // Donwloaded = 4 - // SQLiteDataReader rdr = cmd.ExecuteReader(); - // while (rdr.Read()) { - // string url = rdr["URL"] as string; - // allLinks.Add(url); - // toDownload.Add(url); - // racLinks.Add(url); - // Res++; - // } - - // // Carico ora tutti i racconti downloadati completamente per evitare doppioni: - // cmd = new SQLiteCommand("SELECT [URL], [Tipo], [Status], [LastUp] FROM [LinksLog] WHERE [Tipo]='Rac' AND [Status]=4", cn); // Donwloaded = 4 - // rdr = cmd.ExecuteReader(); - // while (rdr.Read()) { - // string url = rdr["URL"] as string; - // allLinks.Add(url); - // racLinks.Add(url); - // Res++; - // } - - // } catch (Exception ex) { - // Logger.Log(new object[] { "Error Code: DB07003", "Errore in Data.DBTools.LoadData()", ex }); - // if (Res > 0) Res = -1 * Res; - // } - // return Res; - //} - return 0; - } - - public int SaveData(List allLinks, List toDownload, List downloaded, List racLinks) { - //object obj = new Object(); - //lock (obj) { - // int Res = 0; - // try { - // foreach (string link in racLinks) { LinkLogUpdtate(link, cA69Engine.LinkType(link), eLinkState.Donwloaded); } - // foreach (string link in toDownload) { LinkLogUpdtate(link, cA69Engine.LinkType(link), eLinkState.ToDownload); } - // foreach (string link in downloaded) { LinkLogUpdtate(link, cA69Engine.LinkType(link), eLinkState.Donwloaded); } - // } catch (Exception ex) { - // Logger.Log(new object[] { "Error Code: DB07003", "Errore in Data.DBTools.LoadData()", ex }); - // if (Res > 0) Res = -1 * Res; - // } - // return Res; - //} - return 0; - } - - - private bool LinkLogUpdtate(string url, string tip, eLinkState st) { - // object obj = new Object(); - // lock (obj) { - // Cancello riga (se non presente, non fa nulla) - // Inserisco riga - bool Res = false; - try { - // Cancello il link anche se non presente - System.Data.SQLite.SQLiteCommand cmd = new SQLiteCommand(string.Format("DELETE FROM [LinksLog] WHERE [URL]='{0}'", url), cn); - int res = cmd.ExecuteNonQuery(); - cmd = null; - // Inserisco il link come se fosse nuovo - cmd = new System.Data.SQLite.SQLiteCommand(); - cmd.Connection = cn; - cmd.CommandText = "INSERT INTO LinksLog (URL,Tipo,Status,LastUp)VALUES (@URL,@Tipo,@Status,@LastUp)"; - cmd.CommandType = System.Data.CommandType.Text; - System.Data.SQLite.SQLiteParameter param = new System.Data.SQLite.SQLiteParameter(); - param.ParameterName = "@URL"; - param.DbType = global::System.Data.DbType.String; - param.SourceColumn = "URL"; - cmd.Parameters.Add(param); - param = new System.Data.SQLite.SQLiteParameter(); - param.ParameterName = "@Tipo"; - param.DbType = global::System.Data.DbType.String; - param.SourceColumn = "Tipo"; - cmd.Parameters.Add(param); - param = new System.Data.SQLite.SQLiteParameter(); - param.ParameterName = "@Status"; - param.DbType = global::System.Data.DbType.Int32; - param.SourceColumn = "Status"; - cmd.Parameters.Add(param); - param = new System.Data.SQLite.SQLiteParameter(); - param.ParameterName = "@LastUp"; - param.DbType = global::System.Data.DbType.DateTime; - param.SourceColumn = "LastUp"; - cmd.Parameters.Add(param); - cmd.Parameters[0].Value = url; - cmd.Parameters[1].Value = tip; - cmd.Parameters[2].Value = st; - //if (InsertDate) { cmd.Parameters[3].Value = DateTime.Now; } else { cmd.Parameters[3].Value = DateTime.MaxValue; } - cmd.Parameters[3].Value = DateTime.Now; - res = cmd.ExecuteNonQuery(); - if (res != 1) { - Logger.Log(new object[] { "Error Code: DB06010", string.Format("DBTools.LinkLogUpdtate({0})={1}", url, res) }); - Res = false; - } else { - Res = true; - } - } catch (Exception ex) { - Logger.Log(new object[] { "Error Code: DB06001", string.Format("DBTools.LinkLogUpdtate({0})", url), ex }); - return false; - } finally { - //if ((cn != null) && (cn.State != System.Data.ConnectionState.Closed)) cn.Close(); - } - return Res; - // } // lock (obj) - } - - + + + /// + /// Ritorna lo stato di un link + /// + /// URL identificativo del link + /// Stato del link nel DB (ToDownload se link non presente nel DB) public eLinkState GetStateByURL(string url) { lock (objLock) { try { @@ -313,7 +743,12 @@ namespace A69WD { } } - + /// + /// Verifica se il link è già presente nel DB + /// + /// URL del link da testare + /// Offset temporale per la verifica (0 per l'intero DB) + /// True se URL presente, false altrimenti public bool IsPresent(string url, int timeOffset = 0) { lock (objLock) { try { @@ -425,6 +860,875 @@ namespace A69WD { // } // lock (obj) } + + + /// + /// Seleziona dal DB il racconto richiesto + /// + /// Identificativo del racconto desiderato + /// Ritorna il racconto estratto dal DB + public cRac GetRacById(long IDrac) { + lock (objLock) { + cRac rac = null; + List tmp = null; + try { + + // Creo nuovo racconto vuoto: + rac = new cRac(); + + #region Estraggo i dati dalla tabella 'Racconti': + + // Query per interrogare la tabella 'Racconti': + SQLiteCommand SelRac = new System.Data.SQLite.SQLiteCommand(); + SelRac.Connection = cn; + SelRac.CommandText = "SELECT * FROM Racconti WHERE IDrac=@IDrac"; + SelRac.CommandType = System.Data.CommandType.Text; + System.Data.SQLite.SQLiteParameter param = new System.Data.SQLite.SQLiteParameter(); + param.ParameterName = "@IDrac"; + param.DbType = global::System.Data.DbType.Int64; + param.SourceColumn = "IDrac"; + param.Value = IDrac; //SelRac.Parameters["@IDrac"].Value = IDrac; + SelRac.Parameters.Add(param); + SQLiteDataReader rdr = SelRac.ExecuteReader(); + bool res = rdr.Read(); + if (res == false) { + rdr.Close(); + rdr = null; + Logger.Information(String.Format("Attenzione, il racconto richiesto ({0}), non è stasto trovato.", IDrac.ToString())); + return new cRac("Errore", "Attenzione, il racconto richiesto non è stato trovato."); + } + rac.IDrac = (long)(rdr["IDrac"]); + if (rac.IDrac != IDrac) throw new Exception("Attenzione trovato ID diverso da quello richiesto"); + rac.Title = rdr["Title"] as string; + rac.SubTitle = rdr["SubTitle"] as string; + //rac.Creato = DateTime.Parse(rdr["Creato"].ToString()); + rac.Creato = DateTime.Parse(rdr["Creato"] as string); + //rac.Updated = DateTime.Parse(rdr["Aggiornato"].ToString()); + rac.Updated = DateTime.Parse(rdr["Aggiornato"].ToString()); + rdr.Close(); + rdr = null; + + #endregion + + #region Estraggo i dati dalla tabella 'Trame': + + // Query per interrogare la tabella 'Trame': + SQLiteCommand SelTra = new System.Data.SQLite.SQLiteCommand(); + SelTra.Connection = cn; + SelTra.CommandText = "SELECT Trama FROM Trame WHERE IDrac=@IDrac"; + SelTra.CommandType = System.Data.CommandType.Text; + param = new System.Data.SQLite.SQLiteParameter(); + param.ParameterName = "@IDrac"; + param.DbType = global::System.Data.DbType.Int64; + param.SourceColumn = "IDrac"; + param.Value = IDrac; //SelTra.Parameters["@IDrac"].Value = IDrac; + SelTra.Parameters.Add(param); + rdr = SelTra.ExecuteReader(); + res = rdr.Read(); + rac.Trama = rdr["Trama"] as string; + rdr.Close(); + rdr = null; + + #endregion + + #region Estraggo i dati dalla tabella 'Autori': + + // Query per interrogare la tabella 'Autori': + SQLiteCommand SelAut = new System.Data.SQLite.SQLiteCommand(); + SelAut.Connection = cn; + SelAut.CommandText = "SELECT Autori.Autore AS Autore FROM Autori, Links_Rac_Aut WHERE Autori.IDaut=Links_Rac_Aut.IDaut AND Links_Rac_Aut.IDrac=@IDrac GROUP BY Autori.Autore"; + SelAut.CommandType = System.Data.CommandType.Text; + param = new System.Data.SQLite.SQLiteParameter(); + param.ParameterName = "@IDrac"; + param.DbType = global::System.Data.DbType.Int64; + param.SourceColumn = "IDrac"; + param.Value = IDrac; //SelAut.Parameters["@IDrac"].Value = IDrac; + SelAut.Parameters.Add(param); + rdr = SelAut.ExecuteReader(); + if (rdr.HasRows) { + tmp = new List(); + while (rdr.Read()) { + tmp.Add(rdr["Autore"] as string); + } + tmp.Sort(); + rac.Autori = tmp; + tmp = null; + } + rdr.Close(); + rdr = null; + #endregion + + #region Estraggo i dati dalla tabella 'Tags': + + // Query per interrogare la tabella 'Tags': + SQLiteCommand SelTag = new System.Data.SQLite.SQLiteCommand(); + SelTag.Connection = cn; + SelTag.CommandText = "SELECT Tags.Tag as Tag FROM Tags, Links_Rac_Tag WHERE Tags.IDtag=Links_Rac_Tag.IDtag AND Links_Rac_Tag.IDrac=@IDrac"; + SelTag.CommandType = System.Data.CommandType.Text; + param = new System.Data.SQLite.SQLiteParameter(); + param.ParameterName = "@IDrac"; + param.DbType = global::System.Data.DbType.Int64; + param.SourceColumn = "IDrac"; + param.Value = IDrac; //SelTag.Parameters["@IDrac"].Value = IDrac; + SelTag.Parameters.Add(param); + rdr = SelTag.ExecuteReader(); + if (rdr.HasRows) { + tmp = new List(); + while (rdr.Read()) { + tmp.Add(rdr["Tag"] as string); + } + tmp.Sort(); + rac.Tags = tmp; + tmp = null; + } + rdr.Close(); + rdr = null; + + #endregion + + #region Estraggo i dati dalla tabella 'Origini': + + // Query per interrogare la tabella 'Origini': + SQLiteCommand SelOri = new System.Data.SQLite.SQLiteCommand(); + SelOri.Connection = cn; + SelOri.CommandText = "SELECT Origini.Origine as Origine FROM Origini, Links_Rac_Ori WHERE Origini.IDori=Links_Rac_Ori.IDori AND Links_Rac_Ori.IDrac=@IDrac"; + SelOri.CommandType = System.Data.CommandType.Text; + param = new System.Data.SQLite.SQLiteParameter(); + param.ParameterName = "@IDrac"; + param.DbType = global::System.Data.DbType.Int64; + param.SourceColumn = "IDrac"; + param.Value = IDrac; //SelOri.Parameters["@IDrac"].Value = IDrac; + SelOri.Parameters.Add(param); + rdr = SelOri.ExecuteReader(); + if (rdr.HasRows) { + tmp = new List(); + while (rdr.Read()) { + tmp.Add(rdr["Origine"] as string); + } + tmp.Sort(); + rac.Origini = tmp; + tmp = null; + } + rdr.Close(); + rdr = null; + #endregion + + #region Estraggo i dati dalla tabella 'Notes': + + // Query per interrogare la tabella 'Notes': + SQLiteCommand SelNot = new System.Data.SQLite.SQLiteCommand(); + SelNot.Connection = cn; + SelNot.CommandText = "SELECT Notes.NKey AS NKey, Notes.NVal AS NVal FROM Notes, Links_Rac_Not WHERE Notes.IDnot=Links_Rac_Not.IDnot AND Links_Rac_Not.IDrac=@IDrac"; + SelNot.CommandType = System.Data.CommandType.Text; + param = new System.Data.SQLite.SQLiteParameter(); + param.ParameterName = "@IDrac"; + param.DbType = global::System.Data.DbType.Int64; + param.SourceColumn = "IDrac"; + param.Value = IDrac; //SelNot.Parameters["@IDrac"].Value = IDrac; + SelNot.Parameters.Add(param); + rdr = SelNot.ExecuteReader(); + rac.Notes = new List(); + if (rdr.HasRows) { + while (rdr.Read()) { + rac.Notes.Add(new cNota((rdr["NKey"] as string), (rdr["NVal"] as string))); + } + } + rdr.Close(); + rdr = null; + + #endregion + + + #region Estraggo i dati dalla tabella 'Voti': + + // Query per interrogare la tabella 'Voti': + SQLiteCommand SelVot = new System.Data.SQLite.SQLiteCommand(); + SelVot.Connection = cn; + SelVot.CommandText = "SELECT Voti.Voto as Voto FROM Voti, Links_Rac_Vot WHERE Voti.IDvot=Links_Rac_Vot.IDvot AND Links_Rac_Vot.IDrac=@IDrac"; + SelVot.CommandType = System.Data.CommandType.Text; + param = new System.Data.SQLite.SQLiteParameter(); + param.ParameterName = "@IDrac"; + param.DbType = global::System.Data.DbType.Int64; + param.SourceColumn = "IDrac"; + param.Value = IDrac; //SelTag.Parameters["@IDrac"].Value = IDrac; + SelVot.Parameters.Add(param); + rdr = SelVot.ExecuteReader(); + res = rdr.Read(); + rac.Voto = rdr["Voto"] as string; + rdr.Close(); + rdr = null; + + #endregion + + rac.Validate(); + return rac; + + } catch (Exception ex) { + Logger.Error(string.Format("Error Code: {0} - Errore in {1}.{2}: {3}", "ER00080", System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.FullName, System.Reflection.MethodInfo.GetCurrentMethod().Name, ex.Message)); + rac = null; + } + return rac; + } + } + + + + + /// + /// Importa il racconto passato sul DB + /// + /// Racconto d aimportare + /// 1 se tutto ok, -1 se importazione abortita per errore, -10 se importazione abortita per duplicato, .... + public int ImportRac(cRac rac) { + lock (objLock) { + // Inizializzo le variabili che occorrono + int res = 0; + long IDvot = 0; + long IDrac = 0; + long IDtag = 0; + long IDaut = 0; + long IDori = 0; + long IDnot = 0; + try { + SQLiteCommand cmd = null; + + #region Verifico se il racconto da inserire è un duplicato + { + // Per ora definisco un racconto duplicato quando ha lo stesso titolo e la stessa trama. + cmd = new System.Data.SQLite.SQLiteCommand(); + cmd.Connection = cn; + cmd.CommandText = "SELECT IDrac FROM Trame WHERE Trama=@Trama LIMIT 1"; + cmd.CommandType = System.Data.CommandType.Text; + System.Data.SQLite.SQLiteParameter param = new System.Data.SQLite.SQLiteParameter(); + param.ParameterName = "@Trama"; + param.DbType = global::System.Data.DbType.String; + param.SourceColumn = "Trama"; + param.Value = rac.Trama; + cmd.Parameters.Add(param); + object RacID = cmd.ExecuteScalar(); + if (RacID != null) { + IDrac = (long)RacID; + if (IDrac > 0) { + + #region Unione del duplicato: + { + + // Ricavo il racconto originale su cui voglio unificare il duplicato: + cRac racOrig = GetRacById(IDrac); + + // Title & SubTitle + // Se titoli diversi, metto tutti e due i titoli suddividendoli e numerandoli: + if (racOrig.Title != rac.Title) { + racOrig.Title = string.Format("1 -> {0} -|- 2 -> {1}", racOrig.Title, rac.Title); + } + if (racOrig.SubTitle != rac.SubTitle) { + racOrig.SubTitle = string.Format("1 -> {0} -|- 2 -> {1}", racOrig.SubTitle, rac.SubTitle); + } + + // Creato + // Mantengo come data di creazione quella più antica delle due: + if (rac.Creato < racOrig.Creato) racOrig.Creato = rac.Creato; + + // Updated + // Mantengo come data di aggiornamento, quella più recente delle due: + if (rac.Updated > racOrig.Updated) racOrig.Updated = rac.Updated; + + // Autors + // Unisco tutti gli autori + if (racOrig.Autori == null) { + racOrig.Autori = rac.Autori; + } else { + foreach (string autore in rac.Autori) { + if (!racOrig.Autori.Contains(autore)) { + racOrig.Autori.Add(autore); + } + } + } + + // Voto + // Se uno dei due è "Non Letto" mantengo l'altro voto, altrimenti se non sono uguali lo segnalo. + if (rac.Voto != racOrig.Voto) { + if (racOrig.Voto == "Non Letto") { + racOrig.Voto = rac.Voto; + } else { + Logger.FailureAudit("ATTENZIONE UNIONE DI UN RACCONTO DUPLICATO; TROVATO VOTAZIONI DISCORDANTI"); + return -222; + } + } + + // Origine + // Unisco le varie origini raccogliendole tutte + if (racOrig.Origini == null) { + racOrig.Origini = rac.Origini; + } else { + foreach (string origine in rac.Origini) { + if (!racOrig.Origini.Contains(origine)) { + racOrig.Origini.Add(origine); + } + } + } + + // Tags + // Unisco le varie tag raccogliendole tutte + if (racOrig.Tags == null) { + racOrig.Tags = rac.Tags; + } else { + foreach (string tag in rac.Tags) { + if (!racOrig.Tags.Contains(tag)) { + racOrig.Tags.Add(tag); + } + } + } + + // Notes + // Per ora inserisco tutte le note ma devo fare attenzione ai duplicati o il DB mi dà errore: + if (racOrig.Notes == null) { + racOrig.Notes = rac.Notes; + } else { + foreach (cNota nota in rac.Notes) { + bool duplicata = false; + // Verifico se la key è già presente: + foreach (cNota notaOrig in racOrig.Notes) { + if (nota.Key == notaOrig.Key) { + if (nota.Description == notaOrig.Description) { + duplicata = true; + break; + } + } + } + if (!duplicata) racOrig.Notes.Add(nota); + } + } + + // Avviso di quanto fatto: + Logger.Warning("ATTENZIONE UNIONE DI UN RACCONTO DUPLICATO SUL RACCONTO: " + racOrig.strIDrac + " -> " + racOrig.fullTitle); + + // Eseguo l'update delle informazioni sul DB: + return UpdateRac(racOrig); + } + #endregion + + } + } + } + #endregion + + // Start a local transaction + SQLiteTransaction myTrans = cn.BeginTransaction(System.Data.IsolationLevel.ReadCommitted); + + + #region 10) Inserisco sulla tabella Racconti + try { + // Creo il nuovo record + cmd = new System.Data.SQLite.SQLiteCommand(); + cmd.Connection = cn; + cmd.CommandText = "INSERT INTO [Racconti]([Title], [SubTitle], [Creato], [Aggiornato]) VALUES (@Title, @SubTitle, @Creato, @Aggiornato)"; + cmd.CommandType = System.Data.CommandType.Text; + cmd.Parameters.Add("@Title", System.Data.DbType.String).Value = rac.Title; + cmd.Parameters.Add("@SubTitle", System.Data.DbType.String).Value = rac.SubTitle; + cmd.Parameters.Add("@Creato", System.Data.DbType.String).Value = rac.strCreato; + cmd.Parameters.Add("@Aggiornato", System.Data.DbType.String).Value = rac.strUpdated; + + res = cmd.ExecuteNonQuery(); + if (res != 1) { return -10; } + // Ricavo l'ID del record appena inserito + cmd.CommandText = "SELECT last_insert_rowid()"; + IDrac = (long)cmd.ExecuteScalar(); + } catch (Exception ex) { + Logger.Error(string.Format("Error Code: {0} - Errore in {1}.{2}: {3}", "ER00009", System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.FullName, System.Reflection.MethodInfo.GetCurrentMethod().Name, ex.Message)); + myTrans.Rollback(); + return -10; + } + #endregion + + #region 20) Inserisco sulla tabella Trama + try { + // Creo il nuovo record + cmd = new System.Data.SQLite.SQLiteCommand(); + cmd.Connection = cn; + cmd.CommandText = "INSERT INTO [Trame]([IDrac], [Trama]) VALUES (@IDrac, @Trama)"; + cmd.CommandType = System.Data.CommandType.Text; + cmd.Parameters.Add("@IDrac", System.Data.DbType.Int64).Value = IDrac; + cmd.Parameters.Add("@Trama", System.Data.DbType.String).Value = rac.Trama; + res = cmd.ExecuteNonQuery(); + if (res != 1) { return -20; } + } catch (Exception ex) { + Logger.Error(string.Format("Error Code: {0} - Errore in {1}.{2}: {3}", "ER00010", System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.FullName, System.Reflection.MethodInfo.GetCurrentMethod().Name, ex.Message)); + myTrans.Rollback(); + return -20; + } + #endregion + + #region 30) Inserisco sulla tabella Links_Rac_Vot + try { + // Decodifico il voto + // ToDo: Ricavare il IDvot dal Voto e non assegnarlo d'ufficio. + IDvot = 0; // Si sa già che il voto "Non Letto" ha indice 1 perchè fa parte dei valori predefiniti. + // Creo il nuovo record + cmd = new System.Data.SQLite.SQLiteCommand(); + cmd.Connection = cn; + cmd.CommandText = "INSERT INTO [Links_Rac_Vot]([IDrac], [IDvot]) VALUES (@IDrac, @IDvot)"; + cmd.CommandType = System.Data.CommandType.Text; + cmd.Parameters.Add("@IDrac", System.Data.DbType.Int64).Value = IDrac; + cmd.Parameters.Add("@IDvot", System.Data.DbType.Int64).Value = IDvot; + res = cmd.ExecuteNonQuery(); + if (res != 1) { return -30; } + } catch (Exception ex) { + Logger.Error(string.Format("Error Code: {0} - Errore in {1}.{2}: {3}", "ER00011", System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.FullName, System.Reflection.MethodInfo.GetCurrentMethod().Name, ex.Message)); + myTrans.Rollback(); + return -30; + } + #endregion + + #region 40) Inserisco i Tags (edito tabelle: Tags, Links_Rac_Tag) + try { + //foreach (string tag in rac.Tags) { + for (int i = 0; i < rac.Tags.Count; i++) { + // Ricavo l'ID del tag o lo inserisco sul DB: + cmd = new System.Data.SQLite.SQLiteCommand(); + cmd.Connection = cn; + cmd.CommandText = "SELECT IDtag FROM [Tags] WHERE [Tag]=@Tag"; + cmd.CommandType = System.Data.CommandType.Text; + cmd.Parameters.Add("@Tag", System.Data.DbType.String).Value = rac.Tags[i]; + try { IDtag = (long)cmd.ExecuteScalar(); } catch { + // Tag non presente in archivio, lo inserisco: + cmd.Parameters.Clear(); + cmd.CommandText = "INSERT INTO [Tags]([Tag]) VALUES (@Tag)"; + cmd.Parameters.Add("@Tag", System.Data.DbType.String).Value = rac.Tags[i]; + res = cmd.ExecuteNonQuery(); + if (res != 1) { return -40; } + // Ricavo l'ID del record appena inserito + cmd.Parameters.Clear(); + cmd.CommandText = "SELECT last_insert_rowid()"; + IDtag = (long)cmd.ExecuteScalar(); + } + // Assegno al racconto il tag: + cmd.Parameters.Clear(); + cmd.CommandText = "INSERT INTO [Links_Rac_Tag]([IDrac], [IDtag]) VALUES (@IDrac, @IDtag)"; + cmd.CommandType = System.Data.CommandType.Text; + cmd.Parameters.Add("@IDrac", System.Data.DbType.Int64).Value = IDrac; + cmd.Parameters.Add("@IDtag", System.Data.DbType.Int64).Value = IDtag; + res = cmd.ExecuteNonQuery(); + if (res != 1) { return -40; } + } + } catch (Exception ex) { + Logger.Error(string.Format("Error Code: {0} - Errore in {1}.{2}: {3}", "ER00012", System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.FullName, System.Reflection.MethodInfo.GetCurrentMethod().Name, ex.Message)); + myTrans.Rollback(); + return -40; + } + #endregion + + #region 50) Inserisco gli Autori (edito tabelle: Autori, Links_Rac_Aut) + try { + //foreach (string autore in rac.Autori) { + for (int i=0; i + /// Aggiorna i dati del racconto passato. + /// Se ID è valido aggiorna i dati del racconto già presente in memoria, altrimenti ne inserisce uno nuovo. + /// + /// Racconto da inserire sul DB + /// Codice di errore se negativo + public int UpdateRac(cRac rac) { + if (rac.IDrac == 0) { + return ImportRac(rac); + } else { + return _updateRac(rac); + } + } + + + /// + /// Aggiorna, nel DB, i dati del racconto passato. + /// + /// Racconto da inserire sul DB + /// Codice di errore se negativo + private int _updateRac(cRac rac) { + lock (objLock) { + + // Inizializzo le variabili che occorrono + int res = 0; + long IDvot = 0; + long IDtag = 0; + long IDaut = 0; + long IDori = 0; + long IDnot = 0; + + // Elimino il racconto per poi reinserirlo: + + try { + + #region 05) Elimino il racconto per poi reinserirlo + try { + SQLiteCommand cmd = new System.Data.SQLite.SQLiteCommand { + Connection = cn, + CommandText = "DELETE FROM [Racconti] WHERE [IDrac]=@IDrac", + CommandType = System.Data.CommandType.Text + }; + cmd.Parameters.Add("@IDrac", System.Data.DbType.Int64).Value = rac.IDrac; + res = cmd.ExecuteNonQuery(); + if (res != 1) { return -5; } + } catch (Exception ex) { + Logger.Error(string.Format("Error Code: {0} - Errore in {1}.{2}: {3}", "ER00001", System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.FullName, System.Reflection.MethodInfo.GetCurrentMethod().Name, ex.Message)); + return -10; + } + #endregion + + #region 10) Inserisco sulla tabella Racconti + try { + // Creo il nuovo record + SQLiteCommand cmd = new System.Data.SQLite.SQLiteCommand { + Connection = cn, + CommandText = "INSERT INTO [Racconti]([IDrac], [Title], [SubTitle], [Creato], [Aggiornato]) VALUES (@IDrac, @Title, @SubTitle, @Creato, @Aggiornato)", + CommandType = System.Data.CommandType.Text + }; + cmd.Parameters.Add("@IDrac", System.Data.DbType.Int64).Value = rac.IDrac; + cmd.Parameters.Add("@Title", System.Data.DbType.String).Value = rac.Title; + cmd.Parameters.Add("@SubTitle", System.Data.DbType.String).Value = rac.SubTitle; + cmd.Parameters.Add("@Creato", System.Data.DbType.String).Value = rac.strCreato; + cmd.Parameters.Add("@Aggiornato", System.Data.DbType.String).Value = rac.strUpdated; + res = cmd.ExecuteNonQuery(); + if (res != 1) { return -10; } + } catch (Exception ex) { + Logger.Error(string.Format("Error Code: {0} - Errore in {1}.{2}: {3}", "ER00002", System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.FullName, System.Reflection.MethodInfo.GetCurrentMethod().Name, ex.Message)); + return -10; + } + #endregion + + #region 20) Inserisco sulla tabella Trama + try { + // Creo il nuovo record + SQLiteCommand cmd = new System.Data.SQLite.SQLiteCommand { + Connection = cn, + CommandText = "INSERT INTO [Trame]([IDrac], [Trama]) VALUES (@IDrac, @Trama)", + CommandType = System.Data.CommandType.Text + }; + cmd.Parameters.Add("@IDrac", System.Data.DbType.Int64).Value = rac.IDrac; + cmd.Parameters.Add("@Trama", System.Data.DbType.String).Value = rac.Trama; + res = cmd.ExecuteNonQuery(); + if (res != 1) { return -20; } + } catch (Exception ex) { + Logger.Error(string.Format("Error Code: {0} - Errore in {1}.{2}: {3}", "ER00003", System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.FullName, System.Reflection.MethodInfo.GetCurrentMethod().Name, ex.Message)); + return -20; + } + #endregion + + #region 30) Inserisco sulla tabella Links_Rac_Vot + try { + // Decodifico il voto + SQLiteCommand cmd = new System.Data.SQLite.SQLiteCommand { + Connection = cn, + CommandText = "SELECT IDvot FROM Voti WHERE Voto=@Voto", + CommandType = System.Data.CommandType.Text + }; + cmd.Parameters.Add("@Voto", System.Data.DbType.String).Value = rac.Voto; + //IDvot = (long)cmd.ExecuteScalar(System.Data.CommandBehavior.Default); + IDvot = (long)cmd.ExecuteScalar(); + // Creo il nuovo record + cmd = new System.Data.SQLite.SQLiteCommand { + Connection = cn, + CommandText = "INSERT INTO [Links_Rac_Vot]([IDrac], [IDvot]) VALUES (@IDrac, @IDvot)", + CommandType = System.Data.CommandType.Text + }; + cmd.Parameters.Add("@IDrac", System.Data.DbType.Int64).Value = rac.IDrac; + cmd.Parameters.Add("@IDvot", System.Data.DbType.Int64).Value = IDvot; + res = cmd.ExecuteNonQuery(); + if (res != 1) { return -30; } + } catch (Exception ex) { + Logger.Error(string.Format("Error Code: {0} - Errore in {1}.{2}: {3}", "ER00004", System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.FullName, System.Reflection.MethodInfo.GetCurrentMethod().Name, ex.Message)); + return -30; + } + #endregion + + #region 40) Inserisco i Tags (edito tabelle: Tags, Links_Rac_Tag) + try { + foreach (string tag in rac.Tags) { + // Ricavo l'ID del tag o lo inserisco sul DB: + SQLiteCommand cmd = new System.Data.SQLite.SQLiteCommand { + Connection = cn, + CommandText = "SELECT IDtag FROM [Tags] WHERE [Tag]=@Tag", + CommandType = System.Data.CommandType.Text + }; + cmd.Parameters.Add("@Tag", System.Data.DbType.String).Value = tag; + try { IDtag = (long)cmd.ExecuteScalar(); } catch { + // Tag non presente in archivio, lo inserisco: + cmd.Parameters.Clear(); + cmd.CommandText = "INSERT INTO [Tags]([Tag]) VALUES (@Tag)"; + cmd.Parameters.Add("@Tag", System.Data.DbType.String).Value = tag; + res = cmd.ExecuteNonQuery(); + if (res != 1) { return -40; } + // Ricavo l'ID del record appena inserito + cmd.Parameters.Clear(); + cmd.CommandText = "SELECT last_insert_rowid()"; + IDtag = (long)cmd.ExecuteScalar(); + } + // Assegno al racconto il tag: + cmd.Parameters.Clear(); + cmd.CommandText = "INSERT INTO [Links_Rac_Tag]([IDrac], [IDtag]) VALUES (@IDrac, @IDtag)"; + cmd.CommandType = System.Data.CommandType.Text; + cmd.Parameters.Add("@IDrac", System.Data.DbType.Int64).Value = rac.IDrac; + cmd.Parameters.Add("@IDtag", System.Data.DbType.Int64).Value = IDtag; + res = cmd.ExecuteNonQuery(); + if (res != 1) { return -40; } + } + } catch (Exception ex) { + Logger.Error(string.Format("Error Code: {0} - Errore in {1}.{2}: {3}", "ER00005", System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.FullName, System.Reflection.MethodInfo.GetCurrentMethod().Name, ex.Message)); + return -40; + } + #endregion + + #region 50) Inserisco gli Autori (edito tabelle: Autori, Links_Rac_Aut) + try { + foreach (string autore in rac.Autori) { + // Ricavo l'ID del tag o lo inserisco sul DB: + SQLiteCommand cmd = new System.Data.SQLite.SQLiteCommand { + Connection = cn, + CommandText = "SELECT IDaut FROM [Autori] WHERE [Autore]=@Autore", + CommandType = System.Data.CommandType.Text + }; + cmd.Parameters.Add("@Autore", System.Data.DbType.String).Value = autore; + try { IDaut = (long)cmd.ExecuteScalar(); } catch { + // Tag non presente in archivio, lo inserisco: + cmd.Parameters.Clear(); + cmd.CommandText = "INSERT INTO [Autori]([Autore]) VALUES (@Autore)"; + cmd.Parameters.Add("@Autore", System.Data.DbType.String).Value = autore; + res = cmd.ExecuteNonQuery(); + if (res != 1) { return -50; } + // Ricavo l'ID del record appena inserito + cmd.Parameters.Clear(); + cmd.CommandText = "SELECT last_insert_rowid()"; + IDaut = (long)cmd.ExecuteScalar(); + } + // Assegno al racconto il tag: + cmd.Parameters.Clear(); + cmd.CommandText = "INSERT INTO [Links_Rac_Aut]([IDrac], [IDaut]) VALUES (@IDrac, @IDaut)"; + cmd.CommandType = System.Data.CommandType.Text; + cmd.Parameters.Add("@IDrac", System.Data.DbType.Int64).Value = rac.IDrac; + cmd.Parameters.Add("@IDaut", System.Data.DbType.Int64).Value = IDaut; + res = cmd.ExecuteNonQuery(); + if (res != 1) { return -50; } + } + } catch (Exception ex) { + Logger.Error(string.Format("Error Code: {0} - Errore in {1}.{2}: {3}", "ER00006", System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.FullName, System.Reflection.MethodInfo.GetCurrentMethod().Name, ex.Message)); + return -50; + } + #endregion + + #region 60) Inserisco le Origini (edito tabelle: Origini, Links_Rac_Ori) + try { + foreach (string origine in rac.Origini) { + // Ricavo l'ID dell'origine: + SQLiteCommand cmd = new System.Data.SQLite.SQLiteCommand { + Connection = cn, + CommandText = "SELECT IDori FROM [Origini] WHERE [Origine]=@Origine", + CommandType = System.Data.CommandType.Text + }; + cmd.Parameters.Add("@Origine", System.Data.DbType.String).Value = origine; + try { IDori = (long)cmd.ExecuteScalar(); } catch { + // Tag non presente in archivio, lo inserisco: + cmd.Parameters.Clear(); + cmd.CommandText = "INSERT INTO [Origini]([Origine]) VALUES (@Origine)"; + cmd.Parameters.Add("@Origine", System.Data.DbType.String).Value = origine; + res = cmd.ExecuteNonQuery(); + if (res != 1) { return -60; } + // Ricavo l'ID del record appena inserito + cmd.Parameters.Clear(); + cmd.CommandText = "SELECT last_insert_rowid()"; + IDori = (long)cmd.ExecuteScalar(); + } + // Assegno al racconto il tag: + cmd.Parameters.Clear(); + cmd.CommandText = "INSERT INTO [Links_Rac_Ori]([IDrac], [IDori]) VALUES (@IDrac, @IDori)"; + cmd.CommandType = System.Data.CommandType.Text; + cmd.Parameters.Add("@IDrac", System.Data.DbType.Int64).Value = rac.IDrac; + cmd.Parameters.Add("@IDori", System.Data.DbType.Int64).Value = IDori; + res = cmd.ExecuteNonQuery(); + if (res != 1) { return -60; } + } + } catch (Exception ex) { + Logger.Error(string.Format("Error Code: {0} - Errore in {1}.{2}: {3}", "ER00007", System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.FullName, System.Reflection.MethodInfo.GetCurrentMethod().Name, ex.Message)); + return -60; + } + #endregion + + #region 70) Inserisco le Note (edito tabelle: Notes, Links_Rac_Not) + try { + foreach (cNota nota in rac.Notes) { + // Verifico se la nota esiste ancora: + SQLiteCommand cmd = new System.Data.SQLite.SQLiteCommand { + Connection = cn, + CommandText = "SELECT IDnot FROM Notes WHERE NKey=@NKey AND NVal=@NVal", + CommandType = System.Data.CommandType.Text + }; + cmd.Parameters.Add("@NKey", System.Data.DbType.String).Value = nota.Key; + cmd.Parameters.Add("@NVal", System.Data.DbType.String).Value = nota.Description; + //try { IDnot = (long)cmd.ExecuteScalar(System.Data.CommandBehavior.Default); } catch (Exception ex) { + try { IDnot = (long)cmd.ExecuteScalar(); } catch (Exception ex) { + // Nota non presente in archivio, la inserisco: + SQLiteCommand cmdi = new System.Data.SQLite.SQLiteCommand { + Connection = cn, + CommandText = "INSERT INTO [Notes]([NKey], [NVal]) VALUES (@NKey, @NVal)", + CommandType = System.Data.CommandType.Text + }; + cmdi.Parameters.Add("@NKey", System.Data.DbType.String).Value = nota.Key; + cmdi.Parameters.Add("@NVal", System.Data.DbType.String).Value = nota.Description; + res = cmdi.ExecuteNonQuery(); + if (res != 1) { return -70; } + // Ricavo l'ID del record appena inserito + cmd.CommandText = "SELECT last_insert_rowid()"; + IDnot = (long)cmd.ExecuteScalar(); + } + // Lo associo al racconto + cmd.Parameters.Clear(); + cmd.CommandText = "INSERT INTO [Links_Rac_Not]([IDrac], [IDnot]) VALUES (@IDrac, @IDnot)"; + cmd.CommandType = System.Data.CommandType.Text; + cmd.Parameters.Add("@IDrac", System.Data.DbType.Int64).Value = rac.IDrac; + cmd.Parameters.Add("@IDnot", System.Data.DbType.Int64).Value = IDnot; + res = cmd.ExecuteNonQuery(); + if (res != 1) { return -70; } + } + } catch (Exception ex) { + Logger.Error(string.Format("Error Code: {0} - Errore in {1}.{2}: {3}", "ER00008", System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.FullName, System.Reflection.MethodInfo.GetCurrentMethod().Name, ex.Message)); + return -70; + } + #endregion + + return 1; + + } catch (Exception ex) { + Logger.Error(string.Format("Error Code: {0} - Errore in {1}.{2}: {3}", "ER00093", System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.FullName, System.Reflection.MethodInfo.GetCurrentMethod().Name, ex.Message)); + return -1; + } + } + } + + + + } // class DBTools diff --git a/Src/A69WD/Data/cNota.cs b/Src/A69WD/Data/cNota.cs new file mode 100644 index 0000000..566db36 --- /dev/null +++ b/Src/A69WD/Data/cNota.cs @@ -0,0 +1,38 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace A69WD.Data { + + /// + /// Serve per gestire una nota che sarà la coppia di stringhe: {Key} - {Descrizione} + /// + public class cNota { + + public string Key { get; set; } + public string Description { get; set; } + + /// + /// Stringa di separazione fra i vari campi quando esprimo un elenco tramite una singola stringa + /// + private const string SEPARATORETXT = " -|- "; + + public cNota() { + Key = ""; + Description = ""; + } + + public cNota(string key, string description) { + Key = key; + Description = description; + } + + public override string ToString() { + return Key + SEPARATORETXT + Description; + } + + }//class cNota + +}//namespace A69WD.Data diff --git a/Src/A69WD/Data/cRac.cs b/Src/A69WD/Data/cRac.cs new file mode 100644 index 0000000..c6bb4f1 --- /dev/null +++ b/Src/A69WD/Data/cRac.cs @@ -0,0 +1,830 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace A69WD.Data { + + public class cRac { + + #region Costruttori + + /// + /// Costruttore + /// + public cRac() { isValid = false; } + + /// + /// Costruttore per un racconto nullo, utilizzato per mostrare eventuali errori o messaggi + /// + /// Stringa che si vuole visualizzare come titolo del racconto + /// Stringa che si vuole visualizzare come testo del racconto + public cRac(string title, string trama) { + this.IDrac = 0; + this.Title = title; + this.Trama = "\n\n" + trama + "\n\n"; + this.Creato = DateTime.Now; + this.Updated = DateTime.Now; + this.isValid = true; + } + + + #endregion + + + #region Propietà e Fields: + + /// + /// Identificativo del racconto + /// + public long IDrac = -1; + + /// + /// Titolo del racconto + /// + public string Title = null; + + /// + /// Sottotitolo del racconto + /// + public string SubTitle = null; + + /// + /// Elenco dei tag (ex Props) associati al racconto + /// + public List Tags = null; + + /// + /// Note aggiuntive associate al racconto, sono del tipo: {Key} - {Descrizione} + /// Un tipo di nota sempre presente è la "Src" che individua la sorgente (link del file downloadato) da dove ho preso il racconto + /// Devo poter aver più source e quindi abbandono la struttura dizionario per avere una lista di coppie di stringhe + /// + //public System.Collections.Generic.Dictionary Notes = null; + public List Notes = null; + + /// + /// Elenco degli autori del racconto + /// + public List Autori = null; + + /// + /// Elenco delle origini del racconto + /// + public List Origini = null; + + /// + /// Voto assegnato al racconto + /// + public string Voto = null; + + /// + /// Trama del racconto + /// + public string Trama = null; + + /// + /// Data di creazione/pubblicazione del racconto o in mancanza di essa, data di inserimento del racconto in ATDB + /// + public DateTime Creato = DateTime.MinValue; + + /// + /// Data dell'ultimo update del racconto. + /// Inizialmente sarà la data di inserimento in ATDB, poi sarà la data dell'ultima lettura o dell'ultima iterazione con il racconto stesso. + /// + public DateTime Updated = DateTime.MinValue; + + #endregion + + + #region Metodi: strIDrac, strTags, fullTitle + + /// + /// ID del racconto espresso in formato testuale + /// + public string strIDrac { get { return IDrac.ToString("000000"); } } + + /// + /// Data di creazione del racconto espressa in forma testuale + /// + public string strCreato { get { return DateFormat(Creato); } } + + /// + /// Data di creazione del racconto espressa in forma testuale + /// + public string strUpdated { get { return DateFormat(Updated); } } + + /// + /// Elenco dei tags associati al racconto, espresso come singola stringa in cui i tag sono separati da | + /// + public string strTags { + get { + try { + string msg = ""; + Tags.Sort(); + foreach (string tags in Tags) { + msg += tags + SEPARATORETXT; + } + return msg.Remove(msg.Length - SEPARATORETXT.Length); + } catch { + return " "; + } + } + } + + /// + /// Elenco delle note associate al racconto, espresso come singola stringa in cui ciascuna riga è una nota e utilizzo il separatore per dividere la Key dalla Descrizione + /// + public string strNotes { + get { + try { + string msg = ""; + string endLine = "\r\n"; + Notes.Sort(); + foreach (cNota nota in Notes) { + msg += nota.ToString() + endLine; + } + return msg.Remove(msg.Length - endLine.Length); + } catch { + return " "; + } + } + } + + /// + /// Titolo completo del racconto, cioè il suo titolo con il sottotitolo + /// + public string fullTitle { + get { + if (string.IsNullOrEmpty(SubTitle)) { + return Title; + } else { + return Title + " - " + SubTitle; + } + } + } + + /// + /// Indica se il racconto è valido o no (nullo) + /// + public bool IsValid { get { return isValid; } } + private bool isValid = false; + + /// + /// Esegue la verifica dei dati del racconto e ritorna lo stato di raconto valido. + /// Per ora lo imposta di ufficio a valido, ma in futuro questo è da rivedere. + /// + public bool Validate() { + try { + isValid = true; + if (String.IsNullOrEmpty(Title) || String.IsNullOrWhiteSpace(Title)) { + Logger.Warning("NOT VALIDATE - Missing Title - " + strIDrac + " - " + fullTitle); + isValid = false; + } + if (String.IsNullOrEmpty(Trama) || String.IsNullOrWhiteSpace(Trama)) { + Logger.Warning("NOT VALIDATE - Missing Trama - " + strIDrac + " - " + fullTitle); + isValid = false; + } + if (Autori == null) { + Logger.Warning("NOT VALIDATE - Missing Autors -" + strIDrac + " - " + fullTitle); + isValid = false; + } else { + foreach (string autor in Autori) { + if (String.IsNullOrEmpty(autor) || String.IsNullOrWhiteSpace(autor)) { + Logger.Warning("NOT VALIDATE - Missing Autor -" + strIDrac + " - " + fullTitle); + isValid = false; + } + } + } + if (Tags == null) { + Logger.Warning("NOT VALIDATE - Missing Tags -" + strIDrac + " - " + fullTitle); + isValid = false; + } else { + foreach (string tag in Tags) { + if (String.IsNullOrEmpty(tag) || String.IsNullOrWhiteSpace(tag)) { + Logger.Warning("NOT VALIDATE - Missing Tag -" + strIDrac + " - " + fullTitle); + isValid = false; + } + } + } + if (Creato > Updated) { + Logger.Warning("NOT VALIDATE - Creato > Updated -" + strIDrac + " - " + fullTitle); + isValid = false; + } + } catch (Exception ex) { Logger.Log(new object[] { "Error Code:val001", "Errore in ATWD.Rac.Validate", ex }); } + + try { + //if (!isValid) { + // Logger.Warning("NOT VALIDATE: " + strIDrac + " - " + fullTitle); + //} + } catch (Exception ex) { Logger.Error(string.Format("Error Code: {0} - Errore in {1}.{2}: {3}", "ER375278", System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.FullName, System.Reflection.MethodInfo.GetCurrentMethod().Name, ex.Message)); } + + return isValid; + } + + #endregion + + + + /// + /// Crea il file html che rappresenta il racconto. + /// + /// True se tutto ok, False altrimenti. + public bool CreaFileRac() { + bool res = true; + try { + StringBuilder sb = new StringBuilder(); + sb.AppendFormat("\n\t\n\t\t{0}\n\t\t\n\t\n\t\n", fullTitle); + sb.AppendFormat("\t\t

{0}

\n", Title); + if (!string.IsNullOrEmpty(SubTitle)) sb.AppendFormat("\t\t

{0}

\n", SubTitle); + sb.Append("\t\t\n"); + if (Autori.Count == 1) { + sb.AppendFormat("\t\t

Autore: {0}

\n", Autori[0]); + } else { + sb.Append("\t\t

Autore: "); + foreach (string autor in Autori) { + sb.AppendFormat("{0} - ", autor); + } + sb.Append("

\n"); + } + sb.Append("\t\t

Propietà del racconto:
\n"); + foreach (string prop in Tags) { + sb.AppendFormat("{0}
\n", prop); + } + sb.Append("\t\t

"); + sb.AppendFormat("\t\t

Inserito il: {0}

\n", Creato.ToString("dd/MM/yyyy")); + if (Origini.Count == 1) { + sb.AppendFormat("\t\t

Origine: {0}

\n", Origini[0]); + } else { + sb.Append("\t\t

Origine: "); + foreach (string orig in Origini) { + sb.AppendFormat("{0} - ", orig); + } + sb.Append("

\n"); + } + sb.Append("\t\t

Note del racconto:
\n"); + foreach (cNota nota in Notes) { sb.AppendFormat("{0}
\n", nota.ToString()); } + sb.AppendFormat("ID: {0}
\n

", strIDrac); + //sb.AppendFormat("\t\t

{0}

\n", rac.Trama.Replace("\n", "

\n

")); + sb.AppendFormat("\t\t

{0}

\n", Trama.Replace("\n", "
")); + sb.Append("\t\t\n"); + sb.AppendLine("\t\n"); + // Salvo il file + cTools.WriteTextFile(System.IO.Path.Combine(Cfg.Settings.PathDownloadWorking, FileRacName(IDrac)), sb); + } catch (Exception ex) { + Logger.Log(new object[] { "Error Code: eBook003", "Errore in ATWD.frmMain.CreaFileToc(Racs)", ex }); + res = false; + } + return res; + } + + /// + /// Crea il file Markdown che rappresenta un racconto. + /// + /// True se tutto ok, False altrimenti. + public bool CreaFileMD() { + bool res = true; + try { + StringBuilder sb = new StringBuilder(); + sb.AppendFormat("# {0}\n", Title); + if (!string.IsNullOrEmpty(SubTitle)) sb.AppendFormat("## {0}\n", SubTitle); + if (Autori.Count == 1) { + sb.AppendFormat("### By {0}\n", Autori[0]); + } else { + sb.Append("### By "); + foreach (string autor in Autori) { + sb.AppendFormat("{0}, ", autor); + } + sb.Append("\n"); + } + sb.AppendFormat("- Voto: #{0} \n", Voto.Replace(" ", "")); + sb.Append("- Tags: "); + foreach (string prop in Tags) { + sb.AppendFormat("#{0} ", prop.Replace(" ", "")); + } + sb.Append("\n"); + sb.AppendFormat("- Creato: {0}\n", Creato.ToString("dd/MM/yyyy")); + sb.AppendFormat("- Update: {0}\n", Updated.ToString("dd/MM/yyyy")); + if (Origini.Count == 1) { + sb.AppendFormat("- Origin: {0}\n", Origini[0]); + } else { + sb.Append("- Origin: "); + foreach (string orig in Origini) { + sb.AppendFormat(" - {0}\n", orig); + } + } + sb.Append("- Notes: \n"); + foreach (cNota nota in Notes) { sb.AppendFormat(" - {0}
\n", nota.ToString()); } + sb.Append("\n"); + sb.AppendFormat("{0}\n", Trama); + sb.Append("\n"); + sb.Append("\n"); + // Salvo il file + cTools.WriteTextFile(System.IO.Path.Combine(Cfg.Settings.PathDownloadWorking, "Rac" + IDrac.ToString("00000") + ".md"), sb); + } catch (Exception ex) { + Logger.Log(new object[] { "Error Code: eBook003", "Errore in ATWD.frmMain.CreaFileMD(Racs)", ex }); + res = false; + } + return res; + } + + + /// + /// Crea un nome univoco per il file htm che rappresenta un racconto. + /// Rac00000.htm + /// + public static string FileRacName(long RacID) { return "Rac" + RacID.ToString("00000") + ".htm"; } + + /// + /// Stringa di separazione fra i vari campi quando esprimo un elenco tramite una singola stringa + /// + private const string SEPARATORETXT = " -|- "; + + /// + /// Esprime la data indicata con una stringa opportunamente formattata + /// + /// DateTime da esprimere in testo + /// Il testo opportunamente formattato + private string DateFormat(DateTime dt) { return dt.ToString("yyyy/MM/dd"); } + + /// + /// Override per esprimere in modo formale un racconto con una singola stringa. + /// + /// Stringa che rappresenta l'intero racconto + public override string ToString() { + try { + if (!Validate()) return string.Format("Racconto (ID={0}) non valido.", strIDrac); + + StringBuilder sb = new StringBuilder(); + sb.AppendFormat("- ID Rac:\t{0}\n", strIDrac); + sb.AppendFormat("- Title: \t{0}\n", Title); + sb.AppendFormat("- SubTit:\t{0}\n", SubTitle); + string tmp = ""; + if (Autori != null) { + Autori.Sort(); + foreach (string aut in Autori) { + tmp += string.Format("{0}{1}", aut, SEPARATORETXT); + } + if (tmp.Length > 0) tmp = tmp.Remove(tmp.Length - SEPARATORETXT.Length); + } + sb.AppendFormat("- Autors:\t{0}\n", tmp); + sb.AppendFormat("- Voto: \t{0}\n", Voto); + tmp = ""; + if (Tags != null) { + Tags.Sort(); + foreach (string tag in Tags) { tmp += string.Format("{0}{1}", tag, SEPARATORETXT); } + if (tmp.Length > 0) tmp = tmp.Remove(tmp.Length - SEPARATORETXT.Length); + } + sb.AppendFormat("- Tags: \t{0}\n", tmp); + tmp = ""; + if (Notes != null) { + foreach (cNota nota in Notes) { sb.AppendFormat("- Notes: \t{0}{2}{1}\n", nota.Key, nota.Description, SEPARATORETXT); } + } else { sb.Append("- Notes: \n"); } + sb.AppendFormat("- Creato:\t{0}\n", strCreato); + sb.AppendFormat("- Update:\t{0}\n", strUpdated); + tmp = ""; + if (Origini != null) { + Origini.Sort(); + foreach (string origine in Origini) { + tmp += string.Format("{0}{1}", origine, SEPARATORETXT); + } + if (tmp.Length > 0) tmp = tmp.Remove(tmp.Length - SEPARATORETXT.Length); + } + sb.AppendFormat("- Origin:\t{0}\n", tmp); + sb.AppendFormat("- Trama: \t{0}\n", Trama); + sb.AppendLine(""); + + return sb.ToString(); + } catch (Exception ex) { + Logger.Error(string.Format("Error Code: {0} - Errore in {1}.{2}: {3}", "ER00030", System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.FullName, System.Reflection.MethodInfo.GetCurrentMethod().Name, ex.Message)); + return string.Format(string.Format("Error Code: {0} - Errore in {1}.{2}: {3}", "ER00030", System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.FullName, System.Reflection.MethodInfo.GetCurrentMethod().Name, ex.Message)); + } + + } + + /// + /// Esprime il racconto in formato HTML formale. + /// + /// Stringa html che rappresenta l'intero racconto + public string ToHTML() { + try { + if (!Validate()) return string.Format("Racconto (ID={0}) non valido.", strIDrac); + + StringBuilder sb = new StringBuilder(); + sb.AppendFormat("\n\t\n\t\t{0}\n\t\n\t\n", fullTitle); + sb.AppendLine("\t\t"); + sb.AppendFormat("\t\t

Salta alla fine

\n", strIDrac); + sb.AppendLine("\t\t"); + sb.AppendFormat("\t\t

- ID Rac: {0}

\n", strIDrac); + sb.AppendFormat("\t\t

- Title: {0}

\n", Title); + sb.AppendFormat("\t\t

- SubTit: {0}

\n", SubTitle); + string tmp = ""; + if (Autori != null) { + Autori.Sort(); + foreach (string aut in Autori) { + tmp += string.Format("{0}{1}", aut, SEPARATORETXT); + } + if (tmp.Length > 2) tmp = tmp.Remove(tmp.Length - SEPARATORETXT.Length); + } + sb.AppendFormat("\t\t

- Autors: {0}

\n", tmp); + sb.AppendFormat("\t\t

- Voto: {0}

\n", Voto); + tmp = ""; + if (Tags != null) { + Tags.Sort(); + foreach (string tag in Tags) { tmp += string.Format("{0}{1}", tag, SEPARATORETXT); } + if (tmp.Length > 2) tmp = tmp.Remove(tmp.Length - SEPARATORETXT.Length); + } + sb.AppendFormat("\t\t

- Tags: {0}

\n", tmp); + + tmp = ""; + if (Notes != null) { + foreach (cNota nota in Notes) { sb.AppendFormat("\t\t

- Notes: {0}{2}{1}

\n", nota.Key, nota.Description, SEPARATORETXT); } + } else { sb.Append("\t\t

- Notes:

\n"); } + sb.AppendFormat("\t\t

- Creato: {0}

\n", strCreato); + sb.AppendFormat("\t\t

- Update: {0}

\n", strUpdated); + sb.AppendFormat("\t\t

- Trama: {0}

\n", Trama.Replace("\n", "\n")); + sb.AppendLine("\t\t"); + sb.AppendFormat("\t\t

Ritorna all'inizio

\n", strIDrac); + sb.AppendLine("\t\t"); + sb.AppendLine("\t\n"); + return sb.ToString(); + } catch (Exception ex) { + Logger.Error(string.Format("Error Code: {0} - Errore in {1}.{2}: {3}", "ER00040", System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.FullName, System.Reflection.MethodInfo.GetCurrentMethod().Name, ex.Message)); + return string.Format(string.Format("Error Code: {0} - Errore in {1}.{2}: {3}", "ER00040", System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.FullName, System.Reflection.MethodInfo.GetCurrentMethod().Name, ex.Message)); + } + } + + + /// + /// Esprime il racconto in una pagina html con lo style interno. + /// + /// Nome del racconto successivo a cui lincare + /// Stringa html che rappresenta l'intero racconto + public string ToHTML(string NextRacHtmlName) { + //try { + // if (!IsValid) return string.Format("Racconto (ID={0}) non valido.", strIDrac); + + // StringBuilder sb = new StringBuilder(); + // sb.AppendFormat("\n\t\n\t\t{0}\n\t\n\t\n", fullTitle); + // sb.AppendLine("\t\t"); + // //sb.AppendFormat("\t\t

Salta alla fine

\n", strIDrac); + // sb.AppendFormat("\t\t

Salta al prossimo

\n", strIDrac); + // sb.AppendLine("\t\t"); + // sb.AppendFormat("\t\t

- ID Rac: {0}

\n", strIDrac); + // sb.AppendFormat("\t\t

- Title: {0}

\n", Title); + // sb.AppendFormat("\t\t

- SubTit: {0}

\n", SubTitle); + // string tmp = ""; + // if (Autori != null) { + // for (int i = 0; i < Autori.Length; i++) { + // tmp += string.Format("{0} | ", Autori[i]); + // } + // if (tmp.Length > 2) tmp = tmp.Remove(tmp.Length - 3); + // } + // sb.AppendFormat("\t\t

- Autors: {0}

\n", tmp); + // sb.AppendFormat("\t\t

- Voto: {0}

\n", Voto); + // tmp = ""; + // if (Tags != null) { + // for (int i = 0; i < Tags.Length; i++) { + // tmp += string.Format("{0} | ", Tags[i]); + // } + // if (tmp.Length > 2) tmp = tmp.Remove(tmp.Length - 3); + // } + // sb.AppendFormat("\t\t

- Tags: {0}

\n", tmp); + + // tmp = ""; + // if (Notes != null) { + // for (int i = 0; i < Notes.Length; i++) { sb.AppendFormat("\t\t

- {0}

\n", Notes[i]); } + // } else { sb.Append("\t\t

- Notes:

\n"); } + // sb.AppendFormat("\t\t

- Creato: {0}

\n", Creato.ToString("dd/MM/yyyy")); + // sb.AppendFormat("\t\t

- Update: {0}

\n", Updated.ToString("dd/MM/yyyy")); + // sb.AppendFormat("\t\t

- Trama: {0}

\n", Trama.Replace("\n", "\n")); + // sb.AppendLine("\t\t"); + // sb.AppendFormat("\t\t

Ritorna all'inizio

\n", strIDrac); + // sb.AppendLine("\t\t"); + // sb.AppendLine("\t\n"); + // return sb.ToString(); + //} catch (Exception ex) { + // Logger.Error(string.Format("Error Code: {0} - Errore in {1}.{2}: {3}", "ER00040", System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.FullName, System.Reflection.MethodInfo.GetCurrentMethod().Name, ex.Message)); + // return string.Format(string.Format("Error Code: {0} - Errore in {1}.{2}: {3}", "ER00040", System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.FullName, System.Reflection.MethodInfo.GetCurrentMethod().Name, ex.Message)); + //} + try { + if (!Validate()) return string.Format("Racconto (ID={0}) non valido.", strIDrac); + + StringBuilder sb = new StringBuilder(); + sb.Append("\n\t\n\t\t\n\t\t\n\t\t{0}\n\t\n\t", fullTitle); + sb.AppendLine("\t\t"); + sb.AppendFormat("\t\t
Salta al prossimo

\n", strIDrac); + sb.AppendLine("\t\t"); + sb.AppendFormat("\t\t

{0}

\n", strIDrac); + sb.AppendFormat("\t\t

{0}

\n", Title); + sb.AppendFormat("\t\t

{0}

\n", SubTitle); + string tmp = ""; + if (Autori != null) { + Autori.Sort(); + foreach (string aut in Autori) { + tmp += string.Format("{0}{1}", aut, SEPARATORETXT); + } + if (tmp.Length > 2) tmp = tmp.Remove(tmp.Length - 3); + } + sb.AppendFormat("\t\t

- Autors: {0}

\n", tmp); + sb.AppendFormat("\t\t

- Voto: {0}

\n", Voto); + tmp = ""; + if (Tags != null) { + Tags.Sort(); + foreach (string tag in Tags) { + tmp += string.Format("{0}{1}", tag, SEPARATORETXT); + } + if (tmp.Length > 2) tmp = tmp.Remove(tmp.Length - 3); + } + sb.AppendFormat("\t\t

- Tags: {0}

\n", tmp); + + tmp = ""; + if (Notes != null) { + foreach (cNota nota in Notes) { sb.AppendFormat("\t\t

- Notes: {0} - {1}

\n", nota.Key, nota.Description); } + } else { sb.Append("\t\t

- Notes:

\n"); } + sb.AppendFormat("\t\t

- Creato: {0}

\n", strCreato); + sb.AppendFormat("\t\t

- Update: {0}

\n", strUpdated); + sb.AppendFormat("\t\t

{0}

\n", Trama.Replace("\n", "\n")); + sb.AppendLine("\t\t"); + sb.AppendFormat("\t\t
Ritorna all'inizio

\n", strIDrac); + sb.AppendLine("\t\t"); + sb.AppendLine("\t\n"); + return sb.ToString(); + } catch (Exception ex) { + Logger.Error(string.Format("Error Code: {0} - Errore in {1}.{2}: {3}", "ER00040", System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.FullName, System.Reflection.MethodInfo.GetCurrentMethod().Name, ex.Message)); + return string.Format(string.Format("Error Code: {0} - Errore in {1}.{2}: {3}", "ER00040", System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.FullName, System.Reflection.MethodInfo.GetCurrentMethod().Name, ex.Message)); + } + } + + + public static int Read(string Txt, out cRac[] Racs) { + + // I racconti inseriti devono avere la struttura formale: + // + // - ID Rac:\t{0}\n + // - Title: \t{0}\n + // - SubTit:\t{0}\n + // - Autors:\t{0}\n Elenco degli autori separati tramite il separatore + // - Voto: \t{0}\n + // - Tags: \t{0}\n Elenco dei tag separati tramite il separatore + // - Notes: \t{0}{2}{1}\n Per ciascuna riga, la coppia Key e Descr separati tramite il separatore + // - Creato:\t{0}\n + // - Update:\t{0}\n + // - Origin:\t{0}\n + // - Trama: \t{0}\n + // + + try { + // Suddivido i vari racconti: + string[] splitSeparator = new string[] { "- ID Rac:" }; + string[] txtRacs = Txt.Split(splitSeparator, StringSplitOptions.RemoveEmptyEntries); + List elenco = new List(); + // Analizzo ciascuno di essi: + foreach (string txtRac in txtRacs) { + // Leggo il testo riga per riga, fino a che inizia il primo racconto (trovo il tag ID o il titolo): + splitSeparator = new string[] { "\n" }; + string[] rows = ("- ID Rac:" + txtRac).Replace("\r\n", "\n").Split(splitSeparator, StringSplitOptions.RemoveEmptyEntries); + cRac rac = new cRac(); + int i; + // Ricerco inizio del racconto: + for (i = 0; i < rows.Length; i++) { + if (rows[i].Trim().StartsWith("- ID Rac:")) { + rac.IDrac = long.Parse(rows[i].Replace("- ID Rac:", "").Trim()); + i++; + } + if (rows[i].Trim().StartsWith("- Title:")) { + rac.Title = rows[i].Replace("- Title:", "").Trim(); + i++; + break; + } + } + if (rows[i].Trim().StartsWith("- SubTit:")) { + rac.SubTitle = rows[i].Replace("- SubTit:", "").Trim(); + i++; + } + if (rows[i].Trim().StartsWith("- Autors:")) { + splitSeparator[0] = SEPARATORETXT.Trim(); + string[] autors = rows[i].Replace("- Autors:", "").Trim().Split(splitSeparator, StringSplitOptions.RemoveEmptyEntries); + rac.Autori = new List(); + foreach (string aut in autors) { rac.Autori.Add(aut.Trim()); } + i++; + } + if (rows[i].Trim().StartsWith("- Voto:")) { + rac.Voto = rows[i].Replace("- Voto:", "").Trim(); + i++; + } + if (rows[i].Trim().StartsWith("- Tags:")) { + splitSeparator[0] = SEPARATORETXT.Trim(); + string[] tags = rows[i].Replace("- Tags:", "").Trim().Split(splitSeparator, StringSplitOptions.RemoveEmptyEntries); + rac.Tags = new List(); + foreach (string tag in tags) { rac.Tags.Add(tag.Trim()); } + i++; + } + rac.Notes = new List(); + while (rows[i].Trim().StartsWith("- Notes:")) { + string[] note = rows[i].Replace("- Notes:", "").Trim().Split(splitSeparator, StringSplitOptions.RemoveEmptyEntries); + if (note.Length == 2) { rac.Notes.Add(new cNota(note[0].Trim(), note[1].Trim())); } + i++; + } + if (rows[i].Trim().StartsWith("- Creato:")) { + rac.Creato = DateTime.Parse(rows[i].Replace("- Creato:", "").Trim()); + i++; + } + if (rows[i].Trim().StartsWith("- Update:")) { + rac.Updated = DateTime.Parse(rows[i].Replace("- Update:", "").Trim()); + i++; + } + if (rows[i].Trim().StartsWith("- Origin:")) { + splitSeparator[0] = SEPARATORETXT.Trim(); + string[] origini = rows[i].Replace("- Origin:", "").Trim().Split(splitSeparator, StringSplitOptions.RemoveEmptyEntries); + rac.Origini = new List(); + foreach (string origine in origini) { rac.Origini.Add(origine.Trim()); } + i++; + } + if (rows[i].Trim().StartsWith("- Trama:")) { + rac.Trama = rows[i].Replace("- Trama:", "").Trim() + "\n"; + i++; + for (int j = i; j < rows.Length; j++) { + rac.Trama += rows[j].Trim() + "\n"; + } + } + if (rac.Validate()) { + elenco.Add(rac); + } else { + Logger.Error("Decodifica del racconto dal testo inserito, non riuscita"); + } + } + + Racs = elenco.ToArray(); + return Racs.Length; + } catch (Exception ex) { + Logger.Error(string.Format("Error Code: {0} - Errore in {1}.{2}: {3}", "ER00030", System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.FullName, System.Reflection.MethodInfo.GetCurrentMethod().Name, ex.Message)); + Racs = null; + return -1; + } + } + + public static int Read_Old(string Txt, out cRac[] Racs) { + + // ToDo: Gestire più racconti in modo da fare una vera e propia importazione + + // I racconti inseriti devono avere la struttura formale: + // + // - ID Rac:\t{0}\n + // - Title: \t{0}\n + // - SubTit:\t{0}\n + // - Autors:\t{0}\n Elenco degli autori separati tramite il separatore + // - Voto: \t{0}\n + // - Tags: \t{0}\n Elenco dei tag separati tramite il separatore + // - Notes: \t{0}{2}{1}\n Per ciascuna riga, la coppia Key e Descr separati tramite il separatore + // - Creato:\t{0}\n + // - Update:\t{0}\n + // - Origin:\t{0}\n + // - Trama: \t{0}\n + // + + try { + // Leggo il testo riga per riga, fino a che inizia il primo racconto (trovo il tag ID o il titolo): + string[] splitSeparator = new string[] { "\n" }; + string[] rows = Txt.Replace("\r\n", "\n").Split(splitSeparator, StringSplitOptions.RemoveEmptyEntries); + + cRac rac = new cRac(); + int i; + // Ricerco inizio del racconto: + for (i = 0; i < rows.Length; i++) { + if (rows[i].Trim().StartsWith("- ID Rac:")) { + rac.IDrac = long.Parse(rows[i].Replace("- ID Rac:", "").Trim()); + i++; + } + if (rows[i].Trim().StartsWith("- Title:")) { + rac.Title = rows[i].Replace("- Title:", "").Trim(); + i++; + break; + } + } + if (rows[i].Trim().StartsWith("- SubTit:")) { + rac.SubTitle = rows[i].Replace("- SubTit:", "").Trim(); + i++; + } + if (rows[i].Trim().StartsWith("- Autors:")) { + splitSeparator[0] = SEPARATORETXT.Trim(); + string[] autors = rows[i].Replace("- Autors:", "").Trim().Split(splitSeparator, StringSplitOptions.RemoveEmptyEntries); + rac.Autori = new List(); + foreach (string aut in autors) { rac.Autori.Add(aut.Trim()); } + i++; + } + if (rows[i].Trim().StartsWith("- Voto:")) { + rac.Voto = rows[i].Replace("- Voto:", "").Trim(); + i++; + } + if (rows[i].Trim().StartsWith("- Tags:")) { + splitSeparator[0] = SEPARATORETXT.Trim(); + string[] tags = rows[i].Replace("- Tags:", "").Trim().Split(splitSeparator, StringSplitOptions.RemoveEmptyEntries); + rac.Tags = new List(); + foreach (string tag in tags) { rac.Tags.Add(tag.Trim()); } + i++; + } + rac.Notes = new List(); + while (rows[i].Trim().StartsWith("- Notes:")) { + string[] note = rows[i].Replace("- Notes:", "").Trim().Split(splitSeparator, StringSplitOptions.RemoveEmptyEntries); + if (note.Length == 2) { rac.Notes.Add(new cNota(note[0].Trim(), note[1].Trim())); } + i++; + } + if (rows[i].Trim().StartsWith("- Creato:")) { + rac.Creato = DateTime.Parse(rows[i].Replace("- Creato:", "").Trim()); + i++; + } + if (rows[i].Trim().StartsWith("- Update:")) { + rac.Updated = DateTime.Parse(rows[i].Replace("- Update:", "").Trim()); + i++; + } + if (rows[i].Trim().StartsWith("- Origin:")) { + splitSeparator[0] = SEPARATORETXT.Trim(); + string[] origini = rows[i].Replace("- Origin:", "").Trim().Split(splitSeparator, StringSplitOptions.RemoveEmptyEntries); + rac.Origini = new List(); + foreach (string origine in origini) { rac.Origini.Add(origine.Trim()); } + i++; + } + if (rows[i].Trim().StartsWith("- Trama:")) { + rac.Trama = rows[i].Replace("- Trama:", "").Trim() + "\n"; + i++; + for (int j = i; j < rows.Length; j++) { + rac.Trama += rows[j].Trim() + "\n"; + } + } + Racs = new cRac[1]; + rac.isValid = true; + Racs[0] = rac; + return 1; + } catch (Exception ex) { + Logger.Error(string.Format("Error Code: {0} - Errore in {1}.{2}: {3}", "ER00030", System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.FullName, System.Reflection.MethodInfo.GetCurrentMethod().Name, ex.Message)); + Racs = null; + return -1; + } + } + + public bool UnificaConDuplicato(cRac copia) { + try { + // ID Rac: Tengo l'ID del racconto attuale + // Title: Il titolo è lo stesso e non devo fare nulla + // SubTit: Se è lo stesso tengo l'attuale, altrimenti se uno solo è non nullo lo tengo, altrimenti li unisco. + if (this.SubTitle != copia.SubTitle) { + if (string.IsNullOrEmpty(this.SubTitle)) { + this.SubTitle = copia.SubTitle; + } else { + this.SubTitle = this.SubTitle + SEPARATORETXT + copia.SubTitle; + } + } + // Autors: Unisco tutti gli autori distinti: + foreach (string aut in copia.Autori) { + if (!this.Autori.Contains(aut)) { + this.Autori.Add(aut); + } + } + // Voto: Metto il voto più alto fra i due + if (copia.Voto != this.Voto) if (this.Voto == "Non Letto") this.Voto = copia.Voto; + // Tags: Unisco tutti i tag distinti: + foreach (string tag in copia.Tags) { + if (!this.Tags.Contains(tag)) this.Tags.Add(tag); + } + // Notes: Unisco tutte le note distinte: + foreach (cNota nota in copia.Notes) { + if (!this.Notes.Contains(nota)) this.Notes.Add(nota); + } + // Creato: Uso la data di creazione più vecchia: + if (copia.Creato < this.Creato) this.Creato = copia.Creato; + // Update: Uso la data più nuova + if (copia.Updated > this.Updated) this.Updated = copia.Updated; + // Origin: Unisco tutte le origini distinte: + foreach (string orig in copia.Origini) { + if (!this.Origini.Contains(orig)) this.Origini.Add(orig); + } + // Trama: La trama è la stessa e non devo fare nulla + + return true; + } catch (Exception ex) { + Logger.Error(string.Format("Error Code: {0} - Errore in {1}.{2}: {3}", "ER00040", System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.FullName, System.Reflection.MethodInfo.GetCurrentMethod().Name, ex.Message)); + return false; + } + } + + } // class cRac + +}//namespace A69WD.Data diff --git a/Src/A69WD/General/cTools.cs b/Src/A69WD/General/cTools.cs index 55aae75..67d9d91 100644 --- a/Src/A69WD/General/cTools.cs +++ b/Src/A69WD/General/cTools.cs @@ -473,17 +473,17 @@ namespace A69WD { public static string FormattaTesto(string txt, bool eliminaTagHtml) { try { // Analisi dei tag prima di levarli: - string testo = Regex.Replace(txt, @"

", "\n", RegexOptions.IgnoreCase); - testo = Regex.Replace(testo, @"

", "\n", RegexOptions.IgnoreCase); - testo = Regex.Replace(testo, @"

", "\n", RegexOptions.IgnoreCase); - testo = Regex.Replace(testo, @"", "\n", RegexOptions.IgnoreCase); - testo = Regex.Replace(testo, @"", "\n", RegexOptions.IgnoreCase); - testo = Regex.Replace(testo, @"", "\n", RegexOptions.IgnoreCase); - testo = Regex.Replace(testo, @"
", "\n", RegexOptions.IgnoreCase); - testo = Regex.Replace(testo, @"
", "\n", RegexOptions.IgnoreCase); - testo = Regex.Replace(testo, @"
", "\n", RegexOptions.IgnoreCase); - testo = Regex.Replace(testo, @"", "\n", RegexOptions.IgnoreCase); - testo = Regex.Replace(testo, @"

", "\n", RegexOptions.IgnoreCase); + string testo = Regex.Replace(txt, @"

", "\r\n", RegexOptions.IgnoreCase); + testo = Regex.Replace(testo, @"

", "\r\n", RegexOptions.IgnoreCase); + testo = Regex.Replace(testo, @"

", "\r\n", RegexOptions.IgnoreCase); + testo = Regex.Replace(testo, @"", "\r\n", RegexOptions.IgnoreCase); + testo = Regex.Replace(testo, @"", "\r\n", RegexOptions.IgnoreCase); + testo = Regex.Replace(testo, @"", "\r\n", RegexOptions.IgnoreCase); + testo = Regex.Replace(testo, @"
", "\r\n", RegexOptions.IgnoreCase); + testo = Regex.Replace(testo, @"
", "\r\n", RegexOptions.IgnoreCase); + testo = Regex.Replace(testo, @"
", "\r\n", RegexOptions.IgnoreCase); + testo = Regex.Replace(testo, @"

", "\r\n", RegexOptions.IgnoreCase); + testo = Regex.Replace(testo, @"
", "\r\n", RegexOptions.IgnoreCase); testo = Regex.Replace(testo, @"<<", "«", RegexOptions.IgnoreCase); testo = Regex.Replace(testo, @">>", "»", RegexOptions.IgnoreCase); // Se richiesto, elimino i tag html: @@ -496,10 +496,79 @@ namespace A69WD { testo = re.Replace(testo, ""); } + // Special Entities dal sito https://www.htmlhelp.com/reference/html40/entities/special.html + testo = Regex.Replace(testo, @""", "\"", RegexOptions.IgnoreCase); + testo = Regex.Replace(testo, @"&", "&", RegexOptions.IgnoreCase); + testo = Regex.Replace(testo, @"<", "<", RegexOptions.IgnoreCase); + testo = Regex.Replace(testo, @">", ">", RegexOptions.IgnoreCase); + testo = Regex.Replace(testo, @"œ", "œ", RegexOptions.IgnoreCase); + testo = Regex.Replace(testo, @"š", "š", RegexOptions.IgnoreCase); + testo = Regex.Replace(testo, @"Ÿ", "Ÿ", RegexOptions.IgnoreCase); + testo = Regex.Replace(testo, @"ˆ", "ˆ", RegexOptions.IgnoreCase); + testo = Regex.Replace(testo, @"˜", "", RegexOptions.IgnoreCase); + testo = Regex.Replace(testo, @"–", "–", RegexOptions.IgnoreCase); + testo = Regex.Replace(testo, @"—", "—", RegexOptions.IgnoreCase); + testo = Regex.Replace(testo, @"‘", "‘", RegexOptions.IgnoreCase); + testo = Regex.Replace(testo, @"’", "’", RegexOptions.IgnoreCase); + testo = Regex.Replace(testo, @"‚", "‚", RegexOptions.IgnoreCase); + testo = Regex.Replace(testo, @"“", "“", RegexOptions.IgnoreCase); + testo = Regex.Replace(testo, @"”", "”", RegexOptions.IgnoreCase); + testo = Regex.Replace(testo, @"„", "„", RegexOptions.IgnoreCase); + testo = Regex.Replace(testo, @"†", "†", RegexOptions.IgnoreCase); + testo = Regex.Replace(testo, @"‰", "‰", RegexOptions.IgnoreCase); + testo = Regex.Replace(testo, @"‹", "‹", RegexOptions.IgnoreCase); + testo = Regex.Replace(testo, @"›", "›", RegexOptions.IgnoreCase); + testo = Regex.Replace(testo, @"€", "€", RegexOptions.IgnoreCase); + testo = Regex.Replace(testo, @""", "\"", RegexOptions.IgnoreCase); + testo = Regex.Replace(testo, @"&", "&", RegexOptions.IgnoreCase); + testo = Regex.Replace(testo, @"<", "<", RegexOptions.IgnoreCase); + testo = Regex.Replace(testo, @">", ">", RegexOptions.IgnoreCase); + testo = Regex.Replace(testo, @"œ", "œ", RegexOptions.IgnoreCase); + testo = Regex.Replace(testo, @"š", "š", RegexOptions.IgnoreCase); + testo = Regex.Replace(testo, @"Ÿ", "Ÿ", RegexOptions.IgnoreCase); + testo = Regex.Replace(testo, @"ˆ", "ˆ", RegexOptions.IgnoreCase); + testo = Regex.Replace(testo, @"˜", "", RegexOptions.IgnoreCase); + testo = Regex.Replace(testo, @"–", "–", RegexOptions.IgnoreCase); + testo = Regex.Replace(testo, @"—", "—", RegexOptions.IgnoreCase); + testo = Regex.Replace(testo, @"‘", "‘", RegexOptions.IgnoreCase); + testo = Regex.Replace(testo, @"’", "’", RegexOptions.IgnoreCase); + testo = Regex.Replace(testo, @"‚", "‚", RegexOptions.IgnoreCase); + testo = Regex.Replace(testo, @"“", "“", RegexOptions.IgnoreCase); + testo = Regex.Replace(testo, @"”", "”", RegexOptions.IgnoreCase); + testo = Regex.Replace(testo, @"„", "„", RegexOptions.IgnoreCase); + testo = Regex.Replace(testo, @"†", "†", RegexOptions.IgnoreCase); + testo = Regex.Replace(testo, @"‰", "‰", RegexOptions.IgnoreCase); + testo = Regex.Replace(testo, @"‹", "‹", RegexOptions.IgnoreCase); + testo = Regex.Replace(testo, @"›", "›", RegexOptions.IgnoreCase); + testo = Regex.Replace(testo, @"€", "€", RegexOptions.IgnoreCase); + testo = Regex.Replace(testo, @""", "\"", RegexOptions.IgnoreCase); + testo = Regex.Replace(testo, @"&", "&", RegexOptions.IgnoreCase); + testo = Regex.Replace(testo, @"<", "<", RegexOptions.IgnoreCase); + testo = Regex.Replace(testo, @">", ">", RegexOptions.IgnoreCase); + testo = Regex.Replace(testo, @"œ", "œ", RegexOptions.IgnoreCase); + testo = Regex.Replace(testo, @"š", "š", RegexOptions.IgnoreCase); + testo = Regex.Replace(testo, @"Ÿ", "Ÿ", RegexOptions.IgnoreCase); + testo = Regex.Replace(testo, @"ˆ", "ˆ", RegexOptions.IgnoreCase); + testo = Regex.Replace(testo, @"˜", "", RegexOptions.IgnoreCase); + testo = Regex.Replace(testo, @"–", "–", RegexOptions.IgnoreCase); + testo = Regex.Replace(testo, @"—", "—", RegexOptions.IgnoreCase); + testo = Regex.Replace(testo, @"‘", "‘", RegexOptions.IgnoreCase); + testo = Regex.Replace(testo, @"’", "’", RegexOptions.IgnoreCase); + testo = Regex.Replace(testo, @"‚", "‚", RegexOptions.IgnoreCase); + testo = Regex.Replace(testo, @"“", "“", RegexOptions.IgnoreCase); + testo = Regex.Replace(testo, @"”", "”", RegexOptions.IgnoreCase); + testo = Regex.Replace(testo, @"„", "„", RegexOptions.IgnoreCase); + testo = Regex.Replace(testo, @"†", "†", RegexOptions.IgnoreCase); + testo = Regex.Replace(testo, @"‰", "‰", RegexOptions.IgnoreCase); + testo = Regex.Replace(testo, @"‹", "‹", RegexOptions.IgnoreCase); + testo = Regex.Replace(testo, @"›", "›", RegexOptions.IgnoreCase); + testo = Regex.Replace(testo, @"€", "€", RegexOptions.IgnoreCase); + + + // Correggo risultato togliendo doppie linee e caratteri html: testo = Regex.Replace(testo, @" ", " ", RegexOptions.IgnoreCase); testo = Regex.Replace(testo, @"•", " * ", RegexOptions.IgnoreCase); - testo = Regex.Replace(testo, @"‹", " < ", RegexOptions.IgnoreCase); testo = Regex.Replace(testo, @"<", "<", RegexOptions.IgnoreCase); testo = Regex.Replace(testo, @"›", " > ", RegexOptions.IgnoreCase); testo = Regex.Replace(testo, @">", ">", RegexOptions.IgnoreCase); @@ -513,6 +582,7 @@ namespace A69WD { testo = Regex.Replace(testo, @"ò", "ò", RegexOptions.IgnoreCase); testo = Regex.Replace(testo, @"ù", "ù", RegexOptions.IgnoreCase); + testo = Regex.Replace(testo, @"–", "–", RegexOptions.IgnoreCase); testo = Regex.Replace(testo, @"—", "—", RegexOptions.IgnoreCase); testo = Regex.Replace(testo, @"‘", "‘", RegexOptions.IgnoreCase); @@ -541,9 +611,10 @@ namespace A69WD { //while (testo.Contains("ù")) { testo = testo.Replace("ù", "ù"); } //while (testo.Contains("’")) { testo = testo.Replace("’", "'"); } - - // Correggo scritto: + testo = testo.Replace("&egrave", "è"); + testo = testo.Replace("&", "&"); + testo = testo.Replace("…", "…"); testo = testo.Replace("\r", ""); while (testo.Contains("\t")) { testo = testo.Replace("\t", " "); } while (testo.Contains("...")) { testo = testo.Replace("...", "…"); } diff --git a/Src/A69WD/Net/cLink_A69.cs b/Src/A69WD/Net/cLink_A69.cs index 49c8bb7..3d3a7a2 100644 --- a/Src/A69WD/Net/cLink_A69.cs +++ b/Src/A69WD/Net/cLink_A69.cs @@ -1,12 +1,16 @@ using System; using System.Collections.Concurrent; using System.Collections.Generic; +using System.Globalization; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Security.Policy; using System.Text; +using System.Text.RegularExpressions; using System.Threading.Tasks; +using A69WD.Data; using A69WD.Service; +using HtmlAgilityPack; namespace A69WD.Net { public class cLink_A69 : iLink { @@ -86,7 +90,7 @@ namespace A69WD.Net { public static bool InsertStartLink(Service_Crawler service) { //string url = LinkIdxBase.Replace("{Categoria}", "altro").Replace("{ID}", "1"); //LinkIdxBase.Replace("{Categoria}", "trio").Replace("{ID}", "1"); //string name = "_A69_altro_0001.html"; //"_A69_trio_0001.html"; - //service.EnqueueUrl(new cLink_A69(url, name)); + //serviceCrawler.EnqueueUrl(new cLink_A69(url, name)); //return true; int i = 1; try { @@ -102,6 +106,458 @@ namespace A69WD.Net { } } + + + public async Task EstraiRac(string FileFullPath) { + /* + * Analisi html dei racconti aggiornata al 2025/12/27: + * + * + * Per ciascun file html, si ha un unico racconto che ha un formato interno pari a: + * + * + * ... + *
incesto
+ * ... + *

Mia Madre , La mia Amante

+ *            diBambino + * ... + *
+ *  Scritto il 22.08.2015    |    + * Letture: 8.947  |    + * Votazione 8.0: + *
+ * ... + *
+ * Eliminare i DIV interni che hanno cose grafiche + * Il testo è quello che rimane. + *
+ * + * + * + * quindi i dati del racconto che si possono estrapolare sono: + * Titolo: --> Testo del nodo

+ * SubTitle: --> Sempre Vuoto + * Autore: --> Testo del nodo + * Creato: --> Estrarre la parte dal
+ * Tags: --> Testo del nodo div class="targhetta_racconti"> + * Trama: --> Testo del nodo
a cui si levano i DIV interni. + * Notes: --> SrcFile - Nome del file che si analizza + * Origini: --> Sempre l'ID della sorgente web + * Voto: --> Sempre "Non Letto" + * Updated: --> Data attuale + * + */ + cRac rac = new cRac(); + HtmlNodeCollection nodes; + try { + Console.WriteLine($"A69 - Importo: {FileFullPath}"); + + string filePathName = System.IO.Path.GetFileName(FileFullPath); + + // Ricavo il nodo radice del racconto: + HtmlDocument tdoc = new HtmlDocument(); + tdoc.Load(FileFullPath); + HtmlNode root = tdoc.DocumentNode; + if (root == null) { + // racconto non presente + return null; + } + + #region Origini: --> Sempre l'ID della sorgente web + rac.Origini = new List { ID }; + #endregion + + #region Titolo: --> Testo del nodo

+ try { + nodes = root.SelectNodes("//h1[@class='titolone_nero']"); + rac.Title = cTools.FormattaTesto(nodes[0].InnerText.Trim(), false); + if (string.IsNullOrEmpty(rac.Title)) { + Logger.Error($"A69 - Import - No Title - {filePathName}"); + return null; + } + } catch (Exception ex) { Logger.Error(string.Format("Fallita estrazione titolo dal file {0}\r\n{1}", FileName, ex.Message)); return null; } + #endregion + + #region SubTitle: --> Sempre Vuoto + rac.SubTitle = ""; + #endregion + + #region Autore: --> Testo del nodo + try { + // Autore --> Testo del nodo items = new List(); + foreach (HtmlNode nd in nodes) { + string aut = nd.ParentNode.InnerText.Replace(" ", "").Trim(); + if (aut.StartsWith("di")) { + items.Add(aut.Replace("di", "").Trim()); + } + } + items.Sort(); + string tmp = ""; + rac.Autori = new List(); + // Rimuovo eventuali duplicati + foreach (string aut in items) { + if (tmp != aut) { + rac.Autori.Add(aut); + tmp = aut; + } + } + if (rac.Autori == null || string.IsNullOrEmpty(rac.Autori[0])) { + Logger.Error($"A69 - Import - No Autors - {filePathName}"); + return null; + } + } catch (Exception ex) { Logger.Error(string.Format("Fallita estrazione autore dal file {0}\r\n{1}", FileName, ex.Message)); return null; } + #endregion + + #region Creato: --> Estrarre la parte dal
+ rac.Creato = DateTime.Now; + try { + // Creato --> Estrarre la prima parte dal che ha il testo "Data|Visite|Commenti": + nodes = root.SelectNodes("//span[@class='text_grigio']"); + foreach (HtmlNode nd in nodes) { + string txt = nd.InnerText.Trim().Replace(" ", ""); + string[] parts = txt.Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries); + if (parts.Length == 3) { + CultureInfo culture = CultureInfo.CreateSpecificCulture("it-IT"); + DateTimeStyles styles = DateTimeStyles.None; + rac.Creato = DateTime.Now; + if (!DateTime.TryParse(parts[0].Trim(), culture, styles, out rac.Creato)) { + Logger.Error($"A69 - Import - No data - {filePathName}"); + } + } + } + } catch (Exception ex) { Logger.Warning(string.Format("Data non riconosciuta nel file {0}\r\n{1}", FileName, ex.Message)); return null; } + #endregion + + #region Updated: --> Data attuale + rac.Updated = DateTime.Now; + #endregion + + #region Tags: --> Testo del nodo div class="targhetta_racconti"> + try { + nodes = root.SelectNodes("//div[@class='targhetta_racconti']"); + List items = new List(); + foreach (HtmlNode nd in nodes) { + items.Add(cTools.FormattaTesto(nd.InnerText.Replace("genere", "").Trim(), false)); + } + //items.Sort(); + items = items + .OrderBy(s => s) // ordina alfabeticamente + .Distinct() // elimina duplicati + .ToList(); + Format_Insert_Tags(rac, items); // rac.Tags = items; + } catch (Exception ex) { Logger.Warning(string.Format("Fallita estrazione Tags dal file {0}\r\n{1}", FileName, ex.Message)); return null; } + #endregion + + #region Trama: --> Testo del nodo
a cui si levano i DIV interni. + try { + nodes = root.SelectNodes("//div[@class='testoracc']"); + foreach (HtmlNode nd in nodes) { + foreach (HtmlNode n in nd.ChildNodes) { + if (n.Name.ToUpper() == "#TEXT") { rac.Trama += cTools.FormattaTesto(n.InnerText.Trim(), false); } + if (n.Name.ToUpper() == "BR") { rac.Trama += "\r"; } + if (n.Name.ToUpper() == "DIV") {; } + } + } + } catch (Exception ex) { Logger.Error(string.Format("Fallita estrazione Trama dal file {0}\r\n{1}", FileName, ex.Message)); return null; } + #endregion + + #region Voto: --> Sempre "Non Letto" + rac.Voto = "Non Letto"; + #endregion + + #region Notes: --> SrcFile - Nome del file che si analizza + rac.Notes = new List(); + rac.Notes.Add(new Data.cNota("SrcFile", System.IO.Path.GetFileName(filePathName))); + #endregion + + // Formalizzo esito estrazione: + if (!rac.Validate()) { + rac = null; + } + + } catch (Exception ex) { + Logger.Error($"A69 - Import Error - {FileFullPath}: {ex.Message}"); + Console.WriteLine($"A69 - Import Error - {FileFullPath}: {ex.Message}"); + return null; + } + return rac; + } + + + protected virtual void Format_Insert_Tags(Data.cRac rac, List items) { + // Per ora riporto tutti i tag rilevati, mentre in futuro dovrò: + // - parsare la lista e formattare correttamente i tag + // - ordinare la lista dei tag formattati ed eliminare i duplicati + // - se non sono rimasti tag, inserisco il tag generale per indicare che non vi sono tag + // - altrimenti inserisco tutti i tag rimasti. + rac.Tags = new List(); + try { + items.Sort(); + string tmp = ""; + foreach (string item in items) { + string it = item.Trim().ToLower(); + if (tmp != it) { + #region switch per formattare il testo + switch (it) { + //case "racconti 69": + // rac.Tags.Add("69"); + // break; + //case "abusi": + // rac.Tags.Add("Abusi"); + // break; + //case "camgirl": + //case "chat e siti di incontri…": + //case "fiche": + // rac.Tags.Add("Altro"); + // break; + //case "amatoriali": + // rac.Tags.Add("Amatoriali"); + // break; + //case "anale": + // rac.Tags.Add("Anale"); + // break; + //case "audio libri erotici": + //case "audio racconti erotici": + // rac.Tags.Add("Audio"); + // break; + //case "bdsm": + // rac.Tags.Add("BDMS"); + // break; + //case "bisex": + //case "bisex ♀": + //case "bisex ♂": + // rac.Tags.Add("Bisex"); + // break; + //case "bondage": + // rac.Tags.Add("Bondage"); + // break; + //case "bondage e sadomaso": + // rac.Tags.Add("Bondage"); + // rac.Tags.Add("Sadomaso"); + // break; + //case "bukkake": + // rac.Tags.Add("Bukkake"); + // break; + //case "comici": + //case "comunità": + // rac.Tags.Add("Comico"); + // break; + //case "concorso estate 2019": + //case "concorso natale 2018": + //case "decameron 2020": + // rac.Tags.Add("Concorso"); + // break; + //case "confessioni": + // rac.Tags.Add("Confessioni"); + // break; + //case "coppie": + //case "scambio di coppia": + //case "scambio di coppie": + // rac.Tags.Add("Coppie"); + // break; + //case "cuckold": + //case "racconti cuckold": + // rac.Tags.Add("Cuckold"); + // break; + //case "curiosità": + //case "curiosità sul sesso": + // rac.Tags.Add("Curiosità"); + // break; + //case "dominazione": + //case "racconti di dominazione": + //case "schiavi&padroni": + // rac.Tags.Add("Dominazione"); + // break; + //case "doppia penetrazione": + // rac.Tags.Add("Doppia Penetrazione"); + // break; + //case "esibizionismo": + // rac.Tags.Add("Esibizionismo"); + // break; + //case "etero": + //case "lui & lei": + //case "racconti erotici etero": + // rac.Tags.Add("Etero"); + // break; + //case "feticismo": + // rac.Tags.Add("Feticismo"); + // break; + //case "fisting": + // rac.Tags.Add("Fisting"); + // break; + //case "gang bang": + // rac.Tags.Add("Gang Bang"); + // break; + //case "gay": + //case "racconti gay": + // rac.Tags.Add("Gay"); + // break; + //case "gay & bisex": + //case "gay e bisex": + // rac.Tags.Add("Gay"); + // rac.Tags.Add("Bisex"); + // break; + //case "gay - travestiti": + // rac.Tags.Add("Gay"); + // rac.Tags.Add("Trans"); + // break; + //case "incesti": + //case "incesto": + //case "racconti erotici sull'incesto": + // rac.Tags.Add("Incesto"); + // break; + //case "interviste": + //case "interviste erotiche": + // rac.Tags.Add("Intervista"); + // break; + //case "lesbo": + //case "racconti erotici lesbo": + //case "saffico": + // rac.Tags.Add("Lesbo"); + // break; + //case "autoerotismo": + //case "masturbazione": + //case "masturbazioni": + //case "racconti sull'autoerotismo": + // rac.Tags.Add("Masturbazione"); + // break; + //case "milf": + // rac.Tags.Add("MILF"); + // break; + //case "nudismo": + // rac.Tags.Add("Nudismo"); + // break; + //case "orge": + //case "orgia": + //case "sesso di gruppo": + // rac.Tags.Add("Orge"); + // break; + //case "pissing": + // rac.Tags.Add("Pissing"); + // break; + //case "lirica erotica": + //case "poesia erotica": + //case "poesie": + //case "poesie erotiche": + // rac.Tags.Add("Poesia"); + // break; + //case "pompini": + // rac.Tags.Add("Pompini"); + // break; + //case "giochi erotici": + //case "prime esperienze": + //case "prime volte": + // rac.Tags.Add("Prime Esperienze"); + // break; + //case "pulp": + // rac.Tags.Add("Pulp"); + // break; + //case "sadomaso": + // rac.Tags.Add("Sadomaso"); + // break; + //case "sensazioni": + //case "sentimentali": + // rac.Tags.Add("Sentimentali"); + // break; + //case "cornuti": + //case "tradimenti": + //case "tradimento": + // rac.Tags.Add("Tradimento"); + // break; + //case "racconti con trans": + //case "racconti trans": + //case "trans": + //case "trans e travestiti": + // rac.Tags.Add("Trans"); + // break; + //case "trasgressivo": + // rac.Tags.Add("Trasgressivo"); + // break; + //case "trio": + // rac.Tags.Add("Trio"); + // break; + //case "uncategorized": + // rac.Tags.Add("Uncategorized"); + // break; + //case "voyeur": + //case "voyeurismo": + // rac.Tags.Add("Voyeur"); + // break; + //case "animali": + //case "zoofilia": + // rac.Tags.Add("Zoofilia"); + // break; + + //case "Gay": + // rac.Tags.Add("Gay"); + // break; + //case "Racconti bisex": + // rac.Tags.Add("Bisex"); + // break; + //case "Racconti etero": + // rac.Tags.Add("Etero"); + // break; + //case "Racconti fetish": + // rac.Tags.Add("Feticismo"); + // break; + //case "Racconti incesto": + // rac.Tags.Add("Incesto"); + // break; + //case "Racconti lesbo": + // rac.Tags.Add("Lesbo"); + // break; + //case "Racconti masturbazione": + // rac.Tags.Add("Masturbazione"); + // break; + //case "Racconti mature": + // rac.Tags.Add("Mature"); + // break; + //case "Racconti orge": + // rac.Tags.Add("Orge"); + // break; + //case "Racconti prima volta": + // rac.Tags.Add("Prime Esperienze"); + // break; + //case "Racconti ricatto": + // rac.Tags.Add("Ricatto"); + // break; + //case "Racconti scambio di coppia": + // rac.Tags.Add("Coppie"); + // break; + //case "Racconti sottomissione": + // rac.Tags.Add("Dominazione"); + // break; + //case "Racconti tradimenti": + // rac.Tags.Add("Tradimento"); + // break; + //case "Racconti trav": + //case "Trans": + // rac.Tags.Add("Trans"); + // break; + + default: + rac.Tags.Add(item); + break; + } + #endregion + tmp = it; + + }//if + + }//foreach + + } catch (Exception ex) { + Logger.Error(string.Format("Error Code: {0} - Errore in {1}.{2}: {3}", "ER00040", System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.FullName, System.Reflection.MethodInfo.GetCurrentMethod().Name, ex.Message)); + } finally { + if (rac.Tags.Count == 0) rac.Tags.Add("_None_"); + } + }//function + + + }//class cLink_A69 }//namespace A69WD.Net diff --git a/Src/A69WD/Service/Service_Importer.cs b/Src/A69WD/Service/Service_Importer.cs new file mode 100644 index 0000000..3ba7d0b --- /dev/null +++ b/Src/A69WD/Service/Service_Importer.cs @@ -0,0 +1,123 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using System.Windows.Forms; +using A69WD.Data; +using A69WD.Net; +using A69WD.Site; + + + +namespace A69WD.Service { + + + public class Service_Importer { + + // Thread worker che consuma la coda + private Thread _workerThread; + private readonly Label _lblInCorso; + private readonly ProgressBar _progressBar; + private string _path; + // Contatori + private int _totali = 0; + private int _completati = 0; + private int _errori = 0; + + public Service_Importer(Label lblInCorso, ProgressBar pbStatus) { + _lblInCorso = lblInCorso; + _progressBar = pbStatus; + } + + public void StartWorker(string path) { + _path = path; + _workerThread = new Thread(ProcessWorking) { IsBackground = true }; + _workerThread.Start(); + } + + public void StopWorker() { + ; + } + + + + private async void ProcessWorking() { + string[] files = System.IO.Directory.GetFiles(_path, "A69_*.html"); + _totali = files.Length; + _completati = 0; + _errori = 0; + UpdateCounters(); + + // foreach (string file in files) { + // Task.Run(async () => { + // Logger.Warning($"Start estrazione racconto: {file}"); + // cLink_A69 lk = new cLink_A69("url", file); + // cRac rac = await lk.EstraiRac(file); + // if (rac != null) { + // // Racconto estratto correttamente, lo salvo sul DB + // Logger.Warning($"Start estrazione racconto: {file}"); + // int res = App.DB.ImportRac(rac); + // if (res != 1) { + // // Errore nel salvataggio + // Interlocked.Increment(ref _errori); + // } else { + // // salvataggio corretto + // Interlocked.Increment(ref _completati); + // } + // } else { + // Interlocked.Increment(ref _errori); + // } + // UpdateCounters(); + // }); + // } + + foreach (string file in files) { + string name = System.IO.Path.GetFileName(file); + Logger.Warning($"Import - Start estrazione racconto: {name}"); + + cLink_A69 lk = new cLink_A69(file, name); + cRac rac = await lk.EstraiRac(file); + if (rac != null) { + // Racconto estratto correttamente, lo salvo sul DB + Logger.Warning($"Import - estrazione corretta: {name}"); + int res = App.DB.ImportRac(rac); + if (res != 1) { + // errore nel salvataggio + Logger.Warning($"Import - errore nel salvataggio: {name}"); + Interlocked.Increment(ref _errori); + } else { + // salvataggio ok + Logger.Warning($"Import - racconto salvato: {name}"); + Interlocked.Increment(ref _completati); + } + } else { + Logger.Warning($"Import - estrazione errata: {name}"); + Interlocked.Increment(ref _errori); + } + UpdateCounters(); + } + UpdateCounters(); + } + + + private void UpdateCounters() { + if (_lblInCorso.InvokeRequired) { + _lblInCorso.Invoke(new Action(UpdateCounters)); + return; + } + + int daFare = _totali - _completati - _errori; + + _lblInCorso.Text = $"Totali: {_totali} - Completati: {_completati} - Errori: {_errori} - Da fare: {daFare}"; + + _progressBar.Maximum = _totali > 0 ? _totali : 1; + _progressBar.Value = _completati + _errori; + } + + + }//class Service_Importer + +}//namespace A69WD.Service diff --git a/Src/A69WD/UI/frmDownloader.Designer.cs b/Src/A69WD/UI/frmDownloader.Designer.cs index b6a13a8..915fa03 100644 --- a/Src/A69WD/UI/frmDownloader.Designer.cs +++ b/Src/A69WD/UI/frmDownloader.Designer.cs @@ -30,11 +30,12 @@ this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog(); this.btnShowLog = new System.Windows.Forms.Button(); this.pbST = new System.Windows.Forms.ProgressBar(); + this.btnImport = new System.Windows.Forms.Button(); this.SuspendLayout(); // // btnClose // - this.btnClose.Location = new System.Drawing.Point(263, 12); + this.btnClose.Location = new System.Drawing.Point(348, 12); this.btnClose.Name = "btnClose"; this.btnClose.Size = new System.Drawing.Size(79, 33); this.btnClose.TabIndex = 14; @@ -58,7 +59,7 @@ this.lblST.Dock = System.Windows.Forms.DockStyle.Bottom; this.lblST.Location = new System.Drawing.Point(0, 73); this.lblST.Name = "lblST"; - this.lblST.Size = new System.Drawing.Size(352, 22); + this.lblST.Size = new System.Drawing.Size(433, 22); this.lblST.TabIndex = 9; this.lblST.Text = "Status"; this.lblST.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; @@ -81,7 +82,7 @@ // // btnShowLog // - this.btnShowLog.Location = new System.Drawing.Point(178, 12); + this.btnShowLog.Location = new System.Drawing.Point(263, 12); this.btnShowLog.Name = "btnShowLog"; this.btnShowLog.Size = new System.Drawing.Size(79, 33); this.btnShowLog.TabIndex = 17; @@ -94,14 +95,25 @@ this.pbST.Dock = System.Windows.Forms.DockStyle.Bottom; this.pbST.Location = new System.Drawing.Point(0, 55); this.pbST.Name = "pbST"; - this.pbST.Size = new System.Drawing.Size(352, 18); + this.pbST.Size = new System.Drawing.Size(433, 18); this.pbST.TabIndex = 18; // + // btnImport + // + this.btnImport.Location = new System.Drawing.Point(182, 12); + this.btnImport.Name = "btnImport"; + this.btnImport.Size = new System.Drawing.Size(79, 33); + this.btnImport.TabIndex = 19; + this.btnImport.Text = "Import Rac"; + this.btnImport.UseVisualStyleBackColor = true; + this.btnImport.Click += new System.EventHandler(this.btnImport_Click); + // // frmDownloader // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; - this.ClientSize = new System.Drawing.Size(352, 95); + this.ClientSize = new System.Drawing.Size(433, 95); + this.Controls.Add(this.btnImport); this.Controls.Add(this.pbST); this.Controls.Add(this.btnShowLog); this.Controls.Add(this.btnImportLinks); @@ -123,5 +135,6 @@ private System.Windows.Forms.OpenFileDialog openFileDialog1; private System.Windows.Forms.Button btnShowLog; private System.Windows.Forms.ProgressBar pbST; + private System.Windows.Forms.Button btnImport; } } \ No newline at end of file diff --git a/Src/A69WD/UI/frmDownloader.cs b/Src/A69WD/UI/frmDownloader.cs index 1fc7f7b..2e8a854 100644 --- a/Src/A69WD/UI/frmDownloader.cs +++ b/Src/A69WD/UI/frmDownloader.cs @@ -17,6 +17,7 @@ using A69WD.Net; using System.Collections.Concurrent; using System.Xml.Linq; using A69WD.Service; +using A69WD.Data; namespace A69WD { @@ -53,9 +54,7 @@ namespace A69WD { } private async void btnDownloadAll_Click(object sender, EventArgs e) { - ////engine.Start(true); - ////engine.Start(!cbSoloFileIndice.Checked); - //engine.StartParallel(!cbSoloFileIndice.Checked, int.Parse(tbNumThred.Text)); + btnDownloadAll.Enabled = false; // - Creo istanza del client per il sito con autenticazione: lblST.Text = DateTime.Now.ToString() + " - Login"; @@ -99,18 +98,18 @@ namespace A69WD { // Preparo il servizio - service = new Service_Crawler(lblST, pbST); + serviceCrawler = new Service_Crawler(lblST, pbST); // Inserisco i link iniziali nella coda - if (!cLink_A69.InsertStartLink(service)) { + if (!cLink_A69.InsertStartLink(serviceCrawler)) { lblST.Text = "Inserimento A69 start link fault."; return; } // avvio il servizio - service.StartWorker(siteA69); + serviceCrawler.StartWorker(siteA69); } - private Service_Crawler service = null; + private Service_Crawler serviceCrawler = null; private void btnShowLog_Click(object sender, EventArgs e) { @@ -126,12 +125,15 @@ namespace A69WD { private void btnClose_Click(object sender, EventArgs e) { //if (engine.Stop()) this.Close(); - // fermo il servizio - if (service != null) service.StopWorker(); + // fermo i servizi + if (serviceCrawler != null) serviceCrawler.StopWorker(); + if (serviceImporter != null) serviceImporter.StopWorker(); this.Close(); } + + #region Gestione eventi dal engine // // private void Engine_Updating(object sender, EngineEventArgs e) { EngineUpdatingStatus(e.Message, e.NTot, e.NtoDown, e.NDown); } @@ -156,6 +158,31 @@ namespace A69WD { // #endregion + private void btnImport_Click(object sender, EventArgs e) { + // string fp = "C:\\Commesse\\_zPrivate\\A69WD\\Test\\Down\\__A69_altro_Collarini-e-fantasie_166756.html"; + // cLink_A69 lk = new cLink_A69("Tmp", "tmp"); + // cRac rac = await lk.EstraiRac(fp); + // if (rac != null) { + // //foreach (string tag in rac.Tags) { + // for (int i = 0; i