public void SaveFoto(Foto fotos, byte[] myBytes, string percorsoFileFoto) { try { //se la foto è la principale devo settare le altre a false if (fotos.Principale == true) { var lstFoto = new FotoDAC(ConnectionString).GetFoto(fotos.idAnagrafica); foreach (var ft in lstFoto) { if (ft.Principale == true) { ft.Principale = false; new FotoDAC(ConnectionString).Save(ft); } } } new FotoDAC(ConnectionString).Save(fotos); var percorso = Path.Combine(percorsoFileFoto, fotos.idAnagrafica.ToString()); WriteToFile(percorso, fotos.Nome, myBytes); } catch (Exception ex) { var dex = new DataException(ex.Message); throw new FaultException <DataException>(dex, new FaultReason(ex.Message), new FaultCode("Sender")); } }
public object ExecuteScalar(IDbConnection connection, string statment, params IDataParameter[] dataParameters) { if (connection == null) { Logger.Log(LevelEnum.Warn, Resources.ERR_CONNECTION_NULL); throw new ArgumentNullException("connection", Resources.ERR_CONNECTION_NULL); } try { using (IDbCommand command = CreateCommandImpl(statment, connection)) { return(ExecuteScalarImpl(connection, command, false, dataParameters)); } } catch (DataException) { throw; } catch (Exception ex) { string msg = string.Format(Resources.ERR_EXECUTING_EXECUTE, statment); Logger.Log(LevelEnum.Error, ex, msg); DataException dataException = new DataException(msg, ex); ex.Data["CommandText"] = statment; ex.Data["Database"] = connection.Database; ex.Data["Parameters"] = ToString(dataParameters); throw dataException; } }
public void SaveFotoList(List <Foto> fotos) { using (TransactionScope transaction = new TransactionScope()) { try { foreach (var foto in fotos) { //se la foto è la principale devo settare le altre a false if (foto.Principale == true) { var lstFoto = new FotoDAC(ConnectionString).GetFoto(foto.idAnagrafica); foreach (var ft in lstFoto) { if (ft.Principale == true) { ft.Principale = false; new FotoDAC(ConnectionString).Save(ft); } } } new FotoDAC(ConnectionString).Save(foto); } transaction.Complete(); } catch (Exception ex) { var dex = new DataException(ex.Message); throw new FaultException <DataException>(dex, new FaultReason(ex.Message), new FaultCode("Sender")); } } }
public void ExecuteReader(IDbConnection connection, string statment, Action <IDataReader> fillAction, params IDataParameter[] dataParameters) { if (connection == null) { Logger.Log(LevelEnum.Warn, Resources.ERR_CONNECTION_NULL); throw new ArgumentNullException("connection", Resources.ERR_CONNECTION_NULL); } if (fillAction == null) { Logger.Log(LevelEnum.Warn, Resources.ERR_READER_FILLACTION); throw new ArgumentNullException("fillAction", Resources.ERR_READER_FILLACTION); } try { using (IDbCommand command = CreateCommandImpl(statment, connection)) { ExecuteReaderImpl(connection, command, fillAction, false, dataParameters); } } catch (DataException) { throw; } catch (Exception ex) { string msg = string.Format(Resources.ERR_EXECUTING_EXECUTE, statment); Logger.Log(LevelEnum.Error, ex, msg); DataException dataException = new DataException(msg, ex); throw dataException; } }
public IEnumerable <T> ExecuteReader <T>(object mapperKey, string statment, params IDataParameter[] dataParameters) where T : new() { IDbConnection con = null; try { con = CreateConnection(); } catch (Exception ex) { string msg = string.Format(Resources.ERR_EXECUTING_EXECUTE, statment); Logger.Log(LevelEnum.Error, ex, msg); DataException dataException = new DataException(msg, ex); throw dataException; } foreach (var _value in ExecuteReader <T>(mapperKey, con, statment, dataParameters)) { yield return(_value); } try { using (con) { } } catch (Exception ex) { string msg = string.Format(Resources.ERR_EXECUTING_EXECUTE, statment); Logger.Log(LevelEnum.Error, ex, msg); DataException dataException = new DataException(msg, ex); throw dataException; } }
public static void ThrowDataException(Exception ex, int index, IDataReader reader, string toType, object value) { Exception toThrow; try { var colName = reader.GetName(index); var formattedValue = String.Empty; var fromType = String.Empty; colName = reader.GetName(index); try { if (value == null || value is DBNull) { fromType = "null/DBNull"; formattedValue = "<null>"; } else { formattedValue = Convert.ToString(value); fromType = value.GetType().FullName; } } catch (Exception valEx) { formattedValue = valEx.Message; } toThrow = new DataException($"反序列化失败,Reader[{index}-{colName}](Value:{formattedValue},Type:{fromType}) to Type:{toType} fail", ex); } catch { toThrow = new DataException(ex.Message, ex); } throw toThrow; }
private object ExecuteScalarImpl(IDbConnection con, IDbCommand command, bool usePlainTextHasCommand, params IDataParameter[] dataParameters) { Logger.LogFormat(LevelEnum.Verbose, Resources.INFO_EXECUTE_SCALAR, command.CommandText); if (usePlainTextHasCommand) { Logger.LogFormat(LevelEnum.Alert, Resources.INFO_EXECUTE_RUNNING_PLAINSQL); } object result = null; try { OpenConnection(con); PopulateParameterImpl(command, false, usePlainTextHasCommand, dataParameters); result = command.ExecuteScalar(); } catch (Exception ex) { string msg = string.Format(Resources.ERR_EXECUTING_EXECUTE, command.CommandText); Logger.Log(LevelEnum.Error, ex, msg); DataException dataException = new DataException(msg, ex); ex.Data["CommandText"] = command.CommandText; ex.Data["ComandTimeout"] = command.CommandTimeout; ex.Data["Database"] = con.Database; ex.Data["Parameters"] = ToString(dataParameters); throw dataException; } Logger.LogFormat(LevelEnum.Verbose, Resources.INFO_EXECUTE_SCALAR_END, command.CommandText); return(result); }
public List <T> RunSp <T>(ConnectionNameEnum connectionNameEnum, string storeProcureName, int recordCount, int pageNumber, out int allRecordCount) { var param = Parameters.Clone(); //.ToDictionary(x => x.Key, x => x.Value); Parameters.Clear(); List <T> list; var com = new GeneralMethods().MakeSqlCommand(connectionNameEnum, storeProcureName, param, ConnectionTimeout); var dt = new DataTable(); try { using (var result = com.ExecuteReader()) { var schemaTable = result.GetSchemaTable(); if (schemaTable != null && schemaTable.Select("ColumnName='ErrorCode'").Length > 0) { var sqlSpException = new DataException(); //sqlSpException.Add((int)result["ErrorCode"], result["ErrorMessage"].ToString()); while (result.Read()) { sqlSpException.Add((int)result["ErrorCode"], result["ErrorMessage"].ToString()); } throw sqlSpException; } if (typeof(T).IsValueType || "".GetType() == typeof(T)) { list = new List <T>(); Parallel.ForEach(SimpleParallelDataReader <T>(result), (data) => { list.Add(data); }); allRecordCount = list.Count; return(list); } return(new GeneralMethods().ToViewModel <T>(result, recordCount, pageNumber, out allRecordCount)); //dt.Load(result); ////var tempTable = dt.n ////for(int i = 0; i <= ) //var l = dt.AsEnumerable(); //.Select(); //allRecordCount = l.Count(); //var newList = l.Skip((pageNumber - 1)*recordCount).Take(recordCount); //list = new GeneralMethods().ToViewModel<T>(newList); } } catch (DataException) { Parameters.Clear(); throw; } finally { ConnectionManager.ReleaseConnection(com.Connection); } }
public static DbModelException Create(IObject obj, DataException e) { switch (e.Number) { case null: //-2146233087 return(new DbModelConnectionException(obj, e)); case -1: // connection case 11: case 19: case 17142: return(new DbModelConnectionException(obj, e)); case 17: return(new DbModelDoesNotExistsException(obj, e)); case -2: // timeout return(new DbModelTimeoutException(obj, e)); case 1205: // deadlock return(new DbModelDeadlockException(obj, e)); case 50000: // raiserror from sp return(new DbModelRaiserrorException(obj, e.Message, e)); } return(new DbModelException(obj, e.Message, "", e)); }
public void RemovePerson(long id, string username) { if (UserService.IsAuthentificated(username)) { if (UserService.IsAuthorized(username, ERights.Write)) { if (DataBase.Person_DB.ContainsKey(id)) { Console.WriteLine("--" + DateTime.Now.ToString() + "--"); Console.WriteLine("\tRemove Person with ID:" + id); DataBase.Person_DB.Remove(id); } else { DataException ex = new DataException("User with that ID, doesn't exist!"); throw new FaultException <DataException>(ex); } } else { DataException ex = new DataException("User is not Authorized(Write)!"); throw new FaultException <DataException>(ex); } } else { DataException ex = new DataException("User is not Authentificated!"); throw new FaultException <DataException>(ex); } }
public DataSet GetAllTablesOfData(string spName, string connectionString, Dictionary <string, string> parameters = null, bool includeMessageTable = false) { var dataSet = RunSp(spName, connectionString, parameters); var tempDataset = new DataSet(); var defTable = dataSet.Tables[dataSet.Tables.Count - 1]; for (var i = 0; i < defTable.Rows.Count; i++) { DataTable generalAlertData = dataSet.Tables[0]; dataSet.Tables.Remove(generalAlertData.TableName); if (defTable.Rows[i]["TableType"].ToString() == "D") { tempDataset.Tables.Add(generalAlertData); } if (defTable.Rows[i]["TableType"].ToString() == "S") { tempDataset.Tables.Add(generalAlertData); } if (defTable.Rows[i]["TableType"].ToString() == "M" && includeMessageTable) { tempDataset.Tables.Add(generalAlertData); } if (defTable.Rows[i]["TableType"].ToString() != "E") { continue; } var exception = new DataException(); exception.Data.Add("ErrorTable", dataSet.Tables[i]); throw exception; } return(tempDataset); }
private void CatchValidateException(DataException exception) { if (exception is DbEntityValidationException) { var valException = (DbEntityValidationException)exception; foreach (var eve in valException.EntityValidationErrors) { var log = string.Format("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:", eve.Entry.Entity.GetType().Name, eve.Entry.State); //GeeFashion.Common.Helper.Logger.log.Info("DbEntityValidationException: " + log); foreach (var ve in eve.ValidationErrors) { var errorLog = string.Format("- Property: \"{0}\", Error: \"{1}\"", ve.PropertyName, ve.ErrorMessage); //GeeFashion.Common.Helper.Logger.log.Info("DbEntityValidationException: " + errorLog); } } throw new RepositoryValidationException(valException, context); } if (exception is DbUpdateException) { throw new RepositoryUpdateException((DbUpdateException)exception, ((exception.InnerException != null && exception.InnerException.InnerException != null)?exception.InnerException.InnerException.Message:"Unspecified Exception")); } throw new Exception("Unspecified Error", exception); }
public void SalvaModificheFoto(int idFoto, bool elimina) { Foto foto = new FotoDAC(ConnectionString).Load(idFoto); if (elimina == false) //imposto la foto come di default { foto.Principale = true; var lstFoto = new List <Foto>(); lstFoto.Add(foto); SaveFotoList(lstFoto); } else { //elimino il file dal percorso try { string percorsoFileFoto = ConfigurationManager.AppSettings["PercorsoSalvataggioFoto"]; var percorso = Path.Combine(percorsoFileFoto, foto.idAnagrafica.ToString()); DeleteToFile(percorso, foto.Nome); } catch (Exception) //in caso di errore non effettuo nessun controllo o intervento { } try { new FotoDAC(ConnectionString).Delete(foto); } catch (Exception ex) { var dex = new DataException(ex.Message); throw new FaultException <DataException>(dex, new FaultReason(ex.Message), new FaultCode("Sender")); } } }
protected void NotifyError(DataException error) { foreach (var observer in _carSetupObservers) { observer.OnError(error); } foreach (var observer in _carStatusObservers) { observer.OnCompleted(); } foreach (var observer in _carTelemetryObservers) { observer.OnCompleted(); } foreach (var observer in _eventDataObservers) { observer.OnCompleted(); } foreach (var observer in _lapDataObservers) { observer.OnCompleted(); } foreach (var observer in _motionDataObservers) { observer.OnCompleted(); } foreach (var observer in _participantsDataObservers) { observer.OnCompleted(); } foreach (var observer in _sessionDataObservers) { observer.OnCompleted(); } }
public void Formatting4_Every_exception_gets_an_unique_id_which_is_shared_among_inner_and_outer_exceptions() { Log.EntryPosted += (sender, e) => Console.WriteLine(e.LogEntry.ToLogString()); // scope down the formatting to show just the relevant bits Formatter <LogEntry> .RegisterForMembers(e => e.ExceptionId, e => e.EventType, e => e.Subject); Formatter <DataException> .RegisterForMembers(e => e.Data, e => e.InnerException); Formatter <NullReferenceException> .RegisterForMembers(e => e.Data, e => e.InnerException); Formatter <InvalidOperationException> .RegisterForMembers(e => e.Data, e => e.InnerException); ; var dataException = new DataException("oops!"); dataException.Data["why?"] = "because"; var nullReferenceException = new NullReferenceException("oh my.", dataException); var outerException = new InvalidOperationException("oh noes!", nullReferenceException); try { throw outerException; } catch (Exception ex) { Log.Write(() => ex); } }
protected DataException CreateCommandSpException(Exception sqlEx, string commandName, IDataParameter[] parameters) { DataException newEx = new DataException(string.Format("Error invoking the stored procedure '{0}'", commandName), sqlEx); newEx.Data.Add("StoredProcedureName", commandName); if (parameters != null && parameters.Length > 0) { foreach (IDataParameter prm in parameters) { try { if (prm.Value != null && !(prm.Value is DBNull)) { newEx.Data.Add("param_" + prm.ParameterName, prm.Value.ToString()); } else { newEx.Data.Add("param_" + prm.ParameterName, "NULL"); } } catch { } } } return(newEx); }
public List <Person> PersonsToList(string username) { if (UserService.IsAuthentificated(username)) { if (UserService.IsAuthorized(username, ERights.Read)) { Console.WriteLine(DateTime.Now.ToString()); Console.WriteLine("\t PersonsToList -> {0}", username); File.AppendAllText(path, String.Format("\t" + DateTime.Now.ToString() + " PersonsToList -> {0}" + nl, username)); List <Person> list = new List <Person>(); list = DataBaseAdapter.Persons.Values.ToList(); return(list); } else { DataException ex = new DataException("User " + username + " is not authorized!"); throw new FaultException <DataException>(ex); } } else { DataException ex = new DataException("User " + username + " is not authentificated!"); throw new FaultException <DataException>(ex); } }
public void PrintPersonsInJSON(string username, string filepath) { if (UserService.IsAuthentificated(username)) { if (UserService.IsAuthorized(username, ERights.Read)) { Console.WriteLine(DateTime.Now.ToString()); Console.WriteLine("\t PrintPersonsInJSON -> {0}", username); File.AppendAllText(path, String.Format("\t" + DateTime.Now.ToString() + " PrintPersonsInJSON -> {0}" + nl, username)); List <Person> list = new List <Person>(); list = DataBaseAdapter.Persons.Values.ToList(); string data = JsonConvert.SerializeObject(list, Formatting.Indented); File.WriteAllText("../../../" + filepath, data); } else { DataException ex = new DataException("User " + username + " is not authorized!"); throw new FaultException <DataException>(ex); } } else { DataException ex = new DataException("User " + username + " is not authentificated!"); throw new FaultException <DataException>(ex); } }
public UserModel Login(LoginInModel lim) { var user = new User(); try { user = userio.LoadEntity(u => u.Username == lim.UserName).FirstOrDefault(); } catch (Exception e) { var de = new DataException(); de.Info = ErrorType.IOError.GetHashCode().ToString(); throw de; } if (user == null) { var de = new DataException(); de.Info = ErrorType.UsernotExist.GetHashCode().ToString(); throw de; } if (lim.Password == user.Password) { var um = new UserModel(); um.Id = user.Id; um.Name = user.Name; um.UserName = user.Username; return(um); } else { var de = new DataException(); de.Info = ErrorType.WrongPassword.GetHashCode().ToString(); throw de; } }
// Helper for Error Messages static void GenerateErrorOutput(DataException dataException) { if (dataException == null) { throw new ArgumentNullException("dataException"); } int innerLevel = 0; Exception currentException = dataException; while (currentException != null) { WriteIndents(innerLevel); Console.WriteLine("Type: {0} | Message: {1}", currentException.GetType(), currentException.Message); SqlException sqlException = currentException as SqlException; if (sqlException != null) { WriteIndents(innerLevel); GenerateSqlExceptionOutput(sqlException, innerLevel); } currentException = currentException.InnerException; innerLevel++; if (currentException != null) { WriteIndents(innerLevel); Console.WriteLine("Inner Exception:"); } } }
protected virtual void OnDataException(UdpServerEventArgs arg) { NetStat.Set("Errors", 1, arg.Data?.Length ?? 0); DataException?.Invoke(this, arg); Helper.OnException(arg.Exception); }
internal static DataException Data(string message) { DataException e = new DataException(message); TraceExceptionAsReturnValue(e); return(e); }
public void RemovePerson(long id, string username) { if (UserService.IsAuthentificated(username)) { if (UserService.IsAuthorized(username, ERights.Write)) { if (DataBase.person_DB.ContainsKey(id)) { Console.WriteLine("-- " + DateTime.Now.ToString() + " --"); Console.WriteLine("\t->Remove Person wit id: " + id + " !"); Person p = DataBase.person_DB[id]; DataBase.person_DB.Remove(id); p.Removed = true; Removed.Add(p); } else { DataException ex = new DataException("ERROR: Person with ID:" + id + " doesn't exist!"); throw new FaultException <DataException>(ex); } } else { DataException ex = new DataException("User is not Authorized(Write)!"); throw new FaultException <DataException>(ex); } } else { DataException ex = new DataException("User is not Authentificated!"); throw new FaultException <DataException>(ex); } }
/// <summary> /// Creates a response that represents a data exception failure. /// </summary> /// <param name="dispatchId"></param> /// <param name="e"></param> /// <returns></returns> private static byte[] Exception(int dispatchId, DataException e) { int code = /* TODO: e.ErrorCode */ -1; string msg = e.Message; if (String.IsNullOrEmpty(msg)) { msg = "NULL exception message"; } string server_msg = ""; string stack_trace = ""; if (e is DbDataException) { DbDataException me = (DbDataException)e; server_msg = me.ServerErrorMessage; stack_trace = me.ServerErrorStackTrace; } else { stack_trace = e.StackTrace; } MemoryStream output = new MemoryStream(); BinaryWriter writer = new BinaryWriter(output, Encoding.Unicode); writer.Write(dispatchId); writer.Write(ProtocolConstants.Exception); writer.Write(code); writer.Write(msg); writer.Write(stack_trace); return(output.ToArray()); }
/// <summary> /// Deletes the current Language. /// /// Notice: this can have various sideeffects - use with care. /// </summary> /// <remarks> /// You cannot delete the default language: en-US, this is installed by default and is required. /// </remarks> public void Delete() { lock (Locker) { if (SqlHelper.ExecuteScalar <int>("SELECT count(id) FROM umbracoDomains where domainDefaultLanguage = @id", SqlHelper.CreateParameter("@id", id)) == 0) { var e = new DeleteEventArgs(); FireBeforeDelete(e); if (!e.Cancel) { //remove the dictionary entries first Item.RemoveByLanguage(id); InvalidateCache(); SqlHelper.ExecuteNonQuery("delete from umbracoLanguage where id = @id", SqlHelper.CreateParameter("@id", id)); FireAfterDelete(e); } } else { var e = new DataException("Cannot remove language " + _friendlyName + " because it's attached to a domain on a node"); LogHelper.Error <Language>("Cannot remove language " + _friendlyName + " because it's attached to a domain on a node", e); throw e; } } }
protected DataException CreateCommandTextException(Exception sqlEx, string query, IDataParameter[] parameters) { DataException newEx = new DataException("Error invoking query.", sqlEx); newEx.Data.Add("Query", query); if (parameters != null && parameters.Length > 0) { foreach (IDataParameter prm in parameters) { try { if (prm.Value != null && !(prm.Value is DBNull)) { newEx.Data.Add("param_" + prm.ParameterName, prm.Value.ToString()); } else { newEx.Data.Add("param_" + prm.ParameterName, "NULL"); } } catch { } } } return(newEx); }
private static string ExplainDataException(DataException exception) { if (exception == null) { return(null); } if (exception is DbEntityValidationException validationEx) { var errorMessages = validationEx.EntityValidationErrors .SelectMany(x => x.ValidationErrors) .Select(x => x.ErrorMessage); return(string.Join("\r\n", errorMessages)); } var sqlException = FindSqlException(exception); if (sqlException != null) { return(sqlException.Message); } return(exception.Message); }
public void RemovePerson(long jmbg) { if (StateService.State.Equals(ЕStateServer.Primary)) { if (Database.persons.ContainsKey(jmbg)) { Console.WriteLine("{1} : Deleted person with JMBG : {0}", jmbg, DateTime.Now); Database.persons.Remove(jmbg); } else { DataException ex = new DataException() { Message = "Idem with ID this cannot be found." }; throw new FaultException <DataException>(ex); } } else { ServisStateException ex = new ServisStateException() { Reason = "Server is not in Primary state" }; throw new FaultException <ServisStateException>(ex); } }
public static void LogException(this Exception ex) { // Get the stack trace from the given exception StackTrace st = new StackTrace(ex); int nOffset = -1; // check if it contains valid info if (st.FrameCount == 0) { // nothing found, so we create new Stack Trace st = new StackTrace(); nOffset = 2; } else { nOffset = 0; } // only if we have valid offset CodeException codeEx = new CodeException(); codeEx.MachineName = Environment.MachineName; codeEx.ExceptionTime = DateTime.Now; //codeEx.UserId = System.Threading.Thread.CurrentPrincipal.Identity.Name; if (nOffset >= 0) { // get the current frame StackFrame sf = st.GetFrame(nOffset); codeEx.MethodName = sf.GetMethod().Name; codeEx.ClassName = sf.GetMethod().DeclaringType.Name; codeEx.AssemblyName = sf.GetMethod().DeclaringType.Assembly.FullName;; codeEx.AssemblyVersion = sf.GetMethod().DeclaringType.Assembly.ImageRuntimeVersion; codeEx.StackDump = st.ToString(); } codeEx.ErrorMessage = ex.Message; if (ex is DataException) { DataException x = ex as DataException; if (x.Data != null) { foreach (var key in x.Data.Keys) { codeEx.StackDump += key + ":" + x.Data[key] + Environment.NewLine; } } } while (ex.InnerException != null) { codeEx.ErrorMessage += Environment.NewLine + ex.InnerException.Message; ex = ex.InnerException; } using (var dbContext = new VSDBContext()) { dbContext.CodeExceptions.Add(codeEx); dbContext.SaveChanges(); } }
/// <summary> /// Throws a data exception, only used internally /// </summary> /// <param name="ex">The exception to throw.</param> /// <param name="index">The index the exception occured at.</param> /// <param name="reader">The reader the exception occured in.</param> /// <param name="value">The value that caused the exception.</param> public static void ThrowDataException(Exception ex, int index, IDataReader reader, object value) { Exception toThrow; try { string name = "(n/a)", formattedValue = "(n/a)"; if (reader != null && index >= 0 && index < reader.FieldCount) { name = reader.GetName(index); try { if (value == null || value is DBNull) { formattedValue = "<null>"; } else { formattedValue = Convert.ToString(value) + " - " + Type.GetTypeCode(value.GetType()); } } catch (Exception valEx) { formattedValue = valEx.Message; } } toThrow = new DataException($"Error parsing column {index} ({name}={formattedValue})", ex); } catch { // throw the **original** exception, wrapped as DataException toThrow = new DataException(ex.Message, ex); } throw toThrow; }
public OperationExceptionRetryEventArgs(OperationType operation, DataException exception) : base (operation) { _exception = exception; RetryOperation = false; }
public OperationExceptionEventArgs(OperationType operation, DataException exception) : base (operation) { _exception = exception; }