public static async Task <IEnumerable <string> > GetItemsImageUrlsAsync( this IHasItemIds hasItemIds, RegionEnum?region = null, string dataDragonVersion = null) { if (hasItemIds == null) { throw new ArgumentNullException("hasItemIds"); } var staticService = new StaticService(hasItemIds.ApiConfiguration); if (string.IsNullOrWhiteSpace(dataDragonVersion)) { var realm = await staticService.GetRealmAsync(region); dataDragonVersion = realm.CurrentVersion; } return(hasItemIds.ItemIds .Where(x => x > 0) .Select(x => string.Format("http://ddragon.leagueoflegends.com/cdn/{0}/img/item/{1}.png", dataDragonVersion, x))); }
public static async Task <IEnumerable <IItem> > GetItemsStaticInfosAsync( this IHasItemIds hasItemIds, ItemDataEnum?itemData = null, RegionEnum?region = null, LanguageEnum?languageCode = null, string dataDragonVersion = null) { if (hasItemIds == null) { throw new ArgumentNullException("hasItemIds"); } var result = new List <IItem>(); var staticService = new StaticService(hasItemIds.ApiConfiguration); foreach (var itemId in hasItemIds.ItemIds.Where(x => x > 0)) { var item = await staticService.GetItemsAsync( itemId, itemData, region, languageCode, dataDragonVersion); result.Add(item); } return(result); }
public async Task ServiceTest() { var tokenId = Guid.NewGuid(); var serviceInfo = new StaticServiceInfo { Name = "Service", Id = Guid.NewGuid(), Data = "Data", Tokens = new[] { new TokenInfo { Id = tokenId } } }; var cacheRegion = "cacheRegion"; var cache = Substitute.For <ICache>(); var tokenService = Substitute.For <ITokenService>(); var sut = new StaticService(cache, tokenService); ServiceResponse actual = await sut.CallService(serviceInfo, cacheRegion, CancellationToken.None, null); tokenService.Received(1).ParseTokens(cacheRegion, serviceInfo.Data, serviceInfo.Tokens); Assert.AreEqual(ServiceResponseStatus.Success, actual.Status); Assert.AreEqual(serviceInfo.Data, actual.Value); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.Run(async(context) => { var names = StaticService.GetNames(); StringBuilder builder = new StringBuilder(); foreach (var name in names) { builder.Append(name + " "); } await context.Response.WriteAsync(builder.ToString()); }); app.UseCookiePolicy(); app.UseMvc(); }
public static async Task <IEnumerable <ISummonerSpell> > GetSummonerSpellsStaticInfosAsync( this IHasSummonerSpells hasSummonerSpells, SpellDataEnum?itemData = null, RegionEnum?region = null, LanguageEnum?languageCode = null, string dataDragonVersion = null) { if (hasSummonerSpells == null) { throw new ArgumentNullException("hasSummonerSpells"); } var staticService = new StaticService(hasSummonerSpells.ApiConfiguration); var allSummonerSpells = await staticService.GetSummonerSpellsAsync( false, itemData, region, languageCode, dataDragonVersion); return(allSummonerSpells.Data .Where(x => hasSummonerSpells.SummonerSpells.Select(z => z.ToString()).Contains(x.Value.Key)) .Select(x => x.Value)); }
decimal accumulatedIncome = 0; // накопленный доход public PositionRepository() { StaticService.DeleteFile(out_data_log); StaticService.DeleteFile(data_price_log); StaticService.DeleteFile(data_position_log); StaticService.LogFileWriteNotDateTime("Time\tTimeMSK\tOperation\tQantity\tPrice\t*\tAccum. icome\tVar. Margin\tOpen pos.\t*\tvarMarLots\taccumIncomeLots", out_data_log, true); }
private void Logs(DateTime _dt, decimal _eqSum, decimal _eq) { StaticService.LogFileWriteNotDateTime(_dt + "\t" + _eqSum + "\t" + _eq, FILE_NAME1, true); resultOnePositions.Enqueue(new ResultOnePosition { Date_Time = _dt, EquityOne = _eq }); //SuccessTradesFiltr(_dt, _eq); }
//- - - - - - - - //--Constructor-- public EquityChange() { Initialization(); StaticService.DeleteFile(FILE_NAME); StaticService.DeleteFile(FILE_NAME1); StaticService.DeleteFile(FILE_NAME2); StaticService.DeleteFile(FILE_NAME3); }
private void Init() { Champion = new ChampionService(LeagueApiConfiguration); Game = new GameService(LeagueApiConfiguration); League = new LeagueService(LeagueApiConfiguration); Stats = new StatsService(LeagueApiConfiguration); Summoner = new SummonerService(LeagueApiConfiguration); Team = new TeamService(LeagueApiConfiguration); Static = new StaticService(LeagueApiConfiguration); }
public void SendDataAsync() { ThreadPool.QueueUserWorkItem(new Action(() => { var result = StaticService.SendData(); var handler = CallCompleted(); if (handler != null) { handler(result); } })); }
// This method gets called by the runtime. Use this method to add services to the //container. public void ConfigureServices(IServiceCollection services) { services.AddDbContext <TodoContext>(opt => opt.UseInMemoryDatabase("TodoList")); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); StaticService.GetData(Configuration.GetConnectionString("DefaultConnection")); services.Add(new ServiceDescriptor(typeof(CustomerService), new CustomerService())); services.Add(new ServiceDescriptor(typeof(CityService), new CityService())); services.Add(new ServiceDescriptor(typeof(PlaceService), new PlaceService())); services.Add(new ServiceDescriptor(typeof(CustomerPlaceService), new CustomerPlaceService())); // }
public void SendDataAsync() { ThreadPool.QueueUserWorkItem(state => { var result = StaticService.SendData(); var handler = CallCompleted; if (handler != null) { handler(this, new CompletedEventArgs { Result = result }); } }); }
public static async Task<IChampion> GetChampionStaticInfosAsync( this IHasChampionId hasChampionId, ChampDataEnum? champData = null, RegionEnum? region = null, LanguageEnum? languageCode = null, string dataDragonVersion = null) { if (hasChampionId == null) throw new ArgumentNullException("hasChampionId"); var staticService = new StaticService(hasChampionId.ApiConfiguration); return await staticService.GetChampionAsync( hasChampionId.ChampionId, champData, region, languageCode, dataDragonVersion); }
public static async Task<IMastery> GetMasteryStaticInfosAsync( this IHasMasteryId hasMasteryId, MasteryDataEnum? masteryData = null, RegionEnum? region = null, LanguageEnum? languageCode = null, string dataDragonVersion = null) { if (hasMasteryId == null) throw new ArgumentNullException("hasMasteryId"); var staticService = new StaticService(hasMasteryId.ApiConfiguration); return await staticService.GetMasteryAsync( hasMasteryId.Id, masteryData, region, languageCode, dataDragonVersion); }
public static async Task<IRune> GetRuneStaticInfosAsync( this IHasRuneId hasRuneId, RuneDataEnum? runeData = null, RegionEnum? region = null, LanguageEnum? languageCode = null, string dataDragonVersion = null) { if (hasRuneId == null) throw new ArgumentNullException("hasRuneId"); var staticService = new StaticService(hasRuneId.ApiConfiguration); return await staticService.GetRuneAsync( hasRuneId.RuneId, runeData, region, languageCode, dataDragonVersion); }
public async Task WrongServiceTypeTest() { var serviceInfo = new ServiceInfo { Name = "Service", Id = Guid.NewGuid(), }; var cacheRegion = "cacheRegion"; var cache = Substitute.For <ICache>(); var tokenService = Substitute.For <ITokenService>(); var sut = new StaticService(cache, tokenService); ServiceResponse actual = await sut.CallService(serviceInfo, cacheRegion, CancellationToken.None, null); Assert.IsNull(actual); }
// GroupBy private ResultExtremDistance MyGroupBy(List <ResultExtremDistance> _inputList) { if (_inputList.Count == 0 || _inputList == null) { return(new ResultExtremDistance(0, 0, 0, 0, 0)); } StaticService.LogFileWriteNotDateTime("otkat\tdistance\tprofit\tdrawdown\teqcurrent", "group_log.txt", true); var otkatGroup = from result in _inputList group result by new { _otkat = result.otkat, _distance = result.distance } into resGroup orderby resGroup.Key._otkat select resGroup; //foreach (var item in otkatGroup) //{ // StaticService.LogFileWriteNotDateTime(item.Key._otkat + " " + item.Key._distance, "group_log.txt", true); // //StaticService.LogFileWriteNotDateTime("\t" + ((int)item.Average(x => x.profit) / 10) * 10 + " " + item.Count(), "group_log.txt", true); // StaticService.LogFileWriteNotDateTime("\t" + item.Min(x=>x.profit) + " " + item.Count(), "group_log.txt", true); //} //foreach (var item in otkatGroup) //{ // StaticService.LogFileWriteNotDateTime(item.Key._otkat + " " + item.Key._distance, "group_log.txt", true); // foreach (var item1 in item) // { // StaticService.LogFileWriteNotDateTime("\t" + item1.otkat + " " + item1.distance + " " + item1.profit + " ** " + item1.drawdown, "group_log.txt", true); // } //} foreach (var item in otkatGroup) { StaticService.LogFileWriteNotDateTime("\n", "group_log.txt", true); foreach (var item1 in item) { StaticService.LogFileWriteNotDateTime(item1.otkat + "\t" + item1.distance + "\t" + item1.profit + "\t" + item1.drawdown + "\t" + item1.eqcurrent, "group_log.txt", true); } } //return new ResultExtremDistance(0, 0, otkatGroup.ElementAt(0).Key._otkat, otkatGroup.ElementAt(0).Key._distance, ((int)otkatGroup.ElementAt(0).Average(x => x.profit) / 10) * 10); return(new ResultExtremDistance(0, 0, otkatGroup.ElementAt(0).Key._otkat, otkatGroup.ElementAt(0).Key._distance, otkatGroup.ElementAt(0).Min(x => x.profit))); }
public static async Task <string> GetUrlAsync( this IImage imageDto, RegionEnum?region = null, string dataDragonVersion = null) { if (imageDto == null) { throw new ArgumentNullException("imageDto"); } var staticService = new StaticService(imageDto.ApiConfiguration); return(await GetImageUrlAsync( imageDto.Group, imageDto.Full, staticService, region, dataDragonVersion)); }
public static async Task <string> GetProfileIconUrlAsync( this ISummoner summoner, RegionEnum?region = null, string dataDragonVersion = null) { if (summoner == null) { throw new ArgumentNullException("summoner"); } var staticService = new StaticService(summoner.ApiConfiguration); return(await GetImageUrlAsync( "profileicon", string.Format("{0}.png", summoner.ProfileIconId), staticService, region, dataDragonVersion)); }
public static async Task <string> GetChampionImageUrlAsync( this IChampion champion, RegionEnum?region = null, string dataDragonVersion = null) { if (champion == null) { throw new ArgumentNullException("champion"); } var staticService = new StaticService(champion.ApiConfiguration); return(await GetImageUrlAsync( "champion", string.Format("{0}.png", champion.Name), staticService, region, dataDragonVersion)); }
public static async Task <string> GetSpriteUrlAsync( this IImage image, RegionEnum?region = null, string dataDragonVersion = null) { if (image == null) { throw new ArgumentNullException("image"); } var staticService = new StaticService(image.ApiConfiguration); return(await GetImageUrlAsync( "sprite", image.Sprite, staticService, region, dataDragonVersion)); }
/// <summary> /// 加载今天头部包含页面 /// js and css /// 并动态取得当前访问ip对应的静态服务器地址,输出到包含页面 /// </summary> /// <returns></returns> public ActionResult Include() { if (Session[STATICURL] != null) { string staticUrl = Session[STATICURL].ToString(); if (String.IsNullOrEmpty(staticUrl)) { string userIp = Request.ServerVariables.Get("REMOTE_ADDR");//自动获取用户IP staticUrl = StaticService.GetStaticUrl(userIp); Session[STATICURL] = staticUrl; } ViewData[STATICURL] = staticUrl; } else { ViewData[STATICURL] = "../../";//默认的 } return(View()); }
public static async Task <IMastery> GetMasteryStaticInfosAsync( this IHasMasteryId hasMasteryId, MasteryDataEnum?masteryData = null, RegionEnum?region = null, LanguageEnum?languageCode = null, string dataDragonVersion = null) { if (hasMasteryId == null) { throw new ArgumentNullException("hasMasteryId"); } var staticService = new StaticService(hasMasteryId.ApiConfiguration); return(await staticService.GetMasteryAsync( hasMasteryId.Id, masteryData, region, languageCode, dataDragonVersion)); }
public static async Task <IChampion> GetChampionStaticInfosAsync( this IHasChampionId hasChampionId, ChampDataEnum?champData = null, RegionEnum?region = null, LanguageEnum?languageCode = null, string dataDragonVersion = null) { if (hasChampionId == null) { throw new ArgumentNullException("hasChampionId"); } var staticService = new StaticService(hasChampionId.ApiConfiguration); return(await staticService.GetChampionAsync( hasChampionId.ChampionId, champData, region, languageCode, dataDragonVersion)); }
public static async Task <IRune> GetRuneStaticInfosAsync( this IHasRuneId hasRuneId, RuneDataEnum?runeData = null, RegionEnum?region = null, LanguageEnum?languageCode = null, string dataDragonVersion = null) { if (hasRuneId == null) { throw new ArgumentNullException("hasRuneId"); } var staticService = new StaticService(hasRuneId.ApiConfiguration); return(await staticService.GetRuneAsync( hasRuneId.RuneId, runeData, region, languageCode, dataDragonVersion)); }
public static async Task<IEnumerable<IItem>> GetItemsStaticInfosAsync( this IHasItemIds hasItemIds, ItemDataEnum? itemData = null, RegionEnum? region = null, LanguageEnum? languageCode = null, string dataDragonVersion = null) { if (hasItemIds == null) throw new ArgumentNullException("hasItemIds"); var result = new List<IItem>(); var staticService = new StaticService(hasItemIds.ApiConfiguration); foreach (var itemId in hasItemIds.ItemIds.Where(x => x > 0)) { var item = await staticService.GetItemsAsync( itemId, itemData, region, languageCode, dataDragonVersion); result.Add(item); } return result; }
/// <summary> /// Поиск экстремумов с дистанцией между ними /// Торговля с профитом. /// </summary> private void ExtremumSearchDistance(decimal _price, DateTime _datetime, decimal _otkat, decimal _distance, decimal _profit, bool _write_trades) { if (_otkat <= 0 | _distance <= 0 | _profit <= 0) { return; } if (high1 == 0 && low1 == 0) { high1 = _price; low1 = _price; } if (high1 > 0 && _price > high1) { high1 = _price; datetime = _datetime; } if (low1 > 0 && _price < low1) { low1 = _price; datetime = _datetime; } if (high1 > 0 && high1 - _price > _otkat) // нашли локальный максимум { if (_write_trades) { StaticService.LogFileWriteNotDateTime("High " + high1 + " Time " + _datetime, "trade_log.txt", true); } if (high_dist_last == null) { high_dist_last = high1; low_dist_last = -1; } if (high_dist_last < 0) // если макс_дист. еще не найден { if (high1 - low_dist_last >= _distance) // если нашли макс_дист. { if (_write_trades) { StaticService.LogFileWriteNotDateTime("HighD " + high1 + " Time " + _datetime, "trade_log.txt", true); } extremums_distance.Enqueue(new ExtremumPriceParametr(high1, 0, datetime)); high_dist_last = high1; low_dist_last = -1; if (type_current_extremum != 1) // если до этого был не максимум { int _qty = 0; if (base.TP == 0) { _qty = -1; base.CalcEquity(_datetime, high1 - _otkat, _qty); if (_write_trades) { StaticService.LogFileWriteNotDateTime("Short " + (high1 - _otkat) + " Qty " + _qty + " Time " + _datetime + " Equity " + base.EqCurrent, "trade_log.txt", true); } high_position = high1; low_position = 0; } } type_current_extremum = 1; } } else { if (high1 > high_dist_last) { if (_write_trades) { StaticService.LogFileWriteNotDateTime("HighD " + high1 + " Time " + _datetime, "trade_log.txt", true); } extremums_distance.Enqueue(new ExtremumPriceParametr(high1, 0, datetime)); high_dist_last = high1; } } low1 = _price; highlast = high1; high1 = -1; } //******************************************************* if (low1 > 0 && _price - low1 > _otkat) // нашли локальный минимум { if (_write_trades) { StaticService.LogFileWriteNotDateTime("Low " + low1 + " Time " + _datetime, "trade_log.txt", true); } if (low_dist_last == null) { low_dist_last = low1; high_dist_last = -1; } if (low_dist_last < 0) // если min_дист. еще не найден { if (high_dist_last - low1 >= _distance) // если нашли min_дист. { if (_write_trades) { StaticService.LogFileWriteNotDateTime("LowD " + low1 + " Time " + _datetime, "trade_log.txt", true); } extremums_distance.Enqueue(new ExtremumPriceParametr(0, low1, datetime)); low_dist_last = low1; high_dist_last = -1; if (type_current_extremum != -1) // если до этого был не минимум { int _qty = 0; if (base.TP == 0) { _qty = 1; base.CalcEquity(_datetime, low1 + _otkat, _qty); if (_write_trades) { StaticService.LogFileWriteNotDateTime("Long " + (low1 + _otkat) + " Qty " + _qty + " Time " + _datetime + " Equity " + base.EqCurrent, "trade_log.txt", true); } high_position = 0; low_position = low1; } } type_current_extremum = -1; } } else { if (low1 < low_dist_last) { if (_write_trades) { StaticService.LogFileWriteNotDateTime("LowD " + low1 + " Time " + _datetime, "trade_log.txt", true); } extremums_distance.Enqueue(new ExtremumPriceParametr(0, low1, datetime)); low_dist_last = low1; } } high1 = _price; lowlast = low1; low1 = -1; } if (base.TP < 0 && _price < base.PricePosition - _profit) // close short profit { base.CalcEquity(_datetime, _price, base.TP * -1); if (_write_trades) { StaticService.LogFileWriteNotDateTime("Short profit " + _price + " Qty " + base.TP * -1 + " Time " + _datetime + " Equity " + base.EqCurrent, "trade_log.txt", true); } high_position = 0; } if (high_position > 0 && _price > high_position) // close short loss { base.CalcEquity(_datetime, _price, base.TP * -1); if (_write_trades) { StaticService.LogFileWriteNotDateTime("Short loss " + _price + " Qty " + base.TP * -1 + " Time " + _datetime + " Equity " + base.EqCurrent, "trade_log.txt", true); } high_position = 0; } if (base.TP > 0 && _price > base.PricePosition + _profit) // close long profit { base.CalcEquity(_datetime, _price, base.TP * -1); if (_write_trades) { StaticService.LogFileWriteNotDateTime("Long profit " + _price + " Qty " + base.TP * -1 + " Time " + _datetime + " Equity " + base.EqCurrent, "trade_log.txt", true); } low_position = 0; } if (low_position > 0 && _price < low_position) // close long loss { base.CalcEquity(_datetime, _price, base.TP * -1); if (_write_trades) { StaticService.LogFileWriteNotDateTime("Long loss " + _price + " Qty " + base.TP * -1 + " Time " + _datetime + " Equity " + base.EqCurrent, "trade_log.txt", true); } low_position = 0; } }
public string SendData() { return(StaticService.SendData()); }
public static async Task<string> GetSpriteUrlAsync( this IImage image, RegionEnum? region = null, string dataDragonVersion = null) { if (image == null) throw new ArgumentNullException("image"); var staticService = new StaticService(image.ApiConfiguration); return await GetImageUrlAsync( "sprite", image.Sprite, staticService, region, dataDragonVersion); }
public void TradesFilled(ParametrMarketTrades _paramMarketTrades) { decimal variation_margin = 0; // вариационная маржа после каждой сделки decimal varMarLots = 0; // вариационка на один лот при каждой сделке decimal accumIncomeLots = 0; // накопленный доход на лот при каждой сделке decimal countOpenPosition = 0; // количество открытых позиций после каждой сделки decimal qty_trad = _paramMarketTrades.Quantity; if (_paramMarketTrades.Operation == Constants.OperationSell) { qty_trad *= -1; } if (this.Count == 0) { // добавляем новую позу this.Add(new ParametrPosition(_paramMarketTrades.PriceTrades, qty_trad)); } else { // провeрка корректности элементов int sign_position = Math.Sign(this[0].Quantity); bool correct_element = this.All(x => Math.Sign(x.Quantity) == sign_position); if (!correct_element) { System.Windows.MessageBox.Show("Есть лонги и шорты!"); return; } // сортировка this.Sort((a, b) => a.Price.CompareTo(b.Price)); // если позиции длинные if (sign_position > 0) { // если оперция покупка - добаление позиции if (_paramMarketTrades.Operation == Constants.OperationBuy) { AddPosition(_paramMarketTrades.PriceTrades, qty_trad); } else // в протвном случае - закрытие позиции { decimal balance = qty_trad; for (int i = 0; i < Math.Abs(qty_trad); i++) { if (balance != 0) { if (this.Count > 0) // если еще есть, что закрывать { decimal income = 0; balance = this[0].CountCloseLong(balance, _paramMarketTrades.PriceTrades, out income); accumulatedIncome += income; this.RemoveAll(x => x.Quantity == 0); // удаляем позы с нулевыми остатками } else // в протвном случае добляем позу { this.Add(new ParametrPosition(_paramMarketTrades.PriceTrades, balance)); break; } } else { break; } } } } // если позиции короткие if (sign_position < 0) { // если оперция продажа - добаление позиции if (_paramMarketTrades.Operation == Constants.OperationSell) { AddPosition(_paramMarketTrades.PriceTrades, qty_trad); } else // в протвном случае - закрытие позиции { decimal balance = qty_trad; for (int i = 0; i < Math.Abs(qty_trad); i++) { if (balance != 0) { if (this.Count > 0) // если еще есть, что закрывать { decimal income = 0; balance = this[this.Count - 1].CountCloseShort(balance, _paramMarketTrades.PriceTrades, out income); accumulatedIncome += income; this.RemoveAll(x => x.Quantity == 0); // удаляем позы с нулевыми остатками } else // в протвном случае добляем позу { this.Add(new ParametrPosition(_paramMarketTrades.PriceTrades, balance)); break; } } else { break; } } } } } // установить вариационную маржу + общая вариационка + общее кол. откр. поз foreach (ParametrPosition item in this) { variation_margin += item.VariationMarginChange(_paramMarketTrades.PriceTrades); countOpenPosition += item.Quantity; } if (countOpenPosition != 0) { varMarLots = variation_margin / Math.Abs(countOpenPosition); accumIncomeLots = accumulatedIncome / Math.Abs(countOpenPosition); } StaticService.LogFileWriteNotDateTime(_paramMarketTrades.DateTimeTrades + "\t" + _paramMarketTrades.TimeMsk + "\t" + _paramMarketTrades.Operation + "\t" + _paramMarketTrades.Quantity + "\t" + _paramMarketTrades.PriceTrades + "\t*\t" + accumulatedIncome + "\t" + variation_margin + "\t" + countOpenPosition + "\t*\t" + Math.Abs(varMarLots).ToString("#") + "\t" + accumIncomeLots.ToString("#"), out_data_log, true); StaticService.LogFileWriteNotDateTime(_paramMarketTrades.PriceTrades.ToString(), data_price_log, true); StaticService.LogFileWriteNotDateTime(countOpenPosition.ToString(), data_position_log, true); }
/// <summary> /// Main del servicio, carga la base de datos en el objeto contexto e inicializa el servicio /// </summary> /// <param name="args"></param> private static void Main(string[] args) { InitializeServive(); StaticService.Initialize(args, SERVICE_NAME, SERVICE_DISPLAY_NAME, SERVICE_DESCRIPTION, SERVICE_OBJECT_NAME); StaticService.ManageService(); }
public static async Task<IEnumerable<string>> GetItemsImageUrlsAsync( this IHasItemIds hasItemIds, RegionEnum? region = null, string dataDragonVersion = null) { if (hasItemIds == null) throw new ArgumentNullException("hasItemIds"); var staticService = new StaticService(hasItemIds.ApiConfiguration); if (string.IsNullOrWhiteSpace(dataDragonVersion)) { var realm = await staticService.GetRealmAsync(region); dataDragonVersion = realm.CurrentVersion; } return hasItemIds.ItemIds .Where(x => x > 0) .Select(x => string.Format("http://ddragon.leagueoflegends.com/cdn/{0}/img/item/{1}.png", dataDragonVersion, x)); }
public static async Task<string> GetProfileIconUrlAsync( this ISummoner summoner, RegionEnum? region = null, string dataDragonVersion = null) { if (summoner == null) throw new ArgumentNullException("summoner"); var staticService = new StaticService(summoner.ApiConfiguration); return await GetImageUrlAsync( "profileicon", string.Format("{0}.png", summoner.ProfileIconId), staticService, region, dataDragonVersion); }
public static async Task<string> GetUrlAsync( this IImage imageDto, RegionEnum? region = null, string dataDragonVersion = null) { if (imageDto == null) throw new ArgumentNullException("imageDto"); var staticService = new StaticService(imageDto.ApiConfiguration); return await GetImageUrlAsync( imageDto.Group, imageDto.Full, staticService, region, dataDragonVersion); }
public static async Task<IEnumerable<ISummonerSpell>> GetSummonerSpellsStaticInfosAsync( this IHasSummonerSpells hasSummonerSpells, SpellDataEnum? itemData = null, RegionEnum? region = null, LanguageEnum? languageCode = null, string dataDragonVersion = null) { if (hasSummonerSpells == null) throw new ArgumentNullException("hasSummonerSpells"); var staticService = new StaticService(hasSummonerSpells.ApiConfiguration); var allSummonerSpells = await staticService.GetSummonerSpellsAsync( false, itemData, region, languageCode, dataDragonVersion); return allSummonerSpells.Data .Where(x => hasSummonerSpells.SummonerSpells.Select(z => z.ToString()).Contains(x.Value.Key)) .Select(x => x.Value); }
public void SingleCachedServiceTest() { Guid serviceId = Guid.NewGuid(); Guid tokenId = Guid.NewGuid(); var cacheRegion = "cacheRegion"; TimeSpan timeSpan = TimeSpan.FromMilliseconds(10); Guid[] serviceIds = new[] { serviceId }; var endpoint = "/"; var innerText = "Text"; var serviceInfo = new CachedServiceInfo { Id = serviceId, Endpoint = endpoint, Timeout = TimeSpan.FromMilliseconds(5), CircuitBreakerInfo = new CircuitBreakerInfo { ExceptionCount = 1 }, Tokens = new[] { new XPathTokenInfo { Id = tokenId, Name = "XPath", XPath = "/content/text()" } } }; var httpClientResponse = new HttpClientResponse { HttpStatusCode = System.Net.HttpStatusCode.OK, Response = $"<content>{innerText}</content>" }; var cache = new CacheMock(); var httpClientWrapper = Substitute.For <IHttpClientWrapper>(); var serviceRepository = Substitute.For <IServiceRepository>(); var taskScheduler = Substitute.For <ITaskScheduler>(); serviceRepository.GetServicesAndTokens(serviceIds).Returns(new[] { serviceInfo }); httpClientWrapper.PostAsync(endpoint, null, CancellationToken.None).ReturnsForAnyArgs(httpClientResponse); var tokenService = new TokenService(cache); var dynamicService = new DynamicService(cache, httpClientWrapper, tokenService); var cachedService = new CachedService(cache, httpClientWrapper, tokenService); var staticService = new StaticService(cache, tokenService); var serviceBroker = new ServiceBrokerService(serviceRepository, dynamicService, cachedService, staticService, taskScheduler, cache); ServiceBrokerResponse actual = serviceBroker.CallServices(serviceIds, cacheRegion, timeSpan); serviceBroker.CallServices(serviceIds, cacheRegion, timeSpan); httpClientWrapper.ReceivedWithAnyArgs(1).PostAsync(endpoint, null, CancellationToken.None); Assert.IsNotNull(actual); Assert.IsNotNull(actual.ServiceResponses); Assert.IsTrue(actual.ServiceResponses.Any()); ServiceResponse serviceResponse = actual.ServiceResponses.First(); Assert.AreEqual(ServiceResponseStatus.Success, serviceResponse.Status); Assert.AreEqual(httpClientResponse.Response, serviceResponse.Value); Assert.IsNotNull(serviceResponse.TokenResponses); Assert.IsTrue(serviceResponse.TokenResponses.Any()); TokenResponse tokenResponse = serviceResponse.TokenResponses.First(); Assert.AreEqual(TokenResponseStatus.Found, tokenResponse.Status); Assert.AreEqual(innerText, tokenResponse.Value); }
public void MultipleDynamicServiceTest() { Guid service1Id = Guid.NewGuid(); Guid service2Id = Guid.NewGuid(); Guid token1Id = Guid.NewGuid(); Guid token2Id = Guid.NewGuid(); var cacheRegion = "cacheRegion"; TimeSpan timeSpan = TimeSpan.FromMilliseconds(10); Guid[] serviceIds = new[] { service1Id, service2Id }; var endpoint1 = "/endpoint1"; var endpoint2 = "/endpoint2"; var innerText1 = "Text1"; var innerText2 = "Text2"; var service1Info = new DynamicServiceInfo { Id = service1Id, Endpoint = endpoint1, Timeout = TimeSpan.FromMilliseconds(5), CircuitBreakerInfo = new CircuitBreakerInfo { ExceptionCount = 1 }, Tokens = new[] { new XPathTokenInfo { Id = token1Id, Name = "XPath", XPath = "/content/text()" } } }; var service2Info = new DynamicServiceInfo { Id = service2Id, Endpoint = endpoint2, Timeout = TimeSpan.FromMilliseconds(5), CircuitBreakerInfo = new CircuitBreakerInfo { ExceptionCount = 1 }, Tokens = new[] { new XPathTokenInfo { Id = token2Id, Name = "XPath", XPath = "/content/text()" } } }; var httpClientResponse1 = new HttpClientResponse { HttpStatusCode = System.Net.HttpStatusCode.OK, Response = $"<content>{innerText1}</content>" }; var httpClientResponse2 = new HttpClientResponse { HttpStatusCode = System.Net.HttpStatusCode.OK, Response = $"<content>{innerText2}</content>" }; var cache = Substitute.For <ICache>(); var httpClientWrapper = Substitute.For <IHttpClientWrapper>(); var serviceRepository = Substitute.For <IServiceRepository>(); var taskScheduler = Substitute.For <ITaskScheduler>(); serviceRepository.GetServicesAndTokens(serviceIds).Returns(new[] { service1Info, service2Info }); httpClientWrapper.PostAsync(endpoint1, null, CancellationToken.None).ReturnsForAnyArgs(callInfo => { var endpointArg = callInfo.ArgAt <string>(0); if (endpointArg.Equals(endpoint1)) { return(httpClientResponse1); } if (endpointArg.Equals(endpoint2)) { return(httpClientResponse2); } return(null); }); var tokenService = new TokenService(cache); var dynamicService = new DynamicService(cache, httpClientWrapper, tokenService); var cachedService = new CachedService(cache, httpClientWrapper, tokenService); var staticService = new StaticService(cache, tokenService); var serviceBroker = new ServiceBrokerService(serviceRepository, dynamicService, cachedService, staticService, taskScheduler, cache); ServiceBrokerResponse actual = serviceBroker.CallServices(serviceIds, cacheRegion, timeSpan); Assert.IsNotNull(actual); Assert.IsNotNull(actual.ServiceResponses); Assert.IsTrue(actual.ServiceResponses.Any()); ServiceResponse serviceResponse1 = actual.ServiceResponses.First(); Assert.AreEqual(ServiceResponseStatus.Success, serviceResponse1.Status); Assert.AreEqual(httpClientResponse1.Response, serviceResponse1.Value); Assert.IsNotNull(serviceResponse1.TokenResponses); Assert.IsTrue(serviceResponse1.TokenResponses.Any()); TokenResponse tokenResponse1 = serviceResponse1.TokenResponses.First(); Assert.AreEqual(TokenResponseStatus.Found, tokenResponse1.Status); Assert.AreEqual(innerText1, tokenResponse1.Value); ServiceResponse serviceResponse2 = actual.ServiceResponses.Skip(1).First(); Assert.AreEqual(ServiceResponseStatus.Success, serviceResponse2.Status); Assert.AreEqual(httpClientResponse2.Response, serviceResponse2.Value); Assert.IsNotNull(serviceResponse1.TokenResponses); Assert.IsTrue(serviceResponse1.TokenResponses.Any()); TokenResponse tokenResponse2 = serviceResponse2.TokenResponses.First(); Assert.AreEqual(TokenResponseStatus.Found, tokenResponse2.Status); Assert.AreEqual(innerText2, tokenResponse2.Value); }
public static async Task<string> GetChampionImageUrlAsync( this IChampion champion, RegionEnum? region = null, string dataDragonVersion = null) { if (champion == null) throw new ArgumentNullException("champion"); var staticService = new StaticService(champion.ApiConfiguration); return await GetImageUrlAsync( "champion", string.Format("{0}.png", champion.Name), staticService, region, dataDragonVersion); }
public async Task AdaptationAsync() { string _result_test = String.Empty; TimeSpan _runTime; DateTime _startRun = DateTime.Now; TimeSpan steptime = new TimeSpan(2, 0, 0); TimeSpan steptime1 = new TimeSpan(2, 0, 0); TimeSpan starttime = new TimeSpan(10, 1, 0).Subtract(steptime1); TimeSpan finishtime = starttime.Add(steptime); TimeSpan stoptime = new TimeSpan(19, 0, 0); decimal otkat = 30; decimal distance = 30; decimal profit = 30; MarketTradesRepository mTR = new MarketTradesRepository(); mTR = (MarketTradesRepository)StaticService.Deserializes(mTR.GetType().ToString(), mTR); ExtremumPrice _extPrice = new ExtremumPrice(); // !!! StaticService.DeleteFile("trade_log.txt"); StaticService.DeleteFile("equ.txt"); StaticService.DeleteFile("trade_log.txt"); StaticService.DeleteFile("group_log.txt"); StaticService.LogFileWriteNotDateTime("EqCurrent\tCountTrades\tCountProfit\tCountLoss\tDrawdown\t_otkat\t_distance\t_profit", "equ.txt", true); //StaticService.LogFileWriteNotDateTime("EqCurrent\tDrawdown\t_otkat\t_distance\t_profit", "trade_log.txt", true); do { //------------------------------------- finishtime = finishtime.Add(steptime1); starttime = finishtime.Subtract(steptime); if (finishtime > stoptime) { finishtime = stoptime; } //-------------------------------------- // I поиск оптимальных параметров List <Task <ResultExtremDistance> > tasksResult = new List <Task <ResultExtremDistance> >(); List <Task <string> > tasksString = new List <Task <string> >(); List <ResultExtremDistance> resultsExDist = new List <ResultExtremDistance>(); MarketTradesRepository _mtr_range = ResWhereTime(mTR, starttime, finishtime); for (int i = (int)otkat; i <= 200; i += 10) { for (int ii = i; ii <= 200; ii += 10) { for (int iii = i; iii <= 200; iii += 10) { Task <ResultExtremDistance> theTask = TaskCalculation(_mtr_range, i, ii, iii); tasksResult.Add(theTask); } } } await Task <ResultExtremDistance> .WhenAll(tasksResult); foreach (Task <ResultExtremDistance> item in tasksResult) { if (item.Result.otkat > 0) { resultsExDist.Add(item.Result); } } // II выборка лучших параметров ResultExtremDistance _bestResExDist = MyGroupBy(resultsExDist); /* * // III следующий интервал торгуем с выбранными параметрами * MarketTradesRepository _mtr = ResWhereTime(mTR, finishtime, finishtime.Add(steptime1)); * * StaticService.LogFileWriteNotDateTime("\nParametr\t" + _bestResExDist.eqcurrent + "\t" + _bestResExDist.drawdown + "\t" + _bestResExDist.otkat + "\t" + _bestResExDist.distance + "\t" + _bestResExDist.profit, "trade_log.txt", true); * * Task<string> theTaskMarket = TaskCalculationString(_mtr, _extPrice, _bestResExDist.otkat, _bestResExDist.distance, _bestResExDist.profit); * tasksString.Add(theTaskMarket); * * await Task<string>.WhenAll(tasksString); * * foreach (Task<string> item in tasksString) * { * _result_test += item.Result; * }*/ }while (finishtime < stoptime); _runTime = DateTime.Now - _startRun; StaticService.LogFileWriteNotDateTime(String.Format("{0:00}:{1:00}:{2:00}.{3:000}", _runTime.Hours, _runTime.Minutes, _runTime.Seconds, _runTime.Milliseconds), "runtime.txt", true); StaticService.LogFileWriteNotDateTime(_result_test, "equ.txt", true); }
public StaticController(StaticService staticService) { _staticService = staticService; }