private async Task <KioskDto> CreateKioskAsync(CountryDto countryDto, GroupDto groupDto) { _log.Debug("Begin ProcessKioskAsync Create"); var defaultValue = await _collectDeviceService.CollectDeviceInfoAsync(); _log.Debug("defaultValue: " + defaultValue); var kiosk = await _apiService.CreateKioskAsync(new KioskDto { MachineId = KioskConfigurationHepler.GetValueFromSecurity(MACHINE_ID), Name = SettingsConfigurationCommon.MACHINE_NAME, GroupId = groupDto.Id, CountryId = countryDto.Id, IpAddress = UnitHelper.GetLocalIPAddress(), Address = GeoLocaltion.GetCountryName(), DefaultValue = defaultValue, Status = KioskStatus.online, Long = GeoLocaltion.GetLongitude(), Lat = GeoLocaltion.GetLatitude() }); _log.Debug("UnitHelper.GetMacAddress() " + UnitHelper.GetMacAddress()); await _apiService.UpdateKioskSecurityByKeyAsync(KioskConfigurationHepler.GetValueFromSecurity(LICENSE_KEY), new KioskSecurityDto { MacAddress = UnitHelper.GetMacAddress(), IsActive = true }); return(kiosk); }
void EventForCreatingAnother() { GameEvent.Register(GameEventType.MineralsChanged, argsA => { if (_producingWorker == null && argsA.Minerals >= 50) { // After he collected minerals, another worker will be built var baseCenter = BuildingHelper.GetMyBuildings <BaseCenter>()[0]; baseCenter.ProduceUnit(UnitType.Worker); // After creating (it means after few seconds), he will need to go gather too _producingWorker = GameEvent.Register(GameEventType.UnitProduced, argsB => { if (argsB.MyUnit is Worker) { Worker worker = (Worker)argsB.MyUnit; Gather(worker); argsB.ThisGameEvent.UnregisterEvent(); _producingWorker = null; } }); } // This event will work only while there are not enough workers. // After that, minerals will be left to go over 150. if (UnitHelper.GetMyUnits <Worker>().Length >= 7) { argsA.ThisGameEvent.UnregisterEvent(); } }); }
protected override void RewriteReturn(IOperation op) { // get a reference to System.GC var systemGC = UnitHelper.FindType( base.host.NameTable, base.host.FindAssembly(host.CoreAssemblySymbolicIdentity), "System.GC" ); Contract.Assert(systemGC != Dummy.Type); // store an IMethodReference to System.GC.WaitForPendingFinalizers() var systemGCWaitForPendingFinalizers = TypeHelper.GetMethod( systemGC, base.host.NameTable.GetNameFor("WaitForPendingFinalizers") ); Contract.Assert(systemGCWaitForPendingFinalizers != null); Contract.Assert(systemGCWaitForPendingFinalizers != Dummy.Method); // call method. base.generator.Emit(OperationCode.Call, systemGCWaitForPendingFinalizers); base.RewriteReturn(op); }
public async Task <IEnumerable <string> > GenerateLicenseKeyAsync(string clientId, int number) { IList <string> licenses = new List <string>(); for (int i = 0; i < number; i++) { var username = UnitHelper.RandomString(); var password = UnitHelper.RandomString(); var userProfile = await _userProfileService.CreateAsync(username, password, PulseIdentityRole.Kiosk); await _userProfileService.AddClientUserAsync(userProfile.UserId, clientId); string passwordHash = password.GeneratePasswordHash(); var encryptionUserDto = await CreateEncryptionUserAsync(username, password, passwordHash, userProfile.UserId); _repository.Add(new KioskSecurity { MachineId = userProfile.UserId, LicenseKey = userProfile.UserId, IsActive = false, EncryptionUserId = encryptionUserDto.Id, ClientId = clientId, }); await _unitOfWork.CommitAsync(); licenses.Add(userProfile.UserId); } return(licenses); }
// GET: Admin/Products/Edit/5 public async Task <IActionResult> Edit(int?id) { if (id == null) { return(NotFound()); } var product = await _context.Products.SingleOrDefaultAsync(m => m.ProductID == id); if (product == null) { return(NotFound()); } AdminProductViewModel vm = new AdminProductViewModel() { ProductID = product.ProductID, AvailableQuantity = Math.Round(product.AvailableQuantity, 2).ToString(), Description = product.Description, MinimumPurchaseQuantity = Math.Round(product.MinimumPurchaseQuantity, 2).ToString(), Name = product.Name, Price = Math.Round(product.Price, 2).ToString(), ProductNumber = product.ProductNumber, PeriodID = product.ShippingPeriod, SizeID = product.Size, ShortDescription = product.ShortDescription, BasesUnitID = product.BasesUnitID, SecondBaseUnitID = product.SecondBaseUnit, SecondBasePrice = Math.Round(product.SecondBasePrice, 2).ToString(), IsActive = product.IsActive, BasesUnit = new UnitHelper(_context, factory).GetUnitName(product.BasesUnitID), Period = new ShippingPeriodHelper(_context).GetDescription(product.ShippingPeriod), SecondBaseUnit = new UnitHelper(_context, factory).GetUnitName(product.SecondBaseUnit), Size = new SizeHelper(_context).GetName(product.Size), ImageUrls = new ProductImageHelper(_context, factory).GetUrls(product.ProductID), ShippingPriceTypeID = product.ShippingPriceType, ShippingPriceTypeName = new ShippingPriceTypeHelper(_context).GetNameByID(product.ShippingPriceType), SeoDescription = product.SeoDescription, SeoKeywords = product.SeoKeywords }; List <UnitViewModel> vmunits = new UnitHelper(_context, factory).GetVmUnits(); List <SizeViewModel> vwsizes = new SizeHelper(_context).GetVmSizes(); List <ShippingPeriodViewModel> periods = new ShippingPeriodHelper(_context).GetVmShippingPeriods(); List <SelectItemViewModel> catvms = new CategoryHelper(_context).GetVmList(); List <SelectItemViewModel> catsubvms = new CategorySubHelper(_context).GetVmList(); List <SelectItemViewModel> catdeatailvms = new CategoryDetailHelper(_context).GetVmList(); List <SelectItemViewModel> shippingPriceTypes = new ShippingPriceTypeHelper(_context).GetVmList(); ViewData["BaseUnit"] = new SelectList(vmunits, "UnitID", "Name"); ViewData["Size"] = new SelectList(vwsizes, "ID", "Name"); ViewData["SeconedUnit"] = new SelectList(vmunits, "UnitID", "Name"); ViewData["Periods"] = new SelectList(periods, "ID", "Value"); ViewData["CategoryID"] = new SelectList(catvms, "ID", "Name"); ViewData["CategorySubID"] = new SelectList(catsubvms, "ID", "Name"); ViewData["CategoryDetailID"] = new SelectList(catdeatailvms, "ID", "Name"); ViewData["ShippingPriceTypeID"] = new SelectList(shippingPriceTypes, "ID", "Name"); return(View(vm)); }
// searches for the interface given by name and adds it to the interface transformation list public void addInterfaceToListByName(String interfaceName) { this.logger.writeLine("Search for interface: " + interfaceName); var foundInterfaceNamespace = UnitHelper.FindType(this.host.NameTable, this.host.LoadAssembly(host.CoreAssemblySymbolicIdentity), interfaceName); // continue if interface could not be located if (foundInterfaceNamespace is Microsoft.Cci.Dummy) { this.logger.writeLine("Interface \"" + interfaceName + "\" was not found"); this.logger.writeLine(""); return; } // adds the interface and all "parent interfaces" to the allInterfaces list ITypeDefinition foundInterface = (foundInterfaceNamespace as ITypeDefinition); if (foundInterface == null) { throw new ArgumentException("Do not know how to handle interface."); } this.logger.writeLine("Resolve inheritance of interface: " + foundInterface.ToString()); getListOfAllImplementedInterfaces(foundInterface); this.logger.writeLine(""); }
public static void Postfix(MechBayMechInfoWidget __instance, MechDef ___selectedMech, GameObject ___initiativeObj, TextMeshProUGUI ___initiativeText, HBSTooltip ___initiativeTooltip) { if (___initiativeObj == null || ___initiativeText == null) { return; } //SkillBasedInit.Logger.Log($"MechBayMechInfoWidget::SetInitiative::post - disabling text"); if (___selectedMech == null) { ___initiativeObj.SetActive(true); ___initiativeText.SetText("-"); } else { List <string> details = new List <string>(); // Static initiative from tonnage float tonnage = ___selectedMech.Chassis.Tonnage; int tonnageMod = UnitHelper.GetTonnageModifier(tonnage); details.Add($"Tonnage Base: {tonnageMod}"); // Any modifiers that come from the chassis/mech/vehicle defs int componentsMod = UnitHelper.GetNormalizedComponentModifier(___selectedMech); if (componentsMod > 0) { details.Add($"<space=2em><color=#00FF00>{componentsMod:+0} components</color>"); } else if (componentsMod < 0) { details.Add($"<space=2em><color=#FF0000>{componentsMod:0} components </color>"); } // Modifier from the engine int engineMod = UnitHelper.GetEngineModifier(___selectedMech); if (engineMod > 0) { details.Add($"<space=2em><color=#00FF00>{engineMod:+0} engine</color>"); } else if (engineMod < 0) { details.Add($"<space=2em><color=#FF0000>{engineMod:0} engine</color>"); } // --- Badge --- ___initiativeObj.SetActive(true); ___initiativeText.SetText($"{tonnageMod + componentsMod + engineMod}"); // --- Tooltip --- int maxInit = Math.Max(tonnageMod + componentsMod + engineMod, Mod.MinPhase); details.Add($"Expected Phase: <b>{maxInit}</b> "); string tooltipTitle = $"{___selectedMech.Name}"; string tooltipText = String.Join("\n", details.ToArray()); BaseDescriptionDef initiativeData = new BaseDescriptionDef("MB_MIW_MECH_TT", tooltipTitle, tooltipText, null); ___initiativeTooltip.enabled = true; ___initiativeTooltip.SetDefaultStateData(TooltipUtilities.GetStateDataFromObject(initiativeData)); } }
private bool IsImplementingInvisibleInterface(IMethodDefinition method) { if (MemberHelper.IsVisibleOutsideAssembly(method)) { return(false); } foreach (var bm in MemberHelper.GetExplicitlyOverriddenMethods(method)) { var containing = bm.ContainingType; var unitref = TypeHelper.GetDefiningUnitReference(containing); if (UnitHelper.UnitsAreEquivalent(unitref, TypeHelper.GetDefiningUnitReference(method.ContainingType))) { var instance = containing as IGenericTypeInstanceReference; if (instance != null) { containing = instance.GenericType; } var spec = containing as ISpecializedNestedTypeReference; if (spec != null) { containing = spec.UnspecializedVersion; } var resolved = containing.ResolvedType; if (resolved.IsInterface && !TypeHelper.IsVisibleOutsideAssembly(resolved)) { return(true); } } } return(false); }
/* * public void LookAtRange(MapFieldHelper.Range range) * { * transform.LookAt (range.center); * * float scale = range.width / 2 / sizeControl.expectScreenWidth2; * float height2 = sizeControl.expectScreenHeight2 * scale; * camera.orthographicSize = height2; * * } */ private void GetOrientation() { float dist = transform.position.magnitude; _orientation = UnitHelper.GetOrientation(transform); VectorHelper.ResizeVector(ref _orientation, dist); }
public static void CreateBackground(string asset) { string resName = AppConfig.FOLDER_PROFAB + "background/" + asset; string resNameTop = resName + "-top"; string resNameEffect = resName + "-effect"; Vector3 cameraDir = UnitHelper.GetOrientation(BattleGame.instance.camera.transform); VectorHelper.ResizeVector(ref cameraDir, 50); GameObject background = ResourceHelper.Load(resName); background.transform.position += cameraDir; AddUnitToLayer(background, BattleConfig.LAYER.OTHER); GameObject backgroundTop = ResourceHelper.Load(resNameTop); backgroundTop.transform.position += cameraDir; AddUnitToLayer(backgroundTop, BattleConfig.LAYER.OTHER); GameObject backgroundEffect = ResourceHelper.Load(resNameEffect); backgroundEffect.transform.position += cameraDir; AddUnitToLayer(backgroundEffect, BattleConfig.LAYER.OTHER); }
public static bool InSameUnit(ITypeDefinition type1, ITypeDefinition type2) { IUnit unit1 = TypeHelper.GetDefiningUnit(type1); IUnit unit2 = TypeHelper.GetDefiningUnit(type2); return(UnitHelper.UnitsAreEquivalent(unit1, unit2)); }
private string GetSize(Element target) { switch (TargetType) { case PAATargetType.Pipe: var size = UnitHelper.ConvertFromFootTo(target.GetParameters(PAAContext.SharedParameterDiameter).First().AsDouble(), VLUnitType.millimeter); return("DN" + size); case PAATargetType.Duct: if (IsRoundDuct(target)) { size = UnitHelper.ConvertFromFootTo(target.GetParameters(PAAContext.SharedParameterDiameter).First().AsDouble(), VLUnitType.millimeter); return("Φ" + size); } else { var height = UnitHelper.ConvertFromFootTo(target.GetParameters(PAAContext.SharedParameterHeight).First().AsDouble(), VLUnitType.millimeter); var width = UnitHelper.ConvertFromFootTo(target.GetParameters(PAAContext.SharedParameterWidth).First().AsDouble(), VLUnitType.millimeter); return(width + "x" + height); } case PAATargetType.CableTray: size = UnitHelper.ConvertFromFootTo(target.GetParameters(PAAContext.SharedParameterHeight).First().AsDouble(), VLUnitType.millimeter); return(size + "x" + size); case PAATargetType.Conduit: default: throw new NotImplementedException("暂未支持该类型"); } }
public static void ActionsGUI(UnitEntityData ch) { var player = Game.Instance.Player; UI.Space(25); if (!player.PartyAndPets.Contains(ch)) { UI.ActionButton("Add", () => { charToAdd = ch; }, UI.Width(150)); UI.Space(25); } else if (player.ActiveCompanions.Contains(ch)) { UI.ActionButton("Remove", () => { charToRemove = ch; }, UI.Width(150)); UI.Space(25); } if (player.Party.Contains(ch)) { respecableCount++; UI.ActionButton("Respec", () => { Actions.ToggleModWindow(); UnitHelper.Respec(ch); }, UI.Width(150)); } else { UI.Space(170); } }
private void HasGoalieStrikeLogic(Hockeyist enemyGoalie) { Move.Action = Self.SwingTicks < Current.Stratagy.RandomSwingCount ? ActionType.Swing : ActionType.Strike; if (Move.Action == ActionType.Swing) { var xPossibleConnection = Math.Abs((Self.Y + Self.SpeedY * Current.Game.SwingActionCooldownTicks - enemyGoalie.Y) / Math.Tan(Self.Angle)); double offset = 1.0D; if (Self.X - enemyGoalie.X > 0.0) { offset = -1.0D; } var dis = UnitHelper.GetDistance(Self.X + Self.SpeedX * Current.Game.SwingActionCooldownTicks + xPossibleConnection * offset, enemyGoalie.Y, enemyGoalie.X + offset * enemyGoalie.Radius * -1.0D, enemyGoalie.Y); if (dis < 2.0D * enemyGoalie.Radius) { Move.Action = ActionType.Strike; } } }
private bool Move() { speed += ACCELERATE * TimeHelper.deltaTime; speed = Mathf.Min(speed, SPEED_MAX); float rotSpeed = speed / SPEED_MAX * SPEED_ROTATE; Vector3 destination = GetCurrentDestination(); AimmingControl.RESULT rotateR = AimmingControl.Rotate( transform.position, destination, transform.rotation.eulerAngles.y, rotSpeed, 0.01f); transform.Rotate(new Vector3(0, rotateR.turnDegree, 0)); Vector3 line = destination - transform.position; float dist = line.magnitude; Vector3 orientation = UnitHelper.GetOrientation(transform); VectorHelper.ResizeVector(ref orientation, dist); Vector3 p = orientation + transform.position; float radius = _shoot.target.unit.dataUnit.GetHurtRadius(); MovingControl.RESULT moveR = MovingControl.MoveTo(transform.position, p, speed, radius + heightInitOffset); transform.position = moveR.destination; return(moveR.arrived); }
public void Post(string cookId, [FromBody] ShoppingListItem value) { if (Guid.TryParse(cookId, out Guid _cookId) && ControllerHelper.CookExists(_cookId)) { if (ControllerHelper.GetShoppingList(_cookId).Any(sli => ControllerHelper.TypeEquals(sli.Ingredient, value.Ingredient))) { // Ingredient exists in the shopping list => update Ingredient ingToUpdate = ControllerHelper.GetShoppingList(_cookId).First(sli => ControllerHelper.TypeEquals(sli.Ingredient, value.Ingredient)).Ingredient; if (ingToUpdate.Unit != value.Ingredient.Unit) { ingToUpdate.Quantity += UnitHelper.ConvertTo(value.Ingredient.Quantity, Enum.Parse <Unit>(value.Ingredient.Unit), Enum.Parse <Unit>(ingToUpdate.Unit)); } else { ingToUpdate.Quantity += value.Ingredient.Quantity; } } else { // New ingredient top add => create value.Id = Guid.NewGuid(); ControllerHelper.GetShoppingList(_cookId).Add(value); } } }
/// <summary> /// True if the specified type is defined in mscorlib and has the specified name /// </summary> public static bool IsMscorlibTypeNamed(ITypeReference type, string name) { Contract.Requires(type != null); return(TypeHelper.GetTypeName(type) == name && UnitHelper.UnitsAreEquivalent(TypeHelper.GetDefiningUnitReference(type), TypeHelper.GetDefiningUnitReference(type.PlatformType.SystemObject))); }
public override async Task <ClientDto> CreateAsync(ClientDto model) { PasswordHasher passwordHasher = new PasswordHasher(); Client client = DtoToEntity(model); client.ClientId = UnitHelper.GenerateNewGuid(); client.SecretKey = UnitHelper.GenerateNewGuid(); client.Secret = passwordHasher.HashPassword(client.SecretKey); client.MongoName = (REST_MONGO_NAME + "_" + client.ClientId); client.MongoConnectionString = (MONGO_PREFIX + model.MongoConnectionString + "/" + client.MongoName); _repository.Add(client); await _unitOfWork.CommitAsync(); var username = model.Email; var password = UnitHelper.RandomString(""); var userProfile = await _userProfileService.CreateAsync(username, password, PulseIdentityRole.ClientAdmin); await _userProfileService.AddClientUserAsync(userProfile.UserId, client.ClientId, client.SecretKey); return(EntityToDto(client)); }
public async Task CreateUserAsync() { PasswordHasher <User> userHasher = new PasswordHasher <User>(); PasswordHasher <Client> clientHasher = new PasswordHasher <Client>(); var client = new Client() { Name = "Butter Ngo", Active = true, RefreshTokenLifeTime = 7, TokenLifeTime = 20, AllowedGrant = OAuthGrant.SystemAdmin, AllowedOrigin = "*" }; client.ClientId = UnitHelper.GenerateNewGuid(); client.SecretKey = UnitHelper.GenerateNewGuid(); client.Secret = clientHasher.HashPassword(client, client.SecretKey); _unitOfWork.ClientRepository.Add(client); var user = new User { UserName = "******" }; user.PasswordHash = userHasher.HashPassword(user, "admin"); user.ClientId = client.ClientId; user.SecretKey = client.SecretKey; await _userManager.CreateAsync(user); await _unitOfWork.CommitAsync(); }
public async Task CreateAsync(AuthenticationTokenCreateContext context) { var refreshTokenId = Guid.NewGuid().ToString("n"); if (context.Ticket == null) { context.Response.StatusCode = 400; context.Response.ContentType = "application/json"; context.Response.ReasonPhrase = "invalid refresh token"; return; } IRefreshTokenService refreshTokenService = ResolverFactory.GetService <RefreshTokenService>(); var client = context.OwinContext.Get <Client>("oauth:client"); var token = new RefreshTokenDto() { RefreshTokenId = UnitHelper.GetHash(refreshTokenId), Subject = context.Ticket.Identity.Name, IssuedUtc = DateTime.UtcNow, ExpiresUtc = DateTime.UtcNow.AddDays(client.RefreshTokenLifeTime) }; context.Ticket.Properties.IssuedUtc = token.IssuedUtc; context.Ticket.Properties.ExpiresUtc = token.ExpiresUtc; token.ProtectedTicket = context.SerializeTicket(); await refreshTokenService.CreateAsync(token); context.SetToken(refreshTokenId); }
void EventForCreatingAnother() { Event.Register(EventType.MineralsChanged, argsA => { if (argsA.Minerals > 50) { // After he collected minerals, another worker will be built var baseCenter = BuildingHelper.GetBuildings <BaseCenter>()[0]; baseCenter.CreateWorker(); // After creating (it means after few seconds), he will need to go gather too Event.Register(EventType.UnitCreated, argsB => { if (argsB.MyUnit.GetType().Equals(typeof(Worker))) { Worker worker = (Worker)argsB.MyUnit; worker.SendGather(MaterialHelper.GetNearestMineralsTo(worker)); argsB.ThisEvent.UnregisterEvent(); } }); } argsA.ThisEvent.UnregisterEvent(); // This event will work only while there are not enough workers. // After that, minerals will be left to go over 150. if (UnitHelper.GetUnits <Worker>().Length >= 5) { argsA.ThisEvent.UnregisterEvent(); } }); }
public void DebugTestUnitQueue() { var workers = UnitHelper.GetMyUnitsAsList <Worker>(); workers[0] .MoveTo(PlaceType.MyBase.Left) .After(new CustomFunction(() => workers[0].CreateBuilding(BuildingType.BaseCenter, PlaceType.MyBase.Left))) .After(new Move(PlaceType.MyBase.Right)) .After(new GatherResource(ResourceHelper.GetNearestMineralTo(workers[0]))) .After(new CustomFunction(() => workers[0].CreateBuilding(BuildingType.BaseCenter, PlaceType.MyBase.Right))); var enemyBaseMovement = new Move(PlaceType.EnemyBase.Center); workers[1] .MoveTo(PlaceType.EnemyBase.UnderRampRight) .After(enemyBaseMovement); workers[2].ActionQueue = new UnitActionQueue(enemyBaseMovement); GameEvent.Register(GameEventType.EnemyBuildingsOnSight, args => { if (args.EnemyBuildings[0] is BaseCenter & args.MyUnit != null) { Log.d("Found enemy base, returning"); args.MyUnit.MoveTo(PlaceType.MyBase.Center); } else { Log.d("Found building " + args.EnemyBuildings[0].GetType()); } }); }
public Dictionary <Units, int> GetMyUnitsInVillage(RequestManager reqManager, int village) { CQ html = GetPlaceHtml(reqManager, village); var units = new Dictionary <Units, int>(); var selector = "form#command-data-form table tbody table.vis td.nowrap a.units-entry-all"; var linkList = html.Select(selector).ToList(); foreach (var item in linkList) { var typeStr = RegExHelper.GetTextWithRegEx(@"units_entry_all_([a-z]+)", item.Id); var type = UnitHelper.GetTypeForString(typeStr); var nrOfUnits = RegExHelper.GetNumberWithRegEx(@"\((\d+)\)", item.InnerText); if (nrOfUnits == 0) { continue; } units.Add(type, nrOfUnits); } return(units); }
public void DebugTestBuilding() { var workers = UnitHelper.GetMyUnitsAsList <Worker>(); workers[0].CreateBuilding(BuildingType.NubianArmory, PlaceType.MyBase.Right); StartCoroutine(RunAfterSeconds(1, () => { for (var index = 1; index < workers.Count; index++) { workers[index].SendGather(ResourceHelper.GetNearestMineralTo(workers[index])); } })); GameEvent.Register(GameEventType.MineralsChanged, args => { Log.i(this, args.Minerals + " minerals"); var building = workers[0].CreateBuilding(BuildingType.NubianArmory, PlaceType.MyBase.Left); workers[1].CreateBuilding(BuildingType.NubianArmory, PlaceType.MyBase.Back); workers[2].CreateBuilding(BuildingType.NubianArmory, PlaceType.MyBase.Front); foreach (var worker in workers) { worker.FinishBuiding(building); } args.ThisGameEvent.UnregisterEvent(); }); }
public static bool InSameUnit(ITypeDefinitionMember member1, ITypeDefinitionMember member2) { IUnit unit1 = TypeHelper.GetDefiningUnit(member1.ContainingTypeDefinition); IUnit unit2 = TypeHelper.GetDefiningUnit(member2.ContainingTypeDefinition); return(UnitHelper.UnitsAreEquivalent(unit1, unit2)); }
public Helper(IModule module, PeReader.DefaultHost host, Log.Log logger) { this.host = host; this.logger = logger; this.module = module; // get all needed functions and namespaces this.systemString = UnitHelper.FindType(this.host.NameTable, this.host.LoadAssembly(this.host.CoreAssemblySymbolicIdentity), "System.String"); this.systemIOTextWriter = UnitHelper.FindType(this.host.NameTable, this.host.LoadAssembly(this.host.CoreAssemblySymbolicIdentity), "System.IO.TextWriter"); this.systemIOStreamWriter = UnitHelper.FindType(this.host.NameTable, this.host.LoadAssembly(this.host.CoreAssemblySymbolicIdentity), "System.IO.StreamWriter"); this.systemInt32 = UnitHelper.FindType(this.host.NameTable, this.host.LoadAssembly(this.host.CoreAssemblySymbolicIdentity), "System.Int32"); this.systemObject = UnitHelper.FindType(this.host.NameTable, this.host.LoadAssembly(this.host.CoreAssemblySymbolicIdentity), "System.Object"); this.systemConsole = UnitHelper.FindType(this.host.NameTable, this.host.LoadAssembly(this.host.CoreAssemblySymbolicIdentity), "System.Console"); this.systemRandom = UnitHelper.FindType(this.host.NameTable, this.host.LoadAssembly(this.host.CoreAssemblySymbolicIdentity), "System.Random"); ITypeReference[] concatThreeParameterTypes = { this.host.PlatformType.SystemString, this.host.PlatformType.SystemString, this.host.PlatformType.SystemString }; ITypeReference[] concatTwoParameterTypes = { this.host.PlatformType.SystemString, this.host.PlatformType.SystemString }; ITypeReference[] streamWriterAppendTypes = { this.host.PlatformType.SystemString, this.host.PlatformType.SystemBoolean }; this.stringConcatThree = TypeHelper.GetMethod(systemString, this.host.NameTable.GetNameFor("Concat"), concatThreeParameterTypes); this.stringConcatTwo = TypeHelper.GetMethod(systemString, this.host.NameTable.GetNameFor("Concat"), concatTwoParameterTypes); this.textWriterWriteLine = TypeHelper.GetMethod(systemIOTextWriter, this.host.NameTable.GetNameFor("WriteLine"), this.host.PlatformType.SystemString); this.streamWriterCtor = TypeHelper.GetMethod(systemIOStreamWriter, this.host.NameTable.GetNameFor(".ctor"), this.host.PlatformType.SystemString); this.streamWriterCtorAppend = TypeHelper.GetMethod(systemIOStreamWriter, this.host.NameTable.GetNameFor(".ctor"), streamWriterAppendTypes); this.textWriterWrite = TypeHelper.GetMethod(systemIOTextWriter, this.host.NameTable.GetNameFor("Write"), this.host.PlatformType.SystemString); this.int32ToString = TypeHelper.GetMethod(systemInt32, this.host.NameTable.GetNameFor("ToString")); this.textWriterClose = TypeHelper.GetMethod(systemIOTextWriter, this.host.NameTable.GetNameFor("Close")); this.objectGetHashCode = TypeHelper.GetMethod(systemObject, this.host.NameTable.GetNameFor("GetHashCode")); this.systemConsoleWriteLine = TypeHelper.GetMethod(systemConsole, host.NameTable.GetNameFor("WriteLine"), host.PlatformType.SystemString); this.objectCtor = TypeHelper.GetMethod(systemObject, this.host.NameTable.GetNameFor(".ctor")); this.systemRandomCtor = TypeHelper.GetMethod(systemRandom, this.host.NameTable.GetNameFor(".ctor")); this.systemRandomNext = TypeHelper.GetMethod(systemRandom, this.host.NameTable.GetNameFor("Next"), host.PlatformType.SystemInt32); }
public static TurnedUnit CalculateTrickyUnitTimeProduction(TimeLineStatus premiumTimeLine, TurnedUnit turnedUnit, int currTime, int shipyardLevel) { var lastUpgrade = turnedUnit.DateLastUpgrade; var index = premiumTimeLine.Points.FindLastIndex(j => j <= lastUpgrade); var baseUnitProductionTime = UnitHelper.GetBaseUnit(turnedUnit.UnitType).BasePrice.TimeProduction; // 0-1 true // 1-2 false // 2-3 true for (var i = index; i < premiumTimeLine.Points.Count(); i++) { var statusPremiumIsActive = false; if (i != -1) { statusPremiumIsActive = premiumTimeLine.Status[i]; } var oneUnitProductionSpeedPerSecond = CalculateTimeProduction(baseUnitProductionTime, statusPremiumIsActive, shipyardLevel); int duration; var hasNextPoint = (premiumTimeLine.Points.Count() - 1 > i); if (hasNextPoint) { var nextPoint = premiumTimeLine.Points[i + 1]; duration = nextPoint - lastUpgrade; lastUpgrade = nextPoint; } else { duration = currTime - lastUpgrade; lastUpgrade = currTime; } if (duration > (turnedUnit.TotalCount - turnedUnit.ReadyUnits) * oneUnitProductionSpeedPerSecond) { turnedUnit.ReadyUnits += (currTime - turnedUnit.DateLastUpgrade) / oneUnitProductionSpeedPerSecond; if (turnedUnit.ReadyUnits >= turnedUnit.TotalCount) { turnedUnit.ReadyUnits = turnedUnit.TotalCount; } lastUpgrade = currTime; break; } turnedUnit.ReadyUnits += duration / oneUnitProductionSpeedPerSecond; } turnedUnit.DateLastUpgrade = lastUpgrade; return(turnedUnit); }
public void then_the_SUT_should_return_the_according_unit_prefix_and_value_suffix( int scaleFactorExponent, string unitPrefix, string valueSuffix) { var scaleFactorInfo = UnitHelper.GetScaleFactorInfo(scaleFactorExponent); scaleFactorInfo.UnitPrefix.ShouldEqual(unitPrefix); scaleFactorInfo.ValueSuffix.ShouldEqual(valueSuffix); }
protected bool CanNowProduceUnit(UnitType unitType) { return(SupportsUnitProduction.Contains(unitType) && null != BuildingController.unitProduction.TryConstructProduction( UnitHelper.FindUnitIndexInUnitProduction(unitType, BuildingController.unitProduction), GameManager.Instance.ResourceManagerFaction[BuildingController.FactionIndex], BuildingController.PlayerOwner)); }
private Types(IMetadataHost host) { this.host = host; var unit = host.FindUnit(host.CoreAssemblySymbolicIdentity); this.PureAttributeType = UnitHelper.FindType(host.NameTable, unit, "System.Diagnostics.Contracts.PureAttribute"); }