Here are the examples of the csharp api System.Diagnostics.Debugger.Break() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
538 Examples
19
Source : DebugProgramTemplate.cs
with MIT License
from 71
with MIT License
from 71
public static int Main(string[] args)
{
try
{
Diagnosticreplacedyzer replacedyzer = new Cometaryreplacedyzer();
CSharpParseOptions parseOptions = new CSharpParseOptions(preprocessorSymbols: new[] { "DEBUGGING" });
if (IsWrittenToDisk && ShouldBreakAtStart)
Debugger.Break();
CompilationWithreplacedyzers compilation = CSharpCompilation.Create(
replacedemblyName + "+Debugging",
Files.Split(';').Select(x => CSharpSyntaxTree.ParseText(File.ReadAllText(x), parseOptions)),
References.Split(';').Select(x => MetadataReference.CreateFromFile(x))
).Withreplacedyzers(ImmutableArray.Create(replacedyzer));
ExecuteAsync(compilation).Wait();
return 0;
}
catch (Exception e)
{
Console.Error.WriteLine(e.Message);
Console.Error.WriteLine();
Console.Error.WriteLine(e.StackTrace);
Console.ReadKey();
return 1;
}
}
19
Source : DebugProgramTemplate.cs
with MIT License
from 71
with MIT License
from 71
public static void Success(Diagnostic[] diagnostics)
{
// If you got here, that means the compilation was a success!
//
Debugger.Break();
}
19
Source : DebugProgramTemplate.cs
with MIT License
from 71
with MIT License
from 71
public static void Failure(Diagnostic[] diagnostics, string[] errors)
{
// If you got here, that means the compilation failed...
// You can inspect the errors via the debugger, or in the error file available at:
// %ERRORFILE%
//
Debugger.Break();
}
19
Source : Contract.cs
with MIT License
from abdullin
with MIT License
from abdullin
[DebuggerStepThrough, DebuggerHidden]
internal static void RaiseContractFailure(SDC.ContractFailureKind kind, string message, string file, int line)
{
if (message == null)
{
switch (kind)
{
case SDC.ContractFailureKind.replacedert: message = "An replacedertion was not met"; break;
case SDC.ContractFailureKind.Precondition: message = "A pre-requisite was not met"; break;
case SDC.ContractFailureKind.Postcondition: message = "A post-condition was not met"; break;
default: message = "An expectation was not met"; break;
}
}
if (file != null)
{ // add the caller infos
message = String.Format("{0} in {1}:line {2}", message, file, line);
}
//TODO: check if we are running under NUnit, and map to an replacedert.Fail() instead ?
Debug.Fail(message);
// If you break here, that means that an replacedertion failed somewhere up the stack.
// TODO: find a way to have the debugger break, but show the caller of Contract.replacedert(..) method, instead of here ?
if (Debugger.IsAttached) Debugger.Break();
throw new InvalidOperationException(message);
}
19
Source : Program.cs
with MIT License
from actions
with MIT License
from actions
private static async Task WaitForDebugger(Tracing trace)
{
trace.Info($"Waiting for a debugger to be attached. Edit the 'GITHUB_ACTIONS_RUNNER_ATTACH_DEBUGGER' environment variable to toggle this feature.");
int waitInSeconds = 20;
while (!Debugger.IsAttached && waitInSeconds-- > 0)
{
trace.Info($"Waiting for a debugger to be attached. {waitInSeconds} seconds left.");
await Task.Delay(1000);
}
Debugger.Break();
}
19
Source : MainWindow.xaml.cs
with MIT License
from ADeltaX
with MIT License
from ADeltaX
private void treeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
if (e.NewValue == e.OldValue)
return;
keyVals.Clear();
void PopulateListView(RegistryKey registryKey, RegistryHive registryBase)
{
if (registryKey.ValueCount > 0)
{
foreach (var keyval in registryKey.GetValueNames())
{
keyVals.Add(new KeyVal
{
Name = keyval,
DataTypeEnum = (DataTypeEnum)registryKey.GetValueType(keyval),
Data = registryKey.GetValueRaw(keyval),
Path = registryKey.Name,
Hive = registryBase
});
}
}
}
if (e.NewValue is RegistryKeyTreeView registryKeyTreeView)
{
RegistryKey currKey = registryKeyTreeView.AttachedHive.Root.OpenSubKey(registryKeyTreeView.Path);
if (currKey == null)
Debugger.Break();
currentPathTxt.Text = "Computer" + "\\" + registryKeyTreeView.Root.Name + "\\" + registryKeyTreeView.Path;
selectedIconImage.Source = registryKeyTreeView.ImageSource;
PopulateListView(currKey, registryKeyTreeView.AttachedHive);
}
else if (e.NewValue is RegistryHiveTreeView registryHiveTreeView)
{
RegistryKey currKey = registryHiveTreeView.AttachedHive.Root;
currentPathTxt.Text = "Computer" + "\\" + registryHiveTreeView.Name;
selectedIconImage.Source = new BitmapImage(new Uri("replacedets/RegistryIcon.png", UriKind.Relative));
PopulateListView(currKey, registryHiveTreeView.AttachedHive);
}
else
{
currentPathTxt.Text = "Computer";
selectedIconImage.Source = computerBitmap;
}
}
19
Source : ConsoleDriver.cs
with MIT License
from allisterb
with MIT License
from allisterb
public static void RunAndExit(string[] args)
{
if (args.Contains("--wait-for-attach"))
{
Console.WriteLine("Attach debugger and press any key to continue execution...");
Console.ReadKey(true);
if (!Debugger.IsAttached)
{
Console.WriteLine("No debugger detected! Exiting.");
return;
}
else
{
Debugger.Break();
}
}
if (args.Contains("--with-debug"))
{
WithDebugOutput = true;
}
if (args.Contains("--with-log-file"))
{
WithLogFile = true;
}
if (args.Contains("--without-console"))
{
WithoutConsole = true;
}
LoggerConfiguration = new LoggerConfiguration()
.Enrich.FromLogContext()
.Enrich.WithThreadId();
if (WithDebugOutput)
{
LoggerConfiguration = LoggerConfiguration.MinimumLevel.Debug();
}
if (!WithoutConsole)
{
LoggerConfiguration = LoggerConfiguration.WriteTo.Console(outputTemplate: "{Timestamp:HH:mm:ss} [{ThreadId:d2}][{Level:u3}] {Message}{NewLine}{Exception}");
}
if (WithLogFile)
{
LogFileName = Path.Combine("logs", "ClreplacedifyBot") + "-{Date}.log";
LoggerConfiguration = LoggerConfiguration.WriteTo.RollingFile(LogFileName, outputTemplate: "{Timestamp:HH:mm:ss}[{ThreadId:d2}] [{Level:u3}] {Message}{NewLine}{Exception}");
}
Log.Logger = LoggerConfiguration.CreateLogger();
L = Log.ForContext<Driver>();
ExitToEnvironment = true;
if (WithLogFile)
{
L.Information("Log file is at {0}.", LogFileName);
}
for (int i = 0; i < args.Length; i++)
{
if (args[i] == "-x" || args[i] == "--explicit")
{
if ((i + 1) <= args.Length - 1)
{
ExplicitreplacedemblyName = args[i + 1].StartsWith("ClreplacedifyBot.") ? args[i + 1] : "ClreplacedifyBot." + args[i + 1];
args = args.Except(new string[] { "-x", "--explicit", args[i + 1] }).ToArray();
}
else
{
L.Error("You must enter an replacedembly name to explicitly load. Valid replacedembly names are : {0}."
.F(string.Join(", ", AllLoadedreplacedemblies.Select(a => a.GetName().Name).ToArray())));
Exit(StageResult.INVALID_OPTIONS);
}
break;
}
}
StageResult result = MarshalOptionsForStage(args, ExplicitreplacedemblyName, out Stage stage, out string optionsHelp);
if (result == StageResult.INVALID_OPTIONS && stage == null && !optionsHelp.IsEmpty())
{
L.Information(optionsHelp);
}
else if (result == StageResult.CREATED && stage != null && optionsHelp.IsEmpty())
{
Exit(stage.Run());
}
else
{
throw new Exception("Unknown stage state {0} {1}.".F( result, stage));
}
}
19
Source : PasswordEntryControl.xaml.cs
with MIT License
from angelsix
with MIT License
from angelsix
public static void LabelWidthChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
try
{
// Set the column definition width to the new value
(d as PreplacedwordEntryControl).LabelColumnDefinition.Width = (GridLength)e.NewValue;
}
// Making ex available for developer on break
#pragma warning disable CS0168
catch (Exception ex)
#pragma warning restore CS0168
{
// Make developer aware of potential issue
Debugger.Break();
(d as PreplacedwordEntryControl).LabelColumnDefinition.Width = GridLength.Auto;
}
}
19
Source : TextEntryControl.xaml.cs
with MIT License
from angelsix
with MIT License
from angelsix
public static void LabelWidthChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
try
{
// Set the column definition width to the new value
(d as TextEntryControl).LabelColumnDefinition.Width = (GridLength)e.NewValue;
}
// Making ex available for developer on break
#pragma warning disable CS0168
catch (Exception ex)
#pragma warning restore CS0168
{
// Make developer aware of potential issue
Debugger.Break();
(d as TextEntryControl).LabelColumnDefinition.Width = GridLength.Auto;
}
}
19
Source : ApplicationPageHelpers.cs
with MIT License
from angelsix
with MIT License
from angelsix
public static BasePage ToBasePage(this ApplicationPage page, object viewModel = null)
{
// Find the appropriate page
switch (page)
{
case ApplicationPage.Login:
return new LoginPage(viewModel as LoginViewModel);
case ApplicationPage.Register:
return new RegisterPage(viewModel as RegisterViewModel);
case ApplicationPage.Chat:
return new ChatPage(viewModel as ChatMessageListViewModel);
default:
Debugger.Break();
return null;
}
}
19
Source : ApplicationPageHelpers.cs
with MIT License
from angelsix
with MIT License
from angelsix
public static ApplicationPage ToApplicationPage(this BasePage page)
{
// Find application page that matches the base page
if (page is ChatPage)
return ApplicationPage.Chat;
if (page is LoginPage)
return ApplicationPage.Login;
if (page is RegisterPage)
return ApplicationPage.Register;
// Alert developer of issue
Debugger.Break();
return default(ApplicationPage);
}
19
Source : AsyncAwaiter.cs
with MIT License
from angelsix
with MIT License
from angelsix
public static async Task AwaitAsync(string key, Func<Task> task, int maxAccessCount = 1)
{
#region Create Semapreplaced
//
// Asynchronously wait to enter the Semapreplaced
//
// If no-one has been granted access to the Semapreplaced
// code execution will proceed
// Otherwise this thread waits here until the semapreplaced is released
//
await SelfLock.WaitAsync();
try
{
// Create semapreplaced if it doesn't already exist
if (!Semapreplaceds.ContainsKey(key))
Semapreplaceds.Add(key, new SemapreplacedSlim(maxAccessCount, maxAccessCount));
}
finally
{
//
// When the task is ready, release the semapreplaced
//
// It is vital to ALWAYS release the semapreplaced when we are ready
// or else we will end up with a Semapreplaced that is forever locked
// This is why it is important to do the Release within a try...finally clause
// Program execution may crash or take a different path, this way you are guaranteed execution
//
SelfLock.Release();
}
#endregion
// Now use this semapreplaced and perform the desired task inside its lock
// NOTE: We never remove semapreplaceds after creating them, so this will never be null
var semapreplaced = Semapreplaceds[key];
// Await this semapreplaced
await semapreplaced.WaitAsync();
try
{
// Perform the job
await task();
}
catch (Exception ex)
{
// Get error message
var error = ex.Message;
// Log message to debug level
// (may not be an issue but we don't want to miss anything in debug)
Logger.LogDebugSource($"Crash in {nameof(AwaitAsync)}. {ex.Message}");
// Break debugger
Debugger.Break();
// Bubble exception up as normal
throw;
}
finally
{
// Release the semapreplaced
semapreplaced.Release();
}
}
19
Source : SendGridEmailSender.cs
with MIT License
from angelsix
with MIT License
from angelsix
public async Task<SendEmailResponse> SendEmailAsync(SendEmailDetails details)
{
// Get the SendGrid key
var apiKey = Configuration["SendGridKey"];
// Create a new SendGrid client
var client = new SendGridClient(apiKey);
// From
var from = new EmailAddress(details.FromEmail, details.FromName);
// To
var to = new EmailAddress(details.ToEmail, details.ToName);
// Subject
var subject = details.Subject;
// Content
var content = details.Content;
// Create Email clreplaced ready to send
var msg = MailHelper.CreateSingleEmail(
from,
to,
subject,
// Plain content
details.IsHTML ? null : details.Content,
// HTML content
details.IsHTML ? details.Content : null);
// Finally, send the email...
var response = await client.SendEmailAsync(msg);
// If we succeeded...
if (response.StatusCode == System.Net.HttpStatusCode.Accepted)
// Return successful response
return new SendEmailResponse();
// Otherwise, it failed...
try
{
// Get the result in the body
var bodyResult = await response.Body.ReadreplacedtringAsync();
// Deserialize the response
var sendGridResponse = JsonConvert.DeserializeObject<SendGridResponse>(bodyResult);
// Add any errors to the response
var errorResponse = new SendEmailResponse
{
Errors = sendGridResponse?.Errors.Select(f => f.Message).ToList()
};
// Make sure we have at least one error
if (errorResponse.Errors == null || errorResponse.Errors.Count == 0)
// Add an unknown error
// TODO: Localization
errorResponse.Errors = new List<string>(new[] { "Unknown error from email sending service. Please contact Fasetto support." });
// Return the response
return errorResponse;
}
catch (Exception ex)
{
// TODO: Localization
// Break if we are debugging
if (Debugger.IsAttached)
{
var error = ex;
Debugger.Break();
}
// If something unexpected happened, return message
return new SendEmailResponse
{
Errors = new List<string>(new[] { "Unknown error occurred" })
};
}
}
19
Source : DnaSettings.cs
with MIT License
from angelsix
with MIT License
from angelsix
private static Platform GetPlatform()
{
// If windows...
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
// Return Windows 32/64bit
return RuntimeInformation.OSArchitecture == Architecture.X64 ? Platform.Windows64 : Platform.Windows32;
// If linux...
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
// Return Linux 32/64bit
return RuntimeInformation.OSArchitecture == Architecture.X64 ? Platform.Linux64 : Platform.Linux32;
// If osx...
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
// Return OSX
return Platform.Osx;
// Anything else is unknown
// Log it
CoreLogger.Log("Running on unknown architecture!", type: LogType.Error);
// Break to debugger
Debugger.Break();
// Return unknown
return Platform.Unknown;
}
19
Source : BaseEngine.cs
with MIT License
from angelsix
with MIT License
from angelsix
protected string[] GetConfigurationSearchPaths(string path)
{
// Get this files current directory
var currentDirectory = DnaConfiguration.ResolveFullPath(string.Empty, Path.GetDirectoryName(path), false, out bool wasRelative);
// If this path is not within the monitor path (somehow?) then just return this folder
if (!currentDirectory.StartsWith(ResolvedMonitorPath))
{
// Break for developer as this is unusual
Debugger.Break();
// Return the current files directory path configuration file
return new[] { Path.Combine(currentDirectory, DnaSettings.ConfigurationFileName) };
}
// If this file is within the monitor path (as it should always be)...
else
{
// New list of configuration files
var configurationFiles = new List<string>();
// Get all directories until we hit the monitor path
while (currentDirectory != ResolvedMonitorPath)
{
// Add the current folders configuration file
configurationFiles.Add(Path.Combine(currentDirectory, DnaSettings.ConfigurationFileName));
// Go up to next folder
currentDirectory = Path.GetDirectoryName(currentDirectory);
}
// Add the monitor path itself
configurationFiles.Add(Path.Combine(currentDirectory, DnaSettings.ConfigurationFileName));
// Reverse order so parents are first and children take priority (load after)
configurationFiles.Reverse();
// Return list
return configurationFiles.ToArray();
}
}
19
Source : BorderAttachedProperties.cs
with MIT License
from angelsix
with MIT License
from angelsix
public override void OnValueChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
// Get self
var self = (sender as FrameworkElement);
// Check we have a parent Border
if (!(self.Parent is Border border))
{
Debugger.Break();
return;
}
// Setup loaded event
mBorder_Loaded = (s1, e1) => Border_OnChange(s1, e1, self);
// Setup size changed event
mBorder_SizeChanged = (s1, e1) => Border_OnChange(s1, e1, self);
// If true, hook into events
if ((bool)e.NewValue)
{
border.Loaded += mBorder_Loaded;
border.SizeChanged += mBorder_SizeChanged;
}
// Otherwise, unhook
else
{
border.Loaded -= mBorder_Loaded;
border.SizeChanged -= mBorder_SizeChanged;
}
}
19
Source : App.xaml.cs
with MIT License
from anjoy8
with MIT License
from anjoy8
private void RootFrame_NavigationFailed(object sender, NavigationFailedEventArgs e)
{
if (Debugger.IsAttached)
{
// A navigation has failed; break into the debugger
Debugger.Break();
}
}
19
Source : App.xaml.cs
with MIT License
from anjoy8
with MIT License
from anjoy8
private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
if (Debugger.IsAttached)
{
// An unhandled exception has occurred; break into the debugger
Debugger.Break();
}
}
19
Source : App.xaml.cs
with MIT License
from anjoy8
with MIT License
from anjoy8
private void InitializeLanguage()
{
try
{
// Set the font to match the display language defined by the
// ResourceLanguage resource string for each supported language.
//
// Fall back to the font of the neutral language if the Display
// language of the phone is not supported.
//
// If a compiler error is hit then ResourceLanguage is missing from
// the resource file.
RootFrame.Language = XmlLanguage.GetLanguage(AppResources.ResourceLanguage);
// Set the FlowDirection of all elements under the root frame based
// on the ResourceFlowDirection resource string for each
// supported language.
//
// If a compiler error is hit then ResourceFlowDirection is missing from
// the resource file.
FlowDirection flow = (FlowDirection)Enum.Parse(typeof(FlowDirection), AppResources.ResourceFlowDirection);
RootFrame.FlowDirection = flow;
}
catch
{
// If an exception is caught here it is most likely due to either
// ResourceLangauge not being correctly set to a supported language
// code or ResourceFlowDirection is set to a value other than LeftToRight
// or RightToLeft.
if (Debugger.IsAttached)
{
Debugger.Break();
}
throw;
}
}
19
Source : Dbg.cs
with Apache License 2.0
from AnthonyLloyd
with Apache License 2.0
from AnthonyLloyd
public static void Break() => Debugger.Break();
19
Source : DbiScope.cs
with GNU General Public License v3.0
from anydream
with GNU General Public License v3.0
from anydream
public void Read(RecursionCounter counter, IImageStream stream, uint scopeEnd) {
if (!counter.Increment())
throw new PdbException("Scopes too deep");
while (stream.Position < scopeEnd) {
var size = stream.ReadUInt16();
var begin = stream.Position;
var end = begin + size;
var type = (SymbolType)stream.ReadUInt16();
DbiScope child = null;
uint? childEnd = null;
string name;
switch (type) {
case SymbolType.S_BLOCK32: {
stream.Position += 4;
childEnd = stream.ReadUInt32();
var len = stream.ReadUInt32();
var addr = PdbAddress.ReadAddress(stream);
name = PdbReader.ReadCString(stream);
child = new DbiScope(name, addr.Offset, len);
break;
}
case SymbolType.S_UNAMESPACE:
Namespaces.Add(new DbiNamespace(PdbReader.ReadCString(stream)));
break;
case SymbolType.S_MANSLOT: {
var variable = new DbiVariable();
variable.Read(stream);
Variables.Add(variable);
break;
}
case SymbolType.S_OEM:
if (stream.Position + 20 > end)
break;
if (!ReadAndCompareBytes(stream, end, dotNetOemGuid)) {
Debug.Fail("Unknown OEM record GUID, not .NET GUID");
break;
}
stream.Position += 4;// typeIndex or 0
name = ReadUnicodeString(stream, end);
Debug.replacedert(name != null);
if (name == null)
break;
var data = stream.ReadBytes((int)(end - stream.Position));
if (oemInfos == null)
oemInfos = new List<OemInfo>(1);
oemInfos.Add(new OemInfo(name, data));
break;
case SymbolType.S_MANCONSTANT:
uint signatureToken = stream.ReadUInt32();
object value;
if (!NumericReader.TryReadNumeric(stream, end, out value))
break;
name = PdbReader.ReadCString(stream);
if (constants == null)
constants = new List<ConstantInfo>();
constants.Add(new ConstantInfo(name, signatureToken, value));
break;
case SymbolType.S_END:
break;
default:
Debug.Fail("Unknown symbol type: " + type);
break;
}
stream.Position = end;
if (child != null) {
child.Read(counter, stream, childEnd.Value);
Children.Add(child);
child = null;
}
}
counter.Decrement();
if (stream.Position != scopeEnd)
Debugger.Break();
}
19
Source : DbContext.cs
with MIT License
from ARKlab
with MIT License
from ARKlab
[AfterScenario]
public void KeepStudioRunning(ScenarioContext ctx)
{
if (ctx.ScenarioExecutionStatus == ScenarioExecutionStatus.TestError && Debugger.IsAttached)
Debugger.Break();
}
19
Source : Program.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
public static async Task MainAsync(string[] args)
{
var logLevel = LogLevel.Information;
for (var i = 0; i < args.Length; i++)
{
if (args[i].IndexOf("debug", StringComparison.OrdinalIgnoreCase) >= 0)
{
while (!Debugger.IsAttached)
{
Thread.Sleep(1000);
}
Debugger.Break();
continue;
}
if (args[i] == "--logLevel" && i + 1 < args.Length)
{
var logLevelString = args[++i];
if (!Enum.TryParse(logLevelString, out logLevel))
{
logLevel = LogLevel.Information;
Console.WriteLine($"Invalid log level '{logLevelString}'. Defaulting to {logLevel.ToString()}.");
}
}
}
Serializer.Instance.JsonSerializer.Converters.RegisterRazorConverters();
var factory = new LoggerFactory();
ILanguageServer server = null;
server = await OmniSharp.Extensions.LanguageServer.Server.LanguageServer.From(options =>
options
.WithInput(Console.OpenStandardInput())
.WithOutput(Console.OpenStandardOutput())
.WithLoggerFactory(factory)
.AddDefaultLoggingProvider()
.WithMinimumLogLevel(logLevel)
.WithHandler<RazorDoreplacedentSynchronizationEndpoint>()
.WithHandler<RazorCompletionEndpoint>()
.WithHandler<RazorLanguageEndpoint>()
.WithHandler<RazorProjectEndpoint>()
.WithServices(services =>
{
services.AddSingleton<RemoteTextLoaderFactory, DefaultRemoteTextLoaderFactory>();
services.AddSingleton<ProjectResolver, DefaultProjectResolver>();
services.AddSingleton<DoreplacedentResolver, DefaultDoreplacedentResolver>();
services.AddSingleton<FilePathNormalizer>();
services.AddSingleton<RazorProjectService, DefaultRazorProjectService>();
services.AddSingleton<ProjectSnapshotChangeTrigger, BackgroundDoreplacedentGenerator>();
services.AddSingleton<DoreplacedentProcessedListener, RazorDiagnosticsPublisher>();
services.AddSingleton<HostDoreplacedentFactory, DefaultHostDoreplacedentFactory>();
services.AddSingleton<ProjectSnapshotManagerAccessor, DefaultProjectSnapshotManagerAccessor>();
services.AddSingleton<TagHelperFactsService, DefaultTagHelperFactsService>();
services.AddSingleton<VisualStudio.Editor.Razor.TagHelperCompletionService, VisualStudio.Editor.Razor.DefaultTagHelperCompletionService>();
services.AddSingleton<TagHelperDescriptionFactory, DefaultTagHelperDescriptionFactory>();
// Completion
services.AddSingleton<Completion.TagHelperCompletionService, Completion.DefaultTagHelperCompletionService>();
services.AddSingleton<RazorCompletionItemProvider, DirectiveCompletionItemProvider>();
services.AddSingleton<RazorCompletionItemProvider, DirectiveAttributeCompletionItemProvider>();
services.AddSingleton<RazorCompletionItemProvider, DirectiveAttributeParameterCompletionItemProvider>();
services.AddSingleton<RazorCompletionItemProvider, DirectiveAttributeTransitionCompletionItemProvider>();
var foregroundDispatcher = new VSCodeForegroundDispatcher();
services.AddSingleton<ForegroundDispatcher>(foregroundDispatcher);
services.AddSingleton<RazorCompletionFactsService, DefaultRazorCompletionFactsService>();
var doreplacedentVersionCache = new DefaultDoreplacedentVersionCache(foregroundDispatcher);
services.AddSingleton<DoreplacedentVersionCache>(doreplacedentVersionCache);
services.AddSingleton<ProjectSnapshotChangeTrigger>(doreplacedentVersionCache);
var containerStore = new DefaultGeneratedCodeContainerStore(
foregroundDispatcher,
doreplacedentVersionCache,
new Lazy<ILanguageServer>(() => server));
services.AddSingleton<GeneratedCodeContainerStore>(containerStore);
services.AddSingleton<ProjectSnapshotChangeTrigger>(containerStore);
}));
// Workaround for https://github.com/OmniSharp/csharp-language-server-protocol/issues/106
var languageServer = (OmniSharp.Extensions.LanguageServer.Server.LanguageServer)server;
languageServer.MinimumLogLevel = logLevel;
try
{
var logger = factory.CreateLogger<Program>();
var replacedemblyInformationAttribute = typeof(Program).replacedembly.GetCustomAttribute<replacedemblyInformationalVersionAttribute>();
logger.LogInformation("Razor Language Server version " + replacedemblyInformationAttribute.InformationalVersion);
}
catch
{
// Swallow exceptions from determining replacedembly information.
}
await server.WaitForExit;
TempDirectory.Instance.Dispose();
}
19
Source : MSBuildProjectManager.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
private void HandleDebug(ProjectInstance projectInstance)
{
var debugPlugin = projectInstance.GetPropertyValue(DebugRazorOmnisharpPluginPropertyName);
if (!string.IsNullOrEmpty(debugPlugin) && string.Equals(debugPlugin, "true", StringComparison.OrdinalIgnoreCase))
{
Console.WriteLine($"Waiting for a debugger to attach to the Razor Plugin. Process id: {Process.GetCurrentProcess().Id}");
while (!Debugger.IsAttached)
{
Thread.Sleep(1000);
}
Debugger.Break();
}
}
19
Source : HandlebarsHelpers.cs
with MIT License
from Avanade
with MIT License
from Avanade
public static void RegisterHelpers()
{
if (_areRegistered)
return;
_areRegistered = true;
// Will check that the first argument equals at least one of the subsequent arguments.
Handlebars.RegisterHelper("ifeq", (writer, context, parameters, args) =>
{
if (IfEq(args))
context.Template(writer, parameters);
else
context.Inverse(writer, parameters);
});
// Will check that the first argument does not equal any of the subsequent arguments.
Handlebars.RegisterHelper("ifne", (writer, context, parameters, args) =>
{
if (IfEq(args))
context.Inverse(writer, parameters);
else
context.Template(writer, parameters);
});
// Will check that the first argument is less than or equal to the subsequent arguments.
Handlebars.RegisterHelper("ifle", (writer, context, parameters, args) =>
{
if (IfLe(args))
context.Template(writer, parameters);
else
context.Inverse(writer, parameters);
});
// Will check that the first argument is greater than or equal to the subsequent arguments.
Handlebars.RegisterHelper("ifge", (writer, context, parameters, args) =>
{
if (IfGe(args))
context.Template(writer, parameters);
else
context.Inverse(writer, parameters);
});
// Will check that all of the arguments have a non-<c>null</c> value.
Handlebars.RegisterHelper("ifval", (writer, context, parameters, args) =>
{
foreach (var arg in args)
{
if (arg == null)
{
context.Inverse(writer, parameters);
return;
}
}
context.Template(writer, parameters);
});
// Will check that all of the arguments have a <c>null</c> value.
Handlebars.RegisterHelper("ifnull", (writer, context, parameters, args) =>
{
foreach (var arg in args)
{
if (arg != null)
{
context.Inverse(writer, parameters);
return;
}
}
context.Template(writer, parameters);
});
// Will check that any of the arguments have a <c>true</c> value where bool; otherwise, non-null.
Handlebars.RegisterHelper("ifor", (writer, context, parameters, args) =>
{
foreach (var arg in args)
{
if (arg is bool opt)
{
if (opt)
{
context.Template(writer, parameters);
return;
}
}
else if (arg != null)
{
var opt2 = arg as bool?;
if (opt2 != null && !opt2.Value)
continue;
context.Template(writer, parameters);
return;
}
}
context.Inverse(writer, parameters);
});
// Initiate a breakpoint in the debugger.
Handlebars.RegisterHelper("breakpoint", (writer, context, parameters, args) =>
{
System.Diagnostics.Debugger.Break();
});
// Converts a value to lowercase.
Handlebars.RegisterHelper("lower", (writer, context, parameters) => writer.WriteSafeString(parameters.FirstOrDefault()?.ToString()?.ToLowerInvariant() ?? ""));
// NOTE: Any ending in 'x' are to explicitly ignore special names!!!
// Converts a value to camelcase.
Handlebars.RegisterHelper("camel", (writer, context, parameters) => writer.WriteSafeString(StringConversion.ToCamelCase(parameters.FirstOrDefault()?.ToString()) ?? ""));
Handlebars.RegisterHelper("camelx", (writer, context, parameters) => writer.WriteSafeString(StringConversion.ToCamelCase(parameters.FirstOrDefault()?.ToString(), true) ?? ""));
// Converts a value to pascalcase.
Handlebars.RegisterHelper("pascal", (writer, context, parameters) => writer.WriteSafeString(StringConversion.ToPascalCase(parameters.FirstOrDefault()?.ToString()) ?? ""));
Handlebars.RegisterHelper("pascalx", (writer, context, parameters) => writer.WriteSafeString(StringConversion.ToPascalCase(parameters.FirstOrDefault()?.ToString(), true) ?? ""));
// Converts a value to private case.
Handlebars.RegisterHelper("private", (writer, context, parameters) => writer.WriteSafeString(StringConversion.ToPrivateCase(parameters.FirstOrDefault()?.ToString()) ?? ""));
Handlebars.RegisterHelper("privatex", (writer, context, parameters) => writer.WriteSafeString(StringConversion.ToPrivateCase(parameters.FirstOrDefault()?.ToString(), true) ?? ""));
Handlebars.RegisterHelper("sentence", (writer, context, parameters) => writer.WriteSafeString(StringConversion.ToSentenceCase(parameters.FirstOrDefault()?.ToString()) ?? ""));
Handlebars.RegisterHelper("sentencex", (writer, context, parameters) => writer.WriteSafeString(StringConversion.ToSentenceCase(parameters.FirstOrDefault()?.ToString(), true) ?? ""));
// Converts a value to the c# '<see cref="value"/>' comments equivalent.
Handlebars.RegisterHelper("seecomments", (writer, context, parameters) => writer.WriteSafeString(ConfigBase.ToSeeComments(parameters.FirstOrDefault()?.ToString())));
// Inserts indent spaces based on the preplaceded index value.
Handlebars.RegisterHelper("indent", (writer, context, parameters) => writer.WriteSafeString(new string(' ', 4 * (int)(parameters.FirstOrDefault() ?? 0))));
// Adds a value to a value.
Handlebars.RegisterHelper("add", (writer, context, parameters) =>
{
int sum = 0;
foreach (var p in parameters)
{
if (p is int pi)
sum += pi;
else if (p is string ps)
sum += int.Parse(ps, NumberStyles.Integer, CultureInfo.InvariantCulture);
else
writer.WriteSafeString("!!! add with invalid integer !!!");
}
writer.WriteSafeString(sum);
});
}
19
Source : GLSLGpuProgram.cs
with GNU Lesser General Public License v2.1
from axiom3d
with GNU Lesser General Public License v2.1
from axiom3d
[OgreVersion(1, 7, 2790)]
public override void BindProgramParameters(GpuProgramParameters parms, GpuProgramParameters.GpuParamVariability mask)
{
try
{
// activate the link program object
GLSLLinkProgram linkProgram = GLSLLinkProgramManager.Instance.ActiveLinkProgram;
// preplaced on parameters from params to program object uniforms
linkProgram.UpdateUniforms(parms, mask, Type);
}
catch (Exception e)
{
LogManager.Instance.Write("Remove this when validated");
Debugger.Break();
}
}
19
Source : Debug.cs
with MIT License
from ay2015
with MIT License
from ay2015
private static void _Break()
{
//if (!_isNotAtRuntime)
{
#if DEV_DEBUG
Debugger.Break();
#else
Debug.replacedert(false);
#endif
}
}
19
Source : App.xaml.cs
with Apache License 2.0
from azanov
with Apache License 2.0
from azanov
private void RootFrame_NavigationFailed(object sender, NavigationFailedEventArgs e)
{
if (System.Diagnostics.Debugger.IsAttached)
{
// A navigation has failed; break into the debugger
System.Diagnostics.Debugger.Break();
}
}
19
Source : App.xaml.cs
with Apache License 2.0
from azanov
with Apache License 2.0
from azanov
private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
if (System.Diagnostics.Debugger.IsAttached)
{
// An unhandled exception has occurred; break into the debugger
System.Diagnostics.Debugger.Break();
}
}
19
Source : RenPyUnpacker.cs
with MIT License
from Azukee
with MIT License
from Azukee
public IEnumerable<IExtractableFile> LoadFilesFromArchive(string inputArchive)
{
using (var fs = File.OpenRead(inputArchive))
using (var br = new BinaryReader(fs)) {
var readMagic = Encoding.ASCII.GetString(br.ReadBytes(MagicLength));
if (!Regex.IsMatch(readMagic, MagicRegex))
throw new InvalidMagicException();
long indexOff = Convert.ToInt64(readMagic.Substring(8, 16), 16);
uint key = Convert.ToUInt32(readMagic.Substring(25, 8), 16);
// seek to index offset and read it
fs.Seek(indexOff + 2, SeekOrigin.Begin); // TODO: skipping zlib header here
using (var decStream = new DeflateStream(fs, CompressionMode.Decompress, true)) {
var indexObject = PickleReader.ReadFromStream(decStream);
if (!(indexObject is Dictionary<object, object> dic))
throw new Exception("File index was not a dictionary.");
foreach (var o in dic) {
var val = (object[])((List<object>)o.Value)[0];
long v1 = Convert.ToInt64(val[0]) ^ key;
uint v2 = (uint)(Convert.ToInt64(val[1]) ^ key);
var v3 = (string)val[2];
if (!string.IsNullOrEmpty(v3))
Debugger.Break();
yield return new FileSlice((string)o.Key, v1, v2, inputArchive);
}
}
}
}
19
Source : PowerShellManagerTests.cs
with MIT License
from Azure
with MIT License
from Azure
internal static void Break()
{
while (!System.Diagnostics.Debugger.IsAttached)
{
System.Threading.Thread.Sleep(200);
}
System.Diagnostics.Debugger.Break();
}
19
Source : TestHelper.cs
with MIT License
from Azure
with MIT License
from Azure
public static string ReadLine()
{
if (HttpMockServer.Mode == HttpRecorderMode.Record)
{
// NOTE: This test requires a manual action to be performed before it can continue recording.
// Please go up the execution stack (or check test output window) to see what steps needs
// to be performed before you can continue execution.
if (Debugger.IsAttached)
{
Debugger.Break();
return "[Running in interactive mode]";
}
throw new NotSupportedException(
"This test requires a manual action to be performed before it can continue recording. " +
"Please run it with a debugger attached to be able to perform required steps in the Record mode.");
}
return "[Running in non interactive mode]";
}
19
Source : Debugger.cs
with MIT License
from Azure
with MIT License
from Azure
public static void Await()
{
while (!System.Diagnostics.Debugger.IsAttached)
{
Console.Error.WriteLine($"Waiting for debugger to attach to process {System.Diagnostics.Process.GetCurrentProcess().Id}");
for (int i = 0; i < 50; i++)
{
if (System.Diagnostics.Debugger.IsAttached)
{
break;
}
System.Threading.Thread.Sleep(100);
Console.Error.Write(".");
}
Console.Error.WriteLine();
}
System.Diagnostics.Debugger.Break();
}
19
Source : MainWindow.xaml.cs
with MIT License
from azyobuzin
with MIT License
from azyobuzin
private async void UpdateCursorPosition(Point pos)
{
var imgSource = this.imgScreen.Source;
if (!(imgSource is WriteableBitmap)) return;
pos = this.ToGamePosition(pos);
this.BindingModel.CursorX = (int)pos.X;
this.BindingModel.CursorY = (int)pos.Y;
this.BindingModel.CursorRatioX = pos.X / imgSource.Width;
this.BindingModel.CursorRatioY = pos.Y / imgSource.Height;
if (this._connection != null)
{
try
{
await this._connection.SetCursorPositionAsync(checked((short)pos.X), checked((short)pos.Y)).ConfigureAwait(false);
}
catch
{
if (Debugger.IsAttached) Debugger.Break();
}
}
this._updateCursorImageSubject.OnNext(Unit.Default);
}
19
Source : MainWindow.xaml.cs
with MIT License
from azyobuzin
with MIT License
from azyobuzin
private async void SendClickEvent()
{
if (this._connection == null) return;
try
{
await this._connection.MouseClickAsync();
}
catch (Exception ex)
{
if (Debugger.IsAttached) Debugger.Break();
this._connection = null;
MessageBox.Show(this, ex.ToString(), "エラー", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
19
Source : Program.cs
with MIT License
from azyobuzin
with MIT License
from azyobuzin
private int OnExecute()
{
var hashLength = this.Bits * this.Bits / 8;
var inputLength = this.InputFiles.Length;
var results = new byte[hashLength * inputLength];
// 順番にハッシュを計算
var successAll = true;
for (var i = 0; i < this.InputFiles.Length; i++)
{
try
{
var span = new Span<byte>(results, hashLength * i, hashLength);
using (var image = Image.Load(this.InputFiles[i]))
{
Blockhash.ComputeHash(new Rgba32InputImage(image), span, this.Bits);
}
Console.WriteLine("{0}: {1}", i, ToHashString(span));
}
catch (Exception ex)
{
if (Debugger.IsAttached) Debugger.Break();
Console.Error.WriteLine("{0}: {1}", i, ex);
successAll = false;
}
}
if (!successAll) return 1;
// 最短距離を計算
if (inputLength > 1)
{
var minDistance = int.MaxValue;
for (var i = 0; i < inputLength; i++)
{
for (var j = 0; j < inputLength; j++)
{
if (i == j) continue;
var bs1 = new ArraySegment<byte>(results, hashLength * i, hashLength);
var bs2 = new ArraySegment<byte>(results, hashLength * j, hashLength);
var distance = Blockhash.GetDistance(bs1, bs2);
if (distance < minDistance) minDistance = distance;
}
}
Console.WriteLine("Min Distance: {0}", minDistance);
}
return 0;
}
19
Source : MainWindow.xaml.cs
with MIT License
from azyobuzin
with MIT License
from azyobuzin
private async void btnConnect_Click(object sender, RoutedEventArgs e)
{
if (this._logSubscription != null)
{
this._logSubscription.Dispose();
this._logSubscription = null;
}
if (this._connection != null)
{
this._connection.Dispose();
this._connection = null;
}
var host = this.txtRemoteAddr.Text;
int port;
try
{
var colonIndex = host.LastIndexOf(':');
if (colonIndex >= 0)
{
port = int.Parse(host.Substring(colonIndex + 1));
host = host.Remove(colonIndex);
}
else
{
port = GrpcToaServer.DefaultPort;
}
}
catch (Exception ex)
{
MessageBox.Show(this, ex.Message, "接続先エラー", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
this.btnConnect.IsEnabled = false;
try
{
var conn = new GrpcRemoteWagahighOperator(host, port);
this._connection = conn;
await conn.ConnectAsync();
this._logSubscription = conn.LogStream
.ObserveOn(this.Dispatcher)
.Subscribe(
this.OnNextLog,
ex =>
{
if (Debugger.IsAttached) Debugger.Break();
MessageBox.Show(this, ex.ToString(), "ログエラー", MessageBoxButton.OK, MessageBoxImage.Error);
},
() => MessageBox.Show(this, "ログストリームが終了しました。", "ログエラー", MessageBoxButton.OK, MessageBoxImage.Error)
);
}
catch (Exception ex)
{
if (Debugger.IsAttached) Debugger.Break();
MessageBox.Show(this, ex.ToString(), "接続失敗", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
finally
{
this.btnConnect.IsEnabled = true;
}
if (this._timer == null)
{
// 0.1 秒ごとに画面を更新
this._timer = new DispatcherTimer(
new TimeSpan(100 * TimeSpan.TicksPerMillisecond),
DispatcherPriority.Normal,
this.TimerTick,
this.Dispatcher
);
}
}
19
Source : MainWindow.xaml.cs
with MIT License
from azyobuzin
with MIT License
from azyobuzin
private async void TimerTick(object sender, EventArgs e)
{
if (this._connection == null) return;
try
{
await this.UpdateScreen();
}
catch (Exception ex)
{
if (Debugger.IsAttached) Debugger.Break();
this._connection = null;
MessageBox.Show(this, ex.ToString(), "エラー", MessageBoxButton.OK, MessageBoxImage.Error);
}
// CanExecute 更新チェック
CommandManager.InvalidateRequerySuggested();
}
19
Source : MainWindow.xaml.cs
with MIT License
from azyobuzin
with MIT License
from azyobuzin
private async Task UpdateCursorImage()
{
if (this._connection == null) return;
try
{
var source = this.imgCursor.Source as WriteableBitmap;
bool createNewBitmap;
var img = await this._connection.GetCursorImageAsync();
this._cursorImage?.Dispose();
this._cursorImage = img;
createNewBitmap = source == null || source.PixelWidth != img.Width || source.PixelHeight != img.Height;
if (createNewBitmap)
source = new WriteableBitmap(img.Width, img.Height, 96, 96, PixelFormats.Pbgra32, null);
source.Lock();
try
{
CopyPixels(img, source.BackBuffer, source.BackBufferStride * source.PixelHeight);
source.AddDirtyRect(new Int32Rect(0, 0, source.PixelWidth, source.PixelHeight));
}
finally
{
source.Unlock();
}
if (createNewBitmap)
this.imgCursor.Source = source;
}
catch (Exception ex)
{
if (Debugger.IsAttached) Debugger.Break();
this._connection = null;
MessageBox.Show(this, ex.ToString(), "エラー", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
19
Source : DebugManager.cs
with MIT License
from Bannerlord-Coop-Team
with MIT License
from Bannerlord-Coop-Team
public void replacedert(
bool condition,
string message,
[CallerFilePath] string CallerFile = "",
[CallerMemberName] string CallerMethod = "",
[CallerLineNumber] int CallerLine = 0)
{
if (!condition)
{
Logger.Debug(
"replacedert failure in {file}::{method}::{line}: {message}",
CallerFile,
CallerMethod,
CallerLine);
if (Debugger.IsAttached)
{
Debugger.Break();
}
}
}
19
Source : DebugManager.cs
with MIT License
from Bannerlord-Coop-Team
with MIT License
from Bannerlord-Coop-Team
public void Silentreplacedert(
bool condition,
string message = "",
bool getDump = false,
[CallerFilePath] string callerFile = "",
[CallerMemberName] string callerMethod = "",
[CallerLineNumber] int callerLine = 0)
{
if (!condition)
{
Logger.Debug(
"replacedert failure in {file}::{method}::{line}: {message}",
callerFile,
callerMethod,
callerLine);
if (Debugger.IsAttached)
{
Debugger.Break();
}
}
}
19
Source : Program.cs
with MIT License
from BaristaLabs
with MIT License
from BaristaLabs
static int Main(string[] args)
{
var cliArguments = Cli.Parse<CliArguments>(args);
//Do an initial check to ensure that the Skrapr Definition exists.
if (!File.Exists(cliArguments.SkraprDefinitionPath))
throw new FileNotFoundException($"The specified skrapr definition ({cliArguments.SkraprDefinitionPath}) could not be found. Please check that the skrapr definition exists.");
//Setup our DI
var serviceProvider = new ServiceCollection()
.AddLogging()
.BuildServiceProvider();
//Remove previous log file
File.Delete("skraprlog.json");
//Configure Serilog
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Verbose()
.Enrich.FromLogContext()
.WriteTo.File(new JsonFormatter(), "skraprlog.json")
.WriteTo.ColoredConsole(restrictedToMinimumLevel: LogEventLevel.Debug)
.CreateLogger();
//Configure the logger.
var logger = serviceProvider
.GetService<ILoggerFactory>()
.AddSerilog()
.CreateLogger<Program>();
ChromeBrowser browser = null;
SkraprDevTools devTools = null;
SkraprWorker worker = null;
try
{
if (cliArguments.Launch)
{
browser = ChromeBrowser.Launch(cliArguments.RemoteDebuggingHost, cliArguments.RemoteDebuggingPort);
}
logger.LogInformation("Connecting to a Chrome session on {chromeHost}:{chromeRemoteDebuggingPort}...", cliArguments.RemoteDebuggingHost, cliArguments.RemoteDebuggingPort);
ChromeSessionInfo session = null;
try
{
var sessions = ChromeBrowser.GetChromeSessions(cliArguments.RemoteDebuggingHost, cliArguments.RemoteDebuggingPort).GetAwaiter().GetResult();
session = sessions.FirstOrDefault(s => s.Type == "page" && !String.IsNullOrWhiteSpace(s.WebSocketDebuggerUrl));
}
catch (System.Net.Http.HttpRequestException)
{
logger.LogWarning("Unable to connect to a Chrome session on {chromeHost}:{chromeRemoteDebuggingPort}.", cliArguments.RemoteDebuggingHost, cliArguments.RemoteDebuggingPort);
logger.LogWarning("Please ensure that a chrome session has been launched with the --remote-debugging-port={chromeRemoteDebuggingPort} command line argument", cliArguments.RemoteDebuggingPort);
logger.LogWarning("Or, launch SkraprConsoleHost with -l");
Debugger.Break();
return -1;
}
//TODO: Create a new session if one doesn't exist.
if (session == null)
{
logger.LogWarning("Unable to locate a suitable session. Ensure that the Developer Tools window is closed on an existing session or create a new chrome instance with the --remote-debugging-port={chromeRemoteDebuggingPort) command line argument", cliArguments.RemoteDebuggingPort);
Debugger.Break();
return -1;
}
devTools = SkraprDevTools.Connect(serviceProvider, session).GetAwaiter().GetResult();
logger.LogInformation("Using session {sessionId}: {sessionreplacedle} - {webSocketDebuggerUrl}", session.Id, session.replacedle, session.WebSocketDebuggerUrl);
worker = SkraprWorker.Create(serviceProvider, cliArguments.SkraprDefinitionPath, devTools.Session, devTools, debugMode: cliArguments.Debug);
if (cliArguments.Debug)
{
logger.LogInformation($"Operating in debug mode. Tasks may perform additional behavior or may skip themselves.");
}
if (cliArguments.Attach == true)
{
var targetInfo = devTools.Session.Target.GetTargetInfo(session.Id).GetAwaiter().GetResult();
var matchingRuleCount = worker.GetMatchingRules().GetAwaiter().GetResult().Count();
if (matchingRuleCount > 0)
{
logger.LogInformation($"Attach specified and {matchingRuleCount} rules match the current session's state; Continuing.", matchingRuleCount);
worker.Post(new NavigateTask
{
Url = targetInfo.Url
});
}
else
{
logger.LogInformation($"Attach specified but no rules matched the current session's state; Adding start tasks.");
worker.AddStartUrls();
}
}
else
{
logger.LogInformation($"Adding start tasks.");
worker.AddStartUrls();
}
Console.TreatControlCAsInput = true;
logger.LogInformation("Skrapr is currently processing. Press ENTER to exit...");
var cancelKeyTokenSource = new CancellationTokenSource();
var workerCompletion = worker.Completion
.ContinueWith((t) => cancelKeyTokenSource.Cancel());
var keyCompletion = ConsoleUtils.ReadKeyAsync(ConsoleKey.Enter, cancelKeyTokenSource.Token)
.ContinueWith(async (t) =>
{
if (!t.IsCanceled)
{
logger.LogWarning("Stop requested at the console, cancelling...");
worker.Cancel();
await worker.Completion;
}
});
Task.WaitAny(workerCompletion, keyCompletion);
if (worker.Completion.IsFaulted)
{
logger.LogError("Worker was faulted. Exiting with status code of -1");
if (Debugger.IsAttached)
{
throw worker.Completion.Exception.Flatten();
}
return -1;
}
}
catch(TaskCanceledException)
{
//Do Nothing
}
finally
{
//Cleanup.
if (worker != null)
{
worker.Dispose();
worker = null;
}
if (devTools != null)
{
devTools.Dispose();
devTools = null;
}
if (browser != null)
{
browser.Dispose();
browser = null;
}
}
logger.LogInformation("Worker completed successfully. Status code 0");
Debugger.Break();
return 0;
}
19
Source : Worker.cs
with GNU Affero General Public License v3.0
from Barsonax
with GNU Affero General Public License v3.0
from Barsonax
public void Start()
{
_disposed = false;
while (!_disposed)
{
_waitHandle.WaitOne();
try
{
_processer.Process(_workItem);
_onCompleted?.Invoke(_workItem);
}
catch (Exception ex)
{
Debug.WriteLine(ex);
Debugger.Break();
}
_waitHandle.Reset();
IsBusy = false;
}
}
19
Source : AssemblyExtensions.cs
with MIT License
from Baseflow
with MIT License
from Baseflow
private static IEnumerable<Type> ExceptionSafeGetTypes(this replacedembly replacedembly)
{
try
{
return replacedembly.GetTypes();
}
catch (ReflectionTypeLoadException ex)
{
// MvxLog.Instance can be null, when reflecting for Setup.cs
// Check for null
//...LogError($"ReflectionTypeLoadException masked during loading of {replacedembly.FullName} - error {ex.ToLongString()}");
if (ex.LoaderExceptions != null)
{
foreach (var excp in ex.LoaderExceptions)
{
//...LogWarn(ex.Message);
}
}
if (Debugger.IsAttached)
Debugger.Break();
return Array.Empty<Type>();
}
}
19
Source : ArchiveController.cs
with MIT License
from bbepis
with MIT License
from bbepis
[Route("reprocess")]
[HttpGet]
public async Task<IActionResult> Reprocess([FromServices] HaydenDbContext dbContext)
{
foreach (var subfolder in Directory.EnumerateDirectories("G:\\utg-archive", "*", SearchOption.TopDirectoryOnly))
{
string board = Path.GetFileName(subfolder);
if (board == "hayden" || board == "server" || board == "temp")
continue;
var baseDirectory = Path.Combine(Config.Value.FileLocation, board);
Directory.CreateDirectory(Path.Combine(baseDirectory, "image"));
Directory.CreateDirectory(Path.Combine(baseDirectory, "thumb"));
Directory.CreateDirectory(Path.Combine(baseDirectory, "thread"));
foreach (var jsonFile in Directory.EnumerateFiles(subfolder, "thread.json", SearchOption.AllDirectories))
{
if (jsonFile.StartsWith(Config.Value.FileLocation))
continue;
var thread = ReadJson(jsonFile);
var existingThread = await dbContext.Threads.FirstOrDefaultAsync(x => x.Board == board && x.ThreadId == thread.OriginalPost.PostNumber);
var lastModifiedTime = thread.OriginalPost.ArchivedOn.HasValue
? Utility.ConvertGMTTimestamp(thread.OriginalPost.ArchivedOn.Value).UtcDateTime
: Utility.ConvertGMTTimestamp(thread.Posts.Max(x => x.UnixTimestamp)).UtcDateTime;
if (existingThread != null)
{
existingThread.IsDeleted = thread.IsDeleted == true;
existingThread.IsArchived = thread.OriginalPost.Archived == true;
existingThread.LastModified = lastModifiedTime;
}
else
{
existingThread = new DBThread()
{
Board = board,
ThreadId = thread.OriginalPost.PostNumber,
replacedle = thread.OriginalPost.Subject,
IsArchived = thread.OriginalPost.Archived == true,
IsDeleted = thread.OriginalPost.FileDeleted == true,
LastModified = lastModifiedTime
};
dbContext.Add(existingThread);
}
var existingPosts = await dbContext.Posts.Where(x => x.Board == board && x.ThreadId == thread.OriginalPost.PostNumber).ToArrayAsync();
foreach (var post in thread.Posts)
{
if (post == null)
System.Diagnostics.Debugger.Break();
var existingPost = existingPosts.FirstOrDefault(x => x.PostId == post.PostNumber);
if (existingPost != null)
{
existingPost.IsDeleted = post.ExtensionIsDeleted == true;
existingPost.Html = post.Comment;
existingPost.IsImageDeleted = post.FileDeleted == true;
}
else
{
existingPost = new DBPost()
{
Board = board,
PostId = post.PostNumber,
ThreadId = thread.OriginalPost.PostNumber,
Html = post.Comment,
Author = post.Name == "Anonymous" ? null : post.Name,
MediaHash = post.FileMd5 == null ? null : Convert.FromBase64String(post.FileMd5),
MediaFilename = post.OriginalFilenameFull,
DateTime = Utility.ConvertGMTTimestamp(post.UnixTimestamp).UtcDateTime,
IsSpoiler = post.SpoilerImage == true,
IsDeleted = post.ExtensionIsDeleted == true,
IsImageDeleted = post.FileDeleted == true
};
// This block of logic is to fix a bug with JSON files specifying the same posts multiple times
var trackedPost = dbContext.Posts.Local.FirstOrDefault(x => x.Board == board && x.PostId == post.PostNumber);
if (trackedPost != null)
{
dbContext.Entry(trackedPost).State = EnreplacedyState.Detached;
}
dbContext.Add(existingPost);
}
if (existingPost.MediaHash == null)
continue;
var base64Name = Utility.ConvertToBase(existingPost.MediaHash);
if (string.IsNullOrWhiteSpace(base64Name))
System.Diagnostics.Debugger.Break();
var destinationFilename = Path.Combine(Config.Value.FileLocation, board, "image",
base64Name + post.FileExtension);
if (!System.IO.File.Exists(destinationFilename))
{
var sourceFilename = Path.Combine(subfolder, existingPost.ThreadId.ToString(),
post.TimestampedFilenameFull);
System.IO.File.Copy(sourceFilename, destinationFilename);
sourceFilename = Path.Combine(subfolder, existingPost.ThreadId.ToString(), "thumbs",
post.TimestampedFilename.Value + "s.jpg");
destinationFilename = Path.Combine(Config.Value.FileLocation, board, "thumb",
base64Name + ".jpg");
System.IO.File.Copy(sourceFilename, destinationFilename);
}
}
await dbContext.SaveChangesAsync();
dbContext.DetachAllEnreplacedies();
System.IO.File.Copy(jsonFile, Path.Combine(Config.Value.FileLocation, board, "thread", thread.OriginalPost.PostNumber + ".json"), true);
}
//foreach (var threadFolder in Directory.EnumerateDirectories(subfolder, "*", SearchOption.TopDirectoryOnly))
//{
// IEnumerable<string> mediaFiles = Directory
// .EnumerateFiles(threadFolder, "*.jpg" , SearchOption.TopDirectoryOnly)
// .Concat(Directory.EnumerateFiles(threadFolder, "*.jpeg", SearchOption.TopDirectoryOnly))
// .Concat(Directory.EnumerateFiles(threadFolder, "*.png" , SearchOption.TopDirectoryOnly))
// .Concat(Directory.EnumerateFiles(threadFolder, "*.webm", SearchOption.TopDirectoryOnly));
// foreach (var mediaFile in mediaFiles)
// {
// }
//}
}
return Ok();
}
19
Source : DynamicTree.cs
with MIT License
from benukhanov
with MIT License
from benukhanov
[Conditional("DEBUG")]
[DebuggerNonUserCode]
[DebuggerHidden]
[DebuggerStepThrough]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void replacedert(bool replacedertion, [CallerMemberName]
string? member = default,
[CallerFilePath]
string? file = default, [CallerLineNumber]
int line = default)
{
if (replacedertion) return;
var msg = $"replacedertion failure in {member} ({file}:{line})";
Debug.Print(msg);
Debugger.Break();
throw new InvalidOperationException(msg);
}
19
Source : AssemblyPatcher.cs
with GNU Lesser General Public License v2.1
from BepInEx
with GNU Lesser General Public License v2.1
from BepInEx
public void PatchAndLoad()
{
// First, create a copy of the replacedembly dictionary as the initializer can change them
var replacedemblies =
new Dictionary<string, replacedemblyDefinition>(PatcherContext.Availablereplacedemblies,
StringComparer.InvariantCultureIgnoreCase);
// Next, initialize all the patchers
foreach (var replacedemblyPatcher in PatcherPluginsSafe)
try
{
replacedemblyPatcher.Initialize();
}
catch (Exception ex)
{
Logger.LogError($"Failed to run initializer of {replacedemblyPatcher.Info.GUID}: {ex}");
}
// Then, perform the actual patching
var patchedreplacedemblies = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase);
var resolvedreplacedemblies = new Dictionary<string, string>();
// TODO: Maybe instead reload the replacedembly and repatch with other valid patchers?
var invalidreplacedemblies = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase);
Logger.LogMessage($"Executing {PatcherContext.PatchDefinitions.Count} patch(es)");
foreach (var patchDefinition in PatcherContext.PatchDefinitions.ToList())
{
string targetDll = patchDefinition.Targetreplacedembly?.Targetreplacedembly ??
patchDefinition.TargetType.Targetreplacedembly;
bool isreplacedemblyPatch = patchDefinition.Targetreplacedembly != null;
if (targetDll == TargetreplacedemblyAttribute.Allreplacedemblies)
{
foreach (var kv in PatcherContext.Availablereplacedemblies.ToList())
{
if (invalidreplacedemblies.Contains(kv.Key))
continue;
RunPatcher(kv.Value, kv.Key);
}
}
else
{
if (!PatcherContext.Availablereplacedemblies.TryGetValue(targetDll, out var replacedembly)
|| invalidreplacedemblies.Contains(targetDll))
continue;
RunPatcher(replacedembly, targetDll);
}
bool RunPatcher(replacedemblyDefinition replacedembly, string targetDll)
{
try
{
var arguments = new object[patchDefinition.MethodInfo.GetParameters().Length];
if (!isreplacedemblyPatch)
{
var targetType =
replacedembly.MainModule.Types.FirstOrDefault(x => x.FullName ==
patchDefinition.TargetType.TargetType);
if (targetType == null)
{
Logger
.LogWarning($"Unable to find type [{patchDefinition.TargetType.TargetType}] defined in {patchDefinition.MethodInfo.Name}. Skipping patcher"); //TODO: Proper name
return false;
}
arguments[0] = targetType;
}
else
{
arguments[0] = replacedembly;
}
if (arguments.Length > 1)
arguments[1] = targetDll;
var result = patchDefinition.MethodInfo.Invoke(patchDefinition.Instance, arguments);
if (patchDefinition.MethodInfo.ReturnType == typeof(void)
|| patchDefinition.MethodInfo.ReturnType == typeof(bool) && (bool)result)
{
if (isreplacedemblyPatch)
{
replacedembly = (replacedemblyDefinition)arguments[0];
PatcherContext.Availablereplacedemblies[targetDll] = replacedembly;
}
patchedreplacedemblies.Add(targetDll);
}
return true;
}
catch (Exception e)
{
Logger.LogError($"Failed to run [{patchDefinition.FullName}] when patching [{replacedembly.Name.Name}]. This replacedembly will not be patched. Error: {e}");
patchedreplacedemblies.Remove(targetDll);
invalidreplacedemblies.Add(targetDll);
return false;
}
}
foreach (var resolvedreplaced in AppDomain.CurrentDomain.Getreplacedemblies())
{
var name = Utility.TryParsereplacedemblyName(resolvedreplaced.FullName, out var replacedName)
? replacedName.Name
: resolvedreplaced.FullName;
// Report only the first type that caused the replacedembly to load, because any subsequent ones can be false positives
if (!resolvedreplacedemblies.ContainsKey(name))
resolvedreplacedemblies[name] = patchDefinition.MethodInfo.DeclaringType.ToString();
}
}
// Check if any patched replacedemblies have been already resolved by the CLR
// If there are any, they cannot be loaded by the preloader
var patchedreplacedemblyNames =
new
HashSet<string>(replacedemblies.Where(kv => patchedreplacedemblies.Contains(kv.Key)).Select(kv => kv.Value.Name.Name),
StringComparer.InvariantCultureIgnoreCase);
var earlyLoadreplacedemblies = resolvedreplacedemblies.Where(kv => patchedreplacedemblyNames.Contains(kv.Key)).ToList();
if (earlyLoadreplacedemblies.Count != 0)
Logger.LogWarning(new StringBuilder()
.AppendLine("The following replacedemblies have been loaded too early and will not be patched by preloader:")
.AppendLine(string.Join(Environment.NewLine,
earlyLoadreplacedemblies
.Select(kv =>
$"* [{kv.Key}] (first loaded by [{kv.Value}])")
.ToArray()))
.AppendLine("Expect unexpected behavior and issues with plugins and patchers not being loaded.")
.ToString());
var dumpedreplacedemblyPaths = new Dictionary<string, string>();
// Finally, load patched replacedemblies into memory
if (ConfigDumpreplacedemblies.Value || ConfigLoadDumpedreplacedemblies.Value)
{
if (!Directory.Exists(PatcherContext.DumpedreplacedembliesPath))
Directory.CreateDirectory(PatcherContext.DumpedreplacedembliesPath);
foreach (var kv in replacedemblies)
{
var filename = kv.Key;
var name = Path.GetFileNameWithoutExtension(filename);
var ext = Path.GetExtension(filename);
var replacedembly = kv.Value;
if (!patchedreplacedemblies.Contains(filename))
continue;
for (var i = 0;; i++)
{
var postfix = i > 0 ? $"_{i}" : "";
var path = Path.Combine(PatcherContext.DumpedreplacedembliesPath, $"{name}{postfix}{ext}");
if (!Utility.TryOpenFileStream(path, FileMode.Create, out var fs))
continue;
replacedembly.Write(fs);
fs.Dispose();
dumpedreplacedemblyPaths[filename] = path;
break;
}
}
}
if (ConfigBreakBeforeLoadreplacedemblies.Value)
{
Logger.LogInfo($"BepInEx is about load the following replacedemblies:\n{string.Join("\n", patchedreplacedemblies.ToArray())}");
Logger.LogInfo($"The replacedemblies were dumped into {PatcherContext.DumpedreplacedembliesPath}");
Logger.LogInfo("Load any replacedemblies into the debugger, set breakpoints and continue execution.");
Debugger.Break();
}
foreach (var kv in replacedemblies)
{
var filename = kv.Key;
var replacedembly = kv.Value;
// Note that since we only *load* replacedemblies, they shouldn't trigger dependency loading
// Not loading all replacedemblies is very important not only because of memory reasons,
// but because some games *rely* on that because of messed up internal dependencies.
if (patchedreplacedemblies.Contains(filename))
{
replacedembly loadedreplacedembly;
if (ConfigLoadDumpedreplacedemblies.Value &&
dumpedreplacedemblyPaths.TryGetValue(filename, out var dumpedreplacedemblyPath))
loadedreplacedembly = replacedembly.LoadFrom(dumpedreplacedemblyPath);
else
{
using var replacedemblyStream = new MemoryStream();
replacedembly.Write(replacedemblyStream);
loadedreplacedembly = replacedembly.Load(replacedemblyStream.ToArray());
}
PatcherContext.Loadedreplacedemblies.Add(filename, loadedreplacedembly);
Logger.LogDebug($"Loaded '{replacedembly.FullName}' into memory");
}
// Though we have to dispose of all replacedemblies regardless of them being patched or not
replacedembly.Dispose();
}
// Finally, run all finalizers
foreach (var replacedemblyPatcher in PatcherPluginsSafe)
try
{
replacedemblyPatcher.Finalizer();
}
catch (Exception ex)
{
Logger.LogError($"Failed to run finalizer of {replacedemblyPatcher.Info.GUID}: {ex}");
}
}
19
Source : DownloadService.cs
with MIT License
from bezzad
with MIT License
from bezzad
private async Task<Stream> StartDownload()
{
try
{
Package.TotalFileSize = await _requestInstance.GetFileSize().ConfigureAwait(false);
OnDownloadStarted(new DownloadStartedEventArgs(Package.FileName, Package.TotalFileSize));
ValidateBeforeChunking();
Package.Chunks ??= _chunkHub.ChunkFile(Package.TotalFileSize, Options.ChunkCount);
Package.Validate();
if (Options.ParallelDownload)
{
await ParallelDownload(_globalCancellationTokenSource.Token).ConfigureAwait(false);
}
else
{
await SerialDownload(_globalCancellationTokenSource.Token).ConfigureAwait(false);
}
await StoreDownloadedFile(_globalCancellationTokenSource.Token).ConfigureAwait(false);
}
catch (OperationCanceledException exp)
{
OnDownloadFileCompleted(new AsyncCompletedEventArgs(exp, true, Package));
}
catch (Exception exp)
{
OnDownloadFileCompleted(new AsyncCompletedEventArgs(exp, false, Package));
Debugger.Break();
}
finally
{
if (IsCancelled)
{
// flush streams
Package.Flush();
}
else
{
// remove temp files
Package.Clear();
}
await Task.Yield();
}
return _destinationStream;
}
19
Source : Program.cs
with MIT License
from bezzad
with MIT License
from bezzad
private static async Task Main()
{
try
{
DummyHttpServer.HttpServer.Run(3333);
Console.Clear();
new Thread(AddEscapeHandler) { IsBackground = true }.Start();
Initial();
List<DownloadItem> downloadList = GetDownloadItems();
await DownloadAll(downloadList).ConfigureAwait(false);
}
catch (Exception e)
{
Console.Error.WriteLine(e);
Debugger.Break();
}
Console.WriteLine("END");
Console.Read();
}
19
Source : Model.cs
with MIT License
from bing-framework
with MIT License
from bing-framework
public static void Debug()
{
System.Diagnostics.Debugger.Launch();
System.Diagnostics.Debugger.Break();
}
See More Examples