//public bool Insert(Optional selecDeiValori As String = "", Optional ByRef sql As Ogg = Nothing, Optional nuovaConn As NuovaConn = NuovaConn.seNecessario, Optional strConn As StrConnessione = Nothing, // Optional commitRollback As CommitRoll = CommitRoll.commitRollback, Optional timeOutQuery As Int32 = 0, Optional logMess As Mess = Nothing) As Boolean // If IsNothing(logMess) Then logMess = New Mess(Tipi.err, log.errUserText) // If IsNothing(sql) Then sql = New Ogg // Dim query As String // If IsNothing(selecDeiValori) = True OrElse selecDeiValori = "" Then // Dim col As Colonna, qryTestata, qryValori As String, valori As New List(Of String), primaCol As Boolean, valXqry As List(Of String) // primaCol = True // For Each proprietàCol As Reflection.FieldInfo In Me.GetType.GetFields 'Scorro tutti i field della classe che eredita da TabellaBase alla ricerca delle colonne // If proprietàCol.FieldType<> GetType(Colonna) Then Continue For // col = proprietàCol.GetValue(Me) // If col.ident = True Then Continue For 'Se è identity non va nella insert // qryTestata += col.nm & ", " // If primaCol = True Then // For Each tmpVal In col.valXqryList // valori.Add(tmpVal) // Next // primaCol = False // Else '2° col in poi // valXqry = col.valXqryList 'valXqryList al suo interno cicla i valori per renderli compatibili con sql, quindi la richiamo solamente una volta per le prestazioni // If valori.Count<> valXqry.Count Then // log.Acc(New Mess(Tipi.err, log.errUserText, "per la tabella:<" & nmTab & ">, la colonna:<" & col.nm & "> ha un numero valori di:<" & valXqry.Count & "> mentre la prima colonna ne prevedeva:<" & valori.Count & "> la insert sarà annullata")) // Return False // End If // For i = 0 To valori.Count - 1 // valori(i) += ", " & valXqry(i) // Next // End If // Next // If ValidaBusinessLogic(qryIns, logMess:=logMess) = False Then Return False // qryTestata = RimuoviFinale(qryTestata, ", ") // For Each gruppoValore In valori // qryValori += "(" & gruppoValore & "), " // Next // qryValori = RimuoviFinale(qryValori, ", ") // query = qryIns & nmTab & " (" & qryTestata & ") VALUES " & qryValori // Else // If ValidaBusinessLogic(qryUpd, selecDeiValori, logMess:=logMess) = False Then Return False // query = qryIns & nmTab & " " & selecDeiValori // End If // If sql.ExecNoQuery(query, commitRollback:=commitRollback, nuovaConn:=nuovaConn, strConn:=strConn, timeOutQuery:=timeOutQuery, logMess:=logMess) = False Then Return False // If commitRollback = CommitRoll.commitRollback Then EventoEseguitaQuery(qryIns) // Return True //End Function //Public Function Update(where As String, Optional wherePresente As Boolean = True, Optional ByRef sql As Ogg = Nothing, Optional nuovaConn As NuovaConn = NuovaConn.seNecessario, Optional strConn As StrConnessione = Nothing, // Optional commitRollback As CommitRoll = CommitRoll.commitRollback, Optional visualLog As Boolean = True, Optional timeOutQuery As Int32 = 0, Optional ByRef descErr As String = "") As Boolean public bool UpdateWithPKValue(NuovaConn nuovaConn = NuovaConn.seNecessario, StrConnection strConn = null, CommitRoll commitRollback = CommitRoll.commitRollback, Int32 timeOutQuery = 0, Mess logMess = null) { SqlObj sql = null; return(UpdateWithPKValue(ref sql, nuovaConn, strConn, commitRollback, timeOutQuery, logMess)); }
//Public Function Update(where As String, Optional wherePresente As Boolean = True, Optional ByRef sql As Ogg = Nothing, Optional nuovaConn As NuovaConn = NuovaConn.seNecessario, Optional strConn As StrConnessione = Nothing, // Optional commitRollback As CommitRoll = CommitRoll.commitRollback, Optional timeOutQuery As Int32 = 0, Optional logMess As Mess = Nothing) As Boolean // If IsNothing(logMess) Then logMess = New Mess(Tipi.err, log.errUserText) // If IsNothing(where) Then where = "" // If wherePresente = True AndAlso where = "" Then 'Serve poichè inibisce la possibilità di eseguire la query senza la parte where // logMess.testoDaLoggare = "ricevuto 'wherePresente' a true, ma ricevuto 'where' a nothing o vuoto" // log.Acc(New Mess(Tipi.err, log.errUserText, logMess.testoDaLoggare)) // Return False // End If // If IsNothing(sql) Then sql = New Ogg // Dim query, qrySet, val As String, col As Colonna // For Each proprietàCol As Reflection.FieldInfo In Me.GetType.GetFields 'Scorro tutti i field della classe che eredita da TabellaBase alla ricerca delle colonne // If proprietàCol.FieldType<> GetType(Colonna) Then Continue For // col = proprietàCol.GetValue(Me) // If col.ident = True Then Continue For 'Se è identity non va nella Update // val = col.valXqry // If (val = "NULL" OrElse val = "DEFAULT") AndAlso col.valNull = False Then Continue For // qrySet += col.nm & "=" & val & ", " // Next // If ValidaBusinessLogic(qryUpd, logMess:=logMess) = False Then Return False // qrySet = RimuoviFinale(qrySet, ", ") // If where<> "" Then where = " WHERE " & where // query = qryUpd & nmTab & " SET " & qrySet & where // If sql.ExecNoQuery(query, commitRollback:=commitRollback, nuovaConn:=nuovaConn, strConn:=strConn, timeOutQuery:=timeOutQuery, logMess:=logMess) = False Then Return False // If commitRollback = CommitRoll.commitRollback Then EventoEseguitaQuery(qryUpd) // Return True //End Function public bool Delete(string where, bool wherePresente = true, NuovaConn nuovaConn = NuovaConn.seNecessario, StrConnection strConn = null, CommitRoll commitRollback = CommitRoll.commitRollback, Int32 timeOutQuery = 0, Mess logMess = null) { SqlObj sql = null; return(Delete(where, wherePresente, ref sql, nuovaConn, strConn, commitRollback, timeOutQuery, logMess)); }
public bool Delete(string where, bool wherePresente, ref SqlObj sql, NuovaConn nuovaConn, StrConnection strConn, CommitRoll commitRollback, Int32 timeOutQuery, Mess logMess) { if (logMess == null) { logMess = new Mess(LogType.ERR, Log.main.errUserText); } if (where == null) { where = ""; } if (wherePresente == true && where == "") //Serve poichè inibisce la possibilità di eseguire la query senza la parte where { Log.main.Add(new Mess(LogType.ERR, Log.main.errUserText, "ricevuto 'wherePresente' a true, ma ricevuto 'where' a nothing o vuoto")); return(false); } if (sql == null) { sql = new SqlObj(); } string query; if (where != "") { where = " WHERE " + where; } if (ValidaBusinessLogic(Sql.del, where, logMess: logMess) == false) { return(false); } query = Sql.del + Nm + where; if (sql.ExecNoQuery(query, commitRollback: commitRollback, nuovaConn: nuovaConn, strConn: strConn, timeOutQuery: timeOutQuery, logMess: logMess) == false) { return(false); } if (commitRollback == CommitRoll.commitRollback) { EventoEseguitaQuery(Sql.del); } return(true); }
public static void NotificaErrThrCiclo(Exception ex, bool visualLog) { //Tale metodo mi permette di bloccare la segnalazione di continue notifiche create da thread con ciclo infinito che vanno continuamente in eccezione if (errThrCiclo.Columns.Count == 0) { errThrCiclo.Columns.Add("nomeThr", typeof(String)); errThrCiclo.Columns.Add("data", typeof(DateTime)); } string nomeThrCiclo, testeUteLog; DataRow[] rigaDate; testeUteLog = Log.main.warnUserText; //Non posso ricercare quelli che iniziano per 'thrciclo' poichè l'offuscatore gli cambia nome quindi presumo che l'eccezione arrivi dal thrCiclo, contrariamente se l'eccezione arriva da un metodo richiamato dal... nomeThrCiclo = Util.GetCallStack(dammiSoloSubLiv: 2); //...thrCiclo, inevitabilmente prendere il nome sbagliato rigaDate = errThrCiclo.Select("nomeThr='" + nomeThrCiclo + "'"); if (rigaDate.Length > 0) { if ((DateTime.Now - ((DateTime)rigaDate[0]["data"])).TotalSeconds < 20) { return; //Se già ho visualizzato una eccezione per questo ciclo meno di 20 sec. fa non rivisualizzo } else { rigaDate[0]["data"] = DateTime.Now; } } else { errThrCiclo.Rows.Add(nomeThrCiclo, DateTime.Now); } if (SqlObj.FiltraEccezioniQuery(ex) == true) { visualLog = false; } if (visualLog == false) { testeUteLog = ""; } Log.main.Add(new Mess(LogType.Warn, testeUteLog, "Eccezione in thrCiclo:<" + nomeThrCiclo + ">, ex.mess:<" + ex.Message + ">, ex.type:<" + ex.GetType().ToString() + ">")); }
public bool UpdateWithPKValue(ref SqlObj sql, NuovaConn nuovaConn = NuovaConn.seNecessario, StrConnection strConn = null, CommitRoll commitRollback = CommitRoll.commitRollback, Int32 timeOutQuery = 0, Mess logMess = null) { string where, val; Column col; where = ""; foreach (FieldInfo proprietàCol in this.GetType().GetFields()) { //Scorro tutti i field della classe che eredita da TabellaBase alla ricerca delle colonne if (proprietàCol.FieldType != typeof(Column)) { continue; } col = (Column)proprietàCol.GetValue(this); if (col.PrimKey == false) { continue; //Se non è PrimKey la scarto } val = col.ValXqry; if (val == "NULL" || val == "DEFAULT") { Log.main.Add(new Mess(LogType.Warn, Log.main.warnUserText, "Non è stata valorizzata la colonna chiave:<" + col.Nm + ">")); return(false); } where += col.Nm + "=" + val + " AND "; } if (where == "") { Log.main.Add(new Mess(LogType.Warn, Log.main.warnUserText, "Nella tabella non sono presenti campi chiave")); return(false); } where = where.RemoveFinal("AND "); return(Update(where, true, ref sql, nuovaConn, strConn, commitRollback, timeOutQuery, logMess)); }
public bool ControlloStrutturaDB(out bool esito, out List <string> listaErr) { esito = false; listaErr = new List <string>(); //*****Popolo strutturaInDef List <AnalisiTabella> strutturaInDef = new List <AnalisiTabella>(); AnalisiTabella analisiTabDef; AnalisiColonna analisiColDef; AnalisiFK analisiFK; Type tipoDB, tipoTabella; analisiTabDef = null; tipoDB = this.GetType(); //Prendo il tipo della classe che eredita da DB foreach (PropertyInfo proprietàTab in tipoDB.GetProperties()) { //Scorro tutti i field della classe che eredita da DB alla ricerca delle tabelle if (proprietàTab.PropertyType.IsSubclassOf(typeof(TabellaBase))) { //If proprietàTab.FieldType.BaseType = GetType(TabellaBase) Then TabellaBase tab = (TabellaBase)proprietàTab.GetValue(this); analisiTabDef = new AnalisiTabella(tab); tipoTabella = tab.GetType(); foreach (ForeignKey FK in tab.listaFK) { analisiFK = new AnalisiFK(FK); //Per controllare i FK non posso usare la lista interna a tab poichè non mi posso segnare se è stato controllato analisiTabDef.foreignKeys.Add(analisiFK); } foreach (FieldInfo proprietaCampo in tipoTabella.GetFields()) { if (proprietaCampo.FieldType == typeof(Column)) { Column col = (Column)proprietaCampo.GetValue(tab); if (col == null) { listaErr.Add("In definizione nella tab:<" + tab.Nm + "> è definita la colonna " + proprietaCampo.Name + " ma il valore è null, manca quindi l'instanza della colonna nel costruttore della tabella"); continue; } analisiColDef = new AnalisiColonna(col); analisiTabDef.colonne.Add(analisiColDef); } } strutturaInDef.Add(analisiTabDef); } } //*****Leggo le informazioni che mi servono da DB per poter fare il confronto SqlObj sql = new SqlObj(); DataTable sqlTab = new DataTable(); DataTable sqlCampi = new DataTable(); DataTable sqlKeysPrim = new DataTable(); DataTable sqlIdent = new DataTable(); DataTable sqlFK = new DataTable(); string nomeTabInSql, nomeColInSql, testoErrTab, testoErrCol; ColumnTypes.Base tipoColInSql; if (sql.ExecQuery(Sql.sel + "table_name FROM information_schema.tables", res: ref sqlTab) == false) { return(false); //Recupera sia tabelle che viste } if (sql.ExecQuery(Sql.sel + "* FROM information_schema.columns", res: ref sqlCampi) == false) { return(false); } if (sql.ExecQuery(Sql.sel + "ku.table_name AS tab, ku.column_name AS col " + "FROM information_schema.table_constraints AS tc " + "INNER JOIN information_schema.key_column_usage AS ku ON tc.constraint_type = 'PRIMARY KEY' AND tc.constraint_name = ku.constraint_name", res: ref sqlKeysPrim) == false) { return(false); } if (sql.ExecQuery(Sql.sel + "obj.name AS tab, ident.name AS col FROM sys.identity_columns AS ident " + "INNER JOIN sys.objects as obj ON obj.object_id = ident.object_id " + "where obj.type_desc != 'INTERNAL_TABLE'", res: ref sqlIdent) == false) { return(false); } if (sql.ExecQuery(Sql.sel + "obj.name AS nome, tab1.name AS tab, col1.name AS col, tab2.name AS tabFk, col2.name AS colFk " + "FROM sys.foreign_key_columns fkc " + "INNER JOIN sys.objects obj ON obj.object_id = fkc.constraint_object_id " + "INNER JOIN sys.tables tab1 ON tab1.object_id = fkc.parent_object_id " + "INNER JOIN sys.columns col1 ON col1.column_id = parent_column_id And col1.object_id = tab1.object_id " + "INNER JOIN sys.tables tab2 ON tab2.object_id = fkc.referenced_object_id " + "INNER JOIN sys.columns col2 ON col2.column_id = fkc.referenced_column_id AND col2.object_id = tab2.object_id ", res: ref sqlFK) == false) { return(false); } foreach (DataRow tabInSql in sqlTab.Rows) { nomeTabInSql = (string)tabInSql["TABLE_NAME"]; //*****verifica esistenza tabella in definizione var listaTabInDef = from tmp in strutturaInDef where tmp.tabella.Nm == nomeTabInSql select tmp; if (listaTabInDef.Count() == 0) { listaErr.Add("In sql è presente la tabella:<" + nomeTabInSql + "> non presente in definizione"); continue; } else if (listaTabInDef.Count() > 1) { listaErr.Add("In definizione c'è più di una tabella con il nome:<" + nomeTabInSql + ">"); continue; } else { analisiTabDef = listaTabInDef.ElementAt(0); } testoErrTab = "per la tabella:<" + nomeTabInSql + ">"; foreach (DataRow colInSql in sqlCampi.Select("TABLE_NAME='" + nomeTabInSql + "'")) { nomeColInSql = (string)colInSql["COLUMN_NAME"]; testoErrCol = " la colonna:<" + nomeColInSql + ">"; //*****verifica esistenza colonne in definizione var listaColInDef = from tmp in analisiTabDef.colonne where tmp.colonna.Nm == nomeColInSql select tmp; Column colInDef; if (listaColInDef.Count() == 0) { listaErr.Add("In sql " + testoErrTab + " è presente" + testoErrCol + ", non presente in definizione"); continue; } else if (listaTabInDef.Count() > 1) { listaErr.Add("In definizione " + testoErrTab + " c'è più di una colonna con il nome:<" + nomeColInSql + ">"); continue; } else { colInDef = listaColInDef.ElementAt(0).colonna; } switch (colInSql["IS_NULLABLE"]) { case "NO": if (colInDef.ValNull == true) { listaErr.Add("In sql " + testoErrTab + testoErrCol + " non può essere null, in definizione si"); //Non serve Continue For cos' controllo anche altri errori } break; case "YES": if (colInDef.ValNull == false) { listaErr.Add("In sql " + testoErrTab + testoErrCol + " può essere null, in definizione no"); //Non serve Continue For cos' controllo anche altri errori } break; default: Log.main.Add(new Mess(LogType.ERR, Log.main.errUserText, "In sql " + testoErrTab + testoErrCol + " ha il valore IS_NULLABLE sconosciuto, valore:<" + colInSql["IS_NULLABLE"].ToString() + ">")); continue; } if (Convert.IsDBNull(colInSql["COLUMN_DEFAULT"])) { if (colInDef.ValPred != null) { listaErr.Add("In sql " + testoErrTab + testoErrCol + " non ha valore predefinito, in definizione si, colInDef.valPred:<" + colInDef.ValPred + ">"); //Non serve Continue For cos' controllo anche altri errori } } else { if (colInDef.ValPred == null) { listaErr.Add("In sql " + testoErrTab + testoErrCol + " ha valore predefinito, in definizione no, COLUMN_DEFAULT:<" + colInSql["COLUMN_DEFAULT"].ToString() + ">"); //Non serve Continue For cos' controllo anche altri errori } if (Regex.IsMatch((string)colInSql["COLUMN_DEFAULT"], @"^((\(\(){1}[0-9]+(\)\)){1}|(\('){1}[\s\S]*('\)){1})$")) { //Regex: ((num)) or ('str') , str può essere 0 caratteri num no string valPredInSql = ((string)colInSql["COLUMN_DEFAULT"]).Right(-2).Left(-2); if (valPredInSql != (string)colInDef.ValPred) { listaErr.Add("In sql " + testoErrTab + testoErrCol + " ha valore predefinito:<" + valPredInSql + ">, in definizione:<" + colInDef.ValPred + ">"); //Non serve Continue For cos' controllo anche altri errori } } else { Log.main.Add(new Mess(LogType.ERR, Log.main.errUserText, "In sql " + testoErrTab + testoErrCol + " ha il valore COLUMN_DEFAULT con formato sconosciuto, valore:<" + colInSql["COLUMN_DEFAULT"].ToString() + ">")); continue; } } if (sqlKeysPrim.Select("tab='" + nomeTabInSql + "' AND col='" + nomeColInSql + "'").Count() == 1) { if (colInDef.PrimKey == false) { listaErr.Add("In sql " + testoErrTab + testoErrCol + " è chiave primaria, in definizione no"); //Non serve Continue For cos' controllo anche altri errori } } else { if (colInDef.PrimKey == true) { listaErr.Add("In sql " + testoErrTab + testoErrCol + " non è chiave primaria, in definizione si"); //Non serve Continue For cos' controllo anche altri errori } } //*****verifica del tipo di colonna switch (colInSql["DATA_TYPE"].ToString().ToLower()) { //I tipi che hanno un costruttore devono essere trattati singolarmente case "nvarchar": if (Convert.IsDBNull(colInSql["CHARACTER_MAXIMUM_LENGTH"])) { //se è NVarChar(MAX) la colonna CHARACTER_MAXIMUM_LENGTH vale -1 Log.main.Add(new Mess(LogType.ERR, Log.main.errUserText, "In sql " + testoErrTab + testoErrCol + " è di tipo NVarChar ma il valore di CHARACTER_MAXIMUM_LENGTH è null")); continue; } else if (colInSql["CHARACTER_MAXIMUM_LENGTH"].IsNumeric() == false) { Log.main.Add(new Mess(LogType.ERR, Log.main.errUserText, "In sql " + testoErrTab + testoErrCol + " è di tipo NVarChar ma il valore di CHARACTER_MAXIMUM_LENGTH non è numerico, valore:<" + colInSql["CHARACTER_MAXIMUM_LENGTH"].ToString() + ">")); continue; } else if (Num.ContieneCaratNum(colInSql["CHARACTER_MAXIMUM_LENGTH"].ToString(), ctrlSegno: false)) { Log.main.Add(new Mess(LogType.ERR, Log.main.errUserText, "In sql " + testoErrTab + testoErrCol + " è di tipo NVarChar ma il valore di CHARACTER_MAXIMUM_LENGTH contiene caratteri disattesi, valore:<" + colInSql["CHARACTER_MAXIMUM_LENGTH"].ToString() + ">")); continue; } else if (colInSql["CHARACTER_MAXIMUM_LENGTH"].ToString() == "-1") { //-1 è NVarChar(MAX) tipoColInSql = new ColumnTypes.NVarChar("MAX"); } else { tipoColInSql = new ColumnTypes.NVarChar(colInSql["CHARACTER_MAXIMUM_LENGTH"].ToString()); } break; case "decimal": if (Convert.IsDBNull(colInSql["NUMERIC_PRECISION"]) || Convert.IsDBNull(colInSql["NUMERIC_SCALE"])) { Log.main.Add(new Mess(LogType.ERR, Log.main.errUserText, "In sql " + testoErrTab + testoErrCol + " è di tipo Decimal ma il valore di NUMERIC_PRECISION o NUMERIC_SCALE è null, NUMERIC_PRECISION:<" + colInSql["NUMERIC_PRECISION"].ToString() + ">, NUMERIC_SCALE:<" + colInSql["NUMERIC_SCALE"].ToString() + ">")); continue; } else if (colInSql["NUMERIC_PRECISION"].IsNumeric() == false || colInSql["NUMERIC_SCALE"].IsNumeric() == false) { Log.main.Add(new Mess(LogType.ERR, Log.main.errUserText, "In sql " + testoErrTab + testoErrCol + " è di tipo Decimal ma il valore di NUMERIC_PRECISION o NUMERIC_SCALE non è numerico, NUMERIC_PRECISION:<" + colInSql["NUMERIC_PRECISION"].ToString() + ">, NUMERIC_SCALE:<" + colInSql["NUMERIC_SCALE"].ToString() + ">")); continue; } else if (Num.ContieneCaratNum(colInSql["NUMERIC_PRECISION"].ToString()) || Num.ContieneCaratNum(colInSql["NUMERIC_SCALE"].ToString())) { Log.main.Add(new Mess(LogType.ERR, Log.main.errUserText, "In sql " + testoErrTab + testoErrCol + " è di tipo Decimal ma il valore di NUMERIC_PRECISION o NUMERIC_SCALE contiene caratteri disattesi, NUMERIC_PRECISION:<" + colInSql["NUMERIC_PRECISION"].ToString() + ">, NUMERIC_SCALE:<" + colInSql["NUMERIC_SCALE"].ToString() + ">")); continue; } else { tipoColInSql = new ColumnTypes.Decimal(Convert.ToUInt32(colInSql["NUMERIC_PRECISION"]), Convert.ToUInt32(colInSql["NUMERIC_SCALE"])); } break; default: //Tipo di colonna senza costruttore var tipo = from tmp in Assembly.GetExecutingAssembly().GetTypes() where tmp.IsClass == true && tmp.BaseType == typeof(ColumnTypes.Base) && tmp.Name.ToLower() == (string)colInSql["DATA_TYPE"].ToString().ToLower() select tmp; if (tipo.Count() == 0) { listaErr.Add("In sql " + testoErrTab + testoErrCol + " è di tipo sconoscito, DATA_TYPE:<" + colInSql["DATA_TYPE"].ToString() + ">"); continue; } tipoColInSql = (ColumnTypes.Base)Activator.CreateInstance(tipo.ElementAt(0)); break; } if (tipoColInSql.GetType() != colInDef.Tipo.GetType()) { listaErr.Add("In sql " + testoErrTab + testoErrCol + " ha il tipo è diverso alla definizione, tipoColInSql:<" + tipoColInSql.GetType().Name + ">, colInDef:<" + colInDef.Tipo.GetType().Name + ">"); } else { //Se sono dello stesso tipo controllo il contenuto (le variabili interne) string serialColInSql, serialColInDef; serialColInSql = serialColInDef = ""; if (Serialize.SerializeInText(tipoColInSql, ref serialColInSql) == false || Serialize.SerializeInText(colInDef.Tipo, ref serialColInDef) == false) { continue; } if (serialColInSql.ToLower() != serialColInDef.ToLower()) { listaErr.Add("In sql " + testoErrTab + testoErrCol + " ha il contenuto è diverso dalla definizione" + Util.crLf + Util.crLf + "serialColInSql:<" + serialColInSql + ">" + Util.crLf + Util.crLf + "serialColInDef:<" + serialColInDef + ">"); } } listaColInDef.ElementAt(0).controllato = true; } //*****Verifica del campo Identity della tabella DataRow[] colIdentInSql = sqlIdent.Select("tab='" + nomeTabInSql + "'"); string colIdentInDef = analisiTabDef.tabella.NomeColIdentity; if (colIdentInSql.Count() == 1) { if (colIdentInSql[0]["col"].ToString() != colIdentInDef) { listaErr.Add("In sql " + testoErrTab + " la colonna identity è diversa da quella in definizione, colInSql:<" + colIdentInSql[0]["col"].ToString() + ">, colInDef:<" + colIdentInDef + ">"); } } else { if (colIdentInDef != "") { listaErr.Add("In sql " + testoErrTab + " non c'è la colonna identity, in definizione si, nome colonna:<" + colIdentInDef + ">"); } } //*****Verifica delle foreign key foreach (DataRow fkInSql in sqlFK.Select("tab='" + nomeTabInSql + "'")) { var listaFkInDef = from tmp in analisiTabDef.foreignKeys where tmp.foreignKey.nome == fkInSql["nome"].ToString() select tmp; ForeignKey fkInDef; string testoErrFk; testoErrFk = " la foreign key:<" + fkInSql["nome"] + ">"; if (listaFkInDef.Count() == 0) { listaErr.Add("In sql " + testoErrTab + " c'è" + testoErrFk + ", in definizione no"); continue; } fkInDef = listaFkInDef.ElementAt(0).foreignKey; if (fkInDef.tab != fkInSql["tab"].ToString()) { listaErr.Add("In sql " + testoErrTab + testoErrFk + " ha come tabella:<" + fkInSql["tab"] + "> mentre in definizione è:<" + fkInDef.tab + ">"); } if (fkInDef.col != fkInSql["col"].ToString()) { listaErr.Add("In sql " + testoErrTab + testoErrFk + " ha come colonna:<" + fkInSql["col"] + "> mentre in definizione è:<" + fkInDef.col + ">"); } if (fkInDef.tabFk != fkInSql["tabFk"].ToString()) { listaErr.Add("In sql " + testoErrTab + testoErrFk + " ha come tabellaFk:<" + fkInSql["tabFk"] + "> mentre in definizione è:<" + fkInDef.tabFk + ">"); } if (fkInDef.colFk != fkInSql["colFk"].ToString()) { listaErr.Add("In sql " + testoErrTab + testoErrFk + " ha come colonnaFk:<" + fkInSql["colFk"] + "> mentre in definizione è:<" + fkInDef.colFk + ">"); } listaFkInDef.ElementAt(0).controllato = true; } analisiTabDef.controllato = true; } //*****Ricerca dei non controllati (Significa presenti in definizione ma non presenti in sql) foreach (AnalisiTabella analisiTabInDef in strutturaInDef) { if (analisiTabInDef.controllato == false) { listaErr.Add("In sql la tabella:<" + analisiTabInDef.tabella.Nm + "> non esiste"); continue; } foreach (AnalisiColonna analisiColInDef in analisiTabInDef.colonne) { if (analisiColInDef.controllato == false) { listaErr.Add("In sql nella tabella:<" + analisiTabInDef.tabella.Nm + "> la colonna:<" + analisiColInDef.colonna.Nm + "> non esiste"); } } foreach (AnalisiFK analisiFKInDef in analisiTabInDef.foreignKeys) { if (analisiFKInDef.controllato == false) { listaErr.Add("In sql nella tabella:<" + analisiTabInDef.tabella.Nm + "> il foreign key:<" + analisiFKInDef.foreignKey.nome + "> non esiste"); } } } if (listaErr.Count() == 0) { esito = true; } return(true); }
public static bool Save(this ISavable obj, object destination, Mess logMess = null) { string testo, configType, errDesc; testo = ""; configType = obj.GetType().Name.ParoleMinuMaiu(Str.MinMai.minu, true); errDesc = "name:<" + obj.SavableName + ">, parent:<" + obj.SavableParentName + ">, configType:<" + configType + ">"; if (obj.SavableMarkUser == true) { if (App.CurrentUserId == 0) { Log.main.Add(new Mess(LogType.Warn, Log.main.warnUserText, "for the config: " + errDesc + ", there is no logged in user")); return(false); } errDesc += ", user id:<" + App.CurrentUserId + ">"; } if (Serialize.SerializeInText(obj, ref testo) == false) { return(false); } //if (App.Db != null && (this.memorizzaIn == memorizzaIn.@default || this.memorizzaIn == memorizzaIn.dbPrincipaleApp)) { //Salvo la config nella tabella impostApp del DB if (destination.GetType() == typeof(DBBase) || destination.GetType().IsSubclassOf(typeof(DBBase))) { DBBase Db = (DBBase)destination; SqlObj sql = new SqlObj(connStr: Db.ConnString); DBTabs.ImpostApp settingsTab = Db.ImpostApp; string where = settingsTab.nome.Nm + Sql.WhereFormat(obj.SavableName) + " AND " + settingsTab.padre.Nm + Sql.WhereFormat(obj.SavableParentName) + " AND " + settingsTab.tipo.Nm + Sql.WhereFormat(configType); if (obj.SavableMarkUser == true) { where += " AND " + settingsTab.fk_utentiUte.Nm + Sql.WhereFormat(App.CurrentUserId); settingsTab.fk_utentiUte.Value = App.CurrentUserId; } else { settingsTab.fk_utentiUte.Value = 0; } if (obj.SavableMarkPcName == true) { where += " AND " + settingsTab.nomePc.Nm + Sql.WhereFormat(Environment.MachineName); settingsTab.nomePc.Value = Environment.MachineName; } else { settingsTab.nomePc.Value = ""; } if (sql.ExecQuery(Sql.sel + settingsTab.valore.Nm + " FROM " + settingsTab.Nm + " WHERE " + where) == false) { return(false); } settingsTab.nome.Value = obj.SavableName; settingsTab.padre.Value = obj.SavableParentName; settingsTab.tipo.Value = configType; settingsTab.valore.Value = testo; settingsTab.ultData.Value = DateTime.Now; if (sql.ResDt.Rows.Count == 0) { if (settingsTab.Insert(sql: ref sql) == false) { return(false); } } else if (sql.ResDt.Rows.Count == 1) { if (settingsTab.Update(where : where, sql: ref sql) == false) { return(false); } } else { Log.main.Add(new Mess(LogType.Warn, Log.main.warnUserText, "in the table:<" + settingsTab.Nm + ">, there are more than one setting with: " + errDesc + ", the setting will not be saved")); return(false); } } else if (destination.GetType().IsSubclassOf(typeof(ConfigFile))) { //Salvo la config nel file di configurazione dell'applicazione ConfigFile configFile = (ConfigFile)destination; if (configFile.SaveConfig(obj, obj.SavableMarkUser, errDesc) == false) { return(false); } } else { Log.main.Add(new Mess(LogType.ERR, Log.main.errUserText, "unexpected value for DestinationType:<" + destination.GetType().ToString() + ">")); return(false); } return(true); }
public static ISavable Load(this ISavable obj, object source, out bool inErr, Mess logMess = null) { inErr = true; if (logMess == null) { logMess = new Mess(LogType.Warn, Log.main.warnUserText); } if (String.IsNullOrEmpty(obj.SavableName)) { logMess.testoDaLoggare = "received null or void SavableName"; Log.main.Add(new Mess(LogType.ERR, Log.main.errUserText, logMess.testoDaLoggare)); return(obj); } if (obj == null) { logMess.testoDaLoggare = "received null savable object"; Log.main.Add(new Mess(LogType.ERR, Log.main.errUserText, logMess.testoDaLoggare)); return(obj); } string text, configType, errDesc; configType = obj.GetType().Name; errDesc = "name:<" + obj.SavableName + ">, parent:<" + obj.SavableParentName + ">, configType:<" + configType + ">"; if (obj.SavableMarkUser == true) { if (App.CurrentUserId == 0) { logMess.testoDaLoggare = "for the config: " + errDesc + ", there is no logged in user"; Log.main.Add(new Mess(LogType.ERR, Log.main.errUserText, logMess.testoDaLoggare)); return(obj); } errDesc += ", id utente:<" + App.CurrentUserId + ">"; } if (source.GetType() == typeof(DBBase) || source.GetType().IsSubclassOf(typeof(DBBase))) { //Carico la config dalla tabella impostApp del DB DBBase Db = (DBBase)source; DBTabs.ImpostApp settingsTab = Db.ImpostApp; SqlObj sql = new SqlObj(connStr: Db.ConnString); string where; List <string> queries = new List <string>(); where = settingsTab.nome.Nm + Sql.WhereFormat(obj.SavableName) + " AND " + settingsTab.padre.Nm + Sql.WhereFormat(obj.SavableParentName) + " AND " + settingsTab.tipo.Nm + Sql.WhereFormat(configType); if (obj.SavableMarkUser == true) { where += " AND " + settingsTab.fk_utentiUte.Nm + Sql.WhereFormat(App.CurrentUserId); } else { where += " AND " + settingsTab.fk_utentiUte.Nm + Sql.WhereFormat(0); } //Se distinguiNomePc allora verifico se cè la config per nomePc se non c'è allora eseguo la ricerca senza così eventualmente prendo la confg.dell'utente se if (obj.SavableMarkPcName == true) { queries.Add(Sql.sel + settingsTab.valore.Nm + " FROM " + settingsTab.Nm + " WHERE " + where + " AND " + settingsTab.nomePc.Nm + Sql.WhereFormat(Environment.MachineName)); } queries.Add(Sql.sel + settingsTab.valore.Nm + " FROM " + settingsTab.Nm + " WHERE " + where); foreach (string query in queries) { if (sql.ExecQuery(query) == false) { return(obj); } if (sql.ResDt.Rows.Count > 0) { break; } } if (sql.ResDt.Rows.Count == 0) { //If tipoLogErr <> Tipi._Nothing Then log.Acc(New Mess(tipoLogErr, log.testoUteGen(tipoLogErr), "nella tabella:<" & .nmTab & ">, non ho trovato impostazioni con " & descErr)) logMess.testoDaLoggare = "in the table:" + settingsTab.Nm + ">, there are no settings with: " + errDesc; Log.main.Add(logMess); return(obj); } else if (sql.ResDt.Rows.Count > 1) { logMess.testoDaLoggare = "in the table:" + settingsTab.Nm + ">, there are more than one setting with: " + errDesc + ", sarà preso il primo valore"; Log.main.Add(new Mess(LogType.ERR, Log.main.errUserText, logMess.testoDaLoggare)); } text = (string)sql.ResDt.Rows[0][settingsTab.valore.Nm]; if (Serialize.DeserializeFromText(text, ref obj) == false) { return(obj); } } else if (source.GetType().IsSubclassOf(typeof(ConfigFile))) //Carico la config dal file di configurazione dell'applicazione { ConfigFile configFile = (ConfigFile)source; if (configFile.GetConfig(ref obj, obj.SavableMarkUser, logMess) == false) { return(obj); } } else { Log.main.Add(new Mess(LogType.ERR, Log.main.errUserText, "unexpected value for source type:<" + source.GetType().ToString() + ">")); } inErr = false; return(obj); }
public bool ConnectionTest() { SqlObj sql = new SqlObj(this); return(sql.ConnettiDB()); }
public bool Update(string where, bool wherePresente, ref SqlObj sql, NuovaConn nuovaConn, StrConnection strConn, CommitRoll commitRollback, Int32 timeOutQuery, Mess logMess) { if (logMess == null) { logMess = new Mess(LogType.ERR, Log.main.errUserText); } if (where == null) { where = ""; } if (wherePresente == true && where == "") //Serve poichè inibisce la possibilità di eseguire la query senza la parte where { logMess.testoDaLoggare = "ricevuto 'wherePresente' a true, ma ricevuto 'where' a nothing o vuoto"; Log.main.Add(new Mess(LogType.ERR, Log.main.errUserText, logMess.testoDaLoggare)); return(false); } if (sql == null) { sql = new SqlObj(); } string query, qrySet, val; Column col; qrySet = ""; foreach (FieldInfo proprietàCol in this.GetType().GetFields()) //Scorro tutti i field della classe che eredita da TabellaBase alla ricerca delle colonne { if (proprietàCol.FieldType != typeof(Column)) { continue; } col = (Column)proprietàCol.GetValue(this); if (col.Ident == true) { continue; //Se è identity non va nella Update } val = col.ValXqry; if ((val == "NULL" || val == "DEFAULT") && col.ValNull == false) { continue; } qrySet += col.Nm + "=" + val + ", "; } if (ValidaBusinessLogic(Sql.upd, logMess: logMess) == false) { return(false); } qrySet = qrySet.RemoveFinal(", "); if (where != "") { where = " WHERE " + where; } query = Sql.upd + Nm + " SET " + qrySet + where; if (sql.ExecNoQuery(query, commitRollback: commitRollback, nuovaConn: nuovaConn, strConn: strConn, timeOutQuery: timeOutQuery, logMess: logMess) == false) { return(false); } if (commitRollback == CommitRoll.commitRollback) { EventoEseguitaQuery(Sql.upd); } return(true); }
public bool Insert(string selecDeiValori, ref SqlObj sql, NuovaConn nuovaConn, StrConnection strConn, CommitRoll commitRollback, Int32 timeOutQuery, Mess logMess) { if (logMess == null) { logMess = new Mess(LogType.ERR, Log.main.errUserText); } if (sql == null) { sql = new SqlObj(); } string query; if (selecDeiValori == null || selecDeiValori == "") { Column col; string qryTestata, qryValori; List <string> valori = new List <String>(); bool primaCol; List <string> valXqry; primaCol = true; qryTestata = qryValori = ""; foreach (FieldInfo proprietàCol in this.GetType().GetFields()) { //Scorro tutti i field della classe che eredita da TabellaBase alla ricerca delle colonne if (proprietàCol.FieldType != typeof(Column)) { continue; } col = (Column)proprietàCol.GetValue(this); if (col.Ident == true) { continue; //Se è identity non va nella insert } qryTestata += col.Nm + ", "; if (primaCol == true) { foreach (string tmpVal in col.ValXqryList) { valori.Add(tmpVal); } primaCol = false; } else { //2° col in poi valXqry = col.ValXqryList; //valXqryList al suo interno cicla i valori per renderli compatibili con sql, quindi la richiamo solamente una volta per le prestazioni if (valori.Count != valXqry.Count) { Log.main.Add(new Mess(LogType.ERR, Log.main.errUserText, "per la tabella:<" + Nm + ">, la colonna:<" + col.Nm + "> ha un numero valori di:<" + valXqry.Count + "> mentre la prima colonna ne prevedeva:<" + valori.Count + "> la insert sarà annullata")); return(false); } for (int i = 0; i < valori.Count; i++) { valori[i] += ", " + valXqry[i]; } } } if (ValidaBusinessLogic(Sql.ins, logMess: logMess) == false) { return(false); } qryTestata = qryTestata.RemoveFinal(", "); foreach (string gruppoValore in valori) { qryValori += "(" + gruppoValore + "), "; } qryValori = qryValori.RemoveFinal(", "); query = Sql.ins + Nm + " (" + qryTestata + ") VALUES " + qryValori; } else { if (ValidaBusinessLogic(Sql.upd, selecDeiValori, logMess: logMess) == false) { return(false); } query = Sql.ins + Nm + " " + selecDeiValori; } if (sql.ExecNoQuery(query, commitRollback: commitRollback, nuovaConn: nuovaConn, strConn: strConn, timeOutQuery: timeOutQuery, logMess: logMess) == false) { return(false); } if (commitRollback == CommitRoll.commitRollback) { EventoEseguitaQuery(Sql.ins); } return(true); }
public bool Insert(ref SqlObj sql, string selecDeiValori = "", NuovaConn nuovaConn = NuovaConn.seNecessario, StrConnection strConn = null, CommitRoll commitRollback = CommitRoll.commitRollback, Int32 timeOutQuery = 0, Mess logMess = null) { return(Insert(selecDeiValori, ref sql, nuovaConn, strConn, commitRollback, timeOutQuery, logMess)); }
public static void thrCycle_LockedQryKiller() { SqlObj sql = new SqlObj(); string query, queryBloccante; DateTime oraXatt; UInt64 procIdToKill, durataProc; ProcessStartInfo cmdShell; queryBloccante = ""; oraXatt = DateTime.Now; //// QUERY COMPLETA //query = qrySel & "blocking_session_id AS BlockingSessionID, session_id AS VictimSessionID, " & // " (SELECT [text] FROM sys.sysprocesses CROSS APPLY sys.dm_exec_sql_text([sql_handle]) WHERE spid = blocking_session_id) AS BlockingQuery, " & // " [text] AS VictimQuery, wait_time AS WaitDurationMs, wait_type AS WaitType, percent_complete AS BlockingQueryCompletePercent " & // " FROM sys.dm_exec_requests CROSS APPLY sys.dm_exec_sql_text([sql_handle]) WHERE blocking_session_id > 0 AND " & // " blocking_session_id NOT IN (Select session_id FROM sys.dm_exec_requests CROSS APPLY sys.dm_exec_sql_text([sql_handle]) WHERE blocking_session_id > 0)" // QUERY CON I SOLI CAMPI CHE MI INTERESSANO query = Sql.sel + "blocking_session_id AS BlockingSessionID, (SELECT [text] FROM sys.sysprocesses CROSS APPLY sys.dm_exec_sql_text([sql_handle]) WHERE spid = blocking_session_id) AS BlockingQuery, " + " wait_time AS WaitDurationMs FROM sys.dm_exec_requests CROSS APPLY sys.dm_exec_sql_text([sql_handle]) WHERE blocking_session_id > 0 AND " + " blocking_session_id NOT IN (Select session_id FROM sys.dm_exec_requests CROSS APPLY sys.dm_exec_sql_text([sql_handle]) WHERE blocking_session_id > 0)"; //la WHERE blocking_session_id NOT IN... è stata messa poichè se una query blocca una tabella le altre query saranno tutte vittime della prima, poichè è la prima che blocca tutte le altre in cascata //Come dimostra l'esempio sotto stante //BlockingSessionID() VictimSessionID BlockingQuery VictimQuery //54 57 INSERT INTO xxx (idRnd) VALUES ('12345') SELECT * FROM excDispositivi //57 62 SELECT * FROM excDispositivi SELECT * FROM [excDispositivi] WHERE idRnd=1 while (true) { #if DEBUG == false try { #endif //If AttesaTempoDormiente(oraXatt, 500) = False Then Continue While Thread.Sleep(500); if (App.Config.MainDbConnString.KillQryBloccanteMs < 1) { continue; } if (sql.ExecQuery(query, @out: QryOut.dataReader, strConn: App.Config.MainDbConnString) == false) { continue; //qui posso usare il dataReader tanto sfrutto sempre la stessa connessione senza chiuderla } while (sql.ResOle.Read()) { if (Convert.IsDBNull(sql.ResOle["BlockingSessionID"]) == true) { continue; } procIdToKill = (UInt64)sql.ResOle["BlockingSessionID"]; if (Convert.IsDBNull(sql.ResOle["WaitDurationMs"]) == true) { continue; } durataProc = (UInt64)sql.ResOle["WaitDurationMs"]; queryBloccante = ""; if (Convert.IsDBNull(sql.ResOle["BlockingQuery"]) == false) { queryBloccante = (string)sql.ResOle["BlockingQuery"]; } if (durataProc >= App.Config.MainDbConnString.KillQryBloccanteMs) { Log.main.Add(new Mess(LogType.Warn, "", "query bloccante sarà terminata, id:<" + procIdToKill + ">, query:<" + queryBloccante + ">")); //è stato usato una shell CMD poichè l'istruzione kill se lanciata direttamente de questo programma tramite una semplice query o una stored procedure generava errore(come se non si avessero i diritti) //invece se viene lanciata da un cmdShell(soluzione attuale) oppure da un .bat(soluzione adottata precedentemente) va a buon fine. var mainDb = App.Config.MainDbConnString; if (mainDb.TrustedConn == false) { cmdShell = new ProcessStartInfo("cmd", String.Format("/k {0} & {1}", "osql -S " + mainDb.IndirServer + " -U " + mainDb.UserId + " -P " + mainDb.Password + " -d " + mainDb.Database + @" -Q ""exec dbo.KILLSPID " + procIdToKill + @"""", "exit")); } else { cmdShell = new ProcessStartInfo("cmd", String.Format("/k {0} & {1}", "osql -S " + mainDb.IndirServer + " -E -d " + mainDb.Database + @" -Q ""exec dbo.KILLSPID " + procIdToKill + @"""", "exit")); } cmdShell.WindowStyle = ProcessWindowStyle.Hidden; Process.Start(cmdShell); } } #if DEBUG == false } catch (Exception ex) { Thrs.Thr.NotificaErrThrCiclo(ex, true); } #endif } }