Exemplo n.º 1
0
        public void WhenSavingEntityTwice_ThenCanReloadIt()
        {
            var id = Guid.NewGuid();

            using (var context = new SqlDataContext<TestAggregateRoot>(() => new TestDbContext(), Mock.Of<IEventBus>()))
            {
                var aggregateRoot = new TestAggregateRoot(id);
                context.Save(aggregateRoot);
            }

            using (var context = new SqlDataContext<TestAggregateRoot>(() => new TestDbContext(), Mock.Of<IEventBus>()))
            {
                var aggregateRoot = context.Find(id);
                aggregateRoot.Title = "test";

                context.Save(aggregateRoot);
            }

            using (var context = new SqlDataContext<TestAggregateRoot>(() => new TestDbContext(), Mock.Of<IEventBus>()))
            {
                var aggregateRoot = context.Find(id);

                Assert.Equal("test", aggregateRoot.Title);
            }
        }
        public void CreateConnection_ValidConfiguration_DoesNotThrow()
        {
            // Arrange, Act
            var dbContext = new SqlDataContext(
                new FakeCompleteLambdaConfiguration(),
                _exceptionLogFormatter.Object);

            // not sure of a way to validate that the SqlDataContext object is valid.
            // HOWEVER, I'm not going to write tests against GetBlogPostLookup, because it is a simple
            // database access method, and assuming the configuration is valid, the
            // method will be fine. Also, too much work to mock/wrap SqlConnection and SqlCommand,
            // with little payoff.
        }
Exemplo n.º 3
0
 public bool DeleteBulkResponse(IEnumerable <Response> responses, out string status)
 {
     try
     {
         SqlDataContext.Repository <Response>().DeleteMany(responses);
         SqlDataContext.Save();
         status = "Success";
         return(true);
     }
     catch (Exception ex)
     {
         status = ex.GetAllMessages();
         return(false);
     }
 }
Exemplo n.º 4
0
        public bool CheckSnipeValidity(Snipe snipe, UltimateSniper_Services.ServiceEBay eBayService)
        {
            bool res = false;
            SqlDataContext myDataConnection = new SqlDataContext();

            User user = this.GetUserForSnipe(snipe);

            if (user == null)
            {
                snipe.SnipeStatus = EnumSnipeStatus.ERROR;
                snipe.SnipeErrorReason = "The user assocated to the snipe couldn't be loaded properly.";
            }
            else
            {
                eBayItemData item = eBayService.GetItemDetails(snipe.ItemID);

                if (item.ItemCurrentHighestBid > snipe.SnipeBidInFinalCurrency)
                {
                    UltimateSniper_Services.ServiceEmail emailService = new UltimateSniper_Services.ServiceEmail();

                    snipe.SnipeStatus = EnumSnipeStatus.OVERBID;
                    snipe.SnipeErrorReason = "The snipe bid is lower the current price.";

                    ServiceEmail.SendEmail(user, "[SnipeAgent] Maximum bid reached for: " + snipe.SnipeName, "Hello, you snipe bid is lower the current price. You can still modify it by going on www.snipeagent.com and into the section 'My Snipes'. Kind regards, Snipe Agent.");
                }

                res = true;

                item.ItemCurrentHighestBidUserCurrency = this.ConvertValue(item.ItemCurrentHighestBid, item.ItemCurrencyCode.ToString(), user.UserCurrency.ToString());
                snipe.ItemLastKnownPrice = item.ItemCurrentHighestBidUserCurrency;

                snipe.ItemEndDate = item.ItemEndDate;
                snipe.ItemTitle = item.ItemTitle;
                snipe.ItemURL = item.ItemURL;
                snipe.ItemSellerID = item.ItemSellerID;
                snipe.ItemPictureURL = item.ItemPictureURL;

                snipe.ItemLastUdpate = ServiceTimeZone.DateTimeToUniversal(DateTime.Now);
            }

            snipe.ValidityCheckInProgress = false;

            myDataConnection.Save<Snipe>((object)snipe, snipe);

            return res;
        }
        public void WhenSavingAggregateRoot_ThenCanRetrieveIt()
        {
            var id = Guid.NewGuid();

            using (var context = new SqlDataContext <TestAggregateRoot>(() => new TestDbContext(), Mock.Of <IEventBus>())) {
                var aggregateRoot = new TestAggregateRoot(id)
                {
                    Title = "test"
                };
                context.Save(aggregateRoot);
            }

            using (var context = new SqlDataContext <TestAggregateRoot>(() => new TestDbContext(), Mock.Of <IEventBus>())) {
                var aggregateRoot = context.Find(id);

                Assert.NotNull(aggregateRoot);
                Assert.AreEqual("test", aggregateRoot.Title);
            }
        }
Exemplo n.º 6
0
        public void WhenSavingAggregateRoot_ThenCanRetrieveIt()
        {
            var id = Guid.NewGuid();

            using (var context = new SqlDataContext<TestAggregateRoot>(() => new TestDbContext(), Mock.Of<IEventBus>()))
            {
                var aggregateRoot = new TestAggregateRoot(id) { Title = "test" };

                context.Save(aggregateRoot);
            }

            using (var context = new SqlDataContext<TestAggregateRoot>(() => new TestDbContext(), Mock.Of<IEventBus>()))
            {
                var aggregateRoot = context.Find(id);

                Assert.NotNull(aggregateRoot);
                Assert.Equal("test", aggregateRoot.Title);
            }
        }
Exemplo n.º 7
0
        public bool SaveRequest(out string status)
        {
            try
            {
                var user = SqlDataContext.Repository <User>().Query()
                           .Get().FirstOrDefault();

                if (user == null)
                {
                    status = "There is no registered User in the database";
                    return(false);
                }

                var requestType = SqlDataContext.Repository <RequestType>()
                                  .Query().Get().FirstOrDefault();

                if (requestType != null)
                {
                    SqlDataContext.Repository <Request>().InsertGraph(new Request
                    {
                        Id            = Guid.NewGuid(),
                        RequestTypeId = requestType.Id,
                        Header        = "Test Request",
                        Body          = "Body text for test request",
                        UserId        = user.Id
                    });

                    SqlDataContext.Save();

                    status = "Success";
                    return(true);
                }

                status = "There is no registered Request Type in the database";
                return(false);
            }
            catch (Exception ex)
            {
                status = ex.GetAllMessages();
                return(false);
            }
        }
        public void WhenEntityExposesEvent_ThenRepositoryPublishesIt()
        {
            var busMock = new Mock <IEventBus>();
            var events  = new List <IEvent>();

            busMock.Setup(x => x.Publish(It.IsAny <IEnumerable <Envelope <IEvent> > >()))
            .Callback <IEnumerable <Envelope <IEvent> > >(x => events.AddRange(x.Select(e => e.Body)));

            var @event = new TestEvent();

            using (var context = new SqlDataContext <TestEventPublishingAggregateRoot>(() => new TestDbContext(), busMock.Object)) {
                var aggregate = new TestEventPublishingAggregateRoot(Guid.NewGuid());
                aggregate.AddEvent(@event);

                context.Save(aggregate);
            }

            Assert.AreEqual(1, events.Count);
            Assert.IsTrue(events.Contains(@event));
        }
Exemplo n.º 9
0
        public bool SaveBulkResponse(out string status)
        {
            try
            {
                var user = SqlDataContext.Repository <User>().Query().Get().FirstOrDefault();

                if (user == null)
                {
                    status = "There is no registered User in the database";
                    return(false);
                }

                var request = SqlDataContext.Repository <Request>().Query().Include(r => r.Response).Get().FirstOrDefault();
                if (request == null)
                {
                    status = "There is no registered Request in the database";
                    return(false);
                }

                var responses = Enumerable.Range(0, 1000).Select(p => new Response
                {
                    Id        = Guid.NewGuid(),
                    Body      = "Bulk insert test for responses",
                    Header    = "Bulk insert test",
                    RequestId = request.Id,
                    UserId    = user.Id
                });

                SqlDataContext.Repository <Response>().InsertMany(responses);

                SqlDataContext.Save();

                status = "Success";
                return(true);
            }
            catch (Exception ex)
            {
                status = ex.GetAllMessages();
                return(false);
            }
        }
        public void WhenSavingEntityTwice_ThenCanReloadIt()
        {
            var id = Guid.NewGuid();

            using (var context = new SqlDataContext <TestAggregateRoot>(() => new TestDbContext(), Mock.Of <IEventBus>())) {
                var aggregateRoot = new TestAggregateRoot(id);
                context.Save(aggregateRoot);
            }

            using (var context = new SqlDataContext <TestAggregateRoot>(() => new TestDbContext(), Mock.Of <IEventBus>())) {
                var aggregateRoot = context.Find(id);
                aggregateRoot.Title = "test";

                context.Save(aggregateRoot);
            }

            using (var context = new SqlDataContext <TestAggregateRoot>(() => new TestDbContext(), Mock.Of <IEventBus>())) {
                var aggregateRoot = context.Find(id);
                Assert.AreEqual("test", aggregateRoot.Title);
            }
        }
Exemplo n.º 11
0
        public bool UserExtensionMethodTest(out string status)
        {
            try
            {
                var activeUsers = SqlDataContext.Repository <User>()
                                  .GetActiveUsers().ToList();

                if (activeUsers.Any())
                {
                    status = "Success";
                    return(true);
                }

                status = "No active user";
                return(false);
            }
            catch (Exception ex)
            {
                status = ex.GetAllMessages();
                return(false);
            }
        }
Exemplo n.º 12
0
        public IList <Response> ResponseListFromStoredProcedure
            (out string status)
        {
            try
            {
                var request = SqlDataContext.Repository <Request>()
                              .Query().Get().FirstOrDefault();

                if (request != null)
                {
                    var responses = SqlDataContext.Repository <Response>().SqlQuery(
                        "exec [dbo].[spGetResponsesByRequestId] @requestId", new SqlParameter
                    {
                        DbType        = DbType.Guid,
                        ParameterName = "@requestId",
                        Direction     = ParameterDirection.Input,
                        Value         = request.Id
                    }).ToList();

                    if (responses.Any())
                    {
                        status = "Success";
                        return(responses);
                    }

                    status = "There is no registered response in the database";
                    return(null);
                }

                status = "There is no registered Request in the database";
                return(null);
            }
            catch (Exception ex)
            {
                status = ex.GetAllMessages();
                return(null);
            }
        }
Exemplo n.º 13
0
        public bool SaveTestUser(out string status)
        {
            try
            {
                SqlDataContext.Repository <User>().InsertGraph(new User
                {
                    Id       = Guid.NewGuid(),
                    Email    = "*****@*****.**",
                    FullName = "Emre Gulay",
                    IsActive = true,
                    Password = "******"
                });

                SqlDataContext.Save();

                status = "Saved";
                return(true);
            }
            catch (Exception ex)
            {
                status = ex.GetAllMessages();
                return(false);
            }
        }
Exemplo n.º 14
0
 public StockRepository(SqlDataContext context, ILogger <IStockRepository> log)
 {
     _context = context;
     _log     = log;
 }
Exemplo n.º 15
0
 public UserRepository(SqlDataContext context)
 {
     _context = context;
 }
Exemplo n.º 16
0
 public PlanosVxTelRepository(SqlDataContext sqlDataContext)
 {
     this.sqlDataContext = sqlDataContext;
 }
Exemplo n.º 17
0
        private static void ConfigureDiContainer(ContainerBuilder builder)
        {
            var cwd = Directory.GetCurrentDirectory();

            // configuration
            string env           = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
            string configFile    = "appsettings." + (env != null && env != "" ? $"{env}." : "") + "json";
            var    configuration = new ConfigurationBuilder()
                                   .SetBasePath(cwd)
                                   .AddJsonFile("appsettings.json")
                                   .AddJsonFile(configFile)
                                   .AddEnvironmentVariables()
                                   .Build();

            builder.RegisterInstance(configuration).As <IConfigurationRoot>();

            // serilog logger
            string logFolder = configuration["Logging:LogFolder"];
            string logFile   = $"{cwd}\\{logFolder}\\SlingshotWiftBridge.log";
            var    logger    = new LoggerConfiguration()
                               .Enrich.With(new ThreadIdEnricher())
                               .WriteTo.File(
                logFile,
                rollingInterval: RollingInterval.Day,
                outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} ({ThreadCnt}) {Message:lj}{NewLine}{Exception}"
                )
                               .CreateLogger();

            builder.RegisterInstance(logger).As <ILogger>();

            // db context
            StringBuilder sb = new StringBuilder();

            sb.Append($"Server={configuration["Database:HostUrl"]};");
            sb.Append($"Database={configuration["Database:DatabaseName"]};");
            sb.Append($"user id={configuration["Database:UserName"]};");
            sb.Append($"Password={configuration["Database:Password"]};");
            sb.Append($"Trusted_Connection=False;MultipleActiveResultSets=true;");
            string connStr   = sb.ToString();
            var    dbcontext = new SqlDataContext(connStr);

            builder.RegisterInstance(dbcontext).As <ISqlDataContext>();

            // wift
            builder.RegisterType <WiftConnector>().As <IWiftConnector>();
            builder.RegisterType <Wift>()
            .WithParameter("uri", configuration["Wift:HostUrl"])
            .As <IWift>();

            // repositories
            builder.RegisterType <HistoryRepository>().As <IHistoryRepository>();

            // services
            builder.RegisterType <WiftWrapper>().As <IWiftWrapper>();
            builder.RegisterType <WiftService>().As <IWiftService>();
            builder.RegisterType <PoolService>().As <IPoolService>();
            builder.RegisterType <DividendService>().As <IDividendService>();
            builder.RegisterType <RunnerService>().As <IRunnerService>();
            builder.RegisterType <RaceService>().As <IRaceService>();
            builder.RegisterType <MeetingService>().As <IMeetingService>();

            // this actual service class
            builder.RegisterType <Application>();
        }
Exemplo n.º 18
0
 public PageBehaviourSqlDataSource(SqlDataContext dbContext)
 {
     _dbContext = dbContext;
 }
Exemplo n.º 19
0
 public TabelacaoPrecos(SqlDataContext sqlDataContext)
 {
     this.sqlDataContext = sqlDataContext;
 }
Exemplo n.º 20
0
        /// <summary>
        /// This code should be executed just before the item ends
        /// </summary>
        /// <param name="snipe">Snipe to be executed</param>
        /// <returns></returns>
        public void PlaceBids()
        {
            try
            {

                SqlDataContext myDataConnection = new SqlDataContext();

                UltimateSniper_Services.ServiceOthers otherServ = new UltimateSniper_Services.ServiceOthers();

                User user = otherServ.GetUserForSnipe(_Snipe);

                if (user == null)
                {
                    _Snipe.SnipeErrorReason = "The user assocated to the snipe couldn't be loaded properly.";
                }
                else
                {
                    if (!_Snipe.SnipeInProgress)
                    {
                        _Snipe.SnipeInProgress = true;

                        myDataConnection.Save<Snipe>((object)_Snipe, _Snipe);
                    }

                    try
                    {
                        SL_Scheduler.eBayService.User = user;

                        while (true)
                        {
                            if (SL_Scheduler.eBayService.IsUserWinning(this._Snipe)) break;
                            SL_Scheduler.eBayService.SetSnipe(this._Snipe);
                            System.Threading.Thread.Sleep(1000);
                        }
                    }
                    catch (ControlObjectException ex)
                    {
                        foreach (UserMessage message in ex.ErrorList)
                        {
                            if (message.MessageCode == EnumMessageCode.SnipeBidOptimizerMaxBidReached)
                            {
                                UltimateSniper_Services.ServiceEmail emailService = new UltimateSniper_Services.ServiceEmail();

                                _Snipe.SnipeStatus = EnumSnipeStatus.OVERBID;
                                _Snipe.SnipeErrorReason = "The snipe bid is lower the current price.";

                                ServiceEmail.SendEmail(user, "[SnipeAgent] Maximum bid reached for: " + _Snipe.SnipeName, "Hello, the maximum bid for your item has been reached. You can still modify it and win the item. To do so, go on www.snipeagent.com and into the section 'My Snipes'. Kind regards, Snipe Agent.");
                            }
                        }
                        _Snipe.SnipeErrorReason = ex.Message;
                    }
                    catch (Exception ex)
                    {
                        _Snipe.SnipeErrorReason = ex.Message;
                    }
                }

                _Snipe.ItemLastUdpate = ServiceTimeZone.DateTimeToUniversal(DateTime.Now);
                _Snipe.SnipeInProgress = false;

                myDataConnection.Save<Snipe>((object)_Snipe, _Snipe);

            }
            catch (ControlObjectException ex)
            {
                foreach (UserMessage error in ex.ErrorList)
                    Logger.CreateLog("Error__Timer_BidOptimizer_RefreshSnipes_" + error.MessageCode.ToString() + error.Severity.ToString(), null, ex, EnumLogLevel.ERROR);
            }
            catch (Exception ex)
            {
                Logger.CreateLog("Error__Timer_BidOptimizer_RefreshSnipes", null, ex, EnumLogLevel.ERROR);
            }
        }
Exemplo n.º 21
0
        public void GetSimilarItemsTest()
        {
            ServiceEBay target = new ServiceEBay(true); // TODO: Initialize to an appropriate value
            Snipe snipe = new Snipe();
            List<eBayItemData> expected = null; // TODO: Initialize to an appropriate value
            List<eBayItemData> actual;

            IList<User> users = new List<User>();

            SqlDataContext myDataConnection = new SqlDataContext();

            Query q = new Query();

            Criterion crit = new Criterion();
            crit.Operator = CriteriaOperator.Equal;
            crit.PropertyName = "UserID";
            crit.Value = "2";

            q.Criteria.Add(crit);

            q.Members.Add("*");

            users = myDataConnection.GetByCriteria<User>(q);

            target.User = users[0];

            IList<Snipe> snipes = new List<Snipe>();

            myDataConnection = new SqlDataContext();

            q = new Query();

            crit = new Criterion();
            crit.Operator = CriteriaOperator.Equal;
            crit.PropertyName = "SnipeID";
            crit.Value = "1";

            q.Criteria.Add(crit);

            q.Members.Add("*");

            snipes = myDataConnection.GetByCriteria<Snipe>(q);

            snipe = snipes[0];

            actual = target.GetSimilarItems(snipe);
            Assert.AreEqual(expected, actual);
            Assert.Inconclusive("Verify the correctness of this test method.");
        }
Exemplo n.º 22
0
 public IQueryable <Response> GetResponses()
 {
     return(SqlDataContext.Repository <Response>().Query().Get());
 }
Exemplo n.º 23
0
        public Snipe GetSnipe(int snipeID)
        {
            SqlDataContext myDataConnection = new SqlDataContext();

            Query q = new Query();

            Criterion crit = new Criterion();
            crit.Operator = CriteriaOperator.Equal;
            crit.PropertyName = "SnipeID";
            crit.Value = snipeID;

            q.Criteria.Add(crit);

            q.Members.Add("*");

            List<Snipe> snipes = myDataConnection.GetByCriteria<Snipe>(q).ToList();

            if (snipes.Count != 1)
                throw new Exception("Error when loading the snipe");
            else
                return snipes[0];
        }
Exemplo n.º 24
0
        public User GetUserForSnipe(Snipe snipe)
        {
            SqlDataContext myDataConnection = new SqlDataContext();

            Query q = new Query();

            Criterion c = new Criterion();
            c.Operator = CriteriaOperator.Equal;
            c.PropertyName = "UserID";
            c.Value = snipe.UserID;

            q.Criteria.Add(c);

            q.Members.Add("*");

            IList<User> userList = myDataConnection.GetByCriteria<User>(q);

            if (userList.Count != 1)
                return null;
            else
                return userList[0];
        }
Exemplo n.º 25
0
        public void WhenEntityExposesEvent_ThenRepositoryPublishesIt()
        {
            var busMock = new Mock<IEventBus>();
            var events = new List<IEvent>();

            busMock
                .Setup(x => x.Publish(It.IsAny<IEnumerable<Envelope<IEvent>>>()))
                .Callback<IEnumerable<Envelope<IEvent>>>(x => events.AddRange(x.Select(e => e.Body)));

            var @event = new TestEvent();

            using (var context = new SqlDataContext<TestEventPublishingAggregateRoot>(() => new TestDbContext(), busMock.Object))
            {
                var aggregate = new TestEventPublishingAggregateRoot(Guid.NewGuid());
                aggregate.AddEvent(@event);
                context.Save(aggregate);
            }

            Assert.Equal(1, events.Count);
            Assert.True(events.Contains(@event));
        }
Exemplo n.º 26
0
 public AdministradorRepository(SqlDataContext sqlDataContext)
 {
     this.sqlDataContext = sqlDataContext;
 }