How To Generate A Javascript File From The Server - c#

I'm using BlogEngine.NET (a fine, fine tool) and I was playing with the TinyMCE editor and noticed that there's a place for me to create a list of external links, but it has to be a javascript file:
external_link_list_url : "example_link_list.js"
this is great, of course, but the list of links I want to use needs to be generated dynamically from the database. This means that I need to create this JS file from the server on page load. Does anyone know of a way to do this? Ideally, I'd like to just overwrite this file each time the editor is accessed.
Thanks!

I would create an HTTPHandler that responds with the desired data read from the db. Just associate the HTTPHandler with the particular filename 'example_link_list.js' in your web-config. Make sure you set
context.Response.ContentType = "text/javascript";
then just context.Response.Write(); your list of external links

if your 3rd party code doesn't require that the javascript file has the .js extension, then you can create your HTTPHandler and map it to either .axd or .ashx extension in web.config only - no need to change IIS settings as these extensions are automatically configured by IIS to be handled by asp.net.
<system.web>
<httpHandlers>
<add verb="*" path="example_link_list.axd" type= "MyProject.MyTinyMCE, MyAssembly" />
</httpHandlers>
</system.web>
This instructs IIS to pass all requests for 'example_link_list.axd' (via POST and GET) to the ProcessRequest method of MyProject.MyTinyMCE class in MyAssembly assembly (the name of your .dll)
You could alternatively use Visual Studio's 'Generic Handler' template instead - this will create an .ashx file and code-behind class for you. No need to edit web.config either.
using an HTTPHandler is preferrable to using an .aspx page as .aspx requests have a lot more overheads associated (all of the page events etc.)

If you can't change the file extension (and just return plain text, the caller shouldn't care about the file extension, js is plain text) then you can set up a handler on IIS (assuming it's IIS) to handle javascript files.
See this link - http://msdn.microsoft.com/en-us/library/bb515343.aspx - for how to setup IIS 6 within windows to handle any file extension. Then setup a HttpHandler to receive requests for .js (Just google httphandler and see any number of good tutorials like this one: http://www.devx.com/dotnet/Article/6962/0/page/3 )

Just point it at an aspx file and have that file spit out whatever javascript you need. I did this recently with TinyMCE in PHP and it worked like a charm.
external_link_list_url : "example_link_list.aspx"
In your aspx file:
<%# Page Language="C#" AutoEventWireup="false" CodeFile="Default.aspx.cs" Inherits="Default" %>
in your code-behind (C#):
using System;
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Write("var tinyMCELinkList = new Array(");
// put all of your links here in the right format..
Response.Write(string.Format("['{0}', '{1}']", "name", "url"));
Response.Write(");");
}
}

Related

SharePoint 2010 Allow Code Blocks for a specific page

I am trying to use C# code in an aspx page within SharePoint 2010. I keep getting the "Code blocks are not allowed" error.
My aspx page located at (server)/SitePages/ajax.aspx: (edited in SharePoint Designer 2010 if it matters)
<%# Page Language="C#" %>
<script runat="server">
Response.Write("Hello world");
</script>
I added the following to web.config at C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\CONFIG
<PageParserPath VirtualPath="/SitePages/ajax.aspx" CompilationMode="Always" AllowServerSideScript="true" />
Here is the same line that I added to web.config, shown in context:
<SharePoint>
<SafeMode
MaxControls = "200"
CallStack = "false"
DirectFileDependencies ="10"
TotalFileDependencies = "50"
AllowPageLevelTrace = "false"
>
<PageParserPaths>
<PageParserPath VirtualPath="/SitePages/ajax.aspx" CompilationMode="Always" AllowServerSideScript="true" />
</PageParserPaths>
Why do I still get the "Code blocks" error? Is there another security switch somewhere?
(I know custom web parts are the preferred solution, but I don't think that will suffice here because the return value should be json - this is a page to hit via ajax to get data.)
I suppose, you have to define PageParserPath element in an Web application web.config that is located C:\inetpub\wwwroot\wss\VirtualDirectories[application folder]\web.config.
When you upload an aspx page to a document library (which is what you're doing when you use SharePoint Designer) that aspx page can't have inline code blocks and it can't have a code behind. This is primarily a security mechanism. It prevents any old user from uploading an aspx page with malicious content that will then be executed with full privileges on your server, and also serving content to (potentially) any user.
For an aspx page to execute code it needs to be compiled into a WSP and deployed to the GAC on the server. When you do that you can either use inline code blocks or, better yet, have an aspx page with a code behind. To publish that page to the site you would need to compile the project in visual studio into a WSP, deploy that to the server by logging into the machine with sufficient privileges, and then add and deploy the code. This ensures that non-developers can't upload executable code to your site.
Finally, on a more unrelated note, since you don't actually want to display a page, but just JSON content, you probably shouldn't use an aspx page at all (although you can). You should probably just create an HTTP handler or a web service that writes the appropriate content out.

C# variable in .js file from embeded resource in server control ASP.NET

I am building my ASP server control which has some resources. One of them is .js file where i must pass a variable from my ServerControl.cs file.
I know how to for example get resource images in my resource style files and javascript files like this:
var resourceOpen = "<%=WebResource("PatientList.Images.DirOpen.png")%>" ;
var resourceClose = "<%=WebResource("PatientList.Images.DirClose.png")%>";
background: url('<%=WebResource("PatientList.Images.letter-bg.png")%>');
I want to do the same with my public variables in my server control .cs file
Let's say i've got
public string TestVariable = "It works"
How to pass it to javascript file in my resources?
var jsvariable = "<%=TestVariable%>"
Doesn't work. It seems that only WebResource(...) works. When i try to use variables, when I make something like this:
alert("<%=TestVariable%>");
The window with string "<%=TestVariable%>" will appear instead of "It works"
Maybe I'm not understanding your question correctly, but you have a server control that references an external JavaScript file, but in the external file you want to use a property on the control.
If that is what you are asking, then I'm afraid that it's not possible without writing custom handlers or something of the sort. You see, the external JavaScript file is requested by the client seperately from your control execution. At the time the JavaScript file is served by the server, the control has long been destroyed.
Here's what happens:
A request comes to your server for the page
The page loads and creates your usercontrol and a LINK to an external javascript file
The client gets the result from the server
The client sees a link to the external javascript file and requests it from the server
The request for the javascript file comes in on the server
The server gives the client the javascript file
As you can see, there are two requests coming in (step 1 and step 5). In the second request, the one for the javascript file, you no longer have the control with the property available (which was in step 1).
The only way I can think of to get this done is to do something with a custom handler to provide the javascript. This way you can pass any variables as querystring values and have the custom handler insert them into your java script.
I hope this answers your question.

Disable Caching For A Single JS File Using Web.config

I currently cache everything possible on my site (images, JS, CSS). There is only one JS file that I need to be loaded fresh every single time. How do I omit just one file from caching, using web.config, whilst leaving everything else cached?
Note that I tried another link here, and it didn't seem to stop the caching of my file:
How do I disable caching of an individual file in IIS 7 using weserver config settings
How about:
<configuration>
<location path="path/to/the/file.js">
<system.webServer>
<staticContent>
<clientCache cacheControlMode="DisableCache" />
</staticContent>
</system.webServer>
</location>
</configuration>
(Note that the path is relative to the web.config file)
I don't think you can do it using web.config, but you could add a unique querystring parameter to the javascript url in order for it to be loaded every time:
If you are using ASP.NET
<script src="mycode.js?<%=System.Guid.NewGuid.ToString()%>"></script>
Set the path for it not as a static URL but get an ASPX page to serve the script. Inside your ASPX page just send back the text:
byte[] javascriptTextBuffer = GetMyJavascript();
Response.ContentType = "text/javascript";
Response.Write(javascriptTextBuffer);
Inside the page turn off caching.
Having said that, it seems to me that you are doing something wrong that have to load the JavaScript file everytime. Make scripts static but use parameters to drive versatility.

Getting text after URL in asp.net / URL Rewriting (sort of!)

My app is a very simple "one page" type app-
It has Default.aspx
I'm basically trying to get, for example:
www.myappurl.com/this is my text
I want to get hold of "this is my text" from the above example.
This will be displayed on the page (for now)
I didn't really want to have to use any complext url rewriting things for this...
(My hosting provider uses IIS6)
I tried using a 404 handler, but this is a bit long winded, and i'm using shared hosting, that can't set the "execute url" on custom 404 pages.
Any other ideas?
You can add a mapping for all requests with the * extension to the ASP.NET isapi dll (GET/POST) verbs. You will need to uncheck the "verify file is on disk" checkbox when mapping the extension in IIS. (In IIS7 integrated mode, you map the extension in the web.config as well). Note that this will caause everything to be served by asp.net, even images and script files, which can slow things down.
Then create a handler mapping in your web.config to a http handler you create.
From there, in the ProcessRequest() method of the handler, you have access to the HttpContext that spawned the request and can manipulate the URL from there.
That is the easiest option, you could also create a HttpModule, or have the default page at root redirect to http://www.domain.com/default.aspx/this is my text, in the code-behind of default.aspx, you will be able to get the text following the page and slash.

Using HttpModule with .html file extension

I need access to session in httpmodule. It works fine when my page is a aspx page, but context.session is null when the request url is .html
I have .html mapped to use aspnet_isapi.dll
I am trying to access session in context_PreRequestHandlerExecute and I have httpmodule inherit IReadOnlySessionState
From my experience IReadOnlySessionState and IRequiresSessionState only apply to HttpHandlers.
See the following SO links on how to implement it:
Can I access session state from an HTTPModule?
IIS HttpModule unable to set Session
It does not work with HTML extension because aspnet_isapi.dll does not handle the extension, but handels .aspx pages.
You should use another extension instead of using HTML and you should register the new extension in IIS Application Configuration (Web Site Properties -> Home Directory tab -> Configuration button -> Mappings tab). Use .aspx as an example to add your own extension.

Categories

Resources