public ResourceResponse OnRequest(ResourceRequest request)
        {
            if(UserAgent != null)
                request.AppendExtraHeader("User-Agent", UserAgent);

            return null;
        }
        public ResourceResponse OnRequest(ResourceRequest request)
        {
            var webRequest = HttpWebRequest.CreateHttp(request.Url);
            webRequest = request.ToWebRequest(webRequest);
            Stream stream = null;
            var startTime = DateTime.Now;
            try
            {
                var response = webRequest.GetResponse();
                stream = response.GetResponseStream();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            var streamData = stream.ReadFully();
            var endTime = DateTime.Now;

            var timeTaken = (endTime - startTime).TotalMilliseconds;
            var filename = Guid.NewGuid().ToString();
            File.WriteAllBytes(filename, streamData);

            RecordTimeOfResourceOccured.Invoke(new ResourceTimingResult
            {
                ResourceUrl = request.Url.ToString(),
                TimeTaken = timeTaken,
                Size = streamData.Length,
            });
            return ResourceResponse.Create(filename);
        }
 protected override ResourceResponse OnRequest(ResourceRequest request)
 {
     // try to recover login data
     if (request.Count>0 && request.Method == "POST" && request.Url.AbsoluteUri.ToLower().EndsWith(LoginUrl))
     {
         _lastLoginData = ParseData(Uri.UnescapeDataString(request[0].Bytes));
     }
     return base.OnRequest(request);
 }
        public ResourceResponse OnRequest(ResourceRequest request)
        {
            /*Console.WriteLine("OnRequest:\t" + request.Url);
            if (request.Url.Host == "home")
            {

                return ResourceResponse.Create("/Core/home.html");
            }*/
            return null;
        }
 public ResourceResponse OnRequest(ResourceRequest request)
 {
     string login = "******";
       string password = "******";
       string data = @"_filter%5Btitle%5D=&_filter%5Bcount_min%5D=&_filter%5Bcount_max%5D=&_filter%5Blevel_min%5D=&_filter%5Blevel_max%5D=&_filter%5Bkind%5D=g1_12&_filter%5Bquality%5D=-1&_filterapply=%D0%9E%D0%BA";
       request.Method = @"POST";
       request.AppendUploadBytes(data, (uint)data.Length);
       request.AppendExtraHeader("Content-Type", "application/x-www-form-urlencoded");
       return null;
 }
        public override Task ProcessAsync(ResourceRequest request)
        {
            if (Engine != null && IsDifferentToCurrentDownloadUrl(request.Target))
            {
                CancelDownload();
                Download = DownloadWithCors(request);
                return FinishDownloadAsync();
            }

            return null;
        }
        public virtual Task ProcessAsync(ResourceRequest request)
        {
            if (IsDifferentToCurrentDownloadUrl(request.Target))
            {
                CancelDownload();
                Download = _loader.DownloadAsync(request);
                return FinishDownloadAsync();
            }

            return null;
        }
        /// <summary>
        /// Loads the data for the request asynchronously.
        /// </summary>
        /// <param name="request">The issued request.</param>
        /// <returns>The active download.</returns>
        public virtual IDownload DownloadAsync(ResourceRequest request)
        {
            var data = new Request
            {
                Address = request.Target,
                Method = HttpMethod.Get
            };

            data.Headers[HeaderNames.Referer] = request.Source.Owner.DocumentUri;
            return DownloadAsync(data, request.Source);
        }
        public override Task ProcessAsync(ResourceRequest request)
        {
            var contentHtml = _element.GetContentHtml();

            if (contentHtml != null)
            {
                var referer = _element.Owner.DocumentUri;
                return ProcessResponse(contentHtml, referer);
            }

            return base.ProcessAsync(request);
        }
 /// <summary>
 /// Befores the handling request.
 /// </summary>
 /// <param name="context">The context.</param>
 public void BeforeHandlingRequest(RequestProcessingContext context)
 {
     if (context != null && context.Request != null)
     {
         var request = context.Request;
         var resource = new ResourceRequest { request.GetType ().FullName };
         if ( !_accessControlManager.CanAccess ( resource ) )
         {
             throw new InvalidOperationException ( "You do not have permission to access: " + resource );
         }
     }
 }
Exemple #11
0
        /// <summary>
        /// Loads the data for the request asynchronously.
        /// </summary>
        /// <param name="request">The issued request.</param>
        /// <param name="cancel">The cancellation token.</param>
        /// <returns>The task creating the response.</returns>
        public virtual Task<IResponse> LoadAsync(ResourceRequest request, CancellationToken cancel)
        {
            var events = _document.Context.Configuration.Events;
            var data = new Request
            {
                Address = request.Target,
                Method = HttpMethod.Get
            };

            data.Headers[HeaderNames.Referer] = request.Source.Owner.DocumentUri;
            return _filter(data) ? _requesters.LoadAsync(data, events, cancel) : TaskEx.FromResult(default(IResponse));
        }
        /// <summary>
        /// Determines whether access to the specified resource request should be granted.
        /// </summary>
        /// <param name="resourceRequest">The resource request.</param>
        /// <returns>
        ///   <c>true</c> if this instance can access the specified resource request; otherwise, <c>false</c>.
        /// </returns>
        public bool CanAccess( ResourceRequest resourceRequest )
        {
            if ( resourceRequest == null )
            {
                throw new ArgumentException ( "resource request is required." );
            }

            if ( resourceRequest.ResourceHierarchy.Count == 0 )
            {
                throw new ArgumentException ( "Invalid resource request." );
            }

            Permission requiredPermission = null;
            var canAccess = false;
            var resourceList = _resourceList;
            foreach ( var resourceName in resourceRequest.ResourceHierarchy )
            {
                if ( resourceList == null )
                {
                    break;
                }

                var name = resourceName;
                var resource = resourceList.FirstOrDefault ( r => r.Name == name );
                if ( resource == null )
                {
                    break;
                }

                requiredPermission = resource.Permission;
                resourceList = resource.Resources;
            }

            if ( requiredPermission != null )
            {
                canAccess = _currentUserPermissionService.DoesUserHavePermission ( requiredPermission );
                Logger.Debug (
                    "Permission ({0}) {1} for resource request ({2}).",
                    requiredPermission,
                    canAccess ? "granted" : "denied",
                    resourceRequest );
            }
            else
            {
                Logger.Debug ( "No permission defined for resource request ({0}).", resourceRequest );
            }

            return canAccess;
        }
      public void prova()
      {
         //persona = myres.Get<Person>(new {userId=10}, succ, err);
         
         //persona = myres.Action<Person>("fetch", new {userId=10}, succ, err);

         //persona.Action("fetch");
        
         ResourceRequest<Person> r = new ResourceRequest<Person>(myres);         
         r.Action = "fetch";
         r.Parameters["userId"] = 10;
         r.PostData = null;
         r.Success = succ;
         r.Error = err;
         persona = r.ExecuteRequest();

         persona.Action("save");
      }
        public ResourceResponse OnRequest(ResourceRequest request)
        {
            var path = request.Url.ToString().ToLower();

            try {
                path = path.IndexOf("?", StringComparison.InvariantCultureIgnoreCase) >= 0 ? path.Substring(0, path.IndexOf("?", StringComparison.InvariantCultureIgnoreCase)) : path;
                var fileName = path.Substring(path.LastIndexOf("/", StringComparison.InvariantCultureIgnoreCase) + 1);
                var ext = Path.GetExtension(fileName);
                var badFileName = !string.IsNullOrEmpty(ext) && !_enabledExtensions.Contains(ext.ToLower());
                if (badFileName) {
                    request.Cancel();
                    return null;
                }
            } catch (Exception e) {
                request.Cancel();
                return null;
            }

            return null;
        }
Exemple #15
0
        /// <summary>
        /// Loads the data for the request asynchronously.
        /// </summary>
        /// <param name="request">The issued request.</param>
        /// <returns>The active download.</returns>
        public virtual IDownload DownloadAsync(ResourceRequest request)
        {
            var data = new Request
            {
                Address = request.Target,
                Method = HttpMethod.Get,
                Headers = new Dictionary<String, String>
                {
                    { HeaderNames.Referer, request.Source.Owner.DocumentUri }
                }
            };

            var cookie = GetCookie(request.Target);

            if (cookie != null)
            {
                data.Headers[HeaderNames.Cookie] = cookie;
            }

            return DownloadAsync(data, request.Source);
        }
        public ResourceResponse OnRequest(ResourceRequest request)
        {
            // This tries to get a local resource. If there is no local resource null is returned by GetLocalResource, which
            // triggers the default handler, which should respect the "target='_blank'" attribute added
            // in ParsedDocument.ToHtml(), thus avoiding a bug in Awesomium where trying to navigate to a
            // local resource fails when showing an in-memory file (https://github.com/Code52/DownmarkerWPF/pull/208)

            // What works:
            //	- resource requests for remote resources (like <link href="http://somecdn.../jquery.js"/>)
            //	- resource requests for local resources that exist relative to filename of the file (like <img src="images/logo.png"/>)
            //	- clicking links for remote resources (like [Google](http://www.google.com))
            //	- clicking links for local resources which don't exist (eg [test](test)) does nothing (WebControl_LinkClicked checks for existence)
            // What fails:
            //	- clicking links for local resources where the resource exists (like [test](images/logo.png))
            //		- This _sometimes_ opens the resource in the preview pane, and sometimes opens the resource 
            //		using Process.Start (WebControl_LinkClicked gets triggered). The behaviour seems stochastic.
            //	- alt text for images where the image resource is not found
            if (request.Url.ToString().StartsWith(LocalRequestUrlBase))
                return GetLocalResource(request.Url.ToString().Replace(LocalRequestUrlBase, ""));

            // If the request wasn't local, return null to let the usual handler load the url from the network			

            return null;
        }
Exemple #17
0
        private IntPtr internalResourceRequestCallback( IntPtr caller, IntPtr request )
        {
            ResourceRequest requestWrap = new ResourceRequest( request );
            ResourceRequestEventArgs e = new ResourceRequestEventArgs( requestWrap );

            if ( ResourceRequest != null )
            {
                ResourceResponse response = this.OnResourceRequest( this, e );
                CommandManager.InvalidateRequerySuggested();

                if ( response != null )
                    return response.getInstance();
            }

            return IntPtr.Zero;
        }
 private IDownload DownloadWithCors(ResourceRequest request)
 {
     return _loader.FetchWithCors(new CorsRequest(request)
     {
         Setting = _link.CrossOrigin.ToEnum(CorsSetting.None),
         Behavior = OriginBehavior.Taint,
         Integrity = _document.Options.GetProvider<IIntegrityProvider>()
     });
 }
Exemple #19
0
        /// <summary>
        /// When overridden in a derived class, is invoked whenever application code or internal processes (such as a rebuilding layout pass) call <see cref="M:System.Windows.Controls.Control.ApplyTemplate"/>. In simplest terms, this means the method is called just before a UI element displays in an application. For more information, see Remarks.
        /// </summary>
        public override void OnApplyTemplate ()
        {
            base.OnApplyTemplate ();
            if ( string.IsNullOrEmpty ( Name ) )
            {
                throw new InvalidOperationException ( "A secure control requires the Name property to be set." );
            }

            //TODO: adding RadTileViewItem here but should be some cleaner way of adding more parent realm types
            var parentRealm = this.FindAncestor<UserControl> () ?? ( FrameworkElement )this.FindAncestor<RadTileViewItem> ();
            if ( parentRealm == null )
            {
                parentRealm = this.FindAncestor<ChildWindow> ();
            }

            //TODO: revisit this to possibly not require secure control to be in a user control
            if ( parentRealm == null && HtmlPage.IsEnabled )
            {
                throw new InvalidOperationException ( "A secure control must be a child of a user control or Child Window." );
            }
            _resourceRequest = new ResourceRequest { parentRealm.GetType ().FullName, ( string.IsNullOrEmpty ( Name ) ? string.Empty : Name ) };
            CheckRemAccess ();
        }
Exemple #20
0
		/// <summary>
		///   Informs the station a container is available.
		/// </summary>
		/// <param name="source">The station currently holding the container.</param>
		/// <param name="condition">The container's current condition.</param>
		public void ResourceReady(Station source, Condition condition)
		{
			var request = new ResourceRequest(source, condition);
			if (!_resourceRequests.Contains(request))
				_resourceRequests.Add(request);
		}
        private IntPtr internalResourceRequestCallback(IntPtr caller, IntPtr request)
        {
            ResourceRequest requestWrap = new ResourceRequest(request);

            ResourceRequestEventArgs e = new ResourceRequestEventArgs(this, requestWrap);

            if (OnResourceRequest != null)
            {
                ResourceResponse response = OnResourceRequest(this, e);

                if (response != null)
                    return response.getInstance();
            }

            return IntPtr.Zero;
        }
 public ResourceRequestEventArgs(WebView webView, ResourceRequest request)
 {
     this.webView = webView;
     this.request = request;
 }
 public Task<Resource> GetTrashInfoAsync(ResourceRequest request, CancellationToken cancellationToken)
 {
     return GetAsync<ResourceRequest, Resource>("trash/resources", request, cancellationToken);
 }
 public ResourceRequestEventArgs( ResourceRequest request )
 {
     this.request = request;
 }
        public Task ProcessAsync(ResourceRequest request)
        {
            if (_loader != null && Engine != null)
            {
                Download = _loader.FetchWithCors(new CorsRequest(request)
                {
                    Behavior = OriginBehavior.Taint,
                    Setting = _script.CrossOrigin.ToEnum(CorsSetting.None),
                    Integrity = _document.Options.GetProvider<IIntegrityProvider>()
                });
                return Download.Task;
            }

            return null;
        }
        /// <summary>
        ///     Creates a response using the contents of an embedded assembly resource.
        /// </summary>
        private ResourceResponse CreateResponseFromResource(ResourceRequest request)
        {
            string resourceName;
            string filePath;

            // this project embeds static HTML/JS/CSS/PNG files as resources
            // by translating the resource's relative file path like Resources\foo/bar.html
            // to a logical name like /www/foo/bar.html
            resourceName = String.Concat("www", request.Url.AbsolutePath);
            filePath = Path.GetFullPath(Path.Combine(TempFolder, resourceName.Replace('/', Path.DirectorySeparatorChar)));

            // cache the resource to a temp file if
            if (!File.Exists(filePath))
            {
                ExtractResourceToFile(resourceName, filePath);
            }

            return ResourceResponse.Create(filePath);
        }
 public Task<Resource> GetInfoAsync(ResourceRequest request, CancellationToken cancellationToken = default(CancellationToken))
 {
     return GetAsync<ResourceRequest, Resource>("resources", request, cancellationToken);
 }
 /// <summary>
 ///     Determines if the request is for an embedded resource
 /// </summary>
 private bool IsEmbeddedResource(ResourceRequest request)
 {
     return EmbeddedResourceDomain.IsBaseOf(request.Url);
 }
Exemple #29
0
 public ResourceResponse OnRequest(ResourceRequest request)
 {
     var req = request;
     return null;
 }
        /// <summary>
        ///     Intercepts any requests for the EmbeddedResourceDomain base Uri,
        ///     and returns a response using the embedded resource in this app's assembly/DLL file
        /// </summary>
        public virtual ResourceResponse OnRequest(ResourceRequest request)
        {
            ResourceResponse response = null;

            // log the request to the debugger output
            System.Diagnostics.Debug.Print(String.Concat(request.Method, ' ', request.Url.ToString()));

            if (IsEmbeddedResource(request))
            {
                response = CreateResponseFromResource(request);
            }

            return response;
        }