internal static string FormatSingleLineDirect(PSObject obj, ScriptBlock script, PsContext ctx) { string val; using (FormatAltSingleLineCommand cmd = new FormatAltSingleLineCommand()) { val = cmd.RenderScriptValue(obj, script, false, ctx); } // TODO: What to do if it spans more than a line? Just truncate? Issue a // warning? Add "..."? Also, consider that the view definition might have been // generated. if (null == val) { return(String.Empty); } else { int idx = CaStringUtil.ApparentIndexOf(val, '\n'); if (idx < 0) { return(val); } else { return(CaStringUtil.Truncate(val, idx)); } } } // end FormatSingleLineDirect
public ScriptColumn(string label, ScriptBlock script, ColumnAlignment alignment, int width, string tag, TrimLocation trimLocation, bool captureContext) : base(alignment, width, tag, trimLocation) { if (String.IsNullOrEmpty(label)) { throw new ArgumentException("You must supply a column label.", "label"); } if (null == script) { throw new ArgumentNullException("script"); } m_label = label; Script = script; if (captureContext) { Context = DbgProvider.CapturePsContext(); } } // end constructor
// Allows customization of the GroupBy header used between different groups. protected virtual ScriptBlock GetCustomWriteGroupByGroupHeaderScript( out PsContext context, out bool preserveHeaderContext) { context = null; preserveHeaderContext = false; return(null); }
} // end ResetState() protected override ScriptBlock GetCustomWriteGroupByGroupHeaderScript( out PsContext context, out bool preserveHeaderContext) { Util.Assert(null != m_view); context = m_view.Context; preserveHeaderContext = m_view.PreserveHeaderContext; return(m_view.ProduceGroupByHeader); }
public async Task <ActionResult <User> > GetUser(ulong id) { using (var db = new PsContext()) { var user = db.Users.FirstOrDefault(x => x.Id.Equals(id)); if (user != null) { return(Ok(user)); } } return(StatusCode(404, "User not found")); }
public AltSingleLineViewDefinition(ScriptBlock script, bool captureContext) { if (null == script) { throw new ArgumentNullException("script"); } Script = script; if (captureContext) { Context = DbgProvider.CapturePsContext(); } } // end constructor
private void _WriteGroupByGroupHeader(object newResult, bool isDefaultGroupBy) { PsContext headerCtx; bool preserveHeaderContext; ScriptBlock customHeaderScript = GetCustomWriteGroupByGroupHeaderScript(out headerCtx, out preserveHeaderContext); if (null != customHeaderScript) { // ISSUE: Or maybe the group-by evaluation functions should return a // PSObject instead. PSObject pso = newResult as PSObject; if ((null == pso) && (null != newResult)) { pso = new PSObject(newResult); // you can't pass null to the PSObject constructor. } using (var pch = new PsContextHelper(customHeaderScript, headerCtx, preserveHeaderContext)) { string val = RenderScriptValue(pso, pch.AdjustedScriptBlock, true, pch.WithContext); m_groupByHeaderCtx = pch.SavedContext; if (null != val) { WriteObject(val); } } } else if (isDefaultGroupBy) { // If something makes sense to be the default group by, it's probably clear what it is from context without a special label // And we probably don't want indentation & blank lines surrounding something that is printed all the time WriteObject(ObjectToMarkedUpString(newResult).ToString()); } else { WriteObject(String.Empty); WriteObject(new ColorString(" ") //.AppendPushFgBg( ConsoleColor.Black, ConsoleColor.Cyan ) //.AppendPushFg( ConsoleColor.Cyan ) .AppendPushFgBg(ConsoleColor.Black, ConsoleColor.White) .Append(m_groupByLabel) .AppendPop() .Append(": ") .Append(ObjectToMarkedUpString(newResult).ToString()) .ToString(DbgProvider.HostSupportsColor)); WriteObject(String.Empty); } } // end _WriteGroupByGroupHeader()
public Footer(ColumnAlignment alignment, ScriptBlock script, bool captureContext) { if (null == script) { throw new ArgumentNullException("script"); } Alignment = alignment; Script = script; if (captureContext) { Context = DbgProvider.CapturePsContext(); } }
} // end constructor /// <summary> /// Pure assignment constructor--does not copy columns. /// </summary> internal AltTableViewDefinition(Column[] columns, Footer footer, ScriptBlock produceGroupByHeader, object groupBy, PsContext context, bool preserveHeaderContext) { m_columns = columns; m_roColumns = new ReadOnlyCollection <Column>(m_columns); Footer = footer; ProduceGroupByHeader = produceGroupByHeader; GroupBy = groupBy; Context = context; PreserveHeaderContext = preserveHeaderContext; } // end constructor
private void _WriteGroupByGroupHeader(object newResult) { PsContext headerCtx; bool preserveHeaderContext; ScriptBlock customHeaderScript = GetCustomWriteGroupByGroupHeaderScript(out headerCtx, out preserveHeaderContext); if (null != customHeaderScript) { // ISSUE: Or maybe the group-by evaluation functions should return a // PSObject instead. PSObject pso = newResult as PSObject; if ((null == pso) && (null != newResult)) { pso = new PSObject(newResult); // you can't pass null to the PSObject constructor. } using (var pch = new PsContextHelper(customHeaderScript, headerCtx, preserveHeaderContext)) { string val = RenderScriptValue(pso, pch.AdjustedScriptBlock, true, pch.WithContext); m_groupByHeaderCtx = pch.SavedContext; if (null != val) { WriteObject(val); } } } else { WriteObject(String.Empty); WriteObject(new ColorString(" ") //.AppendPushFgBg( ConsoleColor.Black, ConsoleColor.Cyan ) //.AppendPushFg( ConsoleColor.Cyan ) .AppendPushFgBg(ConsoleColor.Black, ConsoleColor.White) .Append(m_groupByLabel) .AppendPop() .Append(": ") .Append(ObjectToMarkedUpString(newResult).ToString()) .ToString(DbgProvider.HostSupportsColor)); WriteObject(String.Empty); } } // end _WriteGroupByGroupHeader()
protected override void ApplyViewToInputObject() { string val; using (var pch = new PsContextHelper(m_view.Script, m_view.Context + m_preservedScriptContext, m_view.PreserveScriptContext)) { val = RenderScriptValue(InputObject, pch.AdjustedScriptBlock, true, pch.WithContext); if (m_view.PreserveScriptContext) { m_preservedScriptContext += pch.SavedContext; } } if (null != val) { WriteObject(val); } } // end ProcessRecord()
public AltListViewDefinition(IReadOnlyList <ListItem> listItems, ScriptBlock produceGroupByHeader, object groupBy, bool captureContext, bool preserveHeaderContext) { if (null == listItems) { throw new ArgumentNullException("listItems"); } ListItems = listItems; ProduceGroupByHeader = produceGroupByHeader; GroupBy = groupBy; PreserveHeaderContext = preserveHeaderContext; if (captureContext) { Context = DbgProvider.CapturePsContext(); } } // end constructor
} // end InvokeScript internal static Collection <PSObject> InvokeWithContext(ScriptBlock scriptBlock, PsContext withContext, PSReference saveContext) { if (null == withContext) { withContext = new PsContext(); // TODO: share a single, readonly Empty context } using (var ctxHelper = new PsContextHelper(scriptBlock, withContext, null != saveContext)) { // TODO: Should I switch to using shell.AddScript, like in FormatBaseCommand.cs? var results = ctxHelper.AdjustedScriptBlock.InvokeWithContext(ctxHelper.WithContext.Funcs, ctxHelper.WithContext.VarList); if (null != saveContext) { saveContext.Value = ctxHelper.SavedContext; } return(results); } // end using( ctxHelper ) } // end InvokeWithContext
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseMvc(); // Run migrations Console.WriteLine("Running migrations"); using (var db = new PsContext()) { RelationalDatabaseFacadeExtensions.Migrate(db.Database); } }
public ScriptListItem(string label, ScriptBlock script, bool captureContext) { if (String.IsNullOrEmpty(label)) { throw new ArgumentException("You must supply a label.", "label"); } if (null == script) { throw new ArgumentNullException("script"); } m_label = label; Script = script; if (captureContext) { Context = DbgProvider.CapturePsContext(); } else { Context = new PsContext(); } } // end constructor
public AltCustomViewDefinition(ScriptBlock script, ScriptBlock produceGroupByHeader, object groupBy, ScriptBlock end, bool captureContext, bool preserveHeaderContext, bool preserveScriptContext) { if (null == script) { throw new ArgumentNullException("script"); } Script = script; ProduceGroupByHeader = produceGroupByHeader; GroupBy = groupBy; End = end; PreserveHeaderContext = preserveHeaderContext; PreserveScriptContext = preserveScriptContext; if (captureContext) { Context = DbgProvider.CapturePsContext(); } } // end constructor
protected string RenderScriptValue(PSObject inputObject, ScriptBlock script, bool dontGroupMultipleResults, PsContext context) { // Let the script also use context created by the custom header script (if any). context = context + m_groupByHeaderCtx; Collection <PSObject> results = null; if (null == context) { context = new PsContext(); } if (null == m_pipeIndexPSVar) { m_pipeIndexPSVar = new PipeIndexPSVariable(this); } context.Vars["_"] = new PSVariable("_", inputObject); context.Vars["PSItem"] = new PSVariable("PSItem", inputObject); context.Vars["PipeOutputIndex"] = m_pipeIndexPSVar; PowerShell shell; using (DbgProvider.LeaseShell(out shell)) { #if DEBUG sm_renderScriptCallDepth++; if (sm_renderScriptCallDepth > 10) { // Helps to catch runaway rendering /before/ gobbling tons of memory System.Diagnostics.Debugger.Break(); // Maybe I should just throw? } #endif // // This code is a lot nicer-looking. But the problem with it is that non- // terminating errors get squelched (there's no way for us to get them), // and I'd prefer that no errors get hidden. Strangely, non-terminating // errors do NOT get squelched when calling script.InvokeWithContext // directly in InvokeScriptCommand.InvokeWithContext. I don't know what is // making the difference. I thought it might have something to do with the // SessionState attached to the ScriptBlock, but I couldn't demonstrate // that. // // Things to try with both methods: // // $ctx = $null // $savedCtx = $null // Invoke-Script -ScriptBlock { "hi" ; Write-Error "non-term" ; "bye" } -WithContext $ctx // // { "hi" ; Write-Error "non-term" ; "bye" }.InvokeWithContext( @{}, @() ) // // $tmpMod = New-Module { } // $scriptBlockWithDifferentExecCtx = & $tmpMod { { "hi" ; Write-Error "non-term" ; "bye" } } // $scriptBlockWithDifferentExecCtx.InvokeWithContext( @{}, @() ) // // Register-AltTypeFormatEntries { New-AltTypeFormatEntry -TypeName 'System.Int32' { New-AltCustomViewDefinition { "It's an int: $_" ; Write-Error "this is non-terminating" ; "done" } } } // 42 // // try // { // // Note that StrictMode will be enforced for value converters, because // // they execute in the scope of Debugger.Formatting.psm1, which sets // // StrictMode. // results = script.InvokeWithContext( context.Funcs, context.VarList ); // } // catch( RuntimeException e ) // { // return new ColorString( ConsoleColor.Red, // Util.Sprintf( "<Error: {0}>", e ) ) // .ToString( DbgProvider.HostSupportsColor ); // } shell.AddScript(@"$args[ 0 ].InvokeWithContext( $args[ 1 ].Funcs, $args[ 1 ].VarList )", true) .AddArgument(script) .AddArgument(context); results = shell.Invoke(); // Let's not keep the input object rooted. context.Vars.Remove("_"); context.Vars.Remove("PSItem"); #if DEBUG sm_renderScriptCallDepth--; #endif // For some reason, sometimes shell.HadErrors returns true when // shell.Streams.Error.Count is 0, when the pipeline is stopping. if (Stopping) { return(String.Empty); } // INT2d518c4b: shell.HadErrors is clueless. //if( shell.HadErrors ) if (shell.Streams.Error.Count > 0) { if (1 == shell.Streams.Error.Count) { return(new ColorString(ConsoleColor.Red, Util.Sprintf("<Error: {0}>", shell.Streams.Error[0])) .ToString(DbgProvider.HostSupportsColor)); } else { return(new ColorString(ConsoleColor.Red, Util.Sprintf("<Multiple errors ({0}) encountered>", shell.Streams.Error.Count)) .ToString(DbgProvider.HostSupportsColor)); } } else { if ((null == results) || (0 == results.Count)) { return(null); } return(ObjectsToMarkedUpString(results, "{0}", // <-- IMPORTANT: this prevents infinite recursion via Format-AltSingleLine null, dontGroupMultipleResults).ToString()); } // end else( no errors ) } // end using( shell lease ) } // end RenderScriptValue()
/// <summary> /// Returns null if the script returned no results. /// </summary> protected string RenderScriptValue(PSObject inputObject, ScriptBlock script, PsContext context) { return(RenderScriptValue(inputObject, script, false, context)); }
} // end _EvaluateCalculatedPropertyGroupBy() private object _EvaluateScriptGroupBy() { var script = (ScriptBlock)GroupBy; Collection <PSObject> results = null; // TODO: this is pretty awkward. These things should probably be split out // into individual properties. PsContext context; bool dontCare; var alsoDontCare = GetCustomWriteGroupByGroupHeaderScript(out context, out dontCare); if (null == context) { context = new PsContext(); } context.Vars["_"] = new PSVariable("_", InputObject); context.Vars["PSItem"] = new PSVariable("PSItem", InputObject); try { // Note that StrictMode will be enforced for value converters, because // they execute in the scope of Debugger.Formatting.psm1, which sets // StrictMode. results = script.InvokeWithContext(context.Funcs, context.VarList); } catch (RuntimeException re) { LogManager.Trace("Ignoring error in _EvaluateScriptGroupBy: {0}", Util.GetExceptionMessages(re)); } // Let's not keep the input object rooted. context.Vars.Remove("_"); context.Vars.Remove("PSItem"); // PowerShell shell; // using( DbgProvider.LeaseShell( out shell ) ) // { // // Note that StrictMode will be enforced for value converters, because // // they execute in the scope of Debugger.Formatting.psm1, which sets // // StrictMode. // shell.AddScript( @"args[ 0 ].InvokeWithContext( $args[ 1 ].Funcs, $args[ 1 ].VarList )", // true ) // .AddArgument( script ) // .AddArgument( context ); // results = shell.Invoke(); // } // I guess we don't care if errors were encountered, as long as it produced output? if (Stopping || (null == results) || (0 == results.Count)) { return(null); } else if (1 == results.Count) { return(results[0].BaseObject); } else { var list = new List <object>(results.Count); list.AddRange(results.Select((r) => r.BaseObject)); return(list); } } // end _EvaluateScriptGroupBy()