示例#1
0
        public IActionResult Task3()
        {
            var productStore = new ProductStore()
            {
                Path = productPath
            };
            var productInfoStore = new ProductInfoStore()
            {
                Path = productInfoPath
            };

            var productList     = productStore.GetCollection();
            var productInfoList = productInfoStore.GetCollection();

            var temp1 = productList.Join(productInfoList, tempItem => tempItem.Id,
                                         info => info.ProductId,

                                         (tempItem, info) =>
                                         new ProductAndProductInfo
            {
                ProductId             = tempItem.Id,
                ProductName           = tempItem.Name,
                ProductPrice          = tempItem.Price,
                ProductAmount         = tempItem.Amount,
                ProductDeliveryPeriod = tempItem.DeliveryPeriod,
                ProductMarketId       = tempItem.MarketId,
                ProductInfoId         = info.Id,
                ProductInfoParameter  = info.Parameter,
                ProductInfoDefinition = info.Definition,
                ProductInfoProductId  = info.ProductId
            }).Where(x => (x.ProductInfoParameter == "Rating" && int.Parse(x.ProductInfoDefinition) < 6));

            return(View(temp1));
        }
示例#2
0
        public IActionResult Task1()
        {
            var marketStore = new MarketStore()
            {
                Path = marketPath
            };
            var productStore = new ProductStore()
            {
                Path = productPath
            };
            var productInfoStore = new ProductInfoStore()
            {
                Path = productInfoPath
            };

            var marketList      = marketStore.GetCollection();
            var productList     = productStore.GetCollection();
            var productInfoList = productInfoStore.GetCollection();
            var temp            = from product in productList
                                  join market in marketList on product.MarketId equals market.ID
                                  select new
            {
                MarketID              = market.ID,
                MarketName            = market.Name,
                MarketRating          = market.Rating,
                ProductId             = product.Id,
                ProductName           = product.Name,
                ProductPrice          = product.Price,
                ProductAmount         = product.Amount,
                ProductDeliveryPeriod = product.DeliveryPeriod,
                ProductMarketId       = product.MarketId
            };
            var temp1 = temp.Join(productInfoList, tempItem => tempItem.ProductId,
                                  info => info.ProductId,

                                  (tempItem, info) =>
                                  new Complete
            {
                MarketID              = tempItem.MarketID,
                MarketName            = tempItem.MarketName,
                MarketRating          = tempItem.MarketRating,
                ProductId             = tempItem.ProductId,
                ProductName           = tempItem.ProductName,
                ProductPrice          = tempItem.ProductPrice,
                ProductAmount         = tempItem.ProductAmount,
                ProductDeliveryPeriod = tempItem.ProductDeliveryPeriod,
                ProductMarketId       = tempItem.ProductMarketId,
                ProductInfoId         = info.Id,
                ProductInfoParameter  = info.Parameter,
                ProductInfoDefinition = info.Definition,
                ProductInfoProductId  = info.ProductId
            });


            return(View(temp1));
        }
        public async Task SetProductInfoTest()
        {
            // Arrange
            string edgeProductInfo = "IoTEdge 1.0.7";
            string clientVersion   = $"TestClientVersion{Guid.NewGuid().ToString()}";
            var    identity        = Mock.Of <IDeviceIdentity>(i => i.Id == "d1" && i.DeviceId == "d1");

            var deviceListener = Mock.Of <IDeviceListener>();

            var connectionHandler = Mock.Of <IConnectionHandler>(c => c.GetDeviceListener() == Task.FromResult(deviceListener));
            var amqpAuthenticator = new Mock <IAmqpAuthenticator>();

            amqpAuthenticator.Setup(c => c.AuthenticateAsync("d1")).ReturnsAsync(true);
            Mock <ICbsNode> cbsNodeMock    = amqpAuthenticator.As <ICbsNode>();
            ICbsNode        cbsNode        = cbsNodeMock.Object;
            var             amqpConnection = Mock.Of <IAmqpConnection>(
                c =>
                c.FindExtension <IConnectionHandler>() == connectionHandler &&
                c.FindExtension <ICbsNode>() == cbsNode);
            var amqpSession = Mock.Of <IAmqpSession>(s => s.Connection == amqpConnection);
            var amqpLink    = Mock.Of <IReceivingAmqpLink>(l => l.Session == amqpSession && l.IsReceiver && l.Settings == new AmqpLinkSettings() && l.State == AmqpObjectState.Opened);

            var linkSettings = new AmqpLinkSettings
            {
                Properties = new Fields()
                {
                    { IotHubAmqpProperty.ClientVersion, clientVersion }
                }
            };

            Mock.Get(amqpLink).SetupGet(l => l.Settings).Returns(linkSettings);

            var requestUri     = new Uri("amqps://foo.bar/devices/d1/messages/events");
            var boundVariables = new Dictionary <string, string> {
                { "deviceid", "d1" }
            };
            var messageConverter = new AmqpMessageConverter();

            var storeProvider = new StoreProvider(new InMemoryDbStoreProvider());
            IEntityStore <string, string> store = storeProvider.GetEntityStore <string, string>("productInfo");
            var productInfoStore = new ProductInfoStore(store, edgeProductInfo);
            var modelIdStore     = Mock.Of <IModelIdStore>();

            ILinkHandler linkHandler = new EventsLinkHandler(identity, amqpLink, requestUri, boundVariables, connectionHandler, messageConverter, productInfoStore, modelIdStore);

            // Act
            await linkHandler.OpenAsync(TimeSpan.FromSeconds(1));

            // Assert
            string productInfo = await productInfoStore.GetProductInfo(identity.Id);

            string deviceEdgeProductInfo = await productInfoStore.GetEdgeProductInfo(identity.Id);

            Assert.Equal(clientVersion, productInfo);
            Assert.Equal($"{clientVersion} {edgeProductInfo}", deviceEdgeProductInfo);
        }
示例#4
0
        public async Task EmptyProductInfoTest()
        {
            // Arrange
            string edgeProductInfo = "IoTEdge 1.0.7";
            var    storeProvider   = new StoreProvider(new InMemoryDbStoreProvider());
            IEntityStore <string, string> store = storeProvider.GetEntityStore <string, string>("productInfo");
            var productInfoStore = new ProductInfoStore(store, edgeProductInfo);

            // Act
            await productInfoStore.SetProductInfo("d1", string.Empty);

            string productInfoValue = await productInfoStore.GetProductInfo("d1");

            // Assert
            Assert.Equal(string.Empty, productInfoValue);
        }
        public async Task SmokeTest()
        {
            // Arrange
            string edgeProductInfo = "IoTEdge 1.0.7";
            var    storeProvider   = new StoreProvider(new InMemoryDbStoreProvider());
            IEntityStore <string, string> store = storeProvider.GetEntityStore <string, string>("productInfo");
            var productInfoStore = new ProductInfoStore(store, edgeProductInfo);

            var deviceProductInfos = new Dictionary <string, string>
            {
                ["d1"]    = Guid.NewGuid().ToString(),
                ["d2"]    = Guid.NewGuid().ToString(),
                ["d3"]    = Guid.NewGuid().ToString(),
                ["d3/m1"] = Guid.NewGuid().ToString(),
                ["d3/m2"] = Guid.NewGuid().ToString()
            };

            // Act
            foreach (KeyValuePair <string, string> kvp in deviceProductInfos)
            {
                await productInfoStore.SetProductInfo(kvp.Key, kvp.Value);
            }

            var receivedDeviceInfos     = new Dictionary <string, string>();
            var receivedEdgeDeviceInfos = new Dictionary <string, string>();

            foreach (string id in deviceProductInfos.Keys)
            {
                string productInfo = await productInfoStore.GetProductInfo(id);

                string deviceEdgeProductInfo = await productInfoStore.GetEdgeProductInfo(id);

                receivedDeviceInfos.Add(id, productInfo);
                receivedEdgeDeviceInfos.Add(id, deviceEdgeProductInfo);
            }

            // Assert
            Assert.Equal(deviceProductInfos.Count, receivedDeviceInfos.Count);
            Assert.Equal(deviceProductInfos.Count, receivedEdgeDeviceInfos.Count);

            foreach (KeyValuePair <string, string> kvp in deviceProductInfos)
            {
                Assert.Equal(kvp.Value, receivedDeviceInfos[kvp.Key]);
                Assert.Equal($"{kvp.Value} {edgeProductInfo}", receivedEdgeDeviceInfos[kvp.Key]);
            }
        }
示例#6
0
        public IActionResult Test(int ID)
        {
            Console.WriteLine("Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
            var marketStore = new MarketStore()
            {
                Path = marketPath
            };
            var productStore = new ProductStore()
            {
                Path = productPath
            };
            var productInfoStore = new ProductInfoStore()
            {
                Path = productInfoPath
            };

            var marketList      = marketStore.GetCollection();
            var productList     = productStore.GetCollection().Where(x => x.MarketId == ID);
            var productInfoList = productInfoStore.GetCollection();

            var temp1 = productList.Join(productInfoList, tempItem => tempItem.Id,
                                         info => info.ProductId,

                                         (tempItem, info) =>
                                         new ProductAndProductInfo
            {
                ProductId             = tempItem.Id,
                ProductName           = tempItem.Name,
                ProductPrice          = tempItem.Price,
                ProductAmount         = tempItem.Amount,
                ProductDeliveryPeriod = tempItem.DeliveryPeriod,
                ProductMarketId       = tempItem.MarketId,
                ProductInfoId         = info.Id,
                ProductInfoParameter  = info.Parameter,
                ProductInfoDefinition = info.Definition,
                ProductInfoProductId  = info.ProductId
            });

            ViewData["ID"] = ID;
            return(View(temp1));
        }
示例#7
0
        public IActionResult Task5()
        {
            Console.WriteLine("Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
            var marketStore = new MarketStore()
            {
                Path = marketPath
            };
            var productStore = new ProductStore()
            {
                Path = productPath
            };
            var productInfoStore = new ProductInfoStore()
            {
                Path = productInfoPath
            };

            var marketList      = marketStore.GetCollection();
            var productList     = productStore.GetCollection();
            var productInfoList = productInfoStore.GetCollection();

            return(View(marketList));
        }
示例#8
0
        public IActionResult Task4()
        {
            var marketStore = new MarketStore()
            {
                Path = marketPath
            };
            var productStore = new ProductStore()
            {
                Path = productPath
            };
            var productInfoStore = new ProductInfoStore()
            {
                Path = productInfoPath
            };

            var marketList      = marketStore.GetCollection();
            var productList     = productStore.GetCollection();
            var productInfoList = productInfoStore.GetCollection();
            var temp            = from product in productList
                                  join market in marketList on product.MarketId equals market.ID
                                  select new
            {
                MarketID              = market.ID,
                MarketName            = market.Name,
                MarketRating          = market.Rating,
                ProductId             = product.Id,
                ProductName           = product.Name,
                ProductPrice          = product.Price,
                ProductAmount         = product.Amount,
                ProductDeliveryPeriod = product.DeliveryPeriod,
                ProductMarketId       = product.MarketId
            };
            var temp1 = temp.Join(productInfoList, tempItem => tempItem.ProductId,
                                  info => info.ProductId,

                                  (tempItem, info) =>
                                  new Complete
            {
                MarketID              = tempItem.MarketID,
                MarketName            = tempItem.MarketName,
                MarketRating          = tempItem.MarketRating,
                ProductId             = tempItem.ProductId,
                ProductName           = tempItem.ProductName,
                ProductPrice          = tempItem.ProductPrice,
                ProductAmount         = tempItem.ProductAmount,
                ProductDeliveryPeriod = tempItem.ProductDeliveryPeriod,
                ProductMarketId       = tempItem.ProductMarketId,
                ProductInfoId         = info.Id,
                ProductInfoParameter  = info.Parameter,
                ProductInfoDefinition = info.Definition,
                ProductInfoProductId  = info.ProductId
            });
            var xx = marketList.Select(m => new SpecialMarket
            {
                Name    = m.Name,
                ID      = m.ID,
                Rating  = m.Rating,
                Average = temp1.Where(t => (t.MarketID == m.ID && t.ProductInfoParameter == "Rating")).Average(z => int.Parse(z.ProductInfoDefinition))
            }).Where(x => x.Rating < x.Average);

            return(View(xx));
        }
示例#9
0
        protected override void Load(ContainerBuilder builder)
        {
            // IMetricsListener
            builder.Register(
                c =>
                this.metricsConfig.Enabled
                            ? new MetricsListener(this.metricsConfig.ListenerConfig, c.Resolve <IMetricsProvider>())
                            : new NullMetricsListener() as IMetricsListener)
            .As <IMetricsListener>()
            .SingleInstance();

            // IMetricsProvider
            builder.Register(
                c =>
                this.metricsConfig.Enabled
                            ? new MetricsProvider(MetricsConstants.EdgeHubMetricPrefix, this.iothubHostName, this.edgeDeviceId)
                            : new NullMetricsProvider() as IMetricsProvider)
            .As <IMetricsProvider>()
            .SingleInstance();

            // ISignatureProvider
            builder.Register(
                c =>
            {
                ISignatureProvider signatureProvider = this.edgeHubConnectionString.Map(
                    cs =>
                {
                    IotHubConnectionStringBuilder csBuilder = IotHubConnectionStringBuilder.Create(cs);
                    return(new SharedAccessKeySignatureProvider(csBuilder.SharedAccessKey) as ISignatureProvider);
                })
                                                       .GetOrElse(
                    () =>
                {
                    string edgeHubGenerationId = this.edgeHubGenerationId.Expect(() => new InvalidOperationException("Generation ID missing"));
                    string workloadUri         = this.workloadUri.Expect(() => new InvalidOperationException("workloadUri is missing"));
                    string workloadApiVersion  = this.workloadApiVersion.Expect(() => new InvalidOperationException("workloadUri version is missing"));
                    return(new HttpHsmSignatureProvider(this.edgeHubModuleId, edgeHubGenerationId, workloadUri, workloadApiVersion, Constants.WorkloadApiVersion) as ISignatureProvider);
                });
                return(signatureProvider);
            })
            .As <ISignatureProvider>()
            .SingleInstance();

            // Detect system environment
            builder.Register(c => new SystemEnvironment())
            .As <ISystemEnvironment>()
            .SingleInstance();

            // DataBase options
            builder.Register(c => new RocksDbOptionsProvider(c.Resolve <ISystemEnvironment>(), this.optimizeForPerformance, this.storageMaxTotalWalSize))
            .As <IRocksDbOptionsProvider>()
            .SingleInstance();

            if (!this.usePersistentStorage && this.useBackupAndRestore)
            {
                // Backup and restore serialization
                builder.Register(c => new ProtoBufDataBackupRestore())
                .As <IDataBackupRestore>()
                .SingleInstance();
            }

            // IStorageSpaceChecker
            builder.Register(
                c =>
            {
                IStorageSpaceChecker spaceChecker = !this.usePersistentStorage
                       ? new MemorySpaceChecker(() => 0L) as IStorageSpaceChecker
                       : new NullStorageSpaceChecker();
                return(spaceChecker);
            })
            .As <IStorageSpaceChecker>()
            .SingleInstance();

            // IDbStoreProvider
            builder.Register(
                async c =>
            {
                var loggerFactory = c.Resolve <ILoggerFactory>();
                ILogger logger    = loggerFactory.CreateLogger(typeof(RoutingModule));

                if (this.usePersistentStorage)
                {
                    // Create partitions for messages and twins
                    var partitionsList = new List <string> {
                        Core.Constants.MessageStorePartitionKey, Core.Constants.TwinStorePartitionKey, Core.Constants.CheckpointStorePartitionKey
                    };
                    try
                    {
                        IDbStoreProvider dbStoreProvider = DbStoreProvider.Create(
                            c.Resolve <IRocksDbOptionsProvider>(),
                            this.storagePath,
                            partitionsList);
                        logger.LogInformation($"Created persistent store at {this.storagePath}");
                        return(dbStoreProvider);
                    }
                    catch (Exception ex) when(!ex.IsFatal())
                    {
                        logger.LogError(ex, "Error creating RocksDB store. Falling back to in-memory store.");
                        IDbStoreProvider dbStoreProvider = await this.BuildInMemoryDbStoreProvider(c);
                        return(dbStoreProvider);
                    }
                }
                else
                {
                    logger.LogInformation($"Using in-memory store");
                    IDbStoreProvider dbStoreProvider = await this.BuildInMemoryDbStoreProvider(c);
                    return(dbStoreProvider);
                }
            })
            .As <Task <IDbStoreProvider> >()
            .SingleInstance();

            // Task<Option<IEncryptionProvider>>
            builder.Register(
                async c =>
            {
                Option <IEncryptionProvider> encryptionProviderOption = await this.workloadUri
                                                                        .Map(
                    async uri =>
                {
                    var encryptionProvider = await EncryptionProvider.CreateAsync(
                        this.storagePath,
                        new Uri(uri),
                        this.workloadApiVersion.Expect(() => new InvalidOperationException("Missing workload API version")),
                        Constants.WorkloadApiVersion,
                        this.edgeHubModuleId,
                        this.edgeHubGenerationId.Expect(() => new InvalidOperationException("Missing generation ID")),
                        Constants.InitializationVectorFileName) as IEncryptionProvider;
                    return(Option.Some(encryptionProvider));
                })
                                                                        .GetOrElse(() => Task.FromResult(Option.None <IEncryptionProvider>()));
                return(encryptionProviderOption);
            })
            .As <Task <Option <IEncryptionProvider> > >()
            .SingleInstance();

            // Task<IStoreProvider>
            builder.Register(async c =>
            {
                var dbStoreProvider          = await c.Resolve <Task <IDbStoreProvider> >();
                IStoreProvider storeProvider = new StoreProvider(dbStoreProvider);
                return(storeProvider);
            })
            .As <Task <IStoreProvider> >()
            .SingleInstance();

            // Task<IProductInfoStore>
            builder.Register(
                async c =>
            {
                var storeProvider = await c.Resolve <Task <IStoreProvider> >();
                IKeyValueStore <string, string> entityStore = storeProvider.GetEntityStore <string, string>("ProductInfo");
                IProductInfoStore productInfoStore          = new ProductInfoStore(entityStore, this.productInfo);
                return(productInfoStore);
            })
            .As <Task <IProductInfoStore> >()
            .SingleInstance();

            // ITokenProvider
            builder.Register(c => new ClientTokenProvider(c.Resolve <ISignatureProvider>(), this.iothubHostName, this.edgeDeviceId, this.edgeHubModuleId, TimeSpan.FromHours(1)))
            .Named <ITokenProvider>("EdgeHubClientAuthTokenProvider")
            .SingleInstance();

            // ITokenProvider
            builder.Register(
                c =>
            {
                string deviceId = WebUtility.UrlEncode(this.edgeDeviceId);
                string moduleId = WebUtility.UrlEncode(this.edgeHubModuleId);
                return(new ClientTokenProvider(c.Resolve <ISignatureProvider>(), this.iothubHostName, deviceId, moduleId, TimeSpan.FromHours(1)));
            })
            .Named <ITokenProvider>("EdgeHubServiceAuthTokenProvider")
            .SingleInstance();

            builder.Register(
                c =>
            {
                var loggerFactory = c.Resolve <ILoggerFactory>();
                var logger        = loggerFactory.CreateLogger <RoutingModule>();
                return(Proxy.Parse(this.proxy, logger));
            })
            .As <Option <IWebProxy> >()
            .SingleInstance();

            // Task<IDeviceScopeIdentitiesCache>
            builder.Register(
                async c =>
            {
                IDeviceScopeIdentitiesCache deviceScopeIdentitiesCache;
                if (this.authenticationMode == AuthenticationMode.CloudAndScope || this.authenticationMode == AuthenticationMode.Scope)
                {
                    var edgeHubTokenProvider = c.ResolveNamed <ITokenProvider>("EdgeHubServiceAuthTokenProvider");
                    var proxy = c.Resolve <Option <IWebProxy> >();
                    IDeviceScopeApiClient securityScopesApiClient = new DeviceScopeApiClient(this.iothubHostName, this.edgeDeviceId, this.edgeHubModuleId, 10, edgeHubTokenProvider, proxy);
                    IServiceProxy serviceProxy = new ServiceProxy(securityScopesApiClient);
                    IKeyValueStore <string, string> encryptedStore = await GetEncryptedStore(c, "DeviceScopeCache");
                    deviceScopeIdentitiesCache = await DeviceScopeIdentitiesCache.Create(serviceProxy, encryptedStore, this.scopeCacheRefreshRate);
                }
                else
                {
                    deviceScopeIdentitiesCache = new NullDeviceScopeIdentitiesCache();
                }

                return(deviceScopeIdentitiesCache);
            })
            .As <Task <IDeviceScopeIdentitiesCache> >()
            .AutoActivate()
            .SingleInstance();

            // Task<ICredentialsCache>
            builder.Register(
                async c =>
            {
                ICredentialsCache underlyingCredentialsCache;
                if (this.persistTokens)
                {
                    IKeyValueStore <string, string> encryptedStore = await GetEncryptedStore(c, "CredentialsCache");
                    return(new PersistedTokenCredentialsCache(encryptedStore));
                }
                else
                {
                    underlyingCredentialsCache = new NullCredentialsCache();
                }

                ICredentialsCache credentialsCache = new CredentialsCache(underlyingCredentialsCache);
                return(credentialsCache);
            })
            .As <Task <ICredentialsCache> >()
            .SingleInstance();

            // Task<IAuthenticator>
            builder.Register(
                async c =>
            {
                IAuthenticator tokenAuthenticator;
                IAuthenticator certificateAuthenticator;
                IDeviceScopeIdentitiesCache deviceScopeIdentitiesCache;
                var credentialsCacheTask = c.Resolve <Task <ICredentialsCache> >();
                // by default regardless of how the authenticationMode, X.509 certificate validation will always be scoped
                deviceScopeIdentitiesCache = await c.Resolve <Task <IDeviceScopeIdentitiesCache> >();
                certificateAuthenticator   = new DeviceScopeCertificateAuthenticator(deviceScopeIdentitiesCache, new NullAuthenticator(), this.trustBundle, true);
                switch (this.authenticationMode)
                {
                case AuthenticationMode.Cloud:
                    tokenAuthenticator = await this.GetCloudTokenAuthenticator(c);
                    break;

                case AuthenticationMode.Scope:
                    tokenAuthenticator = new DeviceScopeTokenAuthenticator(deviceScopeIdentitiesCache, this.iothubHostName, this.edgeDeviceHostName, new NullAuthenticator(), true, true);
                    break;

                default:
                    IAuthenticator cloudTokenAuthenticator = await this.GetCloudTokenAuthenticator(c);
                    tokenAuthenticator = new DeviceScopeTokenAuthenticator(deviceScopeIdentitiesCache, this.iothubHostName, this.edgeDeviceHostName, cloudTokenAuthenticator, true, true);
                    break;
                }

                ICredentialsCache credentialsCache = await credentialsCacheTask;
                return(new Authenticator(tokenAuthenticator, certificateAuthenticator, credentialsCache) as IAuthenticator);
            })
            .As <Task <IAuthenticator> >()
            .SingleInstance();

            // IClientCredentialsFactory
            builder.Register(c => new ClientCredentialsFactory(c.Resolve <IIdentityProvider>(), this.productInfo))
            .As <IClientCredentialsFactory>()
            .SingleInstance();

            // ConnectionReauthenticator
            builder.Register(
                async c =>
            {
                var edgeHubCredentials               = c.ResolveNamed <IClientCredentials>("EdgeHubCredentials");
                var connectionManagerTask            = c.Resolve <Task <IConnectionManager> >();
                var authenticatorTask                = c.Resolve <Task <IAuthenticator> >();
                var credentialsCacheTask             = c.Resolve <Task <ICredentialsCache> >();
                var deviceScopeIdentitiesCacheTask   = c.Resolve <Task <IDeviceScopeIdentitiesCache> >();
                var deviceConnectivityManager        = c.Resolve <IDeviceConnectivityManager>();
                IConnectionManager connectionManager = await connectionManagerTask;
                IAuthenticator authenticator         = await authenticatorTask;
                ICredentialsCache credentialsCache   = await credentialsCacheTask;
                IDeviceScopeIdentitiesCache deviceScopeIdentitiesCache = await deviceScopeIdentitiesCacheTask;
                var connectionReauthenticator = new ConnectionReauthenticator(
                    connectionManager,
                    authenticator,
                    credentialsCache,
                    deviceScopeIdentitiesCache,
                    TimeSpan.FromMinutes(5),
                    edgeHubCredentials.Identity,
                    deviceConnectivityManager);
                return(connectionReauthenticator);
            })
            .As <Task <ConnectionReauthenticator> >()
            .SingleInstance();

            base.Load(builder);
        }
示例#10
0
        public static void Step1()
        {
            //Step1

            var marketStore = new MarketStore()
            {
                Path = marketPath
            };
            var productStore = new ProductStore()
            {
                Path = productPath
            };
            var productInfoStore = new ProductInfoStore()
            {
                Path = productInfoPath
            };

            var marketList      = marketStore.GetCollection();
            var productList     = productStore.GetCollection();
            var productInfoList = productInfoStore.GetCollection();

            foreach (var item in marketList)
            {
                item.products = productList.Where(x => x.MarketId == item.ID).ToList();
            }
            foreach (var item in productList)
            {
                item.productInfos = productInfoList.Where(x => x.ProductId == item.Id).ToList();
            }

            Console.WriteLine("Step 1 \n");
            foreach (var market in marketList)
            {
                Console.WriteLine("================================");

                Console.WriteLine(string.Format("{0}) {1}; Rating: {2}; Product Price Sum: {3}",
                                                market.ID,
                                                market.Name,
                                                market.Rating,
                                                market.products.Sum(x => x.Price)));



                foreach (var prod in market.products)
                {
                    Console.WriteLine();
                    Console.WriteLine("Product ");

                    var prodTemplate = "{0} | {1} | {2} | {3} | {4}";

                    Console.WriteLine(string.Format(prodTemplate,
                                                    "Id",
                                                    "Name",
                                                    "Price",
                                                    "Amount",
                                                    "Delivery Perion (days)"));

                    Console.WriteLine(string.Format(prodTemplate,
                                                    prod.Id,
                                                    prod.Name,
                                                    prod.Price,
                                                    prod.Amount,
                                                    prod.DeliveryPeriod));
                    var prodInfoTemp = "{0} | {1} | {2}  ";
                    Console.WriteLine();
                    Console.WriteLine("Product Info");
                    Console.WriteLine(string.Format(prodInfoTemp, "Id", "Parameter", "Definition"));

                    foreach (var info in prod.productInfos)
                    {
                        Console.WriteLine(string.Format(prodInfoTemp,
                                                        info.Id,
                                                        info.Parameter,
                                                        info.Definition
                                                        ));
                    }
                }
            }
        }
示例#11
0
        public static void Step5()
        {
            var marketStore = new MarketStore()
            {
                Path = marketPath
            };
            var productStore = new ProductStore()
            {
                Path = productPath
            };
            var productInfoStore = new ProductInfoStore()
            {
                Path = productInfoPath
            };

            var marketList      = marketStore.GetCollection();
            var productList     = productStore.GetCollection();
            var productInfoList = productInfoStore.GetCollection();



            /*foreach (var item in marketList)
             * {
             *  item.products = productList.Where(x => x.MarketId == item.ID).ToList();
             * }
             * foreach (var item in productList)
             * {
             *  item.productInfos = productInfoList.Where(x => x.ProductId == item.Id).OrderBy(x => x.Parameter).ToList();
             * }*/

            Console.WriteLine("====================================");
            foreach (var market in marketList)
            {
                Console.WriteLine("Market {0}:{1}", market.ID, market.Name);
            }
            Console.WriteLine();
            Console.WriteLine("Please, choose the number of the market:");
            string k = Console.ReadLine();

            var chProductList = productList.Where(x => x.MarketId == int.Parse(k)).ToList();

            foreach (var item in chProductList)
            {
                Console.WriteLine("Product {0}, Name {1}, Price {2}, TotalAmount {3}", item.Id, item.Name, item.Price, item.Amount);
            }
            Console.WriteLine();
            List <string> lines = new List <string>();

            /*lines.Add("ffff");
             * File.WriteAllLines(@"AppData/test.csv", lines);*/

            bool   chh         = true;
            double totalAmount = 0;

            while (chh == true)
            {
                Console.WriteLine("For quiting enter 'q', for continuing enter 'c'");
                string ams = Console.ReadLine();
                if (ams == "q")
                {
                    File.WriteAllLines(@"AppData/test.csv", lines);
                    Console.WriteLine("The check");
                    Console.WriteLine("====================================");
                    var data = File.ReadAllLines(@"AppData/test.csv");

                    foreach (var item in data)
                    {
                        Console.WriteLine(item);
                    }
                    Console.WriteLine("=========");
                    Console.WriteLine("Total: {0}", totalAmount);
                    Console.WriteLine();
                    chh = false;
                    break;
                }
                else
                {
                    Console.WriteLine("Please, choose the product");
                    string prName = Console.ReadLine();
                    bool   exist  = false;
                    foreach (var item in chProductList)
                    {
                        if (item.Id == int.Parse(prName))
                        {
                            //lines.Add(prName + ";");
                            //lines.Add(item.Name + ";");
                            Console.WriteLine("Please, enter the amount of the product");
                            string prNum = Console.ReadLine();

                            if (int.Parse(prNum) > item.Amount)
                            {
                                Console.WriteLine("No such amount of the product. Please choose less than or equal {0}", item.Amount);
                                prNum = Console.ReadLine();
                                //lines.Add(prNum + ";");
                                item.Amount -= int.Parse(prNum);
                                double summ = int.Parse(prNum) * item.Price;
                                totalAmount += summ;
                                lines.Add(prName + ";" + item.Name + ";" + prNum + ";" + summ.ToString() + ";");
                                //lines.Add("\n");
                            }
                            else
                            {
                                //lines.Add(prNum + ";");
                                double summ = int.Parse(prNum) * item.Price;
                                item.Amount -= int.Parse(prNum);
                                totalAmount += summ;
                                lines.Add(prName + ";" + item.Name + ";" + prNum + ";" + summ.ToString() + ";");
                                lines.Add("\n");
                            }
                            exist = true;
                        }
                    }
                    if (exist == false)
                    {
                        Console.WriteLine("No such product for this market");
                    }
                }
            }
        }
示例#12
0
        public static void Step4()
        {
            var marketStore = new MarketStore()
            {
                Path = marketPath
            };
            var productStore = new ProductStore()
            {
                Path = productPath
            };
            var productInfoStore = new ProductInfoStore()
            {
                Path = productInfoPath
            };

            var marketList      = marketStore.GetCollection();
            var productList     = productStore.GetCollection();
            var productInfoList = productInfoStore.GetCollection();



            foreach (var item in marketList)
            {
                item.products = productList.Where(x => x.MarketId == item.ID).ToList();
            }
            foreach (var item in productList)
            {
                item.productInfos = productInfoList.Where(x => x.ProductId == item.Id).OrderBy(x => x.Parameter).ToList();
            }
            var temp = from product in productList
                       join market in marketList on product.MarketId equals market.ID
                       select new
            {
                Id             = product.Id,
                Name           = product.Name,
                Price          = product.Price,
                Amount         = product.Amount,
                DeliveryPeriod = product.DeliveryPeriod,
                Rating         = market.Rating,
                productInfos   = product.productInfos
            };
            var temp1 = productList.Join(productInfoList, product => product.Id,
                                         info => info.ProductId,

                                         (product, info) =>
                                         new { Pr        = product, In = info, Name = product.Name, Price = product.Price,
                                               Parameter = info.Parameter, Definition = info.Definition, MarketId = product.MarketId })
                        .Where(PandI => (PandI.Pr.Id == PandI.In.ProductId && PandI.Parameter == "Rating"));



            var xx = marketList.Select(m => new
            {
                Name     = m.Name,
                ID       = m.ID,
                Rating   = m.Rating,
                products = m.products,
                Average  = temp1.Where(t => t.MarketId == m.ID).Average(z => int.Parse(z.Definition))
            });

            double average = temp1.Average(x => int.Parse(x.Definition));

            foreach (var market in xx)
            {
                Console.WriteLine("================================");
                if (market.Average < average)
                {
                    Console.Write("*");
                }

                Console.WriteLine(string.Format("{0}) {1}; Rating: {2};",
                                                market.ID,
                                                market.Name,
                                                market.Rating
                                                ));



                foreach (var prod in market.products)
                {
                    Console.WriteLine();
                    Console.WriteLine("Product ");

                    var prodTemplate = "{0} | {1} | {2} | {3} | {4}";

                    Console.WriteLine(string.Format(prodTemplate,
                                                    "Id",
                                                    "Name",
                                                    "Price",
                                                    "Amount",
                                                    "Delivery Perion (days)"));

                    Console.WriteLine(string.Format(prodTemplate,
                                                    prod.Id,
                                                    prod.Name,
                                                    prod.Price,
                                                    prod.Amount,
                                                    prod.DeliveryPeriod));
                    var prodInfoTemp = "{0} | {1} | {2}  ";
                    Console.WriteLine();
                    Console.WriteLine("Product Info");
                    Console.WriteLine(string.Format(prodInfoTemp, "Id", "Parameter", "Definition"));

                    foreach (var info in prod.productInfos)
                    {
                        Console.WriteLine(string.Format(prodInfoTemp,
                                                        info.Id,
                                                        info.Parameter,
                                                        info.Definition
                                                        ));
                    }
                }
            }
        }
示例#13
0
        public static void Step3()
        {
            var marketStore = new MarketStore()
            {
                Path = marketPath
            };
            var productStore = new ProductStore()
            {
                Path = productPath
            };
            var productInfoStore = new ProductInfoStore()
            {
                Path = productInfoPath
            };

            var marketList      = marketStore.GetCollection();
            var productList     = productStore.GetCollection();
            var productInfoList = productInfoStore.GetCollection();



            foreach (var item in productList)
            {
                item.productInfos = productInfoList.Where(x => x.ProductId == item.Id).OrderBy(x => x.Parameter).ToList();
            }
            var temp = from product in productList join market in marketList on product.MarketId equals market.ID
                       select new { Id     = product.Id, Name = product.Name, Price = product.Price,
                                    Amount = product.Amount, DeliveryPeriod = product.DeliveryPeriod,
                                    Rating = market.Rating, productInfos = product.productInfos };



            foreach (var prod in temp)
            {
                Console.WriteLine();
                Console.WriteLine("Product ");

                if (prod.Rating < 6)
                {
                    Console.Write("*");
                }

                var prodTemplate = "{0} | {1} | {2} | {3} | {4} | {5}";

                Console.WriteLine(string.Format(prodTemplate,
                                                "Id",
                                                "Name",
                                                "Price",
                                                "Amount",
                                                "Delivery Perion (days)",
                                                "Rating"));

                Console.WriteLine(string.Format(prodTemplate,
                                                prod.Id,
                                                prod.Name,
                                                prod.Price,
                                                prod.Amount,
                                                prod.DeliveryPeriod,
                                                prod.Rating));
                var prodInfoTemp = "{0} | {1} | {2}  ";
                Console.WriteLine();
                Console.WriteLine("Product Info");
                Console.WriteLine(string.Format(prodInfoTemp, "Id", "Parameter", "Definition"));

                foreach (var info in prod.productInfos)
                {
                    Console.WriteLine(string.Format(prodInfoTemp,
                                                    info.Id,
                                                    info.Parameter,
                                                    info.Definition
                                                    ));
                }
            }
        }
示例#14
0
        public static void Step2()
        {
            //Step2
            var marketStore = new MarketStore()
            {
                Path = marketPath
            };
            var productStore = new ProductStore()
            {
                Path = productPath
            };
            var productInfoStore = new ProductInfoStore()
            {
                Path = productInfoPath
            };

            var marketList      = marketStore.GetCollection();
            var productList     = productStore.GetCollection();
            var productInfoList = productInfoStore.GetCollection();

            foreach (var item in marketList)
            {
                item.products = productList.Where(x => x.MarketId == item.ID).ToList();
            }


            Console.WriteLine("Step 2 \n");

            foreach (var market in marketList)
            {
                Console.WriteLine("================================");

                Console.WriteLine(string.Format("{0}) {1}; Rating: {2}; Product Price Sum: {3}",
                                                market.ID,
                                                market.Name,
                                                market.Rating,
                                                market.products.Sum(x => (x.Price * x.Amount))));
                foreach (var prod in market.products)
                {
                    Console.WriteLine();
                    Console.WriteLine("Product ");

                    var prodTemplate = "{0} | {1} | {2} | {3} | {4}";

                    Console.WriteLine(string.Format(prodTemplate,
                                                    "Id",
                                                    "Name",
                                                    "Price",
                                                    "Amount",
                                                    "Delivery Perion (days)"));

                    Console.WriteLine(string.Format(prodTemplate,
                                                    prod.Id,
                                                    prod.Name,
                                                    prod.Price,
                                                    prod.Amount,
                                                    prod.DeliveryPeriod));
                }
            }

            Console.WriteLine("\n Sorted by price \n");

            foreach (var item in marketList)
            {
                item.products = productList.Where(x => x.MarketId == item.ID).OrderBy(x => x.Price).ToList();
            }
            foreach (var market in marketList)
            {
                Console.WriteLine("================================");

                Console.WriteLine(string.Format("{0}) {1}; Rating: {2}; Product Price Sum: {3}",
                                                market.ID,
                                                market.Name,
                                                market.Rating,
                                                market.products.Sum(x => (x.Price * x.Amount))));
                foreach (var prod in market.products)
                {
                    Console.WriteLine();
                    Console.WriteLine("Product ");

                    var prodTemplate = "{0} | {1} | {2} | {3} | {4}";

                    Console.WriteLine(string.Format(prodTemplate,
                                                    "Id",
                                                    "Name",
                                                    "Price",
                                                    "Amount",
                                                    "Delivery Perion (days)"));

                    Console.WriteLine(string.Format(prodTemplate,
                                                    prod.Id,
                                                    prod.Name,
                                                    prod.Price,
                                                    prod.Amount,
                                                    prod.DeliveryPeriod));
                }
            }

            Console.WriteLine("\n Sorted by amount \n");
            foreach (var item in marketList)
            {
                item.products = productList.Where(x => x.MarketId == item.ID).OrderBy(x => x.Amount).ToList();
            }
            foreach (var market in marketList)
            {
                Console.WriteLine("================================");

                Console.WriteLine(string.Format("{0}) {1}; Rating: {2}; Product Price Sum: {3}",
                                                market.ID,
                                                market.Name,
                                                market.Rating,
                                                market.products.Sum(x => (x.Price * x.Amount))));
                foreach (var prod in market.products)
                {
                    Console.WriteLine();
                    Console.WriteLine("Product ");

                    var prodTemplate = "{0} | {1} | {2} | {3} | {4}";

                    Console.WriteLine(string.Format(prodTemplate,
                                                    "Id",
                                                    "Name",
                                                    "Price",
                                                    "Amount",
                                                    "Delivery Perion (days)"));

                    Console.WriteLine(string.Format(prodTemplate,
                                                    prod.Id,
                                                    prod.Name,
                                                    prod.Price,
                                                    prod.Amount,
                                                    prod.DeliveryPeriod));
                }
            }
        }
示例#15
0
        static void Main(string[] args)
        {
            var marketStore = new MarketStore()
            {
                Path = marketPath
            };
            var productStore = new ProductStore()
            {
                Path = productsPath
            };
            var productInfoStore = new ProductInfoStore()
            {
                Path = productInfoPath
            };

            // example 1. get markets with products
            // group markets with products

            var productList     = productStore.GetCollection();
            var marketList      = marketStore.GetCollection();
            var productInfoList = productInfoStore.GetCollection();

            foreach (var item in marketList)
            {
                item.Products = productList
                                .Where(x => x.MarketId == item.Id)
                                .ToList();
            }

            Console.WriteLine("\n");
            Console.WriteLine("Шаг 1. Работа с файлами\n1. Извлечь данные из файлов (csv);");
            Console.WriteLine("2. Отобразить все данные из этих файлов в виде списка;\n");
            var prodTemplate = "{0} | {1} | {2} | {3} | {4}";

            Console.WriteLine(string.Format(prodTemplate,
                                            "Id",
                                            "Name",
                                            "Price",
                                            "Amount",
                                            "Delivery Perion (days)"));
            foreach (var item in marketList)
            {
                foreach (var prod in item.Products)
                {
                    Console.WriteLine(string.Format(prodTemplate,
                                                    prod.Id,
                                                    prod.Name,
                                                    prod.Price,
                                                    prod.Amount,
                                                    prod.DeliveryPeriod));
                }
            }

            Console.WriteLine("\n");

            foreach (var item in productList)
            {
                item.ProductInfo = productInfoList.Where(x => x.ProductId == item.Id).ToList();
            }

            var productInfoListTemplate = "{0} |  {1} |  {2}";

            Console.WriteLine(string.Format(productInfoListTemplate,
                                            "Id",
                                            "Parameter",
                                            "Definition"));

            foreach (var i in productList)
            {
                foreach (var prodInfo in i.ProductInfo)
                {
                    Console.WriteLine(string.Format(productInfoListTemplate,
                                                    prodInfo.Id,
                                                    prodInfo.Parameter,
                                                    prodInfo.Definition));
                }
            }

            Console.WriteLine("\n");
            Console.WriteLine(string.Format(productInfoListTemplate,
                                            "Id",
                                            "Name",
                                            "Rating"));
            foreach (var i in marketList)
            {
                Console.WriteLine(string.Format(productInfoListTemplate,
                                                i.Id,
                                                i.MarketName,
                                                i.Rating));
            }

            Console.WriteLine("\n\nШаг 2. Обработка Market");
            Console.WriteLine("\n1. Отобразить список продуктов;\n");

            foreach (var i in marketList)
            {
                Console.Write(i.MarketName + " | ");
            }
            Console.WriteLine();
            string enteredMarketName = Console.ReadLine();

            var selectedMarket = marketList
                                 .First(x => x.MarketName.Equals(enteredMarketName));

            selectedMarket.Products = productList
                                      .Where(x => x.MarketId == selectedMarket.Id)
                                      .ToList();

            foreach (var item in selectedMarket.Products)
            {
                Console.WriteLine(item.Id + " " + item.Name);
            }

            Console.WriteLine("\n2. Вывести сумму цен всех продуктов выбранного Market; ");

            Console.WriteLine("= " + selectedMarket.Products.Sum(x => x.Price));

            Console.WriteLine("\n\n3. Отсортировать по цене (от меньшего к большему) и вывести продукты выбранного Market;");
            selectedMarket.Products = productList
                                      .Where(x => x.MarketId == selectedMarket.Id)
                                      .OrderBy(x => x.Price)
                                      .ToList();

            foreach (var cur in selectedMarket.Products)
            {
                Console.WriteLine(cur.Price + " " + cur.Name);
            }

            Console.WriteLine("\n4. Отсортировать по кол-ву продуктов и вывести их (по выбранному Market);");
            selectedMarket.Products = productList
                                      .Where(x => x.MarketId == selectedMarket.Id)
                                      .OrderBy(x => x.Amount)
                                      .ToList();
            foreach (var cur in selectedMarket.Products)
            {
                Console.WriteLine(cur.Amount + " " + cur.Name);
            }

            Console.WriteLine("\n\nШаг 3. Работа с ProductInfo\n\n1. Сгруппировать Product и Product Info и отобразить их;\n");
            Console.WriteLine("Group Product and PrInfo by their Name\n");
            string pr6LessStr = "{0} |  {1} |  {2}  |  {3} |  {4} |  {5}";

            Console.WriteLine(string.Format(pr6LessStr,
                                            "Name",
                                            "Price",
                                            "Amount",
                                            "DeliveryPeriod",
                                            "Parameter",
                                            "Definition"));

            var proddListttt = productList
                               .Join(productInfoList, x => x.Id, y => y.ProductId, (x, y) => new {
                x.Name,
                x.Price,
                x.Amount,
                x.DeliveryPeriod,
                y.Parameter,
                y.Definition
            })
                               .GroupBy(x => x.Name)
                               .ToList();

            foreach (var itm in proddListttt)
            {
                foreach (var i in itm)
                {
                    Console.WriteLine(string.Format(pr6LessStr,
                                                    i.Name,
                                                    i.Price,
                                                    i.Amount,
                                                    i.DeliveryPeriod,
                                                    i.Parameter,
                                                    i.Definition));
                }
                Console.WriteLine("\n");
            }

            Console.WriteLine("\n2. Отсортировать название параметра в Product Info;");
            var listOfProdInfo = productInfoList
                                 .OrderBy(x => x.Parameter);

            string listOfProdInfoStr = "{0} |  {1} |  {2}";

            Console.WriteLine(string.Format(productInfoListTemplate,
                                            "Id",
                                            "Parameter",
                                            "Definition"));
            foreach (var cur in listOfProdInfo)
            {
                Console.WriteLine(string.Format(listOfProdInfoStr,
                                                cur.Id,
                                                cur.Parameter,
                                                cur.Definition));
            }

            Console.WriteLine("\n3. Выделить все продукты с рейтингом менее 6;");

            var prodRating6Less = productList
                                  .Join(productInfoList, x => x.Id, y => y.ProductId, (x, y) => new {
                x.Name,
                y.Definition,
                y.Parameter
            })
                                  .Where(x => x.Parameter.Equals("Rating") && Convert.ToInt32(x.Definition) < 6)
                                  .ToList();

            foreach (var print in prodRating6Less)
            {
                Console.WriteLine(print.Definition + " " + print.Name);
            }

            Console.WriteLine("\n\nШаг 4. Общее\n\n1. Сгруппировать Market, Product, ProductInfo и вывести;\n");

            var grMarProd = marketList
                            .Join(productList, x => x.Id, y => y.MarketId, (x, y) => new {
                x.MarketName,
                x.Rating,
                y.Id,
                y.Name,
                y.Price,
                y.Amount,
                y.DeliveryPeriod
            });

            var grMarProdPrInf = grMarProd
                                 .Join(productInfoList, x => x.Id, y => y.ProductId, (x, y) => new {
                x.MarketName,
                x.Rating,
                x.Name,
                x.Price,
                x.Amount,
                x.DeliveryPeriod,
                y.Parameter,
                y.Definition
            })
                                 .GroupBy(x => x.MarketName);

            string grMarProdPrInfStr = "{0} |  {1} |  {2}  |  {3} |  {4} |  {5}  |  {6}  |  {7}";

            Console.WriteLine(string.Format(grMarProdPrInfStr,
                                            "MarketName",
                                            "Rating",
                                            "Name",
                                            "Price",
                                            "Amount",
                                            "DeliveryPeriod",
                                            "Parameter",
                                            "Definition\n"));

            foreach (var grMPP in grMarProdPrInf)
            {
                foreach (var g in grMPP)
                {
                    Console.WriteLine(string.Format(grMarProdPrInfStr,
                                                    g.MarketName,
                                                    g.Rating,
                                                    g.Name,
                                                    g.Price,
                                                    g.Amount,
                                                    g.DeliveryPeriod,
                                                    g.Parameter,
                                                    g.Definition));
                }
            }

            var grMarRatAndProdRat = grMarProd
                                     .Join(productInfoList, x => x.Id, y => y.ProductId, (x, y) => new {
                x.MarketName,
                x.Rating,
                x.Name,
                x.Price,
                x.Amount,
                x.DeliveryPeriod,
                y.Parameter,
                y.Definition
            })
                                     .Where(x => x.Parameter.Equals("Rating"));


            foreach (var grMPP in grMarProdPrInf)
            {
                var avPrInMarket = grMPP
                                   .Where(x => x.Parameter.Equals("Rating"))
                                   .Select(x => Convert.ToInt32(x.Definition))
                                   .ToList();
            }

            Console.WriteLine("\n2. Сравнить рейтинг Market с средним значением рейтингов продуктов. Если рейтинг Market ниже, то выделить Market\n");
            foreach (var grMPP in grMarProdPrInf)
            {
                var avPrInMarket = grMPP
                                   .Where(x => x.Parameter.Equals("Rating"))
                                   .Select(x => Convert.ToInt32(x.Definition))
                                   .Average();

                Console.WriteLine("\nAverage rating of product: " + avPrInMarket + "\n");
                string addedTick = "";
                foreach (var g in grMPP)
                {
                    if (Convert.ToDouble(g.Rating) < Convert.ToDouble(avPrInMarket))
                    {
                        addedTick = "      IS LESS";
                    }
                    else
                    {
                        addedTick = "";
                    }
                }
                foreach (var g in grMPP)
                {
                    Console.WriteLine(string.Format(grMarProdPrInfStr,
                                                    g.MarketName,
                                                    g.Rating + addedTick,
                                                    g.Name,
                                                    g.Price,
                                                    g.Amount,
                                                    g.DeliveryPeriod,
                                                    g.Parameter,
                                                    g.Definition));
                }
            }
        }