public PagingContext(Func <Task <PagingLoadStatus> > loadPageAsync, LoadingContext loading) { Ensure.NotNull(loadPageAsync, "loadPageAsync"); Ensure.NotNull(loading, "loading"); LoadPageAsync = loadPageAsync; this.loading = loading; }
protected override void OnFinishLoading(LoadingContext context) { if (!Items.Any()) { Title = Resource.NoHostsDetected; } }
public override void OnEnter(BaseContext context) { base.OnEnter(context); LoadingContext loadingContext = (LoadingContext)context; m_Text.text = loadingContext.m_StrText; }
/// <summary>Загружает тайл с указанными индексами</summary> /// <param name="x">Горизонтальный индекс</param> /// <param name="y">Вертикальный индекс</param> /// <param name="zoom">Уровень масштабирования</param> public MapTileElement GetTile(int x, int y, int zoom) { var context = new LoadingContext(_pathProvider.GetLocalPath(x, y, zoom), _pathProvider.GetWebPath(x, y, zoom), _webPool); context.BeginLoading(); return(new ContextMapTileElement(context, x, y, zoom)); }
protected virtual void Clear() { if (_lexer != null) { _lexer.Clear(); } _context = null; _token = null; }
public Disposable(LoadingContext context) { Ensure.NotNull(context, "context"); this.context = context; context.OperationCount++; if (context.OperationCount == 1) { context.LoadingChanged?.Invoke(context); } }
public async Task InvokeAsyncTest() { // Arrange var source = new byte[0]; var pipe = new ByteArrayPipe <object>(new TestDesignModeService()); var context = new LoadingContext <object>(null, source, null, null, null); LoadingPipeDelegate <object> next = (_, __) => Task.CompletedTask; // Act await pipe.InvokeAsync(context, next); // Assert Assert.IsAssignableFrom <Stream>(context.Current); }
/// <inheritdoc /> public async Task <byte[]> GetByteArrayAsync(object source, CancellationToken cancellationToken = default) { if (source == null) { throw new ArgumentNullException(nameof(source)); } var context = new LoadingContext <byte[]>(SynchronizationContext.Current, source, null, null, null); var pipeDelegate = ImageExService.GetHandler <byte[]>(); await pipeDelegate.Invoke(context, cancellationToken); cancellationToken.ThrowIfCancellationRequested(); return((context.Current as byte[]) !); }
public void LookupContainsIdAlreadyLoaded_ShouldIgnore() { var loookupContext = new LookupContext(); loookupContext.AddLookupIds <Image, string>(new[] { "a", "b" }); var dataStore = new DataStore(); dataStore.AddReferences(new Dictionary <string, Image> { { "b", new Image { Id = "b" } } }); var sut = new LoadingContext(loookupContext, dataStore); var imagesToLoad = sut.ReferenceIds <Image, string>(); Assert.Contains("a", imagesToLoad); Assert.DoesNotContain("b", imagesToLoad); }
void LoadAsyncImpl <T>(string fileName, System.Action <T> finishLoad) where T : Object { LoadingContext context; if (loadingDic.TryGetValue(fileName, out context)) { if (context.loading) { context.callBack.Add(finishLoad); } else { finishLoad(context.res as T); } } else { context = new LoadingContext(); context.fileName = fileName; context.loading = true; context.callBack.Add(finishLoad); loadingDic.Add(fileName, context); assetManager.LoadAsync <T>(fileName, (res) => { //UI内存路线:模板 对象池 引用 4 context.res = res; context.loading = false; foreach (object cb in context.callBack) { System.Action <T> action = cb as System.Action <T>; action(context.res as T); } context.callBack.Clear(); }); } }
public async Task CallOnAppearingAsync() { var mokB = new Mock<IWatcher>(); mokB.SetupAllProperties(); var mockA = new Mock<ITimeWatcher>(); mockA.Setup(x => x.StartWatcher(It.IsAny<string>(),It.IsAny<bool>())).Returns(() => mokB.Object); LocalAutoMock = AutoMock.GetLoose(cfg => cfg.RegisterMock(mockA)); SetMockContainer(); var token = new CancellationToken(false); LoadingContext.FromUser = LoadingContext.Create(LoadingContext.FromUser, token, mockA.Object); LoadingContext.OnAppearing = LoadingContext.Create(LoadingContext.OnAppearing, token, mockA.Object); LoadingContext.RefreshVisual = LoadingContext.Create(LoadingContext.RefreshVisual, token, mockA.Object); var obj = (ViewModel)new ViewModelWhithState(); Assert.IsNotNull(obj); Assert.IsFalse(obj.IsVisible); await obj.OnAppearingAsync(); Assert.IsTrue(obj.IsVisible); Assert.IsFalse(obj.IsLoading); mockA.Verify(x => x.StartWatcher(It.IsAny<string>(), It.IsAny<bool>()),Times.Once); }
public void DoSearch(string query, LoadingContext<BookSummary> context) { context.Progress.Progress = null; Http.RequestHtml(GetSearchUrl(query), doc => { if (doc.DocumentNode.Descendants("title").First().InnerText.StartsWith("The Library Catalog : Item #")) { context.AddResult(new DetailsPageSummary(doc)); context.SetCompleted(); return; } var serverInput = doc.DocumentNode.Descendants("input").First(n => n.GetAttributeValue("name", "") == "server"); var countString = serverInput.PreviousSibling.InnerText; var count = int.Parse(countParser.Match(countString).Groups[1].Value); if (count == 0) context.SetCompleted(); else { context.Progress.Maximum = count; ParseResultList(doc, context); } }); }
static void ParseResultList(HtmlDocument doc, LoadingContext<BookSummary> context) { var mainTable = doc.DocumentNode.FirstChild.Element("body").Element("center").Element("table"); foreach (var elem in mainTable.Elements("tr")) { if (context.Progress.WasCanceled) { context.SetCompleted(); return; } if (elem.Elements("th").Count() != 2) continue; //These are <hr> rows; ignore them context.AddResult(new SearchResult(elem)); context.Progress.Progress++; } //Their next link is supposed to be in a <form> tag, //but the <form> tag is malformed. I do not want to //rely entirely on text matching for this, so I look //in the <form>'s parent. var nextLink = doc.DocumentNode.Descendants("form").SelectMany(f => f.ParentNode.Descendants("a")) .FirstOrDefault(a => a.InnerText.Contains("Next")); if (nextLink == null) { Debug.Assert(context.Progress.Progress == context.Progress.Maximum, "Book count mismatch"); context.SetCompleted(); } else { Http.RequestHtml(new Uri(baseUri, nextLink.GetAttributeValue("href", "")), newDoc => ParseResultList(newDoc, context) ); } }
// private Lexer Init(string filePath, TextReader reader, LoadingContext context) { if (filePath == null) throw new ArgumentNullException("filePath"); if (reader == null) throw new ArgumentNullException("reader"); if (context == null) throw new ArgumentNullException("context"); _filePath = filePath; _reader = reader; _context = context; _index = _count = 0; _isEOF = false; _totalIndex = 0; _lastLine = _lastColumn = _line = _column = 1; if (_stringBuilder == null) { _stringBuilder = new StringBuilder(_stringBuilderCapacity); } return this; }
public static Lexer Get(string filePath, TextReader reader, LoadingContext context) { return Instance.Init(filePath, reader, context); }
public void Clear() { _filePath = null; _reader = null; _context = null; if (_stringBuilder != null && _stringBuilder.Capacity > _stringBuilderCapacity * 8) { _stringBuilder = null; } }
void Awake() { context = new LoadingContext(this); }
public static bool Compile(IReadOnlyList<string> schemaFileList, IReadOnlyList<string> csFileList, IReadOnlyList<string> csPpList, IReadOnlyList<MetadataReference> csRefList, string csAssemblyName, out LoadingContext context, out string csCode) { context = null; csCode = _csGeneratedFileBanner; if (schemaFileList == null || schemaFileList.Count == 0) { return true; } try { context = CompilerContext.Current = new CompilerContext(); var cuList = new List<CompilationUnitNode>(); foreach (var schemaFile in schemaFileList) { using (var reader = new StreamReader(schemaFile)) { CompilationUnitNode cuNode; if (Parser.Parse(schemaFile, reader, context, out cuNode)) { cuList.Add(cuNode); } else { return false; } } } var nsList = new List<NamespaceNode>(); foreach (var cu in cuList) { nsList.AddRange(cu.NamespaceList); } if (nsList.Count == 0) { return true; } var nsInfoMap = new NamespaceInfoMap(); foreach (var ns in nsList) { var uri = ns.UriValue; NamespaceInfo nsInfo; if (!nsInfoMap.TryGetValue(uri, out nsInfo)) { nsInfo = new NamespaceInfo(uri); nsInfoMap.Add(uri, nsInfo); } nsInfo.NamespaceNodeList.Add(ns); ns.NamespaceInfo = nsInfo; } foreach (var ns in nsList) { ns.ResolveImports(nsInfoMap); } foreach (var nsInfo in nsInfoMap.Values) { nsInfo.CheckDuplicateGlobalTypeNodes(); } foreach (var ns in nsList) { ns.Resolve(); } foreach (var ns in nsList) { ns.CreateInfos(); } // if (csFileList == null || csFileList.Count == 0) { return true; } var parseOpts = new CSharpParseOptions(preprocessorSymbols: csPpList, documentationMode: DocumentationMode.None); var compilation = CSharpCompilation.Create( assemblyName: "__TEMP__", syntaxTrees: csFileList.Select(csFile => CSharpSyntaxTree.ParseText(text: File.ReadAllText(csFile), options: parseOpts, path: csFile)), references: csRefList, options: _csCompilationOptions); if (csRefList != null) { foreach (var csRef in csRefList) { if (csRef.Properties.Kind == MetadataImageKind.Assembly) { var assSymbol = compilation.GetAssemblyOrModuleSymbol(csRef) as IAssemblySymbol; if (assSymbol != null) { CSEX.MapNamespaces(nsInfoMap, assSymbol, true); } } } } var compilationAssSymbol = compilation.Assembly; if (CSEX.MapNamespaces(nsInfoMap, compilationAssSymbol, false) == 0) { return true; } foreach (var nsInfo in nsInfoMap.Values) { if (nsInfo.DottedName == null) { CompilerContext.ErrorAndThrow(new DiagMsgEx(DiagCodeEx.SchemaNamespaceAttributeRequired, nsInfo.Uri), default(TextSpan)); } } CSEX.MapGlobalTypes(nsInfoMap, compilationAssSymbol.GlobalNamespace); foreach (var nsInfo in nsInfoMap.Values) { nsInfo.SetGlobalTypeDottedNames(); } foreach (var nsInfo in nsInfoMap.Values) { nsInfo.MapGlobalTypeMembers(); } var cuAttListSyntaxList = new List<AttributeListSyntax>(); var cuMemberSyntaxList = new List<MemberDeclarationSyntax>(); var globalTypeMdRefSyntaxList = new List<ExpressionSyntax>(); foreach (var nsInfo in nsInfoMap.Values) { if (!nsInfo.IsRef) { List<string> dottedPropertyNames; var dottedTypeNames = nsInfo.GetRefData(out dottedPropertyNames); cuAttListSyntaxList.Add(CS.AttributeList("assembly", CSEX.__CompilerSchemaNamespaceAttributeName, SyntaxFactory.AttributeArgument(CS.Literal(nsInfo.Uri)), SyntaxFactory.AttributeArgument(CS.Literal(nsInfo.DottedName.ToString())), SyntaxFactory.AttributeArgument(CS.NewArrOrNullExpr(CS.StringArrayType, dottedTypeNames.Select(i => CS.Literal(i)))), SyntaxFactory.AttributeArgument(CS.NewArrOrNullExpr(CS.StringArrayType, dottedPropertyNames.Select(i => CS.Literal(i)))) )); nsInfo.GetSyntax(cuMemberSyntaxList, globalTypeMdRefSyntaxList); } } var sdataProgramName = CSEX.SDataProgramName(csAssemblyName); //>public static class SData_XX { //> public static void Initialize() { } //> static SData_XX() { //> SData.ProgramMd.AddGlobalTypes(new GlobalTypeMd[]{ ... }); //> } //>} cuMemberSyntaxList.Add(CS.Class(null, CS.PublicStaticTokenList, sdataProgramName, null, CS.Method(CS.PublicStaticTokenList, CS.VoidType, "Initialize", null, null), CS.Constructor(CS.StaticTokenList, sdataProgramName, null, null, CS.ExprStm(CS.InvoExpr(CS.MemberAccessExpr(CSEX.ProgramMdExpr, "AddGlobalTypes"), CS.NewArrOrNullExpr(CSEX.GlobalTypeMdArrayType, globalTypeMdRefSyntaxList)))))); csCode = _csGeneratedFileBanner + SyntaxFactory.CompilationUnit(default(SyntaxList<ExternAliasDirectiveSyntax>), default(SyntaxList<UsingDirectiveSyntax>), SyntaxFactory.List(cuAttListSyntaxList), SyntaxFactory.List(cuMemberSyntaxList)).NormalizeWhitespace().ToString(); return true; } catch (LoadingException) { } catch (Exception ex) { context.AddDiagnostic(DiagnosticSeverity.Error, (int)DiagCodeEx.InternalCompilerError, "Internal compiler error: " + ex.ToString(), default(TextSpan)); } return false; }
protected virtual void Init(string filePath, TextReader reader, LoadingContext context) { _lexer = Lexer.Get(filePath, reader, context); _context = context; _token = null; }
public static bool Parse(string filePath, TextReader reader, LoadingContext context, ClassTypeMd classTypeMd, out object result) { if (classTypeMd == null) throw new ArgumentNullException("classTypeMd"); return Instance.ParsingUnit(filePath, reader, context, classTypeMd, out result); }
protected override void Init(string filePath, TextReader reader, LoadingContext context) { base.Init(filePath, reader, context); _aliasUriListStack.Clear(); }
private bool ParsingUnit(string filePath, TextReader reader, LoadingContext context, ClassTypeMd classTypeMd, out object result) { try { Init(filePath, reader, context); object obj; TextSpan textSpan; if (ClassValue(classTypeMd, out obj, out textSpan)) { EndOfFileExpected(); result = obj; return true; } else { ErrorAndThrow("Class value expected."); } } catch (LoadingException) { } finally { Clear(); } result = null; return false; }
// LoadingContext public void PushLoadingContext(LoadingContext context) { _serverProcess.PushLoadingContext(context); }
private bool CompilationUnit(string filePath, TextReader reader, LoadingContext context, out CompilationUnitNode result) { try { Init(filePath, reader, context); var cu = new CompilationUnitNode(); while (Namespace(cu)) ; EndOfFileExpected(); result = cu; return true; } catch (LoadingException) { } finally { Clear(); } result = null; return false; }
/// <summary>Загружает тайл с указанными индексами</summary> /// <param name="x">Горизонтальный индекс</param> /// <param name="y">Вертикальный индекс</param> /// <param name="zoom">Уровень масштабирования</param> /// <returns>ImageSource тайла</returns> public ITileLoadingContext GetTile(int x, int y, int zoom) { var context = new LoadingContext(x, y, zoom); context.BeginLoading(); return context; }
public static bool Parse(string filePath, TextReader reader, LoadingContext context, out CompilationUnitNode result) { return Instance.CompilationUnit(filePath, reader, context, out result); }
protected void OnLoadingChanged(LoadingContext context) { Log.Debug($"Loading changed to '{context.IsLoading}'."); IsLoading = Context.IsLoading; StateHasChanged(); }
private async Task SetDesignSourceAsync(object?source) { if (_image == null) { return; } _lastLoadCts?.Cancel(); if (source == null) { AttachDesignSource(null); VisualStateManager.GoToState(this, EmptyStateName, true); return; } var loadCts = new CancellationTokenSource(); _lastLoadCts = loadCts; try { IsLoading = true; VisualStateManager.GoToState(this, LoadingStateName, true); // 开始 Loading,重置 DownloadProgress DownloadProgress = default; var context = new LoadingContext <ImageSource>(_uiContext, source, AttachDesignSource, ActualWidth, ActualHeight); context.DownloadProgressChanged += (sender, progress) => { if (_uiContext != null) { _uiContext.Post(state => { DownloadProgress = progress; }, null); } else { DownloadProgress = progress; } }; var pipeDelegate = ImageExService.GetHandler <ImageSource>(); var retryCount = RetryCount; var retryDelay = RetryDelay; var policy = Policy.Handle <Exception>() .WaitAndRetryAsync(retryCount, count => retryDelay, (ex, delay) => { context.Reset(); }); await policy.ExecuteAsync(() => pipeDelegate.Invoke(context, loadCts.Token)); if (!loadCts.IsCancellationRequested) { VisualStateManager.GoToState(this, OpenedStateName, true); if (_uiContext != null) { _uiContext.Post(state => { ImageOpened?.Invoke(this, EventArgs.Empty); }, null); } else { ImageOpened?.Invoke(this, EventArgs.Empty); } } } catch (Exception ex) { if (!loadCts.IsCancellationRequested) { AttachDesignSource(null); VisualStateManager.GoToState(this, FailedStateName, true); if (_uiContext != null) { _uiContext.Post(state => { ImageFailed?.Invoke(this, new ImageExFailedEventArgs(source, ex)); }, null); } else { ImageFailed?.Invoke(this, new ImageExFailedEventArgs(source, ex)); } } } finally { if (!loadCts.IsCancellationRequested) { IsLoading = false; } } }
private void Awake() { context = new LoadingContext(this, true); context.Start(); }
public LoadingBlock(LoadingContext context) { _context = context; _previousState = _context.IsLoadingAllowed; _context.IsLoadingAllowed = false; }