WebResource 404 Hell - can't get JavaScript included in Web Part - javascript

I've tried really hard to include a JavaScript file with my WebPart as a resource. The web part class and the flexidgrid.js file are both in the root level of the project. The Web Part is created in DisplaySearchResults.js:
namespace DisplaySearchResults
{
public class DisplaySearchResults : WebPart
{
### Hidden Irrelevant Stuff Here ###
protected override void CreateChildControls()
{
### Hidden Irrelevant Stuff Here ###
### Load JavaScript Code Here ###
string scriptURL = Page.ClientScript.GetWebResourceUrl(typeof(DisplaySearchResults), "DisplaySearchResults.flexigrid.js");
ClientScriptManager cs = Page.ClientScript;
if (!cs.IsClientScriptBlockRegistered(ByeByeIncludeScriptKey))
cs.RegisterClientScriptInclude(this.GetType(), ByeByeIncludeScriptKey, scriptURL);
}
### Hidden Irrelevant Stuff Here ###
}
}
The AssemblyInfo.cs for DisplaySearchResults looks like this:
[assembly: WebResource("DisplaySearchResults.flexigrid.js", "text/javascript")]
But for some reason the WebResource.axd file still comes up as 404.

Make sure that file's Build Action is set to "Embedded Resource" in the properties for that file.

I had already set the Embedded Resource - it turned out I needed the fully qualified Assembly name - Company.UI.Web.DisplaySearchResults - which I got from right clicking on the properties menu of the project. On the application tab, there is the proper Assembly name.
So, instead of:
[assembly: WebResource("DisplaySearchResults.flexigrid.js", "text/javascript")]
I should have put:
[assembly: WebResource("Company.UI.Web.DisplaySearchResults.flexigrid.js", "text/javascript")]

Related

How to access elements under `shadow-root` at 'chrome://downloads' using jquery and selenium?

I am trying to get the name of the last downloaded file in my selenium javascript application.
I have my selenium driver navigating to the chrome downloads page using: driver.get('chrome://downloads'); , but when I get there, selenium is not able to find ANY elements on the download page.
The chrome downloads page 'chrome://downloads' has a bunch of shadow-root elements that I don't know how to get underneath in order to access the id's that I want. How do I access identifiers beneath shadow-root items?
I want to get $("#file-link") as shown here:
But when I use jquery to find it, everything returns null (probably because it's behind shadow-root)
Here's a big picture of all the information I have including showing that "#file-link" totally exists:
The code I am using to wait for the element to exist is the same that I use for all elements in my application, so I think this is already working:
driver.wait(until.elementLocated(By.id('downloads-manager')), 120000).then(function(){
console.log("#downloads-manager shows");
driver.findElement(By.id('downloads-manager')).then(function(dwMan){
//How do I "open" #shadow-root now? :(
});
});
Here is my version information:
Chromium v54.0.2840.71
Node v6.5.0
ChromeDriver v2.27.440175
selenium-webdriver v3.4.0
Similar Question
Selenium webdriver can't find elements at chrome://downloads (This is the same problem I am having but in python)
Links
Selenium Javascript API: https://seleniumhq.github.io/selenium/docs/api/javascript/
The $ from your example is not a shorthand for JQuery.
It's function overridden by the page to locate an element by id only:
function $(id){var el=document.getElementById(id);return el?assertInstanceof(el,HTMLElement):null}
To select through the shadow DOM, you need to use the '/deep/' combinator.
So to get all the links in the download page:
document.querySelectorAll("downloads-manager /deep/ downloads-item /deep/ [id=file-link]")
And with Selenium:
By.css("downloads-manager /deep/ downloads-item /deep/ [id=file-link]")
Why not check the downloads folder directly? I do this for downloading Excel files. I first clear the downloads folder, click the button to download the file, wait ~5 sec (varies by file size, internet speed, etc.), and then looking in the folder for a "*.xlsx" file. This also has the benefit of working with any browser.
C# Examples:
/// <summary>
/// Deletes the contents of the current user's "Downloads" folder
/// </summary>
public static void DeleteDownloads()
{
// Get the default downloads folder for the current user
string downloadFolderPath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + "\\Downloads";
// Delete all existing files
DirectoryInfo di = new DirectoryInfo(directoryPath);
foreach (FileInfo file in di.GetFiles())
{
file.Delete();
}
foreach (DirectoryInfo dir in di.GetDirectories())
{
dir.Delete(true);
}
}
/// <summary>
/// Looks for a file with the given extension (Example: "*.xlsx") in the current user's "Download" folder.
/// </summary>
/// <returns>Empty string if files are found</returns>
public static string LocateDownloadedFile(string fileExtension)
{
// Get the default downloads folder for the current user
string downloadFolderPath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + "\\Downloads";
DirectoryInfo di = new DirectoryInfo(downloadFolderPath);
FileInfo[] filesFound = di.GetFiles(fileExtension);
if (filesFound.Length == 0)
{
return "No files present";
}
else
{
return "";
}
}
And then in my Test I can Assert.IsEmpty(LocateDownloadedFile); This way if the assert fails, the error message if printed.
Expected: String.Empty.
Actual: No files present.

Convert dynamic html to pdf with HiQPdf

I've been trying to get my HTML to accurately translate into a PDF for some time now but I can't see what I'm doing wrong.
Here's my code for the page:
Imports HiQPdf
Imports System.Text
Imports System.IO
Imports System.Web.UI
Partial Class MODULES_CostCalculator_CostCalculator
Inherits System.Web.UI.Page
Dim convertToPdf As Boolean = False
Protected Sub printClick()
convertToPdf = True
End Sub
Protected Overrides Sub Render(writer As System.Web.UI.HtmlTextWriter)
If (convertToPdf) Then
System.Diagnostics.Debug.Write("overriding render")
Dim tw As TextWriter = New StringWriter()
Dim htw As HtmlTextWriter = New HtmlTextWriter(tw)
'render the html markup into the TextWriter
MyBase.Render(htw)
'get the current page html code
Dim htmlCode As String = tw.ToString()
System.Diagnostics.Debug.Write(htmlCode)
'convert the html to PDF
'create html to pdf converter
Dim htmlToPdfConv As HtmlToPdf = New HtmlToPdf()
'htmlToPdfConv.MediaType = "print"
'base url used to resolve images, css and script files
Dim currentPageUrl As String = HttpContext.Current.Request.Url.AbsoluteUri
'convert html to a pdf memory buffer
Dim pdfBuffer As Byte() = htmlToPdfConv.ConvertHtmlToMemory(htmlCode, currentPageUrl)
'inform the browser about the binary data format
HttpContext.Current.Response.AddHeader("Content-Type", "application/pdf")
'let the browser know how to open the pdf doc
HttpContext.Current.Response.AddHeader("Content-Disposition",
String.Format("attachment; filename=ConvertThisHtmlWithState.pdf; size={0}",
pdfBuffer.Length.ToString()))
'write the pdf buffer to http response
HttpContext.Current.Response.BinaryWrite(pdfBuffer)
'call End() method of http response to stop ASP.NET page processing
HttpContext.Current.Response.End()
Else
MyBase.Render(writer)
End If
End Sub
Does anyone see what I might be doing wrong? A lot of the HTML is linked to a Knockout ViewModel, so I'm not sure if that would be causing an issue.
To be clear, I can create PDF's of the page, but only with the HTML in the state it was when the page first loaded. If I change any of the data-bound HTML, it doesn't reflect when I try to make another PDF.
Priorplease try:
Adding clear:
Response.Clear()
Response.ClearHeaders()
After MyBase.Reder method
htw.Flush()
At the before Response.End
Response.Flush()
If nothing above works:
Call support :)
I think the problem is that you're changing the state of the page after it has rendered (using JavaScript), and you're expecting this: -
MyBase.Render(htw)
'get the current page html code
to give you the current state of the page. It won't - it will give you the state of the page as it was rendered. If you're using Knockout or anything other scripting to manipulate the DOM after the page has loaded, the server-side model of the page knows nothing of these changes.

CakePHP controller function with parameters doesn't show javascript

When I'm using controller function with parameters the rendered view just seems to forget every included .js files.
public function view($id = null) {
if(!$id) {
throw new NotFoundException(__('Invalid post'));
}
$post = $this->Post->findById($id);
if(!$post) {
throw new NotFoundException(__('Invalid post'));
}
$this->set('post', $post);
}
If I take parameters away and put variable '$id = 1' on function the view with postID 1 renders okay in 'posts/view'.
I included javascript files to default.ctp in traditional way:
echo "script type='text/javascript' SRC='../js/jquery-1.9.1.min.js'></script>";);
(it includes '<' but this text editor won't me type it for safety reasons I guess)
I don't have knowledge about 'js helpers' of cakePHP. Can't I use javascript in traditional way?
Site renders okay in every other view (e.g. posts/add) and .js files are included in source code of 'posts/view/1'
The problem
You're using relative paths to the javascript;
<script src='../js/jquery-1.9.1.min.js'></script>
In this url, ../ means '1 directory up from the current location`, so when you're currently visiting this URL;
http://mysite.com/home/
Then your browser will correctly try to load the script from;
http://mysite.com/js/jquery-1.9.1.min.js
However, if you're visiting this url;
http://mysite.com/home/and/some/more/
Then the browser will look for the JavaScript here:
http://mysite.com/home/and/some/js/jquery-1.9.1.min.js
How to fix the problem
Use absolute paths for all 'assets' (CSS, JavaScript, Images);
src='/js/jquery-1.9.1.min.js'
Output the script-tags using CakePHP Helpers (after all, that's what they are meant for: to simplify your work :), e.g. echo $this->Html->script('jquery-1.9.1.min');

Using javascript in ASP.NET Composite control

I have a custom asp.net server control to display images.What I need now is to draw a rectangle on the center of image and the rectangle should be re sizable by dragging on its edges.Is it possible to accomplish this using JavaScript ?. I need to embed that script in that control. Is it possible ?
You can include a javascript file in a server control.
Add a reference to the assemblyinfo.cs
[assembly: WebResource("Custom.js", "text/javascript")]
Then a reference on the PreRender:
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
string resourceName = "Custom.js";
ClientScriptManager cs = this.Page.ClientScript;
cs.RegisterClientScriptResource(typeof(CustomControls.Custom), resourceName);
}
Here is a nice article on the subject

How to add different Javascript in development and production wicket

I have a wicket application in which I have added the javascript files within the markup html:
<script src="script/jquery.min.js" type="text/javascript"></script>
My javascript files are not placed beside my .java or .html files, they are in different location in the server as can be seen on previous script declaration.
My question is: Is it possible to add these javascript files depending on the application mode? I.E. if the application is in development mode, load one javascript file, if it is in production load this other one.
Thanks!
PS: the idea is to load "min" version on production but the extended files on development so debugging becomes posible
NOTE: Watching different answers here I re-state: the problem is not finding when the wicket app is in development or deployment mode, I know that, but is about how to change html markup or adding different JavaScript resources
extendig the answer of #rotsch you can do it in wicket 1.5 with :
#Override
public void renderHead(IHeaderResponse response) {
if(DEVELOPMENT)
response.renderString("<script type=\"text/javascript\" src=\"url1\"></script>");
else
response.renderString("<script type=\"text/javascript\" src=\"url2\"></script>");
}
https://cwiki.apache.org/WICKET/migration-to-wicket-15.html#MigrationtoWicket1.5-RemovedHeaderContributorandfriends.
You can find out in which mode you are with the following code:
RuntimeConfigurationType.DEPLOYMENT.equals(getApplication().getConfigurationType())
or
RuntimeConfigurationType.DEVELOPMENT.equals(getApplication().getConfigurationType())
I use this directory layout:
resources
|---JQueryResource.java
|---jquery-1.6.4.js
|---jquery-1.6.4.min.js
With this class:
public class JQueryResource {
/**
* Must be called in a RequestCycle.
*
* #return Url for the jQuery library.
*/
public static String getURL() {
if (Application.get().usesDevelopmentConfig()) {
Url url =
RequestCycle.get().mapUrlFor(
new PackageResourceReference(JQueryResource.class, "jquery-1.6.4.js"),
null);
return url.toString();
} else {
Url url =
RequestCycle.get().mapUrlFor(
new PackageResourceReference(JQueryResource.class,
"jquery-1.6.4.min.js"), null);
return url.toString();
}
}
}
This is how I add the resource to my page.
#Override
public void renderHead(IHeaderResponse a_response) {
a_response.renderJavaScriptReference(JQueryResource.getURL());
}
You could use pack:tag to compress all your resources: http://sourceforge.net/projects/packtag/
In your web.xml/.properties file you can specify whether to pack it or not depending on your production mode.
I set a property in a properties file with I add to the path when starting the VM.
Then I do a if else similar to the PHP answer.

Categories

Resources