Embedding jQuery into your ASP.Net Server Custom Control - asp.net

I am undergraduate student. I had some queries related to embedding jQuery inside your ASP.NET Server side Custom Control.
private string GetEmbeddedTextFile(string sTextFile)
{
// generic function for retrieving the contents
// of an embedded text file resource as a string
// we'll get the executing assembly, and derive
// the namespace using the first type in the assembly
Assembly a = Assembly.GetExecutingAssembly();
String sNamespace = a.GetTypes()[0].Namespace;
// with the assembly and namespace, we'll get the
// embedded resource as a stream
Stream s = a.GetManifestResourceStream(
string.Format("{0}.{1}",a.GetName().Name, sTextFile)
);
// read the contents of the stream into a string
StreamReader sr = new StreamReader(s);
String sContents = sr.ReadToEnd();
sr.Close();
s.Close();
return sContents;
}
private void RegisterJavascriptFromResource()
{
// load the embedded text file "javascript.txt"
// and register its contents as client-side script
string sScript = GetEmbeddedTextFile("JScript.txt");
this.Page.RegisterClientScriptBlock("PleaseWaitButtonScript", sScript);
}
private void RegisterJQueryFromResource()
{
// load the embedded text file "javascript.txt"
// and register its contents as client-side script
string sScript = GetEmbeddedTextFile("jquery-1.4.1.min.txt");
this.Page.ClientScript.RegisterClientScriptBlock(typeof(string), "jQuery", sScript);
// this.Page.RegisterClientScriptBlock("JQueryResourceFile", sScript);
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
// the client-side javascript code is kept
// in an embedded resource; load the script
// and register it with the page.
RegisterJQueryFromResource();
RegisterJavascriptFromResource();
}
but the problem I am facing is that all my JQuery code which I have written in separate .JS file and have tried to embed in my Custom control , is streamed as output on the screen . Also , my Control is not behaving correctly as it should have to , jQuery functionality is not working behind due to this reason of not getting embedded properly :-(
Please help me out!
Thank you!

It sounds like you are missing the <script> tags surrounding the javascript. Try this overload of RegisterClientScriptBlock that takes a fourth boolean parameter that will add the script tags if it is true.
Page.ClientScript.RegisterClientScriptBlock(typeof(string), "jQuery", sScript, true);

"all my JQuery code which I have written in separate .JS file and have tried to embed in my >Custom control , is streamed as output on the screen" .
Sounds like you need to add a line that tells the code how to download the embedded javascript. Do it with an Assembly annotation above the start of a class in your custom control project. This is the format:
<Assembly: System.Web.UI.WebResource("Namespace.ScriptName.js", "application/x-javascript")>

Related

jQuery UI autocomplete is not displaying results fetched via AJAX

I am trying to use the jQuery UI autocomplete feature in my web application. What I have set up is a page called SearchPreload.aspx. This page checks for a value (term) to come in along with another parameter. The page validates the values that are incoming, and then it pulls some data from the database and prints out a javascript array (ex: ["item1","item2"]) on the page. Code:
protected void Page_Load(object sender, EventArgs e)
{
string curVal;
string type ="";
if (Request.QueryString["term"] != null)
{
curVal = Request.QueryString["term"].ToString();
curVal = curVal.ToLower();
if (Request.QueryString["Type"] != null)
type = Request.QueryString["Type"].ToString();
SwitchType(type,curVal);
}
}
public string PreLoadStrings(List<string> PreLoadValues, string curVal)
{
StringBuilder sb = new StringBuilder();
if (PreLoadValues.Any())
{
sb.Append("[\"");
foreach (string str in PreLoadValues)
{
if (!string.IsNullOrEmpty(str))
{
if (str.ToLower().Contains(curVal))
sb.Append(str).Append("\",\"");
}
}
sb.Append("\"];");
Response.Write(sb.ToString());
return sb.ToString();
}
}
The db part is working fine and printing out the correct data on the screen of the page if I navigate to it via browser.
The jQuery ui autocomplete is written as follows:
$(".searchBox").autocomplete({
source: "SearchPreload.aspx?Type=rbChoice",
minLength: 1
});
Now if my understanding is correct, every time I type in the search box, it should act as a keypress and fire my source to limit the data correct? When I through a debug statement in SearchPreload.aspx code behind, it appears that the page is not being hit at all.
If I wrap the autocomplete function in a .keypress function, then I get into the search preload page but still I do not get any results. I just want to show the results under the search box just like the default functionality example on the jQuery website. What am I doing wrong?
autocomplete will NOT display suggestions if the JSON returned by the server is invalid. So copy the following URL (or the returned JSON data) and paste it on JSONLint. See if your JSON is valid.
http://yourwebsite.com/path/to/Searchpreload.aspx?Type=rbChoice&term=Something
PS: I do not see that you're calling the PreLoadStrings function. I hope this is normal.
A couple of things to check.
Make sure that the path to the page is correct. If you are at http://mysite.com/subfolder/PageWithAutoComplete.aspx, and your searchpreload.aspx page is in another directory such as http://mysite.com/anotherFolder/searchpreload.aspx the url that you are using as the source would be incorrect, it would need to be
source: "/anotherFolder/Searchpreload.aspx?Type=rbChoice"
One other thing that you could try is to make the method that you are calling a page method on the searchpreload.aspx page. Typically when working with javascript, I try to use page methods to handle ajax reqeusts and send back it's data. More on page methods can be found here: http://www.singingeels.com/Articles/Using_Page_Methods_in_ASPNET_AJAX.aspx
HTH.

Asp.Net single control render for AJAX calls

I'm trying to implement something similar to this or this.
I've created a user control, a web service and a web method to return the rendered html of the control, executing the ajax calls via jQuery.
All works fine, but if I put something in the user control that uses a relative path (in my case an HyperLink with NavigateUrl="~/mypage.aspx") the resolution of relative path fails in my developing server.
I'm expecting:
http://localhost:999/MyApp/mypage.aspx
But I get:
http://localhost:999/mypage.aspx
Missing 'MyApp'...
I think the problem is on the creation of the Page used to load the control:
Page page = new Page();
Control control = page.LoadControl(userControlVirtualPath);
page.Controls.Add(control);
...
But I can't figure out why....
EDIT
Just for clarity
My user control is located at ~/ascx/mycontrol.ascx
and contains a really simple structure: by now just an hyperlink with NavigateUrl like "~/mypage.aspx".
And "mypage.aspx" really resides on the root.
Then I've made up a web service to return to ajax the partial rendered control:
[ScriptService]
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class wsAsynch : System.Web.Services.WebService
{
[WebMethod(EnableSession = true)]
public string GetControl(int parma1, int param2)
{
/* ...do some stuff with params... */
Page pageHolder = new Page();
UserControl viewControl = (UserControl)pageHolder.LoadControl("~/ascx/mycontrol.ascx");
Type viewControlType = viewControl.GetType();
/* ...set control properties with reflection... */
pageHolder.Controls.Add(viewControl);
StringWriter output = new StringWriter();
HttpContext.Current.Server.Execute(pageHolder, output, false);
return output.ToString();
}
}
The html is correctly rendered, but the relative path in the NavigateUrl of hyperlink is incorrectly resolved, because when I execute the project from developing server of VS2008, the root of my application is
http://localhost:999/MyApp/
and it's fine, but the NavigateUrl is resolved as
http://localhost:999/mypage.aspx
losing /MyApp/ .
Of Course if I put my ascx in a real page, instead of the pageHolder instance used in the ws, all works fine.
Another strange thing is that if I set the hl.NavigateUrl = Page.ResolveUrl("~/mypage.aspx") I get the correct url of the page:
http://localhost:999/MyApp/mypage.aspx
And by now I'll do that, but I would understand WHY it doesn't work in the normal way.
Any idea?
The problem is that the Page-class is not intented for instantiating just like that. If we fire up Reflector we'll quickly see that the Asp.Net internals sets an important property after instantiating a Page class an returning it as a IHttpHandler. You would have to set AppRelativeTemplateSourceDirectory. This is a property that exists on the Control class and internally it sets the TemplateControlVirtualDirectory property which is used by for instance HyperLink to resolve the correct url for "~" in a link.
Its important that you set this value before calling the LoadControl method, since the value of AppRelativeTemplateSourceDirectory is passed on to the controls created by your "master" control.
How to obtain the correct value to set on your property? Use the static AppDomainAppVirtualPath on the HttpRuntime class. Soo, to sum it up... this should work;
[WebMethod(EnableSession = true)]
public string GetControl(int parma1, int param2)
{
/* ...do some stuff with params... */
var pageHolder = new Page() { AppRelativeTemplateSourceDirectory = HttpRuntime.AppDomainAppVirtualPath };
var viewControl = (UserControl)pageHolder.LoadControl("~/ascx/mycontrol.ascx");
var viewControlType = viewControl.GetType();
/* ...set control properties with reflection... */
pageHolder.Controls.Add(viewControl);
var output = new StringWriter();
HttpContext.Current.Server.Execute(pageHolder, output, false);
return output.ToString();
}
The tildy pust the path in the root of the app, so its going to produce a the results you are seeing. You will want to use:
NavigateUrl="./whatever.aspx"
EDIT:
Here is a link that may also prove helpful...http://msdn.microsoft.com/en-us/library/ms178116.aspx
I find the /MyApp/ root causes all sorts of issues. It doesn't really answer your question 'why is doesn't work the normal way', but do you realize you can get rid of the /MyApp/ and host your website at http:/localhost/...?
Just set Virtual Path in the website properties to '/'.
This clears everything up, unless of course you are trying to host multiple apps on the development PC at the same time.
It might be that the new page object does not have "MyApp" as root, so it is resolved to the server root as default.
My question is rather why it works with Page.ResolveUrl(...).
Maybe ResolveUrl does some more investigation about the location of the usercontrol, and resolves based on that.
Weird, I recreated the example. The hyperlink renders as <a id="ctl00_hlRawr" href="Default.aspx"></a> for a given navigation url of ~/Default.aspx. My guess is that it has something to do with the RequestMethod. On a regular page it is "GET" but on a webservice call it is a "POST".
I was unable to recreate your results with hl.NavigateUrl = Page.ResolveUrl("~/mypage.aspx")
The control always rendered as <a id="ctl00_hlRawr" href="Default.aspx"></a> given a virtual path. (Page.ResolveUrl gives me "~/Default.aspx")
I would suggest doing something like this to avoid the trouble in the future.
protected void Page_Load(object sender, EventArgs e)
{
hlRawr.NavigateUrl = FullyQualifiedApplicationPath + "/Default.aspx";
}
public static string FullyQualifiedApplicationPath
{
get
{
//Return variable declaration
string appPath = null;
//Getting the current context of HTTP request
HttpContext context = HttpContext.Current;
//Checking the current context content
if (context != null)
{
//Formatting the fully qualified website url/name
appPath = string.Format("{0}://{1}{2}{3}",
context.Request.Url.Scheme,
context.Request.Url.Host,
(context.Request.Url.Port == 80 ? string.Empty : ":" + context.Request.Url.Port),
context.Request.ApplicationPath);
}
return appPath;
}
}
Regards,
It is hard to tell what you are trying to achieve without posting the line that actually sets the Url on of the HyperLink, but I think I understand your directory structure.
However, I have never run into a situation that couldn't be solved one way or another with the ResolveUrl() method. String parsing for a temporary path that won't be used in production is not recommended because it will add more complexity to your project.
This code will resolve in any object that inherits from page (including a usercontrol):
Page page = (Page)Context.Handler;
string Url = page.ResolveUrl("~/Anything.aspx");
Another thing you could try is something like this:
Me.Parent.ResolveUrl("~/Anything.aspx");
If these aren't working, you may want to check your IIS settings to make sure your site is configured as an application.

Accessing ScriptManager proxies in code

I have a situation where I'd like to add a "last modified" timestamp to the paths of my js files (ex. "custom.js?2009082020091417") that are referenced in my ScriptManager (contained in my MasterPage) and in any ScriptManagerProxies (content pages).
I can easily get access to the ScriptManager in code and then iterate through it's Scripts collection to get the Script paths that I've set declaratively and then "set" a new path with the tacked on "?[lastmodifiedtimestamp]".
The problem is, I can't figure out how to get to any ScriptManagerProxies that may exist.
When debugging, I can see the proxies in the non-public members (._proxies). I've looked through the documentation and can't see where you can actually publicly access this collection.
Am I'm missing something?
I have the following code in the base class of my content page's Page_PreRenderComplete event:
ScriptManager sm = ScriptManager.GetCurrent((Page)this);
if(sm != null)
{
foreach (ScriptReference sr in sm.Scripts)
{
string fullpath = Server.MapPath(sr.Path);
sr.PathWithVersion(fullpath); //extension method that sets "new" script path
}
}
The above code gives me the one script I have defined in my MasterPage, but not the two other scripts I have defined in the ScriptManagerProxy of my content page.
Came up with a solution. Seems that the only place that all the merged scripts can be accessed is in the main ScriptManager's ResolveScriptReference event. In this event, for each script that has a defined path, I use an extension method that will tack on a "version number" based on the js file's last modified date. Now that my js files are "versioned", when I make a change to a js file, the browser will not cache an older version.
Master Page Code:
protected void scriptManager_ResolveScriptReference(object sender, ScriptReferenceEventArgs e)
{
if (!String.IsNullOrEmpty(e.Script.Path))
{
e.AddVersionToScriptPath(Server.MapPath(e.Script.Path));
}
}
Extension Method:
public static void AddVersionToScriptPath(this ScriptReferenceEventArgs scrArg, string fullpath)
{
string scriptpath = scrArg.Script.Path;
if (File.Exists(fullpath))
{
FileInfo fi = new FileInfo(fullpath);
scriptpath += "?" + fi.LastWriteTime.ToString("yyyyMMddhhmm");
}
scrArg.Script.Path = scriptpath;
}

How to pass content of image file from fileupload control to web method via javascript?

I have a problem with using binary content of file. I want to pass web method content of file. I retriev it from fileupload control on my page via javascript function getAsBinary(). But error appears in web method, when I try to create example of class Image.
So, I have the page (.aspx) with fileupload control and scriptmanager. There are three javascript function:
// Get image from fileupload control and pass it in webmethod
function Get_image() {
var file_uploader = document.getElementById(file_uploader_name);
var file_content = file_uploader.files[0].getAsBinary();
imupcon.Get_image(file_content, OnRequestComplete, OnError);
}
// Successful execution
function OnRequestComplete(result) {alert(result);}
//Error execution
function OnError() { alert("Error!");}
And I have web-service with web-method:
[WebMethod]
public string Get_image(string file_content, string file_name)
{
byte[] data = Encoding.Unicode.GetBytes(file_content);
MemoryStream memStream = new MemoryStream();
memStream.Write(data, 0, data.Length);
//Error appears here
System.Drawing.Image image = System.Drawing.Image.FromStream(memStream);
memStream.Close();
return "Hurray!";
}
Does any have idea, what is reason? How I can pass content of file to web method? Thanks.
You don't need Encoding.Unicode.GetBytes if it's as it's already in binary. The data would be in unicode if you called files[0].getAsText("utf-8"). Please note that all of these methods are now obsolete and you should use feature detection and use the standard FileReader API if it is available.

How do I Pass an Image from Flash to ASP.NET?

Quick version:
How do I get an image that was generated on the users browser back to the server?
The current plan is this:
The Flash developer will convert the bitmap to JPEG
He will then POST the JPEG to a page on the site.
I'm thinking I can create a WebService which will use a StreamReader to read the post and save it as a file.
Would that work? Any existing code/samples for doing this?
I suppose we should be able to look at code for doing any file upload to ASP.NET.
In this example, I've created a Flash file with a button on the stage. When you click that button, the Flash sends the image of the button to an ASPX file which saves it out as a JPEG. As you'll see this is done by drawing the DisplayObject into a BitmapData object and as such, you can easily replace the reference to the button with anything that inherits from DisplayObject (including a movie clip that contains the canvas for a paint application etc).
I’ll walk you through the Flash element first and then the .NET backend.
Flash
To send a generated image like this from Flash to ASP.NET (or any other backend) you’re going to need a couple of 3rd party libraries. We’ll need a JPEG Encoder (which Flash doesn’t have, but recent versions of Flex do) which we can get from the AS3 Core Lib http://code.google.com/p/as3corelib/. We’ll also need a base64 encoder for sending the data over the wire. I’ll use the one from Dynamic Flash, available at http://dynamicflash.com/goodies/base64/.
Download these and extract them somewhere sensible on your hard disk (like a C:\lib folder).
I created a new AS3 Flash file and saved it as uploader.fla. I added a button component to the stage and named it btnUpload. Next I edited the ActionScript settings and added my c:\lib folder to the classpath. Then I gave the document a class name of Uploader and saved the file.
Next, I created an ActionScript file and added the following code to it:
package
{
import flash.display.BitmapData;
import flash.display.MovieClip;
import flash.events.MouseEvent;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.net.URLRequestMethod;
import flash.net.URLVariables;
import flash.utils.ByteArray;
import fl.controls.Button;
import com.adobe.images.JPGEncoder;
import com.dynamicflash.util.Base64;
public class Uploader extends MovieClip
{
// Reference to the button on the stage
public var btnUpload:Button;
// Encoder quality
private var _jpegQuality:int = 100;
// Path to the upload script
private var _uploadPath:String = "/upload.aspx";
public function Uploader()
{
btnUpload.addEventListener(MouseEvent.CLICK, buttonClick);
}
private function buttonClick(e:MouseEvent):void
{
// Create a new BitmapData object the size of the upload button.
// We're going to send the image of the button to the server.
var image:BitmapData = new BitmapData(btnUpload.width, btnUpload.height);
// Draw the button into the BitmapData
image.draw(btnUpload);
// Encode the BitmapData into a ByteArray
var enc:JPGEncoder = new JPGEncoder(_jpegQuality);
var bytes:ByteArray = enc.encode(image);
// and convert the ByteArray to a Base64 encoded string
var base64Bytes:String = Base64.encodeByteArray(bytes);
// Add the string to a URLVariables object
var vars:URLVariables = new URLVariables();
vars.imageData = base64Bytes;
// and send it over the wire via HTTP POST
var url:URLRequest = new URLRequest(_uploadPath);
url.data = vars;
url.method = URLRequestMethod.POST;
var loader:URLLoader = new URLLoader();
loader.load(url);
}
}
}
I saved this file next to the FLA with the name Uploader.as.
I published the SWF into the root of my Asp.NET website.
This code assumes you want to upload the jpeg with a quality of 100% and that the script which will receive the data is called upload.aspx and is located in the root of the site.
ASP.NET
In the root of my website I created a WebForm named upload.aspx. In the .aspx file, i removed all the content apart from the page directive. It’s content look like this:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="upload.aspx.cs" Inherits="upload" %>
Then in the CodeBehind, I added the following:
using System;
using System.IO;
public partial class upload : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// Get the data from the POST array
string data = Request.Form["imageData"];
// Decode the bytes from the Base64 string
byte[] bytes = Convert.FromBase64String(data);
// Write the jpeg to disk
string path = Server.MapPath("~/save.jpg");
File.WriteAllBytes(path, bytes);
// Clear the response and send a Flash variable back to the URL Loader
Response.Clear();
Response.ContentType = "text/plain";
Response.Write("ok=ok");
}
}
There are obviously hard-coded values such as the save path but from this you should be able to create whatever system you require.
If you need to manipulate the image, as long as you can get a byte[] or a Stream of the POSTed file, you can create an image of it, e.g.
MemoryStream mstr = new MemoryStream(myByteArray);
Image myImage = Image.FromStream(mstr);
Have him post the files like a standard HTML form. You can access those files in the Page_Load event of the page he is posting to by using the following collection
Request.Files
This will return a collection of HttpPostedFiles just like what a FileUpload control does.

Resources