public async Task OnlyLogsOnce() { var uuid = string.Empty; var optionsMock = new Mock <IOptions <RollbarOptions> >(); var rollbarClientMock = new Mock <RollbarClient>(optionsMock.Object); rollbarClientMock.SetupSequence(m => m.Send(It.IsAny <Payloads.Payload>())) .Returns(() => ReturnItem("test")) .Returns(() => ReturnItem("fail")); var httpContextMock = new Mock <HttpContext>(); httpContextMock .Setup(h => h.Features.Set(It.IsAny <IRollbarResponseFeature>())); var rollbar = new Rollbar(new IBuilder[] { }, new IExceptionBuilder[] { }, rollbarClientMock.Object); var middleware = new ExceptionHandlerMiddleware(context => { try { throw new Exception("Middleware tests"); } catch (Exception exception) { rollbar.SendException(exception).Wait(); throw; } }); await Assert.ThrowsAsync <Exception>(async() => await middleware.Invoke(httpContextMock.Object, rollbar)); rollbarClientMock.Verify(m => m.Send(It.IsAny <Payloads.Payload>()), Times.Once()); httpContextMock.Verify(m => m.Features.Set(It.Is <IRollbarResponseFeature>(f => f.Uuid == "test"))); }
public ExceptionHandlerMiddleware( RequestDelegate next, Rollbar rollbar) { this.Next = next; this.Rollbar = rollbar; }
private static void RegisterRollbar() { Console.WriteLine("Note that Rollbar API is enabled by default to collect crashes. If you want to opt out, please run with -s switch"); Rollbar.Init(new RollbarConfig { AccessToken = "1dd3cf880c5a46eeb4338dbea73f9620", Environment = "production" }); var version = Assembly.GetExecutingAssembly().GetName().Version.ToString(); Rollbar.PersonData(() => new Person(version) { UserName = $"{version}" }); Application.ThreadException += (sender, args) => { Rollbar.Report(args.Exception); }; AppDomain.CurrentDomain.UnhandledException += (sender, args) => { Rollbar.Report(args.ExceptionObject as System.Exception); }; TaskScheduler.UnobservedTaskException += (sender, args) => { Rollbar.Report(args.Exception); }; }
private static void SetupRollbar() { Rollbar.Init(new RollbarConfig { AccessToken = "5525758f15504199b7125d35d2058cfe", Environment = "production" }); var version = Assembly.GetExecutingAssembly().GetName().Version.ToString(); Rollbar.PersonData(() => new Person(version) { UserName = $"{version} on {GetWindowsVersion()} with {Get45PlusFromRegistry()}" }); Rollbar.Report($"Jexus Manager started", ErrorLevel.Info); Application.ThreadException += (sender, args) => { Rollbar.Report(args.Exception); }; AppDomain.CurrentDomain.UnhandledException += (sender, args) => { Rollbar.Report(args.ExceptionObject as Exception); }; TaskScheduler.UnobservedTaskException += (sender, args) => { Rollbar.Report(args.Exception); }; }
public RollbarFixture() { Rollbar.Init(new RollbarConfig { AccessToken = _accessToken, Environment = "unit-tests" }); }
public static string CleanUpSni(this Binding binding) { #if !IIS if (!binding.GetIsSni()) { return(string.Empty); } #endif try { var hash = binding.CertificateHash == null ? string.Empty : Hex.ToHexString(binding.CertificateHash); // remove sni mapping using (var process = new Process()) { var start = process.StartInfo; start.Verb = "runas"; start.FileName = "cmd"; start.Arguments = $"/c \"\"{Path.Combine(Environment.CurrentDirectory, "certificateinstaller.exe")}\" /h:\"{hash}\" /s:{binding.CertificateStoreName}\" /i:{AppIdIisExpress} /o:{binding.EndPoint.Port} /x:{binding.Host}"; start.CreateNoWindow = true; start.WindowStyle = ProcessWindowStyle.Hidden; process.Start(); process.WaitForExit(); if (process.ExitCode != 0) { return("Remove SNI certificate failed: access is denied"); } return(string.Empty); } } catch (Win32Exception ex) { // elevation is cancelled. if (ex.NativeErrorCode != NativeMethods.ErrorCancelled) { Rollbar.Report(ex, ErrorLevel.Error, new Dictionary <string, object> { { "native", ex.NativeErrorCode } }); return($"Remove SNI certificate failed: unknown (native {ex.NativeErrorCode})"); } return("Remove SNI certificate failed: operation is cancelled"); } catch (NullReferenceException ex) { Rollbar.Report(ex, ErrorLevel.Error, new Dictionary <string, object> { { "binding", binding.ToString() }, { "endpointNull", binding.EndPoint == null } }); return($"Remove SNI certificate failed: unknown ({ex.Message})"); } catch (Exception ex) { Rollbar.Report(ex, ErrorLevel.Error); return($"Remove SNI certificate failed: unknown ({ex.Message})"); } }
static void Main(string[] args) { const string postServerItemAccessToken = "17965fa5041749b6bf7095a190001ded"; Rollbar.Init(new RollbarConfig(postServerItemAccessToken) { Environment = "proxyTest" }); Rollbar.Report("Solving proxy issues..."); }
private void button1_Click(object sender, EventArgs args) { try { List <string> foo = null; foo.Add("test"); } catch (Exception e) { Rollbar.Report(e); } }
private void Create() { var dialog = new NewReservedUrlDialog(Module, this); if (dialog.ShowDialog() != DialogResult.OK) { return; } try { // add reserved URL using (var process = new Process()) { var start = process.StartInfo; start.Verb = "runas"; start.FileName = "cmd"; start.Arguments = $"/c \"\"{Path.Combine(Environment.CurrentDirectory, "certificateinstaller.exe")}\" /u:\"{dialog.Item.UrlPrefix}\""; start.CreateNoWindow = true; start.WindowStyle = ProcessWindowStyle.Hidden; process.Start(); process.WaitForExit(); if (process.ExitCode == 0) { Items.Add(dialog.Item); OnHttpApiSettingsSaved(); } else { var service = (IManagementUIService)GetService(typeof(IManagementUIService)); service.ShowMessage("Invalid URL prefix input is detected.", Name, MessageBoxButtons.OK, MessageBoxIcon.Warning); } } } catch (Win32Exception ex) { // elevation is cancelled. if (ex.NativeErrorCode != Microsoft.Web.Administration.NativeMethods.ErrorCancelled) { Rollbar.Report(ex, ErrorLevel.Error, new Dictionary <string, object> { { "native", ex.NativeErrorCode } }); // throw; } } catch (Exception ex) { Rollbar.Report(ex, ErrorLevel.Error); } }
public void Remove() { var dialog = (IManagementUIService)GetService(typeof(IManagementUIService)); if ( dialog.ShowMessage("Are you sure that you want to remove this IP mapping?", "Confirm Remove", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) != DialogResult.Yes) { return; } try { // remove IP mapping using (var process = new Process()) { var start = process.StartInfo; start.Verb = "runas"; start.FileName = "cmd"; start.Arguments = $"/c \"\"{Path.Combine(Environment.CurrentDirectory, "certificateinstaller.exe")}\" /a:\"{SelectedItem.Address}\" /o:{SelectedItem.Port}\""; start.CreateNoWindow = true; start.WindowStyle = ProcessWindowStyle.Hidden; process.Start(); process.WaitForExit(); if (process.ExitCode == 0) { Items.Remove(SelectedItem); SelectedItem = null; OnHttpApiSettingsSaved(); } } } catch (Win32Exception ex) { // elevation is cancelled. if (ex.NativeErrorCode != Microsoft.Web.Administration.NativeMethods.ErrorCancelled) { Rollbar.Report(ex, ErrorLevel.Error, new Dictionary <string, object> { { "native", ex.NativeErrorCode } }); // throw; } } catch (Exception ex) { Rollbar.Report(ex, ErrorLevel.Error); } }
protected void Application_Start() { RegisterBotDependencies(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); AutoMapperConfig.RegisterMappings(); Rollbar.Init(new RollbarConfig { AccessToken = ConfigurationManager.AppSettings["Rollbar.AccessToken"], Environment = ConfigurationManager.AppSettings["Rollbar.Environment"] }); ScheduleJobs(); }
internal override bool GetSiteState(Site site) { try { using (var process = new Process()) { var start = process.StartInfo; start.Verb = site.Bindings.ElevationRequired && !PublicNativeMethods.IsProcessElevated ? "runas" : null; start.FileName = "cmd"; start.Arguments = $"/c \"\"{Path.Combine(Environment.CurrentDirectory, "certificateinstaller.exe")}\" /config:\"{site.FileContext.FileName}\" /siteId:{site.Id}\""; start.CreateNoWindow = true; start.WindowStyle = ProcessWindowStyle.Hidden; process.Start(); process.WaitForExit(); return(process.ExitCode == 1); } } catch (Win32Exception ex) { // elevation is cancelled. if (ex.NativeErrorCode != NativeMethods.ErrorCancelled) { Rollbar.Report(ex, ErrorLevel.Error, new Dictionary <string, object> { { "native", ex.NativeErrorCode } }); // throw; } } catch (InvalidOperationException ex) { if (ex.HResult != NativeMethods.NoProcessAssociated) { Rollbar.Report(ex, ErrorLevel.Error, new Dictionary <string, object> { { "hresult", ex.HResult } }); } } catch (Exception ex) { Rollbar.Report(ex, ErrorLevel.Error); } return(true); }
public async Task <HttpResponseMessage> Post([FromBody] Activity activity, CancellationToken token) { try { if (activity.Type == ActivityTypes.Message) { using (var scope = DialogModule.BeginLifetimeScope(Conversation.Container, activity)) { var dialog = scope.Resolve <IRootDialog>(); await Conversation.SendAsync(activity, () => dialog); } } else { await HandleSystemMessage(activity); } } catch (Exception e) { var st = new StackTrace(e, true); // create the stack trace var query = st.GetFrames() // get the frames .Select(frame => new { // get the info FileName = frame.GetFileName(), LineNumber = frame.GetFileLineNumber(), ColumnNumber = frame.GetFileColumnNumber(), Method = frame.GetMethod(), Class = frame.GetMethod().DeclaringType, execption = e }); var builder = new StringBuilder(); foreach (var qr in query) { builder.AppendLine($"file: {qr.FileName}, line: {qr.LineNumber}, column: {qr.ColumnNumber}"); builder.AppendLine($"class: {qr.Class}"); builder.AppendLine($"method: {qr.Method}"); builder.AppendLine(); builder.AppendLine(); builder.AppendLine($"execption: {qr.execption}"); } Rollbar.Report(builder.ToString()); } return(Request.CreateResponse(HttpStatusCode.OK)); }
private static void Main() { #if !DEBUG var config = new RollbarConfig(Resources.Rollbar_Access); Rollbar.Init(config); AppDomain.CurrentDomain.AssemblyResolve += OnResolveAssembly; Application.ThreadException += (sender, args) => { Rollbar.Report(args.Exception); }; AppDomain.CurrentDomain.UnhandledException += (sender, args) => { Rollbar.Report(args.ExceptionObject as Exception); }; Rollbar.Init(new RollbarConfig(Resources.Rollbar_Access)); #endif Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(MainF = new MainForm()); }
public RollbarLogger(IConfigurationUtility configurationUtility) { var rollbarOptions = Options.Create(new RollbarOptions { AccessToken = configurationUtility.RollbarAccessToken, Environment = configurationUtility.RollbarEnvironment }); this.Rollbar = new Rollbar( new IBuilder[] { new ConfigurationBuilder(rollbarOptions), new EnvironmentBuilder(new SystemDateTime()), new NotifierBuilder() }, new IExceptionBuilder[] { new ExceptionBuilder() }, new RollbarClient(rollbarOptions) ); }
public async Task Invoke(HttpContext context, Rollbar rollbar) { try { await this.Next(context); } catch (Exception exception) { var response = await rollbar.SendException(exception); var rollbarResponseFeature = new RollbarResponseFeature { Handled = true, Uuid = response.Result.Uuid }; context.Features.Set <IRollbarResponseFeature>(rollbarResponseFeature); // Continue throwing up the stack, we just log, let someone else handle. throw; } }
static void Main() { Rollbar.Init(new RollbarConfig { AccessToken = "POST_SERVER_ACCESS_TOKEN", Environment = "production" }); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.ThreadException += (sender, args) => { Rollbar.Report(args.Exception); }; AppDomain.CurrentDomain.UnhandledException += (sender, args) => { Rollbar.Report(args.ExceptionObject as System.Exception); }; Application.Run(new Form1()); }
public void ReportFromCatch() { try { Rollbar.Init(new RollbarConfig { AccessToken = _accessToken, Environment = Environment.MachineName }); var a = 10; var b = 0; var c = a / b; } catch (System.Exception e) { var log = "Multi" + Environment.NewLine + "Lines"; var dictionary = new Dictionary <string, object> { { "message", log } }; Rollbar.Report(e, ErrorLevel.Error, dictionary); } }
public static bool AddReservedUrl(string url) { try { // add reserved URL using (var process = new Process()) { var start = process.StartInfo; start.Verb = "runas"; start.FileName = "cmd"; start.Arguments = $"/c \"\"{Path.Combine(Environment.CurrentDirectory, "certificateinstaller.exe")}\" /u:\"{url}\""; start.CreateNoWindow = true; start.WindowStyle = ProcessWindowStyle.Hidden; process.Start(); process.WaitForExit(); return(process.ExitCode == 0); } } catch (Win32Exception ex) { // elevation is cancelled. if (ex.NativeErrorCode != Microsoft.Web.Administration.NativeMethods.ErrorCancelled) { Rollbar.Report(ex, ErrorLevel.Error, new Dictionary <string, object> { { "native", ex.NativeErrorCode } }); // throw; } } catch (Exception ex) { Rollbar.Report(ex, ErrorLevel.Error); } return(false); }
private static void RegisterRollbar() { Console.WriteLine("Note that Rollbar API is enabled by default to collect crashes. If you want to opt out, please run with -s switch"); Rollbar.Init(new RollbarConfig { AccessToken = "1dd3cf880c5a46eeb4338dbea73f9620", Environment = "production" }); Application.ThreadException += (sender, args) => { Rollbar.Report(args.Exception); }; AppDomain.CurrentDomain.UnhandledException += (sender, args) => { Rollbar.Report(args.ExceptionObject as System.Exception); }; TaskScheduler.UnobservedTaskException += (sender, args) => { Rollbar.Report(args.Exception); }; }
internal static string FixCertificateMapping(this Binding binding, X509Certificate2 certificate2) { if (binding.Protocol == "http") { return(string.Empty); } if (binding.Parent.Parent.Server.SupportsSni) { if (binding.GetIsSni()) { if (certificate2.GetNameInfo(X509NameType.DnsName, false) != binding.Host) { return("SNI mode requires host name matches common name of the certificate"); } // handle SNI var sni = NativeMethods.QuerySslSniInfo(new Tuple <string, int>(binding.Host, binding.EndPoint.Port)); if (sni == null) { try { // register mapping using (var process = new Process()) { var start = process.StartInfo; start.Verb = "runas"; start.FileName = "cmd"; start.Arguments = $"/c \"\"{Path.Combine(Environment.CurrentDirectory, "certificateinstaller.exe")}\" /h:\"{Hex.ToHexString(binding.CertificateHash)}\" /s:{binding.CertificateStoreName}\" /i:{AppIdIisExpress} /a:{binding.EndPoint.Address} /o:{binding.EndPoint.Port} /x:{binding.Host}"; start.CreateNoWindow = true; start.WindowStyle = ProcessWindowStyle.Hidden; process.Start(); process.WaitForExit(); if (process.ExitCode != 0) { return("Register new certificate failed: access is denied"); } return(string.Empty); } } catch (Win32Exception ex) { // elevation is cancelled. if (ex.NativeErrorCode != NativeMethods.ErrorCancelled) { Rollbar.Report(ex, ErrorLevel.Error, new Dictionary <string, object> { { "native", ex.NativeErrorCode } }); return($"Register new certificate failed: unknown (native {ex.NativeErrorCode})"); } return("Register new certificate failed: operation is cancelled"); } catch (Exception ex) { Rollbar.Report(ex, ErrorLevel.Error); return($"Register new certificate failed: unknown ({ex.Message})"); } } if (!sni.Hash.SequenceEqual(binding.CertificateHash)) { // TODO: fix the error message. var result = MessageBox.Show( "At least one other site is using the same HTTPS binding and the binding is configured with a different certificate. Are you sure that you want to reuse this HTTPS binding and reassign the other site or sites to use the new certificate?", "TODO", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1); if (result != DialogResult.Yes) { return ("Certificate hash does not match. Please use the certificate that matches HTTPS binding"); } try { // register mapping using (var process = new Process()) { var start = process.StartInfo; start.Verb = "runas"; start.FileName = "cmd"; start.Arguments = $"/c \"\"{Path.Combine(Environment.CurrentDirectory, "certificateinstaller.exe")}\" /h:\"{Hex.ToHexString(binding.CertificateHash)}\" /s:{binding.CertificateStoreName}\" /i:{AppIdIisExpress} /a:{binding.EndPoint.Address} /o:{binding.EndPoint.Port} /x:{binding.Host}"; start.CreateNoWindow = true; start.WindowStyle = ProcessWindowStyle.Hidden; process.Start(); process.WaitForExit(); if (process.ExitCode != 0) { return("Register new certificate failed: access is denied"); } return(string.Empty); } } catch (Win32Exception ex) { // elevation is cancelled. if (ex.NativeErrorCode != NativeMethods.ErrorCancelled) { Rollbar.Report(ex, ErrorLevel.Error, new Dictionary <string, object> { { "native", ex.NativeErrorCode } }); return($"Register new certificate failed: unknown (native {ex.NativeErrorCode})"); } return("Register new certificate failed: operation is cancelled"); } catch (Exception ex) { Rollbar.Report(ex, ErrorLevel.Error); return($"Register new certificate failed: unknown ({ex.Message})"); } } if (!string.Equals(sni.StoreName, binding.CertificateStoreName, StringComparison.OrdinalIgnoreCase)) { // TODO: can this happen? return ("Certificate store name does not match. Please use the certificate that matches HTTPS binding"); } return(string.Empty); } } // handle IP based var certificate = NativeMethods.QuerySslCertificateInfo(binding.EndPoint); if (certificate == null) { try { // register mapping using (var process = new Process()) { var start = process.StartInfo; start.Verb = "runas"; start.FileName = "cmd"; start.Arguments = $"/c \"\"{Path.Combine(Environment.CurrentDirectory, "certificateinstaller.exe")}\" /h:\"{Hex.ToHexString(binding.CertificateHash)}\" /s:{binding.CertificateStoreName}\" /i:{AppIdIisExpress} /a:{binding.EndPoint.Address} /o:{binding.EndPoint.Port}"; start.CreateNoWindow = true; start.WindowStyle = ProcessWindowStyle.Hidden; process.Start(); process.WaitForExit(); if (process.ExitCode != 0) { return("Register new certificate failed: access is denied"); } return(string.Empty); } } catch (Win32Exception ex) { // elevation is cancelled. if (ex.NativeErrorCode != NativeMethods.ErrorCancelled) { Rollbar.Report(ex, ErrorLevel.Error, new Dictionary <string, object> { { "native", ex.NativeErrorCode } }); return($"Register new certificate failed: unknown (native {ex.NativeErrorCode})"); } return("Register new certificate failed: operation is cancelled"); } catch (Exception ex) { Rollbar.Report(ex, ErrorLevel.Error); return($"Register new certificate failed: unknown ({ex.Message})"); } } if (!certificate.Hash.SequenceEqual(binding.CertificateHash)) { var result = MessageBox.Show( "At least one other site is using the same HTTPS binding and the binding is configured with a different certificate. Are you sure that you want to reuse this HTTPS binding and reassign the other site or sites to use the new certificate?", "TODO", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1); if (result != DialogResult.Yes) { return("Certificate hash does not match. Please use the certificate that matches HTTPS binding"); } try { // register mapping using (var process = new Process()) { var start = process.StartInfo; start.Verb = "runas"; start.FileName = "cmd"; start.Arguments = $"/c \"\"{Path.Combine(Environment.CurrentDirectory, "certificateinstaller.exe")}\" /h:\"{Hex.ToHexString(binding.CertificateHash)}\" /s:{binding.CertificateStoreName}\" /i:{AppIdIisExpress} /a:{binding.EndPoint.Address} /o:{binding.EndPoint.Port}"; start.CreateNoWindow = true; start.WindowStyle = ProcessWindowStyle.Hidden; process.Start(); process.WaitForExit(); if (process.ExitCode != 0) { return("Register new certificate failed: access is denied"); } return(string.Empty); } } catch (Win32Exception ex) { // elevation is cancelled. if (ex.NativeErrorCode != NativeMethods.ErrorCancelled) { Rollbar.Report(ex, ErrorLevel.Error, new Dictionary <string, object> { { "native", ex.NativeErrorCode } }); return($"Register new certificate failed: unknown (native {ex.NativeErrorCode})"); } return("Register new certificate failed: operation is cancelled"); } catch (Exception ex) { Rollbar.Report(ex, ErrorLevel.Error); return($"Register new certificate failed: unknown ({ex.Message})"); } } if (!string.Equals(certificate.StoreName, binding.CertificateStoreName, StringComparison.OrdinalIgnoreCase)) { // TODO: can this happen? return ("Certificate store name does not match. Please use the certificate that matches HTTPS binding"); } return(string.Empty); }
public RollbarDotNetLogger(Rollbar rollbar) { Rollbar = rollbar; }
public CompleteRequestDialog(IServiceProvider serviceProvider) : base(serviceProvider) { InitializeComponent(); cbStore.SelectedIndex = 0; if (Environment.OSVersion.Version < Version.Parse("6.2")) { // IMPORTANT: WebHosting store is available since Windows 8. cbStore.Enabled = false; } if (!Helper.IsRunningOnMono()) { NativeMethods.TryAddShieldToButton(btnOK); } var container = new CompositeDisposable(); FormClosed += (sender, args) => container.Dispose(); container.Add( Observable.FromEventPattern <EventArgs>(txtName, "TextChanged") .ObserveOn(System.Threading.SynchronizationContext.Current) .Subscribe(evt => { btnOK.Enabled = !string.IsNullOrWhiteSpace(txtName.Text) && !string.IsNullOrWhiteSpace(txtPath.Text); })); container.Add( Observable.FromEventPattern <EventArgs>(btnOK, "Click") .ObserveOn(System.Threading.SynchronizationContext.Current) .Subscribe(evt => { if (!File.Exists(txtPath.Text)) { ShowMessage( string.Format( "There was an error while performing this operation.{0}{0}Details:{0}{0}Could not find file '{1}'.", Environment.NewLine, txtPath.Text), MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1); return; } var p12File = DialogHelper.GetTempFileName(); var p12pwd = "test"; try { // TODO: check administrator permission. var x509 = new X509Certificate2(txtPath.Text); var filename = DialogHelper.GetPrivateKeyFile(x509.Subject); if (!File.Exists(filename)) { ShowMessage( string.Format( "There was an error while performing this operation.{0}{0}Details:{0}{0}Could not find private key for '{1}'.", Environment.NewLine, txtPath.Text), MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1); return; } x509.PrivateKey = PrivateKey.CreateFromFile(filename).RSA; x509.FriendlyName = txtName.Text; var raw = x509.Export(X509ContentType.Pfx, p12pwd); File.WriteAllBytes(p12File, raw); Item = x509; } catch (Exception ex) { ShowError(ex, string.Empty, false); return; } Store = cbStore.SelectedIndex == 0 ? "Personal" : "WebHosting"; try { // add certificate using (var process = new Process()) { var start = process.StartInfo; start.Verb = "runas"; start.FileName = "cmd"; start.Arguments = string.Format("/c \"\"{4}\" /f:\"{0}\" /p:{1} /n:\"{2}\" /s:{3}\"", p12File, p12pwd, txtName.Text, cbStore.SelectedIndex == 0 ? "MY" : "WebHosting", Path.Combine(Environment.CurrentDirectory, "certificateinstaller.exe")); start.CreateNoWindow = true; start.WindowStyle = ProcessWindowStyle.Hidden; process.Start(); process.WaitForExit(); File.Delete(p12File); if (process.ExitCode == 0) { DialogResult = DialogResult.OK; } else { MessageBox.Show(process.ExitCode.ToString()); } } } catch (Win32Exception ex) { // elevation is cancelled. if (ex.NativeErrorCode != Microsoft.Web.Administration.NativeMethods.ErrorCancelled) { Rollbar.Report(ex, ErrorLevel.Error, new Dictionary <string, object> { { "native", ex.NativeErrorCode } }); // throw; } } catch (Exception ex) { Rollbar.Report(ex, ErrorLevel.Error); } })); container.Add( Observable.FromEventPattern <EventArgs>(btnBrowse, "Click") .ObserveOn(System.Threading.SynchronizationContext.Current) .Subscribe(evt => { DialogHelper.ShowOpenFileDialog(txtPath, "*.cer|*.cer|*.*|*.*"); })); }
public void ReportException() { var guid = Rollbar.Report(new System.Exception("test exception"), ErrorLevel.Error, null); Assert.NotNull(guid); }
public SelfCertificateDialog(IServiceProvider serviceProvider) : base(serviceProvider) { InitializeComponent(); cbStore.SelectedIndex = 0; cbLength.SelectedIndex = 3; cbHashing.SelectedIndex = 1; txtCommonName.Text = Environment.MachineName; if (Environment.OSVersion.Version < Version.Parse("6.2")) { // IMPORTANT: WebHosting store is available since Windows 8. cbStore.Enabled = false; } if (!Helper.IsRunningOnMono()) { NativeMethods.TryAddShieldToButton(btnOK); } var container = new CompositeDisposable(); FormClosed += (sender, args) => container.Dispose(); container.Add( Observable.FromEventPattern <EventArgs>(txtName, "TextChanged") .ObserveOn(System.Threading.SynchronizationContext.Current) .Subscribe(evt => { btnOK.Enabled = !string.IsNullOrWhiteSpace(txtName.Text); })); container.Add( Observable.FromEventPattern <EventArgs>(btnOK, "Click") .ObserveOn(System.Threading.SynchronizationContext.Current) .Subscribe(evt => { var name = txtCommonName.Text; // Generate certificate string defaultIssuer = string.Format("CN={0}", name); string defaultSubject = defaultIssuer; byte[] sn = Guid.NewGuid().ToByteArray(); string subject = defaultSubject; string issuer = defaultIssuer; DateTime notBefore = DateTime.Now; DateTime notAfter = new DateTime(643445675990000000); // 12/31/2039 23:59:59Z RSA issuerKey = new RSACryptoServiceProvider(int.Parse(cbLength.Text)); RSA subjectKey = null; CspParameters subjectParams = new CspParameters(); CspParameters issuerParams = new CspParameters(); BasicConstraintsExtension bce = new BasicConstraintsExtension { PathLenConstraint = BasicConstraintsExtension.NoPathLengthConstraint, CertificateAuthority = true }; ExtendedKeyUsageExtension eku = new ExtendedKeyUsageExtension(); eku.KeyPurpose.Add("1.3.6.1.5.5.7.3.1"); SubjectAltNameExtension alt = null; string p12File = Path.GetTempFileName(); string p12pwd = "test"; // serial number MUST be positive if ((sn[0] & 0x80) == 0x80) { sn[0] -= 0x80; } if (subject != defaultSubject) { issuer = subject; issuerKey = null; } else { subject = issuer; subjectKey = issuerKey; } if (subject == null) { throw new Exception("Missing Subject Name"); } X509CertificateBuilder cb = new X509CertificateBuilder(3); cb.SerialNumber = sn; cb.IssuerName = issuer; cb.NotBefore = notBefore; cb.NotAfter = notAfter; cb.SubjectName = subject; cb.SubjectPublicKey = subjectKey; // extensions if (bce != null) { cb.Extensions.Add(bce); } if (eku != null) { cb.Extensions.Add(eku); } if (alt != null) { cb.Extensions.Add(alt); } IDigest digest = new Sha1Digest(); byte[] resBuf = new byte[digest.GetDigestSize()]; var spki = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(DotNetUtilities.GetRsaPublicKey(issuerKey)); byte[] bytes = spki.PublicKeyData.GetBytes(); digest.BlockUpdate(bytes, 0, bytes.Length); digest.DoFinal(resBuf, 0); cb.Extensions.Add(new SubjectKeyIdentifierExtension { Identifier = resBuf }); cb.Extensions.Add(new AuthorityKeyIdentifierExtension { Identifier = resBuf }); SubjectAltNameExtension subjectAltNameExtension = new SubjectAltNameExtension( new string[0], new string[1] { name }, new string[0], new string[0]) { Critical = false }; cb.Extensions.Add(subjectAltNameExtension); // signature string hashName = cbHashing.SelectedIndex == 0 ? "SHA1" : "SHA256"; cb.Hash = hashName; byte[] rawcert = cb.Sign(issuerKey); PKCS12 p12 = new PKCS12(); p12.Password = p12pwd; ArrayList list = new ArrayList(); // we use a fixed array to avoid endianess issues // (in case some tools requires the ID to be 1). list.Add(new byte[] { 1, 0, 0, 0 }); Hashtable attributes = new Hashtable(1); attributes.Add(PKCS9.localKeyId, list); p12.AddCertificate(new X509Certificate(rawcert), attributes); p12.AddPkcs8ShroudedKeyBag(subjectKey, attributes); p12.SaveToFile(p12File); Item = new X509Certificate2(p12File, p12pwd) { FriendlyName = txtName.Text }; Store = cbStore.SelectedIndex == 0 ? "Personal" : "WebHosting"; try { using (var process = new Process()) { // add certificate var start = process.StartInfo; start.Verb = "runas"; start.FileName = "cmd"; start.Arguments = string.Format("/c \"\"{4}\" /f:\"{0}\" /p:{1} /n:\"{2}\" /s:{3}\"", p12File, p12pwd, txtName.Text, cbStore.SelectedIndex == 0 ? "MY" : "WebHosting", Path.Combine(Environment.CurrentDirectory, "certificateinstaller.exe")); start.CreateNoWindow = true; start.WindowStyle = ProcessWindowStyle.Hidden; process.Start(); process.WaitForExit(); File.Delete(p12File); if (process.ExitCode == 0) { DialogResult = DialogResult.OK; } else { MessageBox.Show(process.ExitCode.ToString()); } } } catch (Win32Exception ex) { // elevation is cancelled. if (ex.NativeErrorCode != Microsoft.Web.Administration.NativeMethods.ErrorCancelled) { Rollbar.Report(ex, ErrorLevel.Error, new Dictionary <string, object> { { "native", ex.NativeErrorCode } }); // throw; } } catch (Exception ex) { Rollbar.Report(ex, ErrorLevel.Error); } })); }
public void ReportMessage() { var guid = Rollbar.Report("test message", ErrorLevel.Error, null); Assert.NotNull(guid); }
private static int Main(string[] args) { bool showHelp = false; bool showVersion = false; bool suppress = false; OptionSet p = new OptionSet() .Add("h|?|help", "Print this help information.", delegate(string v) { showHelp = v != null; }) .Add("s|suppress", "Suppress Rollbar crash report.", delegate(string v) { suppress = v != null; }) .Add("V", "Display version number of this application.", delegate(string v) { showVersion = v != null; }); if (args.Length == 0) { ShowHelp(p); return(0); } List <string> extra; try { extra = p.Parse(args); } catch (OptionException ex) { Console.WriteLine(ex.Message); return(1); } if (showHelp) { ShowHelp(p); return(0); } if (showVersion) { Console.WriteLine(Assembly.GetExecutingAssembly().GetName().Version); return(0); } if (extra.Count < 1) { ShowHelp(p); return(1); } if (!suppress) { RegisterRollbar(); } int start = Environment.TickCount; foreach (var project in extra) { try { Console.Write("Loading project {0}...", project); Obfuscator obfuscator = new Obfuscator(project); Console.WriteLine("Done."); obfuscator.RunRules(); Console.WriteLine("Completed, {0:f2} secs.", (Environment.TickCount - start) / 1000.0); } catch (ObfuscarException e) { if (!suppress) { Rollbar.Report(e); } Console.WriteLine(); Console.Error.WriteLine("An error occurred during processing:"); Console.Error.WriteLine(e.Message); if (e.InnerException != null) { Console.Error.WriteLine(e.InnerException.Message); } return(1); } } return(0); }
private async Task PublishErrorReportToRollbarAsync(OwnerMetaData owner, LambdaErrorReport report) { if (owner == null) { throw new ArgumentNullException(nameof(owner)); } if (owner.RollbarAccessToken == null) { return; } // convert error report into rollbar data structure var rollbar = new Rollbar { AccessToken = owner.RollbarAccessToken, Data = new Data { Environment = report.ModuleId, Level = report.Level?.ToLowerInvariant() ?? "error", Timestamp = report.Timestamp, CodeVersion = report.GitSha, Platform = report.Platform, Language = report.Language, Framework = report.Framework, Fingerprint = report.Fingerprint, Title = $"{report.FunctionName}: {report.Message}", Custom = new { report.Message, report.Module, report.ModuleId, report.FunctionId, report.FunctionName, report.GitBranch, report.RequestId }, Body = new DataBody { TraceChain = report.Traces?.Select(trace => new Trace { Exception = new ExceptionClass { Class = trace.Exception?.Type, Message = trace.Exception?.Message, Description = trace.Exception?.StackTrace }, Frames = trace.Frames?.Select(frame => new Frame { Filename = frame.FileName, Lineno = frame.LineNumber.GetValueOrDefault(), Method = frame.MethodName }).ToArray() }).ToArray() } } }; // in case there are no captured traces, inject a simple error message if (rollbar.Data.Body.TraceChain?.Any() != true) { rollbar.Data.Body.TraceChain = null; rollbar.Data.Body = new DataBody { Message = new Message { Body = report.Raw } }; } // send payload to rollbar try { var response = _rollbarClient.SendRollbarPayload(rollbar); LogInfo($"Rollbar.SendRollbarPayload() succeeded: {response}"); } catch (WebException e) { if (e.Response == null) { LogWarn($"Rollbar request failed (status: {e.Status}, message: {e.Message})"); } else { using (var stream = e.Response.GetResponseStream()) { if (stream == null) { LogWarn($"Rollbar.SendRollbarPayload() failed: {e.Status}"); } using (var reader = new StreamReader(stream)) { LogWarn($"Rollbar.SendRollbarPayload() failed: {reader.ReadToEnd()}"); } } } } catch (Exception e) { LogErrorAsWarning(e, "Rollbar.SendRollbarPayload() failed"); } }
public ImportCertificateDialog(IServiceProvider serviceProvider) : base(serviceProvider) { InitializeComponent(); cbStore.SelectedIndex = 0; if (Environment.OSVersion.Version < Version.Parse("6.2")) { // IMPORTANT: WebHosting store is available since Windows 8. cbStore.Enabled = false; } if (!Helper.IsRunningOnMono()) { JexusManager.NativeMethods.TryAddShieldToButton(btnOK); } var container = new CompositeDisposable(); FormClosed += (sender, args) => container.Dispose(); container.Add( Observable.FromEventPattern <EventArgs>(btnBrowse, "Click") .ObserveOn(System.Threading.SynchronizationContext.Current) .Subscribe(evt => { DialogHelper.ShowOpenFileDialog(txtFile, ".pfx|*.pfx|*.*|*.*"); })); container.Add( Observable.FromEventPattern <EventArgs>(txtFile, "TextChanged") .Sample(TimeSpan.FromSeconds(1)) .ObserveOn(System.Threading.SynchronizationContext.Current) .Subscribe(evt => { btnOK.Enabled = !string.IsNullOrWhiteSpace(txtFile.Text); })); container.Add( Observable.FromEventPattern <EventArgs>(btnOK, "Click") .ObserveOn(System.Threading.SynchronizationContext.Current) .Subscribe(evt => { try { // Load your certificate from file Item = new X509Certificate2(txtFile.Text, txtPassword.Text, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet); Store = cbStore.SelectedIndex == 0 ? "Personal" : "WebHosting"; var service = (IConfigurationService)GetService(typeof(IConfigurationService)); if (service.ServerManager.Mode == WorkingMode.Jexus) { var server = (JexusServerManager)service.Server; // Public Key; StringBuilder publicBuilder = new StringBuilder(); publicBuilder.AppendLine("-----BEGIN CERTIFICATE-----"); publicBuilder.AppendLine(Convert.ToBase64String(Item.Export(X509ContentType.Cert), Base64FormattingOptions.InsertLineBreaks)); publicBuilder.AppendLine("-----END CERTIFICATE-----"); var file = AsyncHelper.RunSync(() => server.SaveCertificateAsync(publicBuilder.ToString())); server.SetCertificate(file); // Private Key RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)Item.PrivateKey; MemoryStream memoryStream = new MemoryStream(); TextWriter streamWriter = new StreamWriter(memoryStream); PemWriter pemWriter = new PemWriter(streamWriter); AsymmetricCipherKeyPair keyPair = DotNetUtilities.GetRsaKeyPair(rsa); pemWriter.WriteObject(keyPair.Private); streamWriter.Flush(); string output = Encoding.ASCII.GetString(memoryStream.GetBuffer()).Trim(); int indexOfFooter = output.IndexOf("-----END RSA PRIVATE KEY-----", StringComparison.Ordinal); memoryStream.Close(); streamWriter.Close(); string key = output.Substring(0, indexOfFooter + 29); var keyFile = AsyncHelper.RunSync(() => server.SaveKeyAsync(key)); server.SetKeyFile(keyFile); service.ServerManager.CommitChanges(); } else { try { using (var process = new Process()) { // add certificate var start = process.StartInfo; start.Verb = "runas"; start.FileName = "cmd"; start.Arguments = string.Format( "/c \"\"{4}\" /f:\"{0}\" /p:{1} /n:\"{2}\" /s:{3}\"", txtFile.Text, txtPassword.Text, Item.FriendlyName, cbStore.SelectedIndex == 0 ? "MY" : "WebHosting", Path.Combine(Environment.CurrentDirectory, "certificateinstaller.exe")); start.CreateNoWindow = true; start.WindowStyle = ProcessWindowStyle.Hidden; process.Start(); process.WaitForExit(); if (process.ExitCode == 0) { DialogResult = DialogResult.OK; } else { MessageBox.Show(process.ExitCode.ToString()); } } } catch (Win32Exception ex) { // elevation is cancelled. if (ex.NativeErrorCode != NativeMethods.ErrorCancelled) { Rollbar.Report(ex, ErrorLevel.Error, new Dictionary <string, object> { { "native", ex.NativeErrorCode } }); // throw; } } catch (Exception ex) { Rollbar.Report(ex, ErrorLevel.Error); } } } catch (Exception ex) { ShowError(ex, string.Empty, false); } })); }
protected void Application_Error(object sender, EventArgs e) { var exception = Server.GetLastError().GetBaseException(); Rollbar.Report(exception); }