After opening multiple web pages many times, freezing often occurs - cefsharp

I am developing a web crawler that will frequently request new web pages. During the testing process, the program often freezes.
I've written a test case that explains my usage and the scenario where the problem has occurred.
Sometimes, when it open a web page for 10 times, it may get stuck when it open it for 20 times. How many times do it open the web page, i are not sure.
using CefSharp;
using CefSharp.WinForms;
using System;
using System.Windows.Forms;
namespace WindowsFormsApp2
{
public partial class Form1 : Form
{
ChromiumWebBrowser browser;
System.Timers.Timer timer;
int i = 1;
public Form1()
{
InitializeComponent();
timer = new System.Timers.Timer(400) { AutoReset = true };//Timer, automatically open a new web page
timer.Elapsed += Timer_Elapsed;
browser = new ChromiumWebBrowser("www.baidu.com") { Parent = splitContainer1.Panel1, Dock = DockStyle.Fill };
browser.LifeSpanHandler = new LifeSpanHandler(splitContainer1.Panel2);
browser.FrameLoadEnd += Browser_FrameLoadEnd;
}
private void Browser_FrameLoadEnd(object sender, FrameLoadEndEventArgs e)
{
if (e.Frame.IsMain == false) return;
timer.Start();
}
private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
i = i > 1 ? 1 : i + 1;
browser.ExecuteScriptAsync("document.getElementsByClassName('mnav c-font-normal c-color-t')[" + (i) + "].click()");//Open a link in the web page
}
}
class LifeSpanHandler : ILifeSpanHandler
{
Control host;
internal LifeSpanHandler(Control host)
{
this.host = host;
}
public bool DoClose(IWebBrowser chromiumWebBrowser, IBrowser browser)
{
return false;
}
public void OnAfterCreated(IWebBrowser chromiumWebBrowser, IBrowser browser)
{
}
public void OnBeforeClose(IWebBrowser chromiumWebBrowser, IBrowser browser)
{
}
public bool OnBeforePopup(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, string targetUrl, string targetFrameName, WindowOpenDisposition targetDisposition, bool userGesture, IPopupFeatures popupFeatures, IWindowInfo windowInfo, IBrowserSettings browserSettings, ref bool noJavascriptAccess, out IWebBrowser newBrowser)
{
newBrowser = null;
var webBrowser = (ChromiumWebBrowser)chromiumWebBrowser;
webBrowser.Invoke(new Action(() =>
{
if (host.HasChildren) host.Controls[0].Dispose();
var control = new Control { Parent = host, Dock = DockStyle.Fill };
control.CreateControl();
windowInfo.SetAsChild(control.Handle);
}));
return false;
}
}
}
The test code is placed on GitHub, which is the visual studio 2019 project. We hope you can execute the project locally, so as to find problems more intuitively. Thank you very much.
https://github.com/haohaodz/cefsharp-form-vs2019-problem.git

Have you tested with other websites?
High frequency of requests to other websites can also lead to deadlock.
Does the problem reproduce with github.com/cefsharp/CefSharp.MinimalExample
the problem does not reproduce with github.com/cefsharp/CefSharp.MinimalExample.
in BrowserTabUserControl.cs
browser.LifeSpanHandler = new LifeSpanHandler(openPopupsAsTabs: false);
It opens a web page in a new window by default.High frequency of open multiple web pages, the freezing problem does not reproduce.
I change openPopupsAsTabs to true and open a new page in tabs
browser.LifeSpanHandler = new LifeSpanHandler(openPopupsAsTabs: true);
High frequency of open multiple web pages, the program will freezes.
The program freezes in the dispose method:
System.Windows.Forms .dll! System.Windows.Forms . UnsafeNativeMethods.DestroyWindow (
System.Runtime.InteropServices . handleref hWnd) unknown
System.Windows.Forms .dll! System.Windows.Forms . NativeWindow.DestroyHandle () unknown
System.Windows.Forms .dll! System.Windows.Forms . Control.DestroyHandle () unknown
System.Windows.Forms .dll! System.Windows.Forms . Control.Dispose (bool disposing) unknown
System.dll ! System.ComponentModel.Component . dispose() unknown
Sometimes the program exits suddenly,There is an exception:
Exception thrown:“ System.IO.PipeException ”(located at System.ServiceModel.dll (2)
Exception thrown:“ System.ServiceModel.CommunicationException ”(located at System.ServiceModel.dll (2)
Exception thrown:“ System.ServiceModel.CommunicationException ”(located at System.ServiceModel.dll (2)
Exception thrown:“ System.ServiceModel.CommunicationException ”(located at System.ServiceModel.dll (2)
Exception thrown:“ System.ServiceModel.CommunicationException ”(located at System.ServiceModel.Internals . DLL)
Exception thrown:“ System.ServiceModel.CommunicationException ”(located at System.ServiceModel.Internals . DLL)
Exception thrown:“ System.ServiceModel.CommunicationObjectFaultedException ”(located at System.ServiceModel.dll (2)

Related

exePath exception when using SAP .net connector 3.0 in ASP.net

Have a WPF app that I am converting to ASP.net and I am having issues with SAP.
When I run this line I get an exception.
RfcDestinationManager.RegisterDestinationConfiguration(Backend);
Exception Message {"exePath must be specified when not running inside a stand alone exe."}
Stack Trace
at System.Configuration.ConfigurationManager.OpenExeConfigurationImpl(ConfigurationFileMap fileMap, Boolean isMachine, ConfigurationUserLevel userLevel, String exePath, Boolean preLoad)
at System.Configuration.ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel userLevel)
at SAP.Middleware.Connector.RfcConfigParameters..cctor()
googling around I saw as similar issue here exePath must be specified when not running inside a stand alone exe
The issue seems to be using ConfigurationManager.OpenExeConfiguration rather that System.Web.Configuration.WebConfigurationManagerwhich is what I need to use. Problem is I can't change that as its part of the SAP.Net Connector.
Is there anything I can do?
Edit: My BackendConfig code
public class BackendConfig : IDestinationConfiguration
{
public RfcConfigParameters GetParameters(String destinationName)
{
if ("P38".Equals(destinationName))
{
var parms = new RfcConfigParameters
{
{RfcConfigParameters.AppServerHost, "SAPSERVER"},
{RfcConfigParameters.SystemNumber, "86"},
{RfcConfigParameters.SncMode, "1"},
{RfcConfigParameters.SncPartnerName, "p:SAP#SERVER"},
{RfcConfigParameters.Client, "010"},
{RfcConfigParameters.Language, "EN"},
{RfcConfigParameters.PoolSize, "5"}
};
return parms;
}
else return null;
}
// The following two are not used in this example:
public bool ChangeEventsSupported()
{
return false;
}
public event RfcDestinationManager.ConfigurationChangeHandler ConfigurationChanged;
}

Hosting SignalR with self host in Windows Service

I am new by signalR and Owin and need help.
I wrote all my signalR code in a library [My hub will be self hosted]. Then i referenced that lib from a windows service application, installed the Package "Microsoft.Owin.Host.HttpListener" in the windows service application and tried to execute it.
I am getting that wired exception:
Sequence contains no matching element
I tested my Library in a winForm application and it worked correctly.
I have no idea why i am getting that.
Update: Code example:
In My Library "myLib"
private IDisposable host;
private bool Start()
{
try
{
string url = "http://localhost:5000/";
host = SelfHost.Host(url);
}
catch (Exception ex)
{
log.WriteLine("************HOSTING FAILED ********************************* ex.ToString():"+ ex.ToString()+
" Ex.StackTrace: "+ex.StackTrace +" EX.Message: " + ex.Message + "***************");
}
}
private bool Stop()
{
if (host != null)
{
host.Dispose();
}
}
My SelfHost class:
class SelfHost
{
public static IDisposable Host(string url)
{
return WebApplication.Start<SelfHost>(url);
}
public void Configuration(IAppBuilder app)
{
// Turn cross domain on
var config = new HubConfiguration { EnableCrossDomain = true };
// This will map out to http://localhost:8080/signalr by default
app.MapHubs(config);
}
}
after creating an object from this lib in my windows service application:
myLib l = new myLib();
i implements the OnStart() of the windows Service which starts a thread that calls the Start()-function from myLib:
protected override void OnStart(string[] args)
{
Thread t = new Thread(new ThreadStart(this.StartServiceThread));
t.CurrentCulture = new System.Globalization.CultureInfo("en-US");
t.Start();
}
private void StartServiceThread()
{
l.Start();
}
Output [Ex-Details]
************HOSTING FAILED *********************************
ex.ToString():
System.InvalidOperationException: Sequence contains no matching element
at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source, Func`2 predicate)
at Microsoft.Owin.Hosting.ServerFactory.DefaultServerFactoryLoader.Load(String serverName)
at Microsoft.Owin.Hosting.KatanaEngine.ResolveServerFactory(StartContext context)
at Microsoft.Owin.Hosting.KatanaEngine.Start(StartContext context)
at Microsoft.Owin.Hosting.Starter.DirectHostingStarter.Start(StartOptions options)
at Microsoft.Owin.Hosting.KatanaStarter.Start(StartOptions options)
at Microsoft.Owin.Hosting.WebApplication.Start[TStartup](IServiceProvider services, StartOptions options)
at Microsoft.Owin.Hosting.WebApplication.Start[TStartup](StartOptions options)
at Microsoft.Owin.Hosting.WebApplication.Start[TStartup](String url)
at SelfHost.Host(String url) in SelfHost.cs:line 29
at myLib.Start() in myLib.cs:line 381
Ex.StackTrace:
at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source, Func`2 predicate)
at Microsoft.Owin.Hosting.ServerFactory.DefaultServerFactoryLoader.Load(String serverName)
at Microsoft.Owin.Hosting.KatanaEngine.ResolveServerFactory(StartContext context)
at Microsoft.Owin.Hosting.KatanaEngine.Start(StartContext context)
at Microsoft.Owin.Hosting.Starter.DirectHostingStarter.Start(StartOptions options)
at Microsoft.Owin.Hosting.KatanaStarter.Start(StartOptions options)
at Microsoft.Owin.Hosting.WebApplication.Start[TStartup](IServiceProvider services, StartOptions options)
at Microsoft.Owin.Hosting.WebApplication.Start[TStartup](StartOptions options)
at Microsoft.Owin.Hosting.WebApplication.Start[TStartup](String url)
at SelfHost.Host(String url) in SelfHost.cs:line 29
at myLib.Start() in myLib.cs:line 381
EX.Message: Sequence contains no matching element***************
Thanks in Advance!
I figured out what the problem was. I wrote myLib Code two months ago and was testing it using the winForms Application that i also wrote 2 months ago.
But yesterday i installed the new Owin Packages in my windows service application and tried to use the same library that i wrote before and so i got the error.
The problem is that the NuGetPackage in myLib (old version of Owin.Hosting) is not compatible with the new package version which is released 12 days ago . The new changes do not support WebApplication (from old version). It is called now WebApp.

how to load class from jar inside equinox server side application in jboss 7

I'm face a problem since few days and I can't get solution. below is my app structure:
I have ejbapp.jar inside MyearDeployedOnJboss7.ear at the same level of equinox-server-side-app.war (built using warproduct) and I want to load class from MyJarToLaoadForEjbapp.jar which is in iModernizeWebClient_1.0.0.jar which is in plugins folder of equinox-server-side-app.war (I want show image of app structure but I cannot send image because forum rules need 10 score to be able to do that)
My question is how to allow ejbapp.jar load classes from "MyJarToLaoadForEjbapp.jar" inside MyWebClient_1.0.0.jar's plugin folder which is in the equinox-server-side-app.war.
I think using servletbridge classloader but no idea how to use it.
in my launch.ini I've:
osgi.*=#null org.osgi.*=#null eclipse.*=#null osgi.parentClassloader=app osgi.contextClassLoaderParent=app
I resolved my proble using Servlet HttpServiceTracker from the OSGI spec. how to do it : write HttpServiceTracker liket that :
public class HttpServiceTracker extends ServiceTracker {
private static final Logger logger = Logger
.getLogger(HttpServiceTracker.class.getName());
public HttpServiceTracker(BundleContext context) {
super(context, HttpService.class.getName(), null);
}
public Object addingService(ServiceReference reference) {
HttpService httpService = (HttpService) context.getService(reference);
logger.info("default context path : "
+ org.eclipse.rap.ui.internal.servlet.HttpServiceTracker.ID_HTTP_CONTEXT);
try {
logger.info("will register servlet ");
httpService.registerServlet("/programLauncherServlet",
new ProgramLauncherServlet(), null, null);
logger.info("servlet has been registred with http context ");
// httpService.registerResources( "/", "/html", null );
} catch (Exception e) {
//e.printStackTrace();
logger.info("The alias '/programLauncherServlet' is already in use");
}
return httpService;
}
public void removedService(ServiceReference reference, Object service) {
logger.info("will unregister servlet ");
HttpService httpService = (HttpService) service;
httpService.unregister("/programLauncher");
super.removedService(reference, service);
logger.info("servlet has been unregistred");
}
in your plugin activator class at method start :
#Override
public void start(BundleContext context) throws Exception {
super.start(context);
Activator.plugin = this;
BundleContext osgiContext = BundleReference.class
.cast(AnyClassOfYourProject.class.getClassLoader()).getBundle()
.getBundleContext();
serviceTracker = new HttpServiceTracker(osgiContext);
serviceTracker.open();
LOGGER.info("servlet published !!");
LOGGER.info("Bundle started.");
}
and for unregister the servlet at the stop method :
public void stop(BundleContext context) throws Exception {
Activator.plugin = null;
serviceTracker.close();
serviceTracker = null;
LOGGER.info("servlet unregistered from context !!");
super.stop(context);
}
that's all. your servlet is accessible outside your eclipse bundle and you can call methods inside the bundle.

Trace Listeners in ASP.NET

I have a library assembly that outputs trace information, and a client winforms application that adds a trace listener via app.config. If I were to use the library in ASP.NET, not configured for System.Diagnostics tracing, how could I 'catch' the trace output?
Bonus question: Can I do something with Elmah to catch and log this info? Our ASP.NET app currently uses Elmah for error logging, but that's all I know on that side of things.
I think that, as long as the library outputs trace information, this information could be captured with any specialized tool (like DebugView) or even a house grown tool, regardless of ASP.NET configuration.
I see this is old and answered, but.. I have just had the same issue and I came up with
Exception class for tracelistener
namespace TrueNorth.Elmah.TraceListener
{
internal class TraceInformation : Exception
{
internal TraceInformation(string message) : base(message){}
}
internal class TraceError: Exception
{
internal TraceError(string message) : base(message) { }
}
internal class TraceWarning : Exception
{
internal TraceWarning(string message) : base(message) { }
}
internal class TraceWrite : Exception
{
internal TraceWrite(string message) : base(message) { }
}
}
The listener
namespace TrueNorth.Elmah.TraceListener
{
internal class ElmahListener : System.Diagnostics.TraceListener
{
public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string format, params object[] args)
{
TraceEvent(eventCache, source, eventType, id, string.Format(format, args));
}
public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string message) //
{
Exception exception;
switch (eventType)
{
case TraceEventType.Information:
exception = new TraceInformation(message);
break;
case TraceEventType.Error:
exception = new TraceError(message);
break;
case TraceEventType.Warning:
exception = new TraceWarning(message);
break;
default:
exception = new TraceWrite(message);
break;
}
if (HttpContext.Current.Session == null)
{
ErrorLog.GetDefault(null).Log(new Error(exception));
}
else
{
ErrorSignal.FromCurrentContext().Raise(exception );
}
}
public override void TraceTransfer(TraceEventCache eventCache, string source, int id, string message, Guid relatedActivityId)
{
base.TraceTransfer(eventCache, source, id, message, relatedActivityId);
}
public override void Write(string message)
{
}
public override void WriteLine(string message)
{
}
}
}
And, the GO code ( you can use your web.config)
Tracer.Register();
blogged at http://truenorthit.co.uk/2015/04/17/trace-listener-for-elmah-asp-mvc-exception-logger/
write code for attaching a trace file listener programtically and enable tracing in web.config - you will be done after that

Globally log exceptions from ASP.NET [ScriptService] services

I'm using the [System.Web.Script.Services.ScriptService] tag to use web services callable from client side javascript. What I need is a way of globally logging any unhandled exceptions in those methods. On the client side, I get the error callback and can proceed from there, but I need a server-side catch to log the exception.
The guy at this url:
http://ayende.com/Blog/archive/2008/01/06/ASP.Net-Ajax-Error-Handling-and-WTF.aspx
suggests that this can't be done.
Is that accurate? Do I seriously have to go to every single webmethod in the entire system and try/catch the method as a whole.
You can use an HTTP module to capture the exception message, stack trace and exception type that is thrown by the web service method.
First some background...
If a web service method throws an exception the HTTP response has a status code of 500.
If custom errors are off then the web
service will return the exception
message and stack trace to the client
as JSON. For example:{"Message":"Exception
message","StackTrace":" at
WebApplication.HelloService.HelloWorld()
in C:\Projects\Stackoverflow
Examples\WebApplication\WebApplication\HelloService.asmx.cs:line
22","ExceptionType":"System.ApplicationException"}
When custom errors are on then the
web service returns a default message
to the client and removes the stack
trace and exception type:{"Message":"There was an error processing the request.","StackTrace":"","ExceptionType":""}
So what we need to do is set custom errors off for the web service and plug in an HTTP module that:
Checks if the request is for a web service method
Checks if an exception was thrown - that is, a status code of 500 is being returned
If 1) and 2) are true then get the original JSON that would be sent to the client and replace it with the default JSON
The code below is an example of an HTTP module that does this:
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Web;
public class ErrorHandlerModule : IHttpModule {
public void Init(HttpApplication context) {
context.PostRequestHandlerExecute += OnPostRequestHandlerExecute;
context.EndRequest += OnEndRequest;
}
static void OnPostRequestHandlerExecute(object sender, EventArgs e) {
HttpApplication context = (HttpApplication) sender;
// TODO: Update with the correct check for your application
if (context.Request.Path.StartsWith("/HelloService.asmx")
&& context.Response.StatusCode == 500) {
context.Response.Filter =
new ErrorHandlerFilter(context.Response.Filter);
context.EndRequest += OnEndRequest;
}
}
static void OnEndRequest(object sender, EventArgs e) {
HttpApplication context = (HttpApplication) sender;
ErrorHandlerFilter errorHandlerFilter =
context.Response.Filter as ErrorHandlerFilter;
if (errorHandlerFilter == null) {
return;
}
string originalContent =
Encoding.UTF8.GetString(
errorHandlerFilter.OriginalBytesWritten.ToArray());
// If customErrors are Off then originalContent will contain JSON with
// the original exception message, stack trace and exception type.
// TODO: log the exception
}
public void Dispose() { }
}
This module uses the following filter to override the content sent to the client and to store the original bytes (which contain the exception message, stack trace and exception type):
public class ErrorHandlerFilter : Stream {
private readonly Stream _responseFilter;
public List OriginalBytesWritten { get; private set; }
private const string Content =
"{\"Message\":\"There was an error processing the request.\"" +
",\"StackTrace\":\"\",\"ExceptionType\":\"\"}";
public ErrorHandlerFilter(Stream responseFilter) {
_responseFilter = responseFilter;
OriginalBytesWritten = new List();
}
public override void Flush() {
byte[] bytes = Encoding.UTF8.GetBytes(Content);
_responseFilter.Write(bytes, 0, bytes.Length);
_responseFilter.Flush();
}
public override long Seek(long offset, SeekOrigin origin) {
return _responseFilter.Seek(offset, origin);
}
public override void SetLength(long value) {
_responseFilter.SetLength(value);
}
public override int Read(byte[] buffer, int offset, int count) {
return _responseFilter.Read(buffer, offset, count);
}
public override void Write(byte[] buffer, int offset, int count) {
for (int i = offset; i < offset + count; i++) {
OriginalBytesWritten.Add(buffer[i]);
}
}
public override bool CanRead {
get { return _responseFilter.CanRead; }
}
public override bool CanSeek {
get { return _responseFilter.CanSeek; }
}
public override bool CanWrite {
get { return _responseFilter.CanWrite; }
}
public override long Length {
get { return _responseFilter.Length; }
}
public override long Position {
get { return _responseFilter.Position; }
set { _responseFilter.Position = value; }
}
}
This method requires custom errors to be switched off for the web services. You would probably want to keep custom errors on for the rest of the application so the web services should be placed in a sub directory. Custom errors can be switched off in that directory only using a web.config that overrides the parent setting.
You run the Stored Procedure in the backend. Then, for a single variable, it returns more than 1 value. Because of that, a conflicts occurs, and, this error is thrown.
I know this doesn't answer the question per-say, but I went on my own quest a while back to find this out and would up empty handed. Ended up wrapping each web service call in a try/catch, and the catch calls our error logger. Sucks, but it works.
In ASP.Net it is possible to catch all run handled exceptions using a global error handler although the blog post suggest this would not work but you could experiment with this approach trying to rethrow the error in some way?
Another idea would be to look at the open source elmah (Error Logging Modules and Handlers) for ASP.Net that might help or someone in that community may have an idea.

Resources