public FourSquareLoadRequest(LoadContext context, JeffWilcox.FourthAndMayor.FourSquareWebClient.UriErrorPair uri, string postData) : this(context, uri) { Debug.Assert(_sr != null); _sr.PostString = postData; }
public async Task Load(IFileSystem fileSystem, UPath filePath, LoadContext loadContext) { Stream hpiStream; Stream hpbStream; if (filePath.GetExtensionWithDot() == ".HPI") { var hpbName = filePath.GetNameWithoutExtension() + ".HPB"; if (!fileSystem.FileExists(filePath.GetDirectory() / hpbName)) { throw new FileNotFoundException($"{hpbName} not found."); } hpiStream = await fileSystem.OpenFileAsync(filePath); hpbStream = await fileSystem.OpenFileAsync(filePath.GetDirectory() / hpbName); } else { var hpiName = filePath.GetNameWithoutExtension() + ".HPI"; if (!fileSystem.FileExists(filePath.GetDirectory() / hpiName)) { throw new FileNotFoundException($"{hpiName} not found."); } hpiStream = await fileSystem.OpenFileAsync(filePath.GetDirectory() / hpiName); hpbStream = await fileSystem.OpenFileAsync(filePath); } Files = _hpiHpb.Load(hpiStream, hpbStream); }
internal override void Load( DataObject obj, object value, object exValue, LoadContext loadContext) { MetadataProperty property = this.Association.Property; if (obj.IsPropertyModified(property)) { return; } value = DataProperty.EscapeFromDBNull(value); exValue = DataProperty.EscapeFromDBNull(exValue); obj.LoadPropertyValue(property, value, exValue, loadContext); DataId id = new DataId((string)value); if (!id.IsEmpty) { MetadataAssociationRef metadataAssociationRef = this.Association.Selector == null ? this.Refs[0] : this.Refs.FindBySelectorValue(exValue); if (metadataAssociationRef != null) { ObjectListLoaderByIds refLoader = this.RefLoaders[metadataAssociationRef.Index]; if (refLoader != null && refLoader.ObjectLoader.Count > 0) { refLoader.Add(id); } } } }
/// <summary>Extracts part name and ID from the node.</summary> /// <param name="node">The part's config node.</param> /// <param name="loadContext">The loading context that tells how to extract the values.</param> /// <returns> /// The array of two values, where first value is the name, and the second value is ID. The values that cannot be /// recovered will be <c>null</c>. /// </returns> static string[] GetPartId(ConfigNode node, LoadContext loadContext) { string partName = null; string partId = null; if (loadContext == LoadContext.SFS) { partName = node.GetValue("name"); partId = node.GetValue("cid"); } else { var craftPartName = node.GetValue("part"); if (craftPartName != null) { var pair = craftPartName.Split(new[] { '_' }, 2); if (pair.Length == 2) { partName = pair[0]; partId = pair[1]; } } } return(new[] { partName, partId }); }
/// <summary>Extracts the part name from the game state.</summary> /// <param name="node">The part's config node to extract the value from.</param> /// <param name="loadContext">The current loading context.</param> /// <returns>The part's name.</returns> public static string GetPartNameFromUpgradeNode(ConfigNode node, LoadContext loadContext) { ArgumentGuard.NotNull(node, "node", context: node); ArgumentGuard.OneOf(loadContext, "loadContext", new[] { LoadContext.SFS, LoadContext.Craft }, context: node); return(GetPartId(node, loadContext)[0]); }
public AssemblyLoadResult Load(LoadContext loadContext) { string name = loadContext.AssemblyName; Assembly assembly; if (_cache.TryGetValue(name, out assembly)) { return new AssemblyLoadResult(assembly); } string path = Path.Combine(_path, name + ".dll"); if (File.Exists(path)) { assembly = Assembly.LoadFile(path); } if (assembly != null) { _cache[name] = assembly; return new AssemblyLoadResult(assembly); } return null; }
public AssemblyLoadResult Load(LoadContext loadContext) { string name = loadContext.AssemblyName; Assembly assembly; if (_cache.TryGetValue(name, out assembly)) { return(new AssemblyLoadResult(assembly)); } string path = Path.Combine(_path, name + ".dll"); if (File.Exists(path)) { assembly = Assembly.LoadFile(path); } if (assembly != null) { _cache[name] = assembly; return(new AssemblyLoadResult(assembly)); } return(null); }
public AssemblyLoadResult Load(LoadContext loadContext) { // If there's an output path then skip all loading of cached compilations // This is to avoid using the cached version when trying to produce a new one. // Also skip if we're not loading assemblies if (loadContext.OutputPath != null) { return null; } string name = loadContext.AssemblyName; string path = Path.Combine(_rootPath, name); var targetFrameworkFolder = VersionUtility.GetShortFrameworkName(loadContext.TargetFramework); string cachedFile = Path.Combine(path, "bin", targetFrameworkFolder, name + ".dll"); if (File.Exists(cachedFile)) { Trace.TraceInformation("[{0}]: Loading '{1}' from {2}.", GetType().Name, name, cachedFile); return new AssemblyLoadResult(Assembly.LoadFile(cachedFile)); } return null; }
//test the save file for upgrades public override TestResult OnTest(ConfigNode node, LoadContext loadContext, ref string nodeName) { //when the parts of a craft should be checked if (loadContext == LoadContext.Craft) { TestResult tr = checkPart(node, loadContext); return(tr); } //when the savefile should be updated else if (loadContext == LoadContext.SFS) { //iterate over all vessels in the savefile ConfigNode[] vessels = node.GetNode("FLIGHTSTATE").GetNodes("VESSEL"); for (int i = 0; i < vessels.Length; i++) { //iterate of all parts in the vessel ConfigNode[] parts = vessels[i].GetNodes("PART"); for (int j = 0; j < parts.Length; j++) { if (checkPart(parts[j], loadContext) == TestResult.Upgradeable) { return(TestResult.Upgradeable); } } } return(TestResult.Pass); } return(TestResult.Pass); }
public ADSK.ElementId[] ToRevit(Elements.Element hyparElement, LoadContext context) { var createdElements = new List <ADSK.ElementId>(); var floor = hyparElement as Elements.Floor; var curves = floor.Profile.Perimeter.ToRevitCurveArray(true); var floorType = new ADSK.FilteredElementCollector(context.Document) .OfClass(typeof(ADSK.FloorType)) .OfType <ADSK.FloorType>() .First(e => e.Name.Contains("Generic")); double offsetFromLevel = 0; var level = context.Level ?? FromHyparExtensions.GetLevelClosestToZ(Units.MetersToFeet(floor.Elevation), context.Document, out offsetFromLevel); var rvtFloor = context.Document.Create.NewFloor(curves, floorType, level, false, ADSK.XYZ.BasisZ); context.Document.Regenerate(); // we must regenerate the document before adding openings var allOpenings = floor.Openings.Select(o => o.Perimeter).Union(floor.Profile.Voids); foreach (var opening in allOpenings) { var openingProfile = opening.ToRevitCurveArray(true); var rvtOpen = context.Document.Create.NewOpening(rvtFloor, openingProfile, true); createdElements.Add(rvtOpen.Id); } offsetFromLevel += Units.MetersToFeet(floor.Thickness); rvtFloor.LookupParameter("Height Offset From Level")?.Set(Units.MetersToFeet(offsetFromLevel)); createdElements.Add(rvtFloor.Id); return(createdElements.ToArray()); }
public HttpResponseMessage detail(string username) { using (var context = new LoadContext()) { var user = context.B3G_USERS .Where(b => b.USER_NAME == username.ToUpper()) .FirstOrDefault(); if (user == null) { return(Request.CreateErrorResponse(HttpStatusCode.NotFound, "User not found")); } var userd = context.B3G_USER_DESC .Where(t => t.USER_ID == user.USER_ID && t.LANG_CODE == "TH") .FirstOrDefault(); UserDetail userdetail = new UserDetail(); userdetail.userid = user.USER_ID; userdetail.username = user.USER_NAME; if (userd != null) { userdetail.firstname = userd.FIRST_NAME; userdetail.lastname = userd.LAST_NAME; } return(user == null ? Request.CreateErrorResponse(HttpStatusCode.NotFound, "User not found") : Request.CreateResponse(HttpStatusCode.OK, userdetail)); } }
public AssemblyLoadResult Load(LoadContext loadContext) { string name = loadContext.AssemblyName; Assembly assembly; if (_cache.TryGetValue(name, out assembly)) { return(new AssemblyLoadResult(assembly)); } string path; if (_paths.TryGetValue(name, out path)) { assembly = Assembly.LoadFile(path); _cache[name] = assembly; } if (assembly == null) { return(null); } return(new AssemblyLoadResult(assembly)); }
private static AssemblyLoadResult Build(KProject project, string outputPath, FrameworkName targetFramework, PackageBuilder builder) { var loader = CreateLoader(Path.GetDirectoryName(project.ProjectFilePath)); loader.Walk(project.Name, project.Version, targetFramework); var targetFrameworkFolder = VersionUtility.GetShortFrameworkName(targetFramework); string targetPath = Path.Combine(outputPath, targetFrameworkFolder); var loadContext = new LoadContext(project.Name, targetFramework) { OutputPath = targetPath, PackageBuilder = builder, }; var result = loader.Load(loadContext); if (result == null || result.Errors != null) { return(result); } // REVIEW: This might not work so well when building for multiple frameworks RunStaticMethod("Compiler", "Compile", targetPath); return(result); }
public void LoadAsync(LoadContext context) { m_context = context; if (NetworkInterface.GetIsNetworkAvailable()) { if (m_context != null && m_context.Url != "") { Uri serviceUri = new Uri(m_context.Url); m_downloader.Headers[HttpRequestHeader.Referer] = "http://lab3d.ru"; m_downloader.OpenReadAsync(serviceUri); } else { ContentLoadAsyncEventArgs args = new ContentLoadAsyncEventArgs(); args.m_error = new Exception("Url is invalid!"); if (this.LoadCompleted != null) { this.LoadCompleted(this, args); } } } else { ContentLoadAsyncEventArgs args = new ContentLoadAsyncEventArgs(); args.m_error = new Exception("No network available"); if (this.LoadCompleted != null) { this.LoadCompleted(this, args); } } }
protected virtual FourSquareLoadRequest BuildPostRequest(LoadContext context, JeffWilcox.FourthAndMayor.FourSquareWebClient.UriErrorPair uri, Dictionary <string, string> parameters, byte[] postData) { var ld = new FourSquareLoadRequest(context, uri, postData, parameters); ld.SetMultipartPostData(postData); return(ld); }
public AssemblyLoadResult Load(LoadContext loadContext) { // If there's an output path then skip all loading of cached compilations // This is to avoid using the cached version when trying to produce a new one. // Also skip if we're not loading assemblies if (loadContext.OutputPath != null) { return(null); } string name = loadContext.AssemblyName; string path = Path.Combine(_rootPath, name); var targetFrameworkFolder = VersionUtility.GetShortFrameworkName(loadContext.TargetFramework); string cachedFile = Path.Combine(path, "bin", targetFrameworkFolder, name + ".dll"); if (File.Exists(cachedFile)) { Trace.TraceInformation("[{0}]: Loading '{1}' from {2}.", GetType().Name, name, cachedFile); return(new AssemblyLoadResult(Assembly.LoadFile(cachedFile))); } return(null); }
public override object Deserialize(LoadContext context, Type objectType, System.IO.Stream stream) { DateTime start = DateTime.Now; XElement xElement = XElement.Load(stream); Debug.Assert(xElement.Name == "rsp", "XML root is not rsp"); // check success/fail. // var stat = xElement.Attribute("stat").Value; if (stat != "ok") { var err = xElement.Element("err"); var msg = err.Attribute("msg").Value; PriorityQueue.AddUiWorkItem(() => { MessageBox.Show(String.Format("Error making call {0}: {1}", "getInfo", msg)); }); } else { return(DeserializeCore(context, (XElement)xElement.FirstNode, objectType, stream)); } return(null); }
public async Task Load(IFileSystem fileSystem, UPath filePath, LoadContext loadContext) { Stream lstStream; Stream arcStream; if (filePath.GetExtensionWithDot() == ".irlst") { var arcName = $"{filePath.GetNameWithoutExtension()}.irarc"; if (!fileSystem.FileExists(filePath.GetDirectory() / arcName)) { throw new FileNotFoundException($"{ arcName } not found."); } lstStream = await fileSystem.OpenFileAsync(filePath); arcStream = await fileSystem.OpenFileAsync(filePath.GetDirectory() / arcName); } else { var lstName = $"{filePath.GetNameWithoutExtension()}.irlst"; if (!fileSystem.FileExists(filePath.GetDirectory() / lstName)) { throw new FileNotFoundException($"{lstName} not found."); } lstStream = await fileSystem.OpenFileAsync(filePath.GetDirectory() / lstName); arcStream = await fileSystem.OpenFileAsync(filePath); } Files = _irarc.Load(lstStream, arcStream); }
internal override void LoadValueFromDb(object value, object exValue, LoadContext loadContext) { DataId id = new DataId((string)DataProperty.EscapeFromDBNull(value)); DataObject dataObject = (DataObject)null; DataObjectChildList dataObjectChildList = (DataObjectChildList)null; if (!id.IsEmpty) { MetadataAssociationRefList refs = this.Metadata.Association.Refs; MetadataAssociationRef metadataAssociationRef = this.Metadata.Association.Selector == null ? refs[0] : refs.FindBySelectorValue(exValue); if (metadataAssociationRef == null) { throw new DataException(string.Format("Нарушение целостности данных.\n{0}\nОшибка: Невозможно определить класс связанного объекта по значению селектора '{1}'.\n", (object)this.SystemView, exValue)); } dataObject = this.Session[metadataAssociationRef.RefClass].EnsureCacheItem(id); if (dataObject.IsNull) { dataObject = (DataObject)null; } else if (this.Metadata.IsAggregation) { dataObjectChildList = dataObject.GetChilds(metadataAssociationRef.OwnerChildRef); if ((loadContext & LoadContext.FetchAllObjects) != (LoadContext)0) { dataObjectChildList.SetCompleted(true); } } } base.SetValue((object)dataObject); dataObjectChildList?.AttachChild(this.Object, true); }
public async Task Load(IFileSystem fileSystem, UPath filePath, LoadContext loadContext) { Stream dataStream; Stream indexStream; switch (filePath.GetName()) { case "mcb1.bln": dataStream = await fileSystem.OpenFileAsync(filePath); indexStream = await fileSystem.OpenFileAsync(filePath.GetDirectory() / "mcb0.bln"); break; default: indexStream = await fileSystem.OpenFileAsync(filePath); dataStream = await fileSystem.OpenFileAsync(filePath.GetDirectory() / "mcb1.bln"); break; } if (dataStream == null || indexStream == null) { throw new InvalidOperationException("This is no Bln archive."); } Files = _bln.Load(indexStream, dataStream); }
public void LoadAsync(LoadContext context) { m_context = context; if (NetworkInterface.GetIsNetworkAvailable()) { if (m_context != null && m_context.Url != "") { Uri serviceUri = new Uri(m_context.Url); m_downloader.Headers[HttpRequestHeader.Referer] = "http://lab3d.ru"; m_downloader.OpenReadAsync(serviceUri); } else { ContentLoadAsyncEventArgs args = new ContentLoadAsyncEventArgs(); args.m_error = new Exception("Url is invalid!"); if (this.LoadCompleted != null) { this.LoadCompleted(this, args); } } } else { ContentLoadAsyncEventArgs args = new ContentLoadAsyncEventArgs(); args.m_error = new Exception("No network available"); if (this.LoadCompleted != null) { this.LoadCompleted(this, args); } } }
public async Task Load(IFileSystem fileSystem, UPath filePath, LoadContext loadContext) { var fileStream = await fileSystem.OpenFileAsync(filePath); // Specially handle format 0x2B, which is KTX fileStream.Position = 0x0A; _format = fileStream.ReadByte(); fileStream.Position = 0; switch (_format) { // Load KTX by plugin case 0x2B: var imageInfo = _ktx.Load(fileStream, _fileManager); EncodingDefinition = _ktx.EncodingDefinition; Images = new List <IKanvasImage> { new KanvasImage(EncodingDefinition, imageInfo) }; break; // Otherwise load normal IMGx default: var loadedImg = _img.Load(fileStream); EncodingDefinition = ImgxSupport.GetEncodingDefinition(_img.Magic, _img.Format, _img.BitDepth, loadContext.DialogManager); Images = new List <IKanvasImage> { new KanvasImage(EncodingDefinition, loadedImg) }; break; } }
/// <summary> /// Get B3G_USER /// </summary> /// <remarks></remarks> public UserDetail GetUser(double userid) { using (var context = new LoadContext()) { var user = context.B3G_USERS .Where(b => b.USER_ID == userid) .FirstOrDefault(); if (user == null) { return(null); } var userd = context.B3G_USER_DESC .Where(t => t.USER_ID == user.USER_ID && t.LANG_CODE == "TH") .FirstOrDefault(); UserDetail userdetail = new UserDetail(); userdetail.userid = user.USER_ID; userdetail.username = user.USER_NAME; if (userd != null) { userdetail.firstname = userd.FIRST_NAME; userdetail.lastname = userd.LAST_NAME; } return(userdetail); } }
public override void LoadContent(LoadContext context) { foreach (var sheet in Sheets.Values) { sheet.LoadContent(context); } }
public DB.ElementId[] ToRevit(Elements.Element hyparElement, LoadContext context) { if (hyparElement is ElementInstance instance && instance.BaseDefinition is ContentElement content) { if (content.TryGetLoadedRevitFamily(context, out var familySymbol)) { var insertionPoint = instance.Transform.Origin.ToXYZ(true); var closestLevel = GetLevelClosestToZ(insertionPoint.Z, context.Document, out double offsetFromLevel); var placedContent = context.Document.Create.NewFamilyInstance(insertionPoint, familySymbol, closestLevel, DB.Structure.StructuralType.NonStructural); placedContent.LookupParameter("Elevation from Level")?.Set(offsetFromLevel); try { SetRotationOfInstance(context.Document, instance, content, insertionPoint, placedContent); } catch (Exception e) { context.Logger.Error("Unable to set rotation of instance. Some kinds of elements do not support 3d rotation."); context.Logger.Error(e.Message); context.Logger.Error(e.StackTrace); } placedContent.SetInstanceParametersFromContent(content, context); return(new DB.ElementId[] { placedContent.Id }); } else { context.Logger.Error($"Unable to find family {content.Name}, so its instances were not placed."); return(new DB.ElementId[] { }); } }
private async Task <SaveResult> ReloadInternalAsync(IFileState fileState, IFileSystem destinationFileSystem, UPath savePath, SaveInfo saveInfo) { // 1. Reload current state var temporaryStreamProvider = fileState.StreamManager.CreateTemporaryStreamProvider(); var internalDialogManager = new InternalDialogManager(saveInfo.DialogManager, fileState.DialogOptions); var loadContext = new LoadContext(temporaryStreamProvider, saveInfo.Progress, internalDialogManager); var reloadResult = await TryLoadStateAsync(fileState.PluginState, destinationFileSystem, savePath.ToAbsolute(), loadContext); if (!reloadResult.IsSuccessful) { return(new SaveResult(reloadResult.Exception)); } // 2. Set new file input, if state was loaded from a physical medium if (!fileState.HasParent) { fileState.SetNewFileInput(destinationFileSystem, savePath); } // 3. Reload all child states foreach (var archiveChild in fileState.ArchiveChildren) { var destination = archiveChild.FileSystem.Clone(archiveChild.StreamManager); var reloadChildResult = await ReloadInternalAsync(archiveChild, destination, archiveChild.FilePath, saveInfo); if (!reloadChildResult.IsSuccessful) { return(reloadChildResult); } } return(SaveResult.SuccessfulResult); }
public void TestRefreshWithValidCache() { IUpdatable val = null; LoadContext lc = new LoadContext(ShortCacheObject.DefaultIdentifier); DataManager.Current.Clear <ShortCacheObject>(lc); // write the cache entry // string uniqueName = CacheEntry.BuildUniqueName(typeof(ShortCacheObject), lc); var cii = new CacheItemInfo(uniqueName, DateTime.Now, DateTime.Now.AddMinutes(1)); var t = DateTime.Now.ToString(); DataManager.StoreProvider.Write(cii, ShortCacheObject.SCOLoadRequest.WriteToStream(t, -1).GetBuffer()); string oldDefault = ShortCacheObject.DefaultStringValue; ShortCacheObject.DefaultStringValue = DateTime.Now.Ticks.ToString(); val = DataManager.Current.Refresh <ShortCacheObject>(lc, (v) => { // we've got a value Assert.AreEqual(ShortCacheObject.DefaultStringValue, v.StringProp); ShortCacheObject.DefaultStringValue = oldDefault; TestComplete(); }, (ex) => { Assert.Fail(ex.Message); TestComplete(); }); }
/// <summary> /// Saves this forcefield to an XML node. /// </summary> /// <param name="context">Load context.</param> /// <param name="element">Node to save the forcefield to.</param> /// <returns></returns> public XmlElement Save(LoadContext context, XmlElement element) { //TODO save any necessary information. Helper.AppendAttributeAndValue(element, "PythonHome", pythonHome); Helper.AppendAttributeAndValue(element, "ModelPath", modelPath); return(element); }
void OnMouseDown() { if (Input.GetKey(KeyCode.LeftShift)) { var loadContext = LoadContext.FromUnbufferedFile(FileName); if (loadContext.Exists(Category)) { PointsComponent.Points = loadContext.Load <int>(Category); } else { PointsComponent.Points = 0; } } else { var saveContext = SaveContext.ToUnbufferedFile(FileName); saveContext.Save(PointsComponent.Points, Category); /* * This is not needed when using unbuffered files: * * saveContext.Flush(); */ } }
public static LoadRequest GetLoadRequest(object dataLoader, LoadContext loadContext, Type objectType) { // look for the GetLoadRequestMethod. // Type dataLoaderType = dataLoader.GetType(); MethodInfo mi; if (!_getLoadRequestCache.TryGetValue(dataLoaderType, out mi)) { mi = FindMethodWorker(dataLoaderType, "GetLoadRequest", typeof(DataLoaderProxy), typeof(Type)); _getLoadRequestCache[dataLoaderType] = mi; } try { return (LoadRequest)mi.Invoke(dataLoader, new object[] { loadContext, objectType }); } catch (TargetInvocationException t) { throw t.InnerException; } catch (Exception ex) { string excp = ex.ToString(); throw ex; } }
/// <summary> /// Read DFA state information. /// </summary> /// <param name="context"></param> private void ReadDfaState(LoadContext context) { DfaState dfaState = GetDfaState(context.ReadIntegerEntry()); Symbol acceptSymbol = null; bool acceptState = context.ReadBoolEntry(); if (acceptState) { acceptSymbol = symbolTable[context.ReadIntegerEntry()]; } else { context.ReadIntegerEntry(); // Skip the entry. } context.ReadEmptyEntry(); // Read DFA edges DfaEdge[] edges = new DfaEdge[context.EntryCount / 3]; for (int i = 0; i < edges.Length; i++) { edges[i] = new DfaEdge(context.ReadIntegerEntry(), context.ReadIntegerEntry()); context.ReadEmptyEntry(); } // Create DFA state and store it in DFA state table dfaState.Initialize(acceptSymbol, edges); }
/// <inheritdoc/> public override void OnUpgrade(ConfigNode node, LoadContext loadContext, ConfigNode parentNode) { var partName = PartNodePatcher.GetPartNameFromUpgradeNode(node, loadContext); DebugEx.Warning("Patch saved game state for part: {0}", partName); var badPatches = new List <ConfigNodePatch>(); var applyPatches = _partPatches[partName]; foreach (var patch in applyPatches) { try { PartNodePatcher.PatchNode(node, patch, loadContext); } catch (Exception ex) { DebugEx.Error("Cannot apply patch '" + patch + "': " + ex); node.SetValue("$$failed", true, createIfNotFound: true); } // Ensure that the patch worked and won't trigger another patching round. if (PartNodePatcher.TestPatch(node, patch, loadContext, quietMode: true)) { badPatches.Add(patch); node.SetValue("$$failed", true, createIfNotFound: true); } } foreach (var badPatch in badPatches) { applyPatches.Remove(badPatch); DebugEx.Error("Patch hasn't fixed the part, disabling it: {0}", badPatch); } }
public async Task Load(IFileSystem fileSystem, UPath filePath, LoadContext loadContext) { Stream imgStream; Stream ddtStream; if (filePath.GetExtensionWithDot() == ".IMG") { var ddtPath = filePath.GetDirectory() / (filePath.GetNameWithoutExtension() + ".DDT"); if (!fileSystem.FileExists(ddtPath)) { throw new FileNotFoundException($"{ddtPath.GetName()} not found."); } imgStream = await fileSystem.OpenFileAsync(filePath); ddtStream = await fileSystem.OpenFileAsync(ddtPath); } else { var imgPath = filePath.GetDirectory() / (filePath.GetNameWithoutExtension() + ".IMG"); if (!fileSystem.FileExists(imgPath)) { throw new FileNotFoundException($"{imgPath.GetName()} not found."); } imgStream = await fileSystem.OpenFileAsync(imgPath); ddtStream = await fileSystem.OpenFileAsync(filePath); } Files = _ddtImg.Load(ddtStream, imgStream); }
/// <inheritdoc/> public override TestResult OnTest(ConfigNode node, LoadContext loadContext, ref string nodeName) { if (node.GetValue("$$failed") != null) { return(TestResult.Failed); } var partName = PartNodePatcher.GetPartNameFromUpgradeNode(node, loadContext); if (partName == null) { return(TestResult.Pass); // Part was dropped during the upgrade. } List <ConfigNodePatch> patches; var hasMatches = false; if (_partPatches.TryGetValue(partName, out patches)) { for (var i = patches.Count - 1; i >= 0; --i) { var patch = patches[i]; try { hasMatches |= PartNodePatcher.TestPatch(node, patch, loadContext); } catch (Exception ex) { DebugEx.Error("Cannot handle test condition: {0}", ex); DebugEx.Warning("Disabling patch: {0}", patch); patches.RemoveAt(i); } } } return(hasMatches ? TestResult.Upgradeable : TestResult.Pass); }
/// <summary> /// Ctor. /// </summary> /// <param name="objectType">The type of the object being loaded</param> /// <param name="loadContext">The LoadContext for the load.</param> /// <param name="innerException">The original exception which caused the failure.</param> public LoadRequestFailedException(Type objectType, LoadContext loadContext, Exception innerException) : base("An error occurred loading an object of type " + objectType.Name + ", see InnerException for details.", innerException) { if (objectType == null) throw new ArgumentNullException(); if (loadContext == null) throw new ArgumentNullException(); ObjectType = objectType; LoadContext = loadContext; }
public override AssemblyAndLocation LoadFromPath(string path) { // Create a new context that knows the directory where the assembly was loaded from // and uses it to resolve dependencies of the assembly. We could create one context per directory, // but there is no need to reuse contexts. var assembly = new LoadContext(Loader, Path.GetDirectoryName(path)).LoadFromAssemblyPath(path); return new AssemblyAndLocation(assembly, path, fromGac: false); }
public Assembly LoadAssembly(LoadContext loadContext) { var result = Load(loadContext); if (result == null) { return null; } if (result.Errors != null) { throw new Exception(String.Join(Environment.NewLine, result.Errors)); } return result.Assembly; }
public static object Deserialize(object dataLoader, LoadContext loadContext, Type objectType, Stream stream) { Type dataLoaderType = dataLoader.GetType(); MethodInfo mi; if (!_deserializeCache.TryGetValue(dataLoaderType, out mi)) { mi = FindMethodWorker(dataLoaderType, "Deserialize", typeof(DataLoaderProxy), typeof(Type), typeof(Stream)); _deserializeCache[dataLoaderType] = mi; } try { return mi.Invoke(dataLoader, new object[] { loadContext, objectType, stream }); } catch (TargetInvocationException t) { throw t.InnerException; } }
/// <summary> /// Set up all the handlers for this CacheEntry /// </summary> /// <param name="objectType"></param> /// <param name="context"></param> /// <param name="proxyCallback">callback that should be invoked when update is finished</param> public CacheEntry(LoadContext context, Type objectType, Action<CacheEntry> proxyCallback) { _proxyComplitionCallback = proxyCallback; LoadContext = context; ObjectType = objectType; _stats = new EntryStats(this); // set up our value loaders. // _cacheLoader = new CacheValueLoader(this); _cacheLoader.Loading += ValueLoader_Loading; _cacheLoader.ValueAvailable += Cached_ValueAvailable; _cacheLoader.LoadFailed += CacheLoader_Failed; _liveLoader = new LiveValueLoader(this); _liveLoader.Loading += ValueLoader_Loading; _liveLoader.ValueAvailable += Live_ValueAvailable; _liveLoader.LoadFailed += LiveValueLoader_Failed; NextCompletedAction = new UpdateCompletionHandler(this); }
public AssemblyLoadResult Load(LoadContext loadContext) { var sw = new Stopwatch(); sw.Start(); Trace.TraceInformation("Loading {0} for '{1}'.", loadContext.AssemblyName, loadContext.TargetFramework); var key = loadContext.AssemblyName; Assembly asm; if (!_cache.TryGetValue(key, out asm)) { var loadResult = LoadImpl(loadContext, sw); if (loadResult == null) { return null; } else { asm = loadResult.Assembly; if (asm != null) { _cache.TryAdd(key, asm); } return loadResult; } } else { sw.Stop(); Trace.TraceInformation("[Cache]: Loaded {0} in {1}ms", loadContext.AssemblyName, sw.ElapsedMilliseconds); } return new AssemblyLoadResult(asm); }
/// <summary> /// Reads grammar header information. /// </summary> /// <param name="context"></param> private void ReadHeader(LoadContext context) { properties.Add(NameProperty, context.ReadStringEntry()); properties.Add(VersionProperty, context.ReadStringEntry()); properties.Add(AuthorProperty, context.ReadStringEntry()); properties.Add(AboutProperty, context.ReadStringEntry()); caseSensitive = context.ReadBoolEntry(); context.StartSymbolIndex = context.ReadIntegerEntry(); }
private void ReadGroup(LoadContext context) { int index = context.ReadIntegerEntry(); string name = context.ReadStringEntry(); int containerIndex = context.ReadIntegerEntry(); int startIndex = context.ReadIntegerEntry(); int endIndex = context.ReadIntegerEntry(); GroupAdvanceMode advanceMode = (GroupAdvanceMode)context.ReadIntegerEntry(); GroupEndingMode endingMode = (GroupEndingMode)context.ReadIntegerEntry(); context.ReadEmptyEntry(); int nestingCount = context.ReadIntegerEntry(); Debug.Assert(nestingCount == context.EntryCount); int[] nesting = new int[nestingCount]; for (int i = 0; i < nesting.Length; i++) { nesting[i] = context.ReadIntegerEntry(); } groupTable[index] = new Group(this, index, name, advanceMode, endingMode); context.GroupInfos.Add(index, new GroupInfo(containerIndex, startIndex, endIndex, nesting)); }
/// <summary> /// Read DFA state information. /// </summary> /// <param name="context"></param> private void ReadDfaState(LoadContext context) { DfaState dfaState = GetDfaState(context.ReadIntegerEntry()); Symbol acceptSymbol = null; bool acceptState = context.ReadBoolEntry(); if (acceptState) { acceptSymbol = symbolTable[context.ReadIntegerEntry()]; } else { context.ReadIntegerEntry(); // Skip the entry. } context.ReadEmptyEntry(); // Read DFA edges DfaEdge[] edges = new DfaEdge[context.EntryCount/3]; for (int i = 0; i < edges.Length; i++) { edges[i] = new DfaEdge(context.ReadIntegerEntry(), context.ReadIntegerEntry()); context.ReadEmptyEntry(); } // Create DFA state and store it in DFA state table dfaState.Initialize(acceptSymbol, edges); }
private AssemblyLoadResult LoadImpl(LoadContext loadContext, Stopwatch sw) { foreach (var loader in _loaders) { var loadResult = loader.Load(loadContext); if (loadResult != null) { sw.Stop(); Trace.TraceInformation("[{0}]: Finished loading {1} in {2}ms", loader.GetType().Name, loadContext.AssemblyName, sw.ElapsedMilliseconds); return loadResult; } } return null; }
/// <summary> /// Read char set information. /// </summary> /// <param name="context"></param> private void ReadRangeCharset(LoadContext context) { int index = context.ReadIntegerEntry(); context.ReadIntegerEntry(); // unicode plane int rangeCount = context.ReadIntegerEntry(); context.ReadEmptyEntry(); // reserved Debug.Assert(rangeCount == context.EntryCount/2); StringBuilder result = new StringBuilder(); while (context.EntryCount > 0) { char ch = (char)context.ReadIntegerEntry(); char end = (char)context.ReadIntegerEntry(); while (ch <= end) { result.Append(ch++); } } charSetTable[index] = new DfaCharset(this, index, result.ToString()); }
/// <summary> /// Read char set information. /// </summary> /// <param name="context"></param> private void ReadPackedCharset(LoadContext context) { int index = context.ReadIntegerEntry(); char sequenceStart = (char)context.ReadIntegerEntry(); char sequenceEnd = (char)context.ReadIntegerEntry(); StringBuilder result = new StringBuilder(context.ReadStringEntry()); result.Capacity = result.Length+(sequenceEnd-sequenceStart)+1; for (char c = sequenceStart; c <= sequenceEnd; c++) { result.Append(c); } charSetTable[index] = new DfaCharset(this, index, result.ToString()); }
/// <summary> /// Read symbol information. /// </summary> /// <param name="context"></param> private void ReadSymbol(LoadContext context) { int index = context.ReadIntegerEntry(); string name = context.ReadStringEntry(); SymbolKind symbolKind = (SymbolKind)context.ReadIntegerEntry(); Symbol symbol = new Symbol(this, index, name, symbolKind); switch (symbolKind) { case SymbolKind.Error: errorSymbol = symbol; break; case SymbolKind.End: endSymbol = symbol; break; } symbolTable[index] = symbol; }
public AssemblyLoadResult Load(LoadContext loadContext) { string name = loadContext.AssemblyName; string targetDir = Path.Combine(_solutionDir, name); // Bail if there's a project settings file if (Project.HasProjectFile(targetDir)) { return null; } string projectFile = Path.Combine(targetDir, name + ".csproj"); if (!System.IO.File.Exists(projectFile)) { // There's a solution so check for a project one deeper if (System.IO.File.Exists(Path.Combine(targetDir, name + ".sln"))) { // Is there a project file here? projectFile = Path.Combine(targetDir, name, name + ".csproj"); if (!System.IO.File.Exists(projectFile)) { return null; } } else { return null; } } WatchProject(projectFile); string projectDir = Path.GetDirectoryName(projectFile); foreach (var exePath in _msBuildPaths) { if (!System.IO.File.Exists(exePath)) { continue; } var executable = new Executable(exePath, projectDir); string outputFile = null; var process = executable.Execute(line => { // Look for {project} -> {outputPath} int index = line.IndexOf('-'); if (index != -1 && index + 1 < line.Length && line[index + 1] == '>') { string projectName = line.Substring(0, index).Trim(); if (projectName.Equals(name, StringComparison.OrdinalIgnoreCase)) { outputFile = line.Substring(index + 2).Trim(); } } return true; }, _ => true, Encoding.UTF8, projectFile + " /m"); process.WaitForExit(); if (process.ExitCode != 0) { // REVIEW: Should this throw? return null; } return new AssemblyLoadResult(Assembly.LoadFile(outputFile)); } return null; }
void OnGUI() { if (GUI.Button(new Rect(20, 100, 100, 30), "Save")) { save.savedChatkaRotation.Clear (); save.savedTreesRotation.Clear (); save.savedTreesScale.Clear (); if( Application.platform == RuntimePlatform.OSXWebPlayer || Application.platform == RuntimePlatform.WindowsWebPlayer ) { context = SaveContext.ToPlayerPrefs (saveName); } else { context = SaveContext.ToFile (path+saveName); } // m_voxels.ForEach (checkChunk); save.pos.ForEach (savePos); save.treesPos.ForEach (saveTreePos); save.treesScale.ForEach (saveTreeScale); save.treesRotation.ForEach (saveTreeRotation); save.chatkaPos.ForEach (saveChatkaPos); save.chatkaRotation.ForEach (saveChatkaRotation); //PlayerPrefsX.SetVector3Array("TreesScale", savedTreesScale.ToArray()); //PlayerPrefsX.SetVector3Array("TreesRotation", savedTreesRotation.ToArray()); //PlayerPrefsX.SetVector3Array("Testyy", savedPos.ToArray ()); //PlayerPrefsX.SetVector3Array ("TreesPos", savedTreesPos.ToArray ()); //PlayerPrefsX.SetVector3Array("ChatkaRotation", savedChatkaRotation.ToArray()); //PlayerPrefsX.SetVector3Array ("ChatkaPos", savedChatkaPos.ToArray ()); //PlayerPrefs.SetInt ("SurfaceSeed", m_surfaceSeed); player = GameObject.Find ("PlayerWorld"); save.playerPos = player.transform.localPosition; save.playerVel = player.rigidbody.velocity; save.playerRot = player.transform.localEulerAngles; save.fTimePassed = player.GetComponent<PlayerData>().fTimePassed; //PlayerPrefsX.SetVector3 ("PlayerPos", playerPos); //PlayerPrefsX.SetVector3 ("PlayerVel", playerVel); //PlayerPrefsX.SetVector3 ("PlayerRot", playerRot); //stringTest = builder.ToString (); //indexJson = 0; //save.savedPos = savedPos; context.Save (save.savedTreesScale, "savedTreesScale"); context.Save (save.savedTreesRotation, "savedTreesRotation"); context.Save (save.savedPos, "savedPos"); context.Save (save.savedTreesPos, "savedTreesPos"); context.Save (save.savedChatkaRotation, "savedChatkaRotation"); context.Save (save.savedChatkaPos, "savedChatkaPos"); context.Save (save.playerPos, "playerPos"); context.Save (save.playerVel, "playerVel"); context.Save (save.playerRot, "playerRot"); context.Save (save.m_surfaceSeed, "m_surfaceSeed"); context.Save (save.fTimePassed, "fTimePassed"); context.Flush(); //PlayerPrefsArray.SetVector3Array("Test", testerer1); } if (GUI.Button(new Rect(20, 140, 100, 30), "Load")) { save.savedTreesPos.Clear (); save.savedPos.Clear (); //savedTreesPos = PlayerPrefsX.GetVector3Array("TreesPos").ToList (); //savedPos = PlayerPrefsX.GetVector3Array("Testyy").ToList (); save.savedTreesRotation.Clear (); save.savedTreesScale.Clear (); //savedTreesRotation = PlayerPrefsX.GetVector3Array ("TreesRotation").ToList (); //savedTreesScale = PlayerPrefsX.GetVector3Array ("TreesScale").ToList(); save.savedChatkaRotation.Clear (); save.savedChatkaPos.Clear (); //LoadContext loadCon = LoadContext.FromFile("Test.dat"); if( Application.platform == RuntimePlatform.OSXWebPlayer || Application.platform == RuntimePlatform.WindowsWebPlayer ) { loadCon = LoadContext.FromPlayerPrefs (saveName); } else { loadCon = LoadContext.FromFile (path+saveName); } save.testSerialization = loadCon.Load<List<Vector3>>("savedPos"); save.savedTreesScale = loadCon.Load<List<Vector3>>("savedTreesScale"); save.savedTreesRotation = loadCon.Load<List<Vector3>>("savedTreesRotation"); save.savedPos = loadCon.Load<List<Vector3>>("savedPos"); save.savedTreesPos = loadCon.Load<List<Vector3>>("savedTreesPos"); save.savedChatkaRotation = loadCon.Load<List<Vector3>>("savedChatkaRotation"); save.savedChatkaPos = loadCon.Load<List<Vector3>>("savedChatkaPos"); save.playerPos = loadCon.Load<Vector3>("playerPos"); save.playerVel = loadCon.Load<Vector3>("playerVel"); save.playerRot = loadCon.Load<Vector3>("playerRot"); save.m_surfaceSeed = loadCon.Load<int>("m_surfaceSeed"); // index = 0; //save.m_surfaceSeed = PlayerPrefs.GetInt ("SurfaceSeed"); StartCoroutine(deleteChunk()); //savedChatkaRotation = PlayerPrefsX.GetVector3Array ("ChatkaRotation").ToList (); //savedChatkaPos = PlayerPrefsX.GetVector3Array ("ChatkaPos").ToList(); //savedPos.Add (testerer); save.savedPos.ForEach(loadVoxels); //loadTrees (); player = GameObject.Find ("PlayerWorld"); player.transform.localPosition = save.playerPos; player.rigidbody.velocity = save.playerVel; player.transform.localEulerAngles = save.playerRot; player.GetComponent<PlayerData>().fTimePassed = save.fTimePassed; GameObject.Find ("TerrainGenerator").GetComponent<GenerateTerrain>().m_surfaceSeed = save.m_surfaceSeed; //save.savedTreesPos.ForEach (loadTrees2); StartCoroutine (loadTrees2 ()); save.savedChatkaPos.ForEach (loadChatki); index = 0; cindex = 0; } if (GUI.Button(new Rect(20, 180, 100, 30), "Restart Scene")) { Application.LoadLevel(Application.loadedLevelName); } }
// public StackTrace LastLoadStackTrace { get; set; } #endif #region Methods public static string BuildUniqueName(Type objectType, LoadContext context) { return string.Format("{0}_{1}", objectType.Name, context.UniqueKey); }
/// <summary> /// Updates the live value from an inentional DataManager.Save operation. /// </summary> /// <param name="instance"></param> /// <param name="loadContext"></param> internal void UpdateValue(object instance, LoadContext loadContext) { UpdateExpiration(DateTime.Now, instance as ICachedItem); LoadContext = loadContext; if (_valueReference != null && _valueReference.IsAlive) { UpdateFrom(null, instance); } else { ValueInternal = instance; } }
/// <summary> /// Read initial DFA and LR states. /// </summary> /// <param name="context"></param> private void ReadInitialStates(LoadContext context) { context.DfaInitialStateIndex = context.ReadIntegerEntry(); context.LrInitialState = context.ReadIntegerEntry(); }
/// <summary> /// Read LR state information. /// </summary> /// <param name="context"></param> private void ReadLRState(LoadContext context) { int index = context.ReadIntegerEntry(); context.ReadEmptyEntry(); LalrAction[] table = new LalrAction[context.EntryCount/4]; for (int i = 0; i < table.Length; i++) { Symbol symbol = symbolTable[context.ReadIntegerEntry()]; LalrActionType actionType = (LalrActionType)context.ReadIntegerEntry(); int targetIndex = context.ReadIntegerEntry(); context.ReadEmptyEntry(); LalrAction action; switch (actionType) { case LalrActionType.Accept: action = new LalrActionAccept(i, symbol); break; case LalrActionType.Goto: action = new LalrActionGoto(i, symbol, GetLalrState(targetIndex)); break; case LalrActionType.Reduce: action = new LalrActionReduce(i, symbol, GetRule(targetIndex)); break; case LalrActionType.Shift: action = new LalrActionShift(i, symbol, GetLalrState(targetIndex)); break; default: throw new InvalidOperationException("Invalid table action data"); } table[i] = action; } // Create the transition vector LalrAction[] transitionVector = new LalrAction[symbolTable.Length]; for (int i = 0; i < transitionVector.Length; i++) { transitionVector[i] = null; } for (int i = 0; i < table.Length; i++) { transitionVector[table[i].Symbol.Index] = table[i]; } GetLalrState(index).Initialize(table, transitionVector); }
/// <summary> /// Reads table record counts and initializes tables. /// </summary> /// <param name="context"></param> private void ReadTableCounts(LoadContext context, bool readGroups) { // Initialize tables symbolTable = new Symbol[context.ReadIntegerEntry()]; charSetTable = new DfaCharset[context.ReadIntegerEntry()]; ruleTable = new Rule[context.ReadIntegerEntry()]; for (int i = 0; i < ruleTable.Length; i++) { ruleTable[i] = new Rule(this, i); } dfaStateTable = new DfaState[context.ReadIntegerEntry()]; for (int i = 0; i < dfaStateTable.Length; i++) { dfaStateTable[i] = new DfaState(this, i); } lalrStateTable = new LalrState[context.ReadIntegerEntry()]; for (int i = 0; i < lalrStateTable.Length; i++) { lalrStateTable[i] = new LalrState(this, i); } groupTable = new Group[readGroups ? context.ReadIntegerEntry() : 0]; }
private void ReadProperty(LoadContext context) { int index = context.ReadIntegerEntry(); string name = context.ReadStringEntry(); // override the name for the well-known constants, so that we have the right name for sure switch (index) { case 0: name = NameProperty; break; case 1: name = VersionProperty; break; case 2: name = AuthorProperty; break; case 3: name = AboutProperty; break; case 4: name = CharacterSetProperty; break; case 5: name = CharacterMappingProperty; break; case 6: name = GeneratedByProperty; break; case 7: name = GeneratedDateProperty; break; } properties.Add(name, context.ReadStringEntry()); }
private void FixupGroups(LoadContext context) { Debug.Assert(groupByStartSymbol.Count == 0); if (fileVersion == CgtVersion.V1_0) { List<Group> commentGroups = new List<Group>(1); foreach (Symbol blockStartSymbol in symbolTable) { if (blockStartSymbol.Kind == SymbolKind.BlockStart) { foreach (Symbol blockEndSymbol in symbolTable) { if (blockEndSymbol.Kind == SymbolKind.BlockEnd) { Group group = new Group(this, commentGroups.Count, "Block Comment", GroupAdvanceMode.Character, GroupEndingMode.Closed); commentGroups.Add(group); group.Initialize(blockStartSymbol, blockStartSymbol, blockEndSymbol, new Group[] { group }); groupByStartSymbol.Add(blockStartSymbol, group); // this will fail if there was more than one end symbol of the type "CommentEnd" in the grammar } } } } groupTable = commentGroups.ToArray(); } else { for (int i = 0; i < groupTable.Length; i++) { GroupInfo info = context.GroupInfos[i]; Group[] nesting = new Group[info.Nesting.Length]; for (int n = 0; n < nesting.Length; n++) { nesting[n] = groupTable[info.Nesting[n]]; } Group group = groupTable[i]; group.Initialize(GetSymbol(info.ContainerIndex), GetSymbol(info.StartIndex), GetSymbol(info.EndIndex), nesting); groupByStartSymbol.Add(group.StartSymbol, group); } } }
/// <summary> /// Read rule information. /// </summary> /// <param name="context"></param> private void ReadRule(LoadContext context) { int index = context.ReadIntegerEntry(); Symbol nonterminal = symbolTable[context.ReadIntegerEntry()]; context.ReadEmptyEntry(); Symbol[] symbols = new Symbol[context.EntryCount]; for (int i = 0; i < symbols.Length; i++) { symbols[i] = symbolTable[context.ReadIntegerEntry()]; } GetRule(index).Initialize(nonterminal, symbols); }
/// <summary> /// Loads grammar from the binary reader. /// </summary> private void Load(LoadContext context) { string headerString = context.ReadHeaderString(); // Trace.WriteLine(headerString, "Reading header"); Match headerMatch = FileHeader.Match(headerString); if (!headerMatch.Success) { throw new FileLoadException("The File Header is invalid or unsupported: "+headerString); } switch (headerMatch.Groups["version"].Value) { case "1.0": fileVersion = CgtVersion.V1_0; break; case "5.0": fileVersion = CgtVersion.V5_0; break; default: throw new FileLoadException(string.Format("The file format version {0} is not unsupported", headerMatch.Groups["version"].Value)); } while (context.HasMoreData()) { CgtRecordType recordType = context.ReadNextRecord(); /// Trace.WriteLine(recordType, "Reading record"); switch (recordType) { case CgtRecordType.Parameters: ReadHeader(context); break; case CgtRecordType.Property: ReadProperty(context); break; case CgtRecordType.Groups: ReadGroup(context); break; case CgtRecordType.TableCountsEnhanced: ReadTableCounts(context, true); break; case CgtRecordType.TableCounts: ReadTableCounts(context, false); break; case CgtRecordType.Initial: ReadInitialStates(context); break; case CgtRecordType.Symbols: ReadSymbol(context); break; case CgtRecordType.Charsets: ReadCharset(context); break; case CgtRecordType.PackedCharsets: if (fileVersion == CgtVersion.V1_0) { ReadPackedCharset(context); } else { ReadRangeCharset(context); } break; case CgtRecordType.Rules: ReadRule(context); break; case CgtRecordType.DfaStates: ReadDfaState(context); break; case CgtRecordType.LRStates: ReadLRState(context); break; default: throw new FileLoadException("Invalid record type"); } } dfaInitialState = dfaStateTable[context.DfaInitialStateIndex]; startSymbol = symbolTable[context.StartSymbolIndex]; lalrInitialState = lalrStateTable[context.LrInitialState]; FixupGroups(context); }
/// <summary> /// Read char set information. /// </summary> /// <param name="context"></param> private void ReadCharset(LoadContext context) { int index = context.ReadIntegerEntry(); charSetTable[index] = new DfaCharset(this, index, context.ReadStringEntry()); }
public CacheEntry(LoadContext context, Type objectType, Type loaderObjectType, Action<CacheEntry> proxyCallback) : this(context, objectType, proxyCallback) { LoaderObjectType = loaderObjectType; }