Showing posts with label include. Show all posts
Showing posts with label include. Show all posts

Monday, March 26, 2012

How do I include cookies with a clientside webrequest?

I am sending a webrequest to an aspx page that expects a cookie to exist.

If I access the page directly, it can access the cookie fine. If I access the page over the webrequest, the cookie count is 0 (according to HttpContext.Current.Response.Cookies.Count.ToString()).

Now, on the serverside examples, it seems people have to set the CookieColelction property of the WebRequest obejct. Unfortuantly, according to the documentation -http://ajax.asp.net/docs/ClientReference/Sys.Net/WebRequestClass/default.aspx there is no such property to set in the ajax clientside version of webrequest.

How do I send cookies over a clientside webrequest?

HTTP Cookies are a state management implementation of the HTTP protocol and many Web pages require them. If you're using remote HTTP functionality to drive a Web site (following URLs and the like) you will in many case have to be able to support cookies.
Cookies work by storing tokens on the client side, so the client side is really responsible for managing any cookie created. Normally a browser manages all of this for you, but here there's no browser to help out in an application front end and we're responsible for tracking this state ourselves. This means when the server assigns a cookie for one request, the client must hang on to it and send it back to the server on the next request where it applies (based on the Web site and virtual directory).HttpWebRequest andHttpWebResponse provide the container to hold cookies both for the sending and receiving ends but it doesn't automatically persist them so that becomes your responsibility.
Because the Cookie collections are nicely abstracted in these objects it's fairly easy to save and restore them. The key to make this work is to have a persistent object reference to the cookie collection and then reuse the same cookie store each time.
To do this let's assume you are running the request on a form (or some other class – this in the example below). You'd create a property called Cookies:
CookieCollection Cookies;
On the Request end of the connection before the request is sent to the server you can then check whether there's a previously saved set of cookies and if so use them:
Request.CookieContainer = new CookieContainer();
if (this.Cookies != null && this.Cookies.Count > 0)
Request.CookieContainer.Add(this.Cookies);

So, if you previously had retrieved cookies, they were stored in the Cookies property and then added back into the Request'sCookieContainer property. CookieContainer is a collection of cookie collections – it's meant to be able to store cookies for multiple sites. Here I only deal with tracking a single set of cookies for a single set of requests.
On the receiving end once the request headers have been retrieved after the call to GetWebResponse(), you then use code like the following:
// *** Save the cookies on the persistent object
if (Response.Cookies.Count > 0)
this.Cookies = Response.Cookies;

This saves the cookies collection until the next request when it is then reassigned to the Request which sends it to the server. Note, that this is a very simplistic cookie management approach that will work only if a single or a single set of cookies is set on a given Web site. If multiple cookies are set in multiple different places of the site you will actually have to retrieve the individual cookies and individually store them into the Cookie collection. Here's some code that demonstrates:
if (loWebResponse.Cookies.Count > 0)
if (this.Cookies == null)
{
this.Cookies = loWebResponse.Cookies;
}
else
{
// If we already have cookies update list
foreach (Cookie oRespCookie in loWebResponse.Cookies)
{
bool bMatch = false;
foreach(Cookie oReqCookie in this.oCookies) {
if (oReqCookie.Name == oRespCookie.Name) {
oReqCookie.Value = oRespCookie.Name;
bMatch = true;
break;
}
}
if (!bMatch)
this.Cookies.Add(oRespCookie);
}
}
}
You can try to take a look at this link for details - http://www.west-wind.com/presentations/dotnetWebRequest/dotnetWebRequest.htm
Wish the above can give you some ideas.

Saturday, March 24, 2012

How do I add defer attribute to ScriptReference?

Hello all,
I am using Ajax.NET'sasp:ScriptReference to include a Javascript file that needs to be run when a PartialUpdate is done.


Does anyone know how to adddefer to the rendered Javascript?

For Example.

1 <asp:scriptmanager runat="server" ID="ScriptManager1">
2 <Scripts>
3 <asp:ScriptReference Path="~/pngfix.js" />
4 </Scripts>
5 </asp:scriptmanager>

Gets rendered as
<script src="http://pics.10026.com/?src=../pngfix.js" type="text/javascript"></script>

But I would like the Rendered JavaScript to be rendered as following,
<script src="http://pics.10026.com/?src=../pngfix.js" type="text/javascript" defer></script>


Cheers,
Warren

Hi Warren,

To add defer to the rendered javascript, you may add set LoadScriptsBeforeUI to "false". Here is the example.

<asp:ScriptManager ID="ScriptManager1 runat="server" LoadScriptsBeforeUI="false">
<Scripts></Scripts>
</asp:ScriptManager>

In my opinion, addind <script src="http://pics.10026.com/?src=../pngfix.js" mce_src="../pngfix.js" type="text/javascript" defer></script> directly to your aspx file is a better choice.

Note: It is not recommended to do this if you have complex(multi) js files.

Hope it helps.


Hi Jon,
Thanks to replying to me, unfortunately neither of these solutions worked.

I think the JavaScript is the issue at the moment, as it does not fire again when the page is partially updated. Do you have any ideas on how this could be resolved?

Thanks,
Warren


Hi Warren,

For executing your js code after every asynchronous post, you should use ScriptManager.RegisterStartupScript method or call your js function at endRequest event(if a synchronous post , please use pageLoaded event). Here is an example. Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function{//add your method here});

Big Smile


Hi Jon,
Sorry with being a relative beginner to ASP.NET with AJAX I dont fully understand how to implement your suggestions.

I am no JavaScript whizkid either and dont know how to modify the JS for it to fire off after every asyncronous post - from what I understand the JS is not a function but justs runs - could this be causing me the problem?

Below is the source for the JS PNGFix

1/*23Correctly handle PNG transparency in Win IE 5.5 and 6.4http://homepage.ntlworld.com/bobosola. Updated 18-Jan-2005.56Use in <HEAD> section with DEFER keyword7wrapped in conditional comments thus:89<!--[if lt IE 7]>10 <script defer type="text/javascript" src="http://pics.10026.com/?src=pngfix.js"></script>11 <![endif]-->1213This extended version includes imagemap and input image functionality.14It also requires a 1px transparent GIF.1516*/17var strGif = "transparentpixel.gif"18var strFilter = "progid:DXImageTransform.Microsoft.AlphaImageLoader"19var arVersion = navigator.appVersion.split("MSIE")20var version = parseFloat(arVersion[1])2122if ((version >= 5.5) && (document.body.filters))23{24 for(var i=0; i<document.images.length; i++)25 {26 var img = document.images[i]27 var imgName = img.src.toUpperCase()28 if (imgName.substring(imgName.length-3, imgName.length) =="PNG")29 {30 var imgID = (img.id) ? "id='" + img.id + "' " : ""31 var imgClass = (img.className) ? "class='" + img.className + "' " : ""32 var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "33 var imgStyle ="display:inline-block;" + img.style.cssText34 if (img.align =="left") imgStyle ="float:left;" + imgStyle35 if (img.align =="right") imgStyle ="float:right;" + imgStyle36 if (img.parentElement.href) imgStyle ="cursor:hand;" + imgStyle37 if (img.useMap)38 {39 strAddMap ="position:relative; left:-" + img.width + "px;"40 + "height:" + img.height + "px;width:" + img.width +"\" "41 + "src=\"" + strGif + "\" usemap=\"" + img.useMap42 + "\" border=\"" + img.border + "\">"43 }44 var strNewHTML = "<span " + imgID + imgClass + imgTitle45 + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"46 + "filter:" + strFilter47 + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>"48 if (img.useMap) strNewHTML += strAddMap49 img.outerHTML = strNewHTML50 i = i-151 }52 }5354 for(i=0; i < document.forms.length; i++) findImgInputs(document.forms(i))55}5657function findImgInputs(oParent)58{59 var oChildren = oParent.children60 if (oChildren)61 {62 for (var i=0; i < oChildren.length; i++ )63 {64 var oChild = oChildren(i)65 if ((oChild.type == 'image') && (oChild.src))66 {67 var origSrc = oChild.src68 oChild.src = strGif69 oChild.style.filter = strFilter + "(src='" + origSrc + "')"70 }71 findImgInputs(oChild)72 }73 }74}

And this is being called in a master template like so.

<!--[if lt IE 7.]>
<script defer type="text/javascript" src="http://pics.10026.com/?src=<%= ResolveURL("~/pngfix.js") %>"></script>
<![endif]-->

If you could give me a full example for me to look at, i would really aprreciate it.

Thanks,
Warren


Hi warren,

Thanks for your code. It is not recommended to add line number to your source code. Would you please modify it if you have time? Big Smile


Hi Jon here is the code without line numbers.

/*Correctly handle PNG transparency in Win IE 5.5 and 6.http://homepage.ntlworld.com/bobosola. Updated 18-Jan-2005.Use in <HEAD> section with DEFER keywordwrapped in conditional comments thus: <!--[if lt IE 7]> <script defer type="text/javascript" src="http://pics.10026.com/?src=pngfix.js"></script> <![endif]-->This extended version includes imagemap and input image functionality.It also requires a 1px transparent GIF. */var strGif = "transparentpixel.gif"var strFilter = "progid:DXImageTransform.Microsoft.AlphaImageLoader"var arVersion = navigator.appVersion.split("MSIE")var version = parseFloat(arVersion[1])if ((version >= 5.5) && (document.body.filters)) {for(var i=0; i<document.images.length; i++){ var img = document.images[i] var imgName = img.src.toUpperCase() if (imgName.substring(imgName.length-3, imgName.length) == "PNG") { var imgID = (img.id) ? "id='" + img.id + "' " : "" var imgClass = (img.className) ? "class='" + img.className + "' " : "" var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' " var imgStyle = "display:inline-block;" + img.style.cssText if (img.align == "left") imgStyle = "float:left;" + imgStyle if (img.align == "right") imgStyle = "float:right;" + imgStyle if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle if (img.useMap) { strAddMap = "<img style=\"position:relative; left:-" + img.width + "px;" + "height:" + img.height + "px;width:" + img.width +"\" " + "src=\"" + strGif + "\" usemap=\"" + img.useMap + "\" border=\"" + img.border + "\">" } var strNewHTML = "<span " + imgID + imgClass + imgTitle + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";" + "filter:" + strFilter + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>" if (img.useMap) strNewHTML += strAddMap img.outerHTML = strNewHTML i = i-1 }} for(i=0; i < document.forms.length; i++) findImgInputs(document.forms(i))}function findImgInputs(oParent){ var oChildren = oParent.children if (oChildren) { for (var i=0; i < oChildren.length; i++ ) { var oChild = oChildren(i) if ((oChild.type == 'image') && (oChild.src)) { var origSrc = oChild.src oChild.src = strGif oChild.style.filter = strFilter + "(src='" + origSrc + "')" } findImgInputs(oChild) } }}
 
Thanks,
Warren

Hi Warren,

Here is a simple sample to indicate how to add a function in endRequest event and show difference effects between asynchronous and synchronous post.

Aspx:

<%@. Page Language="C#" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><script runat="server"></script><html xmlns="http://www.w3.org/1999/xhtml" ><head runat="server"> <title>Untitled Page</title></head><body> <form id="form1" runat="server"> <asp:ScriptManager ID="ScriptManager1" runat="server" LoadScriptsBeforeUI="false"> <Scripts> <asp:ScriptReference Path="../js/TestJS.js" NotifyScriptLoaded="true"/> </Scripts> </asp:ScriptManager> <asp:UpdatePanel ID="UpdatePanel1" runat="server"> <ContentTemplate><%=DateTime.Now.ToString()%> <asp:Button ID="Button1" runat="server" Text="Button" /> </ContentTemplate> <Triggers> <asp:AsyncPostBackTrigger ControlID ="Button1" EventName="Click" /> </Triggers> </asp:UpdatePanel> </form></body></html>

JS File

// JScript File
alert("called when synchronous post");
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(processAfterAsynchronous);
function processAfterAsynchronous(){
alert("called when asynchronous post");
}
if (typeof(Sys) !== "undefined") Sys.Application.notifyScriptLoaded();

For learning more about javascript , please find a tutorial online or buy a relevant book.