Inheritance: SystemException, ISerializable
Esempio n. 1
0
 public string UnzipDatabase(string zipFilePath, string sharedFolderPath)
 {
     var tmpDir = PathUtils.PrepareDirectory(sharedFolderPath, PathUtils.GetFileName(Path.GetRandomFileName()));
     _log.InfoFormat("Unzip DB to {0}", tmpDir);
     using (var zipFile = new ZipFile(zipFilePath)) {
         var db = zipFile.SelectEntries("name = *.bak", "db").FirstOrDefault();
         if (db == null) {
             var ex = new ArgumentException("zipFilePath");
             _log.ErrorFormat("Can't find database backup in zip file: {0}", zipFilePath);
             _log.Error(ex);
             throw ex;
         }
         _log.InfoFormat("Extracting database to {0}", tmpDir);
         try {
             db.Extract(tmpDir, ExtractExistingFileAction.OverwriteSilently);
         }
         catch (Exception ex) {
             _log.Error(ex);
             throw;
         }
         var extractedFile = Directory.EnumerateFiles(tmpDir, "*.bak", SearchOption.AllDirectories).FirstOrDefault();
         if (extractedFile == null) {
             var ex = new Exception("zipFilePath");
             _log.ErrorFormat("Can't find extracted database backup in : {0}", tmpDir);
             _log.Error(ex);
             throw ex;
         }
         _log.DebugFormat("Backup found: {0}", extractedFile);
         return extractedFile;
     }
 }
Esempio n. 2
0
        /// *** This is ported from Dart Future to C# Task<TResult>
        /// *** The usage of the class should be mantained - to be checked
        public static async Task <TransactionResult> broadcastStdTx(Wallet wallet, StdTx stdTx, String mode = "sync")
        {
            // Get the endpoint
            String apiUrl = $"{wallet.networkInfo.lcdUrl}/txs";

            // Build the request body
            Dictionary <String, Object> requestBody = new Dictionary <String, Object>
            {
                { "tx", stdTx.toJson() },
                { "mode", mode }
            };
            String payload = JsonConvert.SerializeObject(requestBody);

            Debug.WriteLine($"****** Payload: {payload}");

            HttpContent content = new StringContent(payload, Encoding.UTF8, "application/json");
            // Get the server response
            HttpResponseMessage response = await client.PostAsync(apiUrl, content);

            if (response.StatusCode != System.Net.HttpStatusCode.OK)
            {
                System.ArgumentException argEx = new System.ArgumentException($"Expected status code OK (200) but got ${response.StatusCode} - ${response.ReasonPhrase} - ${response.Content}");
                throw argEx;
            }

            // Convert the response
            String encodedJson = await response.Content.ReadAsStringAsync();

            Debug.WriteLine($"******+++++++ encodedJson: {encodedJson}");
            Dictionary <String, Object> json = JsonConvert.DeserializeObject <Dictionary <String, Object> >(encodedJson);

            return(_convertJson(json));
        }
Esempio n. 3
0
        public abstractshape GetName(string shapetype)
        {
            //variable to collect passed parameter
            string shapetypename = shapetype;

            //checking the passed parameter
            if (shapetypename.Equals("Rectangle", StringComparison.OrdinalIgnoreCase))
            {
                //returning the class
                return(new rectangle());
            }
            //checking the passed parameter
            else if (shapetypename.Equals("Triangle", StringComparison.OrdinalIgnoreCase))
            {
                //returning the class
                return(new triangle());
            }
            //checking the passed parameter
            else if (shapetypename.Equals("Circle", StringComparison.OrdinalIgnoreCase))
            {
                //returning the class
                return(new circle());
            }
            else if (shapetypename.Equals("POLYGON", StringComparison.OrdinalIgnoreCase))
            {
                //returning the class
                return(new polygon()); //creating instance of polygon
            }
            else
            {
                //if we get here then what has been passed in is unknown so throw an appropriate exception
                System.ArgumentException argEx = new System.ArgumentException("Factory error: " + shapetypename + " does not exist");
                throw argEx;
            }
        }
Esempio n. 4
0
        /// <summary>
        /// Create a new ContextRuntime.
        /// </summary>
        /// <param name="serviceInjector"></param>
        /// <param name="contextConfiguration">the Configuration for this context.</param>
        /// <param name="parentContext"></param>
        public ContextRuntime(
                IInjector serviceInjector,
                IConfiguration contextConfiguration,
                Optional<ContextRuntime> parentContext)
        {
            ContextConfiguration config = contextConfiguration as ContextConfiguration;
            if (config == null)
            {
                var e = new ArgumentException("contextConfiguration is not of type ContextConfiguration");
                Org.Apache.REEF.Utilities.Diagnostics.Exceptions.Throw(e, LOGGER);
            }
            _contextLifeCycle = new ContextLifeCycle(config.Id);
            _serviceInjector = serviceInjector;
            _parentContext = parentContext;
            try
            {
                _contextInjector = serviceInjector.ForkInjector();
            }
            catch (Exception e)
            {
                Org.Apache.REEF.Utilities.Diagnostics.Exceptions.Caught(e, Level.Error, LOGGER);

                Optional<string> parentId = ParentContext.IsPresent() ?
                    Optional<string>.Of(ParentContext.Value.Id) :
                    Optional<string>.Empty();
                ContextClientCodeException ex = new ContextClientCodeException(ContextClientCodeException.GetId(contextConfiguration), parentId, "Unable to spawn context", e);
                
                Org.Apache.REEF.Utilities.Diagnostics.Exceptions.Throw(ex, LOGGER);
            }
            // Trigger the context start events on contextInjector.
            _contextLifeCycle.Start();
        }
        internal static int seleccionarEspaciosDisponibles()
        {
            try
            {
                configs    cf         = configs.getInstance();
                string     dateFormat = cf.getNameStringDB();
                SqlCommand command    = new SqlCommand();
                command.CommandText = "select count (id) from EspacioParqueo where disponible=1 and reservado=0";
                command.CommandType = CommandType.Text;
                string userDB = cf.getUserDB();
                string passDB = cf.getPassDB();
                string nameDB = cf.getNameDB();
                using (DataBase db = DatabaseFactory.createdatabase(nameDB, userDB, passDB))
                {
                    int disponibles = Convert.ToInt32(command.ExecuteScalar());
                    return(disponibles);
                }
            }

            catch (Exception err)
            {
                System.ArgumentException argEx = new System.ArgumentException("0x000033", err);
                throw argEx;
            }
        }
 public void TestDisposeExceptions()
 {
     var d1 = Substitute.For<IDisposable>();
     var e1 = new ArgumentException();
     d1.When(d=>d.Dispose()).Do(d => { throw e1; });
     var d2 = Substitute.For<IDisposable>();
     var e2 = new InvalidOperationException();
     d2.When(d => d.Dispose()).Do(d => { throw e2; });
     var d3 = Substitute.For<IDisposable>();
     var exceptionThrown = false;
     try
     {
         using (var c = new CompositeDisposable())
         {
             c.Add(d1);
             c.Add(d2);
             c.Add(d3);
         }
     }
     catch (AggregateException e)
     {
         exceptionThrown = true;
         Assert.IsTrue(e.InnerExceptions.Contains(e1));
         Assert.IsTrue(e.InnerExceptions.Contains(e2));
     }
     Assert.IsTrue(exceptionThrown);
     d1.Received(1).Dispose();
     d2.Received(1).Dispose();
     d3.Received(1).Dispose();
 }
Esempio n. 7
0
        public SeqDateNode(DateTime startDate_, DateTime endDate_, string strgIncrementType)
        {
            //ガード
            if (startDate_ > endDate_)
            {
                ArgumentException aexcep = new ArgumentException("startDateがendDateより大きな数です。");
                throw aexcep;
            }

            this.startDate = startDate_;
            this.endDate = endDate_;

            this.IncrementType = strgIncrementType;

            this.currentDate = this.startDate;

            switch (this.IncrementType)
            {
                case "日":
                    this.currentDate = this.currentDate.AddDays(-1);
                    break;
                case "月":
                    this.currentDate = this.currentDate.AddMonths(-1);
                    break;
                case "年":
                    this.currentDate = this.currentDate.AddYears(-1);
                    break;
                default:
                    break;
            }
        }
Esempio n. 8
0
 public override void InsertInfo()
 {
     for (int i = 0; i < container.Length; i++)
     {
         int    x;
         int    y;
         int    z;
         string name;
         Console.WriteLine("Enter Point {0} info:", i + 1);
         Console.Write("Enter X: ");
         x = Convert.ToInt32(Console.ReadLine());
         Console.Write("Enter Y: ");
         y = Convert.ToInt32(Console.ReadLine());
         Console.Write("Enter Z: ");
         z = Convert.ToInt32(Console.ReadLine());
         Console.Write("Enter name: ");
         name = Console.ReadLine();
         Point pnt = new Point(x, y, z, name);
         try
         {
             container[i] = pnt;
         }
         catch (System.IndexOutOfRangeException ex)
         {
             System.ArgumentException argEx = new System.ArgumentException("Index is out of range", "", ex);
             throw argEx;
         }
     }
 }
        public static async Task <List <GeometryNode> > GetGeometryNode()
        {
            List <GeometryNode> nodeidResponse = new List <GeometryNode>();

            try
            {
                HttpClient client = await ArchesHttpClient.GetHttpClient();

                if ((DateTime.Now - StaticVariables.archesToken["timestamp"]).TotalSeconds > (StaticVariables.archesToken["expires_in"] - 300))
                {
                    StaticVariables.archesToken = await MainDockpaneView.RefreshToken(StaticVariables.myClientid);
                }

                client.DefaultRequestHeaders.Authorization =
                    new AuthenticationHeaderValue("Bearer", StaticVariables.archesToken["access_token"]);
                HttpResponseMessage response = await client.GetAsync(System.IO.Path.Combine(StaticVariables.archesInstanceURL, "api/nodes/?datatype=geojson-feature-collection&perms=write_nodegroup"));

                response.EnsureSuccessStatusCode();
                string responseBody = await response.Content.ReadAsStringAsync();

                var     serializer = new JavaScriptSerializer();
                dynamic results    = serializer.Deserialize <dynamic>(@responseBody);

                foreach (dynamic element in results)
                {
                    nodeidResponse.Add(new GeometryNode(element["resourcemodelname"], element["name"], element["nodeid"]));
                }
            }
            catch (HttpRequestException e)
            {
                System.ArgumentException argEx = new System.ArgumentException("The nodeid cannot be retrieved from the Arches server", e);
                throw argEx;
            }
            return(nodeidResponse);
        }
        /// <summary>
        /// Creates authentication parameters from the WWW-Authenticate header in response received from resource. This method expects the header to contain authentication parameters.
        /// </summary>
        /// <param name="authenticateHeader">Content of header WWW-Authenticate header</param>
        /// <returns>AuthenticationParameters object containing authentication parameters</returns>
        public static AuthenticationParameters CreateFromResponseAuthenticateHeader(string authenticateHeader)
        {
            if (string.IsNullOrWhiteSpace(authenticateHeader))
            {
                throw new ArgumentNullException("authenticateHeader");
            }

            authenticateHeader = authenticateHeader.Trim();

            // This also checks for cases like "BearerXXXX authorization_uri=...." and "Bearer" and "Bearer "
            if (!authenticateHeader.StartsWith(Bearer, StringComparison.OrdinalIgnoreCase) 
                || authenticateHeader.Length < Bearer.Length + 2
                || !char.IsWhiteSpace(authenticateHeader[Bearer.Length]))
            {
                var ex = new ArgumentException(AdalErrorMessage.InvalidAuthenticateHeaderFormat, "authenticateHeader");
                Logger.Error(null, ex);
                throw ex;
            }

            authenticateHeader = authenticateHeader.Substring(Bearer.Length).Trim();

            Dictionary<string, string> authenticateHeaderItems = EncodingHelper.ParseKeyValueList(authenticateHeader, ',', false, null);

            var authParams = new AuthenticationParameters();
            string param;
            authenticateHeaderItems.TryGetValue(AuthorityKey, out param);
            authParams.Authority = param;
            authenticateHeaderItems.TryGetValue(ResourceKey, out param);
            authParams.Resource = param;

            return authParams;
        }
 private static DiscoveryDocument GetDocumentNoParse(ref string url, DiscoveryClientProtocol client)
 {
     DiscoveryDocument document2;
     DiscoveryDocument document = (DiscoveryDocument) client.Documents[url];
     if (document != null)
     {
         return document;
     }
     string contentType = null;
     Stream stream = client.Download(ref url, ref contentType);
     try
     {
         XmlTextReader xmlReader = new XmlTextReader(new StreamReader(stream, RequestResponseUtils.GetEncoding(contentType))) {
             WhitespaceHandling = WhitespaceHandling.Significant,
             XmlResolver = null,
             DtdProcessing = DtdProcessing.Prohibit
         };
         if (!DiscoveryDocument.CanRead(xmlReader))
         {
             ArgumentException innerException = new ArgumentException(System.Web.Services.Res.GetString("WebInvalidFormat"));
             throw new InvalidOperationException(System.Web.Services.Res.GetString("WebMissingDocument", new object[] { url }), innerException);
         }
         document2 = DiscoveryDocument.Read(xmlReader);
     }
     finally
     {
         stream.Close();
     }
     return document2;
 }
Esempio n. 12
0
        public ParseCommandGradient(string parameters)
        {
            var badCommandException = new ArgumentException("command is invalid for Recolor: " + parameters);

            string[] parametersArray = parameters.Split(':');

            if (parametersArray.Length > 3)
            {
                CommandType = parametersArray[0] == "b" ? CommandTypes.Background : CommandTypes.Foreground;
                Counter = Length = int.Parse(parametersArray[parametersArray.Length - 1]);

                bool keep;
                bool useDefault;

                List<Color> steps = new List<Color>();

                for (int i = 1; i < parametersArray.Length - 1; i++)
                {
                    steps.Add(Color.White.FromParser(parametersArray[i], out keep, out keep, out keep, out keep, out useDefault));
                }

                GradientString = new ColorGradient(steps.ToArray()).ToColoredString(new string(' ', Length));
            }

            else
                throw badCommandException;
        }
Esempio n. 13
0
        private async Task GetInstances()
        {
            StaticVariables.myInstanceURL = InstanceURL.Text;
            try
            {
                HttpResponseMessage response = await client.GetAsync(System.IO.Path.Combine(StaticVariables.myInstanceURL, "search/resources"));

                ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show(System.IO.Path.Combine(StaticVariables.myInstanceURL, "search/resources"));

                response.EnsureSuccessStatusCode();
                string responseBody = await response.Content.ReadAsStringAsync();

                var     serializer   = new JavaScriptSerializer();
                dynamic responseJSON = serializer.Deserialize <dynamic>(@responseBody);
                JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
                dynamic results = responseJSON["results"]["hits"]["hits"];
                int     count   = 0;
                string  names   = "";
                foreach (dynamic element in results)
                {
                    count++;
                    string displayname = element["_source"]["displayname"];
                    names += $"{count}. {displayname} \n";
                }
                ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show($"{count} Instances:\n{names}");
            }
            catch (HttpRequestException e)
            {
                Console.WriteLine("\nException Caught!");
                Console.WriteLine("Message :{0} ", e.Message);
                System.ArgumentException argEx = new System.ArgumentException("Addres is wrong", e);
                throw argEx;
            }
        }
Esempio n. 14
0
        public async Task <bool> UpdateUserInformation(User user)
        {
            try
            {
                var existingUser = await _context.Users.CountAsync(x => x.Id == user.Id);

                if (existingUser == 0)
                {
                    throw new Exception("Selected user not found on database");
                }
                _context.Entry(user).State = EntityState.Modified;
                _context.Entry(user).Property(x => x.Created).IsModified         = false;
                _context.Entry(user).Property(x => x.Email).IsModified           = false;
                _context.Entry(user).Property(x => x.CurrentSemester).IsModified = false;
                _context.Entry(user).Property(x => x.DegreeId).IsModified        = false;
                _context.Entry(user).Property(x => x.AspNetUserId).IsModified    = false;
                _context.Entry(user).Property(x => x.IsGraduated).IsModified     = false;
                _context.Entry(user).Property(x => x.IsExpelled).IsModified      = false;

                var operation = await _context.SaveChangesAsync();

                return(true);
            }
            catch (Exception e)
            {
                System.ArgumentException argEx = new System.ArgumentException("Exception", "An error occured on the database", e);
                throw argEx;
            }
        }
Esempio n. 15
0
 public static List <Tarifa> obtenerTodasTarifa()
 {
     try
     {
         SqlDataReader vuelve;
         List <Tarifa> listaTarifas = new List <Tarifa>();
         Tarifa        tarifa       = new Tarifa();
         configs       cf           = configs.getInstance();
         string        dateFormat   = cf.getNameStringDB();
         SqlCommand    command      = new SqlCommand();
         command.CommandText = "Select tipoTarifa,monto from Tarifas";
         command.CommandType = CommandType.Text;
         string userDB = cf.getUserDB();
         string passDB = cf.getPassDB();
         string nameDB = cf.getNameDB();
         using (DataBase db = DatabaseFactory.createdatabase(nameDB, userDB, passDB))
         {
             vuelve = db.ExecuteReader(command);
             while (vuelve.Read())
             {
                 int    tipo  = (int)vuelve["TipoTarifa"];
                 double monto = (double)vuelve["monto"];
                 tarifa.tipoTarifa = tipo;
                 tarifa.monto      = monto;
                 listaTarifas.Add(tarifa);
             }
         }
         return(listaTarifas);
     }
     catch (Exception err)
     {
         System.ArgumentException argEx = new System.ArgumentException("0x000033", err);
         throw argEx;
     }
 }
Esempio n. 16
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="actionName"></param>
        /// <param name="statement"></param>
        /// <returns></returns>
        public static AVM1.AbstractAction Create(string actionName, string statement)
        {
            AbstractAction product = null;

            if ((null == actionName) || (null == statement))
            {
                ArgumentException e = new ArgumentException("actionName or statement is null");
                Log.Error(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, e);
                throw e;
            }

            product = (AbstractAction)MethodBase.GetCurrentMethod().DeclaringType.Assembly.CreateInstance("Recurity.Swf.AVM1." + actionName);

            if (null == product)
            {
                AVM1ExceptionSourceFormat e = new AVM1ExceptionSourceFormat(actionName + " is not a valid AVM1 action");
                Log.Error(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, e);
                throw e;
            }

            if (!product.ParseFrom(statement))
            {
                AVM1ExceptionSourceFormat e = new AVM1ExceptionSourceFormat("Illegal statement: " + statement);
                Log.Error(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, e);
                throw e;
            }

            return product;
        }
Esempio n. 17
0
        public void WhenAnEventIsWrittenToTheSinkItIsRetrievableFromTheDocumentStore()
        {
            using (var documentStore = new EmbeddableDocumentStore {RunInMemory = true}.Initialize())
            {
                var timestamp = new DateTimeOffset(2013, 05, 28, 22, 10, 20, 666, TimeSpan.FromHours(10));
                var exception = new ArgumentException("Mládek");
                const LogEventLevel level = LogEventLevel.Information;
                const string messageTemplate = "{Song}++";
                var properties = new List<LogEventProperty> { new LogEventProperty("Song", new ScalarValue("New Macabre")) };

                using (var ravenSink = new RavenDBSink(documentStore, 2, TinyWait, null))
                {
                    var template = new MessageTemplateParser().Parse(messageTemplate);
                    var logEvent = new Events.LogEvent(timestamp, level, exception, template, properties);
                    ravenSink.Emit(logEvent);
                }

                using (var session = documentStore.OpenSession())
                {
                    var events = session.Query<LogEvent>().Customize(x => x.WaitForNonStaleResults()).ToList();
                    Assert.AreEqual(1, events.Count);
                    var single = events.Single();
                    Assert.AreEqual(messageTemplate, single.MessageTemplate);
                    Assert.AreEqual("\"New Macabre\"++", single.RenderedMessage);
                    Assert.AreEqual(timestamp, single.Timestamp);
                    Assert.AreEqual(level, single.Level);
                    Assert.AreEqual(1, single.Properties.Count);
                    Assert.AreEqual("New Macabre", single.Properties["Song"]);
                    Assert.AreEqual(exception.Message, single.Exception.Message);
                }
            }
        }
Esempio n. 18
0
        public string modificarPaciente(Paciente paciente)
        {
            try
            {
                using (var db = new ApplicationDbContext())
                {
                    var result = db.pacienteContext.SingleOrDefault(b => b.numeroHistoriaClinica == paciente.numeroHistoriaClinica);
                    if (result != null)
                    {
                        result.estadoHC = false;
                        db.SaveChanges();
                    }
                }

                //var pacienteModificado = new Paciente { numeroHistoriaClinica = paciente.numeroHistoriaClinica, estadoHC = false };
                //using (var context = new ApplicationDbContext())
                //{
                //    context.pacienteContext.Attach(pacienteModificado);
                //    pacienteModificado.nombre = "A";
                //    //pacienteModificado.estadoHC = false;
                //    //pacienteModificado.estadoHC = pacienteModificado.estadoHC;
                //    context.SaveChanges();
                //}
            }
            catch (Exception e)
            {
                System.ArgumentException argxEx = new System.ArgumentException("No se pudo actualizar el paciente creado.", e.Message);
                return(argxEx.ToString());
            }
            return("Exito");
        }
Esempio n. 19
0
        private static void WarnAboutUnsupportedActionPreferences(
            Cmdlet cmdlet,
            ActionPreference effectiveActionPreference,
            string nameOfCommandLineParameter,
            Func<string> inquireMessageGetter,
            Func<string> stopMessageGetter)
        {
            string message;
            switch (effectiveActionPreference)
            {
                case ActionPreference.Stop:
                    message = stopMessageGetter();
                    break;

                case ActionPreference.Inquire:
                    message = inquireMessageGetter();
                    break;

                default:
                    return; // we can handle everything that is not Stop or Inquire
            }

            bool actionPreferenceComesFromCommandLineParameter = cmdlet.MyInvocation.BoundParameters.ContainsKey(nameOfCommandLineParameter);
            if (actionPreferenceComesFromCommandLineParameter)
            {
                Exception exception = new ArgumentException(message);
                ErrorRecord errorRecord = new ErrorRecord(exception, "ActionPreferenceNotSupportedByCimCmdletAdapter", ErrorCategory.NotImplemented, null);
                cmdlet.ThrowTerminatingError(errorRecord);
            }
        }
Esempio n. 20
0
        public string modificarCierreHC(IngresoClinica ingresoClinica)
        {
            try
            {
                var cierreHC = new IngresoClinica {
                    idIngresoClinica = ingresoClinica.idIngresoClinica
                };
                using (var context = new ApplicationDbContext())
                {
                    context.ingresoClinicaContext.Attach(cierreHC);
                    cierreHC.idIngresoClinica = ingresoClinica.idIngresoClinica;
                    cierreHC.estadoHC         = true;
                    cierreHC.estadoRemision   = true;
                    //cierreHC.idUsuario = ingresoClinica.idUsuario;
                    context.SaveChanges();
                }

                return("Exito");
            }
            catch (Exception e)
            {
                System.ArgumentException argxEx = new System.ArgumentException("No se pudo modificar el cierre.", e.Message);
                return(argxEx.ToString());
            }
        }
 public override void InsertInfo()
 {
     for (int i = 0; i < container.Length; i++)
     {
         int x;
         int y;
         int z;
         string name;
         Console.WriteLine("Enter Point {0} info:", i + 1);
         Console.Write("Enter X: ");
         x = Convert.ToInt32(Console.ReadLine());
         Console.Write("Enter Y: ");
         y = Convert.ToInt32(Console.ReadLine());
         Console.Write("Enter Z: ");
         z = Convert.ToInt32(Console.ReadLine());
         Console.Write("Enter name: ");
         name = Console.ReadLine();
         Point pnt = new Point(x, y, z, name);
         try
         {
             container[i] = pnt;
         }
         catch (System.IndexOutOfRangeException ex)
         {
             System.ArgumentException argEx = new System.ArgumentException("Index is out of range", "", ex);
             throw argEx;
         }
     } 
 }
Esempio n. 22
0
 public string modificarRemision(List <IngresoClinica> ingresoPaciente)
 {
     try
     {
         foreach (var item in ingresoPaciente)
         {
             var cierreHC = new IngresoClinica {
                 idIngresoClinica = item.idIngresoClinica
             };
             using (var context = new ApplicationDbContext())
             {
                 context.ingresoClinicaContext.Attach(cierreHC);
                 cierreHC.idIngresoClinica = item.idIngresoClinica;
                 cierreHC.estadoRemision   = false;
                 cierreHC.id_paciente      = item.id_paciente;
                 cierreHC = item;
                 context.SaveChanges();
             }
             context.SaveChanges();
         }
         return("Exito");
     }
     catch (Exception e)
     {
         System.ArgumentException argxEx = new System.ArgumentException("No se pudo modificar la remision.", e.Message);
         return(argxEx.ToString());
     }
 }
Esempio n. 23
0
        internal static DataSet getEspacio(int id)
        {
            try
            {
                DataSet    vuelve     = new DataSet();
                configs    cf         = configs.getInstance();
                string     dateFormat = cf.getNameStringDB();
                SqlCommand command    = new SqlCommand();
                command.Parameters.AddWithValue("@id", id);

                command.CommandText = "usp_SELECT_EspacioParqueo_ByID";
                command.CommandType = CommandType.StoredProcedure;
                string userDB = cf.getUserDB();
                string passDB = cf.getPassDB();
                string nameDB = cf.getNameDB();
                using (DataBase db = DatabaseFactory.createdatabase(nameDB, userDB, passDB))
                {
                    vuelve = db.ExecuteReader(command, "consulta");
                    //db.ExecuteNonQuery(command, IsolationLevel.ReadCommitted);
                }
                return(vuelve);
            }
            catch (Exception err)
            {
                System.ArgumentException argEx = new System.ArgumentException("0x000033", err);
                throw argEx;
            }
        }
Esempio n. 24
0
        public string modificarConsultaDocumentoGeneral(Consulta consulta)
        {
            try
            {
                var consult = new Consulta {
                    idConsulta = consulta.idConsulta
                };
                using (var context = new ApplicationDbContext())
                {
                    context.consultaContext.Attach(consult);

                    consult.resultadoAutoevaluacion                    = consulta.resultadoAutoevaluacion;
                    consult.hipotesisPsicologica                       = consulta.hipotesisPsicologica;
                    consult.objetivosTerapeuticos                      = consulta.objetivosTerapeuticos;
                    consult.estrategiasTecnicasTerapeuticas            = consulta.estrategiasTecnicasTerapeuticas;
                    consult.logrosAlcanzadosSegunObjetivosTerapeuticos = consulta.logrosAlcanzadosSegunObjetivosTerapeuticos;
                    consult.logrosAlcanzadosSegunConsultante           = consulta.logrosAlcanzadosSegunConsultante;
                    consult.resumen = consulta.resumen;
                    consult.observacionesRecomendaciones = consulta.observacionesRecomendaciones;
                    context.SaveChanges();
                }
            }
            catch (Exception e)
            {
                System.ArgumentException argxEx = new System.ArgumentException("No se pudo actualizar la informacion de ingreso nueva.", e.Message);
                return(argxEx.ToString());
            }
            return("Exito");
        }
        public object ExecuteQuery(string query)
        {
            connection();

            var cmd = new SqlCommand("", _connection);

            _query = query;

            var where          = "";
            cmd.CommandTimeout = 100000;
            cmd.CommandText    = _query;

            _connection.Open();

            int i;

            try
            {
                return(cmd.ExecuteScalar());
            }
            catch (Exception ex)
            {
                System.ArgumentException argEx = new System.ArgumentException("", "", ex);
            }
            finally
            {
                _connection.Close();
            }



            return(null);
        }
Esempio n. 26
0
 private static void VerifyNotNullOrEmpty(ArgumentException argumentException, string paramName)
 {
     Assert.Equal(
         ToFullArgExMessage(String.Format(CommonResources.Argument_NotNullOrEmpty, paramName), paramName),
         argumentException.Message);
     VerifyArgEx(argumentException, paramName);
 }
Esempio n. 27
0
        /// <summary>
        /// Begin output
        /// </summary>
        protected override void BeginProcessing()
        {
            switch (ParameterSetName)
            {
            case ConnectionStringParameterSetName:
                WriteVerbose(string.Format("Writing SQLConnectionString: {0}", SQLConnectionString));
                bool IsValid = SQLiteDB.ValidateConnectionString(SQLConnectionString);
                if (!IsValid)
                {
                    ArgumentException exception = new System.ArgumentException(
                        String.Format("Argument is not a correct syntax\nValue: {0}", SQLConnectionString),
                        "SQLConnectionString"
                        );
                    ErrorRecord errorRecord = new ErrorRecord(exception, "ErrorId", ErrorCategory.InvalidArgument, null);
                    ThrowTerminatingError(errorRecord);
                }

                Config.SQLConnectionString = SQLConnectionString;
                Config.IsLocalDatabase     = IsLocalDatabase;
                break;
            }
            foreach (KeyValuePair <String, Type> item in Config.SQLTables)
            {
                SQLiteDB.CreateTable(item.Key, item.Value, true);
            }
        }
Esempio n. 28
0
        public Profile GetProfileByName(string name)
        {
            Connect();
            Profile profile = new Profile();
            var     data    = DoTask(DbContract.SELECTPROFILE + " where " + DbContract.USERNAME + "='" + name + "';");

            if (!data.HasRows)
            {
                Console.WriteLine("Can`t find any data by profilename in database");
                System.ArgumentException argEx = new System.ArgumentException("Can`t find any data by profilename in database");
                throw argEx;
            }
            if (data.Read())
            {
                profile = DbDataReader(data);
                Close();
                return(profile);
            }
            else
            {
                Console.WriteLine("Error while reading data from db");
                Close();
                return(profile);
            }
        }
    /// <summary>
    /// Invokes the specified input.
    /// </summary>
    /// <param name="input">The input.</param>
    /// <param name="getNext">The get next.</param>
    /// <returns>The method return result.</returns>
    public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
    {
      foreach (var argument in input.Arguments)
      {
        string target = argument as string;

        if (string.IsNullOrEmpty(target))
        {
          continue;
        }

        if (Regex.Match(target, @"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?").Success)
        {
          continue;
        }

        ArgumentException argumentException = new ArgumentException("Invalid e-mail format", input.MethodBase.Name);

        Log.Error("Argument exception", argumentException, this);

        return input.CreateExceptionMethodReturn(argumentException);
      }

      return getNext()(input, getNext);
    }
Esempio n. 30
0
        static void Main()
        {
            try
            {
                Thread.CurrentThread.Name = "ConsoleClientThread";

                try
                {
                    var ex = new ArgumentException("Ex", new Exception("Inner"));
                    ex.Data.Add("Key3", "Value3");

                    throw ex;
                }
                catch (Exception ex)
                {
                    ex.Data.Add("Key1", "Value1");
                    ex.Data.Add("Key2", "Value2");
                    new Logger().Log(MethodBase.GetCurrentMethod(), LogLevel.Error, "Error", ex);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }

            Console.WriteLine("Message sent");
            Console.WriteLine("Press any key");
            Console.ReadKey();
        }
Esempio n. 31
0
        public int insertarTarifa(string descripcion, decimal monto)
        {
            try
            {
                int        vuelve;
                configs    cf         = configs.getInstance();
                string     dateFormat = cf.getNameStringDB();
                SqlCommand command    = new SqlCommand();
                command.Parameters.AddWithValue("@descripcion", descripcion);
                command.Parameters.AddWithValue("@monto", monto);
                command.CommandText = "prc_insertarNuevaTarifa";
                command.CommandType = CommandType.StoredProcedure;
                string userDB = cf.getUserDB();
                string passDB = cf.getPassDB();
                string nameDB = cf.getNameDB();
                using (DataBase db = DatabaseFactory.createdatabase(nameDB, userDB, passDB))
                {
                    vuelve = db.ExecuteNonQuery(command);
                    //db.ExecuteNonQuery(command, IsolationLevel.ReadCommitted);
                }

                return(vuelve);
            }
            catch (Exception err)
            {
                System.ArgumentException argEx = new System.ArgumentException("0x000033", err);
                throw argEx;
            }
        }
        protected override void ProcessRecord()
        {
            const string particular = @"Software\ParticularSoftware";

            ProviderInfo provider;
            PSDriveInfo drive;
            var psPath = SessionState.Path.GetUnresolvedProviderPathFromPSPath(LicenseFile, out provider, out drive);
            

            if (provider.ImplementingType != typeof(FileSystemProvider))
            {
                var ex = new ArgumentException(string.Format("{0} does not resolve to a path on the FileSystem provider.", psPath));
                var error = new ErrorRecord(ex, "InvalidProvider", ErrorCategory.InvalidArgument, psPath);
                WriteError(error);
                return;
            }

            var content = File.ReadAllText(psPath);
            if (!CheckFileContentIsALicenseFile(content))
            {
                var ex = new InvalidDataException(string.Format("{0} is not not a valid license file", psPath));
                var error = new ErrorRecord(ex, "InvalidLicense", ErrorCategory.InvalidData, psPath);
                WriteError(error);
                return;
            }

            if (EnvironmentHelper.Is64BitOperatingSystem)
            {
                RegistryHelper.LocalMachine(RegistryView.Registry64).WriteValue(particular, "License", content, RegistryValueKind.String);    
            }
            RegistryHelper.LocalMachine(RegistryView.Registry32).WriteValue(particular, "License", content, RegistryValueKind.String);
        }
Esempio n. 33
0
        public int eliminarTarifa(int tipoTarifa)
        {
            try
            {
                int        vuelve;
                configs    cf         = configs.getInstance();
                string     dateFormat = cf.getNameStringDB();
                SqlCommand command    = new SqlCommand();
                command.CommandText = "update Tarifas set estado=0 where tipoTarifa=" + tipoTarifa;
                command.CommandType = CommandType.Text;
                string userDB = cf.getUserDB();
                string passDB = cf.getPassDB();
                string nameDB = cf.getNameDB();
                using (DataBase db = DatabaseFactory.createdatabase(nameDB, userDB, passDB))
                {
                    vuelve = db.ExecuteNonQuery(command);
                    //db.ExecuteNonQuery(command, IsolationLevel.ReadCommitted);
                }

                return(vuelve);
            }
            catch (Exception err)
            {
                System.ArgumentException argEx = new System.ArgumentException("0x000033", err);
                throw argEx;
            }
        }
Esempio n. 34
0
        internal static string GetTokenFromResponseUri(Uri uri)
        {
            var badSessionInfoException = new ArgumentException("The session response (" + uri.AbsoluteUri + ") does not contain connection information.", "uri");

            string query = uri.Query;

            if (!query.Contains("code="))
                throw badSessionInfoException;

            string[] splittedQuery = query.Split('=');
            if (!splittedQuery[0].Contains("code"))
                throw badSessionInfoException;

            var code = splittedQuery[1];

            string accessTokenUrl = String.Format(ACCESS_TOKEN_URL, appId, SUCCESS_URL, apiSecret, code);
            var token = Post(accessTokenUrl);

            if (!token.Contains("access_token="))
                throw badSessionInfoException;

            var accessToken = token.Split('=')[1];

            return accessToken;
        }
		public void CreateEntityWithPropertiesShouldGenerateValidRowKey()
		{
			var timestamp = new DateTimeOffset(2014, 12, 01, 18, 42, 20, 666, TimeSpan.FromHours(2));
			var exception = new ArgumentException("Some exceptional exception happened");
			var level = LogEventLevel.Information;
			var additionalRowKeyPostfix = "POSTFIX";

			var postLength = additionalRowKeyPostfix.Length + 1 + Guid.NewGuid().ToString().Length;
			var messageSpace = 1024 - (level.ToString().Length + 1) - (1 + postLength);

			// Message up to available space, plus some characters (Z) that will be removed
			var messageTemplate = new string('x', messageSpace-4) + "ABCD" + new string('Z', 20);

			var template = new MessageTemplateParser().Parse(messageTemplate);
			var properties = new List<LogEventProperty>();

			var logEvent = new Events.LogEvent(timestamp, level, exception, template, properties);

			var entity = AzureTableStorageEntityFactory.CreateEntityWithProperties(logEvent, null, additionalRowKeyPostfix);

			// Row Key
			var expectedRowKeyWithoutGuid = "Information|" + new string('x', messageSpace-4) + "ABCD|POSTFIX|";
			var rowKeyWithoutGuid = entity.RowKey.Substring(0, expectedRowKeyWithoutGuid.Length);
			var rowKeyGuid = entity.RowKey.Substring(expectedRowKeyWithoutGuid.Length);

			Assert.AreEqual(1024, entity.RowKey.Length);
			Assert.AreEqual(expectedRowKeyWithoutGuid, rowKeyWithoutGuid);
			Assert.DoesNotThrow(() => Guid.Parse(rowKeyGuid));
			Assert.AreEqual(Guid.Parse(rowKeyGuid).ToString(), rowKeyGuid);
			Assert.False(entity.RowKey.Contains('Z'));
		}
		public void DefaultConstructorWorks() {
			var ex = new ArgumentException();
			Assert.IsTrue((object)ex is ArgumentException, "is ArgumentException");
			Assert.IsTrue(ex.ParamName == null, "ParamName");
			Assert.IsTrue(ex.InnerException == null, "InnerException");
			Assert.AreEqual(ex.Message, DefaultMessage);
		}
        public IGameObjectProcessingStrategy GetProcessingStrategy(ObjectType queryResponseType)
        {
            try
            {
                IGameObjectProcessingStrategy currentStrategy;

                switch (queryResponseType)
                {
                    case ObjectType.Champion:
                        currentStrategy = this.GetChampionStrategy();
                        break;
                    case ObjectType.Item:
                        currentStrategy = this.GetItemStrategy();
                        break;
                    case ObjectType.Rune:
                        currentStrategy = this.GetRuneStrategy();
                        break;
                    case ObjectType.Mastery:
                        currentStrategy = this.GetMasteryStrategy();
                        break;
                    default:
                        var exception = new ArgumentException("Invalid argument supplied for query object type.");
                        this.logger.Fatal("Cannot get strategy for query object type: {0}", exception);
                        throw exception;
                }

                return currentStrategy;
            }
            catch (Exception ex)
            {
                this.logger.FatalFormat("Exception raised while getting processing strategy for {0}: {1}", queryResponseType.ToString(), ex);
                throw ex;
            }
        }
		public void ConstructorWithMessageAndParamNameWorks() {
			var ex = new ArgumentException("The message", "someParam");
			Assert.IsTrue((object)ex is ArgumentException, "is ArgumentException");
			Assert.AreEqual(ex.ParamName, "someParam", "ParamName");
			Assert.IsTrue(ex.InnerException == null, "InnerException");
			Assert.AreEqual(ex.Message, "The message");
		}
Esempio n. 39
0
        public async Task <bool> RegisterToCourse(Guid courseId, Guid studentId)
        {
            try
            {
                var semester    = await(from u in _context.Users where u.Id == studentId select u.CurrentSemester).FirstOrDefaultAsync();
                var newRegister = new UserCourse()
                {
                    Id       = Guid.NewGuid(),
                    Active   = true,
                    CourseId = courseId,
                    UserId   = studentId,
                    Created  = DateTime.Now,
                    Semester = semester
                };
                _context.UserCourses.Add(newRegister);
                await _context.SaveChangesAsync();

                return(true);
            }
            catch (Exception e)
            {
                System.ArgumentException argEx = new System.ArgumentException("Exception", "An error occured on the database", e);
                throw argEx;
            }
        }
Esempio n. 40
0
        /// <summary>
        /// Logical function to determine which cell needs to be touched on.
        /// </summary>
        /// <param name="location"></param>
        /// <returns></returns>
        public Cell GetCell(string location)
        {
            char column = location[0];
            int  row;
            Cell cell;

            if (!Char.IsLetter(column))
            {
                return(null);
            }

            if (!int.TryParse(location.Substring(1), out row))
            {
                return(null);
            }

            try
            {
                cell = GetCell(row - 1, column - 64);
            }
            catch (System.Exception ex)
            {
                System.ArgumentException argEx = new System.ArgumentException("Exception has occured. . .", ex);
                throw argEx;
            }
            return(cell);
        }
Esempio n. 41
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldFailValueValidationIfAnyPartFail()
        public virtual void ShouldFailValueValidationIfAnyPartFail()
        {
            // given
            System.ArgumentException failure = new System.ArgumentException("failing");
            for (int i = 0; i < _aliveAccessors.Length; i++)
            {
                for (int j = 0; j < _aliveAccessors.Length; j++)
                {
                    if (i == j)
                    {
                        doThrow(failure).when(_aliveAccessors[i]).validateBeforeCommit(ArgumentMatchers.any(typeof(Value[])));
                    }
                    else
                    {
                        doAnswer(invocation => null).when(_aliveAccessors[i]).validateBeforeCommit(any(typeof(Value[])));
                    }
                }

                // when
                try
                {
                    _fusionIndexAccessor.validateBeforeCommit(new Value[] { stringValue("something") });
                }
                catch (System.ArgumentException e)
                {
                    // then
                    assertSame(failure, e);
                }
            }
        }
Esempio n. 42
0
    {/// <summary>
     ///Shape factory is created
     /// </summary>
     /// <param shape_identifier="shadeshape"></param>
     /// <returns></returns>
        public ShapeInterface getShape(string shadeShape)
        {
            shadeShape = shadeShape.ToUpper().Trim(); //function that converts given lower case alphabets into upper case ..and trim cut the spaces.

            if (shadeShape.Equals("CIRCLE"))
            {
                return(new Circle()); //constructor
            }
            else if (shadeShape.Equals("DRAWTO"))
            {
                return(new Drawto()); //constructor
            }
            else if (shadeShape.Equals("RECTANGLE"))
            {
                return(new Rectangle()); //constructor
            }
            else if (shadeShape.Equals("TRIANGLE"))
            {
                return(new Triangle()); //constructor
            }
            else if (shadeShape.Equals("POLYGON"))
            {
                return(new Polygon()); //constructor
            }
            else
            {
                System.ArgumentException argEx = new System.ArgumentException("ERROR!! : " + shadeShape + " ");
                throw argEx;
            }
        }
Esempio n. 43
0
        public void Should_not_accept_negatives_numbers()
        {
            var argumentException = new ArgumentException();

            _argumentValidator.Expect(validator => validator.FirstNumberIsValid(Arg<long>.Is.Anything)).Throw(argumentException);
            _fibonacciGenerator.Generate(-1, 1);
        }
        public bool Edit <T>(object modelo, string id)
        {
            int i;

            connection();
            try
            {
                var cmd = new SqlCommand("", _connection);

                _query = @"UPDATE [dbo].[" + modelo.GetType().Name.Replace("Model", "") + "] SET ";

                var where = "";

                var data = "";

                foreach (var property in modelo.GetType().GetProperties())
                {
                    if (property.Name == modelo.GetType().Name.Replace("Model", "").ToString() + "Id")
                    {
                        where = property.Name + " = '" + id + "' ";
                    }
                    else
                    {
                        var value = modelo.GetType().GetProperty(property.Name).GetValue(modelo, null);



                        if (value != null)
                        {
                            data += "[" + property.Name + "] = @" + property.Name + ",";


                            cmd.Parameters.AddWithValue("@" + property.Name, value);
                        }
                    }
                }


                _query += data.Remove(data.Length - 1) + " WHERE " + where + "";


                cmd.CommandText = _query;

                _connection.Open();



                i = cmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                System.ArgumentException argEx = new System.ArgumentException("", "", ex);
                throw argEx;
            }

            _connection.Close();


            return(Convert.ToBoolean(i));
        }
        //return only valid numbers
        public string[] GetValidArray(string[] toCheck, bool allowNeg, long upperBound)
        {
            string        negativeNumbers = "";
            List <string> result          = new List <string>();
            // Op is used to check for two operators in a row
            bool op = true;

            // Checking each token if it is a valid number
            foreach (string s in toCheck)
            {
                long tempLong;
                if (long.TryParse(s, out tempLong))
                {
                    if (!allowNeg && tempLong < 0)
                    {
                        negativeNumbers += "," + tempLong;
                    }
                    else if (tempLong > upperBound)
                    {
                        result.Add("" + 0);
                    }
                    else
                    {
                        result.Add("" + tempLong);
                    }
                    op = false;
                }
                else if (s.Trim() == "+" || s.Trim() == "-" || s.Trim() == "*" || s.Trim() == "/")
                {
                    // Throw exception if 2 operators in a row
                    if (op)
                    {
                        System.ArgumentException argEx = new System.ArgumentException("Invalid operators");
                        throw argEx;
                    }
                    op = true;
                    result.Add(s.Trim());
                }
                else
                {
                    result.Add("0");
                    op = false;
                }
            }
            // Throw exception if negative numbers are not allowed but found
            if (negativeNumbers.Length > 0)
            {
                System.ArgumentException argEx = new System.ArgumentException("Negative numbers denied", negativeNumbers);
                throw argEx;
            }

            // Throw exception if ending with an operator
            if (op)
            {
                System.ArgumentException argEx = new System.ArgumentException("Invalid operators");
                throw argEx;
            }

            return(result.ToArray());
        }
        public bool Execute(string query)
        {
            connection();

            var cmd = new SqlCommand("", _connection);

            _query = query;

            var where = "";

            cmd.CommandText = _query;

            _connection.Open();

            int i;

            try
            {
                i = cmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                System.ArgumentException argEx = new System.ArgumentException("", "", ex);
                throw argEx;
            }

            _connection.Close();


            return(Convert.ToBoolean(i));
        }
Esempio n. 47
0
 internal static int desocuparEspacio()
 {
     try
     {
         configs    cf         = configs.getInstance();
         string     dateFormat = cf.getNameStringDB();
         SqlCommand command    = new SqlCommand();
         command.CommandText = "UPDATE EspacioParqueo SET disponible=1 where id=(select max (id) from EspacioParqueo where disponible=0 and reservado=0)";
         command.CommandType = CommandType.Text;
         string userDB = cf.getUserDB();
         string passDB = cf.getPassDB();
         string nameDB = cf.getNameDB();
         using (DataBase db = DatabaseFactory.createdatabase(nameDB, userDB, passDB))
         {
             int insertado = db.ExecuteNonQuery(command, IsolationLevel.ReadCommitted);
             if (insertado == 0)
             {
                 return(-1);
             }
             else
             {
                 return(insertado);
             }
         }
     }
     catch (Exception err)
     {
         System.ArgumentException argEx = new System.ArgumentException("0x000033", err);
         throw argEx;
     }
 }
Esempio n. 48
0
        private void valid(Puzzle initialState, Puzzle goalState)
        {
            List <int> initial = new List <int>();
            List <int> goal    = new List <int>();

            for (int i = 0; i < initialState.template.GetLength(0); i++)
            {
                for (int j = 0; j < initialState.template.GetLength(1); j++)
                {
                    initial.Add(initialState.template[i, j]);
                    goal.Add(goalState.template[i, j]);
                }
            }

            initial.Sort();
            goal.Sort();

            bool test = initial.SequenceEqual(goal);

            if (!test)
            {
                System.ArgumentException argEx = new System.ArgumentException("Niepoprawne dane");
                throw argEx;
            }
        }
        public void IndexDecider_EndsUpInTheOutput()
        {
            //DO NOTE that you cant send objects as scalar values through Logger.*("{Scalar}", {});
            var timestamp = new DateTimeOffset(2013, 05, 28, 22, 10, 20, 666, TimeSpan.FromHours(10));
            const string messageTemplate = "{Song}++ @{Complex}";
            var template = new MessageTemplateParser().Parse(messageTemplate);
            _options.IndexDecider = (l, utcTime) => string.Format("logstash-{1}-{0:yyyy.MM.dd}", utcTime, l.Level.ToString().ToLowerInvariant());
            using (var sink = new ElasticsearchSink(_options))
            {
                var properties = new List<LogEventProperty> { new LogEventProperty("Song", new ScalarValue("New Macabre")) };
                var e = new LogEvent(timestamp, LogEventLevel.Information, null, template, properties);
                sink.Emit(e);
                var exception = new ArgumentException("parameter");
                properties = new List<LogEventProperty>
                {
                    new LogEventProperty("Song", new ScalarValue("Old Macabre")),
                    new LogEventProperty("Complex", new ScalarValue(new { A  = 1, B = 2}))
                };
                e = new LogEvent(timestamp.AddYears(-2), LogEventLevel.Fatal, exception, template, properties);
                sink.Emit(e);
            }

            _seenHttpPosts.Should().NotBeEmpty().And.HaveCount(1);
            var json = _seenHttpPosts.First();
            var bulkJsonPieces = json.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
            bulkJsonPieces.Should().HaveCount(4);
            bulkJsonPieces[0].Should().Contain(@"""_index"":""logstash-information-2013.05.28");
            bulkJsonPieces[1].Should().Contain("New Macabre");
            bulkJsonPieces[2].Should().Contain(@"""_index"":""logstash-fatal-2011.05.28");
            bulkJsonPieces[3].Should().Contain("Old Macabre");

            //serilog by default simpy .ToString()'s unknown objects
            bulkJsonPieces[3].Should().Contain("Complex\":\"{");

        }
Esempio n. 50
0
 private void ClearHistoryByCmdLine()
 {
     if (this._countParamterSpecified && (this.Count < 0))
     {
         Exception exception = new ArgumentException(StringUtil.Format(HistoryStrings.InvalidCountValue, new object[0]));
         base.ThrowTerminatingError(new ErrorRecord(exception, "ClearHistoryInvalidCountValue", ErrorCategory.InvalidArgument, this._count));
     }
     if (this._commandline != null)
     {
         if (!this._countParamterSpecified)
         {
             foreach (string str in this._commandline)
             {
                 this.ClearHistoryEntries(0L, 1, str, this._newest);
             }
         }
         else if (this._commandline.Length > 1)
         {
             Exception exception2 = new ArgumentException(StringUtil.Format(HistoryStrings.NoCountWithMultipleCmdLine, new object[0]));
             base.ThrowTerminatingError(new ErrorRecord(exception2, "NoCountWithMultipleCmdLine ", ErrorCategory.InvalidArgument, this._commandline));
         }
         else
         {
             this.ClearHistoryEntries(0L, this._count, this._commandline[0], this._newest);
         }
     }
 }
        public X509Certificate2KeyEncryptionKey(X509Certificate2 x509Certificate2) : base(x509Certificate2)
        {
            // base handles lots of the validation
            if (!x509Certificate2.HasPrivateKey)
            {
                throw new ArgumentException(string.Format("x509Certificate2 with thumbprint '{0}' does not have a private key.", x509Certificate2.Thumbprint));
            }

            var badPrivateKeyEx = new ArgumentException(string.Format("x509Certificate2 with thumbprint '{0}' does not have a private key.", x509Certificate2.Thumbprint));

            try
            {
                if (x509Certificate2.PrivateKey == null)
                {
                    throw badPrivateKeyEx;
                }
            }
            catch (Exception ex)
            {
                if (ex == badPrivateKeyEx)
                {
                    throw;
                }
                throw new ArgumentException(badPrivateKeyEx.Message, ex);
            }
            _x5092 = x509Certificate2;
        }
        protected override void DoProcessing()
        {
            using (ServerManager serverManager = new ServerManager())
            {
                ServerManagerWrapper serverManagerWrapper = new ServerManagerWrapper(serverManager, this.SiteName, this.VirtualPath);
                PHPConfigHelper configHelper = new PHPConfigHelper(serverManagerWrapper);
                PHPIniFile phpIniFile = configHelper.GetPHPIniFile();

                PHPIniSetting setting = Helper.FindSetting(phpIniFile.Settings, Name);
                if (setting == null)
                {
                    if (ShouldProcess(Name))
                    {
                        RemoteObjectCollection<PHPIniSetting> settings = new RemoteObjectCollection<PHPIniSetting>();
                        settings.Add(new PHPIniSetting(Name, Value, Section));
                        configHelper.AddOrUpdatePHPIniSettings(settings);
                    }
                }
                else
                {
                    ArgumentException ex = new ArgumentException(String.Format(Resources.SettingAlreadyExistsError, Name));
                    ReportNonTerminatingError(ex, "InvalidArgument", ErrorCategory.InvalidArgument);
                }
            }
        }
        protected override void ProcessRecord()
        {
            if (!File.Exists(this.Filename))
            {
                this.WriteVerbose("File already exists");
                if (this.Overwrite)
                {
                    File.Delete(this.Filename);
                }
                else
                {
                    string msg = $"File \"{this.Filename}\" already exists";
                    var exc = new ArgumentException(msg);
                    throw exc;
                }
            }

            string ext = Path.GetExtension(this.Filename).ToLowerInvariant();

            if (ext == ".html" || ext == ".xhtml" || ext == ".htm")
            {
                this.client.Export.SelectionToSVGXHTML(this.Filename);                
            }
            else
            {
                this.client.Export.SelectionToFile(this.Filename);
            }
        }
Esempio n. 54
0
        public ParseExecuteElements(XmlElementType elementType)
        {
            if (elementType != XmlElementType.ExecuteCommand)
            {
                var ex = new ArgumentException("Invalid XmlElement Type For this Xml Parser!");

                var err = new FileOpsErrorMessageDto
                {
                    DirectoryPath = string.Empty,
                    ErrId = 1,
                    ErrorMessage = ex.Message,
                    ErrSourceMethod = "Constructor()",
                    ErrException = ex,
                    FileName = string.Empty,
                    LoggerLevel = LogLevel.FATAL
                };

                ErrorMgr.LoggingStatus = ErrorLoggingStatus.On;
                ErrorMgr.WriteErrorMsg(err);

                throw ex;
            }

            ElementType = elementType;
        }
Esempio n. 55
0
        /// <summary>
        /// this methods passes the shape of any objects.
        /// </summary>
        /// <param name="shapeType"></param>
        /// <returns></returns>
        public override IShape getShape(string shapeType)
        {
            shapeType = shapeType.ToLower().Trim(); //you could argue that you want a specific word string to create an object but I'm allowing any case combination


            if (shapeType.Equals("circle"))
            {
                return(new Circle());
            }
            else if (shapeType.Equals("rectangle"))
            {
                return(new Rectangle());
            }
            else if (shapeType.Equals("3drectangle"))
            {
                return(new _3DRectangle());
            }
            else if (shapeType.Equals("triangle"))
            {
                return(new Rectangle());
            }
            else
            {
                //if we get here then what has been passed in is inkown so throw an appropriate exception
                System.ArgumentException argEx = new System.ArgumentException("Factory error: " + shapeType + " does not exist");
                throw argEx;
            }
        }
Esempio n. 56
0
        public Shape getShape(String shapeType)
        {
            shapeType = shapeType.ToUpper().Trim(); //you could argue that you want a specific word string to create an object but I'm allowing any case combination


            if (shapeType.Equals("CIRCLE"))
            {
                return(new circle());
            }
            else if (shapeType.Equals("RECTANGLE"))
            {
                return(new rectangle());
            }
            else if (shapeType.Equals("SQUARE"))
            {
                return(new square());
            }

            else if (shapeType.Equals("TRIANGLE"))
            {
                return(new triangle());
            }

            else if (shapeType.Equals("TEXTURE"))
            {
                return(new texture());
            }
            else
            {
                //if we get here then what has been passed in is unknown so throw an appropriate exception
                System.ArgumentException argEx = new System.ArgumentException("Factory error: " + shapeType + " does not exist");
                throw argEx;
            }
        }
Esempio n. 57
0
 public void MergeIn(ParameterParser p)
 {
     foreach (string s in p.parsers.Keys)
     {
         if (!parsers.ContainsKey(s))
         {
             ConstructorInfo ci;
             p.parsers.TryGetValue(s, out ci);
             parsers.Add(s, ci);
         }
         else
         {
             ConstructorInfo oldC;
             ConstructorInfo newC;
             parsers.TryGetValue(s, out oldC);
             p.parsers.TryGetValue(s, out newC);
             if (!oldC.Equals(newC))
             {
                 var e = new ArgumentException(
                 "Conflict detected when merging parameter parsers! To parse " + s
                 + " I have a: " + ReflectionUtilities.GetAssemblyQualifiedName(oldC.DeclaringType)
                 + " the other instance has a: " + ReflectionUtilities.GetAssemblyQualifiedName(newC.DeclaringType));
                 Org.Apache.REEF.Utilities.Diagnostics.Exceptions.Throw(e, LOGGER);
             }
         }
     }
 }
Esempio n. 58
0
        public Shape getShape(String shapeType)
        {
            shapeType = shapeType.ToUpper().Trim();


            if (shapeType.Equals("CIRCLE"))
            {
                return(new Circle());
            }
            else if (shapeType.Equals("RECTANGLE"))
            {
                return(new Rectangle());
            }
            else if (shapeType.Equals("SQUARE"))
            {
                return(new Square());
            }
            else if (shapeType.Equals("TRIANGLE"))
            {
                return(new Triangle());
            }
            else
            {
                System.ArgumentException argEx = new System.ArgumentException("Factory error: " + shapeType + " does not exist");
                throw argEx;
            }
        }
        public static List<BindingMap> GetMaps(string paths)
        {
            var scan = new StringScan(paths);

            var ex = new ArgumentException("Invalid path");

            var maps = new List<BindingMap>();
            var state = ParseState.Begin;
            var current = StringScan.EOF;

            //Parsing State Machine
            switch (state)
            {
                case ParseState.Begin:
                case ParseState.BeginMap:
                    var map = ParseMap(scan);
                    if (!maps.Contains(map))
                        maps.Add(map);
                    goto case ParseState.EndMap;
                case ParseState.EndMap:
                    current = scan.Current();
                    if (current == ',')
                    {
                        scan.MoveNext();
                        goto case ParseState.BeginMap;
                    }
                    if (current == StringScan.EOF)
                        goto case ParseState.End;
                    throw scan.CreateException();
                case ParseState.End:
                    break;
            }

            return maps;
        }
        protected override void ProcessRecord()
        {
            if (!this.CheckFileExists(this.Filename))
            {
                return;
            }

            this.WriteVerbose("Loading {0} as xml", this.Filename);
            var xmldoc = SXL.XDocument.Load(this.Filename);

            var root = xmldoc.Root;
            this.WriteVerbose("Root element name ={0}", root.Name);
            if (root.Name == "directedgraph")
            {
                this.WriteVerbose("Loading as a Directed Graph");
                var dg_model = VAS.DirectedGraph.DirectedGraphBuilder.LoadFromXML(
                    this.client,
                    xmldoc);
                this.WriteObject(dg_model);               
            }
            else if (root.Name == "orgchart")
            {
                this.WriteVerbose("Loading as an Org Chart");
                var oc = VAS.OrgChart.OrgChartBuilder.LoadFromXML(this.client, xmldoc);
                this.WriteObject(oc);
            }
            else
            {
                var exc = new ArgumentException("Unknown root element for XML");
                throw exc;
            }
        }