Exemple #1
0
 protected BaseEFService(
     RobotContext dbContext,
     IMapper mapper)
 {
     this.DbContext = dbContext;
     this.Mapper    = mapper;
 }
 public virtual ITradeEvent StopTrading(RobotContext context)
 {
     var lastCandle = context.Candles.Last();
     context.Logger.Debug("Stop trading command. Last candle: {0}", lastCandle);
     context.CurrentState = context.Factory.GetEndState(context);
     return new DealEvent(new Deal(lastCandle.Close, lastCandle.DateTime, !TrendIsLong));
 }
Exemple #3
0
        public override void Initialize(RobotContext context, CurrentProtectedContext protectedContext)
        {
            var    cfgFileName = Assembly.GetAssembly(GetType()).Location + ".xml";
            string error;

            newsSettings = NewsSettings.LoadNewsSettings(cfgFileName, out error);
            if (error != null)
            {
                pendingLogMessages.Add(error);
            }
            currencySettings = CurrencySettings.LoadCurrencySettings(cfgFileName, out error);
            if (error != null)
            {
                pendingLogMessages.Add(error);
            }
            if (string.IsNullOrEmpty(Formula))
            {
                pendingLogMessages.Add("формула не задана");
            }
            try
            {
                expressionResolver = new ExpressionResolver(Formula.ToLower());
            }
            catch (Exception)
            {
                pendingLogMessages.Add("ошибка в формуле");
            }
            base.Initialize(context, protectedContext);
        }
Exemple #4
0
 public RobotController(RobotContext context, IMapper mapper, IArmMovement armMovement, IHeadMovement headMovement)
 {
     _context      = context;
     _mapper       = mapper;
     _armMovement  = armMovement;
     _headMovement = headMovement;
 }
 public BasicTradeState(RobotContext context, Deal deal)
 {
     context.Logger.Debug("Change state to {0}", GetType().Name);
     StartPrice = deal.Price;
     TrendIsLong = deal.IsBuy;
     context.StopLossPrice = GetStopPrice(StartPrice, context.StopLossSize);
 }
        public override void Initialize(RobotContext grobotContext, CurrentProtectedContext protectedContextx)
        {
            base.Initialize(grobotContext, protectedContextx);
            if (Graphics.Count == 0)
            {
                Logger.DebugFormat("IchimokuRobot: настройки графиков не заданы");
                return;
            }
            if (Graphics.Count > 1)
            {
                Logger.DebugFormat("IchimokuRobot: настройки графиков должны описывать один тикер / один ТФ");
                return;
            }

            mainCandlePacker = new CandlePacker(MainTimeFrame);
            dayCandlePacker  = new CandlePacker(dayTimeFrame);
            hourCandlePacker = new CandlePacker(hourTimeFrame);

            // размер этой очереди именно periodL + periodM. Это связано с тем, что рассчитать "облако" надо для "сдвинутой" назад точки, а не для текущей.
            // А что бы это сделать, нужно отступить от "сдвинутой назад точки" ещё на periodL.
            shiftBackPoints = new RestrictedQueue <CandleData>(periodL + periodM);

            subQueue = new[] { new RestrictedQueue <CandleData>(periodMSub1), new RestrictedQueue <CandleData>(periodMSub2) };

            happenIntersection = new RestrictedQueue <bool>(m);
            ticker             = Graphics[0].a;
        }
Exemple #7
0
 /// <summary>
 /// 获取机器码
 /// </summary>
 /// <returns></returns>
 public Machine Get()
 {
     using (RobotContext db = new RobotContext())
     {
         return(db.Set <Machine>().FirstOrDefault());
     }
 }
 public List <MessageType> GetNewMessage()
 {
     using (RobotContext db = new RobotContext())
     {
         var data = db.Set <MessageType>().AsNoTracking().ToList();
         return(data);
     }
 }
        public override void Initialize(RobotContext grobotContext, CurrentProtectedContext gprotectedContext)
        {
            base.Initialize(grobotContext, gprotectedContext);

            packers       = Graphics.ToDictionary(g => g.a, g => new CandlePacker(g.b));
            rsiClosePairs = Graphics.ToDictionary(g => g.a, g => new RestrictedQueue <PriceRsi>(period));

            lastMessages = new List <string>();
        }
Exemple #10
0
 private void Start()
 {
     script        = new Script();
     robot_context = new RobotContext(this);
     foreach (var type in registered_types)
     {
         UserData.RegisterType(type);
     }
     robot_context_desc = UserData.GetDescriptorForObject(robot_context);
 }
 public void SetMessage(List <MessageType> listMessage)
 {
     using (RobotContext db = new RobotContext())
     {
         var data = db.Set <MessageType>().ToList();
         db.Set <MessageType>().RemoveRange(data);
         db.SaveChanges();
         db.Set <MessageType>().AddRange(listMessage);
         db.SaveChanges();
     }
 }
Exemple #12
0
        /// <summary>
        /// 授权应用
        /// </summary>
        /// <returns></returns>
        public OperResult Auth(string authCode, string mcCode)
        {
            OperResult result = new OperResult();

            result.Code = ResultCodeEnums.warning;
            result.Msg  = "授权未完成";
            MachineSvc svc = new MachineSvc();

            svc.Add(mcCode);
            if (string.IsNullOrEmpty(mcCode))
            {
                result.Code = ResultCodeEnums.Error;
                result.Msg  = "未能获取到机器码!";
                return(result);
            }
            int count = 0;

            if (!int.TryParse(GetAESInfo.Get(authCode, mcCode), out count))
            {
                result.Code = ResultCodeEnums.warning;
                result.Msg  = "无效的授权码,请输入有效的授权码!";
                return(result);
            }
            ServiceRecord Record = new ServiceRecord();

            Record.IsAuth       = true;
            Record.LastOperTime = DateTime.Now;
            Record.SurplusTotal = authCode;
            Record.Total        = authCode;
            using (RobotContext db = new RobotContext())
            {
                var data = db.Set <ServiceRecord>().Where(a => true).FirstOrDefault();
                if (null == data)
                {
                    db.Set <ServiceRecord>().Add(Record);
                }
                else
                {
                    data.IsAuth       = true;
                    data.LastOperTime = DateTime.Now;
                    data.SurplusTotal = authCode;
                    data.Total        = authCode;
                }
                int res = db.SaveChanges();
                if (res > 0)
                {
                    result.Code = ResultCodeEnums.success;
                    result.Msg  = "授权成功!";
                    return(result);
                }
            }
            return(result);
        }
 public override void Initialize(RobotContext grobotContext, CurrentProtectedContext protectedContextx)
 {
     base.Initialize(grobotContext, protectedContextx);
     if (Graphics.Count == 0)
     {
         Logger.DebugFormat("OptionTraderRobot: настройки графиков не заданы");
         return;
     }
     tickers          = Graphics.Select(r => r.a).ToArray();
     tickerVolatility = tickers.ToDictionary(t => t,
                                             t => Model == PriceModel.Gauss ?
                                             (IVolatilityCalculator) new GaussVolatilityCalculator(200) : new ReverseVolatilityCalculator(1000));
 }
        public SearchState(RobotContext context)
        {
            context.Logger.Debug("Change state to Search");

            ExtremumsRepo = new ExtremumsRepository();
            searchTree = new LinkedList<CandleNode>();

            for (int i = 0; i < context.Candles.Count; ++i)
            {
                AppendToTree(context.Candles[i], i);
            }

            pegTopSize = context.PegtopSize;
        }
Exemple #15
0
 /// <summary>
 /// This method is used to configure the strategy and is called once before any strategy method is called.
 /// </summary>
 public virtual void Initialize(RobotContext robotContext, CurrentProtectedContext protectedContext)
 {
     this.protectedContext = protectedContext;
     this.robotContext     = robotContext;
     TerminalLog.Instance.SaveRobotLog(string.Format("Запущен робот {0} #{1}",
                                                     GetUniqueName(), robotContext.AccountInfo.ID));
     if ((FixedVolume ?? 0) <= 0 && (Leverage ?? 0) <= 0)
     {
         if (lastMessages != null)
         {
             lastMessages.Add("Не указаны ни плечо сделки, ни фиксированный объем входа. Торговля осуществляться не будет");
         }
     }
 }
Exemple #16
0
        /// <summary>
        /// 更新使用次数
        /// </summary>
        /// <returns></returns>
        public void SetRecord()
        {
            MachineSvc svc     = new MachineSvc();
            var        machine = svc.Get();

            using (RobotContext db = new RobotContext())
            {
                var data = db.Set <ServiceRecord>().FirstOrDefault();
                int now  = int.Parse(GetAESInfo.Get(data.SurplusTotal, machine.MachineCode));
                now--;
                data.SurplusTotal = GetAESInfo.Set(now.ToString(), machine.MachineCode);
                data.LastOperTime = DateTime.Now;
                db.SaveChanges();
            }
        }
 public override void Initialize(RobotContext robotContext, CurrentProtectedContext protectedContext)
 {
     base.Initialize(robotContext, protectedContext);
     if (Graphics.Count == 0)
     {
         Logger.DebugFormat("OptionUpDownMartinRobot: настройки графиков не заданы");
         return;
     }
     packers                  = Graphics.ToDictionary(g => g.a, g => new CandlePacker(g.b));
     lastCandles              = Graphics.ToDictionary(g => g.a, g => new RestrictedQueue <CandleData>(candlesBeforeEnter));
     betsBySymbol             = Graphics.ToDictionary(g => g.a, g => new List <Bet>());
     betsHistory              = Graphics.ToDictionary(g => g.a, g => new List <Bet>());
     balance                  = StartDepo;
     maxBalance               = StartDepo;
     betNumberWhenDepoWasLost = 0;
 }
Exemple #18
0
        /// <summary>
        /// 新增唯一机器码
        /// </summary>
        public void Add(string code)
        {
            Machine mc = new Machine();

            mc.MachineCode = code;
            using (RobotContext db = new RobotContext())
            {
                var data = db.Set <Machine>().FirstOrDefault();
                if (null == data)
                {
                    db.Set <Machine>().Add(mc);
                }
                else
                {
                    data.MachineCode = code;
                }
                db.SaveChanges();
            }
        }
        public virtual ITradeEvent Process(RobotContext context, Candle candle)
        {
            if (candle.Time >= context.EndTime)
            {
                context.Logger.Debug("End time exit. StopPrice: {0}, Candle: {1}", context.StopLossPrice, candle);
                context.CurrentState = context.Factory.GetEndState(context);
                return new DealEvent(new Deal(candle.Close, candle.DateTime, !TrendIsLong));
            }

            if (TrendIsLong && candle.Low <= context.StopLossPrice ||
                !TrendIsLong && candle.High >= context.StopLossPrice)
            {
                context.Logger.Debug("Stop has catched. StopPrice: {0}, Candle: {1}", context.StopLossPrice, candle);
                context.CurrentState = context.Factory.GetEndState(context);
                return new StopLossEvent(new Deal(context.StopLossPrice, candle.DateTime, !TrendIsLong));
            }

            return null;
        }
        public ITradeEvent Process(RobotContext context, Candle candle)
        {
            int currentIndex = context.Candles.Count - 1;
            var bestSecondExtremum = AppendToTree(candle, currentIndex);

            if (bestSecondExtremum == null)
                return null;

            if (NeedToTrade(context, bestSecondExtremum))
            {
                context.Logger.Debug("Need to trade, extremum: {0}", bestSecondExtremum);
                var deal = new Deal(candle.Close, candle.DateTime, bestSecondExtremum.IsMinimum, context.Advisor.GetAdvice(candle.Close, bestSecondExtremum.IsMinimum));

                context.Logger.Debug("Deal: {0}", deal);
                context.CurrentState = context.Factory.GetTradeState(context, deal);
                return new DealEvent(deal);
            }

            return new SecondExtremumEvent(bestSecondExtremum, ExtremumsRepo.FirstMaximums, ExtremumsRepo.FirstMinimums);
        }
        public override ITradeEvent Process(RobotContext context, Candle candle)
        {
            var result = base.Process(context, candle);
            if (result != null)
                return result;

            if (!hasBreakeven &&
                (TrendIsLong && candle.High >= StartPrice + context.StopLossSize ||
                !TrendIsLong && candle.Low <= StartPrice - context.StopLossSize))
            {
                hasBreakeven = true;

                context.StopLossPrice = GetStopPrice(StartPrice, -context.BreakevenSize);

                context.Logger.Debug("Breakeven. StopPrice: {0}, Candle: {1}", context.StopLossPrice, candle);
                return new StopLossMovingEvent(context.StopLossPrice, TrendIsLong);
            }

            return null;
        }
Exemple #22
0
        /// <summary>
        /// 判断是否有受权记录或已受权
        /// </summary>
        /// <returns></returns>
        public OperResult IsAuth()
        {
            ServiceRecord record = null;
            string        key    = string.Empty;

            using (RobotContext db = new RobotContext())
            {
                record = db.Set <ServiceRecord>().FirstOrDefault();
                var mc = db.Set <Machine>().FirstOrDefault();
                if (mc != null)
                {
                    key = mc.MachineCode;
                }
            }
            OperResult result = new OperResult();

            if (record == null)
            {
                result.Msg  = "应用未授权";
                result.Code = ResultCodeEnums.UnAuth;
            }
            else if (record.IsAuth == false)
            {
                result.Msg  = "应用未授权";
                result.Code = ResultCodeEnums.UnAuth;
            }
            else if (int.Parse(GetAESInfo.Get(record.SurplusTotal, key)) <= 0)
            {
                result.Msg  = "应用使用次数已用完";
                result.Code = ResultCodeEnums.AuthExpire;
            }
            else
            {
                result.Msg  = "应用已授权";
                result.Code = ResultCodeEnums.Auth;
            }
            return(result);
        }
        public override ITradeEvent Process(RobotContext context, Candle candle)
        {
            var result = base.Process(context, candle);
            if (result != null)
                return result;

            if (TrendIsLong)
            {
                if (candle.High - context.StopLossPrice >= context.TrailingStopLoss)
                {
                    var newPrice = GetStopPrice(candle.High, context.TrailingStopLoss);
                    if (newPrice > context.StopLossPrice	//if stopSize < trailingStopSize
                        && newPrice < candle.Close)
                    {
                        context.StopLossPrice = newPrice;
                        context.Logger.Debug("Trailing moving. StopPrice: {0}, Candle: {1}", context.StopLossPrice, candle);
                        result = new StopLossMovingEvent(context.StopLossPrice, TrendIsLong);
                    }
                }
            }
            else
            {
                if (context.StopLossPrice - candle.Low >= context.TrailingStopLoss)
                {
                    var newPrice = GetStopPrice(candle.Low, context.TrailingStopLoss);
                    if (newPrice < context.StopLossPrice
                        && newPrice > candle.Close)
                    {
                        context.StopLossPrice = newPrice;
                        context.Logger.Debug("Trailing moving. StopPrice: {0}, Candle: {1}", context.StopLossPrice, candle);
                        result = new StopLossMovingEvent(context.StopLossPrice, TrendIsLong);
                    }
                }
            }

            return result;
        }
Exemple #24
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, RobotContext db)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            db.Database.EnsureCreated();
            if (!db.Robots.Any())
            {
                StreamReader r    = new StreamReader("bots.json");
                string       json = r.ReadToEnd();
                List <Robot> bots = JsonConvert.DeserializeObject <List <Robot> >(json);
                db.AddRange(bots);
                db.SaveChanges();
            }
            app.UseHttpsRedirection();
            app.UseMvc();
        }
 public DetailsWeaponModel(RobotContext context)
 {
     _context = context;
 }
 public EditWeaponModel(RobotContext context)
 {
     _context = context;
 }
 public RobotDataService(RobotContext dbContext, IMapper mapper, UserManager <User> userManager)
     : base(dbContext, mapper)
 {
     this.userManager = userManager;
 }
 public DeleteArmorModel(RobotContext context)
 {
     _context = context;
 }
Exemple #29
0
 public Repository(RobotContext context)
 {
     _context = context;
 }
        public void EditingRobot_ShouldEditRobotName()
        {
            var users = new[]
            {
                new User()
                {
                    Id = "111"
                },
                new User()
                {
                    Id = "222"
                },
                new User()
                {
                    Id = "333"
                },
                new User()
                {
                    Id = "444"
                }
            };
            var mockUserStore   = new Mock <IUserStore <User> >();
            var mockUserManager = new Mock <UserManager <User> >(
                mockUserStore.Object, null, null, null, null, null, null, null, null);

            mockUserManager.Setup(um => um.GetUserAsync(null))
            .ReturnsAsync(users[1]);


            this.dbContext     = MockDbContext.GetContext();
            this.service       = new RobotDataService(dbContext, MockAutoMapper.GetAutoMapper(), mockUserManager.Object);
            this.armorService  = new ArmorDataService(dbContext, this.service, MockAutoMapper.GetAutoMapper(), mockUserManager.Object);
            this.weaponService = new WeaponDataService(dbContext, this.service, MockAutoMapper.GetAutoMapper(), mockUserManager.Object);

            var controller = new RobotController(mockUserManager.Object, MockAutoMapper.GetAutoMapper(), this.service, this.weaponService, this.armorService);

            controller.ControllerContext = new ControllerContext()
            {
                HttpContext = new DefaultHttpContext()
                {
                    User = new ClaimsPrincipal(new ClaimsIdentity(new[]
                    {
                        new Claim(ClaimTypes.Role, "Admin")
                    }))
                }
            };
            var user2 = controller.ControllerContext.HttpContext.User;


            var robot = new Models.Robots.Robot()
            {
                Id            = 1,
                BaseHealth    = 1000,
                CurrentHealth = 1000,
                BaseDamage    = 100,
                Type          = "Fire",
                ImageUrl      = "https://i.ytimg.com/vi/Rrb4jW_uJxE/hqdefault.jpg"
            };

            this.dbContext.Robots.Add(robot);
            this.dbContext.SaveChanges();
            var updateNameBindingModel = new UpdateNameBindingModel()
            {
                Name = "Edited"
            };
            var result = controller.Edit(robot.Id, updateNameBindingModel);

            //service.CreateRobotAsync(user2, robot);
            Assert.AreEqual("Edited", dbContext.Robots.First().Name);
        }
 public CreepDataService(RobotContext dbContext, IMapper mapper)
     : base(dbContext, mapper)
 {
 }
        public async void RepairCenter_ShouldRepairArmor()
        {
            var users = new[]
            {
                new User()
                {
                    Id = "222"
                },
                new User()
                {
                    Id = "333"
                },
                new User()
                {
                    Id = "444"
                }
            };



            //setup your expectations here

            var mockUserStore   = new Mock <IUserStore <User> >();
            var mockUserManager = new Mock <UserManager <User> >(
                mockUserStore.Object, null, null, null, null, null, null, null, null);

            mockUserManager.Setup(um => um.GetUserAsync(null))
            .ReturnsAsync(users[1]);
            this.dbContext        = MockDbContext.GetContext();
            this.service          = new RobotDataService(dbContext, MockAutoMapper.GetAutoMapper(), mockUserManager.Object);
            this.armorService     = new ArmorDataService(dbContext, this.service, MockAutoMapper.GetAutoMapper(), mockUserManager.Object);
            this.weaponService    = new WeaponDataService(dbContext, this.service, MockAutoMapper.GetAutoMapper(), mockUserManager.Object);
            this.creepService     = new CreepDataService(dbContext, this.service, MockAutoMapper.GetAutoMapper());
            this.dbContextService = new DbContextService(dbContext, this.service, MockAutoMapper.GetAutoMapper(), mockUserManager.Object);
            this.userService      = new UserDataService(dbContext, MockAutoMapper.GetAutoMapper(), mockUserManager.Object);

            var controller = new RepairCenterController(mockUserManager.Object, MockAutoMapper.GetAutoMapper(), dbContextService, this.service, armorService, weaponService, userService);

            controller.ControllerContext = new ControllerContext()
            {
                HttpContext = new DefaultHttpContext()
                {
                    User = new ClaimsPrincipal(new ClaimsIdentity(new[]
                    {
                        new Claim(ClaimTypes.Role, "Admin")
                    }))
                }
            };
            var tempData = new TempDataDictionary(controller.HttpContext, Mock.Of <ITempDataProvider>());

            controller.TempData = tempData;

            var newwwwUser = new User()
            {
                Id = "1", Coins = 251
            };
            var armor = new ArmorDetailsViewModel()
            {
                Id           = 1,
                Name         = "mechoo",
                ArmorPoints  = 101,
                CurrentArmor = 50,
                Durability   = 50,
                ImageUrl     = "kk",
                Price        = 120,
            };

            dbContext.Users.Add(newwwwUser);
            var actualArmor = new Armor()
            {
                Id          = 1,
                Name        = "mechoo",
                ArmorPoints = 101,
                Durability  = 50,
                ImageUrl    = "kk",
                Price       = 120,
                UserId      = "1",
                User        = newwwwUser
            };

            this.dbContext.Armors.Add(actualArmor);
            this.dbContext.SaveChanges();
            await controller.Repair(1, "ArmorRepairViewModel");

            Assert.AreEqual(1, newwwwUser.Coins);
        }
Exemple #33
0
 public ITradeEvent Process(RobotContext context, Candle candle)
 {
     return new EndEvent();
 }
 public ITradeEvent StopTrading(RobotContext context)
 {
     context.Logger.Debug("Stop trading command");
     context.CurrentState = context.Factory.GetEndState(context);
     return new EndEvent();
 }
Exemple #35
0
 public ITradeEvent StopTrading(RobotContext context)
 {
     return new EndEvent();
 }
 public TrailingTradeState(RobotContext context, Deal deal)
     : base(context, deal)
 {
 }
 private bool NeedToTrade(RobotContext context, Extremum secondExtremum)
 {
     var isTrendLong = IsTrendLong(context.Candles);
     context.Logger.Debug("NeedToTrade? extremum:{0}, trend:{1}", secondExtremum.IsMinimum, isTrendLong);
     return secondExtremum.IsMinimum == isTrendLong;
 }
Exemple #38
0
        public async void Fight_ShouldDecreaseRobotPoints()
        {
            var users = new[]
            {
                new User()
                {
                    Id = "111"
                },
                new User()
                {
                    Id = "222"
                },
                new User()
                {
                    Id = "333"
                },
                new User()
                {
                    Id = "444"
                }
            };

            var mockUserStore   = new Mock <IUserStore <User> >();
            var mockUserManager = new Mock <UserManager <User> >(
                mockUserStore.Object, null, null, null, null, null, null, null, null);

            mockUserManager.Setup(um => um.GetUserAsync(null))
            .ReturnsAsync(users[1]);


            this.dbContext        = MockDbContext.GetContext();
            this.service          = new RobotDataService(dbContext, MockAutoMapper.GetAutoMapper(), mockUserManager.Object);
            this.armorService     = new ArmorDataService(dbContext, this.service, MockAutoMapper.GetAutoMapper(), mockUserManager.Object);
            this.weaponService    = new WeaponDataService(dbContext, this.service, MockAutoMapper.GetAutoMapper(), mockUserManager.Object);
            this.creepService     = new CreepDataService(dbContext, this.service, MockAutoMapper.GetAutoMapper());
            this.dbContextService = new DbContextService(dbContext, this.service, MockAutoMapper.GetAutoMapper(), mockUserManager.Object);



            var robot = new Models.Robots.Robot()
            {
                Id            = 1,
                BaseHealth    = 1000,
                CurrentHealth = 1000,
                BaseDamage    = 100,
                Type          = "Fire",
                ImageUrl      = "https://i.ytimg.com/vi/Rrb4jW_uJxE/hqdefault.jpg"
            };
            var creep = new Creep()
            {
                Id       = 1,
                Name     = "aaaa",
                Type     = "Fire",
                Health   = 1000,
                Damage   = 100,
                Bounty   = 10,
                ImageUrl = "1"
            };

            var controller = new BattleController
                             (
                mockUserManager.Object,
                MockAutoMapper.GetAutoMapper(),
                this.service,
                this.creepService,
                this.dbContextService
                             );

            controller.ControllerContext = new ControllerContext()
            {
                HttpContext = new DefaultHttpContext()
                {
                    User = new ClaimsPrincipal(new ClaimsIdentity(new[]
                    {
                        new Claim(ClaimTypes.Role, "Admin")
                    }))
                }
            };
            this.dbContext.Robots.Add(robot);
            this.dbContext.Creeps.Add(creep);
            this.dbContext.SaveChanges();
            await controller.Fight(robot.Id, creep.Id);

            Assert.AreEqual(0, robot.CurrentHealth);
        }
Exemple #39
0
 public EndState(RobotContext context)
 {
     context.Logger.Debug("Change state to End");
 }
 public BreakevenTradeState(RobotContext context, Deal deal)
     : base(context, deal)
 {
 }
        public void UnequipArmor_ShouldRemoveArmorFromRobot()
        {
            var users = new[]
            {
                new User()
                {
                    Id = "111"
                },
                new User()
                {
                    Id = "222"
                },
                new User()
                {
                    Id = "333"
                },
                new User()
                {
                    Id = "444"
                }
            };
            var mockUserStore   = new Mock <IUserStore <User> >();
            var mockUserManager = new Mock <UserManager <User> >(
                mockUserStore.Object, null, null, null, null, null, null, null, null);

            mockUserManager.Setup(um => um.GetUserAsync(null))
            .ReturnsAsync(users[1]);


            this.dbContext = MockDbContext.GetContext();
            this.service   = new RobotDataService(dbContext, MockAutoMapper.GetAutoMapper(), mockUserManager.Object);

            this.armorService  = new ArmorDataService(dbContext, this.service, MockAutoMapper.GetAutoMapper(), mockUserManager.Object);
            this.weaponService = new WeaponDataService(dbContext, this.service, MockAutoMapper.GetAutoMapper(), mockUserManager.Object);

            var controller = new RobotController(mockUserManager.Object, MockAutoMapper.GetAutoMapper(), this.service, this.weaponService, this.armorService);

            controller.ControllerContext = new ControllerContext()
            {
                HttpContext = new DefaultHttpContext()
                {
                    User = new ClaimsPrincipal(new ClaimsIdentity(new[]
                    {
                        new Claim(ClaimTypes.Role, "Admin")
                    }))
                }
            };
            var user2 = controller.ControllerContext.HttpContext.User;


            var robot = new Models.Robots.Robot()
            {
                Id            = 1,
                BaseHealth    = 1000,
                CurrentHealth = 1000,
                BaseDamage    = 100,
                Type          = "Fire",
                ImageUrl      = "https://i.ytimg.com/vi/Rrb4jW_uJxE/hqdefault.jpg"
            };
            var armor = new Models.Items.Armor()
            {
                Name                 = "mechoo",
                ArmorPoints          = 101,
                DurabilityLossAmount = 15,
                ImageUrl             = "kk",
                Price                = 101
            };

            dbContext.Robots.Add(robot);
            dbContext.Armors.Add(armor);
            robot.Armors.Add(armor);
            this.dbContext.SaveChanges();
            var result = controller.UnequipArmor(robot.Id, armor.Id);

            this.dbContext.SaveChanges();
            Assert.AreEqual(0, robot.Armors.Count());
        }
Exemple #42
0
 public DbContextService(RobotContext dbContext, IRobotDataService robotDataService, IMapper mapper, UserManager <User> userManager)
     : base(dbContext, mapper)
 {
     this.userManager      = userManager;
     this.robotDataService = robotDataService;
 }
Exemple #43
0
 public RobotsController(RobotContext context)
 {
     _context = context;
 }
 public ScenesController(RobotContext context)
 {
     _context = context;
 }