public ResourceEntry WriteScriptEntry(ResourceEntry entry, XPathNodeIterator nodes, string sdsFolder, XmlNode descNode) { //get xml data. nodes.Current.MoveToNext(); string path = nodes.Current.Value; nodes.Current.MoveToNext(); int numScripts = Convert.ToInt32(nodes.Current.Value); //main stuff ScriptResource resource = new ScriptResource(); resource.Path = path; for (int i = 0; i != numScripts; i++) { ScriptData data = new ScriptData(); nodes.Current.MoveToNext(); data.Name = nodes.Current.Value; data.Data = File.ReadAllBytes(sdsFolder + data.Name); resource.Scripts.Add(data); } //finish nodes.Current.MoveToNext(); ushort version = Convert.ToUInt16(nodes.Current.Value); MemoryStream stream = new MemoryStream(); resource.Serialize(version, stream, Endian.Little); entry.Version = version; entry.Data = stream.GetBuffer(); descNode.InnerText = path; return(entry); }
public void ReadScriptEntry(ResourceEntry entry, XmlWriter resourceXML, string scriptDir) { ScriptResource resource = new ScriptResource(); resource.Deserialize(entry.Version, new MemoryStream(entry.Data), _Endian); resourceXML.WriteElementString("File", resource.Path); resourceXML.WriteElementString("ScriptNum", resource.Scripts.Count.ToString()); for (int x = 0; x != resource.Scripts.Count; x++) { string scrdir = scriptDir; string[] dirs = resource.Scripts[x].Name.Split('/'); for (int z = 0; z != dirs.Length - 1; z++) { scrdir += "/" + dirs[z]; Directory.CreateDirectory(scrdir); } File.WriteAllBytes(scriptDir + "/" + resource.Scripts[x].Name, resource.Scripts[x].Data); if (ToolkitSettings.DecompileLUA) { LuaHelper.ReadFile(new FileInfo(scriptDir + "/" + resource.Scripts[x].Name)); } resourceXML.WriteElementString("Name", resource.Scripts[x].Name); } resourceXML.WriteElementString("Version", entry.Version.ToString()); resourceXML.WriteEndElement(); //finish early. }
public void ReadScriptEntry(ResourceEntry entry, XmlWriter resourceXML, string scriptDir) { ScriptResource resource = new ScriptResource(); resource.Deserialize(entry.Version, new MemoryStream(entry.Data), _Endian); resourceXML.WriteElementString("File", resource.Path); resourceXML.WriteElementString("ScriptNum", resource.Scripts.Count.ToString()); for (int x = 0; x != resource.Scripts.Count; x++) { string scrdir = scriptDir; string[] dirs = resource.Scripts[x].Name.Split('/'); for (int z = 0; z != dirs.Length - 1; z++) { scrdir += "/" + dirs[z]; Directory.CreateDirectory(scrdir); } using (BinaryWriter writer = new BinaryWriter( File.Open(scriptDir + "/" + resource.Scripts[x].Name, FileMode.Create))) { writer.Write(resource.Scripts[x].Data); } resourceXML.WriteElementString("Name", resource.Scripts[x].Name); } resourceXML.WriteElementString("Version", entry.Version.ToString()); resourceXML.WriteEndElement(); //finish early. }
public void UpdateScriptTest_Success() { var scriptResource = new ScriptResource(); var script = new Script { Version = "1" }; _mapper.Setup(m => m.Map <ScriptResource, Script>(scriptResource, script)) .Returns(script); _mapper.Setup(m => m.Map <Script, ScriptResource>(script)) .Returns(scriptResource); _scriptRepository.Setup(sr => sr.GetScriptWithTagsAsync(1)) .Returns(Task.FromResult(script)); _unitOfWork.Setup(uow => uow.CompleteAsync()) .Returns(Task.FromResult(1)); var updateScriptCommand = new UpdateScriptCommand.Handler( _dateTime.Object, _scriptRepository.Object, _unitOfWork.Object); var result = updateScriptCommand.Handle( new UpdateScriptCommand { Id = 1, Name = "name", Tags = new List <TagResource>() }, CancellationToken.None).Result; _scriptRepository.Verify(sr => sr.GetScriptWithTagsAsync(1)); _unitOfWork.Verify(uow => uow.CompleteAsync()); }
public void GetScriptTest_Success() { var script = new Script(); var scriptResource = new ScriptResource(); _scriptRepository.Setup(sr => sr.GetScriptWithTagsAsync(1)) .Returns(Task.FromResult(script)); _mapper.Setup(m => m.Map <Script, ScriptResource>(script)) .Returns(scriptResource); var getScriptQuery = new GetScriptQuery.Handler( _scriptRepository.Object, _translationService.Object, _mapper.Object); var result = getScriptQuery.Handle( new GetScriptQuery { Id = 1, Language = TranslationService.DefaultLanguageCode }, CancellationToken.None).Result; _scriptRepository.Verify(sr => sr.GetScriptWithTagsAsync(1)); _mapper.Verify(m => m.Map <Script, ScriptResource>(script)); _translationService.Verify(ts => ts.SetScriptTranslation(TranslationService.DefaultLanguageCode, scriptResource)); Assert.That(result, Is.Not.Null); Assert.That(result, Is.EqualTo(scriptResource)); }
static private void LoadResources(String from) { StaticResources.Init(); if (Directory.Exists(from)) { System.String[] archs = Directory.GetFiles(from); foreach (System.String arch in archs) { if (Path.GetExtension(arch).Equals(".cs", System.StringComparison.InvariantCultureIgnoreCase)) { ScriptResource script = new ScriptResource(); script.FileName = arch; } else if (Path.GetExtension(arch).Equals(".png", System.StringComparison.InvariantCultureIgnoreCase)) { Texture2D texture = new Texture2D(); texture.FileName = arch; } else if (Path.GetExtension(arch).Equals(".dae", System.StringComparison.InvariantCultureIgnoreCase)) { Mesh mesh = new Mesh(); mesh.FileName = arch; } } } }
private async void ExportOnClick(object sender, RoutedEventArgs e) { ScriptResource scriptResource = Resource as ScriptResource; SaveFileDialog dialog = new SaveFileDialog { InitialFileName = scriptResource.GetAssemblyName(), Filters = new List <FileDialogFilter> { new FileDialogFilter { Name = $"DLL-{App.GetResource<string>("Files")}", Extensions = { "dll" } } } }; string s = await dialog.ShowAsync(WindowsManager.MainWindow); if (!string.IsNullOrEmpty(s)) { byte[] data = new byte[scriptResource.Assembly.BaseStream.Length]; await scriptResource.Assembly.BaseStream.ReadAsync(data, 0, data.Length); using (FileStream fileStream = new FileStream(s, FileMode.Create, FileAccess.Write)) await fileStream.WriteAsync(data, 0, data.Length); WindowsManager.MainWindow.GetDataContext <MainViewModel>().NotificationManager.Show( new Notification(App.GetResource <string>("Successful"), App.GetResource <string>("FileExported"), NotificationType.Success)); } }
public void SetScriptTranslationTest_Success() { var translationRepository = new Mock <ITranslationRepository>(); translationRepository.Setup(sr => sr.GetScriptTranslation(1, Language.Polish)) .Returns(Task.FromResult(new ScriptTranslation() { Name = "new name", Description = null, Notes = "note" })); var translationService = new TranslationService(translationRepository.Object); var scriptResource = new ScriptResource() { Id = 1, Name = "a", Description = "b", Notes = "c" }; Task.FromResult(translationService.SetScriptTranslation("pl", scriptResource)); Assert.That(scriptResource.Name, Is.EqualTo("new name")); Assert.That(scriptResource.Description, Is.EqualTo("b")); Assert.That(scriptResource.Notes, Is.EqualTo("note")); }
public async Task SetScriptTranslation(string languageCode, ScriptResource scriptResource) { if (Languages.ContainsKey(languageCode) && Languages[languageCode] != scriptResource.DefaultLanguage) { var scriptTranslation = await _translationRepository.GetScriptTranslation(scriptResource.Id, Languages[languageCode]); if (scriptTranslation == null) { return; } if (scriptTranslation.Name != null) { scriptResource.Name = scriptTranslation.Name; } if (scriptTranslation.Description != null) { scriptResource.Description = scriptTranslation.Description; } if (scriptTranslation.Notes != null) { scriptResource.Notes = scriptTranslation.Notes; } } return; }
static private bool ProcessCreated(FileSystemEventArgs ev) { if (Path.GetExtension(ev.Name).Equals(".cs", System.StringComparison.InvariantCultureIgnoreCase)) { ScriptResource script = new ScriptResource(); script.FileName = "Resources\\" + ev.Name; } else if (Path.GetExtension(ev.Name).Equals(".png", System.StringComparison.InvariantCultureIgnoreCase)) { Texture2D texture = new Texture2D(); texture.FileName = "Resources\\" + ev.Name; } else if (Path.GetExtension(ev.Name).Equals(".dae", System.StringComparison.InvariantCultureIgnoreCase)) { Mesh mesh = new Mesh(); mesh.FileName = "Resources\\" + ev.Name; } else { return(false); } FormPrincipal.Instance.menuComponentesValido = false; return(true); }
internal ScriptResourceDocumentTab(ScriptEditorPanel panel, ScriptResource resource, ScriptConfiguration config) : base(panel, config) { // Store resource source = resource; // Load the data MemoryStream stream = source.Resource.LoadFile(source.Filename, source.LumpIndex); if (stream != null) { hash = MD5Hash.Get(stream); editor.SetText(stream.ToArray()); editor.Scintilla.ReadOnly = source.IsReadOnly; editor.ClearUndoRedo(); } else { General.ErrorLogger.Add(ErrorType.Warning, "Failed to load " + source.ScriptType + " resource \"" + source.Filename + "\" from \"" + source.Resource.Location.GetDisplayName() + "\"."); } // Set title and tooltip tabtype = ScriptDocumentTabType.RESOURCE; filepathname = source.FilePathName; SetTitle(source.ToString()); this.ToolTipText = filepathname; // Update navigator panel.ShowErrors(UpdateNavigator(), true); }
static public void StartMonitorearRecursos() { if (Directory.Exists("Resources")) { System.String[] archs = Directory.GetFiles("Resources"); foreach (System.String arch in archs) { if (Path.GetExtension(arch).Equals(".cs", System.StringComparison.InvariantCultureIgnoreCase)) { ScriptResource script = new ScriptResource(); script.FileName = arch; } else if (Path.GetExtension(arch).Equals(".png", System.StringComparison.InvariantCultureIgnoreCase)) { Texture2D texture = new Texture2D(); texture.FileName = arch; } else if (Path.GetExtension(arch).Equals(".dae", System.StringComparison.InvariantCultureIgnoreCase)) { Mesh mesh = new Mesh(); mesh.FileName = arch; } } fileSystemWatcher = new FileSystemWatcher(Path.GetFullPath("Resources")); fileSystemWatcher.Changed += new FileSystemEventHandler(fileSystemWatcher_Changed); fileSystemWatcher.Created += new FileSystemEventHandler(fileSystemWatcher_Created); fileSystemWatcher.Deleted += new FileSystemEventHandler(fileSystemWatcher_Deleted); fileSystemWatcher.Renamed += new RenamedEventHandler(fileSystemWatcher_Renamed); fileSystemWatcher.EnableRaisingEvents = true; } }
//mxd protected bool AddTextResource(TextResourceData parsedata) { // Script Editor resources don't have actual path and should always be parsed if(string.IsNullOrEmpty(parsedata.SourceLocation.location)) { if(parsedata.Trackable) throw new NotSupportedException("Trackable TextResource must have a valid path."); return true; } string path = Path.Combine(parsedata.SourceLocation.location, parsedata.Filename + (parsedata.LumpIndex != -1 ? "#" + parsedata.LumpIndex : "")); if(scriptresources.ContainsKey(path) || untrackedtextresources.Contains(path)) return false; //mxd. Create TextResource for this file if(parsedata.Trackable) { textresourcepath = path; ScriptResource res = new ScriptResource(parsedata, this.ScriptType); scriptresources.Add(textresourcepath, res); } // Track the untrackable! else { untrackedtextresources.Add(path); textresourcepath = string.Empty; } return true; }
public void OnSourceFileChanged() { Script = ScriptResource.FromFileInfo(SourceFile, true); _scriptIndex = 0; _scriptStart = Script?.Keyframes?.First().Position ?? float.NaN; _scriptEnd = Script?.Keyframes?.Last().Position ?? float.NaN; _time = 0; }
private void RemoveNotAddedTags(ScriptResource scriptResource, Script script) { var removedTags = script.Tags.Where(t => !scriptResource.Tags.Select(tr => tr.Id).Contains(t.TagId)).ToList(); foreach (var tag in removedTags) { script.Tags.Remove(tag); } }
public S3SAViewer(IResource resource, Action importDll) : this() { Resource = resource; ScriptResource scriptResource = Resource as ScriptResource; AvaloniaEdit.Document.Text = scriptResource.Value; Export.Click += ExportOnClick; Import.Click += (s, e) => importDll?.Invoke(); }
void menuCrearScript_Click(object sender, System.EventArgs e) { if (vistaConArbolActiva != null && vistaConArbolActiva.vistaEscena.SelectedEntity != null) { ToolStripMenuItem menuItem = (ToolStripMenuItem)sender; ScriptResource script = (ScriptResource)menuItem.Tag; script.AssignTo(vistaConArbolActiva.vistaEscena.SelectedEntity); } }
private void AddNewTags(ScriptResource scriptResource, Script script) { var addedTags = scriptResource.Tags.Where(tr => !script.Tags.Any(t => t.TagId == tr.Id)) .Select(tr => new ScriptTag { TagId = tr.Id }).ToList(); foreach (var tag in addedTags) { script.Tags.Add(tag); } }
private void LoadComponent(ComponentXML xmlComponent) { Type tipoComponente; if (xmlComponent.type == typeof(Script).FullName) { FieldValueXML fvScriptName = xmlComponent.FindAttribute("__ScriptName__"); if (fvScriptName != null && fvScriptName.value != null) { ScriptResource scriptRes = (ScriptResource)Resource.FindResource(typeof(ScriptResource), (String)fvScriptName.ValueAs(typeof(String))); if (scriptRes != null) { tipoComponente = scriptRes.ScriptType; } else { tipoComponente = null; } } else { tipoComponente = null; } } else { tipoComponente = Type.GetType(xmlComponent.type); } if (tipoComponente != null) { Component comp = (Component)tipoComponente.GetConstructor(Type.EmptyTypes).Invoke(null); comp.ForceId(xmlComponent.id); handledComponents.Add(comp.Id, comp); AccesorValor[] accesoresValores = comp.GetAccesoresValores(); object val; foreach (AccesorValor accesor in accesoresValores) { if (LoadValueComponent(xmlComponent, accesor, out val)) { accesor.Value = val; } } } }
private IResource CreateResource(eResourceType eType, string name, string assetpath, Object objresource, bool isAssetBundle) { IResource resource = null; switch (eType) { //case E_ResourceType.Actor: case eResourceType.UI: case eResourceType.Prefab: resource = new PrefabResource(objresource, eType, isAssetBundle); break; // case E_ResourceType.UnitySprite: // resource = new SpriteResource(objresource); // break; case eResourceType.Script: resource = new ScriptResource(objresource, isAssetBundle); break; case eResourceType.SpriteAsset: SpritePackerAsset spritePackerAsset = (SpritePackerAsset)objresource; resource = new SpriteAssetResource(spritePackerAsset.AllSprites, isAssetBundle); break; case eResourceType.Scriptable: resource = new ScriptableResource(objresource, isAssetBundle); break; case eResourceType.Texture: resource = new TextureResouce(objresource, isAssetBundle); break; case eResourceType.Sound: resource = new SoundResource(objresource, isAssetBundle); break; } resource.InitLoad(name, assetpath); Dictionary <int, IResource> dicRes = GetDicResource(eType); if (dicRes.ContainsKey(resource.GetHashCode())) { // LogManager.GetInstance().LogDebug("CreateResource name error" + name); } else { dicRes.Add(resource.GetHashCode(), resource); } return(resource); }
public static string GetAssemblyName(this ScriptResource scriptResource) { try { byte[] data = new byte[scriptResource.Assembly.BaseStream.Length]; scriptResource.Assembly.BaseStream.Read(data, 0, data.Length); Assembly assembly = Assembly.Load(data); return(assembly.FullName.Split(',')[0] + ".dll"); } catch { } return("*.dll"); }
/// <summary> /// @see IInitializationPostOperations#AfterPropertiesSet. /// </summary> public void AfterPropertiesSet() { //=> make sure source exists... Assert.State(ScriptResource.Exists(), ScriptResource.GetDescription() + " does not exist."); Assert.IsTrue(_timeout > 0, "timeout value must be greater than zero"); _stoppable = (JobExplorer != null); //=> initialize string builders... _sbOutput.AppendLine(Environment.NewLine + "*** PowerShell Write-Output Stream ***"); _sbVerbose.AppendLine(Environment.NewLine + "*** PowerShell Write-Verbose Stream ***"); _sbError.AppendLine(Environment.NewLine + "*** PowerShell Write-Error Stream ***"); _sbWarning.AppendLine(Environment.NewLine + "*** PowerShell Write-Warning Stream ***"); _sbDebug.AppendLine(Environment.NewLine + "*** PowerShell Write-Debug Stream ***"); }
public bool Load(string filename) { ScriptResource scriptResource = Global.ResourceMgr.CreateScriptResource(filename, ePath.Data); bool result = false; byte[] bytes = XOREncryption.Decrypt(scriptResource.TexObject.bytes, encryptKey); using (Stream stream = new MemoryStream(bytes)) { BinaryDecoder decoder = new BinaryDecoder(stream); result = ReadData(decoder); } Global.ResourceMgr.DestoryResource(scriptResource); return(result); }
public static string ScriptResourceKey(ScriptResource script) { if (String.IsNullOrEmpty(script.Name)) { if (script is FileScriptResource) return (script as FileScriptResource).DebugPath; string body = (script as InlineScriptResource).Body; if (body.Length > 20) return body.Substring(0, 20); return body; } return script.Name; }
public void UpdateScriptTest_NoneScript_Success() { var scriptResource = new ScriptResource(); _scriptRepository.Setup(sr => sr.GetScriptWithTagsAsync(1)) .Returns(Task.FromResult(default(Script))); var updateScriptCommand = new UpdateScriptCommand.Handler( _dateTime.Object, _scriptRepository.Object, _unitOfWork.Object); Assert.ThrowsAsync <NotFoundException>(() => updateScriptCommand.Handle( new UpdateScriptCommand { Id = 1, Name = "name", Tags = new List <TagResource>() }, CancellationToken.None)); }
private string RenderResource(DotvvmConfiguration configuration, ScriptResource jquery) { var context = new TestDotvvmRequestContext() { Configuration = configuration, ResourceManager = new ResourceManager(configuration.Resources), ViewModel = new DotvvmViewModelBase() }; using (var text = new StringWriter()) { var html = new HtmlWriter(text, context); jquery.RenderLink(jquery.Location, html, context, "jquery"); return(text.GetStringBuilder().ToString()); } }
public ResourceEntry WriteScriptEntry(ResourceEntry entry, XPathNodeIterator nodes, string sdsFolder, XmlNode descNode) { // Get data from Xml. nodes.Current.MoveToNext(); string path = nodes.Current.Value; nodes.Current.MoveToNext(); int numScripts = Convert.ToInt32(nodes.Current.Value); // Create the new resource, add path. ScriptResource resource = new ScriptResource(); resource.Path = path; // Iterate through scripts, reading each one and pushing them into the list. for (int i = 0; i < numScripts; i++) { ScriptData data = new ScriptData(); nodes.Current.MoveToNext(); data.Name = nodes.Current.Value; data.Data = File.ReadAllBytes(sdsFolder + data.Name); resource.Scripts.Add(data); } // Finish reading the Xml by getting the version. nodes.Current.MoveToNext(); ushort version = Convert.ToUInt16(nodes.Current.Value); // Create the stream and serialize the resource package into said stream. using (MemoryStream stream = new MemoryStream()) { resource.Serialize(version, stream, Endian.Little); entry.Data = stream.ToArray(); entry.SlotRamRequired = resource.GetRawBytes(); } // Set the entry version and setup the data for the meta info. entry.Version = version; descNode.InnerText = "not available"; return(entry); }
public void ReadScriptEntry(ResourceEntry entry, XmlWriter resourceXML, string scriptDir) { ScriptResource resource = new ScriptResource(); resource.Deserialize(entry.Version, new MemoryStream(entry.Data), _Endian); resourceXML.WriteElementString("File", resource.Path); resourceXML.WriteElementString("ScriptNum", resource.Scripts.Count.ToString()); for (int x = 0; x != resource.Scripts.Count; x++) { // Get the script resource. ScriptData ScriptItem = resource.Scripts[x]; // Get directory and Script name. string ScriptDirectory = Path.GetDirectoryName(ScriptItem.Name); string ScriptName = Path.GetFileName(ScriptItem.Name); // Create the new directory. string NewDirectory = scriptDir + ScriptDirectory; Directory.CreateDirectory(NewDirectory); // Write the script data to the designated file. string ScriptPath = Path.Combine(NewDirectory, ScriptName); File.WriteAllBytes(ScriptPath, ScriptItem.Data); // If user requests, decompile the Lua file. if (ToolkitSettings.DecompileLUA) { FileInfo Info = new FileInfo(ScriptPath); FileLua LuaFile = new FileLua(Info); LuaFile.TryDecompileBytecode(); } resourceXML.WriteElementString("Name", ScriptItem.Name); } resourceXML.WriteElementString("Version", entry.Version.ToString()); resourceXML.WriteEndElement(); // We finish early with scripts, as this has an alternate layout. }
private void LoadSDSContent(FileInfo info) { if (!info.Name.Contains("SDSContent") && info.Extension != "xml") { return; } XmlDocument document = new XmlDocument(); document.Load(info.FullName); XPathNavigator nav = document.CreateNavigator(); var nodes = nav.Select("/SDSResource/ResourceEntry"); while (nodes.MoveNext() == true) { nodes.Current.MoveToFirstChild(); string resourceType = nodes.Current.Value; BaseResource resource = null; if (!resources.ContainsKey(resourceType)) { resources.Add(resourceType, new List <TreeNode>()); } switch (resourceType) { case "FrameResource": case "Effects": case "PREFAB": case "ItemDesc": case "FrameNameTable": case "Actors": case "NAV_AIWORLD_DATA": case "NAV_OBJ_DATA": case "NAV_HPD_DATA": case "Cutscene": case "FxActor": case "FxAnimSet": case "Translokator": case "Speech": case "SoundTable": case "AnimalTrafficPaths": case "AudioSectors": case "Animated Texture": case "Collisions": case "IndexBufferPool": case "VertexBufferPool": case "EntityDataStorage": case "Animation2": case "Mipmap": case "Sound": case "MemFile": resource = new BaseResource(); resource.ReadResourceEntry(nodes); break; case "Texture": resource = new TextureResource(); resource.ReadResourceEntry(nodes); break; case "XML": resource = new XMLResource(); resource.ReadResourceEntry(nodes); break; case "Script": resource = new ScriptResource(); resource.ReadResourceEntry(nodes); break; case "Table": resource = new TableResource(); resource.ReadResourceEntry(nodes); break; default: MessageBox.Show("Did not pack type: " + resourceType, "Toolkit", MessageBoxButtons.OK, MessageBoxIcon.Information); break; } TreeNode node = BuildTreeNode(resource.GetFileName(), resource); resources[resourceType].Add(node); } }
/// <summary> /// Adds script to layer /// </summary> public void AddScript(string scriptName, ScriptResource script) { Scripts.Add(scriptName, script); }
private static void RegisterResources(DotvvmResourceRepository resources) { resources.Register("ControlSamples_SpaContentPlaceHolder_testCss", new StylesheetResource(new FileResourceLocation("Content/testResource.css"))); resources.Register("ControlSamples_SpaContentPlaceHolder_testJs", new ScriptResource(new FileResourceLocation("Scripts/testResource.js"))); resources.Register("ControlSamples_SpaContentPlaceHolder_MasterPageResource", new ScriptResource(new FileResourceLocation("Scripts/testResource2.js"))); resources.Register("FeatureSamples_Resources_CdnUnavailableResourceLoad", new ScriptResource() { Location = new UrlResourceLocation("~/nonexistentResource.js"), LocationFallback = new ResourceLocationFallback("window.dotvvmTestResource", new FileResourceLocation("~/Scripts/testResource.js")) }); resources.Register("FeatureSamples_Resources_CdnScriptPriority", new ScriptResource { Location = new UrlResourceLocation("/Scripts/testResource.js"), LocationFallback = new ResourceLocationFallback("window.dotvvmTestResource", new FileResourceLocation("~/Scripts/testResource2.js")) }); resources.Register("FeatureSamples_Resources_RequiredOnPostback", new ScriptResource() { Location = new UrlResourceLocation("~/nonexistentResource.js"), LocationFallback = new ResourceLocationFallback("window.dotvvmTestResource", new FileResourceLocation("~/Scripts/testResource.js")) }); resources.Register("Errors_InvalidLocationFallback", new ScriptResource { Location = new FileResourceLocation("~/Scripts/testResource.js"), LocationFallback = new ResourceLocationFallback("window.dotvvmTestResource", new FileResourceLocation("~/Scripts/testResource2.js")) }); // resource that triggers the circular dependency check in the render phase var circular = new ScriptResource { Location = new FileResourceLocation("~/Scripts/testResource.js") }; resources.Register("Errors_ResourceCircularDependency", circular); var circular2 = new ScriptResource { Location = new FileResourceLocation("~/Scripts/testResource2.js"), Dependencies = new [] { "Errors_ResourceCircularDependency" } }; resources.Register("Errors_ResourceCircularDependency2", circular2); circular.Dependencies = new[] { "Errors_ResourceCircularDependency" }; resources.Register("extenders", new ScriptResource { Location = new FileResourceLocation("Scripts/ClientExtenders.js") }); resources.Register(nameof(StopwatchPostbackHandler), new ScriptResource { Location = new FileResourceLocation($"~/Scripts/{nameof(StopwatchPostbackHandler)}.js"), Dependencies = new[] { "dotvvm.internal" } }); resources.Register(nameof(ErrorCountPostbackHandler), new ScriptResource { Location = new FileResourceLocation($"~/Scripts/{nameof(ErrorCountPostbackHandler)}.js"), Dependencies = new[] { "dotvvm.internal" } }); // dev files resources.SetEmbeddedResourceDebugFile("knockout", "../DotVVM.Framework/Resources/Scripts/knockout-latest.debug.js"); resources.SetEmbeddedResourceDebugFile("dotvvm.internal", "../DotVVM.Framework/Resources/Scripts/DotVVM.js"); resources.SetEmbeddedResourceDebugFile("dotvvm.debug", "../DotVVM.Framework/Resources/Scripts/DotVVM.Debug.js"); resources.SetEmbeddedResourceDebugFile("dotvvm.fileupload-css", "../DotVVM.Framework/Resources/Scripts/DotVVM.FileUploads.css"); }
/// <summary> /// Wraps command execution into system process call. /// </summary> /// <returns></returns> /// <exception cref="Exception"></exception> public RepeatStatus Execute(StepContribution contribution, ChunkContext chunkContext) { if (Logger.IsTraceEnabled) { Logger.Trace("*** Executing PowerShell Script File: {0}", ScriptResource.GetFullPath()); } //=> PowerShell will throw an error if we do not Suppress ambient transaction... // see https://msdn.microsoft.com/en-us/library/system.transactions.transaction.current(v=vs.110).aspx#NotExistJustToMakeTheAElementVisible using (var transactionScope = new TransactionScope(TransactionScopeOption.Suppress)) { //=> Runspace configuration information includes the assemblies, commands, format and type files, // providers, and scripts that are available within the runspace. RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create(); //Creates a single runspace that uses the default host and runspace configuration using (Runspace runSpace = RunspaceFactory.CreateRunspace(runspaceConfiguration)) { //=> When this runspace is opened, the default host and runspace configuration // that are defined by Windows PowerShell will be used. runSpace.Open(); //=> Set Variables so they are available to user script... if (Variables != null && Variables.Any()) { foreach (KeyValuePair <string, object> variable in Variables) { runSpace.SessionStateProxy.SetVariable(variable.Key, variable.Value); } } //=> this is exit status variables to be tested on exit from power shell script... // it is defined in PwerShell global scope...and must be set by scipt writer on exit... runSpace.SessionStateProxy.SetVariable("ScriptExitStatus", _scriptExitStatus); //=> Allows the execution of commands from a CLR //RunspaceInvoke scriptInvoker = new RunspaceInvoke(runSpace); //scriptInvoker.Invoke("Set-ExecutionPolicy Unrestricted"); using (PowerShell psInstance = PowerShell.Create()) { try { // prepare a new collection to store output stream objects PSDataCollection <PSObject> outputCollection = new PSDataCollection <PSObject>(); outputCollection.DataAdded += AllStreams_DataAdded; psInstance.Streams.Error.DataAdded += AllStreams_DataAdded; psInstance.Streams.Verbose.DataAdded += AllStreams_DataAdded; psInstance.Streams.Warning.DataAdded += AllStreams_DataAdded; psInstance.Streams.Debug.DataAdded += AllStreams_DataAdded; psInstance.Runspace = runSpace; //=> This tasklet should be in the same dll as ExitStatus, i.e. Summer.Batch.Core.dll // we need to get the path to loaded Summer.Batch.Core.dll so we can load it in PowerShell var assemblyLocation = System.Reflection.Assembly.GetExecutingAssembly().Location; //=> need to load Summer.Batch.Core into runspace so we can reference ExitStatus psInstance.AddScript("[System.Reflection.Assembly]::LoadFrom(\"" + assemblyLocation + "\")").AddStatement(); //=> add user command and its parameters... psInstance.AddCommand(ScriptResource.GetFullPath()); if (Parameters != null && Parameters.Any()) { foreach (KeyValuePair <string, object> variable in Parameters) { psInstance.AddParameter(variable.Key, variable.Value); } } //=> Invoke Asynchronously... IAsyncResult asyncResult = psInstance.BeginInvoke <PSObject, PSObject>(null, outputCollection); // do something else until execution has completed. long t0 = DateTime.Now.Ticks; while (!asyncResult.IsCompleted) { //=> take a nap and let script do its job... Thread.Sleep(new TimeSpan(_checkInterval)); //=> to check if job was told to stop... CheckStoppingState(chunkContext); //=> lets make sure we did not exceed alloted time... long timeFromT0 = (long)(new TimeSpan(DateTime.Now.Ticks - t0)).TotalMilliseconds; if (timeFromT0 > _timeout) { //=> Stop PowerShell... psInstance.Stop(); //=> behave based on TimeoutBehaviorOption if (_timeoutBehavior.Equals(TimeoutBehaviorOption.SetExitStatusToFailed)) { contribution.ExitStatus = ExitStatus.Failed; break; } else if (_timeoutBehavior.Equals(TimeoutBehaviorOption.ThrowException)) { //=> lets dump what we got before throwing an error... LogStreams(); throw new FatalStepExecutionException("Execution of PowerShell script exceeded allotted time.", null); } } else if (_execution.TerminateOnly) { //=> Stop PowerShell... psInstance.Stop(); //=> lets dump what we got before throwing an error... LogStreams(); throw new JobInterruptedException( string.Format("Job interrupted while executing PowerShell script '{0}'", ScriptResource.GetFilename())); } else if (_stopped) { psInstance.Stop(); contribution.ExitStatus = ExitStatus.Stopped; break; } } // end while scope //=> Wait to the end of execution... //psInstance.EndInvoke(_asyncResult); //NOTE: asyncResult.IsCompleted will be set to true if PowerShell.Stop was called or // PowerShell completed its work //=> if status not yet set (script completed)...handle completion... if (contribution.ExitStatus.IsRunning()) { //=> script needs to set exit code...if exit code not set we assume 0 var lastExitCode = (int)runSpace.SessionStateProxy.PSVariable.GetValue("LastExitCode", 0); _scriptExitStatus = runSpace.SessionStateProxy.GetVariable("ScriptExitStatus") as ExitStatus; //=> set exit status... if (_scriptExitStatus != null && !_scriptExitStatus.IsRunning()) { if (Logger.IsTraceEnabled) { Logger.Trace("***> ScriptExitStatus returned by script => {0}", _scriptExitStatus); } contribution.ExitStatus = _scriptExitStatus; } else //=> let user decide on ExitStatus { if (Logger.IsTraceEnabled) { if (_scriptExitStatus == null) { Logger.Trace("***> ScriptExitStatus is null. Using PowerShellExitCodeMapper to determine ExitStatus."); } else if (_scriptExitStatus.IsRunning()) { Logger.Trace("***> ScriptExitStatus is EXECUTING or UNKNOWN. Using PowerShellExitCodeMapper to determine ExitStatus."); } } if (PowerShellExitCodeMapper != null) { //=> determine exit status using User Provided PowerShellExitCodeMapper contribution.ExitStatus = PowerShellExitCodeMapper.GetExitStatus(lastExitCode); } else //at this point we are not able to determine exit status, user needs to fix this... { //=> lets dump what we got before throwing an error... LogStreams(); throw new FatalStepExecutionException( "PowerShellTasklet is not able to determine ExitStatus. ScriptExitStatus is null or (is EXECUTING or UNKNOWN) and " + "PowerShellExitCodeMapper is NOT defined. Please set $global:ScriptExitStatus or define PowerShellExitCodeMapper.", null); } } } if (Logger.IsInfoEnabled) { Logger.Info("PowerShell execution exit status [{0}]", contribution.ExitStatus); } //=> output captured stream data to Log... LogStreams(); } catch (RuntimeException ex) { Logger.Error(ex.Message); throw; } } // end PowerShell Scope //=> close Runspace... runSpace.Close(); //=> we are done... return(RepeatStatus.Finished); } // end of Runspace Scope } // end of TransactionScope }
public static string getAssemblyName(ScriptResource.ScriptResource s3sa) { try { byte[] data = new byte[s3sa.Assembly.BaseStream.Length]; s3sa.Assembly.BaseStream.Read(data, 0, data.Length); Assembly assy = Assembly.Load(data); return assy.FullName.Split(',')[0] + ".dll"; } catch { } return "*.dll"; }