コード例 #1
0
        public void SelectAnonymObject()
        {
            var expected = "SELECT Orders.OrdersID, ProductID, UnitPrice, Quantity, Discount FROM Orders JOIN OrderDetails ON (OrderDetails.OrdersID = Orders.OrdersID)";

            var provider = new ContextProvider(new Mock.ConnectionProvider());
            provider.Interceptor(() => new
            {
                ProductID = 0,
                Quantity = 0
            })
            .BeforeExecute(s => Assert.AreEqual(s.QueryString.Flatten(), expected));

            using (var context = provider.Open())
            {
                var items = context.From<Orders>()
                    .Map(o => o.OrdersID)
                    .Join<OrderDetails>((od, o) => od.OrdersID == o.OrdersID)
                    .Select(od => new
                    {
                        ProductID = od.ProductID,
                        Quantity = od.Quantity
                    });

                items.Any();
            }
        }
コード例 #2
0
 public void ExecuteSelectStatement()
 {
     var provider = new ContextProvider(new Mock.ConnectionProvider());
     provider.Interceptor<Orders>().BeforeExecute(s => Assert.AreEqual(s.QueryString.Flatten(), "SELECT * FROM Orders"));
     using (var context = provider.Open())
     {
         // select with string select statement
         var orders = context.Execute<Orders>("SELECT * FROM Orders");
     }
 }
コード例 #3
0
 public void ExecuteSqlStatement()
 {
     var provider = new ContextProvider(new Mock.ConnectionProvider());
     provider.Interceptor<Orders>().BeforeExecute(s => Assert.AreEqual(s.QueryString.Flatten(), "UPDATE Orders SET Freight = 20 WHERE OrdersID = 10000000"));
     using (var context = provider.Open())
     {
         // select with string select statement
         context.Execute("UPDATE Orders SET Freight = 20 WHERE OrdersID = 10000000");
     }
 }
コード例 #4
0
ファイル: ScenarioRunner.cs プロジェクト: vfarah-net/LightBDD
 private static object InstantiateSubStepsContext(ContextProvider provider)
 {
     try
     {
         return(provider.GetContext());
     }
     catch (Exception e)
     {
         throw new InvalidOperationException($"Sub-steps context initialization failed: {e.Message}", e);
     }
 }
コード例 #5
0
        public static ISessionContext Context(string context)
        {
            var config = new TestServices().Configuration;
            var mock   = new Mock <ILogger <ContextProvider> >();
            ILogger <ContextProvider> logger          = mock.Object;
            ContextProvider           contextProvider = new ContextProvider(config, logger);
            SessionContext            ctx             = (from c in contextProvider.Items where c.Name == context select c).FirstOrDefault();

            ctx.SessionDriver.Connect(ctx.configContext.conn);
            return(ctx);
        }
コード例 #6
0
ファイル: NewTestForm.cs プロジェクト: Arnis1305/HunterGuide
        public NewTestForm()
        {
            InitializeComponent();
            StartPosition         = FormStartPosition.CenterScreen;
            mapper                = AutoMapperProvider.GetIMapper();
            context               = ContextProvider.GetApplicationContext();
            newTestModelValidator = new NewTestModelValidator();

            SetItemsToTypeComboBox();
            SetItemsToTopicComboBox();
        }
コード例 #7
0
        public async Task <string> CheckEmail(string email)
        {
            var user = ContextProvider.GetRepository <IUserRepository>().GetByEmail(email);

            if (user == null)
            {
                throw new CashSchedulerException("There is no such user", new[] { nameof(email) });
            }

            int allowedVerificationInterval = Convert.ToInt32(Configuration["App:Auth:EmailVerificationTokenLifetime"]);
            var verificationCodeService     = ContextProvider.GetService <IUserEmailVerificationCodeService>();

            var existingVerificationCode = verificationCodeService.GetByUserId(user.Id);

            if (existingVerificationCode != null)
            {
                var difference = DateTime.UtcNow.Subtract(existingVerificationCode.ExpiredDate);

                if (difference.TotalSeconds < 0 &&
                    Math.Abs(difference.TotalSeconds) < allowedVerificationInterval * 60 &&
                    !bool.Parse(Configuration["App:Auth:SkipAuth"]))
                {
                    throw new CashSchedulerException(
                              "We already sent you a code. " +
                              $"You can request it again in: {Math.Abs(difference.Minutes)}:{Math.Abs(difference.Seconds)}",
                              new[] { nameof(email) }
                              );
                }
            }

            var verificationCode = await verificationCodeService.Update(new UserEmailVerificationCode(
                                                                            email.Code(Configuration),
                                                                            DateTime.UtcNow.AddMinutes(allowedVerificationInterval),
                                                                            user
                                                                            ));

            var notificationDelegator = new NotificationDelegator();
            var template = notificationDelegator.GetTemplate(
                NotificationTemplateType.VerificationCode,
                new Dictionary <string, string> {
                { "code", verificationCode.Code }
            }
                );
            await Notificator.SendEmail(user.Email, template);

            await ContextProvider.GetService <IUserNotificationService>().Create(new UserNotification
            {
                Title   = template.Subject,
                Content = template.Body,
                User    = user
            });

            return(email);
        }
コード例 #8
0
ファイル: TestServices.cs プロジェクト: tmnkopp/BrowseOmatic
        public static ISessionContext Context(string context)
        {
            var config = new TestServices().Configuration;
            var mock   = new Mock <ILogger <ContextProvider> >();
            ILogger <ContextProvider> logger          = mock.Object;
            ContextProvider           contextProvider = new ContextProvider(config, logger);
            SessionContext            ctx             = contextProvider.Get(context);

            //ctx.SessionDriver.Connect(ctx.configContext.conn);
            return(ctx);
        }
コード例 #9
0
 public void UpdateTestWithKeyExpression()
 {
     var sql = "";
     var provider = new ContextProvider(new Mock.ConnectionProvider());
     provider.Interceptor<Warrior>().BeforeExecute(s => sql = s.QueryString.Flatten());
     using (var context = provider.Open())
     {
         context.Update(() => new Warrior { ID = 1, Race = "Elf", WeaponID = 2 }, e => e.ID);
         context.Commit();
     }
 }
コード例 #10
0
        public void SendRequest_AtUrlForAuthentication_StatusCodeIs200()
        {
            Uri landingUrl = new UriBuilder(ConfigHelper.Scheme, ConfigHelper.Host, ConfigHelper.Port, RouteProvider.OrganizationInfoRoute).Uri;
            Uri uri        = ContextProvider.AuthenticatedUrl(landingUrl);

            HttpWebRequest request = RequestProvider.CreateRequest(uri);

            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) {
                Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
            }
        }
コード例 #11
0
        public AdicionarDroneSteps(ScenarioContext scenarioContext)
        {
            _scenarioContext = scenarioContext;
            _context         = ContextProvider <Drone> .GetContext(null);

            _droneStatusExecutor   = Substitute.For <ICommandExecutor <DroneStatusResult> >();
            _statusDroneExecutor   = Substitute.For <ICommandExecutor <StatusDroneDto> >();
            _pedidoMongoRepository = Substitute.For <IPedidoMongoRepository>();
            _droneRepository       = new DroneRepository(_context, _statusDroneExecutor, _droneStatusExecutor, _pedidoMongoRepository);
            _droneService          = null;
            _droneFacade           = new DroneFacade(_droneService, _droneRepository);
        }
コード例 #12
0
 /// <summary>
 /// Asserts that <paramref name="actual"/> is false
 /// </summary>
 /// <param name="actual"></param>
 /// <param name="message"></param>
 /// <param name="contextProvider"></param>
 public static void AssertFalse(this bool actual, string message = null, ContextProvider contextProvider = null)
 {
     try
     {
         NUnit.Framework.Assert.That(actual, Is.False, message);
     }
     catch
     {
         contextProvider.Trace();
         throw;
     }
 }
コード例 #13
0
 public static void AssertNotNull <T>(this T actual, string message = null, ContextProvider contextProvider = null)
 {
     try
     {
         NUnit.Framework.Assert.That(actual, Is.Not.Null, message);
     }
     catch
     {
         contextProvider.Trace();
         throw;
     }
 }
コード例 #14
0
 public Presenter(IView view)
 {
     _view        = view;
     _view.Start += OnStart;
     _management  = new HouseManagement();
     _management.RequestAdded       += _view.OnRequestAdded;
     _management.RequestProcessed   += _view.OnRequestProcessed;
     _management.RequestPostponed   += _view.OnRequestPostponed;
     _management.RequestFinished    += _view.OnRequestFinished;
     _management.SimulationFinished += _view.OnSimulationFinished;
     ContextProvider.GetInstance().Context = SynchronizationContext.Current;
 }
コード例 #15
0
        public override string Format(string value)
        {
            int    stacks    = ContextProvider.GetPickupCount(modifyingIndices);
            string stacksStr = string.Empty;

            if (showStacks)
            {
                stacksStr += $" ({stacks})";
            }

            return($"\t{name}{stacksStr}: {base.Format(value)}");
        }
コード例 #16
0
 public StockFollower(YesterdayCandleData stock, ContextProvider contextProvider,
                      Action <PlacedOrder> addOrder,
                      Status?status = null)
 {
     Stock            = stock;
     _contextProvider = contextProvider;
     _addOrder        = addOrder;
     if (status != null)
     {
         Status = status;
     }
 }
コード例 #17
0
ファイル: UserMainForm.cs プロジェクト: Ozia123/HunterGuide
        public UserMainForm(ApplicationUser user)
        {
            InitializeComponent();

            context   = ContextProvider.GetApplicationContext();
            this.user = user;

            TestTopicsComboBox.Visible = false;
            TestNamesComboBox.Visible  = false;
            StartTestButton.Enabled    = false;
            SetItemsToTypeComboBox();
        }
コード例 #18
0
        public void UpdateTestWithKeyExpression_Fail()
        {
            var sql = "";
            var provider = new ContextProvider(new Mock.ConnectionProvider());
            provider.Interceptor<Warrior>().BeforeExecute(s => sql = s.QueryString.Flatten());
            using (var context = provider.Open())
            {
                ((Mock.ConnectionProvider)provider.ConnectionProvider).CheckCallbackCall = false;

                Assert.Throws<ArgumentException>(() => context.Update(() => new Warrior {ID = 1, Race = "Elf", WeaponID = 2}, e => e.ID == 1));
                context.Commit();
            }
        }
コード例 #19
0
 public static void DisposeObject(String instanceKey)
 {
     lock (AccessLock)
     {
         IDisposable obj = ContextProvider.GetItem <IDisposable>(instanceKey);
         if (obj == null)
         {
             return;
         }
         obj.Dispose();
         ContextProvider.SetItem <IDisposable>(instanceKey, null);
     }
 }
コード例 #20
0
 public bool UpdateChargeValue(OrderChargeValueModel model)
 {
     using (var context = ContextProvider.Provide())
     {
         var value = context.OrderChargeValues.FirstOrDefault(s => s.SubscriberId == model.SubscriberId && s.Id == model.Id);
         if (value == null)
         {
             return(false);
         }
         value.Charge = model.Charge;
         return(context.SaveChanges() > 0);
     }
 }
コード例 #21
0
        public void SendRequestWithBadKeys_ResponseInterpretationIs_InvalidSig()
        {
            ID2LUserContext badContext = ContextProvider.BadUserContext();
            HttpWebRequest  request    = RequestProvider.PrepareApiRequest(badContext, RouteProvider.OrganizationInfoRoute);

            try {
                using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { }
            } catch (WebException ex) {
                var exceptionWrapper = new D2LWebException(ex);
                var interpretation   = badContext.InterpretResult(exceptionWrapper);
                Assert.AreEqual(RequestResult.RESULT_INVALID_SIG, interpretation);
            }
        }
コード例 #22
0
        public Task <string> GenerateAppToken()
        {
            var user = ContextProvider.GetService <IUserService>().GetById();

            if (user == null)
            {
                throw new CashSchedulerException("Unauthorized", "401");
            }

            return(Task.FromResult(
                       user.GenerateToken(AuthOptions.TokenType.AppAccess, Configuration).token
                       ));
        }
コード例 #23
0
 /// <summary>
 /// Asserts that actual value follows <paramref name="expression"/> constrains
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="actual"></param>
 /// <param name="expression"></param>
 /// <param name="message"></param>
 /// <param name="contextProvider"></param>
 public static void Assert <T>(this T actual, IResolveConstraint expression, string message = null,
                               ContextProvider contextProvider = null)
 {
     try
     {
         NUnit.Framework.Assert.That(actual, expression, message);
     }
     catch
     {
         contextProvider.Trace();
         throw;
     }
 }
コード例 #24
0
 public void BeforeSave()
 {
     SaveMap = new Dictionary <Type, List <EntityInfo> >();
     EntityInfoGroups.ForEach(eg => {
         var entityInfos = eg.EntityInfos.Where(ei => ContextProvider.BeforeSaveEntity(ei)).ToList();
         SaveMap.Add(eg.EntityType, entityInfos);
     });
     SaveMap = ContextProvider.BeforeSaveEntities(SaveMap);
     EntitiesWithAutoGeneratedKeys = SaveMap
                                     .SelectMany(eiGrp => eiGrp.Value)
                                     .Where(ei => ei.AutoGeneratedKey != null && ei.EntityState != EntityState.Detached)
                                     .ToList();
 }
コード例 #25
0
 public void InsertWithAnonymObjectTest()
 {
     var sql = "";
     var provider = new ContextProvider(new Mock.ConnectionProvider());
     provider.Interceptor<Warrior>().BeforeExecute(s => sql = s.QueryString.Flatten());
     using (var context = provider.Open())
     {
         // insert all fields defined in the anonym object
         context.Insert<Warrior>(() => new { ID = 1, Race = "Dwarf" });
         context.Commit();
         Assert.AreEqual(sql, "INSERT INTO Warrior (ID, Race) VALUES (1, 'Dwarf')");
     }
 }
コード例 #26
0
        public void ExecutesPolicy()
        {
            var impl            = new Service();
            var executed        = false;
            var policyProvider  = new CallbackPolicyProvider((method, arguments) => executed = true);
            var contextProvider = new ContextProvider();
            var proxy           = PollyWrapper <IService> .Decorate(impl, policyProvider, contextProvider);

            var result = proxy[HelloWorld];

            result.ShouldBe(HelloWorld);
            executed.ShouldBeTrue();
        }
コード例 #27
0
ファイル: UserService.cs プロジェクト: treesan/taobao-alading
 public static void UpdateUser(User user)
 {
     using (AladingWebEntities context = ContextProvider.DataContext(ConnectionHelper.ConnectionString))
     {
         var old = context.User.FirstOrDefault(p => p.UserCode == user.UserCode);
         if (old != null)
         {
             context.Attach(old);
             context.ApplyPropertyChanges("User", user);
             context.SaveChanges();
         }
     }
 }
コード例 #28
0
 public bool Delete(Guid subscriberId, Guid chargeId)
 {
     using (var context = ContextProvider.Provide())
     {
         var charges = context.OrderChargeValues.Where(s => s.SubscriberId == subscriberId && s.ChargeId == chargeId).ToList();
         if (!charges.Any())
         {
             return(true);
         }
         context.OrderChargeValues.RemoveRange(charges);
         return(context.SaveChanges() > 0);
     }
 }
コード例 #29
0
 public static void UpdateShop(Shop shop)
 {
     using (AladingWebEntities context = ContextProvider.DataContext(ConnectionHelper.ConnectionString))
     {
         var old = context.Shop.FirstOrDefault(c => c.ShopCode == shop.ShopCode);
         if (old != null)
         {
             context.Attach(old);
             context.ApplyPropertyChanges("Shop", shop);
             context.SaveChanges();
         }
     }
 }
コード例 #30
0
        public CriarPedidoUnitTest()
        {
            _dataContext = ContextProvider <Pedido> .GetContext(null);

            _pedidoService         = Substitute.For <IPedidoService>();
            _clienteRepository     = Substitute.For <IClienteRepository>();
            _pedidoRepository      = Substitute.For <IPedidoRepository>();
            _pedidoDroneRepository = Substitute.For <IPedidoDroneRepository>();

            _droneRepository         = Substitute.For <IDroneRepository>();
            _pagamentoServiceFactory = Substitute.For <IPagamentoServiceFactory>();
            _pagamentoServico        = Substitute.For <IPagamentoServico>();
        }
コード例 #31
0
        public Task <UserNotification> Delete(int id)
        {
            var notificationRepository = ContextProvider.GetRepository <IUserNotificationRepository>();

            var targetNotification = notificationRepository.GetByKey(id);

            if (targetNotification == null)
            {
                throw new CashSchedulerException("There is no such notification");
            }

            return(notificationRepository.Delete(id));
        }
コード例 #32
0
        private Task HandleMockRequest(HttpContext ctx)
        {
            var mockId = ctx.GetRouteId();

            var path = mockId.Path.Substring(6);
            var id   = new RouteId(path, mockId.Verb);

            var requestContext = ContextProvider.GetContext(id, ctx);

            requestContext.Config.Handler = "mock";

            return(HandleRequest(requestContext, ctx.Response));
        }
コード例 #33
0
ファイル: ListTable.cs プロジェクト: pacoferre/prot-reloaded
        public ListTable(ContextProvider contextProvider, string listName, string sql, dynamic parameters, int dbNumber, string allDescription)
        {
            ZeroItem             = new object[] { "0", allDescription };
            this.contextProvider = contextProvider;

            sqlList         = sql;
            this.parameters = parameters;
            this.dbNumber   = dbNumber;

            Items = new List <object[]>(40);

            CreateGenerator();
        }
コード例 #34
0
 public override bool UnbindAssociation(Guid subscriberId, Guid associationId)
 {
     using (var context = ContextProvider.Provide())
     {
         var charges = context.OrderCategoryCharges.Where(s => s.SubscriberId == subscriberId && s.ChargeId == associationId).ToList();
         if (!charges.Any())
         {
             return(true);
         }
         context.OrderCategoryCharges.RemoveRange(charges);
         return(context.SaveChanges() > 0);
     }
 }
コード例 #35
0
 public void InsertWithIgnoreTest()
 {
     var sql = "";
     var provider = new ContextProvider(new Mock.ConnectionProvider());
     provider.Interceptor<Warrior>().BeforeExecute(s => sql = s.QueryString.Flatten());
     using (var context = provider.Open())
     {
         // insert all except ignored elements used in the reference expression
         context.Insert(() => new Warrior { ID = 1, Race = "Dwarf" }).Ignore(w => w.ID).Ignore(w => w.WeaponID);
         context.Commit();
         Assert.AreEqual(sql, "INSERT INTO Warrior (Name, Race, SpecialSkill) VALUES (NULL, 'Dwarf', NULL)");
     }
 }
コード例 #36
0
        public virtual ActionResult DeleteAll(string tableName, object id)
        {
            var entityType = ContextProvider.GetTypeByTableName(tableName);
            var relations  = SiteObjectRelationRepository.GetAll(x => x.ObjectType == tableName && x.Object_ID ==
                                                                 LinqToSqlUtils.CorrectPKType(id, entityType));

            foreach (var relation in relations)
            {
                SiteObjectRelationRepository.Delete(relation);
            }
            SiteObjectRelationRepository.SubmitChanges();
            return(null);
        }
コード例 #37
0
        public async Task <User> LogoutConnectedApps()
        {
            var user = ContextProvider.GetService <IUserService>().GetById();

            if (user == null)
            {
                throw new CashSchedulerException("Unauthorized", "401");
            }

            await ContextProvider.GetService <IUserRefreshTokenService>().DeleteAllAppTokens(user.Id);

            return(user);
        }
コード例 #38
0
        public void UpdateTests()
        {
            var sql = "";
            var provider = new ContextProvider(new Mock.ConnectionProvider());
            provider.Interceptor<Warrior>().BeforeExecute(s => sql = s.QueryString.Flatten());
            using (var context = provider.Open())
            {
                context.Update(() => new Warrior { ID = 1, Race = "Elf", WeaponID = 2 });
                context.Commit();

                Assert.AreEqual(sql, "UPDATE Warrior SET Name = NULL, WeaponID = 2, Race = 'Elf', SpecialSkill = NULL WHERE (Warrior.ID = 1)");

                context.Update(() => new Warrior { ID = 1, Race = "Elf", WeaponID = 2 }, e => e.ID);
                context.Commit();

                Assert.AreEqual(sql, "UPDATE Warrior SET Name = NULL, WeaponID = 2, Race = 'Elf', SpecialSkill = NULL WHERE (Warrior.ID = 1)");

                context.Update<Warrior>(() => new { ID = 1, Race = "Elf" });
                context.Commit();

                Assert.AreEqual(sql, "UPDATE Warrior SET Race = 'Elf' WHERE (Warrior.ID = 1)");

                context.Update<Warrior>(() => new { Race = "Elf" }, e => e.ID == 1);
                context.Commit();

                Assert.AreEqual(sql, "UPDATE Warrior SET Race = 'Elf' WHERE (Warrior.ID = 1)");

                context.Update<Warrior>(() => new { ID = 1, Race = "Elf" }, e => e.ID == 1);
                context.Commit();

                Assert.AreEqual(sql, "UPDATE Warrior SET Race = 'Elf' WHERE (Warrior.ID = 1)");

                context.Update<Warrior>(() => new { Race = "Elf" }, e => e.ID == 1 && e.SpecialSkill == null);
                context.Commit();

                Assert.AreEqual(sql, "UPDATE Warrior SET Race = 'Elf' WHERE ((Warrior.ID = 1) AND (Warrior.SpecialSkill is null))");

                context.Update<Warrior>(() => new Warrior { ID = 1, Race = "Elf" }).Ignore(w => w.SpecialSkill).Ignore(w => w.Name);
                context.Commit();

                Assert.AreEqual(sql, "UPDATE Warrior SET WeaponID = 0, Race = 'Elf' WHERE (Warrior.ID = 1)");

                var id = 1;
                context.Update<Warrior>(() => new { ID = 1, Race = "Elf" }, e => e.ID == id);
                context.Commit();

                Assert.AreEqual(sql, "UPDATE Warrior SET Race = 'Elf' WHERE (Warrior.ID = 1)");
            }
        }
コード例 #39
0
 public override object Execute(IContextProvider provider, object[] args, MemoryPool pool)
 {
     XQueryNodeIterator iter = XQueryNodeIterator.Create(
         QueryContext.Engine.Apply(null, null, m_expr, args, m_compiledExpr, pool));
     if (m_root)
         return new XQueryMappingIterator(args, pool, iter, m_bodyExpr);
     else
     {
         ContextProvider contextProvider = new ContextProvider(iter);
         object res = Undefined.Value;
         while (iter.MoveNext())
             res = m_bodyExpr.Execute(contextProvider, args, pool);
         return res;
     }
 }
コード例 #40
0
        public void ISelectQueryExpressionWithIgnoringFields()
        {
            var sql = "";
            var provider = new ContextProvider(new Mock.ConnectionProvider());
            provider.Interceptor<WarriorWithName>().BeforeExecute(s => sql = s.QueryString.Flatten());
            using (var context = provider.Open())
            {
                // ignore a member in the select
                context.From<WarriorWithName>()
                    .Ignore(w => w.ID)
                    .Ignore(w => w.Name)
                    .Ignore(w => w.SpecialSkill)
                    .Select();

                Assert.AreEqual(sql, "SELECT WeaponID, Race FROM WarriorWithName");

                // ignore a member in the select
                context.From<WarriorWithName>()
                    .Ignore(w => w.ID)
                    .Ignore(w => w.Name)
                    .Ignore(w => w.SpecialSkill)
                    .Map(w => w.Name)
                    .Select();

                Assert.AreEqual(sql, "SELECT WarriorWithName.Name, WeaponID, Race FROM WarriorWithName");

                // ignore a member in the select
                context.From<WarriorWithName>()
                    .Ignore(w => w.ID)
                    .Ignore(w => w.Name)
                    .Map(w => w.WeaponID, "TestFieldName")
                    .Ignore(w => w.SpecialSkill)
                    .Select();

                Assert.AreEqual(sql, "SELECT WarriorWithName.WeaponID AS TestFieldName, Race FROM WarriorWithName");
            }
        }
コード例 #41
0
        public void SelectWithPredicate()
        {
            var sql = string.Empty;
            var provider = new ContextProvider(new Mock.ConnectionProvider());
            provider.Interceptor<Warrior>().BeforeExecute(s => sql = s.QueryString.Flatten());
            using (var context = provider.Open())
            {
                // ignore a member in the select
                context.From<Warrior>(w => w.ID == 1)
                    .Select();

                Assert.AreEqual(sql, "SELECT ID, Name, WeaponID, Race, SpecialSkill FROM Warrior WHERE (Warrior.ID = 1)");

                // ignore a member in the SELECT
                context.Select<Warrior>(w => w.ID == 1);

                Assert.AreEqual(sql, "SELECT ID, Name, WeaponID, Race, SpecialSkill FROM Warrior WHERE (Warrior.ID = 1)");
            }
        }
コード例 #42
0
        public void SelectWithOrderTest()
        {
            var sql = "";
            var provider = new ContextProvider(new Mock.ConnectionProvider());
            provider.Interceptor<Orders>().BeforeExecute(s => sql = s.QueryString.Flatten());
            using (var context = provider.Open())
            {
                // join with simple order by
                context.From<Orders>().OrderBy(o => o.OrderDate).Select();
                string expected = "SELECT OrdersID, CustomerID, EmployeeID, OrderDate, RequiredDate, ShippedDate, ShipVia, Freight, ShipName, ShipAddress, ShipCity, ShipRegion, ShipPostalCode, ShipCountry FROM Orders ORDER BY Orders.OrderDate ASC";
                Assert.AreEqual(sql, expected);

                // join with generic order by
                context.From<Orders>().Join<Customers>((c, o) => c.CustomerID == o.CustomerID).Map(c => c.CustomerID).Map(c => c.EmployeeID).OrderBy<Orders>(o => o.OrderDate).Select();
                expected = "SELECT Customers.CustomerID, Customers.EmployeeID, OrdersID, OrderDate, RequiredDate, ShippedDate, ShipVia, Freight, ShipName, ShipAddress, ShipCity, ShipRegion, ShipPostalCode, ShipCountry FROM Orders JOIN Customers ON (Customers.CustomerID = Orders.CustomerID) ORDER BY Orders.OrderDate ASC";
                Assert.AreEqual(sql, expected);

                // join with simple order by desc
                context.From<Orders>().OrderByDesc(o => o.OrderDate).Select();
                expected = "SELECT OrdersID, CustomerID, EmployeeID, OrderDate, RequiredDate, ShippedDate, ShipVia, Freight, ShipName, ShipAddress, ShipCity, ShipRegion, ShipPostalCode, ShipCountry FROM Orders ORDER BY Orders.OrderDate DESC";
                Assert.AreEqual(sql, expected);

                // join with generic order by desc
                context.From<Orders>().Join<Customers>((c, o) => c.CustomerID == o.CustomerID).Map(c => c.CustomerID).Map(c => c.EmployeeID).OrderByDesc<Orders>(o => o.OrderDate).Select();
                expected = "SELECT Customers.CustomerID, Customers.EmployeeID, OrdersID, OrderDate, RequiredDate, ShippedDate, ShipVia, Freight, ShipName, ShipAddress, ShipCity, ShipRegion, ShipPostalCode, ShipCountry FROM Orders JOIN Customers ON (Customers.CustomerID = Orders.CustomerID) ORDER BY Orders.OrderDate DESC";
                Assert.AreEqual(sql, expected);

                // join with simple order by with simple then by
                context.From<Orders>().OrderBy(o => o.OrderDate).ThenBy(o => o.RequiredDate).Select();
                expected = "SELECT OrdersID, CustomerID, EmployeeID, OrderDate, RequiredDate, ShippedDate, ShipVia, Freight, ShipName, ShipAddress, ShipCity, ShipRegion, ShipPostalCode, ShipCountry FROM Orders ORDER BY Orders.OrderDate ASC, Orders.RequiredDate ASC";
                Assert.AreEqual(sql, expected);

                // join with generic order by with simple then by
                context.From<Orders>()
                    .Join<Customers>((c, o) => c.CustomerID == o.CustomerID)
                    .Map(c => c.CustomerID)
                    .Map(c => c.EmployeeID)
                    .OrderBy<Orders>(o => o.OrderDate)
                    .ThenBy(o => o.RequiredDate)
                    .Select();
                expected = "SELECT Customers.CustomerID, Customers.EmployeeID, OrdersID, OrderDate, RequiredDate, ShippedDate, ShipVia, Freight, ShipName, ShipAddress, ShipCity, ShipRegion, ShipPostalCode, ShipCountry FROM Orders JOIN Customers ON (Customers.CustomerID = Orders.CustomerID) ORDER BY Orders.OrderDate ASC, Orders.RequiredDate ASC";
                Assert.AreEqual(sql, expected);

                // join with simple order by desc with simple then by
                context.From<Orders>().OrderByDesc(o => o.OrderDate).ThenBy(o => o.RequiredDate).Select();
                expected = "SELECT OrdersID, CustomerID, EmployeeID, OrderDate, RequiredDate, ShippedDate, ShipVia, Freight, ShipName, ShipAddress, ShipCity, ShipRegion, ShipPostalCode, ShipCountry FROM Orders ORDER BY Orders.OrderDate DESC, Orders.RequiredDate ASC";
                Assert.AreEqual(sql, expected);

                // join with generic order by desc with simple then by
                context.From<Orders>()
                    .Join<Customers>((c, o) => c.CustomerID == o.CustomerID)
                    .Map(c => c.CustomerID)
                    .Map(c => c.EmployeeID)
                    .OrderByDesc<Orders>(o => o.OrderDate)
                    .ThenBy(o => o.RequiredDate)
                    .Select();
                expected = "SELECT Customers.CustomerID, Customers.EmployeeID, OrdersID, OrderDate, RequiredDate, ShippedDate, ShipVia, Freight, ShipName, ShipAddress, ShipCity, ShipRegion, ShipPostalCode, ShipCountry FROM Orders JOIN Customers ON (Customers.CustomerID = Orders.CustomerID) ORDER BY Orders.OrderDate DESC, Orders.RequiredDate ASC";
                Assert.AreEqual(sql, expected);

                // join with simple order by with generic then by
                context.From<Orders>().OrderBy(o => o.OrderDate).ThenBy<Orders>(o => o.RequiredDate).Select();
                expected = "SELECT OrdersID, CustomerID, EmployeeID, OrderDate, RequiredDate, ShippedDate, ShipVia, Freight, ShipName, ShipAddress, ShipCity, ShipRegion, ShipPostalCode, ShipCountry FROM Orders ORDER BY Orders.OrderDate ASC, Orders.RequiredDate ASC";
                Assert.AreEqual(sql, expected);

                // join with generic order by with generic then by
                context.From<Orders>()
                    .Join<Customers>((c, o) => c.CustomerID == o.CustomerID)
                    .Map(c => c.CustomerID)
                    .Map(c => c.EmployeeID)
                    .OrderBy<Orders>(o => o.OrderDate)
                    .ThenBy<Customers>(c => c.CompanyName)
                    .Select();
                expected = "SELECT Customers.CustomerID, Customers.EmployeeID, OrdersID, OrderDate, RequiredDate, ShippedDate, ShipVia, Freight, ShipName, ShipAddress, ShipCity, ShipRegion, ShipPostalCode, ShipCountry FROM Orders JOIN Customers ON (Customers.CustomerID = Orders.CustomerID) ORDER BY Orders.OrderDate ASC, Customers.CompanyName ASC";
                Assert.AreEqual(sql, expected);

                // join with simple order by desc with generic then by
                context.From<Orders>().OrderByDesc(o => o.OrderDate).ThenBy<Orders>(o => o.RequiredDate).Select();
                expected = "SELECT OrdersID, CustomerID, EmployeeID, OrderDate, RequiredDate, ShippedDate, ShipVia, Freight, ShipName, ShipAddress, ShipCity, ShipRegion, ShipPostalCode, ShipCountry FROM Orders ORDER BY Orders.OrderDate DESC, Orders.RequiredDate ASC";
                Assert.AreEqual(sql, expected);

                // join with generic order by desc with generic then by
                context.From<Orders>()
                    .Join<Customers>((c, o) => c.CustomerID == o.CustomerID)
                    .Map(c => c.CustomerID)
                    .Map(c => c.EmployeeID)
                    .OrderByDesc<Orders>(o => o.OrderDate)
                    .ThenBy<Customers>(c => c.CompanyName)
                    .Select();
                expected = "SELECT Customers.CustomerID, Customers.EmployeeID, OrdersID, OrderDate, RequiredDate, ShippedDate, ShipVia, Freight, ShipName, ShipAddress, ShipCity, ShipRegion, ShipPostalCode, ShipCountry FROM Orders JOIN Customers ON (Customers.CustomerID = Orders.CustomerID) ORDER BY Orders.OrderDate DESC, Customers.CompanyName ASC";
                Assert.AreEqual(sql, expected);

                // join with simple order by with generic then by desc
                context.From<Orders>().OrderBy(o => o.OrderDate).ThenByDesc<Orders>(o => o.RequiredDate).Select();
                expected = "SELECT OrdersID, CustomerID, EmployeeID, OrderDate, RequiredDate, ShippedDate, ShipVia, Freight, ShipName, ShipAddress, ShipCity, ShipRegion, ShipPostalCode, ShipCountry FROM Orders ORDER BY Orders.OrderDate ASC, Orders.RequiredDate DESC";
                Assert.AreEqual(sql, expected);

                // join with generic order by with generic then by desc
                context.From<Orders>()
                    .Join<Customers>((c, o) => c.CustomerID == o.CustomerID)
                    .Map(c => c.CustomerID)
                    .Map(c => c.EmployeeID)
                    .OrderBy<Orders>(o => o.OrderDate)
                    .ThenByDesc<Customers>(c => c.CompanyName)
                    .Select();
                expected = "SELECT Customers.CustomerID, Customers.EmployeeID, OrdersID, OrderDate, RequiredDate, ShippedDate, ShipVia, Freight, ShipName, ShipAddress, ShipCity, ShipRegion, ShipPostalCode, ShipCountry FROM Orders JOIN Customers ON (Customers.CustomerID = Orders.CustomerID) ORDER BY Orders.OrderDate ASC, Customers.CompanyName DESC";
                Assert.AreEqual(sql, expected);

                // join with simple order by desc with generic then by desc
                context.From<Orders>().OrderByDesc(o => o.OrderDate).ThenByDesc<Orders>(o => o.RequiredDate).Select();
                expected = "SELECT OrdersID, CustomerID, EmployeeID, OrderDate, RequiredDate, ShippedDate, ShipVia, Freight, ShipName, ShipAddress, ShipCity, ShipRegion, ShipPostalCode, ShipCountry FROM Orders ORDER BY Orders.OrderDate DESC, Orders.RequiredDate DESC";
                Assert.AreEqual(sql, expected);

                // join with generic order by desc with generic then by desc
                context.From<Orders>()
                    .Join<Customers>((c, o) => c.CustomerID == o.CustomerID)
                    .Map(c => c.CustomerID)
                    .Map(c => c.EmployeeID)
                    .OrderByDesc<Orders>(o => o.OrderDate)
                    .ThenByDesc<Customers>(c => c.CompanyName)
                    .Select();
                expected = "SELECT Customers.CustomerID, Customers.EmployeeID, OrdersID, OrderDate, RequiredDate, ShippedDate, ShipVia, Freight, ShipName, ShipAddress, ShipCity, ShipRegion, ShipPostalCode, ShipCountry FROM Orders JOIN Customers ON (Customers.CustomerID = Orders.CustomerID) ORDER BY Orders.OrderDate DESC, Customers.CompanyName DESC";
                Assert.AreEqual(sql, expected);
            }
        }
コード例 #43
0
ファイル: TableElement.cs プロジェクト: Chieze-Franklin/Quic
        /// <summary>
        /// Gets the singleton instance
        /// </summary>
        /// <returns></returns>
        public static ContextProvider Singleton()
        {
            if (singleton == null)
                singleton = new ContextProvider();

            return singleton;
        }
コード例 #44
0
        public void SelectCustomObjectWithDelegate()
        {
            var expected = "SELECT Orders.OrdersID, ProductID, UnitPrice, Quantity, Discount FROM Orders JOIN OrderDetails ON (OrderDetails.OrdersID = Orders.OrdersID)";

            var provider = new ContextProvider(new Mock.ConnectionProvider());
            provider.Interceptor<OrderWithDetail>().BeforeExecute(s => Assert.AreEqual(s.QueryString.Flatten(), expected));
            using (var context = provider.Open())
            {
                // SELECT only the properties that are defined in the anony object
                var items = context.From<Orders>()
                    .Map(o => o.OrdersID)
                    .Join<OrderDetails>((od, o) => od.OrdersID == o.OrdersID)
                    .Select(od => new OrderWithDetail
                    {
                        // only select the properties defined
                        ProductID = od.ProductID,
                        Quantity = od.Quantity
                    });

                items.Any();
            }
        }
コード例 #45
0
 public FakeJourneyRepository(ContextProvider<OldContext> contextProvider)
 {
     _contextProvider = contextProvider;
 }
コード例 #46
0
        public void SelectWithMultipleMapsToSameType()
        {
            var sql = "";
            var provider = new ContextProvider(new Mock.ConnectionProvider());
            provider.Interceptor<WarriorWithName>().BeforeExecute(s => sql = s.QueryString.Flatten());
            using (var context = provider.Open())
            {
                // select the properties that are defined in the mapping
                context.From<WarriorWithName>()
                    .Map(w => w.WeaponID, "ID")
                    .Map(w => w.WeaponID)
                    .Map(w => w.Race, "Name")
                    .Map(w => w.Race)
                    .Select();

                Assert.AreEqual(sql, "SELECT WarriorWithName.WeaponID AS ID, WarriorWithName.WeaponID, WarriorWithName.Race AS Name, WarriorWithName.Race, SpecialSkill FROM WarriorWithName");

                // map one property to a custom field
                context.From<WarriorWithName>()
                    .Map(w => w.WeaponID, "ID")
                    .Map(w => w.Race, "Name")
                    .Map(w => w.Race)
                    .Select();

                Assert.AreEqual(sql, "SELECT WarriorWithName.WeaponID AS ID, WarriorWithName.Race AS Name, WarriorWithName.Race, SpecialSkill FROM WarriorWithName");
            }
        }
コード例 #47
0
        public void SelectWithMin()
        {
            var sql = "";
            var provider = new ContextProvider(new Mock.ConnectionProvider());
            provider.Interceptor<Warrior>().BeforeExecute(s => sql = s.QueryString.Flatten());
            provider.Interceptor(() => new { MinID = 0 }).BeforeExecute(s => sql = s.QueryString.Flatten());
            using (var context = provider.Open())
            {
                // select the min id
                context.From<Warrior>().Min(w => w.ID).Select();
                Assert.AreEqual(sql, "SELECT MIN(ID) AS ID FROM Warrior");

                // select the min id with grouping
                context.From<Warrior>().Min(w => w.ID).Map(w => w.Race).GroupBy(w => w.Race).Select();
                Assert.AreEqual(sql, "SELECT MIN(ID) AS ID, Warrior.Race FROM Warrior GROUP BY Race");

                // select the min id with grouping
                context.From<Warrior>().Min(w => w.ID).Map(w => w.Race).GroupBy(w => w.Race).For<Warrior>().Select();
                Assert.AreEqual(sql, "SELECT MIN(ID) AS ID, Warrior.Race FROM Warrior GROUP BY Race");

                // select the min id
                context.From<Warrior>().Min(w => w.ID, "MinID").For(() => new { MinID = 0 }).Select();
                Assert.AreEqual(sql, "SELECT MIN(ID) AS MinID FROM Warrior");
            }
        }
コード例 #48
0
 public void SelectWithConstraintInBaseClass()
 {
     var sql = "";
     var provider = new ContextProvider(new Mock.ConnectionProvider());
     provider.Interceptor(() => new { ID = 0 }).BeforeExecute(s => sql = s.QueryString.Flatten());
     using (var context = provider.Open())
     {
         // select the properties that are defined in the mapping
         context.From<WarriorDerivate>(a => a.ID == 5).Select(() => new { ID = 0 });
         Assert.AreEqual(sql, "SELECT ID FROM WarriorDerivate WHERE (WarriorDerivate.ID = 5)");
     }
 }
コード例 #49
0
        public void SelectWithINExpression()
        {
            var expected = "SELECT ID, Name, WeaponID, Race, SpecialSkill FROM Warrior WHERE Warrior.Race In ('Elf','Dwarf')";

            var provider = new ContextProvider(new Mock.ConnectionProvider());
            provider.Interceptor<Warrior>().BeforeExecute(s => Assert.AreEqual(s.QueryString.Flatten(), expected));
            using (var context = provider.Open())
            {
                IEnumerable<string> races = new List<string>
                {
                    "Elf",
                    "Dwarf"
                };

                context.From<Warrior>()
                    .Where(w => races.Contains(w.Race))
                    .Select();
            }
        }
コード例 #50
0
ファイル: ContextProvider.cs プロジェクト: jolySoft/Breeze
    public SaveWorkState(ContextProvider contextProvider, JArray entitiesArray)
    {
        ContextProvider = contextProvider;
          var jObjects = entitiesArray.Select(jt => (dynamic)jt).ToList();
          var groups = jObjects.GroupBy(jo => (String)jo.entityAspect.entityTypeName).ToList();

          EntityInfoGroups = groups.Select(g => {
        var entityType = ContextProvider.LookupEntityType(g.Key);
        var entityInfos = g.Select(jo => ContextProvider.CreateEntityInfoFromJson(jo, entityType)).Cast<EntityInfo>().ToList();
        return new EntityGroup() { EntityType = entityType, EntityInfos = entityInfos };
          }).ToList();
    }
コード例 #51
0
        public void SelectTestWithForAndCustomMaps()
        {
            var sql = "";
            var provider = new ContextProvider(new Mock.ConnectionProvider());
            provider.Interceptor<Orders>().BeforeExecute(s => sql = s.QueryString.Flatten());
            provider.Interceptor(() => new
            {
                WarriorName = "",
                WeaponName = ""
            })
            .BeforeExecute(s => sql = s.QueryString.Flatten());

            using (var context = provider.Open())
            {
                // select statement with a FOR expression and mapping members/fields to a specific table
                context.From<Orders>().Join<OrderDetails>((od, o) => od.OrdersID == o.OrdersID).For<Orders>().Map<Orders>(o => o.OrdersID).Select();
                var expected = "SELECT CustomerID, EmployeeID, OrderDate, RequiredDate, ShippedDate, ShipVia, Freight, ShipName, ShipAddress, ShipCity, ShipRegion, ShipPostalCode, ShipCountry, Orders.OrdersID FROM Orders JOIN OrderDetails ON (OrderDetails.OrdersID = Orders.OrdersID)";
                Assert.AreEqual(sql, expected);

                // select statement with a FOR expression and ignoring fields in the resultset
                context.From<Warrior>().Join<Weapon>((wpn, wrir) => wpn.ID == wrir.WeaponID)
                    .For(() => new
                    {
                        WarriorName = "",
                        WeaponName = ""
                    })
                    .Map<Warrior>(wrir => wrir.Name, a => a.WarriorName)
                    .Map<Weapon>(wpn => wpn.Name, a => a.WeaponName)
                    .Select();
                expected = "SELECT Warrior.Name AS WarriorName, Weapon.Name AS WeaponName FROM Warrior JOIN Weapon ON (Weapon.ID = Warrior.WeaponID)";
                Assert.AreEqual(expected, sql);
            }
        }
コード例 #52
0
        public void SelectTestForOrders()
        {
            var sql = "";
            var provider = new ContextProvider(new Mock.ConnectionProvider());
            provider.Interceptor<Orders>().BeforeExecute(s => sql = s.QueryString.Flatten());
            using (var context = provider.Open())
            {
                // select statement with a FOR expression and mapping members/fields to a specific table
                context.From<Orders>().Join<OrderDetails>((od, o) => od.OrdersID == o.OrdersID).For<Orders>().Map<Orders>(o => o.OrdersID).Select();
                var expected = "SELECT CustomerID, EmployeeID, OrderDate, RequiredDate, ShippedDate, ShipVia, Freight, ShipName, ShipAddress, ShipCity, ShipRegion, ShipPostalCode, ShipCountry, Orders.OrdersID FROM Orders JOIN OrderDetails ON (OrderDetails.OrdersID = Orders.OrdersID)";
                Assert.AreEqual(sql, expected);

                // select statement with a FOR expression and ignoring fields in the resultset
                context.From<Orders>()
                    .Join<OrderDetails>((od, o) => od.OrdersID == o.OrdersID)
                    .For<Orders>()
                    .Ignore(o => o.OrdersID)
                    .Ignore(o => o.OrderDate)
                    .Ignore(o => o.RequiredDate)
                    .Select();
                expected = "SELECT CustomerID, EmployeeID, ShippedDate, ShipVia, Freight, ShipName, ShipAddress, ShipCity, ShipRegion, ShipPostalCode, ShipCountry FROM Orders JOIN OrderDetails ON (OrderDetails.OrdersID = Orders.OrdersID)";
                Assert.AreEqual(sql, expected);

                // select statement that compiles FROM a FOR operation with a anonym object defining the resultset entries and mapped to a defined type
                context.From<Orders>().Map(o => o.OrdersID).Join<OrderDetails>((od, o) => od.OrdersID == o.OrdersID).For<Orders>().Select();
                expected = "SELECT Orders.OrdersID, CustomerID, EmployeeID, OrderDate, RequiredDate, ShippedDate, ShipVia, Freight, ShipName, ShipAddress, ShipCity, ShipRegion, ShipPostalCode, ShipCountry FROM Orders JOIN OrderDetails ON (OrderDetails.OrdersID = Orders.OrdersID)";
                Assert.AreEqual(sql, expected);

                // simple select from statement
                context.From<Orders>().Select();
                expected = "SELECT OrdersID, CustomerID, EmployeeID, OrderDate, RequiredDate, ShippedDate, ShipVia, Freight, ShipName, ShipAddress, ShipCity, ShipRegion, ShipPostalCode, ShipCountry FROM Orders";
                Assert.AreEqual(sql, expected);
            }
        }
コード例 #53
0
        public void SelectWithGroupBy()
        {
            var sql = "";
            var provider = new ContextProvider(new Mock.ConnectionProvider());
            provider.Interceptor<Warrior>().BeforeExecute(s => sql = s.QueryString.Flatten());
            provider.Interceptor(() => new { Race = "" }).BeforeExecute(s => sql = s.QueryString.Flatten());
            provider.Interceptor(() => new { Race = "", WeaponID = 0 }).BeforeExecute(s => sql = s.QueryString.Flatten());
            provider.Interceptor(() => new { ID = 0, Race = "" }).BeforeExecute(s => sql = s.QueryString.Flatten());
            using (var context = provider.Open())
            {
                context.From<Warrior>().Ignore(w => w.ID).Ignore(w => w.SpecialSkill).Ignore(w => w.WeaponID).Ignore(w => w.Name).GroupBy(w => w.Race).Select();
                Assert.AreEqual(sql, "SELECT Race FROM Warrior GROUP BY Race");

                context.From<Warrior>().GroupBy(w => w.Race).ThenBy(w => w.WeaponID).For<Warrior>().Ignore(w => w.ID).Ignore(w => w.SpecialSkill).Ignore(w => w.Name).Select();
                Assert.AreEqual(sql, "SELECT WeaponID, Race FROM Warrior GROUP BY Race, WeaponID");

                context.From<Warrior>().For(() => new { ID = 0, Race = "" }).GroupBy(w => w.Race).ThenBy(w => w.ID).Select();
                Assert.AreEqual(sql, "SELECT ID, Race FROM Warrior GROUP BY Race, ID");

                context.From<Warrior>().Join<Weapon>((wep, war) => wep.ID == war.WeaponID).Where(w => w.Damage > 20).GroupBy<Warrior>(w => w.Race).For(() => new { Race = "" }).Select();
                Assert.AreEqual(sql, "SELECT Race FROM Warrior JOIN Weapon ON (Weapon.ID = Warrior.WeaponID) WHERE (Weapon.Damage > 20) GROUP BY Race");

                context.From<Warrior>().Join<Weapon>((wep, war) => wep.ID == war.WeaponID).Where(w => w.Damage > 20).GroupBy<Warrior>(w => w.Race).ThenBy<Warrior>(w => w.WeaponID).For(() => new { Race = "", WeaponID = 0 }).Select();
                Assert.AreEqual(sql, "SELECT Race, WeaponID FROM Warrior JOIN Weapon ON (Weapon.ID = Warrior.WeaponID) WHERE (Weapon.Damage > 20) GROUP BY Race, WeaponID");

                context.From<Warrior>().Join<Weapon>((wep, war) => wep.ID == war.WeaponID).Where(w => w.Damage > 20).For(() => new { Race = "" }).GroupBy(w => w.Race).Select();
                Assert.AreEqual(sql, "SELECT Race FROM Warrior JOIN Weapon ON (Weapon.ID = Warrior.WeaponID) WHERE (Weapon.Damage > 20) GROUP BY Race");

                context.From<Warrior>().Join<Weapon>((wep, war) => wep.ID == war.WeaponID).Where(w => w.Damage > 20).For(() => new { Race = "", WeaponID = 0 }).GroupBy(w => w.Race).ThenBy(w => w.WeaponID).Select();
                Assert.AreEqual(sql, "SELECT Race, WeaponID FROM Warrior JOIN Weapon ON (Weapon.ID = Warrior.WeaponID) WHERE (Weapon.Damage > 20) GROUP BY Race, WeaponID");
            }
        }
コード例 #54
0
        public void SelectWithWhereTest()
        {
            var sql = "";
            var provider = new ContextProvider(new Mock.ConnectionProvider());
            provider.Interceptor<Employee>().BeforeExecute(s => sql = s.QueryString.Flatten());
            provider.Interceptor<Orders>().BeforeExecute(s => sql = s.QueryString.Flatten());
            using (var context = provider.Open())
            {
                // select statement with a where operation and a or operation that has two genereic parameters and alias for both types
                context.From<Customers>("cust")
                    .Map(e => e.EmployeeID)
                    .Map(e => e.Address)
                    .Map(e => e.City)
                    .Map(e => e.PostalCode)
                    .Join<Orders>((o, c) => o.EmployeeID == c.EmployeeID, source: "cust")
                    .Join<Employee>((e, o) => e.EmployeeID == o.EmployeeID, alias: "emp")
                    .Where(e => e.FirstName.Contains("Davolio"))
                    .Or<Customers, Employee>((c, e) => c.EmployeeID == e.EmployeeID, "cust", "emp")
                    .Select();
                var expected = "SELECT cust.EmployeeID, cust.Address, cust.City, cust.PostalCode, LastName, FirstName, Title, BirthDate, HireDate, ReportsTo FROM Customers cust JOIN Orders ON (Orders.EmployeeID = cust.EmployeeID) JOIN Employee emp ON (emp.EmployeeID = Orders.EmployeeID) WHERE emp.FirstName like '%Davolio%' OR (cust.EmployeeID = emp.EmployeeID)";
                    //"select cust.EmployeeID, OrdersID, CustomerID, OrderDate, RequiredDate, ShippedDate, ShipVia, Freight, ShipName, ShipAddress, ShipCity, ShipRegion, ShipPostalCode, ShipCountry FROM Customers cust JOIN Orders ON (Orders.EmployeeID = cust.EmployeeID) JOIN Employee emp ON (emp.EmployeeID = Orders.EmployeeID) where emp.FirstName like '%Davolio%' or (cust.EmployeeID = emp.EmployeeID)";
                Assert.AreEqual(sql, expected);

                // select statement with a where operation and a or operation that has two genereic parameters and a alias ON the source type
                context.From<Customers>()
                    .Map(e => e.EmployeeID)
                    .Map(e => e.Address)
                    .Map(e => e.City)
                    .Map(e => e.PostalCode)
                    .Join<Orders>((o, c) => o.EmployeeID == c.EmployeeID)
                    .Join<Employee>((e, o) => e.EmployeeID == o.EmployeeID, alias: "emp")
                    .Where(e => e.FirstName.Contains("Davolio"))
                    .Or<Customers, Employee>((c, e) => c.EmployeeID == e.EmployeeID, source: "emp")
                    .Select();
                expected = "SELECT Customers.EmployeeID, Customers.Address, Customers.City, Customers.PostalCode, LastName, FirstName, Title, BirthDate, HireDate, ReportsTo FROM Customers JOIN Orders ON (Orders.EmployeeID = Customers.EmployeeID) JOIN Employee emp ON (emp.EmployeeID = Orders.EmployeeID) WHERE emp.FirstName like '%Davolio%' OR (Customers.EmployeeID = emp.EmployeeID)";
                //expected = "select Customers.EmployeeID, OrdersID, CustomerID, OrderDate, RequiredDate, ShippedDate, ShipVia, Freight, ShipName, ShipAddress, ShipCity, ShipRegion, ShipPostalCode, ShipCountry from Customers JOIN Orders ON (Orders.EmployeeID = Customers.EmployeeID) JOIN Employee emp ON (emp.EmployeeID = Orders.EmployeeID) where emp.FirstName like '%Davolio%' or (Customers.EmployeeID = emp.EmployeeID)";
                Assert.AreEqual(sql, expected);

                // select statement with a where operation and a or operation that has two genereic parameters and a alias ON the type
                context.From<Customers>("cust")
                    .Map(e => e.EmployeeID)
                    .Map(e => e.Address)
                    .Map(e => e.City)
                    .Map(e => e.PostalCode)
                    .Join<Orders>((o, c) => o.EmployeeID == c.EmployeeID, source: "cust")
                    .Join<Employee>((e, o) => e.EmployeeID == o.EmployeeID)
                    .Where(e => e.FirstName.Contains("Davolio"))
                    .Or<Customers, Employee>((c, e) => c.EmployeeID == e.EmployeeID, alias: "cust")
                    .Select();
                expected = "SELECT cust.EmployeeID, cust.Address, cust.City, cust.PostalCode, LastName, FirstName, Title, BirthDate, HireDate, ReportsTo FROM Customers cust JOIN Orders ON (Orders.EmployeeID = cust.EmployeeID) JOIN Employee ON (Employee.EmployeeID = Orders.EmployeeID) WHERE Employee.FirstName like '%Davolio%' OR (cust.EmployeeID = Employee.EmployeeID)";
                //expected = "select cust.EmployeeID, OrdersID, CustomerID, OrderDate, RequiredDate, ShippedDate, ShipVia, Freight, ShipName, ShipAddress, ShipCity, ShipRegion, ShipPostalCode, ShipCountry FROM Customers cust JOIN Orders ON (Orders.EmployeeID = cust.EmployeeID) JOIN Employee ON (Employee.EmployeeID = Orders.EmployeeID) where Employee.FirstName like '%Davolio%' or (cust.EmployeeID = Employee.EmployeeID)";
                Assert.AreEqual(sql, expected);

                // Select statement with a simple where operation
                context.From<Orders>()
                    .Map(o => o.OrdersID)
                    .Join<OrderDetails>((d, o) => d.OrdersID == o.OrdersID)
                    .Where(o => o.Discount > 0)
                    .Rebase<OrderDetails, Orders>()
                    .Select();
                expected = "SELECT Orders.OrdersID, CustomerID, EmployeeID, OrderDate, RequiredDate, ShippedDate, ShipVia, Freight, ShipName, ShipAddress, ShipCity, ShipRegion, ShipPostalCode, ShipCountry FROM Orders JOIN OrderDetails ON (OrderDetails.OrdersID = Orders.OrdersID) WHERE (OrderDetails.Discount > '0')";
                Assert.AreEqual(sql, expected);

                // select statement with a where and a simple or operation
                context.From<Orders>()
                    .Where(p => p.CustomerID.StartsWith("P"))
                    .Or<Orders>(o => o.ShipCity == "London")
                    .Select();
                expected = "SELECT OrdersID, CustomerID, EmployeeID, OrderDate, RequiredDate, ShippedDate, ShipVia, Freight, ShipName, ShipAddress, ShipCity, ShipRegion, ShipPostalCode, ShipCountry FROM Orders WHERE Orders.CustomerID like 'P%' OR (Orders.ShipCity = 'London')";
                Assert.AreEqual(sql, expected);

                // select statement with a where and a simple or operation
                context.From<Orders>()
                    .Where(p => p.CustomerID.StartsWith("P"))
                    .Or<Orders>(o => o.ShipCity == "Paris")
                    .Or<Orders>(o => o.ShipCity == "London")
                    .Select();
                expected = "SELECT OrdersID, CustomerID, EmployeeID, OrderDate, RequiredDate, ShippedDate, ShipVia, Freight, ShipName, ShipAddress, ShipCity, ShipRegion, ShipPostalCode, ShipCountry FROM Orders WHERE Orders.CustomerID like 'P%' OR (Orders.ShipCity = 'Paris') OR (Orders.ShipCity = 'London')";
                Assert.AreEqual(sql, expected);

                // Select statement with a where and a generic OR operation
                context.From<Orders>("ord")
                    .Where(p => p.CustomerID.StartsWith("P"))
                    .Or<Orders>(o => o.ShipCity == "London", "ord")
                    .Select();
                expected = "SELECT OrdersID, CustomerID, EmployeeID, OrderDate, RequiredDate, ShippedDate, ShipVia, Freight, ShipName, ShipAddress, ShipCity, ShipRegion, ShipPostalCode, ShipCountry FROM Orders ord WHERE ord.CustomerID like 'P%' OR (ord.ShipCity = 'London')";
                Assert.AreEqual(sql, expected);

                // select statement with a where and a simple and operation
                context.From<Orders>()
                    .Where(p => p.CustomerID.StartsWith("se"))
                    .And(o => o.ShipCity == "London")
                    .Select();
                expected = "SELECT OrdersID, CustomerID, EmployeeID, OrderDate, RequiredDate, ShippedDate, ShipVia, Freight, ShipName, ShipAddress, ShipCity, ShipRegion, ShipPostalCode, ShipCountry FROM Orders WHERE Orders.CustomerID like 'se%' AND (Orders.ShipCity = 'London')";
                Assert.AreEqual(sql, expected);

            }
        }
コード例 #55
0
 private IEnumerable<XPathItem> CreateEnumerator(object[] args,  MemoryPool pool,
     XQueryExprBase expr, XQueryNodeIterator baseIter)
 {
     XQueryNodeIterator iter = baseIter.Clone();
     XQueryExpr numexpr = expr as XQueryExpr;
     if (numexpr != null && numexpr.m_expr.Length == 1
         && numexpr.m_expr[0] is Integer)
     {
         Integer pos = (Integer)numexpr.m_expr[0];
         foreach (XPathItem item in iter)
         {
             if (pos == 1)
             {
                 yield return item;
                 break;
             }
             else
                 pos--;
         }
     }
     else
     {
         ContextProvider provider = new ContextProvider(iter);
         object res = Undefined.Value;
         while (iter.MoveNext())
         {
             if (m_contextSensitive || res == Undefined.Value)
                 res = expr.Execute(provider, args, pool);
             if (res == Undefined.Value)
             {
                 if (!m_contextSensitive)
                     break;
                 continue;
             }                            
             XQueryNodeIterator iter2 = res as XQueryNodeIterator;
             XPathItem item;
             if (iter2 != null)
             {
                 iter2 = iter2.Clone();
                 if (!iter2.MoveNext())
                     continue;
                 item = iter2.Current.Clone();
                 if (!item.IsNode && iter2.MoveNext())
                     throw new XQueryException(Properties.Resources.FORG0006, "fn:boolean()",
                         new XQuerySequenceType(XmlTypeCode.AnyAtomicType, XmlTypeCardinality.OneOrMore));
             }
             else
             {
                 item = res as XPathItem;
                 if (item == null)
                     item = new XQueryItem(res);
             }
             if (item.IsNode)
                 yield return iter.Current;
             else
             {
                 if (ValueProxy.IsNumeric(item.ValueType))
                 {
                     if (QueryContext.Engine.OperatorEq(iter.CurrentPosition + 1, item.TypedValue) != null)
                     {
                         yield return iter.Current;
                         if (!m_contextSensitive)
                             break;
                     }
                 }
                 else
                     if (Core.BooleanValue(item))
                         yield return iter.Current;
             }
         }                
     }
 }
コード例 #56
0
        public void SelectWithExtendedMapping()
        {
            var expected = "SELECT Orders.Freight AS SpecialFreight, CustomerID, EmployeeID, OrderDate, RequiredDate, ShippedDate, ShipVia, ShipName, ShipAddress, ShipCity, ShipRegion, ShipPostalCode, ShipCountry, ProductID, UnitPrice, Quantity, Discount FROM Orders JOIN OrderDetails ON (OrderDetails.OrdersID = Orders.OrdersID)";

            var provider = new ContextProvider(new Mock.ConnectionProvider());
            provider.Interceptor<OrderWithDetailExtended>().BeforeExecute(s => Assert.AreEqual(s.QueryString.Flatten(), expected));
            using (var context = provider.Open())
            {
                // Map => To
                context.From<Orders>()
                    .Join<OrderDetails>((detail, order) => detail.OrdersID == order.OrdersID)
                    .Map(i => i.OrdersID)
                    // map a property from a joni to a property in the result type
                    .Map<Orders, OrderWithDetailExtended>(source => source.Freight, alias => alias.SpecialFreight)
                    .Select<OrderWithDetailExtended>();
            }
        }
コード例 #57
0
        public void SelectForAnonymObjectType()
        {
            var expected = "SELECT ProductID, Quantity FROM Orders JOIN OrderDetails ON (OrderDetails.OrdersID = Orders.OrdersID)";

            var provider = new ContextProvider(new Mock.ConnectionProvider());
            provider.Interceptor(() => new
            {
                ProductID = 0,
                Quantity = 0
            })
            .BeforeExecute(s => Assert.AreEqual(s.QueryString.Flatten(), expected));
            using (var context = provider.Open())
            {
                // select only the properties that are defined in the anony object
                context.From<Orders>()
                    .Join<OrderDetails>((od, o) => od.OrdersID == o.OrdersID)
                    .For(() => new
                    {
                        ProductID = 0,
                        Quantity = 0
                    })
                    .Select();
            }
        }
コード例 #58
0
        public void SelectWithDifferenctCasesInMappedPropertyNamesTest()
        {
            var sql = "";
            var provider = new ContextProvider(new Mock.ConnectionProvider());
            provider.Interceptor<ArbeitsPlanHeader>().BeforeExecute(s => sql = s.QueryString.Flatten());
            using (var context = provider.Open())
            {
                context.From<ArbeitsPlan>()
                        .Map(ap => ap.PlanID)
                        .Map<int>(ap => ap.Status, converter: value => value == 1 ? Status.Active : Status.Inactive)
                        .Map<ArbeitsPlanHeader>(ap => ap.PlanID, aph => aph.ID)
                        .Map<ArbeitsPlanHeader>(ap => ap.ATID, aph => aph.ArbeitsTageId)
                        .Map(ap => ap.Name)
                        .Join<Schemas>((s, ap) => s.SchemaID == ap.SchemaID)
                        .Map(s => s.SchemaID)
                        .Where(ap => ap.Status == 1)
                        .For<ArbeitsPlanHeader>()
                        .Ignore(aph => aph.Layout)
                        .Select();

                Assert.AreEqual(sql, "SELECT ArbeitsPlan.PlanID, ArbeitsPlan.Status, ArbeitsPlan.PlanID AS ID, ArbeitsPlan.ATID AS ArbeitsTageId, Schemas.SchemaID, JahrId, Von, Bis FROM ArbeitsPlan JOIN Schemas ON (Schemas.SchemaID = ArbeitsPlan.SchemaID) WHERE (Schemas.Status = 1)");
            }
        }
コード例 #59
0
        public void SelectAnonymObjectTypeDefiniton()
        {
            var expected = "SELECT ProductID, Quantity FROM Orders JOIN OrderDetails ON (OrderDetails.OrdersID = Orders.OrdersID)";
            var type = new
            {
                ProductID = 0,
                Quantity = 0.0
            };

            var provider = new ContextProvider(new Mock.ConnectionProvider());
            provider.Interceptor(() => type).BeforeExecute(s => Assert.AreEqual(s.QueryString.Flatten(), expected));
            using (var context = provider.Open())
            {
                context.From<Orders>()
                    .Join<OrderDetails>((od, o) => od.OrdersID == o.OrdersID)
                    .Select(() => new
                    {
                        ProductID = 0,
                        Quantity = 0.0
                    });
            }
        }
コード例 #60
0
 private bool MoveNext(object[] args, MemoryPool pool, XQueryNodeIterator[] iter, int index)
 {
     if (iter[index] != null && iter[index].MoveNext())
         return true;
     else
         if (index > 0)
         {
             while (MoveNext(args, pool, iter, index - 1))
             {
                 ContextProvider provider = new ContextProvider(iter[index - 1]);
                 if (!provider.Context.IsNode)
                     throw new XQueryException(Properties.Resources.XPTY0019, provider.Context.Value);
                 iter[index] = XQueryNodeIterator.Create(_path[index].Execute(provider, args, pool));
                 if (iter[index].MoveNext())
                     return true;
             }
         }
     return false;
 }