public async Task ExecuteAsync(ScriptFile script, BuildItem.BuildActionType action) { string cmdText; switch (action) { case BuildItem.BuildActionType.Drop: return; case BuildItem.BuildActionType.Alter: cmdText = script.Sql.GetAlterScript(); break; case BuildItem.BuildActionType.Create: case BuildItem.BuildActionType.DropAndCreate: cmdText = script.Sql.GetCreateScript(); break; default: throw new NotSupportedException(string.Format("Unable to execute a script for build action type {0}.", action)); } using (var cmd = _connection.CreateCommand()) { cmd.CommandText = cmdText; cmd.Transaction = _transaction; await cmd.ExecuteNonQueryAsync(); } }
public async Task ExecuteAsync(ScriptFile script, BuildItem.BuildActionType action) { if(action == BuildItem.BuildActionType.Drop || action == BuildItem.BuildActionType.DropAndCreate) { string cmdText = string.Format("DROP {0} [{1}].[{2}]", script.ScriptObject.ObjectType.ToString(), script.ScriptObject.SchemaName, script.ScriptObject.ObjectName); var cmd = new SqlCommand(cmdText, Connection); await cmd.ExecuteNonQueryAsync(); } }
public override void DeleteFile(ScriptFile file) { if (!this.scripts.Contains(file)) return; this.scripts.Remove(file); file.PendingDelete(); this.MakeDirty(); }
public static CodeCompletionKeyHandler Attach(ScriptFile mainForm, TextEditorControl editor) { CodeCompletionKeyHandler h = new CodeCompletionKeyHandler(mainForm, editor); //editor.ActiveTextAreaControl.TextArea.KeyEventHandler += h.TextAreaKeyEventHandler; editor.ActiveTextAreaControl.TextArea.KeyDown += h.TextAreaKeyEventHandler; // When the editor is disposed, close the code completion window editor.Disposed += h.CloseCodeCompletionWindow; return h; }
public ScriptListEditorRenameDialog(ScriptListFile scriptListFile, ScriptFile file) { this.scriptListFile = scriptListFile; this.file = file; InitializeComponent(); this.textBox3.Text = this.file.ToString(); this.textBox1.Text = this.file.ToString(); this.Shown += new EventHandler(ScriptListEditorRenameDialog_Shown); }
public async Task ExecuteAsync(ScriptFile script, BuildItem.BuildActionType action) { if(action == BuildItem.BuildActionType.Drop || action == BuildItem.BuildActionType.DropAndCreate) { using (var cmd = _connection.CreateCommand()) { cmd.CommandText = string.Format("DROP {0} [{1}].[{2}]", script.ScriptObject.ObjectType.ToString(), script.ScriptObject.SchemaName, script.ScriptObject.ObjectName); cmd.Transaction = _transaction; await cmd.ExecuteNonQueryAsync(); } } }
public ScriptEditor(ScriptFile item) : base(item) { editor = new UI.RubyScintilla(); editor.Dock = DockStyle.Fill; this.Controls.Add(editor); editor.Text = (this.File as ScriptFile).Code; editor.UndoRedo.EmptyUndoBuffer(); editor.TextDeleted += new EventHandler<ScintillaNET.TextModifiedEventArgs>(editor_TextDeleted); editor.TextInserted += new EventHandler<ScintillaNET.TextModifiedEventArgs>(editor_TextInserted); editor.Scrolling.HorizontalWidth = 1; this.FormClosing += new FormClosingEventHandler(ScriptEditor_FormClosing); }
public DebugServiceTests() { this.workspace = new Workspace(); // Load the test debug file this.debugScriptFile = this.workspace.GetFile( @"..\..\..\PowerShellEditorServices.Test.Shared\Debugging\DebugTest.ps1"); this.powerShellContext = new PowerShellContext(); this.powerShellContext.SessionStateChanged += powerShellContext_SessionStateChanged; this.debugService = new DebugService(this.powerShellContext); this.debugService.DebuggerStopped += debugService_DebuggerStopped; this.debugService.BreakpointUpdated += debugService_BreakpointUpdated; }
public override void Use(Player p, string message, CommandData data) { if (message.Length == 0) { Help(p); return; } string[] args = message.SplitSpaces(); PlayerBot bot = Matcher.FindBots(p, args[0]); if (bot == null) { return; } if (!LevelInfo.Check(p, data.Rank, p.level, "change AI of bots in this level")) { return; } if (!bot.EditableBy(p, "change the AI of")) { return; } if (args.Length == 1) { bot.Instructions.Clear(); bot.kill = false; bot.hunt = false; bot.AIName = null; UpdateBot(p, bot, "'s AI was turned off."); return; } else if (args.Length != 2) { Help(p); return; } string ai = args[1].ToLower(); if (ai.CaselessEq("hunt")) { bot.hunt = !bot.hunt; bot.Instructions.Clear(); bot.AIName = null; UpdateBot(p, bot, "'s hunt instinct: " + bot.hunt); return; } else if (ai.CaselessEq("kill")) { if (!CheckExtraPerm(p, data, 1)) { return; } bot.kill = !bot.kill; UpdateBot(p, bot, "'s kill instinct: " + bot.kill); return; } if (!ScriptFile.Parse(p, bot, ai)) { return; } UpdateBot(p, bot, "'s AI was set to " + ai); }
public static void DrawDialogueText(Graphics graphics, ScriptFile scriptFile, ScriptMessage message) { Color fontColor = Color.FromArgb(255, 255, 255); int line = 0; int left = 15; int top = 7; int windowCount = 1; int matchIndex = 0; MatchCollection matches = message.Matches; for (int i = 0; i < message.Content.Length; i++) { if (message.Content[i] == '\n' || message.Content[i] == '\r') { continue; } if (matchIndex < matches.Count) { if (i == matches[matchIndex].Index + 1) { Match match = matches[matchIndex]; if (match.Groups[1].Value == "COL") { int colorIndex = 0; int.TryParse(match.Groups[2].Value, out colorIndex); if (colorIndex > 15) { fontColor = FontColors[0]; } else { fontColor = FontColors[colorIndex]; } } else if (match.Groups[1].Value == "LF") { line++; top += 16; left = 15; } else if (match.Groups[1].Value == "CLR") { left = 15; top = windowCount * 96 + 7; windowCount++; } matchIndex++; i += match.Length - 2; continue; } } char character = message.Content[i]; Font font = scriptFile.Font; if (left >= 191) { continue; } if (scriptFile.IsValidChar(character)) { i++; //if (scriptFile.IsLockedChar(character)) //{ // FontCharacter fontCharacter = new FontCharacter(new FontSymbol(character, character), font); //not accurate engine rendering // Bitmap bitmap = fontCharacter.GetBitmapTransparent(fontColor); // graphics.DrawImage(bitmap, new Rectangle(left, top, 16, 16), 0, 0, 16, 16, GraphicsUnit.Pixel); // left += 16; //} //else if (i == message.Content.Length) { FontCharacter fontCharacter = new FontCharacter(new FontSymbol(character), font); Bitmap bitmap = fontCharacter.GetBitmapTransparent(fontColor); graphics.DrawImage(bitmap, new Rectangle(left, top, 16, 16), 0, 0, 16, 16, GraphicsUnit.Pixel); left += 16; } else if (scriptFile.IsValidChar(message.Content[i])) { FontCharacter fontCharacter = new FontCharacter(new FontSymbol(character, message.Content[i]), font); Bitmap bitmap = fontCharacter.GetBitmapTransparent(fontColor); graphics.DrawImage(bitmap, new Rectangle(left, top, 16, 16), 0, 0, 16, 16, GraphicsUnit.Pixel); left += 16; } else { FontCharacter fontCharacter = new FontCharacter(new FontSymbol(character), font); Bitmap bitmap = fontCharacter.GetBitmapTransparent(fontColor); graphics.DrawImage(bitmap, new Rectangle(left, top, 16, 16), 0, 0, 16, 16, GraphicsUnit.Pixel); left += 16; } } else { continue; } } }
public CustomColorApplier(ScriptFile script, DocRange range) { _script = script; _range = range; }
/// <summary>Gets the embed tag for the specified script.</summary> /// <param name="scriptFile">Flag indicating what script to retrieve the path for.</param> public string this[ScriptFile scriptFile] { get { return ToScriptLink(Path(scriptFile)); } }
public void DeFormat(ScriptFile script) { }
private string GetBasePath(ScriptFile scriptFile) { // Look for exclusions. if (UseDefaultPath(scriptFile)) return DefaultOpenCorePath; return OpenCorePath.IsNullOrEmpty(true) ? DefaultOpenCorePath : OpenCorePath; }
private async static Task PublishScriptDiagnostics( ScriptFile scriptFile, ScriptFileMarker[] semanticMarkers, EventContext eventContext) { var allMarkers = scriptFile.SyntaxMarkers.Concat(semanticMarkers); // Always send syntax and semantic errors. We want to // make sure no out-of-date markers are being displayed. await eventContext.SendEvent( PublishDiagnosticsNotification.Type, new PublishDiagnosticsNotification { Uri = scriptFile.ClientFilePath, Diagnostics = allMarkers .Select(GetDiagnosticFromMarker) .ToArray() }); }
/// <summary> /// Verifies the provided input /// </summary> /// <param name="data">the data that was provided by a source</param> /// <param name="message">the message that was generated during the validation of this constraint</param> /// <returns>a value indicating whether the data fullfills the requirements of the underlaying Requestor</returns> public virtual DecisionResult Verify(T data, out string message) { Scope varScope; IDisposable evaluationContext = GetEvaluationContext(out varScope); varScope["data"] = data; PrepareVariables(varScope); message = null; try { DecisionResult retVal = DecisionResult.None; switch (mode) { case ConstraintExpressionMode.Single: { object tmp = ExpressionParser.Parse(expression, evaluationContext); if (tmp is bool) { retVal = (bool)tmp ? DecisionResult.Success : DecisionResult.Fail; } else { retVal = (DecisionResult)tmp; } if (lastMessage.IsValueCreated && lastMessage.Value != null) { message = lastMessage.Value; lastMessage.Value = null; } break; } case ConstraintExpressionMode.Script: { object tmp = ExpressionParser.ParseBlock(expression, evaluationContext); if (tmp is bool) { retVal = (bool)tmp ? DecisionResult.Success : DecisionResult.Fail; } else { retVal = (DecisionResult)tmp; } message = varScope["message"] as string; break; } case ConstraintExpressionMode.ScriptFile: { ScriptFile <object> script = ScriptFile <object> .FromFile(expression); object tmp = script.Execute(evaluationContext); if (tmp is bool) { retVal = (bool)tmp ? DecisionResult.Success : DecisionResult.Fail; } else { retVal = (DecisionResult)tmp; } message = varScope["message"] as string; break; } } return(retVal); } finally { CloseEvaluationContext(evaluationContext); } }
private async Task <Query> CreateAndActivateNewQuery(QueryExecuteParams executeParams, RequestContext <QueryExecuteResult> requestContext) { try { // Attempt to get the connection for the editor ConnectionInfo connectionInfo; if (!ConnectionService.TryFindConnection(executeParams.OwnerUri, out connectionInfo)) { await requestContext.SendError(SR.QueryServiceQueryInvalidOwnerUri); return(null); } // Attempt to clean out any old query on the owner URI Query oldQuery; if (ActiveQueries.TryGetValue(executeParams.OwnerUri, out oldQuery) && oldQuery.HasExecuted) { oldQuery.Dispose(); ActiveQueries.TryRemove(executeParams.OwnerUri, out oldQuery); } // Retrieve the current settings for executing the query with QueryExecutionSettings settings = WorkspaceService.CurrentSettings.QueryExecutionSettings; // Get query text from the workspace. ScriptFile queryFile = WorkspaceService.Workspace.GetFile(executeParams.OwnerUri); string queryText; if (executeParams.QuerySelection != null) { string[] queryTextArray = queryFile.GetLinesInRange( new BufferRange( new BufferPosition( executeParams.QuerySelection.StartLine + 1, executeParams.QuerySelection.StartColumn + 1 ), new BufferPosition( executeParams.QuerySelection.EndLine + 1, executeParams.QuerySelection.EndColumn + 1 ) ) ); queryText = queryTextArray.Aggregate((a, b) => a + '\r' + '\n' + b); } else { queryText = queryFile.Contents; } // If we can't add the query now, it's assumed the query is in progress Query newQuery = new Query(queryText, connectionInfo, settings, BufferFileFactory); if (!ActiveQueries.TryAdd(executeParams.OwnerUri, newQuery)) { await requestContext.SendError(SR.QueryServiceQueryInProgress); newQuery.Dispose(); return(null); } return(newQuery); } catch (Exception e) { await requestContext.SendError(e.Message); return(null); } // Any other exceptions will fall through here and be collected at the end }
/// <summary> /// Get the file url under "Scripts" folder. /// </summary> /// <param name="relativeScriptFilePath">The relative file path.</param> /// <param name="withCDNResolving">if set to <c>true</c> [with CDN resolving].</param> /// <returns></returns> public virtual IHtmlString ScriptFileUrl(string relativeScriptFilePath, bool withCDNResolving) { Site site = this.Site; var dir = Path.GetDirectoryName(relativeScriptFilePath); var fileVirtualPath = ""; if (string.IsNullOrEmpty(dir)) { fileVirtualPath = new ScriptFile(site, relativeScriptFilePath).VirtualPath; } else { do { var scriptsPath = new ScriptFile(site, ""); fileVirtualPath = UrlUtility.Combine(scriptsPath.VirtualPath, relativeScriptFilePath); var physicalPath = UrlUtility.MapPath(fileVirtualPath); if (File.Exists(physicalPath)) { break; } else { site = site.Parent; } } while (site != null); } if (withCDNResolving) { return ResourceCDNUrl(fileVirtualPath); } else { return new HtmlString(Url.Content(fileVirtualPath)); } }
protected async Task HandleSetBreakpointsRequest( SetBreakpointsRequestArguments setBreakpointsParams, RequestContext <SetBreakpointsResponseBody> requestContext) { ScriptFile scriptFile = null; // Fix for issue #195 - user can change name of file outside of VSCode in which case // VSCode sends breakpoint requests with the original filename that doesn't exist anymore. try { scriptFile = editorSession.Workspace.GetFile(setBreakpointsParams.Source.Path); } catch (Exception e) when(e is FileNotFoundException || e is DirectoryNotFoundException) { Logger.Write( LogLevel.Warning, $"Attempted to set breakpoints on a non-existing file: {setBreakpointsParams.Source.Path}"); string message = this.noDebug ? string.Empty : "Source does not exist, breakpoint not set."; var srcBreakpoints = setBreakpointsParams.Breakpoints .Select(srcBkpt => Protocol.DebugAdapter.Breakpoint.Create( srcBkpt, setBreakpointsParams.Source.Path, message, verified: this.noDebug)); // Return non-verified breakpoint message. await requestContext.SendResult( new SetBreakpointsResponseBody { Breakpoints = srcBreakpoints.ToArray() }); return; } var breakpointDetails = new BreakpointDetails[setBreakpointsParams.Breakpoints.Length]; for (int i = 0; i < breakpointDetails.Length; i++) { SourceBreakpoint srcBreakpoint = setBreakpointsParams.Breakpoints[i]; breakpointDetails[i] = BreakpointDetails.Create( scriptFile.FilePath, srcBreakpoint.Line, srcBreakpoint.Column, srcBreakpoint.Condition, srcBreakpoint.HitCondition); } // If this is a "run without debugging (Ctrl+F5)" session ignore requests to set breakpoints. BreakpointDetails[] updatedBreakpointDetails = breakpointDetails; if (!this.noDebug) { this.setBreakpointInProgress = true; try { updatedBreakpointDetails = await editorSession.DebugService.SetLineBreakpoints( scriptFile, breakpointDetails); } catch (Exception e) { // Log whatever the error is Logger.WriteException("Caught error while setting breakpoints in SetBreakpoints handler", e); } finally { this.setBreakpointInProgress = false; } } await requestContext.SendResult( new SetBreakpointsResponseBody { Breakpoints = updatedBreakpointDetails .Select(Protocol.DebugAdapter.Breakpoint.Create) .ToArray() }); }
public async Task HandleRequestToChangeToSqlcmdFile() { var scriptFile = new ScriptFile() { ClientFilePath = "HandleRequestToChangeToSqlcmdFile_" + DateTime.Now.ToLongDateString() + "_.sql" }; try { // Prepare a script file scriptFile.SetFileContents("koko wants a bananas"); File.WriteAllText(scriptFile.ClientFilePath, scriptFile.Contents); // Create a workspace and add file to it so that its found for intellense building var workspace = new ServiceLayer.Workspace.Workspace(); var workspaceService = new WorkspaceService <SqlToolsSettings> { Workspace = workspace }; var langService = new LanguageService() { WorkspaceServiceInstance = workspaceService }; langService.CurrentWorkspace.GetFile(scriptFile.ClientFilePath); langService.CurrentWorkspaceSettings.SqlTools.IntelliSense.EnableIntellisense = true; // Add a connection to ensure the intellisense building works ConnectionInfo connectionInfo = GetLiveAutoCompleteTestObjects().ConnectionInfo; langService.ConnectionServiceInstance.OwnerToConnectionMap.Add(scriptFile.ClientFilePath, connectionInfo); // Test SQL int countOfValidationCalls = 0; var eventContextSql = new Mock <SqlTools.Hosting.Protocol.EventContext>(); eventContextSql.Setup(x => x.SendEvent(PublishDiagnosticsNotification.Type, It.Is <PublishDiagnosticsNotification>((notif) => ValidateNotification(notif, 2, ref countOfValidationCalls)))).Returns(Task.FromResult(new object())); await langService.HandleDidChangeLanguageFlavorNotification(new LanguageFlavorChangeParams { Uri = scriptFile.ClientFilePath, Language = LanguageService.SQL_LANG.ToLower(), Flavor = "MSSQL" }, eventContextSql.Object); await langService.DelayedDiagnosticsTask; // to ensure completion and validation before moveing to next step // Test SQL CMD var eventContextSqlCmd = new Mock <SqlTools.Hosting.Protocol.EventContext>(); eventContextSqlCmd.Setup(x => x.SendEvent(PublishDiagnosticsNotification.Type, It.Is <PublishDiagnosticsNotification>((notif) => ValidateNotification(notif, 0, ref countOfValidationCalls)))).Returns(Task.FromResult(new object())); await langService.HandleDidChangeLanguageFlavorNotification(new LanguageFlavorChangeParams { Uri = scriptFile.ClientFilePath, Language = LanguageService.SQL_CMD_LANG.ToLower(), Flavor = "MSSQL" }, eventContextSqlCmd.Object); await langService.DelayedDiagnosticsTask; Assert.True(countOfValidationCalls == 2, $"Validation should be called 2 time but is called {countOfValidationCalls} times"); } finally { if (File.Exists(scriptFile.ClientFilePath)) { File.Delete(scriptFile.ClientFilePath); } } }
/// <summary> /// Sets the change tracking <c>State</c> /// of a <c>ScriptFile</c> to <c>EntityState.Modified</c>. /// This allows changes that have been made to the tracked <c>ScriptFile</c> to be /// committed when changes are saved to the database context. /// </summary> /// <param name="scriptFile"></param> public void UpdateScriptFile(ScriptFile scriptFile) { _context.Entry(scriptFile).State = EntityState.Modified; }
/// <summary>Retreives the path to the specified script.</summary> /// <param name="script">The script to retrieve the path for.</param> public string Path(ScriptFile script) { string path; switch (script) { case ScriptFile.JQuery: path = string.Format("JQuery/{0}.js", WebConstantsShared.JQuery); break; case ScriptFile.JQueryUi: path = string.Format("JQuery/{0}.js", WebConstantsShared.JQueryUi); break; case ScriptFile.JQueryCookie: path = "JQuery/jquery.cookie.js"; break; case ScriptFile.JQueryTemplate: path = "JQuery/jquery.tmpl.js"; break; case ScriptFile.JQueryTemplatePlus: path = "JQuery/jquery.tmplPlus.js"; break; case ScriptFile.JQueryJson: path = "JQuery/jquery.json-2.2.min.js"; break; case ScriptFile.MsCoreLib: path = "mscorlib.js"; break; case ScriptFile.Core: path = "Open.Core.debug.js"; break; case ScriptFile.CoreControls: path = "Open.Core.Controls.debug.js"; break; case ScriptFile.CoreLists: path = "Open.Core.Lists.debug.js"; break; case ScriptFile.TestHarness: path = "Open.TestHarness.debug.js"; break; default: throw new NotSupportedException(script.ToString()); } return string.Format( "{0}/{1}", GetBasePath(script).RemoveEnd("/"), path).PrependDomain(); }
/// <summary> /// Sets the list of line breakpoints for the current debugging session. /// </summary> /// <param name="scriptFile">The ScriptFile in which breakpoints will be set.</param> /// <param name="breakpoints">BreakpointDetails for each breakpoint that will be set.</param> /// <param name="clearExisting">If true, causes all existing breakpoints to be cleared before setting new ones.</param> /// <returns>An awaitable Task that will provide details about the breakpoints that were set.</returns> public async Task <BreakpointDetails[]> SetLineBreakpointsAsync( ScriptFile scriptFile, BreakpointDetails[] breakpoints, bool clearExisting = true) { var dscBreakpoints = this.powerShellContext .CurrentRunspace .GetCapability <DscBreakpointCapability>(); string scriptPath = scriptFile.FilePath; // Make sure we're using the remote script path if (this.powerShellContext.CurrentRunspace.Location == RunspaceLocation.Remote && this.remoteFileManager != null) { if (!this.remoteFileManager.IsUnderRemoteTempPath(scriptPath)) { this.logger.LogTrace( $"Could not set breakpoints for local path '{scriptPath}' in a remote session."); return(Array.Empty <BreakpointDetails>()); } string mappedPath = this.remoteFileManager.GetMappedPath( scriptPath, this.powerShellContext.CurrentRunspace); scriptPath = mappedPath; } else if ( this.temporaryScriptListingPath != null && this.temporaryScriptListingPath.Equals(scriptPath, StringComparison.CurrentCultureIgnoreCase)) { this.logger.LogTrace( $"Could not set breakpoint on temporary script listing path '{scriptPath}'."); return(Array.Empty <BreakpointDetails>()); } // Fix for issue #123 - file paths that contain wildcard chars [ and ] need to // quoted and have those wildcard chars escaped. string escapedScriptPath = PowerShellContextService.WildcardEscapePath(scriptPath); if (dscBreakpoints == null || !dscBreakpoints.IsDscResourcePath(escapedScriptPath)) { if (clearExisting) { await _breakpointService.RemoveAllBreakpointsAsync(scriptFile.FilePath).ConfigureAwait(false); } return((await _breakpointService.SetBreakpointsAsync(escapedScriptPath, breakpoints).ConfigureAwait(false)).ToArray()); } return(await dscBreakpoints.SetLineBreakpointsAsync( this.powerShellContext, escapedScriptPath, breakpoints).ConfigureAwait(false)); }
/// <summary> /// Get the most recent corrections computed for a given script file. /// </summary> /// <param name="documentUri">The URI string of the file to get code actions for.</param> /// <returns>A threadsafe readonly dictionary of the code actions of the particular file.</returns> public async Task <IReadOnlyDictionary <string, MarkerCorrection> > GetMostRecentCodeActionsForFileAsync(ScriptFile scriptFile) { if (!_mostRecentCorrectionsByFile.TryGetValue(scriptFile, out CorrectionTableEntry corrections)) { return(null); } // Wait for diagnostics to be published for this file await corrections.DiagnosticPublish.ConfigureAwait(false); return(corrections.Corrections); }
private IEnumerable <CompletionItem> GetKnownParamValuesCompletionItems(Position position, ScriptFile scriptFile, out bool valuesAreExclusive) { var callExpressionNode = scriptFile.Node.GetDescendantNodeOfTypeAtPosition <FunctionCallExpressionNode>(position.ToPosition()); var callExpressionParameterIndex = callExpressionNode?.GetFunctionParameterIndexAtPosition(position.ToPosition()); valuesAreExclusive = false; var knownParamValues = callExpressionParameterIndex.HasValue && callExpressionParameterIndex != -1 ? callExpressionNode.GetKnownParameterValueSymbols(callExpressionParameterIndex.Value, out valuesAreExclusive) : null; return(knownParamValues != null? knownParamValues.Select(symbol => { var displayText = _displayTextEmitter.GetDisplayText(symbol); return new CompletionItem() { Kind = GetCompletionItemKind(symbol), Label = symbol.Name, InsertText = $"\"{symbol.Name}\"", Detail = displayText.Text, SortText = $"_{symbol.Name}", Documentation = displayText.Documentation }; }).ToArray() : Enumerable.Empty <CompletionItem>()); }
private void PublishScriptDiagnostics(ScriptFile scriptFile) => PublishScriptDiagnostics(scriptFile, scriptFile.DiagnosticMarkers);
private Task RunScriptDiagnostics( ScriptFile[] filesToAnalyze, EditorSession editorSession, EventContext eventContext) { if (!this.currentSettings.ScriptAnalysis.Enable.Value) { // If the user has disabled script analysis, skip it entirely return Task.FromResult(true); } // If there's an existing task, attempt to cancel it try { if (existingRequestCancellation != null) { // Try to cancel the request existingRequestCancellation.Cancel(); // If cancellation didn't throw an exception, // clean up the existing token existingRequestCancellation.Dispose(); existingRequestCancellation = null; } } catch (Exception e) { // TODO: Catch a more specific exception! Logger.Write( LogLevel.Error, string.Format( "Exception while cancelling analysis task:\n\n{0}", e.ToString())); TaskCompletionSource<bool> cancelTask = new TaskCompletionSource<bool>(); cancelTask.SetCanceled(); return cancelTask.Task; } // Create a fresh cancellation token and then start the task. // We create this on a different TaskScheduler so that we // don't block the main message loop thread. // TODO: Is there a better way to do this? existingRequestCancellation = new CancellationTokenSource(); Task.Factory.StartNew( () => DelayThenInvokeDiagnostics( 750, filesToAnalyze, editorSession, eventContext, existingRequestCancellation.Token), CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default); return Task.FromResult(true); }
public void GetDefinitionTimeoutTest() { // Given a binding queue that will automatically time out var languageService = new LanguageService(); Mock <ConnectedBindingQueue> queueMock = new Mock <ConnectedBindingQueue>(); languageService.BindingQueue = queueMock.Object; ManualResetEvent mre = new ManualResetEvent(true); // Do not block Mock <QueueItem> itemMock = new Mock <QueueItem>(); itemMock.Setup(i => i.ItemProcessed).Returns(mre); DefinitionResult timeoutResult = null; queueMock.Setup(q => q.QueueBindingOperation( It.IsAny <string>(), It.IsAny <Func <IBindingContext, CancellationToken, object> >(), It.IsAny <Func <IBindingContext, object> >(), It.IsAny <int?>(), It.IsAny <int?>())) .Callback <string, Func <IBindingContext, CancellationToken, object>, Func <IBindingContext, object>, int?, int?>( (key, bindOperation, timeoutOperation, t1, t2) => { timeoutResult = (DefinitionResult)timeoutOperation((IBindingContext)null); itemMock.Object.Result = timeoutResult; }) .Returns(() => itemMock.Object); TextDocumentPosition textDocument = new TextDocumentPosition { TextDocument = new TextDocumentIdentifier { Uri = OwnerUri }, Position = new Position { Line = 0, Character = 20 } }; LiveConnectionHelper.TestConnectionResult connectionResult = LiveConnectionHelper.InitLiveConnectionInfo(); ScriptFile scriptFile = connectionResult.ScriptFile; ConnectionInfo connInfo = connectionResult.ConnectionInfo; scriptFile.Contents = "select * from dbo.func ()"; ScriptParseInfo scriptInfo = new ScriptParseInfo { IsConnected = true }; languageService.ScriptParseInfoMap.Add(OwnerUri, scriptInfo); // When I call the language service var result = languageService.GetDefinition(textDocument, scriptFile, connInfo); // Then I expect null locations and an error to be reported Assert.NotNull(result); Assert.True(result.IsErrorResult); // Check timeout message Assert.Equal(SR.PeekDefinitionTimedoutError, result.Message); }
private static void checkScriptFileForDependencies(Dictionary<string, bool> alreadyAdded, List<ScriptFile> fileList, ScriptFile file) { if (!alreadyAdded.ContainsKey(file.DocumentFilePath)) { fileList.Add(file); alreadyAdded[file.DocumentFilePath] = true; } if (file.Dependencies != null) { foreach (var dep in file.Dependencies) { checkScriptFileForDependencies(alreadyAdded, fileList, dep); } } }
private static bool UseDefaultPath(ScriptFile scriptFile) { if (scriptFile.IsJQuery()) return true; // if (scriptFile == ScriptFile.TestHarness) return true; return false; }
/// <summary> /// Clear all diagnostic markers for a given file. /// </summary> /// <param name="file">The file to clear markers in.</param> /// <returns>A task that ends when all markers in the file have been cleared.</returns> public void ClearMarkers(ScriptFile file) { PublishScriptDiagnostics(file, Array.Empty <ScriptFileMarker>()); }
protected async Task HandleLaunchRequest( LaunchRequestArguments launchParams, RequestContext <object> requestContext) { this.RegisterEventHandlers(); // Set the working directory for the PowerShell runspace to the cwd passed in via launch.json. // In case that is null, use the the folder of the script to be executed. If the resulting // working dir path is a file path then extract the directory and use that. string workingDir = launchParams.Cwd ?? launchParams.Script ?? #pragma warning disable 618 launchParams.Program; #pragma warning restore 618 // When debugging an "untitled" (unsaved) file - the working dir can't be derived // from the Script path. OTOH, if the launch params specifies a Cwd, use it. if (ScriptFile.IsUntitledPath(workingDir) && string.IsNullOrEmpty(launchParams.Cwd)) { workingDir = null; } if (!string.IsNullOrEmpty(workingDir)) { workingDir = PowerShellContext.UnescapePath(workingDir); try { if ((File.GetAttributes(workingDir) & FileAttributes.Directory) != FileAttributes.Directory) { workingDir = Path.GetDirectoryName(workingDir); } } catch (Exception ex) { Logger.Write(LogLevel.Error, "cwd path is invalid: " + ex.Message); workingDir = null; } } if (string.IsNullOrEmpty(workingDir)) { #if CoreCLR workingDir = AppContext.BaseDirectory; #else workingDir = Environment.CurrentDirectory; #endif } if (this.editorSession.PowerShellContext.CurrentRunspace.Location == RunspaceLocation.Local && !this.editorSession.DebugService.IsDebuggerStopped) { await editorSession.PowerShellContext.SetWorkingDirectory(workingDir, isPathAlreadyEscaped : false); Logger.Write(LogLevel.Verbose, "Working dir set to: " + workingDir); } // Prepare arguments to the script - if specified string arguments = null; if ((launchParams.Args != null) && (launchParams.Args.Length > 0)) { arguments = string.Join(" ", launchParams.Args); Logger.Write(LogLevel.Verbose, "Script arguments are: " + arguments); } // Store the launch parameters so that they can be used later this.noDebug = launchParams.NoDebug; #pragma warning disable 618 this.scriptToLaunch = launchParams.Script ?? launchParams.Program; #pragma warning restore 618 this.arguments = arguments; this.IsUsingTempIntegratedConsole = launchParams.CreateTemporaryIntegratedConsole; // If the current session is remote, map the script path to the remote // machine if necessary if (this.scriptToLaunch != null && this.editorSession.PowerShellContext.CurrentRunspace.Location == RunspaceLocation.Remote) { this.scriptToLaunch = this.editorSession.RemoteFileManager.GetMappedPath( this.scriptToLaunch, this.editorSession.PowerShellContext.CurrentRunspace); } await requestContext.SendResult(null); // If no script is being launched, mark this as an interactive // debugging session this.isInteractiveDebugSession = string.IsNullOrEmpty(this.scriptToLaunch); // Send the InitializedEvent so that the debugger will continue // sending configuration requests await this.messageSender.SendEvent( InitializedEvent.Type, null); }
public static CorrectionTableEntry CreateForFile(ScriptFile file) { return(new CorrectionTableEntry()); }
protected async Task HandleSetBreakpointsRequest( SetBreakpointsRequestArguments setBreakpointsParams, RequestContext <SetBreakpointsResponseBody> requestContext) { ScriptFile scriptFile = null; // Fix for issue #195 - user can change name of file outside of VSCode in which case // VSCode sends breakpoint requests with the original filename that doesn't exist anymore. try { // When you set a breakpoint in the right pane of a Git diff window on a PS1 file, // the Source.Path comes through as Untitled-X. if (!ScriptFile.IsUntitledPath(setBreakpointsParams.Source.Path)) { scriptFile = editorSession.Workspace.GetFile(setBreakpointsParams.Source.Path); } } catch (Exception e) when( e is FileNotFoundException || e is DirectoryNotFoundException || e is IOException || e is NotSupportedException || e is PathTooLongException || e is SecurityException || e is UnauthorizedAccessException) { Logger.WriteException( $"Failed to set breakpoint on file: {setBreakpointsParams.Source.Path}", e); string message = this.noDebug ? string.Empty : "Source file could not be accessed, breakpoint not set - " + e.Message; var srcBreakpoints = setBreakpointsParams.Breakpoints .Select(srcBkpt => Protocol.DebugAdapter.Breakpoint.Create( srcBkpt, setBreakpointsParams.Source.Path, message, verified: this.noDebug)); // Return non-verified breakpoint message. await requestContext.SendResult( new SetBreakpointsResponseBody { Breakpoints = srcBreakpoints.ToArray() }); return; } // Verify source file is a PowerShell script file. string fileExtension = Path.GetExtension(scriptFile?.FilePath ?? "")?.ToLower(); if (string.IsNullOrEmpty(fileExtension) || ((fileExtension != ".ps1") && (fileExtension != ".psm1"))) { Logger.Write( LogLevel.Warning, $"Attempted to set breakpoints on a non-PowerShell file: {setBreakpointsParams.Source.Path}"); string message = this.noDebug ? string.Empty : "Source is not a PowerShell script, breakpoint not set."; var srcBreakpoints = setBreakpointsParams.Breakpoints .Select(srcBkpt => Protocol.DebugAdapter.Breakpoint.Create( srcBkpt, setBreakpointsParams.Source.Path, message, verified: this.noDebug)); // Return non-verified breakpoint message. await requestContext.SendResult( new SetBreakpointsResponseBody { Breakpoints = srcBreakpoints.ToArray() }); return; } // At this point, the source file has been verified as a PowerShell script. var breakpointDetails = new BreakpointDetails[setBreakpointsParams.Breakpoints.Length]; for (int i = 0; i < breakpointDetails.Length; i++) { SourceBreakpoint srcBreakpoint = setBreakpointsParams.Breakpoints[i]; breakpointDetails[i] = BreakpointDetails.Create( scriptFile.FilePath, srcBreakpoint.Line, srcBreakpoint.Column, srcBreakpoint.Condition, srcBreakpoint.HitCondition); } // If this is a "run without debugging (Ctrl+F5)" session ignore requests to set breakpoints. BreakpointDetails[] updatedBreakpointDetails = breakpointDetails; if (!this.noDebug) { this.setBreakpointInProgress = true; try { updatedBreakpointDetails = await editorSession.DebugService.SetLineBreakpoints( scriptFile, breakpointDetails); } catch (Exception e) { // Log whatever the error is Logger.WriteException($"Caught error while setting breakpoints in SetBreakpoints handler for file {scriptFile?.FilePath}", e); } finally { this.setBreakpointInProgress = false; } } await requestContext.SendResult( new SetBreakpointsResponseBody { Breakpoints = updatedBreakpointDetails .Select(Protocol.DebugAdapter.Breakpoint.Create) .ToArray() }); }
// [Fact] public async void GetDefinitionFromProcedures() { string queryString = "EXEC master.dbo.sp_MSrepl_startup"; // place the cursor on every token //cursor on objects TextDocumentPosition fnDocument = CreateTextDocPositionWithCursor(30, TestUri); //cursor on sys TextDocumentPosition dboDocument = CreateTextDocPositionWithCursor(14, TestUri); //cursor on master TextDocumentPosition masterDocument = CreateTextDocPositionWithCursor(10, TestUri); LiveConnectionHelper.TestConnectionResult connectionResult = LiveConnectionHelper.InitLiveConnectionInfo(null, TestUri); ScriptFile scriptFile = connectionResult.ScriptFile; ConnectionInfo connInfo = connectionResult.ConnectionInfo; connInfo.RemoveAllConnections(); var bindingQueue = new ConnectedBindingQueue(); bindingQueue.AddConnectionContext(connInfo); scriptFile.Contents = queryString; var service = new LanguageService(); service.RemoveScriptParseInfo(OwnerUri); service.BindingQueue = bindingQueue; await service.UpdateLanguageServiceOnConnection(connectionResult.ConnectionInfo); Thread.Sleep(2000); ScriptParseInfo scriptInfo = new ScriptParseInfo { IsConnected = true }; service.ParseAndBind(scriptFile, connInfo); scriptInfo.ConnectionKey = bindingQueue.AddConnectionContext(connInfo); service.ScriptParseInfoMap.Add(TestUri, scriptInfo); // When I call the language service var fnResult = service.GetDefinition(fnDocument, scriptFile, connInfo); var sysResult = service.GetDefinition(dboDocument, scriptFile, connInfo); var masterResult = service.GetDefinition(masterDocument, scriptFile, connInfo); // Then I expect the results to be non-null Assert.NotNull(fnResult); Assert.NotNull(sysResult); Assert.NotNull(masterResult); // And I expect the all results to be the same Assert.True(CompareLocations(fnResult.Locations, sysResult.Locations)); Assert.True(CompareLocations(fnResult.Locations, masterResult.Locations)); Cleanup(fnResult.Locations); Cleanup(sysResult.Locations); Cleanup(masterResult.Locations); service.ScriptParseInfoMap.Remove(TestUri); connInfo.RemoveAllConnections(); }
public void ApplyMigration(ScriptFile migration) { AssertNotDisposed(); var commands = ParseSqlScript(migration.Content); using (var transaction = Connection.BeginTransaction() as SqlTransaction) { var sw = new Stopwatch(); sw.Restart(); foreach (var command in commands) { if (string.IsNullOrWhiteSpace(command)) continue; using (SqlCommand cmd = Connection.CreateCommand() as SqlCommand) { cmd.Transaction = transaction; cmd.CommandTimeout = 3000; cmd.CommandText = command; var rowsAffected = cmd.ExecuteNonQuery(); } } sw.Stop(); if (migration is RepeatableScript) { // delete any existing record before inserting TryDeleteMigration(transaction, migration); } RecordMigration(transaction, migration, sw.Elapsed.TotalMilliseconds); transaction.Commit(); } }
public void Format(ScriptFile script, bool ignoreMissing = true) { StringBuilder stringBuilder = new StringBuilder(); string[] lines = ScriptParser.TextToLines(Content); stringBuilder.AppendLine(lines[0]); for (int l = 1; l < lines.Length; l++) { string[] splitted = lines[l].Split(','); if (splitted.Length != 3) { throw new Exception("NO!"); } string displayText = splitted[2]; stringBuilder.Append(splitted[0] + "," + splitted[1] + ","); for (int i = 0; i < displayText.Length; i++) { bool pair = false; string neededSymbol = displayText[i].ToString(); if (i + 1 < displayText.Length) { if (script.IsValidChar(displayText[i + 1])) { neededSymbol += displayText[i + 1]; pair = true; } else { neededSymbol += " "; } } else { neededSymbol += " "; } bool found = false; foreach (FontCharacter fontCharacter in script.GeneratedFont) { if (fontCharacter.Symbol == neededSymbol) { byte[] bytes = BitConverter.GetBytes(fontCharacter.Index); stringBuilder.Append(_shiftJis.GetString(bytes)); found = true; if (pair) { i++; } break; } } if (!found) { if (!ignoreMissing) { MessageBox.Show("Couldn't find the needed symbol in the generated font.\nGenerate the font before formating!", "Format Error!"); return; } } } stringBuilder.Append("\r\n"); } Content = stringBuilder.ToString(); }
public void ResyncMigration(ScriptFile migration) { AssertNotDisposed(); using (var transaction = Connection.BeginTransaction() as SqlTransaction) { TryDeleteMigration(transaction, migration); RecordMigration(transaction, migration, 0); transaction.Commit(); } }
public static void DrawSelectionText(Graphics graphics, ScriptFile scriptFile, ScriptMessage message, bool alternative = false) { Color fontColor = Color.FromArgb(255, 255, 255); Font font = scriptFile.Font; int left = 15; int top = 7; string[] lines = null; if (alternative) { lines = ScriptParser.TextToLines(message.ContentAlternative); } else { lines = ScriptParser.TextToLines(message.Content); } bool open = false; if (lines != null) { foreach (string line in lines) { if (line.StartsWith("%SEL:")) { open = true; continue; } if (line.StartsWith("%END:")) { open = false; continue; } if (open) { string[] splitted = line.Split(','); if (splitted.Length < 3) { continue; } string displayText = splitted[2]; for (int i = 0; i < displayText.Length; i++) { char character = displayText[i]; if (left >= 223 || top >= 159) { continue; } if (scriptFile.IsValidChar(character)) { i++; if (i == displayText.Length) { FontCharacter fontCharacter = new FontCharacter(new FontSymbol(character), font); Bitmap bitmap = fontCharacter.GetBitmapTransparent(fontColor); graphics.DrawImage(bitmap, new Rectangle(left, top, 16, 16), 0, 0, 16, 16, GraphicsUnit.Pixel); left += 16; } else if (scriptFile.IsValidChar(displayText[i])) { FontCharacter fontCharacter = new FontCharacter(new FontSymbol(character, displayText[i]), font); Bitmap bitmap = fontCharacter.GetBitmapTransparent(fontColor); graphics.DrawImage(bitmap, new Rectangle(left, top, 16, 16), 0, 0, 16, 16, GraphicsUnit.Pixel); left += 16; } else { FontCharacter fontCharacter = new FontCharacter(new FontSymbol(character), font); Bitmap bitmap = fontCharacter.GetBitmapTransparent(fontColor); graphics.DrawImage(bitmap, new Rectangle(left, top, 16, 16), 0, 0, 16, 16, GraphicsUnit.Pixel); left += 16; } } } } top += 16; left = 15; } } }
private void RecordMigration(DbTransaction transaction, ScriptFile migration, double transactionDuractionMS) { AssertNotDisposed(); using (SqlCommand cmd = Connection.CreateCommand() as SqlCommand) { cmd.Transaction = transaction as SqlTransaction; cmd.CommandText = InsertInfo; var param_FileName = cmd.Parameters.Add("@FileName", SqlDbType.VarChar, 255); var param_FileNameMD5Hash = cmd.Parameters.Add("@FileNameMD5Hash", SqlDbType.UniqueIdentifier); var param_ContentSHA1Hash = cmd.Parameters.Add("@ContentSHA1Hash", SqlDbType.VarChar, 40); var param_Type = cmd.Parameters.Add("@Type", SqlDbType.TinyInt); var param_TransactionDuractionMS = cmd.Parameters.Add("@TransactionDuractionMS", SqlDbType.Float); param_FileName.Value = migration.FileName; param_FileNameMD5Hash.Value = migration.FileNameHash; param_ContentSHA1Hash.Value = migration.ContentSHA1Hash; param_Type.Value = migration.TypeCode; param_TransactionDuractionMS.Value = transactionDuractionMS; cmd.ExecuteNonQuery(); } }
/// <summary> /// Take a codelens and create a new codelens object with updated references. /// </summary> /// <param name="codeLens">The old code lens to get updated references for.</param> /// <returns>A new code lens object describing the same data as the old one but with updated references.</returns> public CodeLens ResolveCodeLens(CodeLens codeLens, ScriptFile scriptFile) { ScriptFile[] references = _workspaceService.ExpandScriptReferences( scriptFile); SymbolReference foundSymbol = _symbolsService.FindFunctionDefinitionAtLocation( scriptFile, codeLens.Range.Start.Line + 1, codeLens.Range.Start.Character + 1); List <SymbolReference> referencesResult = _symbolsService.FindReferencesOfSymbol( foundSymbol, references, _workspaceService); Location[] referenceLocations; if (referencesResult == null) { referenceLocations = s_emptyLocationArray; } else { var acc = new List <Location>(); foreach (SymbolReference foundReference in referencesResult) { if (IsReferenceDefinition(foundSymbol, foundReference)) { continue; } DocumentUri uri = DocumentUri.From(foundReference.FilePath); // For any vscode-notebook-cell, we need to ignore the backing file on disk. if (uri.Scheme == "file" && scriptFile.DocumentUri.Scheme == "vscode-notebook-cell" && uri.Path == scriptFile.DocumentUri.Path) { continue; } acc.Add(new Location { Uri = uri, Range = foundReference.ScriptRegion.ToRange() }); } referenceLocations = acc.ToArray(); } return(new CodeLens { Data = codeLens.Data, Range = codeLens.Range, Command = new Command { Name = "editor.action.showReferences", Title = GetReferenceCountHeader(referenceLocations.Length), Arguments = JArray.FromObject(new object[] { scriptFile.DocumentUri, codeLens.Range.Start, referenceLocations }, LspSerializer.Instance.JsonSerializer) } }); }
private void TryDeleteMigration(DbTransaction transaction, ScriptFile migration) { using (SqlCommand cmd = Connection.CreateCommand() as SqlCommand) { cmd.Transaction = transaction as SqlTransaction; cmd.CommandText = DeleteByFileNameMD5Hash; var param_FileNameMD5Hash = cmd.Parameters.Add("@FileNameMD5Hash", SqlDbType.UniqueIdentifier); param_FileNameMD5Hash.Value = migration.FileNameHash; cmd.ExecuteNonQuery(); } }
/// <summary> /// Get all the CodeLenses for a given script file. /// </summary> /// <param name="scriptFile">The PowerShell script file to get CodeLenses for.</param> /// <returns>All generated CodeLenses for the given script file.</returns> private CodeLens[] ProvideCodeLenses(ScriptFile scriptFile) { return(InvokeProviders(provider => provider.ProvideCodeLenses(scriptFile)) .SelectMany(codeLens => codeLens) .ToArray()); }
IEnumerable <SymbolReference> IDocumentSymbolProvider.ProvideDocumentSymbols( ScriptFile scriptFile) { if (!scriptFile.FilePath.EndsWith( "tests.ps1", StringComparison.OrdinalIgnoreCase)) { return(Enumerable.Empty <SymbolReference>()); } var commandAsts = scriptFile.ScriptAst.FindAll(ast => { CommandAst commandAst = ast as CommandAst; return (commandAst != null && commandAst.InvocationOperator != TokenKind.Dot && PesterSymbolReference.GetCommandType(commandAst.GetCommandName()).HasValue&& commandAst.CommandElements.Count >= 2); }, true); return(commandAsts.Select( ast => { // By this point we know the Ast is a CommandAst with 2 or more CommandElements int testNameParamIndex = 1; CommandAst testAst = (CommandAst)ast; // The -Name parameter for (int i = 1; i < testAst.CommandElements.Count; i++) { CommandParameterAst paramAst = testAst.CommandElements[i] as CommandParameterAst; if (paramAst != null && paramAst.ParameterName.Equals("Name", StringComparison.OrdinalIgnoreCase)) { testNameParamIndex = i + 1; break; } } if (testNameParamIndex > testAst.CommandElements.Count - 1) { return null; } StringConstantExpressionAst stringAst = testAst.CommandElements[testNameParamIndex] as StringConstantExpressionAst; if (stringAst == null) { return null; } string testDefinitionLine = scriptFile.GetLine( ast.Extent.StartLineNumber); return new PesterSymbolReference( scriptFile, testAst.GetCommandName(), testDefinitionLine, stringAst.Value, ast.Extent); }).Where(s => s != null)); }
private Task <CompletionList> HandleEmptyNodeCompletion(CompletionParams request, ScriptFile scriptFile) { var lineText = scriptFile.Text.GetTextInRange(new Common.Range() { Start = new Common.Position() { Line = request.Position.Line, Character = 0 }, End = request.Position.ToPosition() }); var match = Regex.Match(lineText, @"^\s*event\s+((.*)\..*)?.*$", RegexOptions.IgnoreCase); if (!match.Success) { return(Task.FromResult <CompletionList>(null)); } if (match.Groups.Count == 3) { var className = match.Groups[2]; scriptFile.Program.ScriptFiles.TryGetValue(className.Value, out var matchingFile); if (matchingFile != null && matchingFile.Symbol != null) { return(Task.FromResult(new CompletionList( GetEventCompletionItems(matchingFile.Symbol.Children .Where(s => s.Kind == SymbolKinds.Event || s.Kind == SymbolKinds.CustomEvent))))); } } return(Task.FromResult(new CompletionList(GetScriptCompletionItems(scriptFile)))); }
/// <summary> /// Closes a currently open script file with the given file path. /// </summary> /// <param name="scriptFile">The file path at which the script resides.</param> public void CloseFile(ScriptFile scriptFile) { Validate.IsNotNull("scriptFile", scriptFile); this.workspaceFiles.Remove(scriptFile.Id); }
private static int Wain(string[] args) { var app = new CommandLineApplication(throwOnUnexpectedArg: false) { ExtendedHelpText = "Starting without a path to a CSX file or a command, starts the REPL (interactive) mode." }; var file = app.Argument("script", "Path to CSX script"); var interactive = app.Option("-i | --interactive", "Execute a script and drop into the interactive mode afterwards.", CommandOptionType.NoValue); var configuration = app.Option("-c | --configuration <configuration>", "Configuration to use for running the script [Release/Debug] Default is \"Debug\"", CommandOptionType.SingleValue); var packageSources = app.Option("-s | --sources <SOURCE>", "Specifies a NuGet package source to use when resolving NuGet packages.", CommandOptionType.MultipleValue); var debugMode = app.Option(DebugFlagShort + " | " + DebugFlagLong, "Enables debug output.", CommandOptionType.NoValue); var verbosity = app.Option("--verbosity", " Set the verbosity level of the command. Allowed values are t[trace], d[ebug], i[nfo], w[arning], e[rror], and c[ritical].", CommandOptionType.SingleValue); var nocache = app.Option("--no-cache", "Disable caching (Restore and Dll cache)", CommandOptionType.NoValue); var infoOption = app.Option("--info", "Displays environmental information", CommandOptionType.NoValue); var argsBeforeDoubleHyphen = args.TakeWhile(a => a != "--").ToArray(); var argsAfterDoubleHyphen = args.SkipWhile(a => a != "--").Skip(1).ToArray(); const string helpOptionTemplate = "-? | -h | --help"; app.HelpOption(helpOptionTemplate); app.VersionOption("-v | --version", () => new VersionProvider().GetCurrentVersion().Version); app.Command("eval", c => { c.Description = "Execute CSX code."; var code = c.Argument("code", "Code to execute."); var cwd = c.Option("-cwd |--workingdirectory <currentworkingdirectory>", "Working directory for the code compiler. Defaults to current directory.", CommandOptionType.SingleValue); c.HelpOption(helpOptionTemplate); c.OnExecute(async() => { if (string.IsNullOrWhiteSpace(code.Value)) { c.ShowHelp(); return(0); } var logFactory = CreateLogFactory(verbosity.Value(), debugMode.HasValue()); var options = new ExecuteCodeCommandOptions(code.Value, cwd.Value(), app.RemainingArguments.Concat(argsAfterDoubleHyphen).ToArray(), configuration.ValueEquals("release", StringComparison.OrdinalIgnoreCase) ? OptimizationLevel.Release : OptimizationLevel.Debug, nocache.HasValue(), packageSources.Values?.ToArray()); return(await new ExecuteCodeCommand(ScriptConsole.Default, logFactory).Execute <int>(options)); }); }); app.Command("init", c => { c.Description = "Creates a sample script along with the launch.json file needed to launch and debug the script."; var fileName = c.Argument("filename", "(Optional) The name of the sample script file to be created during initialization. Defaults to 'main.csx'"); var cwd = c.Option("-cwd |--workingdirectory <currentworkingdirectory>", "Working directory for initialization. Defaults to current directory.", CommandOptionType.SingleValue); c.HelpOption(helpOptionTemplate); c.OnExecute(() => { var logFactory = CreateLogFactory(verbosity.Value(), debugMode.HasValue()); new InitCommand(logFactory).Execute(new InitCommandOptions(fileName.Value, cwd.Value())); return(0); }); }); app.Command("new", c => { c.Description = "Creates a new script file"; var fileNameArgument = c.Argument("filename", "The script file name"); var cwd = c.Option("-cwd |--workingdirectory <currentworkingdirectory>", "Working directory the new script file to be created. Defaults to current directory.", CommandOptionType.SingleValue); c.HelpOption(helpOptionTemplate); c.OnExecute(() => { var logFactory = CreateLogFactory(verbosity.Value(), debugMode.HasValue()); var scaffolder = new Scaffolder(logFactory); if (fileNameArgument.Value == null) { c.ShowHelp(); return(0); } scaffolder.CreateNewScriptFile(fileNameArgument.Value, cwd.Value() ?? Directory.GetCurrentDirectory()); return(0); }); }); app.Command("publish", c => { c.Description = "Creates a self contained executable or DLL from a script"; var fileNameArgument = c.Argument("filename", "The script file name"); var publishDirectoryOption = c.Option("-o |--output", "Directory where the published executable should be placed. Defaults to a 'publish' folder in the current directory.", CommandOptionType.SingleValue); var dllName = c.Option("-n |--name", "The name for the generated DLL (executable not supported at this time). Defaults to the name of the script.", CommandOptionType.SingleValue); var dllOption = c.Option("--dll", "Publish to a .dll instead of an executable.", CommandOptionType.NoValue); var commandConfig = c.Option("-c | --configuration <configuration>", "Configuration to use for publishing the script [Release/Debug]. Default is \"Debug\"", CommandOptionType.SingleValue); var runtime = c.Option("-r |--runtime", "The runtime used when publishing the self contained executable. Defaults to your current runtime.", CommandOptionType.SingleValue); c.HelpOption(helpOptionTemplate); c.OnExecute(() => { if (fileNameArgument.Value == null) { c.ShowHelp(); return(0); } var options = new PublishCommandOptions ( new ScriptFile(fileNameArgument.Value), publishDirectoryOption.Value(), dllName.Value(), dllOption.HasValue() ? PublishType.Library : PublishType.Executable, commandConfig.ValueEquals("release", StringComparison.OrdinalIgnoreCase) ? OptimizationLevel.Release : OptimizationLevel.Debug, packageSources.Values?.ToArray(), runtime.Value() ?? ScriptEnvironment.Default.RuntimeIdentifier, nocache.HasValue() ); var logFactory = CreateLogFactory(verbosity.Value(), debugMode.HasValue()); new PublishCommand(ScriptConsole.Default, logFactory).Execute(options); return(0); }); }); app.Command("exec", c => { c.Description = "Run a script from a DLL."; var dllPath = c.Argument("dll", "Path to DLL based script"); var commandDebugMode = c.Option(DebugFlagShort + " | " + DebugFlagLong, "Enables debug output.", CommandOptionType.NoValue); c.HelpOption(helpOptionTemplate); c.OnExecute(async() => { if (string.IsNullOrWhiteSpace(dllPath.Value)) { c.ShowHelp(); return(0); } var options = new ExecuteLibraryCommandOptions ( dllPath.Value, app.RemainingArguments.Concat(argsAfterDoubleHyphen).ToArray(), nocache.HasValue() ); var logFactory = CreateLogFactory(verbosity.Value(), debugMode.HasValue()); return(await new ExecuteLibraryCommand(ScriptConsole.Default, logFactory).Execute <int>(options)); }); }); app.OnExecute(async() => { int exitCode = 0; var scriptFile = new ScriptFile(file.Value); var optimizationLevel = configuration.ValueEquals("release", StringComparison.OrdinalIgnoreCase) ? OptimizationLevel.Release : OptimizationLevel.Debug; var scriptArguments = app.RemainingArguments.Concat(argsAfterDoubleHyphen).ToArray(); var logFactory = CreateLogFactory(verbosity.Value(), debugMode.HasValue()); if (infoOption.HasValue()) { var environmentReporter = new EnvironmentReporter(logFactory); await environmentReporter.ReportInfo(); return(0); } if (scriptFile.HasValue) { if (interactive.HasValue()) { return(await RunInteractiveWithSeed(file.Value, logFactory, scriptArguments, packageSources.Values?.ToArray())); } var fileCommandOptions = new ExecuteScriptCommandOptions ( new ScriptFile(file.Value), scriptArguments, optimizationLevel, packageSources.Values?.ToArray(), interactive.HasValue(), nocache.HasValue() ); var fileCommand = new ExecuteScriptCommand(ScriptConsole.Default, logFactory); return(await fileCommand.Run <int, CommandLineScriptGlobals>(fileCommandOptions)); } else { await RunInteractive(!nocache.HasValue(), logFactory, packageSources.Values?.ToArray()); } return(exitCode); }); return(app.Execute(argsBeforeDoubleHyphen)); }
public abstract void DeleteFile(ScriptFile file);
/// <summary> /// Resolve the CodeLens provision asynchronously -- just wraps the CodeLens argument in a task. /// </summary> /// <param name="codeLens">The code lens to resolve.</param> /// <param name="scriptFile">The script file.</param> /// <returns>The given CodeLens, wrapped in a task.</returns> public CodeLens ResolveCodeLens(CodeLens codeLens, ScriptFile scriptFile) { // This provider has no specific behavior for // resolving CodeLenses. return(codeLens); }
private CodeCompletionKeyHandler(ScriptFile mainForm, TextEditorControl editor) { this.mainForm = mainForm; this.editor = editor; }
private static async Task DelayThenInvokeDiagnostics( int delayMilliseconds, ScriptFile[] filesToAnalyze, EditorSession editorSession, EventContext eventContext, CancellationToken cancellationToken) { // First of all, wait for the desired delay period before // analyzing the provided list of files try { await Task.Delay(delayMilliseconds, cancellationToken); } catch (TaskCanceledException) { // If the task is cancelled, exit directly return; } // If we've made it past the delay period then we don't care // about the cancellation token anymore. This could happen // when the user stops typing for long enough that the delay // period ends but then starts typing while analysis is going // on. It makes sense to send back the results from the first // delay period while the second one is ticking away. // Get the requested files foreach (ScriptFile scriptFile in filesToAnalyze) { Logger.Write(LogLevel.Verbose, "Analyzing script file: " + scriptFile.FilePath); var semanticMarkers = editorSession.AnalysisService.GetSemanticMarkers( scriptFile); var allMarkers = scriptFile.SyntaxMarkers.Concat(semanticMarkers); await PublishScriptDiagnostics( scriptFile, semanticMarkers, eventContext); } Logger.Write(LogLevel.Verbose, "Analysis complete."); }
private void UpdateDatabaseVersion(string databaseName, ScriptFile script) { const string alterGetSchemaVersion = @" ALTER FUNCTION m.GetSchemaVersion ( ) RETURNS VARCHAR(32) AS BEGIN RETURN '{0}' END"; const string insertVersion = @" IF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'm' AND TABLE_NAME = 'Upgrade' AND TABLE_TYPE = 'BASE TABLE' ) BEGIN CREATE TABLE m.Upgrade ( ScriptName NVARCHAR(256) NOT NULL ,UtcUpgraded DATETIME NOT NULL ,CONSTRAINT PK_SchemasUpgrade PRIMARY KEY (ScriptName) ) END INSERT m.Upgrade (UtcUpgraded,ScriptName) VALUES (@UtcUpgraded,@ScriptName) "; using (var conn = OpenConnection(databaseName)) { using (var cmd = new SqlCommand()) { cmd.Connection = conn; cmd.CommandText = string.Format(alterGetSchemaVersion, script.Version); cmd.ExecuteNonQuery(); cmd.CommandText = insertVersion; cmd.Parameters.AddWithValue("@UtcUpgraded", DateTime.UtcNow); cmd.Parameters.AddWithValue("@ScriptName", Path.GetFileName(script.FilePath)); cmd.ExecuteNonQuery(); } } }
public ScriptableCampaign(string scriptFileName) { scriptFile = new ScriptFile(scriptFileName); scriptFile.Parse(ResourceGroupManager.DEFAULT_RESOURCE_GROUP_NAME); }
/// <summary> /// Retrieves the build script contained in the given file. /// </summary> /// <param name="file">The file containing a build script</param> /// <returns>A build script.</returns> protected async Task<ScriptFile> GetScriptAsync(FileInfo file) { // Parse file name and path var typeName = file.Directory.Name; var schemaName = file.Directory.Parent.Name; var fileName = Path.GetFileNameWithoutExtension(file.FullName); if(!objectTypes.ContainsKey(typeName)) { return new ScriptFile(new DatabaseObject(ServerName, DatabaseName, schemaName.TrimObjectName(), fileName.TrimObjectName()), new UnexpectedObjectTypeError(typeName)); } var objectType = objectTypes[typeName]; var dbObject = new TypedDatabaseObject(ServerName, DatabaseName, schemaName.TrimObjectName(), fileName.TrimObjectName(), objectType); // Read file contents string content; try { using (var fileInputStream = file.OpenRead()) { using (var fileReader = new StreamReader(fileInputStream)) { content = await fileReader.ReadToEndAsync(); } } } catch (Exception) { return new ScriptFile(dbObject, GetDropScript(dbObject), sqlParser); } // Parse script file var script = new ScriptFile(dbObject, content, sqlParser); return script; }
public static void Deconstruct(string plFilePath, string ajFilePath, string outputFolder) { var plfile = new HSDRawFile(plFilePath); var path = Path.GetDirectoryName(plFilePath) + "\\" + outputFolder + "\\"; Directory.CreateDirectory(path); var data = plfile.Roots[0].Data as SBM_FighterData; if (data == null) { return; } var ajfile = new HSDRawFile(ajFilePath); foreach (var prop in data.GetType().GetProperties()) { var val = prop.GetValue(data) as HSDAccessor; if (val == null) { continue; } if (prop.PropertyType == typeof(SBM_CommonFighterAttributes)) { var attr = prop.GetValue(data) as SBM_CommonFighterAttributes; using (StreamWriter w = new StreamWriter(new FileStream(path + prop.Name + ".ini", FileMode.Create))) { foreach (var v in attr.GetType().GetProperties()) { if (v.Name.Equals("TrimmedSize")) { continue; } w.WriteLine($"{v.Name}={v.GetValue(attr)}"); } } } else if (prop.Name.Equals("SubActionTable")) { ScriptFile f = new ScriptFile(); f.Actions = new ActionGroup[val._s.Length / 0x18]; var ActionDecompiler = new ActionDecompiler(); HashSet <string> ExportedAnimations = new HashSet <string>(); for (int i = 0; i < f.Actions.Length; i++) { SBM_FighterCommand subaction = new HSDRaw.Melee.Pl.SBM_FighterCommand(); subaction._s = val._s.GetEmbeddedStruct(0x18 * i, 0x18); if (!ExportedAnimations.Contains(subaction.Name) && subaction.Name != null && subaction.Name != "") { ExportedAnimations.Add(subaction.Name); if (ajFilePath != null && File.Exists(ajFilePath)) { using (BinaryReaderExt r = new BinaryReaderExt(new FileStream(ajFilePath, FileMode.Open))) { var animdata = r.GetSection((uint)subaction.AnimationOffset, subaction.AnimationSize); File.WriteAllBytes(path + "Animations\\" + subaction.Name + ".dat", animdata); } } } ActionGroup g = new ActionGroup(); g.animation_name = subaction.Name; g.flags = (int)subaction.Flags; g.script = ActionDecompiler.Decompile("Func_" + i.ToString("X3"), subaction.SubAction); //g.script = g.off = subaction.AnimationOffset; g.size = subaction.AnimationSize; f.Actions[i] = g; Console.WriteLine(i + " " + subaction.Name + " " + subaction._s.GetReference <HSDAccessor>(0x0C)._s.References.Count); } XmlSerializer writer = new XmlSerializer(typeof(ScriptFile)); using (var w = new XmlTextWriter(new FileStream(path + prop.Name + ".txt", FileMode.Create), Encoding.UTF8)) { w.Formatting = Formatting.Indented; writer.Serialize(w, f); } } else { HSDRootNode root = new HSDRootNode(); root.Name = prop.Name; root.Data = val; HSDRawFile file = new HSDRawFile(); file.Roots.Add(root); file.Save(path + prop.Name + ".dat"); Console.WriteLine(prop.Name + " " + val._s.GetSubStructs().Count); } } }
private void ReadScripts() { _scripts = new List<ScriptFile>(); var currentVersion = GetDatabaseVersion(DatabaseName); var files = Directory.GetFiles(ScriptPath, "*.sql"); var regex = new Regex(Constants.ScriptFileNamePattern); foreach (var filePath in files) { LogHelper.WriteLine("Reading script " + filePath + "..."); var fileName = Path.GetFileName(filePath); if (fileName == null) throw new NullReferenceException("Invalid File Name: " + filePath); var match = regex.Match(fileName); if (!match.Success) continue; var version = match.Groups[1].Value; if (string.Compare(version, currentVersion, StringComparison.CurrentCulture) <= 0) continue; var script = new ScriptFile { FilePath = filePath, Version = version }; _scripts.Add(script); } _scripts.Sort((s1, s2) => string.Compare(s1.Version, s2.Version, StringComparison.Ordinal)); }