Example #1
0
        public void ReadExceptionFile()
        {
            var expectedException = new ArgumentException("test");
            var mockFile          = Mock.Of <File>();

            Mock.Get(mockFile).Setup(file => file.ReadAllText()).Returns(expectedException.ToString());

            var actualException = ErrorLogHelper.ReadExceptionFile(mockFile);

            Assert.AreEqual(expectedException.ToString(), actualException);
        }
Example #2
0
        public void LogMessage_ReplayedMessageSavedUnitilTheLimit()
        {
            string    replayMessage1 = "ReplayMessage1";
            Exception exception1     = new ArgumentException("Error");
            string    replayMessage2 = "ReplayMessage2";
            Exception exception2     = new NullReferenceException("Error");

            string suffix  = nameof(LogMessage_ReplayedMessageSavedUnitilTheLimit);
            int    eventId = 7;
            Mock <ILogEventSender> eventSourceMock = CreateEventSourceMock(isReplayable: true);

            ReplayableActivity activity = CreateActivity(suffix);

            activity.Start();
            (ILogger logger, _) = LogMessage(eventSourceMock, eventId);
            logger.LogDebug(exception1, replayMessage1);
            logger.LogDebug(exception2, replayMessage2);
            activity.Stop();

            eventSourceMock.Verify(m_logExpression, Times.Exactly(3));
            List <LogMessageInformation> info = activity.GetLogEvents().ToList();

            Assert.AreEqual(2, info.Count);
            StringAssert.Contains(info[0].Message, replayMessage1);
            StringAssert.Contains(info[0].Message, exception1.ToString());
            StringAssert.Contains(info[1].Message, replayMessage2);
            StringAssert.Contains(info[1].Message, exception2.ToString());
        }
Example #3
0
        public void LogMessage_ReplayedMessageSavedUnitilTheLimit()
        {
            string    replayMessage1 = "ReplayMessage1";
            Exception exception1     = new ArgumentException("Error");
            string    replayMessage2 = "ReplayMessage2";
            Exception exception2     = new NullReferenceException("Error");

            string suffix  = nameof(LogMessage_ReplayedMessageSavedUnitilTheLimit);
            int    eventId = 7;
            Mock <ILogEventSender> eventSourceMock = CreateEventSourceMock();

            Activity activity = CreateActivity(suffix);

            activity.Start();
            (ILogger logger, _) = LogMessage(eventSourceMock, logEventReplayer: CreateLogReplayer(2), eventId);
            logger.LogDebug(new DivideByZeroException(), "LostMessage");             // would be lost due overflow
            logger.LogDebug(exception1, replayMessage1);
            logger.LogDebug(exception2, replayMessage2);
            activity.Stop();

            eventSourceMock.Verify(s_logExpression, Times.Exactly(4));
            List <LogMessageInformation> info = activity.GetReplayableLogs().ToList();

            Assert.AreEqual(2, info.Count);
            StringAssert.Contains(info[0].Message, replayMessage1);
            StringAssert.Contains(info[0].Message, exception1.ToString());
            StringAssert.Contains(info[1].Message, replayMessage2);
            StringAssert.Contains(info[1].Message, exception2.ToString());
        }
Example #4
0
        public void TestConstructorWithZeroNumberOfCardsAndNullTopCard()
        {
            // ARRANGE
            IAxiom    axiom         = new Axiom();
            const int numberOfCards = 0;
            ICard     topCard       = new Card(Colour.Blue, Number.Five, axiom);

            // ACT
            ArgumentException argumentException = null;
            IRuleScore        ruleScore         = null;

            try
            {
                ruleScore = new RuleScore(
                    numberOfCards: numberOfCards,
                    topCard: topCard);
            }
            catch (ArgumentException ex)
            {
                argumentException = ex;
            }

            // ASSERT
            if (argumentException != null)
            {
                Console.WriteLine(argumentException.ToString());
            }

            Assert.IsNotNull(argumentException, "argumentException != null");
            Assert.IsNull(ruleScore, "ruleScore == null");
        }
Example #5
0
        private IEnumerator ProcessMatchResponse <JSONRESPONSE, USERRESPONSEDELEGATETYPE>(UnityWebRequest client, NetworkMatch.InternalResponseDelegate <JSONRESPONSE, USERRESPONSEDELEGATETYPE> internalCallback, USERRESPONSEDELEGATETYPE userCallback) where JSONRESPONSE : Response, new()
        {
            yield return(client.SendWebRequest());

            JSONRESPONSE jSONRESPONSE = Activator.CreateInstance <JSONRESPONSE>();
            bool         flag         = client.result == UnityWebRequest.Result.Success;

            if (flag)
            {
                try
                {
                    JsonUtility.FromJsonOverwrite(client.downloadHandler.text, jSONRESPONSE);
                }
                catch (ArgumentException ex2)
                {
                    ArgumentException ex = ex2;
                    jSONRESPONSE.SetFailure(UnityString.Format("ArgumentException:[{0}] ", new object[]
                    {
                        ex.ToString()
                    }));
                }
            }
            else
            {
                jSONRESPONSE.SetFailure(UnityString.Format("Request error:[{0}] Raw response:[{1}]", new object[]
                {
                    client.error,
                    client.downloadHandler.text
                }));
            }
            client.Dispose();
            internalCallback(jSONRESPONSE, userCallback);
            yield break;
        }
Example #6
0
        public void TestConstructorWithEmptyListOfCardsThrowsException()
        {
            // ARRANGE
            IList <ICard> cards = new List <ICard>();

            // ACT
            ArgumentException argumentException = null;
            IPalette          palette           = null;

            try
            {
                palette = new Palette(cards);
            }
            catch (ArgumentException ex)
            {
                argumentException = ex;
            }

            // ASSERT
            if (argumentException != null)
            {
                Console.WriteLine(argumentException.ToString());
            }

            Assert.IsNotNull(argumentException);
            Assert.IsNull(palette);
        }
        public async Task <IActionResult> Create([FromBody] DishType dish)
        {
            if (dish.Name == null)
            {
                var ex = new ArgumentException($"{nameof(dish)} can`t be null");
                _logger.LogError(ex.ToString());
                throw ex;
            }

            if (!_validator.Validate(dish).IsValid)
            {
                var ex = new ArgumentException($"{nameof(dish)} is not valid");
                _logger.LogError(ex.ToString());
                throw ex;
            }

            try
            {
                _dishTypeRepository.Add(dish);
                await _unitOfWork.SaveChangesAsync();

                return(Ok(dish));
            }
            catch (Exception ex)
            {
                ex.Data["dish"] = dish;
                _logger.LogError(ex.ToString());
                throw ex;
            }
        }
Example #8
0
        public void TestAddDuplicateCardThrowsAnException()
        {
            // ARRANGE
            IAxiom        axiom = new Axiom();
            IList <ICard> cards = new List <ICard>
            {
                new Card(Colour.Orange, Number.Three, axiom),
                new Card(Colour.Blue, Number.Seven, axiom),
                new Card(Colour.Red, Number.One, axiom)
            };
            ICard    duplicateCard = new Card(Colour.Orange, Number.Three, axiom);
            IPalette palette       = new Palette(cards);

            // ACT
            ArgumentException argumentException = null;

            try
            {
                palette.AddCard(duplicateCard);
            }
            catch (ArgumentException ex)
            {
                argumentException = ex;
            }

            // ASSERT
            if (argumentException != null)
            {
                Console.WriteLine(argumentException.ToString());
            }

            Assert.IsNotNull(argumentException, "Expected exception not thrown");
        }
Example #9
0
        public void ShowError_WhenArgumentIsRemoteInvocationExceptionForOtherException_ShowsError()
        {
            var remoteException = new ArgumentException(message: "a", new DivideByZeroException(message: "b"));
            var remoteError     = RemoteErrorUtility.ToRemoteError(remoteException);
            var exception       = new RemoteInvocationException(
                message: "c",
                errorCode: 0,
                errorData: null,
                deserializedErrorData: remoteError);
            var defaultLogger = new Mock <INuGetUILogger>();
            var projectLogger = new Mock <INuGetUILogger>();

            defaultLogger.Setup(
                x => x.ReportError(
                    It.Is <ILogMessage>(logMessage => ReferenceEquals(logMessage, remoteError.LogMessage))));
            projectLogger.Setup(
                x => x.Log(
                    It.Is <MessageLevel>(level => level == MessageLevel.Error),
                    It.Is <string>(message => message == remoteException.ToString())));

            using (NuGetUI ui = CreateNuGetUI(defaultLogger.Object, projectLogger.Object))
            {
                ui.ShowError(exception);

                defaultLogger.VerifyAll();
                projectLogger.VerifyAll();
            }
        }
Example #10
0
        /// <summary>
        /// Trains a model using SAR.
        /// </summary>
        /// <param name="settings">The training settings</param>
        /// <param name="usageEvents">The usage events to use for training</param>
        /// <param name="catalogItems">The catalog items to use for training</param>
        /// <param name="uniqueUsersCount">The number of users in the user id index file.</param>
        /// <param name="uniqueUsageItemsCount">The number of usage items in the item id index file</param>
        /// <param name="cancellationToken">A cancellation token</param>
        public IPredictorModel Train(ITrainingSettings settings,
                                     IList <SarUsageEvent> usageEvents,
                                     IList <SarCatalogItem> catalogItems,
                                     int uniqueUsersCount,
                                     int uniqueUsageItemsCount,
                                     CancellationToken cancellationToken)
        {
            if (settings == null)
            {
                throw new ArgumentNullException(nameof(settings));
            }

            if (usageEvents == null)
            {
                throw new ArgumentNullException(nameof(usageEvents));
            }

            if (settings.EnableColdItemPlacement && catalogItems == null)
            {
                throw new ArgumentNullException(nameof(catalogItems));
            }

            if (uniqueUsersCount < 0)
            {
                var exception = new ArgumentException($"{nameof(uniqueUsersCount)} must be a positive integer");
                _tracer.TraceWarning(exception.ToString());
                throw exception;
            }

            if (uniqueUsageItemsCount < 0)
            {
                var exception = new ArgumentException($"{nameof(uniqueUsageItemsCount)} must be a positive integer");
                _tracer.TraceWarning(exception.ToString());
                throw exception;
            }

            cancellationToken.ThrowIfCancellationRequested();

            using (TlcEnvironment environment = new TlcEnvironment(verbose: true))
            {
                _detectedFeatureWeights = null;
                try
                {
                    environment.AddListener <ChannelMessage>(ChannelMessageListener);
                    IHost environmentHost = environment.Register("SarHost");

                    // bind the cancellation token to SAR cancellation
                    using (cancellationToken.Register(() => { environmentHost.StopExecution(); }))
                    {
                        _tracer.TraceInformation("Starting training model using SAR");
                        return(TrainModel(environmentHost, settings, usageEvents, catalogItems, uniqueUsersCount,
                                          uniqueUsageItemsCount));
                    }
                }
                finally
                {
                    environment.RemoveListener <ChannelMessage>(ChannelMessageListener);
                }
            }
        }
Example #11
0
        public async Task <IActionResult> CreateAsync([FromBody] GameConsoleType gameConsoleType)
        {
            if (gameConsoleType == null)
            {
                var ex = new ArgumentException($"{nameof(gameConsoleType)} can't be null");
                _logger.LogError(ex.ToString());
                throw ex;
            }

            if (!_validator.Validate(gameConsoleType).IsValid)
            {
                var ex = new ArgumentException($"{nameof(gameConsoleType)} is not valid");
                _logger.LogError(ex.ToString());
                throw ex;
            }

            try
            {
                _gameConsoleTypeRepository.Add(gameConsoleType);
                await _unitOfWork.SaveChangesAsync();

                return(Ok(gameConsoleType));
            }
            catch
            {
                var ex = new Exception($"Error while adding game console type nameof{nameof(gameConsoleType)}");
                _logger.LogError(ex.ToString());
                throw ex;
            }
        }
Example #12
0
        public async Task <IActionResult> RemoveById(int id)
        {
            if (id == default)
            {
                var ex = new ArgumentException($"{nameof(id)} cannot be 0");
                _logger.LogError(ex.ToString());
                throw ex;
            }

            try
            {
                var table = await _tableRepository.Get(x => x.Id == id);

                _tableRepository.Remove(table);
                await _unitOfWork.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                ex.Data["id"] = id;
                _logger.LogError(ex.ToString());
                throw ex;
            }

            return(Ok());
        }
Example #13
0
        public void TestConstructorWithPositiveNumberOfCardsAndNullTopCard()
        {
            // ARRANGE
            const int numberOfCards = 1;

            // ACT
            ArgumentException argumentException = null;
            IRuleScore        ruleScore         = null;

            try
            {
                ruleScore = new RuleScore(
                    numberOfCards: numberOfCards,
                    topCard: null);
            }
            catch (ArgumentException ex)
            {
                argumentException = ex;
            }

            // ASSERT
            if (argumentException != null)
            {
                Console.WriteLine(argumentException.ToString());
            }

            Assert.IsNotNull(argumentException, "argumentException != null");
            Assert.IsNull(ruleScore, "ruleScore == null");
        }
Example #14
0
        public async Task <IActionResult> CreateAsync([FromBody] Table table)
        {
            if (table == null)
            {
                var ex = new ArgumentException($"{nameof(table)} can't be null");
                _logger.LogError(ex.ToString());
                throw ex;
            }

            var validationResult = _validator.Validate(table);

            if (!validationResult.IsValid)
            {
                var ex = new ArgumentException($"{nameof(table)} is not valid");
                _logger.LogError(ex.ToString());
                throw ex;
            }

            try
            {
                _tableRepository.Add(table);
                await _unitOfWork.SaveChangesAsync();

                return(Ok(table));
            }
            catch
            {
                var ex = new Exception($"Error while adding table nameof{nameof(table)}");
                _logger.LogError(ex.ToString());
                throw ex;
            }
        }
        public async Task <IActionResult> CreateAsync([FromBody] OnlineTableReservation onlineTableReservation)
        {
            if (onlineTableReservation == null)
            {
                var ex = new ArgumentException($"{nameof(onlineTableReservation)} can't be null");
                _logger.LogError(ex.ToString());
                throw ex;
            }

            if (!_validator.Validate(onlineTableReservation).IsValid)
            {
                var ex = new ArgumentException($"{nameof(onlineTableReservation)} is not valid");
                _logger.LogError(ex.ToString());
                throw ex;
            }

            try
            {
                _onlineTableReservationRepository.Add(onlineTableReservation);
                await _unitOfWork.SaveChangesAsync();

                return(Ok(onlineTableReservation));
            }
            catch
            {
                var ex = new Exception($"Error while adding onlineTableReservation nameof{nameof(onlineTableReservation)}");
                _logger.LogError(ex.ToString());
                throw ex;
            }
        }
Example #16
0
        public async Task <IActionResult> CreateAsync([FromBody] Dish dish)
        {
            if (dish == null)
            {
                var ex = new ArgumentException($"{nameof(dish)} can't be null");
                _logger.LogError(ex.ToString());
                throw ex;
            }

            if (!_validator.Validate(dish).IsValid)
            {
                var ex = new ArgumentException($"{nameof(dish)} is not valid");
                _logger.LogError(ex.ToString());
                throw ex;
            }

            try
            {
                _dishRepository.Add(dish);
                await _unitOfWork.SaveChangesAsync();

                return(Ok(dish));
            }
            catch
            {
                var ex = new Exception($"Error while adding dish nameof{nameof(dish)}");
                _logger.LogError(ex.ToString());
                throw ex;
            }
        }
Example #17
0
        public static void ReAddSameNode_Throws()
        {
            var jValue = JsonValue.Create(1);

            var jObject = new JsonObject();
            jObject.Add("Prop", jValue);
            ArgumentException ex = Assert.Throws<ArgumentException>(() => jObject.Add("Prop", jValue));
            Assert.Contains("Prop", ex.ToString());
        }
Example #18
0
        /// <summary>
        /// ArgumentException	An argument to a method was invalid.
        /// </summary>
        /// <param name="ex"></param>
        /// <returns></returns>
        private static SqlMessage SqlException(ArgumentException ex)
        {
            SqlMessage meResul = new SqlMessage
            {
                Status            = sqlMessagerType.SystemError,
                Title             = ex.GetType().FullName,
                Message           = ex.Message,
                ExceptionMesseger = ex.ToString()
            };

            return(meResul);
        }
Example #19
0
        public async Task <IActionResult> UpdateById(int id, [FromBody] User user)
        {
            if (id == default)
            {
                var ex = new ArgumentException($"{nameof(id)} cannot be 0");
                _logger.LogError(ex.ToString());
                throw ex;
            }

            var validationResult = _validator.Validate(user);

            if (!validationResult.IsValid)
            {
                var ex = new ArgumentException($"{nameof(user)} is not valid");
                _logger.LogError(ex.ToString());
                throw ex;
            }

            try
            {
                var currentUser = await _userRepository.Get(x => x.Id == id);

                if (currentUser == null)
                {
                    var ex = new NullReferenceException($"Error while updating user. User with {nameof(id)}={id} not found");
                    _logger.LogError(ex.ToString());
                    throw ex;
                }

                currentUser.Name                  = user.Name;
                currentUser.PhoneNumber           = user.Name;
                currentUser.PhoneNumberConfirmed  = user.PhoneNumberConfirmed;
                currentUser.Email                 = user.Email;
                currentUser.EmailConfirmed        = user.PhoneNumberConfirmed;
                currentUser.PhoneNumber           = user.PhoneNumber;
                currentUser.PhoneNumberConfirmed  = user.PhoneNumberConfirmed;
                currentUser.BirthDate             = user.BirthDate;
                currentUser.GenderId              = user.GenderId;
                currentUser.CommunicationLanguage = user.CommunicationLanguage;
                currentUser.RoleId                = user.RoleId;

                _userRepository.Update(currentUser);
                await _unitOfWork.SaveChangesAsync();

                return(Ok(currentUser));
            }
            catch (Exception ex)
            {
                ex.Data["id"] = id;
                _logger.LogError(ex.ToString());
                throw ex;
            }
        }
Example #20
0
        public MofSpecificationSet(MofSpecification[] specifications)
        {
            this.ClassDeclarations = new Dictionary <string, ClassDeclaration>(StringComparer.OrdinalIgnoreCase);
            if (specifications != null)
            {
                this.m_specifications = specifications;
                MofSpecification[] mofSpecificationArray = specifications;
                for (int i = 0; i < (int)mofSpecificationArray.Length; i++)
                {
                    MofSpecification mofSpecification = mofSpecificationArray[i];
                    MofProduction[]  productions      = mofSpecification.Productions;
                    int num = 0;
                    while (num < (int)productions.Length)
                    {
                        MofProduction mofProduction       = productions[num];
                        MofProduction.ProductionType type = mofProduction.Type;
                        switch (type)
                        {
                        case MofProduction.ProductionType.ClassDeclaration:
                        {
                            ClassDeclaration classDeclaration = (ClassDeclaration)mofProduction;
                            try
                            {
                                this.ClassDeclarations.Add(classDeclaration.Name.FullName, classDeclaration);
                                num++;
                                continue;
                            }
                            catch (ArgumentException argumentException1)
                            {
                                ArgumentException argumentException = argumentException1;
                                argumentException.ToString();
                                throw new ParseFailureException(string.Concat("class ", classDeclaration.Name.FullName, " is already defined"), classDeclaration.Location);
                            }
                        }

                        case MofProduction.ProductionType.CompilerDirective:
                        case MofProduction.ProductionType.InstanceDeclaration:
                        {
                            num++;
                            continue;
                        }
                        }
                        throw new InvalidOperationException();
                    }
                }
                return;
            }
            else
            {
                throw new ArgumentException();
            }
        }
Example #21
0
        public async Task <IActionResult> UpdateById(int id, [FromBody] Employee employee)
        {
            if (id == default)
            {
                var ex = new ArgumentException($"{nameof(id)} cannot be 0");
                _logger.LogError(ex.ToString());
                throw ex;
            }

            var validationResult = _validator.Validate(employee);

            if (!validationResult.IsValid)
            {
                var ex = new ArgumentException($"{nameof(employee)} is not valid");
                _logger.LogError(ex.ToString());
                throw ex;
            }

            try
            {
                var currentEmployee = await _employeeRepository.Get(x => x.Id == id);

                if (currentEmployee == null)
                {
                    var ex = new NullReferenceException($"Error while updating employee. Employee with {nameof(id)}={id} not found");
                    _logger.LogError(ex.ToString());
                    throw ex;
                }

                currentEmployee.FirstName     = employee.FirstName;
                currentEmployee.LastName      = employee.LastName;
                currentEmployee.DepartamentId = employee.DepartamentId;
                currentEmployee.PhoneNumber   = employee.PhoneNumber;
                currentEmployee.PositionId    = employee.PositionId;
                currentEmployee.GenderId      = employee.GenderId;
                currentEmployee.BirthDate     = employee.BirthDate;

                _employeeRepository.Update(currentEmployee);
                await _unitOfWork.SaveChangesAsync();

                return(Ok(currentEmployee));
            }
            catch (Exception ex)
            {
                ex.Data["id"] = id;
                _logger.LogError(ex.ToString());
                throw ex;
            }
        }
Example #22
0
 private static void Main(string[] args)
 {
     if (args[0].ToLower() == UPDATE)
     {
         updateAll();
     }
     else if (args[0].ToLower() == OPEN_XML)
     {
         openXml();
     }
     else
     {
         var e = new ArgumentException(string.Format("Avaliable Args:\n{0}\n{1}", UPDATE, OPEN_XML));
         Console.Error.Write(e.ToString());
     }
 }
Example #23
0
        static void Main(string[] args)
        {
            Logger.Log("-----------------------------Application started!--------------------------------------");
            string inputFilePath;
            string outputFilePath;
            string outputType;

            if (args.Length < 1)
            {
                inputFilePath = @"Data\dane.csv";
            }
            else
            {
                Regex r = new Regex(@"^(([a-zA-Z]:)|(\))(\{1}|((\{1})[^\]([^/:*?<>""|]*))+)$");
                if (!r.IsMatch(args[0]))
                {
                    var exc = new ArgumentException("Podana ścieżka " + args[0] + " jest niepoprawna");
                    Logger.Log(exc.ToString());
                    throw exc;
                }
                else
                {
                    inputFilePath = args[0];
                }
            }
            if (args.Length < 2)
            {
                outputFilePath = @"Data\result.xml";
            }
            else
            {
                outputFilePath = args[1];
            }
            if (args.Length < 3)
            {
                outputType = "xml";
            }
            else
            {
                outputType = args[2];
            }
            var serializer = new Serializer();

            serializer.startSerialization(inputFilePath, outputFilePath, outputType);
            Logger.Log("Task Completed Successfully!");
        }
Example #24
0
        public async Task <IActionResult> UpdateById(int id, [FromBody] Table table)
        {
            if (id == default)
            {
                var ex = new ArgumentException($"{nameof(id)} cannot be 0");
                _logger.LogError(ex.ToString());
                throw ex;
            }

            var validationResult = _validator.Validate(table);

            if (!validationResult.IsValid)
            {
                var ex = new ArgumentException($"{nameof(table)} is not valid");
                _logger.LogError(ex.ToString());
                throw ex;
            }

            try
            {
                var currentTable = await _tableRepository.Get(x => x.Id == id);

                if (currentTable == null)
                {
                    var ex = new NullReferenceException($"Error while updating table. Table with {nameof(id)}={id} not found");
                    _logger.LogError(ex.ToString());
                    throw ex;
                }

                currentTable.Identifier      = table.Identifier;
                currentTable.DepartamentId   = table.DepartamentId;
                currentTable.SeatingCapacity = table.SeatingCapacity;
                currentTable.GameConsoleId   = table.GameConsoleId;

                _tableRepository.Update(currentTable);
                await _unitOfWork.SaveChangesAsync();

                return(Ok(currentTable));
            }
            catch (Exception ex)
            {
                ex.Data["id"] = id;
                _logger.LogError(ex.ToString());
                throw ex;
            }
        }
        public async Task <IActionResult> UpdateById(int id, [FromBody] Departament departament)
        {
            if (id == default)
            {
                var ex = new ArgumentException($"{nameof(id)} cannot be 0");
                _logger.LogError(ex.ToString());
                throw ex;
            }

            if (!_validator.Validate(departament).IsValid)
            {
                var ex = new ArgumentException($"{nameof(departament)} is not valid");
                _logger.LogError(ex.ToString());
                throw ex;
            }

            try
            {
                var currentDepartament = await _departamentRepository.Get(x => x.Id == id);

                if (currentDepartament == null)
                {
                    var ex = new NullReferenceException($"Error while updating departament. Departament with {nameof(id)}={id} not found");
                    _logger.LogError(ex.ToString());
                    throw ex;
                }

                currentDepartament.Name        = departament.Name;
                currentDepartament.Country     = departament.Country;
                currentDepartament.City        = departament.City;
                currentDepartament.Street      = departament.Street;
                currentDepartament.HouseNumber = departament.HouseNumber;

                _departamentRepository.Update(currentDepartament);
                await _unitOfWork.SaveChangesAsync();

                return(Ok(currentDepartament));
            }
            catch (Exception ex)
            {
                ex.Data["id"] = id;
                _logger.LogError(ex.ToString());
                throw ex;
            }
        }
Example #26
0
        public async Task <IActionResult> UpdateById(int id, [FromBody] Dish dish)
        {
            if (id == default)
            {
                var ex = new ArgumentException($"{nameof(id)} cannot be 0");
                _logger.LogError(ex.ToString());
                throw ex;
            }

            if (!_validator.Validate(dish).IsValid)
            {
                var ex = new ArgumentException($"{nameof(dish)} is not valid");
                _logger.LogError(ex.ToString());
                throw ex;
            }

            try
            {
                var currentDish = await _dishRepository.Get(x => x.Id == id);

                if (currentDish == null)
                {
                    var ex = new NullReferenceException($"Error while updating dish. Dish with {nameof(id)}={id} not found");
                    _logger.LogError(ex.ToString());
                    throw ex;
                }

                currentDish.Name        = dish.Name;
                currentDish.Price       = dish.Price;
                currentDish.Description = dish.Description;
                currentDish.TypeId      = dish.TypeId;
                currentDish.IsAvailable = dish.IsAvailable;

                _dishRepository.Update(currentDish);
                await _unitOfWork.SaveChangesAsync();

                return(Ok(currentDish));
            }
            catch (Exception ex)
            {
                ex.Data["id"] = id;
                _logger.LogError(ex.ToString());
                throw ex;
            }
        }
        public async Task <IActionResult> UpdateById(int id, [FromBody] OfflineTableReservation offlineTableReservation)
        {
            if (id == default)
            {
                var ex = new ArgumentException($"{nameof(id)} cannot be 0");
                _logger.LogError(ex.ToString());
                throw ex;
            }

            if (!_validator.Validate(offlineTableReservation).IsValid)
            {
                var ex = new ArgumentException($"{nameof(offlineTableReservation)} is not valid");
                _logger.LogError(ex.ToString());
                throw ex;
            }

            try
            {
                var currentOfflineTableReservation = await _offlineTableReservationRepository.Get(x => x.Id == id);

                if (currentOfflineTableReservation == null)
                {
                    var ex = new NullReferenceException($"Error while updating offline table rReservation. Offline table reservation with {nameof(id)}={id} not found");
                    _logger.LogError(ex.ToString());
                    throw ex;
                }

                currentOfflineTableReservation.TableId           = offlineTableReservation.TableId;
                currentOfflineTableReservation.ClientName        = offlineTableReservation.ClientName;
                currentOfflineTableReservation.ClientPhoneNumber = offlineTableReservation.ClientPhoneNumber;
                currentOfflineTableReservation.EmployeeId        = offlineTableReservation.EmployeeId;

                _offlineTableReservationRepository.Update(currentOfflineTableReservation);
                await _unitOfWork.SaveChangesAsync();

                return(Ok(currentOfflineTableReservation));
            }
            catch (Exception ex)
            {
                ex.Data["id"] = id;
                _logger.LogError(ex.ToString());
                throw ex;
            }
        }
Example #28
0
        public async Task <IActionResult> UpdateById(int id, [FromBody] Game game)
        {
            if (id == default)
            {
                var ex = new ArgumentException($"{nameof(id)} cannot be 0");
                _logger.LogError(ex.ToString());
                throw ex;
            }

            if (!_validator.Validate(game).IsValid)
            {
                var ex = new ArgumentException($"{nameof(game)} is not valid");
                _logger.LogError(ex.ToString());
                throw ex;
            }

            try
            {
                var currentGame = await _gameRepository.Get(x => x.Id == id);

                if (currentGame == null)
                {
                    var ex = new NullReferenceException($"Error while updating game. Game with {nameof(id)}={id} not found");
                    _logger.LogError(ex.ToString());
                    throw ex;
                }

                currentGame.Name             = game.Name;
                currentGame.Description      = game.Description;
                currentGame.LicenseBeginDate = game.LicenseBeginDate;
                currentGame.LicenseEndDate   = game.LicenseEndDate;

                _gameRepository.Update(currentGame);
                await _unitOfWork.SaveChangesAsync();

                return(Ok(currentGame));
            }
            catch (Exception ex)
            {
                ex.Data["id"] = id;
                _logger.LogError(ex.ToString());
                throw ex;
            }
        }
Example #29
0
        public void CreateEntityWithPropertiesShouldGenerateValidEntity()
        {
            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 messageTemplate = "Template {Temp} {Prop}";
            var template        = new MessageTemplateParser().Parse(messageTemplate);
            var properties      = new List <LogEventProperty> {
                new LogEventProperty("Temp", new ScalarValue("Temporary")),
                new LogEventProperty("Prop", new ScalarValue("Property"))
            };
            var additionalRowKeyPostfix = "Some postfix";

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

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

            // Partition key
            var expectedPartitionKey = "0" + new DateTime(logEvent.Timestamp.Year, logEvent.Timestamp.Month, logEvent.Timestamp.Day, logEvent.Timestamp.Hour, logEvent.Timestamp.Minute, 0).Ticks;

            Assert.AreEqual(expectedPartitionKey, entity.PartitionKey);

            // Row Key
            var expectedRowKeyWithoutGuid = "Information|Template {Temp} {Prop}|Some postfix|";
            var rowKeyWithoutGuid         = entity.RowKey.Substring(0, expectedRowKeyWithoutGuid.Length);
            var rowKeyGuid = entity.RowKey.Substring(expectedRowKeyWithoutGuid.Length);

            Assert.AreEqual(expectedRowKeyWithoutGuid, rowKeyWithoutGuid);
            Assert.DoesNotThrow(() => Guid.Parse(rowKeyGuid));
            Assert.AreEqual(Guid.Parse(rowKeyGuid).ToString(), rowKeyGuid);

            // Timestamp
            Assert.AreEqual(logEvent.Timestamp, entity.Timestamp);

            // Properties
            Assert.AreEqual(6, entity.Properties.Count);

            Assert.AreEqual(new EntityProperty(messageTemplate), entity.Properties["MessageTemplate"]);
            Assert.AreEqual(new EntityProperty("Information"), entity.Properties["Level"]);
            Assert.AreEqual(new EntityProperty("Template \"Temporary\" \"Property\""), entity.Properties["RenderedMessage"]);
            Assert.AreEqual(new EntityProperty(exception.ToString()), entity.Properties["Exception"]);
            Assert.AreEqual(new EntityProperty("Temporary"), entity.Properties["Temp"]);
            Assert.AreEqual(new EntityProperty("Property"), entity.Properties["Prop"]);
        }
Example #30
0
        public void SerializesTwoExceptions()
        {
            var exception1 = new InvalidOperationException("Some message 1");
            var exception2 = new ArgumentException("Some message 2");
            var errors     =
                new ErrorSerializer().Serialize(
                    new List <ApiError>()
            {
                new ApiError(exception1), new ApiError(exception2)
            })["errors"];

            Assert.Equal(exception1.Message, errors[0].Value <string>("title"));
            Assert.Equal(exception1.GetType().FullName, errors[0].Value <string>("code"));
            Assert.Equal(exception1.ToString(), errors[0].Value <string>("detail"));

            Assert.Equal(exception2.Message, errors[1].Value <string>("title"));
            Assert.Equal(exception2.GetType().FullName, errors[1].Value <string>("code"));
            Assert.Equal(exception2.ToString(), errors[1].Value <string>("detail"));
        }