Esempio n. 1
0
 void ILoggerService.LogError(string message)
 {
     logger.Error(message);
 }
Esempio n. 2
0
 public void OnException(ExceptionContext context)
 {
     _logger.Error(context.Exception, "Error from filter");
 }
        public static async Task Handle(DroppedSubscription subscription, Func <Task> compensatingAction)
        {
            var message     = subscription.ExceptionMessage;
            var retryPolicy = subscription.RetryPolicy;

            switch (subscription.DropReason)
            {
            case SubscriptionDropReason.UserInitiated:
                //the client called Close() on the subscription
                log.Info($@"Subscription to {subscription.StreamId} was closed by the client. 
                                {message}");
                break;

            case SubscriptionDropReason.NotAuthenticated:
                //the client is not authenticated -> check ACL
                log.Error($@"Subscription to {subscription.StreamId} was dropped because the client could not be authenticated. 
                                 Check the Access Control List. {message}");
                break;

            case SubscriptionDropReason.AccessDenied:
                //access to the stream was denied -> check ACL
                log.Error($@"Subscription to {subscription.StreamId} was dropped because the client was denied access. 
                                 Check the Access Control List. {message}");
                break;

            case SubscriptionDropReason.SubscribingError:
                //something went wrong while subscribing - retry
                log.Error($@"Subscription to {subscription.StreamId} failed. 
                                 {message}");
                await RetrySubscriptionAsync(compensatingAction, retryPolicy).ConfigureAwait(false);

                break;

            case SubscriptionDropReason.ServerError:
                //error on the server
                log.Error($@"A server error occurred which dropped the subscription to {subscription.StreamId}
                                {message}");
                break;

            case SubscriptionDropReason.ConnectionClosed:
                //the connection was closed - retry
                log.Error($@"Subscription to {subscription.StreamId} was dropped due to the connection being closed.
                                 {message}");
                await RetrySubscriptionAsync(compensatingAction, retryPolicy).ConfigureAwait(false);

                break;

            case SubscriptionDropReason.CatchUpError:
                //an error occurred during the catch-up phase - retry
                log.Error($@"Subscription to {subscription.StreamId} was dropped during the catch-up phase.
                                 {message}");
                await RetrySubscriptionAsync(compensatingAction, retryPolicy).ConfigureAwait(false);

                break;

            case SubscriptionDropReason.ProcessingQueueOverflow:
                //occurs when the number of events on the push buffer exceed the specified maximum - retry
                log.Warn($@"Subscription to {subscription.StreamId} was dropped due to a processing buffer overflow.
                                {message}");
                await RetrySubscriptionAsync(compensatingAction, retryPolicy).ConfigureAwait(false);

                break;

            case SubscriptionDropReason.EventHandlerException:
                //Subscription dropped because an exception was thrown by one of our handlers.
                log.Error($@"Subscription to {subscription.StreamId} was dropped in response to a handler exception.
                                 {message}");
                break;

            case SubscriptionDropReason.MaxSubscribersReached:
                //The maximum number of subscribers for the persistent subscription has been reached
                log.Error($@"Subscription to {subscription.StreamId} was dropped because the maximum no. of subscribers was reached.
                                 {message}");
                break;

            case SubscriptionDropReason.PersistentSubscriptionDeleted:
                //The persistent subscription has been deleted
                log.Error($@"The persistent subscription to {subscription.StreamId} was dropped because it was deleted.
                                 {message}");
                break;

            case SubscriptionDropReason.Unknown:
                //Scoobied
                log.Error($@"Subscription to {subscription.StreamId} was dropped for an unspecified reason.
                                 {message}");
                break;

            case SubscriptionDropReason.NotFound:
                //Target of persistent subscription was not found. Needs to be created first
                log.Error($@"The persistent subscription to {subscription.StreamId} could not be found. 
                                 {message}");
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(subscription.DropReason), subscription.DropReason, null);
            }
        }
Esempio n. 4
0
 void ILogger <T> .LogError(string message, Exception ex)
 {
     _logger.Error(ex, message);
 }
Esempio n. 5
0
        static void Main(string[] args)
        {
            using (StoreApplicationContext dbContext = CreateDbContext())
                using (IStoreRepository storeRepository = new StoreRepository(dbContext))
                {
                    while (true)
                    {
                        try
                        {
                            _logger.Info($"Saving");
                            storeRepository.Save();
                        }
                        catch (DbUpdateException ex)
                        {
                            _logger.Error($"Failed to Save");
                            Console.WriteLine(ex.Message);
                        }

                        Console.WriteLine();
                        Console.WriteLine("1:\tDisplay All Names");
                        Console.WriteLine("2:\tSearch By Last Name");
                        Console.WriteLine("3:\tDisplay Order History of each location");
                        Console.WriteLine("4:\tQuit");
                        Console.WriteLine();

                        int                              input = IntValidation(1, 4);
                        string                           input2;
                        var                              count = 0;
                        Customer                         customer;
                        Product                          ProductValue;
                        var                              products  = storeRepository.DisplayProducts();
                        var                              products2 = products.ToList();
                        List <OrderDetails>              orderDetails;
                        IEnumerable <Order>              OrderValue;
                        IEnumerable <Customer>           AllNames;
                        IEnumerable <Inventories>        LocationInventory;
                        IEnumerable <ProductCat>         prodCategories;
                        IEnumerable <Product>            getRecoProduct;
                        IEnumerable <ComponentInventory> componentInventories;
                        List <Product>                   Cart;
                        List <Product>                   ComponentCart;
                        decimal                          Total = 0;
                        int                              tempOrderId;
                        Dictionary <string, int>         HashProducts;
                        HashSet <Product>                HashLoop;
                        int                              inventoryId;
                        switch (input)
                        {
                        case 1:
                            AllNames = storeRepository.GetNames();
                            Console.WriteLine();
                            count = 0;
                            _logger.Info($"Choosing Customer to Order for");
                            foreach (var x in AllNames)
                            {
                                Console.WriteLine($"\t{count}: {x.GetFullName()}");
                                count++;
                            }

                            if (count == 0)
                            {
                                Console.WriteLine("There are 0 Customers");
                                break;
                            }
                            var AllNamesList = AllNames.ToList();

                            Console.WriteLine($"Choose Customer to interact with or Press {AllNames.Count()} to go back");

                            input = IntValidation(0, AllNames.Count());
                            if (input != AllNames.Count())
                            {
                                customer   = AllNames.ElementAt(input);
                                OrderValue = storeRepository.GetOrders(customer);

                                _logger.Info($"Displaying orders for {customer.FName} {customer.LName} {customer.CustomerId}");
                                List <OrderDetails> temp2 = new List <OrderDetails>();
                                while (true)
                                {
                                    Console.WriteLine();
                                    Console.WriteLine("Do you want to view and sort Customer Order History?");
                                    Console.WriteLine("1:\tYes");
                                    Console.WriteLine("2:\tNo");
                                    Console.WriteLine();
                                    input = IntValidation(1, 2);
                                    if (input == 2)
                                    {
                                        break;
                                    }

                                    Console.WriteLine();
                                    Console.WriteLine("What do you want to sort by?");
                                    Console.WriteLine("1:\tEarliest");
                                    Console.WriteLine("2:\tLatest");
                                    Console.WriteLine("3:\tCheapest");
                                    Console.WriteLine("4:\tExpensive");
                                    Console.WriteLine();
                                    input = IntValidation(1, 4);
                                    List <Order> orderList = OrderValue.ToList();
                                    if (input == 1)
                                    {
                                        orderList = Order.SortList(orderList, Sort.Early);
                                    }
                                    else if (input == 2)
                                    {
                                        orderList = Order.SortList(orderList, Sort.Late);
                                    }
                                    else if (input == 3)
                                    {
                                        orderList = Order.SortList(orderList, Sort.Cheap);
                                    }
                                    else if (input == 4)
                                    {
                                        orderList = Order.SortList(orderList, Sort.Expensive);
                                    }
                                    count = 0;
                                    foreach (var x in orderList)
                                    {
                                        Console.WriteLine();
                                        Console.WriteLine($"Order {count}:\tTime:{x.TimeStamp}  \nStore: {x.Location.Name}\tCost: ${x.TotalAmount}");
                                        orderDetails = storeRepository.GetOrderDetails(x).ToList();
                                        temp2.AddRange(orderDetails);
                                        var y = orderDetails;
                                        foreach (var z in y)
                                        {
                                            var i = Order.GetProductName(products.ToList(), z.ProductId);
                                            Console.WriteLine($"\t{i}\tAmount:{z.Quantity} ");
                                        }
                                        count++;
                                    }
                                }
                                Cart = new List <Product>();

                                LocationInventory = storeRepository.GetInventories(customer);
                                List <Inventories> LocationInventoryList = LocationInventory.ToList();
                                Total = 0;
                                while (true)
                                {
                                    count    = 4;
                                    products = storeRepository.DisplayProducts();
                                    Console.WriteLine();
                                    foreach (var x in products)
                                    {
                                        if (count % 3 == 0)
                                        {
                                            Console.WriteLine($"\t{count - 4}: {x.ProductCost}  {x.ProductName}\t\t ");
                                        }
                                        else
                                        {
                                            Console.Write($"\t{count - 4}: {x.ProductCost}  {x.ProductName}\t\t ");
                                        }
                                        count++;
                                    }
                                    _logger.Info($"Get Recommended Items");
                                    Product product = new Product();

                                    List <Product> tempP     = new List <Product>();
                                    List <Order>   orderList = OrderValue.ToList();
                                    foreach (var x in orderList)
                                    {
                                        var y = storeRepository.GetOrderDetails(x).ToList();
                                        foreach (var z in y)
                                        {
                                            foreach (var t in products)
                                            {
                                                if (t.ProductId == z.ProductId)
                                                {
                                                    tempP.Add(t);
                                                }
                                            }
                                        }
                                        count++;
                                    }

                                    Console.WriteLine();
                                    Console.WriteLine();
                                    Console.WriteLine("Recommended Items:\n");
                                    var getStuff = dbContext.Products.Where(x => x.ProductCategoryId == tempP[tempP.Count - 1].CategoryId).ToList();
                                    count = 0;
                                    foreach (var x in getStuff)
                                    {
                                        if (count > 2)
                                        {
                                            break;
                                        }
                                        Console.Write($"   {x.ProductName}");
                                        count++;
                                    }

                                    Console.WriteLine();
                                    Console.WriteLine();
                                    Console.WriteLine();
                                    Console.WriteLine($"Add Product to cart or Enter {products.Count()} to purchase it\n");
                                    Console.WriteLine($"Purchasing from Default Location: {customer.DefaultLocation.Name}");
                                    Console.WriteLine($"There are {Cart.Count} Items in cart for a total of ${Total}");
                                    input = IntValidation(0, products.Count());
                                    _logger.Info($"Choose item to add to cart");
                                    if (input != products.Count())
                                    {
                                        ProductValue = products.ElementAt(input);
                                        _logger.Info($"Item chosen = {ProductValue.ProductName}");
                                        if (ProductValue.HasComponents)
                                        {
                                            componentInventories = storeRepository.GetComponents(ProductValue);
                                            ComponentCart        = new List <Product>();
                                            foreach (var x in componentInventories)
                                            {
                                                foreach (var y in products2)
                                                {
                                                    if (x.ComponentProductId == y.ProductId)
                                                    {
                                                        ComponentCart.Add(y);
                                                    }
                                                }
                                            }
                                            List <Inventories> tempInv = new List <Inventories>();
                                            tempInv.AddRange(LocationInventoryList);
                                            Decimal        tempTotal = Total;
                                            List <Product> tempCart  = new List <Product>();
                                            tempCart.AddRange(Cart);

                                            foreach (var x in ComponentCart)
                                            {
                                                if (Order.CheckCart(x, LocationInventoryList))
                                                {
                                                    Console.WriteLine($"\t{x.ProductName} has been added to cart");
                                                    Total += x.ProductCost;
                                                    Cart.Add(x);
                                                }
                                                else
                                                {
                                                    LocationInventoryList.Clear();
                                                    LocationInventoryList.AddRange(tempInv);
                                                    Cart.Clear();
                                                    Cart.AddRange(tempCart);
                                                    Total = tempTotal;

                                                    Console.WriteLine();
                                                    Console.WriteLine("Inventory is out");

                                                    break;
                                                }
                                            }
                                        }
                                        else
                                        {
                                            if (Order.CheckCart(ProductValue, LocationInventoryList))
                                            {
                                                Console.WriteLine($"\t{ProductValue.ProductName} has been added to cart");
                                                Total += ProductValue.ProductCost;
                                                Cart.Add(ProductValue);
                                            }
                                            else
                                            {
                                                Console.WriteLine();
                                                Console.WriteLine("Inventory is out");
                                            }
                                        }
                                    }
                                    else
                                    {
                                        if (Cart.Count == 0)
                                        {
                                            Console.WriteLine();
                                            Console.WriteLine("The cart is empty, so nothing was purchased!");
                                            Console.WriteLine();
                                            break;
                                        }
                                        else
                                        {
                                            //SA.Orders(ConsumerId,StoreId,TotalAmount)
                                            Order newOrder = new Order
                                            {
                                                CustomerId  = customer.CustomerId,
                                                StoreId     = customer.DefaultLocation.LocationId,
                                                TotalAmount = Total,
                                                Location    = customer.DefaultLocation,
                                                Customer    = customer,
                                                TimeStamp   = DateTime.Now,
                                            };
                                            storeRepository.AddOrder(newOrder, customer.DefaultLocation, customer);
                                            try
                                            {
                                                _logger.Info($"Saving");
                                                storeRepository.Save();
                                            }
                                            catch (DbUpdateException ex)
                                            {
                                                _logger.Error($"Failed to Save");
                                                Console.WriteLine(ex.Message);
                                            }
                                            Thread.Sleep(50);
                                            tempOrderId  = dbContext.Orders.OrderByDescending(y => y.OrderId).Select(a => a.OrderId).FirstOrDefault();
                                            HashProducts = new Dictionary <string, int>();
                                            HashLoop     = new HashSet <Product>();
                                            foreach (var x in Cart)
                                            {
                                                if (HashProducts.ContainsKey(x.ProductName))
                                                {
                                                    HashProducts[x.ProductName] += 1;
                                                }
                                                else
                                                {
                                                    HashProducts.Add(x.ProductName, 1);
                                                }
                                                HashLoop.Add(x);
                                            }
                                            count = 0;
                                            foreach (var x in HashLoop)
                                            {
                                                count++;
                                                Console.WriteLine(count);
                                                OrderDetails newOrderDetails = new OrderDetails
                                                {
                                                    OrderId   = tempOrderId,
                                                    ProductId = x.ProductId,
                                                    Quantity  = HashProducts[x.ProductName],
                                                };

                                                storeRepository.AddOrderDetails(newOrderDetails, newOrder, x);
                                                try
                                                {
                                                    _logger.Info($"Saving");
                                                    storeRepository.Save();
                                                }
                                                catch (DbUpdateException ex)
                                                {
                                                    _logger.Error($"Failed to Save");
                                                    Console.WriteLine(ex.Message);
                                                }
                                                inventoryId = dbContext.Inventory.Where(y => y.ProductId == x.ProductId && y.StoreId == customer.DefaultLocation.LocationId).Select(a => a.InventoryId).First();
                                                Thread.Sleep(50);
                                                Inventories inventories = new Inventories
                                                {
                                                    Quantity    = Order.getInventory(LocationInventoryList, x.ProductId),
                                                    StoreId     = customer.DefaultLocation.LocationId,
                                                    ProductId   = x.ProductId,
                                                    InventoryId = inventoryId,
                                                };
                                                storeRepository.UpdateInventory(inventories);
                                                try
                                                {
                                                    _logger.Info($"Saving");
                                                    storeRepository.Save();
                                                }
                                                catch (DbUpdateException ex)
                                                {
                                                    _logger.Error($"Failed to Save");
                                                    Console.WriteLine(ex.Message);
                                                }
                                            }
                                        }
                                        break;
                                    }
                                }
                            }
                            break;

                        case 2:
                            _logger.Info($"Search for name name");
                            do
                            {
                                Console.WriteLine("Please enter Full/Parital Last Name to search by");
                                input2 = Console.ReadLine();
                                if (input2.Length < 200 && input2.Length > 0)
                                {
                                    break;
                                }
                                else
                                {
                                    Console.WriteLine("Please enter word with 1 - 199 characters, ");
                                }
                            } while (true);

                            AllNames = storeRepository.GetNames(input2);
                            Console.WriteLine();
                            count = 0;

                            foreach (var x in AllNames)
                            {
                                Console.WriteLine($"\t{count}: {x.GetFullName()}");
                                count++;
                            }
                            if (count == 0)
                            {
                                Console.WriteLine("Your search had 0 results");
                            }
                            break;

                        case 3:
                            _logger.Info($"Display All orders by each location");
                            var n = storeRepository.GetOrders().ToList();
                            var p = n.OrderByDescending(k => k.Location.LocationId);


                            foreach (var a in p)
                            {
                                var    b    = dbContext.Consumer.ToList();
                                var    z    = dbContext.Store.ToList();
                                string name = "John Albert";
                                foreach (var m in z)
                                {
                                    if (m.Consumer.Where(c => c.ConsumerId == a.CustomerId).Select(x => x.ConsumerId).FirstOrDefault() == a.CustomerId)
                                    {
                                        name = m.Consumer.Where(c => c.ConsumerId == a.CustomerId).Select(x => x.Fname).FirstOrDefault() + " " + m.Consumer.Where(c => c.ConsumerId == a.CustomerId).Select(x => x.Lname).FirstOrDefault();
                                    }
                                }
                                Console.WriteLine($"{ a.Location.Name}");
                                Console.WriteLine($"\t{name}\t{a.TimeStamp}\t{a.TotalAmount}");
                                Console.WriteLine();
                            }
                            break;

                        case 4:
                            _logger.Info($"Exiting Application");
                            return;
                        }
                    }
                }
        }
Esempio n. 6
0
 public static void Error(string msg, Exception ex)
 {
     _logger.Error(ex, msg);
 }
        public async Task StartMenu()
        {
            while (true)
            {
                PrintMenu();
                int.TryParse(Console.ReadLine(), out int menuNumber);
                switch (menuNumber)
                {
                case (int)AdminsCarMenu.AllCar:
                {
                    ShowCars(await _carProcessing.GetAll());
                }
                break;

                case (int)AdminsCarMenu.AddCar:
                {
                    var       car          = CreateCar();
                    var       validResults = car.IsValid();
                    const int NoError      = 0;
                    if (validResults.Count() != NoError)
                    {
                        foreach (var result in validResults)
                        {
                            Console.WriteLine(result.ErrorMessage);
                        }
                    }
                    else
                    {
                        if (await _carProcessing.UniquenessCheck(car))
                        {
                            await _carProcessing.Add(car);

                            Console.WriteLine("Success");
                        }
                        else
                        {
                            Console.WriteLine("This car is already on the list");
                        }
                    }
                    Console.ReadKey();
                }
                break;

                case (int)AdminsCarMenu.DeleteCar:
                {
                    Console.WriteLine("Enter car id");
                    try
                    {
                        await _carProcessing.Delete(ConsoleHelper.EnterNumber());

                        Console.WriteLine("Delete is sucessfull");
                    }
                    catch (DbException exception)
                    {
                        _logger.Error($"Failed to remove:{exception.Message}");
                        Console.WriteLine("Failed to remove the car");
                    }
                    catch (Exception exception)
                    {
                        _logger.Error($"Delete error:{exception.Message}");
                        Console.WriteLine("Delete error");
                    }

                    Console.ReadKey();
                }
                break;

                case (int)AdminsCarMenu.UpdateCar:
                {
                }
                break;

                case (int)AdminsCarMenu.OnRepair:
                {
                    ShowCars(await _carProcessing.GetCarOnRepair());
                }
                break;

                case (int)AdminsCarMenu.Find:
                {
                    try
                    {
                        var car = await _carProcessing.FindByGovernmentNumber(Console.ReadLine());

                        Console.WriteLine("Goverment number | Model | Color | Registration number | Year of issue | Is repair");
                        Console.WriteLine($"{car.GovernmentNumber} | {car.Model} | {car.Color} | {car.RegistrationNumber} | {car.YearOfIssue} | {car.IsRepair}");
                    }
                    catch (Exception exception)
                    {
                        _logger.Error($"Not found:{exception.Message}");
                        Console.WriteLine("Car is not find");
                    }

                    Console.ReadKey();
                }
                break;

                case (int)AdminsCarMenu.OldCars:
                {
                    Console.Clear();
                    Console.WriteLine("Max age:");
                    ShowCars(await _carProcessing.GetOldCars(ConsoleHelper.EnterNumber()));
                }
                break;

                case (int)AdminsCarMenu.AdminMenu:
                {
                    return;
                }

                default:
                {
                    Console.Clear();
                    Console.WriteLine("Incorrect number");
                }
                break;
                }
            }
        }
Esempio n. 8
0
 public void Error(string msg)
 {
     _log.Error(msg);
 }
Esempio n. 9
0
        public async Task <UserType> DoAction(string RoleARN)
        {
            try
            {
                var creds        = SharedLibrary.Utilities.AssumeRole(RoleARN, RegionEndpoint.USEast1);
                var sessionCreds = new SessionAWSCredentials(creds.AccessKeyId, creds.SecretAccessKey, creds.SessionToken);

                Amazon.IdentityManagement.AmazonIdentityManagementServiceClient client = new Amazon.IdentityManagement.AmazonIdentityManagementServiceClient(sessionCreds);

                GetUserResponse getUserResult;
                bool            userFound = false;
                try
                {
                    getUserResult = await client.GetUserAsync(new GetUserRequest { UserName = Username });

                    userFound = getUserResult.User != null;
                }
                catch { }

                var newPassword = Utilities.RandomString(8);

                if (userFound)
                {
                    try
                    {
                        var getLoginProfileResult = await client.GetLoginProfileAsync(new GetLoginProfileRequest { UserName = Username });

                        if (getLoginProfileResult.LoginProfile != null)
                        {
                            var deleteLoginProfileResult = await client.DeleteLoginProfileAsync(new DeleteLoginProfileRequest { UserName = Username });
                        }
                    }
                    catch (Exception ex)
                    {
                        logger.Debug(ex.Message);
                    }
                    var listAccessKeysResult = client.ListAccessKeysAsync(new ListAccessKeysRequest {
                        UserName = Username
                    }).Result;

                    foreach (var accessKey in listAccessKeysResult.AccessKeyMetadata)
                    {
                        var deleteAccessKeyResult = client.DeleteAccessKeyAsync(new DeleteAccessKeyRequest {
                            AccessKeyId = accessKey.AccessKeyId, UserName = Username
                        }).Result;

                        if (deleteAccessKeyResult.HttpStatusCode == System.Net.HttpStatusCode.OK)
                        {
                            logger.Debug($"Deleted access key {accessKey.AccessKeyId} for user {Username}");
                        }
                    }
                }
                else
                {
                    var createUserResult = await client.CreateUserAsync(new CreateUserRequest { UserName = Username });
                }

                var attachPolicyResult = await client.AttachUserPolicyAsync(new AttachUserPolicyRequest { PolicyArn = "arn:aws:iam::aws:policy/AdministratorAccess", UserName = Username });


                var createLoginProfileResult = await client.CreateLoginProfileAsync(new CreateLoginProfileRequest { Password = newPassword, UserName = Username, PasswordResetRequired = true });

                var createAccessKeyResult = await client.CreateAccessKeyAsync(new CreateAccessKeyRequest { UserName = Username });



                UserType uType = new UserType
                {
                    Username        = Username,
                    Password        = newPassword,
                    AccessKeyId     = createAccessKeyResult.AccessKey.AccessKeyId,
                    SecretAccessKey = createAccessKeyResult.AccessKey.SecretAccessKey
                };

                return(uType);
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
                throw;
            }
        }
Esempio n. 10
0
 public void LogError(string message, ExceptionModel exceptionModel)
 {
     logger.Error(message);
     _exceptionRepository.PostAsync(exceptionModel);
 }
 public void LogError(ApplicationException ex, string message)
 {
     logger?.Error(ex, message);
 }
        //public async Task<IActionResult> DownloadVideoAsync(int profileId)
        //{

        //    var result = await _fileService.DownloadVideoAsync(profileId);
        //    if (result.FileView != null)
        //    {
        //        ContentDisposition cd = new ContentDisposition
        //        {
        //            FileName = result.FileView.Name,
        //            Inline = true  // false = prompt the user for downloading;  true = browser to try to show the file inline
        //        };
        //        Response.Headers.Add("Content-Disposition", cd.ToString());
        //        Response.Headers.Add("X-Content-Type-Options", "nosniff");

        //        return File(result.FileView.FileBytes, result.FileView.MimeType);
        //    }

        //    return Ok(result);

        //}

        public async Task <IActionResult> DownloadVideoAsync(int profileId)
        {
            logger.Info($"{ GetType().Name}  {  ExtensionUtility.GetCurrentMethod() }  EndPoint : {_minIoConfig.EndPoint}");
            logger.Info($"{ GetType().Name}  {  ExtensionUtility.GetCurrentMethod() }  AccessKey : {_minIoConfig.AccessKey}");
            logger.Info($"{ GetType().Name}  {  ExtensionUtility.GetCurrentMethod() }  SecretKey : {_minIoConfig.SecretKey}");
            logger.Info($"{ GetType().Name}  {  ExtensionUtility.GetCurrentMethod() }  BucketName : {_minIoConfig.BucketName}");
            logger.Info($"{ GetType().Name}  {  ExtensionUtility.GetCurrentMethod() }  Location : {_minIoConfig.Location}");

            //var recommendLeader = await _appDbContext.RecommandLeaders.Where(x => x.ID == recommendId).FirstOrDefaultAsync();

            var profile = await _appDbContext.Profiles.FirstOrDefaultAsync(k => k.Id == profileId);

            int.TryParse(profile.ExpressYourselfUrl, out var fileId);

            var file = await _appDbContext.Files.FirstOrDefaultAsync(k => k.Id == fileId).ConfigureAwait(false);

            //if (recommendLeader.RecommendingAudioID != null)
            //{
            var fileGuiId = file.IdGuid.ToString();
            //  mimeType = "audio/mp3";
            //}

            var endpoint     = _minIoConfig.EndPoint;
            var accessKey    = _minIoConfig.AccessKey;
            var secretKey    = _minIoConfig.SecretKey;
            var minioForDev  = _minIoConfig.MinIoForDev;
            var fileLocation = _minIoConfig.FilePath;
            var bucketName   = _minIoConfig.BucketName;
            var location     = _minIoConfig.Location;

            var objectName = fileGuiId;

            if (!Directory.Exists(fileLocation))
            {
                Directory.CreateDirectory(fileLocation);
            }

            var filePath = fileLocation + objectName.ToString();

            try
            {
                if (minioForDev != true)
                {
                    var    minio = new MinioClient(endpoint, accessKey, secretKey).WithSSL();
                    Stream st    = new System.IO.MemoryStream();
                    await minio.GetObjectAsync(bucketName, objectName, fileLocation + objectName.ToString());

                    var fileStreamVal       = new FileStream(fileLocation + objectName.ToString(), FileMode.Open, FileAccess.Read);
                    FileStreamResult result = File(
                        fileStream: fileStreamVal,
                        contentType: file.MimeType,
                        enableRangeProcessing: true                        //<-- enable range requests processing
                        );
                    return(result);
                }
                else
                {
                    var    minio = new MinioClient(endpoint, accessKey, secretKey);
                    Stream st    = new System.IO.MemoryStream();
                    await minio.GetObjectAsync(bucketName, objectName, fileLocation + objectName.ToString());

                    var fileStreamVal       = new FileStream(fileLocation + objectName.ToString(), FileMode.Open, FileAccess.Read);
                    FileStreamResult result = File(
                        fileStream: fileStreamVal,
                        contentType: file.MimeType,
                        enableRangeProcessing: true                        //<-- enable range requests processing
                        );
                    return(result);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                return(NotFound());
            }
            finally
            {
                Response.OnCompleted(async() =>
                {
                    // Do some work here
                    if (System.IO.File.Exists(filePath))
                    {
                        System.IO.File.Delete(filePath);
                    }
                });
            }
        }
Esempio n. 13
0
 public static void Error(string title, Exception exception, [CallerMemberName] string methodName = "")
 {
     logger.Error(exception, $"{methodName}方法出现错误!");
 }
Esempio n. 14
0
 public void Error(string message, Exception ex = null)
 {
     _DefaultLogger.Error(message + Environment.NewLine + ex?.ToString());
 }
Esempio n. 15
0
 public void LogError(Exception exception, string message)
 {
     _logger.Error(exception, message);
 }
 private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
 {
     _logger = ViewModelLocator.Container.Resolve <ILogger>();
     _logger.Error(e.ExceptionObject as Exception, "Unhandled Exception");
 }
Esempio n. 17
0
        public async Task Connect()
        {
            int origin = Interlocked.Exchange(ref _state, _connecting);

            if (!(origin == _none || origin == _closed))
            {
                await Close(false); // connecting with wrong state

                throw new InvalidOperationException("This tcp socket client is in invalid state when connecting.");
            }

            Clean(); // force to clean

            try
            {
                _tcpClient = _localEndPoint != null ?
                             new TcpClient(_localEndPoint) :
                             new TcpClient(_remoteEndPoint.Address.AddressFamily);
                SetSocketOptions();

                var awaiter = _tcpClient.ConnectAsync(_remoteEndPoint.Address, _remoteEndPoint.Port);
                if (!awaiter.Wait(ConnectTimeout))
                {
                    await Close(false); // connect timeout

                    throw new TimeoutException(string.Format("Connect to [{0}] timeout [{1}].", _remoteEndPoint, ConnectTimeout));
                }

                var negotiator = NegotiateStream(_tcpClient.GetStream());
                if (!negotiator.Wait(ConnectTimeout))
                {
                    await Close(false); // ssl negotiation timeout

                    throw new TimeoutException(string.Format("Negotiate SSL/TSL with remote [{0}] timeout [{1}].", _remoteEndPoint, ConnectTimeout));
                }
                _stream = negotiator.Result;

                if (_receiveBuffer == default(ArraySegment <byte>))
                {
                    _receiveBuffer = _configuration.BufferManager.BorrowBuffer();
                }

                _receiveBufferOffset = 0;

                if (Interlocked.CompareExchange(ref _state, _connected, _connecting) != _connecting)
                {
                    await Close(false); // connected with wrong state

                    throw new InvalidOperationException("This tcp socket client is in invalid state when connected.");
                }

                _log.Debug("Connected to server [{0}] with dispatcher [{1}] on [{2}].",
                           this.RemoteEndPoint,
                           _dispatcher.GetType().Name,
                           DateTime.UtcNow.ToString(@"yyyy-MM-dd HH:mm:ss.fffffff"));

                bool isErrorOccurredInUserSide = false;
                try
                {
                    await _dispatcher.OnServerConnected(this);
                }
                catch (Exception ex) // catch all exceptions from out-side
                {
                    isErrorOccurredInUserSide = true;
                    await HandleUserSideError(ex);
                }

                if (!isErrorOccurredInUserSide)
                {
                    Task.Run(async() =>
                    {
                        await Process();
                    })
                    .Forget();
                }
                else
                {
                    await Close(true); // user side handle tcp connection error occurred
                }
            }
            catch (Exception ex) // catch exceptions then log then re-throw
            {
                _log.Error(ex);
                await Close(true); // handle tcp connection error occurred

                throw;
            }
        }
Esempio n. 18
0
 public void Error(string loggingMessage, [CallerMemberName] string memberName = "")
 {
     System.Diagnostics.Trace.WriteLine($"Error Message from {memberName}");
     _logger.Error(loggingMessage);
 }
Esempio n. 19
0
 public void LogException(Exception ex)
 {
     Logger.Error(ex);
 }
 public void PerformanceHelperError(string memo)
 {
     Instance.Error(memo);
 }
Esempio n. 21
0
 private static void LogException(Exception e)
 {
     logger.Error(e, "captured unhandled exception");
 }
Esempio n. 22
0
 public void Error(string message)
 => internalLogger.Error(message);
Esempio n. 23
0
 public void Error(string message)
 {
     _logger?.Error(message);
 }
Esempio n. 24
0
        internal async Task Start()
        {
            //TODO 여기서 read 뿐만 아닌 Send까지 하도록 해야 한다.
            int origin = Interlocked.CompareExchange(ref _state, _connecting, _none);

            if (origin == _disposed)
            {
                throw new ObjectDisposedException("This tcp socket session has been disposed when connecting.");
            }
            else if (origin != _none)
            {
                throw new InvalidOperationException("This tcp socket session is in invalid state when connecting.");
            }

            try
            {
                var negotiator = NegotiateStream(_tcpClient.GetStream());
                if (!negotiator.Wait(ConnectTimeout))
                {
                    await Close(false); // ssl negotiation timeout

                    throw new TimeoutException(string.Format(
                                                   "Negotiate SSL/TSL with remote [{0}] timeout [{1}].", this.RemoteEndPoint, ConnectTimeout));
                }
                _stream = negotiator.Result;

                if (_receiveBuffer == default(ArraySegment <byte>))
                {
                    _receiveBuffer = _bufferManager.BorrowBuffer();
                }
                _receiveBufferOffset = 0;

                if (Interlocked.CompareExchange(ref _state, _connected, _connecting) != _connecting)
                {
                    await Close(false); // connected with wrong state

                    throw new ObjectDisposedException("This tcp socket session has been disposed after connected.");
                }

                _log.Debug("Session started for [{0}] on [{1}] in dispatcher [{2}] with session count [{3}].",
                           this.RemoteEndPoint,
                           this.StartTime.ToString(@"yyyy-MM-dd HH:mm:ss.fffffff"),
                           _dispatcher.GetType().Name,
                           this.Server.SessionCount);

                bool isErrorOccurredInUserSide = false;
                try
                {
                    await _dispatcher.OnSessionStarted(this);
                }
                catch (Exception ex) // catch all exceptions from out-side
                {
                    isErrorOccurredInUserSide = true;
                    await HandleUserSideError(ex);
                }

                if (!isErrorOccurredInUserSide)
                {
                    await Process();
                }
                else
                {
                    await Close(true); // user side handle tcp connection error occurred
                }
            }
            catch (Exception ex) // catch exceptions then log then re-throw
            {
                _log.Error(string.Format("Session [{0}] exception occurred, [{1}].", this, ex.Message));
                await Close(true); // handle tcp connection error occurred

                throw;
            }
        }
Esempio n. 25
0
 public void Error(Exception exp)
 {
     logger.Error(exp);
 }
        public async Task StartMenu()
        {
            while (true)
            {
                PrintMenu();
                int.TryParse(Console.ReadLine(), out int menuNumber);
                switch (menuNumber)
                {
                case (int)AdminsDriverMenu.AllDriver:
                {
                    ShowDrivers(await _driverProcessing.GetAll());
                }
                break;

                case (int)AdminsDriverMenu.AddDriver:
                {
                    var       driver       = CreateDriver();
                    var       validResults = driver.IsValid();
                    const int NoError      = 0;
                    if (validResults.Count() != NoError)
                    {
                        foreach (var result in validResults)
                        {
                            Console.WriteLine(result.ErrorMessage);
                        }
                    }
                    else
                    {
                        if (await _driverProcessing.UniquenessCheck(driver))
                        {
                            await _driverProcessing.Add(driver);

                            Console.WriteLine("Success");
                        }
                        else
                        {
                            Console.WriteLine("This driver is already on the list");
                        }
                    }
                    Console.ReadKey();
                }
                break;

                case (int)AdminsDriverMenu.DeleteDriver:
                {
                    Console.WriteLine("Enter driver id");

                    try
                    {
                        await _driverProcessing.Delete(ConsoleHelper.EnterNumber());

                        Console.WriteLine("Delete is sucessfull");
                    }
                    catch (NullReferenceException exception)
                    {
                        _logger.Error($"Not found:{exception.Message}");
                        Console.WriteLine("Driver is not find");
                    }
                    catch (DbException exception)
                    {
                        _logger.Error($"Failed to remove:{exception.Message}");
                        Console.WriteLine("Find error");
                    }

                    Console.ReadKey();
                }
                break;

                case (int)AdminsDriverMenu.UpdateDriver:
                {
                }
                break;

                case (int)AdminsDriverMenu.Find:
                {
                    Console.Clear();
                    Console.WriteLine("Enter licence number:");
                    var driver = await _driverProcessing.FindByDriverLicenseNumber(Console.ReadLine());

                    if (driver == null)
                    {
                        Console.WriteLine("Licence number not find");
                    }
                    else
                    {
                        Console.WriteLine($"Surname | Name | Patronymic | Call sign | DriverLicenseNumber | Date of issue of drivers license | Is on holiday | Is sick leave");
                        Console.WriteLine($"{driver.Surname} | {driver.Name} | {driver.Patronymic} | {driver.CallSign} | {driver.DriverLicenseNumber} | {driver.DateOfIssueOfDriversLicense} | {driver.IsOnHoliday} | {driver.IsSickLeave}");
                    }
                    Console.ReadKey();
                }
                break;

                case (int)AdminsDriverMenu.GiveCar:
                {
                    Console.Clear();
                    Console.WriteLine("Enter car id");
                    var carId = ConsoleHelper.EnterNumber();
                    if (await _carProcessing.FindById(carId) != null)
                    {
                        Console.WriteLine("Enter driver id");
                        var driverId = ConsoleHelper.EnterNumber();
                        if (_driverProcessing.FindById(driverId) != null)
                        {
                            try
                            {
                                await _driverProcessing.GiveCar(driverId, carId);

                                Console.WriteLine("Sucessfull");
                            }
                            catch (DbUpdateException exception)
                            {
                                _logger.Error($"Update error:{exception.Message}");
                                Console.WriteLine("This car is use");
                            }
                            catch (Exception)
                            {
                                Console.WriteLine("Update error");
                            }
                        }
                        else
                        {
                            Console.WriteLine("Driver not find");
                        }
                    }
                    else
                    {
                        Console.WriteLine("Car not find");
                    }
                    Console.ReadKey();
                }
                break;

                case (int)AdminsDriverMenu.AdminMenu:
                {
                    return;
                }

                default:
                {
                    Console.Clear();
                    Console.WriteLine("Incorrect number");
                }
                break;
                }
            }
        }
Esempio n. 27
0
        public async Task StartMenu()
        {
            while (true)
            {
                PrintMenu();
                int.TryParse(Console.ReadLine(), out int menuNumber);
                switch (menuNumber)
                {
                case (int)AdminsOrderMenu.ShowAll:
                {
                    ShowOrders(await _orderProcessing.GetAll());
                }
                break;

                case (int)AdminsOrderMenu.ShowActive:
                {
                    ShowOrders(await _orderProcessing.GetActiveOrders());
                }
                break;

                case (int)AdminsOrderMenu.ShowInactive:
                {
                    ShowOrders(await _orderProcessing.GetInActiveOrders());
                }
                break;

                case (int)AdminsOrderMenu.Add:
                {
                    const int NoError      = 0;
                    var       order        = CreateOrder();
                    var       validResults = order.IsValid();
                    if (validResults.Count() != NoError)
                    {
                        foreach (var result in validResults)
                        {
                            Console.WriteLine(result.ErrorMessage);
                        }
                    }
                    else
                    {
                        try
                        {
                            await _orderProcessing.Add(order);

                            Console.WriteLine("Success");
                        }
                        catch (DbException exception)
                        {
                            _logger.Error($"Add error:{exception.Message}");
                            Console.WriteLine("Incorrect client id");
                        }
                        catch (Exception exception)
                        {
                            _logger.Error($"Add error:{exception.Message}");
                            Console.WriteLine("Adding error");
                        }
                        Console.ReadKey();
                    }
                }
                break;

                case (int)AdminsOrderMenu.AdminMenu:
                {
                    return;
                }

                default:
                {
                    Console.Clear();
                    Console.WriteLine("Incorrect number");
                }
                break;
                }
            }
        }
Esempio n. 28
0
 public void Error(string message, Exception exception) => _logger.Error(exception, message);
Esempio n. 29
0
 public void LogError(string message)
 {
     logger.Error(message);
 }
Esempio n. 30
0
 public virtual void Error(string message)
 {
     logger.Error(message);
 }