//Eager Loading (Immediate Execution)
        public JsonResult EagerLoading()
        {
            var context  = new OrdersContext();
            var products = context.Products.Include(x => x.Category).ToList();             //Immediate Execution

            //check SQL Profiler here
            var data = products.Select(x => new
            {
                x.ProductId,
                x.ProductName,
                Category = new
                {
                    x.Category.CategoryId,
                    x.Category.CategoryName
                }
            }).ToList();

            //check SQL Profiler here
            return(Json(data, JsonRequestBehavior.AllowGet));
        }
Esempio n. 2
0
 public void NoTracking()
 {
     new TestDefinition
     {
         TestName       = "Query_Simple_NoTracking_EF6",
         IterationCount = 100,
         WarmupCount    = 5,
         Setup          = EnsureDatabaseSetup,
         Run            = harness =>
         {
             using (var context = new OrdersContext(_connectionString))
             {
                 harness.StartCollection();
                 var result = context.Products.AsNoTracking().ToList();
                 harness.StopCollection();
                 Assert.Equal(1000, result.Count);
             }
         }
     }.RunTest();
 }
Esempio n. 3
0
        //private readonly IQueryable<object> _query;

        public Profile()
        {
            var connectionString
                = $@"{BenchmarkConfig.Instance.BenchmarkDatabase}Database=Perf_Query_Simple;";

            _context = new OrdersContext(connectionString);

            //_query = _context.Products.AsNoTracking().Where(p => p.Retail < 15);

            var product
                = (from p in _context.Products
                   from p2 in _context.Products
                   select new { p, p2 })
                  .Select(a => a.p.Name)
                  .OrderBy(n => n)
                  .AsNoTracking()
                  .First();

            //_query.Load();
        }
Esempio n. 4
0
        public async Task <Order> Get(Guid orderKey)
        {
            if (!this.State.Orders.ContainsKey(orderKey))
            {
                ActorEventSource.Current.ActorMessage(this, "Readthrough :(");
                using (OrdersContext db = new OrdersContext()) {
                    db.Configuration.ProxyCreationEnabled = false;

                    Order order = await db.Orders.FirstOrDefaultAsync(o => o.OrderKey == orderKey);

                    this.State.Orders[orderKey] = order;
                    return(order);
                }
            }
            else
            {
                ActorEventSource.Current.ActorMessage(this, "Saved round trip!, used state instead!");
                return(this.State.Orders[orderKey]);
            }
        }
        public static OrderDetail CreateOrderDetail(OrdersContext context, OrderHead order)
        {
            var orderDetail = new OrderDetail
            {
                LineNo          = 1,
                OrderId         = order.OrderId,
                ItemDescription = "Test Product",
                UnitPrice       = 100M,
                Quantity        = 2,
                Discount        = 0M,
                LineTotal       = 200M,
                CreateDate      = DateTime.Now,
                CreateUser      = order.CreateUser
            };

            order.OrderDetails.Add(orderDetail);
            context.SaveChanges();

            return(orderDetail);
        }
        public static Customer CreateCustomer(OrdersContext context, string customerName = "SMME", int companyProfileId = 0, string username = "******")
        {
            var customer = new Customer
            {
                CustomerName     = customerName,
                CompanyProfileId = companyProfileId,
                CustomerDetails  = "test details",
                AccountNo        = "DE232",
                ContactNo        = "0213435566",
                EmailAddress     = "*****@*****.**",
                MobileNo         = "0823334444",
                CreateDate       = DateTime.Now,
                CreateUser       = username
            };

            context.Customers.Add(customer);
            context.SaveChanges();

            return(customer);
        }
Esempio n. 7
0
        public static void Seed(this OrdersContext context)
        {
            context.Order.RemoveRange(context.Order);
            context.SaveChanges();
            context.Order.AddRange(new List <Order> {
                new Order {
                    OrderId = Guid.NewGuid(), RequestDate = DateTime.Now, PaymentDate = DateTime.Now, OrderStatusPagamento = "Pendente", NumberCartaoCredito = "9998666444333", Cvv = "176", NameCartaoCredito = "Andre Luiz", ValidadeDate = "02/2024"
                },
                new Order {
                    OrderId = Guid.NewGuid(), RequestDate = DateTime.Now, PaymentDate = DateTime.Now, OrderStatusPagamento = "Finalizado", NumberCartaoCredito = "99986688888", Cvv = "189", NameCartaoCredito = "Luiza Mel", ValidadeDate = "08/2028"
                },
                new Order {
                    OrderId = Guid.NewGuid(), RequestDate = DateTime.Now, PaymentDate = DateTime.Now, OrderStatusPagamento = "Pendente", NumberCartaoCredito = "9998666477777", Cvv = "112", NameCartaoCredito = "Rodrigo Santos", ValidadeDate = "04/2028"
                }
            });



            context.SaveChanges();
        }
Esempio n. 8
0
        //private readonly IQueryable<object> _query;

        public Profile()
        {
            var connectionString
                = $@"Server={BenchmarkConfig.Instance.BenchmarkDatabaseInstance};Database=Perf_Query_Simple;Integrated Security=True;MultipleActiveResultSets=true;";

            _context = new OrdersContext(connectionString);

            //_query = _context.Products.AsNoTracking().Where(p => p.Retail < 15);

            var product
                = (from p in _context.Products
                   from p2 in _context.Products
                   select new { p, p2 })
                  .Select(a => a.p.Name)
                  .OrderBy(n => n)
                  .AsNoTracking()
                  .First();

            //_query.Load();
        }
Esempio n. 9
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, OrdersContext dbcontext)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();



            app.UseRouting();



            app.UseAuthorization();



            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });



            ////dbcontext.Database.EnsureDeleted();
            //dbcontext.Database.EnsureCreated();



            ////new OrdersSeeder(dbcontext);
        }
        public static CompanyProfile CreateCompany(OrdersContext context, int orderNoSeed = 1)
        {
            var company = new CompanyProfile
            {
                CreateDate     = DateTime.Now,
                CreateUser     = "******",
                DisplayName    = "Test Company",
                EmailAddress   = "*****@*****.**",
                FaxNo          = "0219999999",
                LegalName      = "Test PTY LTD",
                OrderNoSeed    = orderNoSeed,
                RegistrationNo = "TestReg34324",
                TaxReferenceNo = "VAT3e982/01",
                TelephoneNo    = "0212923345"
            };

            context.CompanyProfiles.Add(company);
            context.SaveChanges();

            return(company);
        }
Esempio n. 11
0
        // GET: Orders
        public ActionResult Index()
        {
            using (OrdersContext context = new OrdersContext())

            {
                var orders = context
                             .SalesOrder
                             .Select(o => new ViewModelOrder
                {
                    Id        = o.Id,
                    Customer  = o.Customer.Name,
                    Status    = o.Status.Name,
                    Comment   = o.Comment,
                    OrderDate = o.OrderDate,
                    Total     = o.SalesOrderDetail.Sum(d => d.OrderQty * d.UnitPrice)
                })
                             .ToList();

                return(View(orders));
            }
        }
        public JsonResult ExplicitlyLoadingForSingleEntity()
        {
            var context = new OrdersContext();

            var product = context.Products.Find(1);

            context.Entry(product).Reference(p => p.Category).Load();

            var productDc = new ProductDC
            {
                ProductId   = product.ProductId,
                ProductName = product.ProductName,
                Category    = new CategoryDC()
                {
                    CategoryId   = product.Category.CategoryId,
                    CategoryName = product.Category.CategoryName
                }
            };

            return(Json(productDc, JsonRequestBehavior.AllowGet));
        }
Esempio n. 13
0
 public virtual void InitializeContext()
 {
     _context     = _fixture.CreateContext();
     _simpleQuery = _context.Products
                    .AsNoTracking();
     _complexQuery = _context.Products
                     .AsNoTracking()
                     .Where(p => p.Retail < 1000)
                     .OrderBy(p => p.Name).ThenBy(p => p.Retail)
                     .Select(
         p => new DTO
     {
         ProductId        = p.ProductId,
         Name             = p.Name,
         Description      = p.Description,
         ActualStockLevel = p.ActualStockLevel,
         SKU     = p.SKU,
         Savings = p.Retail - p.CurrentPrice,
         Surplus = p.ActualStockLevel - p.TargetStockLevel
     });
 }
        //Eager Loading: return a singleton value
        public JsonResult EagerLoadingSingletonValue()
        {
            var context = new OrdersContext();

            var supplier = context.Suppliers.Include(s => s.Products).First();

            //check SQL Profiler here
            var supplierDC = new SupplierDC
            {
                SupplierId  = supplier.SupplierId,
                CompanyName = supplier.CompanyName,
                Products    = supplier.Products.Select(p => new ProductDC
                {
                    ProductId   = p.ProductId,
                    ProductName = p.ProductName
                })
            };

            //check SQL Profiler here
            return(Json(supplierDC, JsonRequestBehavior.AllowGet));
        }
        public JsonResult ExplicitlyLoadingForManyEntities()
        {
            var context = new OrdersContext();

            var category = context.Categories.Find(1);

            context.Entry(category).Collection(c => c.Products).Load();

            var categoryDC = new CategoryDC
            {
                CategoryId   = category.CategoryId,
                CategoryName = category.CategoryName,
                Products     = category.Products.Select(p => new ProductDC
                {
                    ProductId   = p.ProductId,
                    ProductName = p.ProductName
                })
            };

            return(Json(categoryDC, JsonRequestBehavior.AllowGet));
        }
Esempio n. 16
0
 public void Include()
 {
     new TestDefinition
     {
         TestName       = "Query_Simple_Include_EF6",
         IterationCount = 100,
         WarmupCount    = 5,
         Setup          = EnsureDatabaseSetup,
         Run            = harness =>
         {
             using (var context = new OrdersContext(_connectionString))
             {
                 harness.StartCollection();
                 var result = context.Customers.Include(c => c.Orders).ToList();
                 harness.StopCollection();
                 Assert.Equal(1000, result.Count);
                 Assert.Equal(2000, result.SelectMany(c => c.Orders).Count());
             }
         }
     }.RunTest();
 }
        private static void Insert(TestHarness harness)
        {
            using (var context = new OrdersContext(_connectionString))
            {
                using (context.Database.BeginTransaction())
                {
                    for (var i = 0; i < 1000; i++)
                    {
                        context.Customers.Add(new Customer {
                            Name = "New Customer " + i
                        });
                    }

                    harness.StartCollection();
                    var records = context.SaveChanges();
                    harness.StopCollection();

                    Assert.Equal(1000, records);
                }
            }
        }
        //Find() method Versus FirstOrDefault() method
        public JsonResult FindVersusFirstOrDefault()
        {
            var context = new OrdersContext();

            //Using Find()
            var supplierX1 = context.Suppliers.Find(1);             // it will be cached
            var supplierX2 = context.Suppliers.Find(1);

            var supplierXDC = new SupplierDC
            {
                SupplierId  = supplierX2.SupplierId,
                CompanyName = supplierX2.CompanyName,
                Products    = supplierX2.Products.Select(p => new ProductDC
                {
                    ProductId   = p.ProductId,
                    ProductName = p.ProductName
                })
            };


            //Using FirstOrDefault()
            var supplierY = context.Suppliers.Include(x => x.Products).FirstOrDefault(x => x.SupplierId == 1);

            var supplierYDC = new SupplierDC
            {
                SupplierId  = supplierY.SupplierId,
                CompanyName = supplierY.CompanyName,
                Products    = supplierX2.Products.Select(p => new ProductDC
                {
                    ProductId   = p.ProductId,
                    ProductName = p.ProductName
                })
            };

            return(Json(new
            {
                supplierXDC,
                supplierYDC
            }, JsonRequestBehavior.AllowGet));
        }
Esempio n. 19
0
        public ActionResult Add(ViewModelAddProducts model)
        {
            using (OrdersContext context = new OrdersContext())

            {
                context.SalesOrderDetail.AddRange(
                    model.Products
                    .Where(it => it.Selected)
                    .Select(it => new SalesOrderDetail
                {
                    ModifyDate   = DateTime.Now,
                    OrderQty     = 1,
                    ProductId    = it.Id,
                    SalesOrderId = model.OrderId,
                    UnitPrice    = it.ListPrice
                }));

                context.SaveChanges();

                return(RedirectToAction("Details", new { id = model.OrderId }));
            }
        }
Esempio n. 20
0
        private static void GetOrdersWithCustomersThread(object obj)
        {
            var tobject = obj as Tuple <Action <List <OrderCustomerModel> >, Action <Exception> >;

            try
            {
                var ret = new List <OrderCustomerModel>();
                if (ThreadSleepEnable)
                {
                    Thread.Sleep(TimeSpan.FromSeconds(ThreadSleepInSeconds));
                }
                using (var db = new OrdersContext())
                {
                    ret = db.Order.Include(nameof(Customer)).Select(OrderCustomerModel.GetOrderCustomer).ToList();
                }
                tobject.Item1.Invoke(ret);
            }
            catch (Exception ex)
            {
                tobject.Item2.Invoke(ex);
            }
        }
Esempio n. 21
0
        private static void ValidateCustomerThread(object obj)
        {
            var tobject = obj as Tuple <string, string, Action <bool>, Action <Exception> >;

            try
            {
                bool ret;
                if (ThreadSleepEnable)
                {
                    Thread.Sleep(TimeSpan.FromSeconds(ThreadSleepInSeconds));
                }
                using (var db = new OrdersContext())
                {
                    ret = !db.Customer.Any(x => x.FirstName.Equals(tobject.Item1) && x.LastName.Equals(tobject.Item2));
                }
                tobject.Item3.Invoke(ret);
            }
            catch (Exception ex)
            {
                tobject.Item4.Invoke(ex);
            }
        }
        public JsonResult LazyLoadingDeferredExecution(bool getSuppliers)
        {
            var context  = new OrdersContext();
            var products = context.Products;             //Deffered Execution

            //check SQL Profiler here

            List <ProductDC> productDCs;

            if (getSuppliers)
            {
                productDCs = products.Select(x => new ProductDC
                {
                    ProductId   = x.ProductId,
                    ProductName = x.ProductName,
                    Supplier    = new SupplierDC
                    {
                        SupplierId  = x.Supplier.SupplierId,
                        CompanyName = x.Supplier.CompanyName
                    }
                }).ToList();
            }
            else
            {
                productDCs = products.Select(x => new ProductDC
                {
                    ProductId   = x.ProductId,
                    ProductName = x.ProductName,
                    Category    = new CategoryDC
                    {
                        CategoryId   = x.Category.CategoryId,
                        CategoryName = x.Category.CategoryName
                    }
                }).ToList();
            }

            //check SQL Profiler here
            return(Json(productDCs, JsonRequestBehavior.AllowGet));
        }
        public void Add(TestHarness harness, bool autoDetectChanges)
        {
            using (var context = new OrdersContext(_connectionString))
            {
                var customers = new Customer[1000];
                for (var i = 0; i < customers.Length; i++)
                {
                    customers[i] = new Customer {
                        Name = "Customer " + i
                    };
                }

                context.Configuration.AutoDetectChangesEnabled = autoDetectChanges;
                using (harness.StartCollection())
                {
                    foreach (var customer in customers)
                    {
                        context.Customers.Add(customer);
                    }
                }
            }
        }
Esempio n. 24
0
        public ActionResult Create(Orders.Models.ViewModelOrder model)
        {
            try
            {
                using (OrdersContext context = new OrdersContext())

                {
                    Customer customer =
                        context.Customer.FirstOrDefault(c =>
                                                        c.Name.Equals(model.Customer, StringComparison.CurrentCultureIgnoreCase));

                    if (customer == null)
                    {
                        customer = new Customer {
                            Name = model.Customer
                        };
                        context.Customer.Add(customer);
                        context.SaveChanges();
                    }

                    context.SalesOrder
                    .Add(new SalesOrder
                    {
                        CustomerId = customer.Id,
                        Comment    = model.Comment,
                        OrderDate  = DateTime.Now,
                        StatusId   = GetOrderStatusId(context, "подтвержден")
                    });

                    context.SaveChanges();

                    return(RedirectToAction(nameof(Index)));
                }
            }
            catch
            {
                return(View());
            }
        }
Esempio n. 25
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, OrdersContext context)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            var pathBase = Configuration["PATH_BASE"];

            if (!string.IsNullOrEmpty(pathBase))
            {
                app.UsePathBase(pathBase);
            }

            context.Database.Migrate();
            app.UseCors("CorsPolicy");
            app.UseAuthentication();
            // app.UseMvc();
            //  app.UseMvcWithDefaultRoute();
            app.UseSwagger()
            .UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint($"{ (!string.IsNullOrEmpty(pathBase) ? pathBase : string.Empty) }/swagger/v1/swagger.json", "OrderApi V1");
                c.OAuthClientId("orderswaggerui");
                //c.OAuthClientSecret("test-secret");
                //c.OAuthRealm("test-realm");
                c.OAuthAppName("Ordering Swagger UI");
                c.OAuthScopeSeparator(" ");
                c.OAuthUseBasicAuthenticationWithAccessCodeGrant();

                //c.ConfigureOAuth2("orderswaggerui", "", "", "Ordering Swagger UI");
            });

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller}/{action}");
            });
        }
Esempio n. 26
0
        static void Main(string[] args)
        {
            string       brokerList    = "localhost:9092";
            const string topic         = "orders";
            const string canceledTopic = "canceledorders";

            var config = new Dictionary <string, object>
            {
                { "group.id", "order-management" },
                { "enable.auto.commit", false },
                { "bootstrap.servers", brokerList }
            };
            var context           = new OrdersContext();
            var repo              = new OrderRepository(context);
            var eventProcessor    = new OrderAcceptedEventProcessor(repo);
            var canceledProcessor = new OrderCanceledEventProcessor(repo);

            var orderConsumer    = new KafkaOrdersConsumer(topic, config, eventProcessor);
            var activityConsumer = new KafkaActivitiesConsumer(canceledTopic, config, canceledProcessor);

            orderConsumer.Consume();
            activityConsumer.Consume();
            const int Port = 3001;

            Server server = new Server
            {
                Services = { OrderManagement.BindService(new OrderManagementImpl(repo)) },
                Ports    = { new ServerPort("localhost", Port, ServerCredentials.Insecure) }
            };

            server.Start();
            Console.WriteLine("Order management RPC service listening on port " + Port);
            Console.WriteLine("Press any key to stop");


            Console.ReadKey();
            server.ShutdownAsync().Wait();
        }
Esempio n. 27
0
        private static void GetCustomerByIdThread(object obj)
        {
            var tobject = obj as Tuple <Guid, Action <Customer>, Action <Exception> >;

            try
            {
                Customer customerRet;
                if (ThreadSleepEnable)
                {
                    Thread.Sleep(TimeSpan.FromSeconds(ThreadSleepInSeconds));
                }
                using (var db = new OrdersContext())
                {
                    customerRet = db.Customer.FirstOrDefault(x => x.Id.Equals(tobject.Item1));
                }

                tobject.Item2.Invoke(customerRet);
            }
            catch (Exception ex)
            {
                tobject.Item3.Invoke(ex);
            }
        }
        public void RemoveCollection()
        {
            new TestDefinition
            {
                TestName       = "ChangeTracker_DbSetOperation_RemoveCollection_EF6",
                IterationCount = 100,
                WarmupCount    = 5,
                Setup          = EnsureDatabaseSetup,
                Run            = harness =>
                {
                    using (var context = new OrdersContext(_connectionString))
                    {
                        var customers = context.Customers.ToArray();
                        Assert.Equal(1000, customers.Length);

                        using (harness.StartCollection())
                        {
                            context.Customers.RemoveRange(customers);
                        }
                    }
                }
            }.RunTest();
        }
Esempio n. 29
0
        private static void Main()
        {
            SetupDatabase();

            using (var db = new OrdersContext())
            {
                var orderSummaries = db.OrderSummaries;

                // Use query type with FromSql
                //var orderSummaries = orderSummaries.FromSql(
                //        @"SELECT o.Amount, p.Name AS ProductName, c.Name AS CustomerName
                //        FROM Orders o
                //        INNER JOIN Product p ON o.ProductId = p.Id
                //        INNER JOIN Customer c ON o.CustomerId = c.Id");

                foreach (var orderSummary in orderSummaries)
                {
                    Console.WriteLine(orderSummary);
                }
            }

            Console.Read();
        }
        //Lazy Loading: return a singleton value
        public JsonResult LazyLoadingSingletonValue()
        {
            var context = new OrdersContext();

            //Queries that return a singleton value are executed immediately
            //e.g: Average, Count, First, Single, and Max
            var supplier = context.Suppliers.First();

            //check SQL Profiler here
            var supplierDC = new SupplierDC
            {
                SupplierId  = supplier.SupplierId,
                CompanyName = supplier.CompanyName,
                Products    = supplier.Products.Select(p => new ProductDC
                {
                    ProductId   = p.ProductId,
                    ProductName = p.ProductName
                })
            };

            //check SQL Profiler here
            return(Json(supplierDC, JsonRequestBehavior.AllowGet));
        }
Esempio n. 31
0
		public static void init() {			
			ordersContext = new OrdersContext();
			ordersContext.context = new OrdersDomainContext();
			ordersContext.filter = new OrderFilter();
			GlobalStatus.Current.init();
		}