protected override bool ProcessRequest(CefRequest request, CefCallback callback) { _uri = new Uri(request.Url); //判断是否本地目录文件 var filePath = Path.GetFullPath(System.Environment.CurrentDirectory + "\\Resources" + _uri.AbsolutePath); if (File.Exists(filePath)) { responseData = ReadFileToBinary(filePath); callback.Continue(); return(true); } //判断是否资源文件 var segments = _uri.Segments; var file = segments[segments.Length - 1]; string resource; if (resources.TryGetValue(file, out resource) && !String.IsNullOrEmpty(resource)) { responseData = Encoding.UTF8.GetBytes(resource); callback.Continue(); return(true); } process = false; callback.Continue(); return(false); }
protected override bool ProcessRequest(CefRequest request, CefCallback callback) { var u = new Uri(request.Url); var file = u.Authority + u.AbsolutePath; _totalBytesRead = 0; _fileBytes = null; _completed = false; var fileInfo = new FileInfo(file); // Check if file exists if (!fileInfo.Exists) { _chromelyErrorHandler.HandleResourceError(ResourceStatus.FileNotFound, file, out _statusCode, out _statusText); _fileBytes = _statusText.GetMemoryStream(); callback.Continue(); } // Check if file exists but empty else if (fileInfo.Length == 0) { _chromelyErrorHandler.HandleResourceError(ResourceStatus.ZeroFileSize, file, out _statusCode, out _statusText); _fileBytes = _statusText.GetMemoryStream(); callback.Continue(); } else { Task.Run(() => { using (callback) { try { _fileBytes = File.ReadAllBytes(file); string extension = Path.GetExtension(file); _mime = MimeMapper.GetMimeType(extension); _statusCode = ResourceConstants.StatusOK; _statusText = ResourceConstants.StatusOKText; } catch (Exception exception) { _chromelyErrorHandler.HandleResourceError(ResourceStatus.FileProcessingError, file, exception, out _statusCode, out _statusText); _fileBytes = _statusText.GetMemoryStream(); } finally { callback.Continue(); } } }); return(true); } callback.Dispose(); return(false); }
protected override bool ProcessRequest(CefRequest request, CefCallback callback) { uri = new Uri(request.Url); fileName = uri.AbsolutePath; // if url is blocked /*if (!myForm.IsURLOk(request.Url)) { * * // return true so it does not open up * return true; * }*/ // if url is browser file if (uri.Host == "storage") { fileName = appPath + uri.Host + fileName; if (File.Exists(fileName)) { Task.Factory.StartNew(() => { using (callback) { //var bytes = Encoding.UTF8.GetBytes(resource); //stream = new MemoryStream(bytes); FileStream fStream = new FileStream(fileName, FileMode.Open, FileAccess.Read); // mimeType = CefResourceHandler.GetMimeType(Path.GetExtension(fileName)); stream = fStream; callback.Continue(); } }); return(true); } } // if url is request for icon of another file if (uri.Host == "fileicon") { Task.Factory.StartNew(() => { using (callback) { stream = FileIconUtils.GetFileIcon(fileName, FileIconSize.Large); // mimeType = ResourceHandler.GetMimeType(".png"); callback.Continue(); } }); return(true); } // by default reject callback.Dispose(); return(false); }
private bool ProcessLocalFile(string file, CefCallback callback) { var fileInfo = new FileInfo(file); // Check if file exists if (!fileInfo.Exists) { _chromelyErrorHandler.HandleResourceError(ResourceStatus.FileNotFound, file, out _statusCode, out _statusText); _fileBytes = _statusText.GetMemoryStream(); callback.Continue(); } // Check if file exists but empty else if (fileInfo.Length == 0) { _chromelyErrorHandler.HandleResourceError(ResourceStatus.ZeroFileSize, file, out _statusCode, out _statusText); _fileBytes = _statusText.GetMemoryStream(); callback.Continue(); } else { Task.Run(() => { using (callback) { try { _fileBytes = File.ReadAllBytes(file); string extension = Path.GetExtension(file); _mime = MimeMapper.GetMimeType(extension); _statusCode = ResourceConstants.StatusOK; _statusText = ResourceConstants.StatusOKText; } catch (Exception exception) { _chromelyErrorHandler.HandleResourceError(ResourceStatus.FileProcessingError, file, exception, out _statusCode, out _statusText); _fileBytes = _statusText.GetMemoryStream(); } finally { callback.Continue(); } } }); return(true); } return(false); }
private bool ProcessLocalFile(string file, CefCallback callback) { _fileInfo = new FileInfo(file); // Check if file exists if (!_fileInfo.Exists) { _chromelyResource = _chromelyErrorHandler.HandleError(_fileInfo); callback.Continue(); } // Check if file exists but empty else if (_fileInfo.Length == 0) { _chromelyResource = _chromelyErrorHandler.HandleError(_fileInfo); callback.Continue(); } else { Task.Run(() => { using (callback) { try { var fileBytes = File.ReadAllBytes(file); _chromelyResource.Content = new MemoryStream(fileBytes); string extension = Path.GetExtension(file); _chromelyResource.MimeType = MimeMapper.GetMimeType(extension); _chromelyResource.StatusCode = ResourceConstants.StatusOK; _chromelyResource.StatusText = ResourceConstants.StatusOKText; } catch (Exception exception) { _chromelyResource = _chromelyErrorHandler.HandleError(_fileInfo, exception); } finally { callback.Continue(); } } }); return(true); } return(false); }
protected override bool ReadResponse(Stream response, int bytesToRead, out int bytesRead, CefCallback callback) { if (bytesToRead > 0) { bytesRead = bytesToRead; callback.Continue(); return(true); } else { callback.Cancel(); } bytesRead = 0; return(false); //if (bytesToRead == 0) //{ // byte[] data = Encoding.UTF8.GetBytes("<html><body><h1>Hello CEF</h1></body></html>"); // bytesRead = data.Length; // Marshal.Copy(data, 0,IntPtr.Zero, data.Length); // return true; //} //else //{ // bytesRead = 0; // return false; //} }
protected override bool ProcessRequest(CefRequest request, CefCallback callback) { var requestNo = Interlocked.Increment(ref _requestNo); var response = new StringBuilder(); response.AppendFormat("<pre>\n"); response.AppendFormat("Requests processed by DemoAppResourceHandler: {0}\n", requestNo); response.AppendFormat("Method: {0}\n", request.Method); response.AppendFormat("URL: {0}\n", request.Url); response.AppendLine(); response.AppendLine("Headers:"); var headers = request.GetHeaderMap(); foreach (string key in headers) { foreach (var value in headers.GetValues(key)) { response.AppendFormat("{0}: {1}\n", key, value); } } response.AppendLine(); response.AppendFormat("</pre>\n"); responseData = Encoding.UTF8.GetBytes(response.ToString()); callback.Continue(); return(true); }
protected override bool ProcessRequest(CefRequest request, CefCallback callback) { Task.Run(() => { using (callback) { try { _apiResponse = _apiRouter.ProcessRequest(request); if (_apiResponse.Data != null) { _logger.Debug(_apiResponse.Data); _responseBytes = Encoding.UTF8.GetBytes(_apiResponse.Data); } } catch (Exception exception) { _logger.Error(exception, exception.Message); _apiResponse = new ApiResponse(exception.Message, 500); } finally { callback.Continue(); } } }); return(true); }
protected override bool ProcessRequest(CefRequest request, CefCallback callback) { callback.Continue(); _completed = false; _transmittedLen = 0; return(true); }
protected override bool ProcessRequest(CefRequest request, CefCallback callback) { var requestNo = Interlocked.Increment(ref _requestNo); var response = new StringBuilder(); response.AppendFormat("<pre>\n"); response.AppendFormat("Requests processed by DemoAppResourceHandler: {0}\n", requestNo); response.AppendFormat("Method: {0}\n", request.Method); response.AppendFormat("URL: {0}\n", request.Url); response.AppendLine(); response.AppendLine("Headers:"); var headers = request.GetHeaderMap(); foreach (string key in headers) { foreach (var value in headers.GetValues(key)) { response.AppendFormat("{0}: {1}\n", key, value); } } response.AppendLine(); response.AppendFormat("</pre>\n"); responseData = Encoding.UTF8.GetBytes(response.ToString()); callback.Continue(); return true; }
protected override void OnWebSocketRequest(CefServer server, int connectionId, string clientAddress, CefRequest request, CefCallback callback) { if (this.webCallbacks["onWebSocketRequest"] != null) { try { var _callback = this.webCallbacks["onWebSocketRequest"]; new Task(() => { _callback.Context.Enter(); var _request = new RequestHelper(server, request); this.webResponseCallbacks.Add(connectionId, _request); _callback.Runner.PostTask(new CallbackTask(_callback.Context, _callback.Callback, connectionId, clientAddress, _request.ToJson())); _callback.Context.Exit(); }).Start(); callback.Continue(); } catch (Exception ex) { Log.Trace(ex.Message, ex.StackTrace, true); } } if (onWebSocketRequest != null) { onWebSocketRequest(this, new OnWebSocketRequestEventArgs(server, connectionId, clientAddress, request, callback)); } }
protected override RequestHandlingFashion ProcessRequestAsync(CefRequest request, CefCallback callback) { Task.Run(async() => { try { var httpRequest = WebRequest.CreateHttp(request.Url); var headers = request.GetHeaderMap(); foreach (var key in request.GetHeaderMap().AllKeys) { httpRequest.Headers.Add(key, headers[key]); } var response = await httpRequest.GetResponseAsync(); Response = response.GetResponseStream(); Headers = response.Headers; // we have to smash any existing value here Headers.Remove(AccessControlAllowOriginHeaderKey); Headers.Add(AccessControlAllowOriginHeaderKey, "*"); } catch { // we should catch exceptions.. network errors cannot crash the app } finally { callback.Continue(); } }); return(RequestHandlingFashion.ContinueAsync); }
protected override bool ProcessRequest(CefRequest request, CefCallback callback) { try { string u = request.Url.Substring(17); int i = u.IndexOf('/'); string file = u.Substring(0, i) + ":" + u.Substring(i); file = HttpUtility.UrlDecode(file); stream = File.Open(file, FileMode.Open); callback.Continue(); return(true); } catch (Exception ex) { if (stream != null) { stream.Dispose(); } MessageBox.Show(ex.ToString()); return(false); } }
protected override bool ProcessRequest(CefRequest request, CefCallback callback) { try { Uri url = new Uri(request.Url); string resourceName = url.LocalPath.Substring(1).Replace('/', '.'); resourceName = HttpUtility.UrlDecode(resourceName); Assembly assm = Assembly.GetEntryAssembly(); stream = assm.GetManifestResourceStream(resourceName); if (stream == null) { throw new Exception("找不到 名为 \"" + resourceName + "\" 的资源 。"); } callback.Continue(); return(true); } catch (Exception ex) { if (stream != null) { stream.Dispose(); } MessageBox.Show(ex.ToString()); return(false); } }
/// <summary> /// Processes the request. /// </summary> /// <param name="request"></param> /// <param name="callback"></param> /// <returns></returns> protected override bool ProcessRequest(CefRequest request, CefCallback callback) { if (request == null) { throw new ArgumentNullException("request"); } Url = request.Url; var application = BaseMainApplication.Current; application.InvokeOnMainAsync(() => { try { var path = application.GetContentPath(request.Url); if (application.ContentProvider.ContentExists(path)) { Data = application.ContentProvider.GetContent(path); } } catch (Exception e) { Data = null; Exception = e; GeneralLog.Error("Content request exception.", e); } callback.Continue(); }); return(true); }
private bool ProcessLocalFile(string file, CefCallback callback) { // Check if file exists and not empty var fileInfo = new FileInfo(file); if ((fileInfo.Exists) && fileInfo.Length > 0) { Task.Run(() => { using (callback) { try { _fileBytes = File.ReadAllBytes(file); string extension = Path.GetExtension(file); _mime = MimeMapper.GetMimeType(extension); } catch (Exception exception) { Logger.Instance.Log.LogError(exception, exception.Message); } finally { callback.Continue(); } } }); return(true); } return(false); }
protected override bool ProcessRequest(CefRequest request, CefCallback callback) { var isCustomScheme = _config?.UrlSchemes?.IsUrlRegisteredCustomScheme(request.Url); if (isCustomScheme.HasValue && isCustomScheme.Value) { Task.Run(() => { using (callback) { try { var uri = new Uri(request.Url); var path = uri.LocalPath; var response = new ChromelyResponse(); if (string.IsNullOrEmpty(path)) { response.ReadyState = (int)ReadyState.ResponseIsReady; response.Status = (int)System.Net.HttpStatusCode.BadRequest; response.StatusText = "Bad Request"; _chromelyResponse = response; } else { var parameters = request.Url.GetParameters(); var postData = GetPostData(request); _chromelyResponse = _requestTaskRunner.Run(request.Method, path, parameters, postData); string jsonData = _chromelyResponse.Data.EnsureResponseDataIsJsonFormat(); _responseBytes = Encoding.UTF8.GetBytes(jsonData); } } catch (Exception exception) { Logger.Instance.Log.Error(exception); _chromelyResponse = new ChromelyResponse { Status = (int)HttpStatusCode.BadRequest, Data = "An error occured." }; } finally { callback.Continue(); } } }); return(true); } Logger.Instance.Log.Error($"Url {request.Url} is not of a registered custom scheme."); callback.Dispose(); return(false); }
/// <summary> /// The ProcessRequest. /// </summary> /// <param name="request">The request<see cref="CefRequest"/>.</param> /// <param name="callback">The callback<see cref="CefCallback"/>.</param> /// <returns>The <see cref="bool"/>.</returns> protected override bool ProcessRequest(CefRequest request, CefCallback callback) { var webRequest = CefGlue.Lib.Browser.WebRequest.Create(request); this.respData = this.ExecuteCore(webRequest); callback.Continue(); return(true); }
protected override bool ProcessRequest(CefRequest request, CefCallback callback) { if (callback != null) { callback.Continue(); } return(true); }
protected override bool Open(CefRequest request, out bool handleRequest, CefCallback callback) { //if(handleRequest) handleRequest = true; callback.Continue(); return(true); //throw new NotImplementedException(); }
public void Continue() { lock (SyncRoot) { if (responseCallback != null) { using (responseCallback) { responseCallback.Continue(); } } } }
protected override bool ProcessRequest(CefRequest request, CefCallback callback) { Task task = new Task(() => { Data = Encoding.UTF8.GetBytes(Parse(sql, connectionString, returnType, executionMode)); callback.Continue(); }); task.Start(); return(true); }
/// <summary> /// The on web socket request. /// </summary> /// <param name="server"> /// The server. /// </param> /// <param name="connectionId"> /// The connection id. /// </param> /// <param name="clientAddress"> /// The client address. /// </param> /// <param name="request"> /// The request. /// </param> /// <param name="callback"> /// The callback. /// </param> protected override void OnWebSocketRequest( CefServer server, int connectionId, string clientAddress, CefRequest request, CefCallback callback) { // Cache name and connection identifier. ConnectionNameMapper.Add(request.Url, connectionId); // Always accept WebSocket connections. callback.Continue(); }
protected override bool ProcessRequest(CefRequest request, CefCallback callback) { //Uri uri = new Uri(request.Url); //Debug.WriteLine("ProcessRequestAsync: " + request.Url); Task task = new Task(() => { Data = Encoding.UTF8.GetBytes(Parse(sql, connectionString, returnType, executionMode)); callback.Continue(); }); task.Start(); return(true); }
private bool ProcessAssmblyEmbeddedFile(string url, string file, string fileAbsolutePath, CefCallback callback) { var urlScheme = _config?.UrlSchemes?.GetScheme(url, UrlSchemeType.AssemblyResource); var option = urlScheme.AssemblyOptions; if (option == null || option.TargetAssembly == null) { return(false); } var manifestName = string.Join(".", option.DefaultNamespace, option.RootFolder, _regex.Replace(fileAbsolutePath, ".")).Replace("..", ".").Replace("..", "."); var stream = option.TargetAssembly.GetManifestResourceStream(manifestName); if (stream != null && stream.Length > 0) { Task.Run(() => { using (callback) { try { _fileBytes = new byte[stream.Length]; stream.Read(_fileBytes, 0, (int)stream.Length); stream.Flush(); stream.Dispose(); string extension = Path.GetExtension(file); _mime = MimeMapper.GetMimeType(extension); } catch (Exception exception) { Logger.Instance.Log.LogError(exception, exception.Message); } finally { callback.Continue(); } } }); return(true); } else { if (stream != null) { stream.Dispose(); } } return(false); }
protected override bool ProcessRequest(CefRequest request, CefCallback callback) { lock (SyncRoot) { if (Response == null && string.IsNullOrEmpty(RedirectUrl)) { responseCallback = callback; } else { callback.Continue(); } return(true); } }
protected override bool ReadResponse(Stream response, int bytesToRead, out int bytesRead, CefCallback callback) { bytesRead = 0; if (_resourceStream != null) { var buffer = new byte[bytesToRead]; bytesRead = _resourceStream.Read(buffer, 0, bytesToRead); if (bytesRead > 0) { response.Write(buffer, 0, bytesRead); } if (bytesRead == bytesToRead && callback != null) { callback.Continue(); } } return(bytesRead == bytesToRead); }
protected override bool ProcessRequest(CefRequest request, CefCallback callback) { var u = new Uri(request.Url); var file = u.Authority + u.AbsolutePath; _totalBytesRead = 0; _fileBytes = null; _completed = false; // Check if file exists and not empty var fileInfo = new FileInfo(file); if ((fileInfo.Exists) && fileInfo.Length > 0) { Task.Run(() => { using (callback) { try { _fileBytes = File.ReadAllBytes(file); string extension = Path.GetExtension(file); _mime = MimeMapper.GetMimeType(extension); } catch (Exception exception) { Logger.Instance.Log.Error(exception); } finally { callback.Continue(); } } }); return(true); } callback.Dispose(); return(false); }
protected override bool ProcessRequest(CefRequest request, CefCallback callback) { Task task = new Task(() => { try { //var serializer = new JavaScriptSerializer(); //serializer.MaxJsonLength = Int32.MaxValue; //serializer.RegisterConverters(new[] { new DynamicJsonConverter() }); var zip = new iZip(configuration.Application, Environment.CurrentDirectory, JsonMapper.ToObject <object>(zipString)); var zipBytes = Data = iZip.CreateZip(zip); var dir = Environment.CurrentDirectory + "\\Web\\" + configuration.Application + "\\reports"; if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } var dt = DateTime.Now.ToString("yyyyMMddHmmssfff"); var file = zip.Properties.Title.Replace(" ", "_") + "_" + dt + "_" + zip.Properties.Items + ".zip"; var path = dir + "\\" + file; File.WriteAllBytes(path, zipBytes); var echo = JsonMapper.ToJson(new FileHelper("OK", "reports/" + file, zip.Properties.Title, zip.Properties.Items)); Data = Encoding.UTF8.GetBytes(echo); } catch (Exception ex) { Log.Trace(ex.Message, ex.StackTrace); var echo = JsonMapper.ToJson(new ErrorHelper(ex.Message, ex.StackTrace)); Data = Encoding.UTF8.GetBytes(echo); } callback.Continue(); }); task.Start(); return(true); }
protected override bool ProcessRequest(CefRequest request, CefCallback callback) { if (!this.PrepareRequest(request)) { return(false); } _cancellationTokenSource = new CancellationTokenSource(); _dataStream = null; GetResource(); return(true); async void GetResource() { try { if (await LoadResourceData(_cancellationTokenSource.Token)) { _dataStream = await GetResourceDataStream(_cancellationTokenSource.Token); } } catch (TaskCanceledException) { Logger.Instance.Log.Info("The request was canceled."); } catch (Exception ex) when(ex.Message == "The request was aborted: The request was canceled.") { Logger.Instance.Log.Info("The request was canceled."); } catch (Exception ex) { Logger.Instance.Log.Error(ex, "Exception thrown while loading resource"); } finally { callback.Continue(); callback.Dispose(); } } }
/// <summary> /// The process request. /// </summary> /// <param name="request"> /// The request. /// </param> /// <param name="callback"> /// The callback. /// </param> /// <returns> /// The <see cref="bool"/>. /// </returns> protected override bool ProcessRequest(CefRequest request, CefCallback callback) { bool isCustomScheme = UrlSchemeProvider.IsUrlOfRegisteredCustomScheme(request.Url); if (isCustomScheme) { Task.Run(() => { using (callback) { try { mChromelyResponse = RequestTaskRunner.Run(request); string jsonData = mChromelyResponse.Data.EnsureResponseIsJsonFormat(); mResponseBytes = Encoding.UTF8.GetBytes(jsonData); } catch (Exception exception) { Log.Error(exception); mChromelyResponse = new ChromelyResponse { Status = (int)HttpStatusCode.BadRequest, Data = "An error occured." }; } finally { callback.Continue(); } } }); return(true); } Log.Error($"Url {request.Url} is not of a registered custom scheme."); callback.Dispose(); return(false); }