Пример #1
0
 public void Setup()
 {
     robotServiceMock = new Mock <IRobotService>();
     robotServiceMock.Setup(x => x.Move(It.IsAny <Arena>(), It.IsAny <Robot>()));
     robotServiceMock.Setup(x => x.Spin(It.IsAny <Direction>(), It.IsAny <Robot>()));
     warService = new WarService(robotServiceMock.Object);
 }
        public void DeleteTransformerReturns_Nothing()
        {
            using (var context = getDBContext())
            {
                var warsService = new WarService(context, _mockLogger.Object);
                Models.DTO.TransformerRequest transformer = new Models.DTO.TransformerRequest()
                {
                    AllegianceType = AllegianceTypes.Autobot,
                    Courage        = 1,
                    Endurance      = 1,
                    Firepower      = 1,
                    Intelligence   = 1,
                    Name           = "Autobot",
                    Rank           = 1,
                    Skill          = 1,
                    Speed          = 1,
                    Strength       = 1
                };

                var addTransformerResult = warsService.AddTransformer(transformer).Result;

                var transformerResult = warsService.DeleteTransformer(context.Transformers.First().TransformerId);
                Assert.Equal(0, context.Transformers.Count());

                context.Database.EnsureDeleted();
            }
        }
        public void GetTransformerReturns_WithATransformer()
        {
            using (var context = getDBContext())
            {
                Models.DB.Transformer autoBotTransformer = new Models.DB.Transformer()
                {
                    Name             = "Autobot",
                    AllegianceTypeId = (int)AllegianceTypes.Autobot,
                    Courage          = 1,
                    Endurance        = 1,
                    Firepower        = 1,
                    Intelligence     = 1,
                    Rank             = 1,
                    Skill            = 1,
                    Speed            = 1,
                    Strength         = 1
                };


                context.Transformers.Add(autoBotTransformer);
                context.SaveChanges();

                var warsService   = new WarService(context, _mockLogger.Object);
                var autoBotResult = warsService.GetTransformer(autoBotTransformer.TransformerId).Result;
                Assert.Equal(autoBotTransformer.Name, autoBotResult.Name);
                context.Database.EnsureDeleted();
            }
        }
Пример #4
0
        public ActionResult PostInTakeForm(InTakeModel model)
        {
            var shelterType = ShelterType.Men;


            if (ModelState.IsValid)
            {
                var clientToAdd = new Client
                {
                    FirstName   = model.FirstName,
                    LastName    = model.LastName,
                    SSN         = model.SSN,
                    PhoneNumber = model.PhoneNumber,
                    DateOfBirth = model.DateOfBirth,
                    Race        = model.Race,
                    Gender      = model.Gender,
                    Ethnicity   = model.Ethnicity,
                    Email       = model.Email
                };

                if (model.VetStatus != null)
                {
                    clientToAdd.VetStatus = model.VetStatus;
                }

                shelterType = ShelterTypeMapper.Map[model.Gender];

                if (model.IsVet)
                {
                    clientToAdd.Veteran = true;
                    shelterType         = ShelterType.Veterans;
                    var warService = new WarService
                    {
                        Client      = clientToAdd,
                        WarServedIn = model.VetStatus.WarServedIn.Value,
                        YearStarted = model.VetStatus.YearEnteredService.Value,
                        YearEnded   = model.VetStatus.YearLeftService.Value
                    };
                    clientToAdd.WarServices.Add(warService);
                }

                var shelterMatcherResult = new ShelterMatcher().Match(clientToAdd, shelterType, _dbContext);

                //clientToAdd.Shelter =  shelterMatcherResult.IsBooked? shelterMatcherResult.Shelter: null;
                if (shelterMatcherResult.IsBooked)
                {
                    //clientToAdd.Shelter = shelterMatcherResult.Shelter;
                    _dbContext.BedBookings.Add(Reserve(clientToAdd, shelterType, shelterMatcherResult.Shelter));
                }

                _dbContext.Clients.Add(clientToAdd);

                _dbContext.SaveChanges();
                return(View(shelterMatcherResult));
            }
            ;
            return(Json(false));
        }
 public void GetTransformerReturns_Error_WhenNotFound()
 {
     using (var context = getDBContext())
     {
         var warsService = new WarService(context, _mockLogger.Object);
         Assert.ThrowsAsync <TransformerWarsException>(() => warsService.GetTransformer(123));
         context.Database.EnsureDeleted();
     }
 }
        public void GetTransformersReturns_WithAListOfTransformers()
        {
            using (var context = getDBContext())
            {
                Models.DB.Transformer autoBotTransformer = new Models.DB.Transformer()
                {
                    Name             = "Autobot",
                    AllegianceTypeId = (int)AllegianceTypes.Autobot,
                    Courage          = 1,
                    Endurance        = 1,
                    Firepower        = 1,
                    Intelligence     = 1,
                    Rank             = 1,
                    Skill            = 1,
                    Speed            = 1,
                    Strength         = 1
                };

                Models.DB.Transformer decepticonTransformer = new Models.DB.Transformer()
                {
                    Name             = "Decepticon",
                    AllegianceTypeId = (int)AllegianceTypes.Decepticon,
                    Courage          = 1,
                    Endurance        = 1,
                    Firepower        = 1,
                    Intelligence     = 1,
                    Rank             = 1,
                    Skill            = 1,
                    Speed            = 1,
                    Strength         = 1
                };

                context.Transformers.Add(autoBotTransformer);
                context.Transformers.Add(decepticonTransformer);
                context.SaveChanges();

                var warsService   = new WarService(context, _mockLogger.Object);
                var autoBotResult = warsService.GetTransformers(Models.AllegianceTypes.Autobot).Result;
                Assert.Collection(autoBotResult, item => Assert.Contains("Autobot", item.Name));
                var decepticonResult = warsService.GetTransformers(Models.AllegianceTypes.Decepticon).Result;
                Assert.Collection(decepticonResult, item => Assert.Contains("Decepticon", item.Name));
                context.Database.EnsureDeleted();
            }
        }
        public void RunWarsReturns_WithNoVictor_WhenNameIsOptimusVsPredaking()
        {
            using (var context = getDBContext())
            {
                Models.DB.Transformer autoBotTransformer = new Models.DB.Transformer()
                {
                    Name             = "Optimus",
                    AllegianceTypeId = (int)AllegianceTypes.Autobot,
                    Courage          = 10,
                    Endurance        = 10,
                    Firepower        = 10,
                    Intelligence     = 10,
                    Rank             = 10,
                    Skill            = 10,
                    Speed            = 10,
                    Strength         = 10
                };

                Models.DB.Transformer decepticonTransformer = new Models.DB.Transformer()
                {
                    Name             = "Predaking",
                    AllegianceTypeId = (int)AllegianceTypes.Decepticon,
                    Courage          = 1,
                    Endurance        = 1,
                    Firepower        = 1,
                    Intelligence     = 1,
                    Rank             = 1,
                    Skill            = 1,
                    Speed            = 1,
                    Strength         = 1
                };
                context.Transformers.Add(autoBotTransformer);
                context.Transformers.Add(decepticonTransformer);
                context.SaveChanges();


                var warsService = new WarService(context, _mockLogger.Object);
                var warResult   = warsService.RunWar().Result;
                Assert.Equal(0, warResult.Autobots.Victors.Count);
                Assert.Equal(0, warResult.Decepticon.Victors.Count);

                context.Database.EnsureDeleted();
            }
        }
Пример #8
0
        // Send a list of items to purchase from the faction store
        public static bool PostBuyItems(Dictionary <string, PurchasedItem> sold, FactionValue owner, bool blackMarket)
        {
            try {
                if (sold == null || owner == null)
                {
                    PersistentMapClient.Logger.LogIfDebug("null owner or dictionary");
                    return(false);
                }
                if (sold.Count() > 0)
                {
                    WarService market = WarService.PostBuyItems;
                    if (blackMarket)
                    {
                        market = WarService.PostBuyBlackMarketItem;
                    }
                    string          testjson = JsonConvert.SerializeObject(sold.Values.ToList <PurchasedItem>());
                    HttpWebRequest  request  = new RequestBuilder(market).Faction(owner).PostData(testjson).Build();
                    HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                    using (Stream responseStream = response.GetResponseStream())
                    {
                        StreamReader reader      = new StreamReader(responseStream);
                        string       pitemString = reader.ReadToEnd();
                        if (blackMarket)
                        {
                            PurchasedItem pItem;
                            pItem = JsonConvert.DeserializeObject <PurchasedItem>(pitemString);
                            PersistentMapClient.updateBMarketId(pItem.TransactionId);
                        }

                        return(true);
                    }
                }
                else
                {
                    PersistentMapClient.Logger.Log("No online items purchased, nothing to do");
                    return(true);
                }
            }
            catch (Exception e) {
                PersistentMapClient.Logger.LogError(e);
                return(false);
            }
        }
        public void PostTransformerReturns_WithUpdatedTransformer()
        {
            using (var context = getDBContext())
            {
                var warsService = new WarService(context, _mockLogger.Object);
                Models.DTO.TransformerRequest transformer = new Models.DTO.TransformerRequest()
                {
                    AllegianceType = AllegianceTypes.Autobot,
                    Courage        = 1,
                    Endurance      = 1,
                    Firepower      = 1,
                    Intelligence   = 1,
                    Name           = "Autobot",
                    Rank           = 1,
                    Skill          = 1,
                    Speed          = 1,
                    Strength       = 1
                };

                var addTransformerResult = warsService.AddTransformer(transformer).Result;
                transformer = new Models.DTO.TransformerRequest()
                {
                    AllegianceType = AllegianceTypes.Decepticon,
                    Courage        = 1,
                    Endurance      = 1,
                    Firepower      = 1,
                    Intelligence   = 1,
                    Name           = "Decepticon",
                    Rank           = 1,
                    Skill          = 1,
                    Speed          = 1,
                    Strength       = 1
                };
                var transformerResult = warsService.UpdateTransformer(context.Transformers.First().TransformerId, transformer).Result;
                Assert.Equal(context.Transformers.First().Name, transformer.Name);
                Assert.Equal(transformerResult.Name, transformer.Name);
                Assert.Equal(transformerResult.Allegiance, AllegianceTypes.Decepticon);


                context.Database.EnsureDeleted();
            }
        }
        public void PostTransformerReturns_WithError_WhenDuplicateName()
        {
            using (var context = getDBContext())
            {
                var warsService = new WarService(context, _mockLogger.Object);
                Models.DTO.TransformerRequest transformer = new Models.DTO.TransformerRequest()
                {
                    AllegianceType = AllegianceTypes.Autobot,
                    Courage        = 1,
                    Endurance      = 1,
                    Firepower      = 1,
                    Intelligence   = 1,
                    Name           = "Autobot#1",
                    Rank           = 1,
                    Skill          = 1,
                    Speed          = 1,
                    Strength       = 1
                };

                warsService.AddTransformer(transformer).Wait();

                transformer = new Models.DTO.TransformerRequest()
                {
                    AllegianceType = AllegianceTypes.Decepticon,
                    Courage        = 1,
                    Endurance      = 1,
                    Firepower      = 1,
                    Intelligence   = 1,
                    Name           = "Autobot#1",
                    Rank           = 2,
                    Skill          = 1,
                    Speed          = 1,
                    Strength       = 1
                };

                Assert.ThrowsAsync <TransformerWarsException>(() => warsService.UpdateTransformer(2, transformer));
                context.Database.EnsureDeleted();
            }
        }
        public void RunBattleReturns_WithTransformerWithHigherScore()
        {
            using (var context = getDBContext())
            {
                Models.DB.Transformer autoBotTransformer = new Models.DB.Transformer()
                {
                    Name             = "TestA",
                    AllegianceTypeId = (int)AllegianceTypes.Autobot,
                    Courage          = 2,
                    Endurance        = 2,
                    Firepower        = 2,
                    Intelligence     = 2,
                    Rank             = 2,
                    Skill            = 2,
                    Speed            = 2,
                    Strength         = 2
                };

                Models.DB.Transformer decepticonTransformer = new Models.DB.Transformer()
                {
                    Name             = "TestB",
                    AllegianceTypeId = (int)AllegianceTypes.Decepticon,
                    Courage          = 1,
                    Endurance        = 1,
                    Firepower        = 1,
                    Intelligence     = 1,
                    Rank             = 1,
                    Skill            = 1,
                    Speed            = 1,
                    Strength         = 1
                };

                var warsService  = new WarService(context, _mockLogger.Object);
                var winnerResult = warsService.GetWinner(autoBotTransformer, decepticonTransformer);
                Assert.Equal(AllegianceTypes.Autobot, winnerResult);
                context.Database.EnsureDeleted();
            }
        }
        public void RunBattleReturns_ErrorWithSameAllegiance()
        {
            using (var context = getDBContext())
            {
                Models.DB.Transformer autoBotTransformer = new Models.DB.Transformer()
                {
                    Name             = "TestA",
                    AllegianceTypeId = (int)AllegianceTypes.Autobot,
                    Courage          = 1,
                    Endurance        = 1,
                    Firepower        = 1,
                    Intelligence     = 1,
                    Rank             = 1,
                    Skill            = 1,
                    Speed            = 1,
                    Strength         = 1
                };

                Models.DB.Transformer decepticonTransformer = new Models.DB.Transformer()
                {
                    Name             = "TestB",
                    AllegianceTypeId = (int)AllegianceTypes.Autobot,
                    Courage          = 1,
                    Endurance        = 1,
                    Firepower        = 1,
                    Intelligence     = 1,
                    Rank             = 2,
                    Skill            = 1,
                    Speed            = 1,
                    Strength         = 1
                };

                var warsService = new WarService(context, _mockLogger.Object);
                Assert.Throws <Exception>(() => warsService.GetWinner(autoBotTransformer, decepticonTransformer));
                context.Database.EnsureDeleted();
            }
        }
Пример #13
0
        // Pulls the inventory for the specified faction
        public static List <ShopDefItem> GetShopForFaction(FactionValue faction, bool blackMarket)
        {
            try {
                WarService market = WarService.GetFactionShop;
                if (blackMarket)
                {
                    market = WarService.GetBlackMarket;
                }
                HttpWebRequest  request  = new RequestBuilder(market).Faction(faction).Build();
                HttpWebResponse response = request.GetResponse() as HttpWebResponse;

                List <ShopDefItem> items;
                using (Stream responseStream = response.GetResponseStream()) {
                    StreamReader reader      = new StreamReader(responseStream);
                    string       itemsstring = reader.ReadToEnd();
                    items = JsonConvert.DeserializeObject <List <ShopDefItem> >(itemsstring);
                }
                return(items);
            }
            catch (Exception e) {
                PersistentMapClient.Logger.LogError(e);
                return(null);
            }
        }
Пример #14
0
 public WarsController(WarService warService)
 {
     _warService = warService;
 }
Пример #15
0
        public async Task Invoke(HttpContext context,
                                 IWarSessionManager sessionManager,
                                 UserManager <User> userManager,
                                 WarService warService,
                                 IActiveWar activeWar)
        {
            if (context.WebSockets.IsWebSocketRequest)
            {
                var requestSocket = await context.WebSockets.AcceptWebSocketAsync();

                var currentUserId = userManager.GetUserId(context.User);

                var newWarSession = new WarSession(currentUserId, requestSocket);
                sessionManager.Add(newWarSession);

                while (requestSocket.State == WebSocketState.Open)
                {
                    var buffer   = new ArraySegment <byte>(new byte[4096]);
                    var received = await requestSocket.ReceiveAsync(buffer, CancellationToken.None);

                    var competitorId = activeWar.CompetitorId;

                    switch (received.MessageType)
                    {
                    case WebSocketMessageType.Text:
                        var receivedJson = Encoding.UTF8.GetString(buffer.Array,
                                                                   buffer.Offset,
                                                                   buffer.Count);

                        var shotParam  = JsonConvert.DeserializeObject <ShotVm>(receivedJson);
                        var shotResult = await warService.ShotAsync(shotParam);

                        var warModel = shotResult.Item1;
                        var errorMsg = shotResult.Item2;

                        var currentPlayerRespMsg = new SocketRespMsg
                        {
                            Content      = warModel,
                            ErrorMessage = errorMsg,
                            State        = errorMsg == null ? Success : Failure
                        };
                        await SendAsync(requestSocket, currentPlayerRespMsg);

                        if (currentPlayerRespMsg.State == Success)
                        {
                            var competotorSession = sessionManager.Find(competitorId);
                            if (competotorSession != null)
                            {
                                var competotorSocket = competotorSession.Socket;
                                if (competotorSocket.State == WebSocketState.Open)
                                {
                                    var competitorWarModel = await warService.FindAsync(competitorId);
                                    await SendAsync(competotorSocket, new SocketRespMsg { Content = competitorWarModel, State = Success });
                                }
                            }
                        }

                        break;
                    }
                }

                await Task.FromResult(0);
            }
            else
            {
                await _next(context);
            }
        }
Пример #16
0
 public RequestBuilder(WarService service)
 {
     this._service = service;
 }
Пример #17
0
        // Send the results of a mission to the server
        public static bool PostMissionResult(Objects.MissionResult mresult, string companyName, bool warmission, out string errorText)
        {
            errorText = "No Error";
            try {
                WarService post = WarService.PostNonWarResult;
                if (warmission)
                {
                    post = WarService.PostMissionResult;
                    PersistentMapClient.Logger.Log($"Post as war mission");
                }
                else
                {
                    PersistentMapClient.Logger.Log($"Post as non-war mission");
                }
                RefreshServerSettings();
                if (serverSettings.CanTransmit)
                {
                    mresult.companyName = companyName;
                }
                else
                {
                    mresult.companyName = "";
                }
                string          testjson = JsonConvert.SerializeObject(mresult);
                HttpWebRequest  request  = new RequestBuilder(post).CompanyName(companyName).PostData(testjson).Build();
                var             watch    = System.Diagnostics.Stopwatch.StartNew();
                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                watch.Stop();
                PersistentMapClient.Logger.LogIfDebug($"PostMissionResult took: {watch.ElapsedMilliseconds}ms.");
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    PersistentMapClient.Logger.Log($"PostMissionResult Failed Code: {response.StatusCode}");
                    errorText = "Unknown Error";
                    return(false);
                }
                using (Stream responseStream = response.GetResponseStream()) {
                    StreamReader reader    = new StreamReader(responseStream);
                    string       mapstring = reader.ReadToEnd();
                }
                return(true);
            }
            catch (WebException e)
            {
                switch (((HttpWebResponse)e.Response).StatusCode)
                {
                case HttpStatusCode.InternalServerError:
                    errorText = "Internal Server, please make a discord ticket!";
                    break;

                case HttpStatusCode.NotFound:
                    errorText = "Connection Error, Try again later";
                    break;

                case HttpStatusCode.BadRequest:
                    errorText = "Improper client code, please make a discord ticket and provide this save";
                    break;

                case HttpStatusCode.Conflict:
                    errorText = "This career is from a not current season career and cannot particpate on the war map";
                    break;

                case HttpStatusCode.Forbidden:
                    errorText = "This career has been banned from particpating on the war map, contact a roguewar moderator or admin for additional details, If you believe this is in error you can appeal your ban by opening a Support Ticket on the main RogueTech Discord";
                    break;

                case HttpStatusCode.ExpectationFailed:
                    errorText = "Cooldown is in affect, results not posted";
                    break;

                case HttpStatusCode.PreconditionFailed:
                    HttpWebResponse response = (HttpWebResponse)e.Response;
                    string          cooldown = "";
                    using (Stream responseStream = response.GetResponseStream())
                    {
                        StreamReader reader = new StreamReader(responseStream);
                        string       errDat = reader.ReadToEnd();
                        Dictionary <string, string> errDict = JsonConvert.DeserializeObject <Dictionary <string, string> >(errDat);
                        cooldown = errDict["Lockout"];
                    }
                    errorText = $"Running multiple saves on a single career is not allowed, if you are rolling back a save (because of a crash or the like) you will need to wait {cooldown} for cooldown to expire before you can continue posting results";
                    break;

                case HttpStatusCode.RequestedRangeNotSatisfiable:
                    errorText = "Client transmission error, could not determine star system";
                    break;

                case HttpStatusCode.NotAcceptable:
                    errorText = "Mission results looked suspicious, results not counted, if you believe this is in error, please make a ticket on discord";
                    break;

                case (HttpStatusCode)418:
                    errorText = "Contract type has not be assigned a value, please contact roguewar admins";
                    break;

                case (HttpStatusCode)444:
                    errorText = "System is surrounded, no control change possible";
                    break;

                case (HttpStatusCode)472:
                    errorText = "Client is out of date, you must update RogueTech to continue participating on the map";
                    break;

                case (HttpStatusCode)473:
                    errorText = "Critical mission data not available, if you are Mac or Linux please file a support ticket on discord. If on Windows restart RogueTech";
                    break;

                case (HttpStatusCode)474:
                    errorText = "Unknown Client version, please make sure RogueTech is up to date and make a ticket if this still occurs";
                    break;

                case (HttpStatusCode)475:
                    errorText = "Mission results could not be posted because a seasonal break is in affect, check the roguewar discord for announcements of when this break will end and mission posts can resume";
                    break;

                default:
                    errorText = "Unknown Error, your install may be out of date, if not make a discord ticket";
                    break;
                }
                PersistentMapClient.Logger.LogError(e);
                return(false);
            }
            catch (Exception e) {
                PersistentMapClient.Logger.LogError(e);
                errorText = "Client Error, consider making a ticket!";
                return(false);
            }
        }
        public void RunWarsReturns_WithResult()
        {
            using (var context = getDBContext())
            {
                Models.DB.Transformer transformer = new Models.DB.Transformer()
                {
                    Name             = "Optimus",
                    AllegianceTypeId = (int)AllegianceTypes.Autobot,
                    Courage          = 10,
                    Endurance        = 9,
                    Firepower        = 1,
                    Intelligence     = 3,
                    Rank             = 1,
                    Skill            = 1,
                    Speed            = 4,
                    Strength         = 2
                };
                context.Transformers.Add(transformer);

                transformer = new Models.DB.Transformer()
                {
                    Name             = "Decepticon#4",
                    AllegianceTypeId = (int)AllegianceTypes.Decepticon,
                    Rank             = 4,
                    Strength         = 10,
                    Intelligence     = 9,
                    Speed            = 1,
                    Endurance        = 2,
                    Courage          = 3,
                    Firepower        = 4,
                    Skill            = 5
                };
                context.Transformers.Add(transformer);

                transformer = new Models.DB.Transformer()
                {
                    Name             = "Autobot#10",
                    AllegianceTypeId = (int)AllegianceTypes.Autobot,
                    Rank             = 10,
                    Strength         = 10,
                    Intelligence     = 9,
                    Speed            = 1,
                    Endurance        = 2,
                    Courage          = 3,
                    Firepower        = 4,
                    Skill            = 5
                };
                context.Transformers.Add(transformer);

                context.SaveChanges();


                var warsService = new WarService(context, _mockLogger.Object);
                var warResult   = warsService.RunWar().Result;
                Assert.Equal(0, warResult.Autobots.Losers.Count);
                Assert.Equal(1, warResult.Autobots.Victors.Count);
                Assert.Equal(1, warResult.Autobots.Survivors.Count);
                Assert.Equal(1, warResult.Decepticon.Losers.Count);
                Assert.Equal(0, warResult.Decepticon.Victors.Count);
                Assert.Equal(0, warResult.Decepticon.Survivors.Count);

                context.Database.EnsureDeleted();
            }
        }