Beispiel #1
0
        public async Task insert_where_key_is_string_using_Insert_should_return_true()
        {
            var ticket = new Ticket("insert customer demographics");
            var customerDemographic = new CustomerDemographic
            {
                CustomerTypeId      = "Potential",
                CustomerDescription = "Potential customers"
            };

            string sql = null;
            IDictionary <string, object> parameters = null;

            Jaunty.OnInserting += (sender, args) =>
            {
                sql        = args.Sql;
                parameters = args.Parameters;
            };

            northwind.Connection.Delete <CustomerDemographic, string>(customerDemographic.CustomerTypeId);

            bool success = await northwind.Connection.InsertAsync(customerDemographic, ticket : ticket);

            Assert.Equal("INSERT INTO CustomerDemographics (CustomerTypeId, CustomerDescription) " +
                         "VALUES (@CustomerTypeId, @CustomerDescription);", sql);
            Assert.NotEmpty(parameters);
            Assert.Equal("CustomerTypeId", parameters.ElementAt(0).Key);
            Assert.Equal("Potential", parameters.ElementAt(0).Value);
            Assert.Equal("CustomerDescription", parameters.ElementAt(1).Key);
            Assert.Equal("Potential customers", parameters.ElementAt(1).Value);

            Assert.True(success);
        }
        private Dictionary <DateTime, long> GetTimelineStats(SqlConnection connection,
                                                             IDictionary <string, DateTime> keyMaps)
        {
            string sqlQuery = string.Format(@"
select [Key], [Value] as [Count] from [{0}].AggregatedCounter
where [Key] in @keys", _storage.GetSchemaName());

            var valuesMap = connection.Query(
                sqlQuery,
                new { keys = keyMaps.Keys })
                            .ToDictionary(x => (string)x.Key, x => (long)x.Count);

            foreach (var key in keyMaps.Keys)
            {
                if (!valuesMap.ContainsKey(key))
                {
                    valuesMap.Add(key, 0);
                }
            }

            var result = new Dictionary <DateTime, long>();

            for (var i = 0; i < keyMaps.Count; i++)
            {
                var value = valuesMap[keyMaps.ElementAt(i).Key];
                result.Add(keyMaps.ElementAt(i).Value, value);
            }

            return(result);
        }
        /// <summary>
        /// 获取用户
        /// </summary>
        /// <param name="userID">用户ID</param>
        /// <returns>用户对象</returns>
        internal static IList <User> GetUserListRandom(string userID)
        {
            var random = new Random();
            var users  = new List <User>();

            _toDoUserList.Remove(userID);

            //模拟用户一
            var entry = _toDoUserList.ElementAt(random.Next(0, _toDoUserList.Count()));
            var user  = new User {
                UserID = entry.Key, UserName = entry.Value
            };

            users.Add(user);
            _toDoUserList.Remove(user.UserID);

            //模拟用户二
            entry = _toDoUserList.ElementAt(random.Next(0, _toDoUserList.Count()));
            user  = new User {
                UserID = entry.Key, UserName = entry.Value
            };
            users.Add(user);
            _toDoUserList.Remove(user.UserID);

            //模拟用户三
            entry = _toDoUserList.ElementAt(random.Next(0, _toDoUserList.Count()));
            user  = new User {
                UserID = entry.Key, UserName = entry.Value
            };
            users.Add(user);
            _toDoUserList.Remove(user.UserID);

            return(users);
        }
        public NodeFactory(NodeFuncGenerator funcGenerator, IDictionary <NodeType, double> probabilityMap)
        {
            if (probabilityMap.Count == 0)
            {
                throw new ArgumentException();
            }

            foreach (var item in probabilityMap)
            {
                if (item.Value < 0)
                {
                    throw new ArgumentException();
                }
            }

            funcGenerator_ = funcGenerator;

            typeDistributionMap_ = new Dictionary <NodeType, double>();
            double sum = 0.0d;

            for (int i = 0; i < probabilityMap.Count; i++)
            {
                sum += probabilityMap.ElementAt(i).Value;
                typeDistributionMap_.Add(probabilityMap.ElementAt(i).Key, sum);
            }
            typeDistributionMapMax_ = sum;
        }
        private Dictionary <DateTime, long> GetTimelineStats(SessionWrapper session,
                                                             IDictionary <string, DateTime> keyMaps)
        {
            var valuesMap = session.Query <_AggregatedCounter>()
                            .Where(i => keyMaps.Keys.Contains(i.Key))
                            .ToDictionary(x => x.Key, x => x.Value);

            foreach (var key in keyMaps.Keys)
            {
                if (!valuesMap.ContainsKey(key))
                {
                    valuesMap.Add(key, 0);
                }
            }

            var result = new Dictionary <DateTime, long>();

            for (var i = 0; i < keyMaps.Count; i++)
            {
                var value = valuesMap[keyMaps.ElementAt(i).Key];
                result.Add(keyMaps.ElementAt(i).Value, value);
            }

            return(result);
        }
Beispiel #6
0
        private Dictionary <DateTime, long> GetTimelineStats(NpgsqlConnection connection,
                                                             IDictionary <string, DateTime> keyMaps)
        {
            var query = $@"
SELECT ""key"", COUNT(""value"") AS ""count"" 
FROM ""{_options.SchemaName}"".""counter""
WHERE ""key"" = ANY (@keys)
GROUP BY ""key"";
";

            var valuesMap = connection.Query(
                query,
                new { keys = keyMaps.Keys.ToList() })
                            .ToList()
                            .ToDictionary(x => (string)x.key, x => (long)x.count);

            foreach (var key in keyMaps.Keys)
            {
                if (!valuesMap.ContainsKey(key))
                {
                    valuesMap.Add(key, 0);
                }
            }

            var result = new Dictionary <DateTime, long>();

            for (var i = 0; i < keyMaps.Count; i++)
            {
                var value = valuesMap[keyMaps.ElementAt(i).Key];
                result.Add(keyMaps.ElementAt(i).Value, value);
            }

            return(result);
        }
Beispiel #7
0
        public async Task get_by_primary_key_using_Get_returns_a_product()
        {
            var    ticket = new Ticket("get a product via primary key using Get");
            string sql    = null;
            IDictionary <string, object> parameters = null;

            Jaunty.OnSelecting += (sender, args) =>
            {
                sql        = args.Sql;
                parameters = args.Parameters;
            };

            Product product = await northwind.Connection.GetAsync <Product, int>(1, ticket : ticket);

            Assert.Equal(1, product.ProductId);

            Assert.Equal("SELECT ProductId, ProductName, SupplierId, CategoryId, QuantityPerUnit, UnitPrice, UnitsInStock, " +
                         "UnitsOnOrder, ReorderLevel, Discontinued " +
                         "FROM Products " +
                         "WHERE ProductId = @ProductId;", sql);
            Assert.Equal("ProductId", parameters.ElementAt(0).Key);
            Assert.Equal(1, parameters.ElementAt(0).Value);

            Assert.NotNull(product);
            Assert.True(product.ProductId > 0);
        }
        private Dictionary <DateTime, long> GetTimelineStats(MySqlConnection connection,
                                                             IDictionary <string, DateTime> keyMaps)
        {
            var valuesMap = connection.Query(
                "select `Key`, `Value` as `Count` from AggregatedCounter where `Key` in @keys",
                new { keys = keyMaps.Keys })
                            .ToDictionary(x => (string)x.Key, x => (long)x.Count);

            foreach (var key in keyMaps.Keys)
            {
                if (!valuesMap.ContainsKey(key))
                {
                    valuesMap.Add(key, 0);
                }
            }

            var result = new Dictionary <DateTime, long>();

            for (var i = 0; i < keyMaps.Count; i++)
            {
                var value = valuesMap[keyMaps.ElementAt(i).Key];
                result.Add(keyMaps.ElementAt(i).Value, value);
            }

            return(result);
        }
Beispiel #9
0
        private static void Main(string[] args)
        {
            // Input
            int numberOfItems = inputItems.Count;

            int[] values           = new int[numberOfItems];
            int[] weigths          = new int[numberOfItems];
            int   knapsackCapacity = 10;

            for (int i = 0; i < numberOfItems; i++)
            {
                weigths[i] = inputItems.ElementAt(i).Value.Key;
                values[i]  = inputItems.ElementAt(i).Value.Value;
            }

            // Solve
            int[,] m = new int[numberOfItems, knapsackCapacity];

            for (int i = 1; i < numberOfItems; i++)
            {
                for (int j = 0; j < knapsackCapacity; j++)
                {
                    if (weigths[i] <= j)
                    {
                        m[i, j] = Math.Max(m[i - 1, j], m[i - 1, j - weigths[i]] + values[i]);
                    }
                    else
                    {
                        m[i, j] = m[i - 1, j];
                    }
                }
            }

            Console.WriteLine(m[m.GetLength(0) - 1, m.GetLength(1) - 1]);
        }
        /// <summary>
        /// Count the number of query executions with the given parameters
        /// </summary>
        /// <param name="parameters">
        /// The parameters with which the query should have been executed
        /// </param>
        /// <param name="queries">
        /// The executed query records
        /// </param>
        /// <returns>
        /// The number of matches found
        /// </returns>
        private int CountQueryWithParameters(IDictionary <string, object> parameters, IEnumerable <ExecutedQuery> queries)
        {
            int matches = 0;

            foreach (var query in queries)
            {
                bool good = true;

                if ((null == query.Parameters) || (query.Parameters.Count != parameters.Count))
                {
                    continue;
                }

                for (int index = 0; index < parameters.Count; index++)
                {
                    if ((!String.Equals(parameters.ElementAt(index).Key, query.Parameters.ElementAt(index).Key)) ||
                        (!Object.Equals(parameters.ElementAt(index).Value, query.Parameters.ElementAt(index).Value)))
                    {
                        good = false;
                        break;
                    }
                }

                if (good)
                {
                    matches++;
                }
            }

            return(matches);
        }
Beispiel #11
0
        public void Get_ProductByPrimaryKey_ReturnsAProduct()
        {
            var    guid = Guid.NewGuid();
            string sql  = null;
            IDictionary <string, object> parameters = null;

            Jaunty.OnSelecting += (sender, args) =>
            {
                if (((Guid)sender).Equals(guid))
                {
                    sql        = args.Sql;
                    parameters = args.Parameters;
                }
            };

            Product product = northwind.Connection.Get <Product, int>(1, token: guid);

            Assert.Equal(1, product.ProductId);

            Assert.Equal("SELECT ProductId, ProductName, SupplierId, CategoryId, QuantityPerUnit, UnitPrice, UnitsInStock, " +
                         "UnitsOnOrder, ReorderLevel, Discontinued " +
                         "FROM Products " +
                         "WHERE ProductId = @ProductId;", sql);
            Assert.Equal("ProductId", parameters.ElementAt(0).Key);
            Assert.Equal(1, parameters.ElementAt(0).Value);

            Assert.NotNull(product);
            Assert.True(product.ProductId > 0);
        }
 /// <summary>
 /// Dispose managed and unmanaged resources.
 /// </summary>
 /// <param name="disposing">Indicates whether all managed resources should be disposed.</param>
 protected virtual void Dispose(bool disposing)
 {
     if (_disposed)
     {
         return;
     }
     // Dispose all unmanaged resources.
     lock (_syncRoot)
     {
         while (_isCaching.Count > 0)
         {
             _isCaching.Clear();
         }
         while (_dataCache.Count > 0)
         {
             while (_dataCache.ElementAt(0).Value.Count > 0)
             {
                 _dataCache.ElementAt(0).Value.Clear();
             }
             _dataCache.Remove(_dataCache.ElementAt(0).Key);
         }
     }
     // Dispose all managed resources.
     if (disposing)
     {
     }
     _disposed = true;
 }
Beispiel #13
0
        public void SelectByFluent_Products_ReturnsAListOfProductsWhereProductIdIs1AndCategoryIdIs1()
        {
            var    guid = Guid.NewGuid();
            string sql  = null;
            IDictionary <string, object> parameters = null;

            Jaunty.OnSelecting += (sender, args) =>
            {
                if (((Guid)sender).Equals(guid))
                {
                    sql        = args.Sql;
                    parameters = args.Parameters;
                }
            };

            var products = northwind.Connection.From <Product>()
                           .Where("SupplierId", 1)
                           .AndWhere("CategoryId", 1)
                           .Select <Product>(token: guid)
                           .ToList();

            Assert.Equal("SELECT ProductId, ProductName, SupplierId, CategoryId, QuantityPerUnit, UnitPrice, UnitsInStock, " +
                         "UnitsOnOrder, ReorderLevel, Discontinued " +
                         "FROM Products " +
                         "WHERE SupplierId = @SupplierId AND CategoryId = @CategoryId ", sql);
            Assert.Equal("SupplierId", parameters.ElementAt(0).Key);
            Assert.Equal(1, parameters.ElementAt(0).Value);
            Assert.Equal("CategoryId", parameters.ElementAt(1).Key);
            Assert.Equal(1, parameters.ElementAt(1).Value);

            Assert.NotEmpty(products);
            Assert.True(products[0].ProductId > 0);
        }
Beispiel #14
0
        public void SelectByFluent_Products_ReturnsAListOfCategoriesInnerJoinedToProductsWhereCategoryNameIsProduce()
        {
            var    guid = Guid.NewGuid();
            string sql  = null;
            IDictionary <string, object> parameters = null;

            Jaunty.OnSelecting += (sender, args) =>
            {
                if (((Guid)sender).Equals(guid))
                {
                    sql        = args.Sql;
                    parameters = args.Parameters;
                }
            };

            var categories = northwind.Connection.From <Product>()
                             .InnerJoin <Category>()
                             .On("Products.CategoryId", "Categories.CategoryId")
                             .Where("CategoryName", "Produce")
                             .Select <Category>(token: guid)
                             .ToList();

            Assert.Equal("SELECT Categories.CategoryId, Categories.CategoryName, Categories.Description, Categories.Picture " +
                         "FROM Products " +
                         "INNER JOIN Categories " +
                         "ON Products.CategoryId = Categories.CategoryId " +
                         "WHERE CategoryName = @CategoryName ", sql);
            Assert.Equal("CategoryName", parameters.ElementAt(0).Key);
            Assert.Equal("Produce", parameters.ElementAt(0).Value);

            Assert.NotEmpty(categories);
            Assert.True(categories[0].CategoryId > 0);
        }
        public void UriSlashPath()
        {
            var uri = new Uri("http://localhost:8080/?param1=value1&param2=value2&param3=value3");
            var d   = new QueryStringDecoder(uri);

            Assert.Equal("/", d.Path);
            IDictionary <string, List <string> > parameters = d.Parameters;

            Assert.Equal(3, parameters.Count);

            KeyValuePair <string, List <string> > entry = parameters.ElementAt(0);

            Assert.Equal("param1", entry.Key);
            Assert.Single(entry.Value);
            Assert.Equal("value1", entry.Value[0]);

            entry = parameters.ElementAt(1);
            Assert.Equal("param2", entry.Key);
            Assert.Single(entry.Value);
            Assert.Equal("value2", entry.Value[0]);

            entry = parameters.ElementAt(2);
            Assert.Equal("param3", entry.Key);
            Assert.Single(entry.Value);
            Assert.Equal("value3", entry.Value[0]);
        }
        public void UriNoPath()
        {
            var uri = new Uri("http://localhost:8080?param1=value1&param2=value2&param3=value3");
            var d   = new QueryStringDecoder(uri);

            // The path component cannot be empty string,
            // if there are no path component, it shoudl be '/' as above UriSlashPath test
            Assert.Equal("/", d.Path);
            IDictionary <string, List <string> > parameters = d.Parameters;

            Assert.Equal(3, parameters.Count);

            KeyValuePair <string, List <string> > entry = parameters.ElementAt(0);

            Assert.Equal("param1", entry.Key);
            Assert.Single(entry.Value);
            Assert.Equal("value1", entry.Value[0]);

            entry = parameters.ElementAt(1);
            Assert.Equal("param2", entry.Key);
            Assert.Single(entry.Value);
            Assert.Equal("value2", entry.Value[0]);

            entry = parameters.ElementAt(2);
            Assert.Equal("param3", entry.Key);
            Assert.Single(entry.Value);
            Assert.Equal("value3", entry.Value[0]);
        }
Beispiel #17
0
 private void setWordsOnButtons(IDictionary <String, String> wordsMap)
 {
     btTranslate1.Text = wordsMap.ElementAt(0).Value;
     btTranslate2.Text = wordsMap.ElementAt(1).Value;
     btTranslate3.Text = wordsMap.ElementAt(2).Value;
     btTranslate4.Text = wordsMap.ElementAt(3).Value;
 }
Beispiel #18
0
        private Dictionary <DateTime, long> GetTimelineStats(FbConnection connection,
                                                             IDictionary <string, DateTime> keyMaps)
        {
            string sqlQuery = string.Format(@"
                SELECT ""KEY"" AS ""Key"", COUNT(""VALUE"") AS ""Count"" 
                FROM ""{0}.COUNTER""
                GROUP BY ""KEY""
                HAVING ""KEY"" IN ('{1}')", _options.Prefix, string.Join("','", keyMaps.Keys));

            var valuesMap = connection.Query(
                sqlQuery,
                new { keys = keyMaps.Keys })
                            .ToDictionary(x => (string)x.Key, x => (long)x.Count);

            foreach (var key in keyMaps.Keys)
            {
                if (!valuesMap.ContainsKey(key))
                {
                    valuesMap.Add(key, 0);
                }
            }

            var result = new Dictionary <DateTime, long>();

            for (var i = 0; i < keyMaps.Count; i++)
            {
                var value = valuesMap[keyMaps.ElementAt(i).Key];
                result.Add(keyMaps.ElementAt(i).Value, value);
            }

            return(result);
        }
Beispiel #19
0
        private Dictionary <DateTime, long> GetTimelineStats(
            DbConnection connection,
            IDictionary <string, DateTime> keyMaps)
        {
            string sqlQuery =
                $@"select [Key], [Value] as [Count] from [{_storage.SchemaName}].AggregatedCounter with (nolock, forceseek)
where [Key] in @keys";

            var valuesMap = connection.Query(
                sqlQuery,
                new { keys = keyMaps.Keys },
                commandTimeout: _storage.CommandTimeout)
                            .ToDictionary(x => (string)x.Key, x => (long)x.Count);

            foreach (var key in keyMaps.Keys)
            {
                if (!valuesMap.ContainsKey(key))
                {
                    valuesMap.Add(key, 0);
                }
            }

            var result = new Dictionary <DateTime, long>();

            for (var i = 0; i < keyMaps.Count; i++)
            {
                var value = valuesMap[keyMaps.ElementAt(i).Key];
                result.Add(keyMaps.ElementAt(i).Value, value);
            }

            return(result);
        }
        private Dictionary <DateTime, long> GetTimelineStats(IDbConnection connection,
                                                             IDictionary <string, DateTime> keyMaps)
        {
            const string sqlQuery = @"
select [Key], [Value] as Count from [HangFire.AggregatedCounter]
where [Key] in @keys";

            var valuesMap = connection.Query(
                sqlQuery,
                new { keys = keyMaps.Keys })
                            .ToDictionary(x => (string)x.Key, x => (long)x.Count);

            foreach (var key in keyMaps.Keys)
            {
                if (!valuesMap.ContainsKey(key))
                {
                    valuesMap.Add(key, 0);
                }
            }

            var result = new Dictionary <DateTime, long>();

            for (var i = 0; i < keyMaps.Count; i++)
            {
                var value = valuesMap[keyMaps.ElementAt(i).Key];
                result.Add(keyMaps.ElementAt(i).Value, value);
            }

            return(result);
        }
        public void InvokeVote()
        {
            Random rnd        = new Random();
            var    nextLeader = wsDict.ElementAt(rnd.Next(0, wsDict.Count)).Value;

            nextLeader.Send("You Are Next Leader");
        }
Beispiel #22
0
        public async Task get_with_two_inner_joins_and_where_clause_using_fluent_Select_returns_a_collection_of_orders()
        {
            var    ticket = new Ticket("fluent select orders from products inner joined to order details inner joined to order where product id is 1");
            string sql    = null;
            IDictionary <string, object> parameters = null;

            Jaunty.OnSelecting += (sender, args) =>
            {
                sql        = args.Sql;
                parameters = args.Parameters;
            };

            var orders = (await northwind.Connection.From <Product>("p")
                          .InnerJoin <OrderDetail>("od")
                          .On("od.ProductId", "p.ProductId")
                          .InnerJoin <Order>("o")
                          .On("o.OrderId", "od.OrderId")
                          .Where("p.ProductId", 1)
                          .SelectAsync <Order>(ticket: ticket))
                         .ToList();

            Assert.Equal("SELECT o.OrderId, o.CustomerId, o.EmployeeId, o.OrderDate, o.RequiredDate, o.ShippedDate, " +
                         "o.ShipVia, o.Freight, o.ShipName, o.ShipAddress, o.ShipCity, o.ShipRegion, o.ShipPostalCode, o.ShipCountry " +
                         "FROM Products p " +
                         "INNER JOIN \"Order Details\" od " +
                         "ON od.ProductId = p.ProductId " +
                         "INNER JOIN Orders o " +
                         "ON o.OrderId = od.OrderId " +
                         "WHERE p.ProductId = @p__ProductId;", sql);
            Assert.Equal("p__ProductId", parameters.ElementAt(0).Key);
            Assert.Equal(1, parameters.ElementAt(0).Value);

            Assert.NotEmpty(orders);
            Assert.True(!string.IsNullOrEmpty(orders[0].OrderId));
        }
Beispiel #23
0
        public async Task get_with_an_inner_join_plus_where_clause_using_fluent_Select_returns_a_collection_of_categories()
        {
            var    ticket = new Ticket("fluent select categories from products inner joined to categories where category name is produce");
            string sql    = null;
            IDictionary <string, object> parameters = null;

            Jaunty.OnSelecting += (sender, args) =>
            {
                sql        = args.Sql;
                parameters = args.Parameters;
            };

            var categories = (await northwind.Connection.From <Product>()
                              .InnerJoin <Category>()
                              .On("Products.CategoryId", "Categories.CategoryId")
                              .Where("CategoryName", "Produce")
                              .SelectAsync <Category>(ticket: ticket))
                             .ToList();

            Assert.Equal("SELECT Categories.CategoryId, Categories.CategoryName, Categories.Description, Categories.Picture " +
                         "FROM Products " +
                         "INNER JOIN Categories " +
                         "ON Products.CategoryId = Categories.CategoryId " +
                         "WHERE CategoryName = @CategoryName;", sql);
            Assert.Equal("CategoryName", parameters.ElementAt(0).Key);
            Assert.Equal("Produce", parameters.ElementAt(0).Value);

            Assert.NotEmpty(categories);
            Assert.True(categories[0].CategoryId > 0);
        }
        public void Using_XDocument_Gets_All_Stored_Values()
        {
            var culture    = CultureInfo.GetCultureInfo("en-US");
            var txtService = new LocalizedTextService(
                new Dictionary <CultureInfo, Lazy <XDocument> >
            {
                {
                    culture, new Lazy <XDocument>(() => new XDocument(
                                                      new XElement(
                                                          "language",
                                                          new XElement("area", new XAttribute("alias", "testArea1"),
                                                                       new XElement("key", new XAttribute("alias", "testKey1"), "testValue1"),
                                                                       new XElement("key", new XAttribute("alias", "testKey2"), "testValue2")),
                                                          new XElement("area", new XAttribute("alias", "testArea2"),
                                                                       new XElement("key", new XAttribute("alias", "blah1"), "blahValue1"),
                                                                       new XElement("key", new XAttribute("alias", "blah2"), "blahValue2")))))
                }
            }, s_loggerFactory.CreateLogger <LocalizedTextService>());

            IDictionary <string, string> result = txtService.GetAllStoredValues(culture);

            Assert.AreEqual(4, result.Count());
            Assert.AreEqual("testArea1/testKey1", result.ElementAt(0).Key);
            Assert.AreEqual("testArea1/testKey2", result.ElementAt(1).Key);
            Assert.AreEqual("testArea2/blah1", result.ElementAt(2).Key);
            Assert.AreEqual("testArea2/blah2", result.ElementAt(3).Key);
            Assert.AreEqual("testValue1", result["testArea1/testKey1"]);
            Assert.AreEqual("testValue2", result["testArea1/testKey2"]);
            Assert.AreEqual("blahValue1", result["testArea2/blah1"]);
            Assert.AreEqual("blahValue2", result["testArea2/blah2"]);
        }
Beispiel #25
0
        public async Task get_a_single_item_using_fluent_Select_returns_a_product()
        {
            var    ticket = new Ticket("fluent select products where product id is 12");
            string sql    = null;
            IDictionary <string, object> parameters = null;

            Jaunty.OnSelecting += (sender, args) =>
            {
                sql        = args.Sql;
                parameters = args.Parameters;
            };

            Product product = (await northwind.Connection.From <Product>()
                               .Where("ProductId", 12)
                               .SelectAsync <Product>(ticket: ticket))
                              .SingleOrDefault();

            Assert.Equal("SELECT ProductId, ProductName, SupplierId, CategoryId, QuantityPerUnit, UnitPrice, UnitsInStock, " +
                         "UnitsOnOrder, ReorderLevel, Discontinued " +
                         "FROM Products " +
                         "WHERE ProductId = @ProductId;", sql);
            Assert.Equal("ProductId", parameters.ElementAt(0).Key);
            Assert.Equal(12, parameters.ElementAt(0).Value);

            Assert.NotNull(product);
            Assert.True(product.ProductId > 0);
        }
Beispiel #26
0
        public async Task get_by_where_using_Select_returns_a_collection_of_products()
        {
            var    ticket = new Ticket("fluent select products where supplier id is 1 and category id is 1");
            string sql    = null;
            IDictionary <string, object> parameters = null;

            Jaunty.OnSelecting += (sender, args) =>
            {
                sql        = args.Sql;
                parameters = args.Parameters;
            };

            var products = (await northwind.Connection.From <Product>()
                            .Where("SupplierId", 1)
                            .AndWhere("CategoryId", 1)
                            .SelectAsync <Product>(ticket: ticket))
                           .ToList();

            Assert.Equal("SELECT ProductId, ProductName, SupplierId, CategoryId, QuantityPerUnit, UnitPrice, UnitsInStock, " +
                         "UnitsOnOrder, ReorderLevel, Discontinued " +
                         "FROM Products " +
                         "WHERE SupplierId = @SupplierId AND CategoryId = @CategoryId;", sql);
            Assert.Equal("SupplierId", parameters.ElementAt(0).Key);
            Assert.Equal(1, parameters.ElementAt(0).Value);
            Assert.Equal("CategoryId", parameters.ElementAt(1).Key);
            Assert.Equal(1, parameters.ElementAt(1).Value);

            Assert.NotEmpty(products);
            Assert.True(products[0].ProductId > 0);
        }
Beispiel #27
0
        public async Task get_using_lambda_Query_returns_a_collection_of_products()
        {
            var    ticket = new Ticket("select product by lambda query");
            string sql    = null;
            IDictionary <string, object> parameters = null;

            Jaunty.OnSelecting += (sender, args) =>
            {
                sql        = args.Sql;
                parameters = args.Parameters;
            };

            var products = (await northwind.Connection.QueryAsync <Product>(x => x.CategoryId == 1 && x.SupplierId == 1, ticket: ticket)).ToList();

            Assert.Equal("SELECT ProductId, ProductName, SupplierId, CategoryId, QuantityPerUnit, UnitPrice, UnitsInStock, " +
                         "UnitsOnOrder, ReorderLevel, Discontinued " +
                         "FROM Products " +
                         "WHERE CategoryId = @CategoryId AND SupplierId = @SupplierId;", sql);
            Assert.Equal("CategoryId", parameters.ElementAt(0).Key);
            Assert.Equal(1, parameters.ElementAt(0).Value);
            Assert.Equal("SupplierId", parameters.ElementAt(1).Key);
            Assert.Equal(1, parameters.ElementAt(1).Value);

            Assert.NotEmpty(products);
            Assert.True(products[0].ProductId > 0);
        }
        private void majExpression()
        {
            this.ExpressionDiv.Controls.Clear();
            IDictionary <int, string> dict1 = (IDictionary <int, string>)ViewState["expressionsAttSalaire"];
            IDictionary <int, string> dict2 = (IDictionary <int, string>)ViewState["expressionsRemuneration"];
            IDictionary <int, string> dict3 = (IDictionary <int, string>)ViewState["expressionsCotisation"];
            IDictionary <int, string> dict4 = (IDictionary <int, string>)ViewState["expressionsArithmethiques"];

            for (int i = 0; i < (int)ViewState["expressionsIndice"]; i++)
            {
                Label lbl    = new Label();
                bool  trouve = false;
                int   j      = 0;
                while ((!trouve) && (j < dict1.Count))
                {
                    if (dict1.ElementAt(j).Key == i)
                    {
                        lbl.Text      = dict1.ElementAt(j).Value;
                        lbl.ForeColor = System.Drawing.Color.LawnGreen;
                        trouve        = true;
                    }
                    j++;
                }
                j = 0;
                while ((!trouve) && (j < dict2.Count))
                {
                    if (dict2.ElementAt(j).Key == i)
                    {
                        lbl.Text      = dict2.ElementAt(j).Value;
                        lbl.ForeColor = System.Drawing.Color.Blue;
                        trouve        = true;
                    }
                    j++;
                }
                j = 0;
                while ((!trouve) && (j < dict3.Count))
                {
                    if (dict3.ElementAt(j).Key == i)
                    {
                        lbl.Text      = dict3.ElementAt(j).Value;
                        lbl.ForeColor = System.Drawing.Color.Brown;
                        trouve        = true;
                    }
                    j++;
                }
                j = 0;
                while ((!trouve) && (j < dict4.Count))
                {
                    if (dict4.ElementAt(j).Key == i)
                    {
                        lbl.Text      = dict4.ElementAt(j).Value;
                        lbl.ForeColor = System.Drawing.Color.DarkSalmon;
                        trouve        = true;
                    }
                    j++;
                }

                this.ExpressionDiv.Controls.Add(lbl);
            }
        }
Beispiel #29
0
    private void EnsureClosed()
    {
        // For each vertex, check if it has 2 adjacent vertices.
        // If not, then look for the closest other vertex and make them adjacent.
        // TODO: what to do if closest already has 2 adjacent vertices?
        for (int i = 0; i < _vertices.Count - 1; i++)
        {
            KeyValuePair <Vector2, List <Vector2> > currentVertex = _vertices.ElementAt(i);

            if (currentVertex.Value.Count < 2)
            {
                KeyValuePair <Vector2, List <Vector2> > closestVertex = _vertices.ElementAt(i + 1);

                for (int j = i + 2; j < _vertices.Count; j++)
                {
                    KeyValuePair <Vector2, List <Vector2> > nextVertex = _vertices.ElementAt(j);

                    if (Mathf.Abs(Vector2.Distance(currentVertex.Key, nextVertex.Key))
                        < Mathf.Abs(Vector2.Distance(currentVertex.Key, closestVertex.Key)))
                    {
                        closestVertex = nextVertex;
                    }
                }

                Debug.Assert(closestVertex.Value.Count < 2, "vertex on cut plane is becoming adjacent to more than 2 other vertices...");

                currentVertex.Value.Add(closestVertex.Key);
                closestVertex.Value.Add(currentVertex.Key);
            }
        }
    }
        public double  RemoveEdgeMax()
        {
            IDictionary <double, int> histogramresult = GetHistogramGraphNormalized();
            double NewMax = m_maxValue;

            if (histogramresult.ElementAt(histogramresult.Count - 1).Value > Threshold)
            {
                return(NewMax);
            }
            if (histogramresult.Count() < 2)
            {
                return(NewMax);
            }
            for (int i = histogramresult.Count - 2; i > 0; i--)
            {
                if (histogramresult.ElementAt(i).Value < Threshold)
                {
                    NewMax = (histogramresult.ElementAt(i).Key + histogramresult.ElementAt(i - 1).Key) / 2;
                }
                else
                {
                    break;
                }
            }

            return(NewMax);
        }
        public string Serialize(IDictionary<string, int> dictionary)
        {
            Precondition.EnsureNotNull("dictionary", dictionary);

            TreeMapNode root = new TreeMapNode();

            int size = dictionary.Count;

            var colors = ColorHelper.GetGradientHexColors(
                //ColorTranslator.FromHtml("#EBEB35"),
                    Color.Yellow,
                    Color.ForestGreen,
                    Color.Red, size)
                .ToList();

            for (int i = 0; i < size; i++)
            {
                var item = dictionary.ElementAt(i);

                TreeMapNode child = new TreeMapNode { Id = item.Key, Name = item.Key };
                TreeMapNodeItem data = new TreeMapNodeItem
                {
                    Area = item.Value,
                    Color = colors[i],
                    Count = item.Value.ToString(CultureInfo.InvariantCulture)
                };

                child.Data = data;
                root.Children.Add(child);
            }

            return JsonConvert.SerializeObject(root);
        }
Beispiel #32
0
 public static string ToJson(IDictionary<string, object> dictionary, string objectName = null)
 {
     if (!string.IsNullOrWhiteSpace(objectName))
         objectName = "{{\"{0}\":".Fmt(objectName);
     var stringBuilder = new StringBuilder(objectName);
     for (var i = 0; i < dictionary.Count; i++)
     {
         var kvp = dictionary.ElementAt(i);
         if (i == 0) stringBuilder.Append("{");
         if (kvp.Value is IDictionary<string, object>)
         {
             stringBuilder.Append("\"{0}\":".Fmt(kvp.Key));
             stringBuilder.Append(ToJson((IDictionary<string, object>)kvp.Value));
         }
         else if (kvp.Value is dynamic[])
         {
             stringBuilder.Append("\"{0}\":[".Fmt(kvp.Key));
             foreach (var dyn in (dynamic[])kvp.Value)
             {
                 stringBuilder.Append(ToJson(dyn));
             }
             stringBuilder.Append("],");
         }
         else
         {
             stringBuilder.Append("\"{0}\":{1}".Fmt(kvp.Key, JsonSerializer.SerializeToString(kvp.Value)));
             stringBuilder.Append(i < dictionary.Count - 1 ? "," : "");
         }
         if (i == dictionary.Count - 1) stringBuilder.Append("}");
     }
     if (!string.IsNullOrWhiteSpace(objectName))
         stringBuilder.Append("}");
     return stringBuilder.ToString().Replace("}{", "},{").Replace("}\"", "},\"");
 }
Beispiel #33
0
        public GraphWindow(IDictionary<DateTime, Decimal> balance)
        {
            InitializeComponent();
            timeBalance = balance;

            startToShow = DateTime.Now.Date;
            endToShow = new DateTime(startToShow.Year, startToShow.Month, 1);
            minboundary = new DateTime(
                balance.ElementAt(0).Key.Year,
                balance.ElementAt(0).Key.Month,
                1);

            ChangeDataByBoundaries();
            chart.Series[0].ChartType = SeriesChartType.Line;
            chart.Series[0].BorderWidth = 4;
            SetupChartArea();
            UpdateLabels();
        }
		public static void ShouldMatch(this IEnumerable<Model.Genre> genres, IDictionary<string,string> mappings)
		{
			for (int i = 0; i < genres.Count(); i++)
			{
				var genre = genres.ElementAt(i);
				var mapping = mappings.ElementAt(i);
				Assert.AreEqual(genre.Id, mapping.Key);
				Assert.AreEqual(genre.Name, mapping.Value);
			}
		}
Beispiel #35
0
        public static string GetQueryString(IDictionary<string, string> dictionary)
        {
            if (dictionary == null || dictionary.Count == 0) {
                throw new ArgumentNullException("dictionary");
            }

            var query = new StringBuilder();
            var first = dictionary.ElementAt(0);

            query.Append(first.Key + "=" + first.Value);

            if (dictionary.Count > 1) {
                for (int i = 1; i < dictionary.Count; i++) {
                    var d = dictionary.ElementAt(i);
                    query.Append("&" + d.Key + "=" + d.Value);
                }
            }

            return query.ToString();
        }
Beispiel #36
0
        public JsonExpression(IDictionary<String, TypeInferenceUnit> props)
            : base(ExpressionType.Json, props.Values)
        {
            // bug: jeez.. wtf alert
//            Props = props;

            Props = new Dictionary<String, TypeInferenceUnit>();
            for (var i = 0; i < props.Count; i++)
            {
                Props.Add("Field" + i, props.ElementAt(i).Value);
            }
        }
        public NodeFactory(NodeFuncGenerator funcGenerator, IDictionary<NodeType, double> probabilityMap)
        {
            if (probabilityMap.Count == 0)
                throw new ArgumentException();

            foreach (var item in probabilityMap)
            {
                if (item.Value < 0)
                    throw new ArgumentException();
            }

            funcGenerator_ = funcGenerator;

            typeDistributionMap_ = new Dictionary<NodeType, double>();
            double sum = 0.0d;
            for (int i = 0; i < probabilityMap.Count; i++)
            {
                sum += probabilityMap.ElementAt(i).Value;
                typeDistributionMap_.Add(probabilityMap.ElementAt(i).Key, sum);
            }
            typeDistributionMapMax_ = sum;
        }
        private string GetDefaultsAsJson(IDictionary<string, object> defaults)
        {
            StringBuilder defaultsAsJson = new StringBuilder();
            if (defaults.Count > 0)
            {
                defaultsAsJson.Append(", {");

                for (int i = 0; i < defaults.Count; i++)
                {
                    var keyPair = defaults.ElementAt(i);
                    defaultsAsJson.AppendFormat("{0}:'{1}'", keyPair.Key, keyPair.Value);

                    if (!keyPair.Equals(defaults.Last()))
                        defaultsAsJson.Append(",");
                }

                defaultsAsJson.Append("}");
            }
            return defaultsAsJson.ToString();
        }
Beispiel #39
0
        private ExpressionInfo HandleUpdateAddOptions(FunctionCall call, ExpressionInfo exprInfo, IVulnerabilityStorage storage, 
                                                      IDictionary<uint, ExpressionInfo> argumentInfos, AnalysisStacks analysisStacks)
        {
            XmlNode firstArgument;
            XmlNode secondArgument;

            string optionKeyValue;

            if (call.Arguments.TryGetValue(1, out firstArgument) &&
                call.Arguments.TryGetValue(2, out secondArgument) &&
                TryGetOptionKeyValue(firstArgument, argumentInfos[1], out optionKeyValue))
            {
                foreach (var sqliTaintSet in argumentInfos.ElementAt(1).Value.ExpressionTaint.SqliTaint)
                {
                    if (sqliTaintSet.TaintTag == SQLITaint.None)
                    {
                        continue;
                    }
                    string varName = (sqliTaintSet.InitialTaintedVariable ?? "???");
                    string message = "Stored SQLI found - Ingoing: " + varName +
                                    " on line: " + call.StartLine + " in file: " + analysisStacks.IncludeStack.Peek();

                    storage.AddPossibleStoredVulnerability(new StoredVulnerabilityInfo()
                    {
                        IncludeStack = analysisStacks.IncludeStack.ToImmutableStack(),
                        CallStack = analysisStacks.CallStack.ToImmutableStack(),
                        Message = message,
                        VulnerabilityType = VulnType.SQL,
                        PossibleStoredVuln = new StoredVulnInfo()
                                             {
                                                 ICantFeelIt = IsItInYet.YesItsGoingIn,
                                                 StorageName = optionKeyValue,
                                                 StorageOrigin = "Options",
                                                 Taint = new TaintSets(sqliTaintSet, new XSSTaintSet())
                                             }
                    });
                }
                foreach (var xssTaintSet in argumentInfos.ElementAt(1).Value.ExpressionTaint.XssTaint)
                {
                    if (xssTaintSet.TaintTag == XSSTaint.None)
                    {
                        continue;
                    }
                    string varName = (xssTaintSet.InitialTaintedVariable ?? "???");
                    string message = "Stored XSS found - Ingoing: " + varName +
                                    " on line: " + call.StartLine + " in file: " + analysisStacks.IncludeStack.Peek();

                    storage.AddPossibleStoredVulnerability(new StoredVulnerabilityInfo()
                    {
                        IncludeStack = analysisStacks.IncludeStack.ToImmutableStack(),
                        CallStack = analysisStacks.CallStack.ToImmutableStack(),
                        Message = message,
                        VulnerabilityType = VulnType.XSS,
                        PossibleStoredVuln = new StoredVulnInfo()
                                            {
                                                ICantFeelIt = IsItInYet.YesItsGoingIn,
                                                StorageName = optionKeyValue,
                                                StorageOrigin = "Options",
                                                Taint = new TaintSets(new SQLITaintSet(), xssTaintSet)
                                            }
                    });
                }
            }

            return exprInfo;
        }
        /// <summary>
        /// Convert a given map to a JSON object.
        /// </summary>
        /// <param name="values">the map of values to be converted</param>
        /// <returns></returns>
        private IJSON MapToJSON( IDictionary<string, string> values )
        {
            using ( var stream = new MemoryStream() ) {

                var writer = new CBORWriter( stream );

                writer.WriteObject();
                for ( int i = 0; i < values.Count; i++ ) {
                    writer.Write( values.ElementAt( i ).Key );
                    writer.Write( values.ElementAt( i ).Value );
                }
                writer.WriteBreak();

                return jsonDataType.ReadValue( stream.ToArray() );
            }
        }
Beispiel #41
0
 /// <summary>
 /// Generates srcML from a file
 /// </summary>
 /// <param name="fileNames">An enumerable of filenames</param>
 /// <param name="xmlFileName">the output file name</param>
 /// <param name="language">The language to use</param>
 /// <param name="namespaceArguments">additional arguments</param>
 /// <param name="extensionMapping">an extension mapping</param>
 public void GenerateSrcMLFromFiles(ICollection<string> fileNames, string xmlFileName, Language language, ICollection<UInt32> namespaceArguments, IDictionary<string, Language> extensionMapping) {
     UInt32 arguments = GenerateArguments(namespaceArguments);
     try {
         using (Archive srcmlArchive = new Archive()) {
             if (Convert.ToBoolean(extensionMapping.Count())) {
                 srcmlArchive.RegisterFileExtension(extensionMapping.ElementAt(0).Key, extensionMapping.ElementAt(0).Value.ToString());
             }
             foreach (string file in fileNames) {
                 using (Unit srcmlUnit = new Unit()) {
                     srcmlUnit.SetUnitFilename(file);
                     srcmlUnit.SetUnitLanguage(LibSrcMLRunner.SrcMLLanguages.SRCML_LANGUAGE_CXX);
                     srcmlArchive.AddUnit(srcmlUnit);
                 }
             }
             srcmlArchive.SetOutputFile(xmlFileName);
             RunSrcML(srcmlArchive, LibSrcMLRunner.SrcmlCreateArchiveFtF);
         }
     }
     catch (Exception e) {
         throw new SrcMLException(e.Message, e);
     }
 }