Showing posts with label created. Show all posts
Showing posts with label created. Show all posts

Saturday, March 24, 2012

Internet Explorer freezes after using AJAX

Hi

I have a weird problem. I have created an ASP.NET site which is displayed as a popup in another website.
The popup shows a treeview with which the user can update some data via an webservice. After selecting a treenode, a webservice is called in the code behind.
When I open this popup two times it will freeze all Internet Explorer windows which belongs to the current website. Only restarting the Internet Explorer helps. There is no javascript error or any other exception.

I have made tests with similar websites without ajax without any problem., so I think this may have to do with ASP.NET AJAX. The problem occurrs with Internet Explorer 6 and 7.

This is the code of the popup website:

<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div id="header">
<h1>
<asp:Label runat="server" Text="folder choice" ID="LaHeader"></asp:Label>
</h1>
</div>
<div id="haupt">
<div id="navi">
<asp:UpdatePanel runat="server" ID="UpPaTreeView" ChildrenAsTriggers="true">
<ContentTemplate>
<asp:TreeView runat="server" ID="TrViStructure" DataSourceID="XmDaSoStructure" OnSelectedNodeChanged="TrViStructure_SelectedNodeChanged">
<DataBindings>
<asp:TreeNodeBinding DataMember="Root" PopulateOnDemand="True" TextField="Name" ValueField="GUID" />
<asp:TreeNodeBinding DataMember="Folder" TextField="Name" ValueField="GUID" />
<asp:TreeNodeBinding DataMember="Underfolder" TextField="Name" ValueField="GUID" />
</DataBindings>
<NodeStyle CssClass="TreeItem" />
<HoverNodeStyle CssClass="TreeItemHovered" />
<SelectedNodeStyle CssClass="TreeItemSelected" />
</asp:TreeView>
</ContentTemplate>
</asp:UpdatePanel>
</div>
<div id="content">
<asp:UpdatePanel ID="UpPaStatus" runat="server" ChildrenAsTriggers="true">
<ContentTemplate>
<asp:Panel ID="PaButton" runat="server" Visible="false">
<div id="controls">
<asp:Button OnClientClick="closewindow()" runat="server" CssClass="button" Text="Close"
ID="BuClose" />
</div>
</asp:Panel>
<asp:Panel ID="PaMessage" runat="server" Visible="false">
<div id="label">
<asp:Label ID="laErrorHeader" runat="server" Text="Header"></asp:Label><br />
<asp:Label ID="laErrorMessage" runat="server" Text="Label"></asp:Label>
</div>
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdateProgress ID="UpdateProgress1" runat="server" AssociatedUpdatePanelID="UpPaTreeView">
<ProgressTemplate>
<div id="update">
<img src="img/ajax-loader-blueBg.gif" />
</div>
</ProgressTemplate>
</asp:UpdateProgress>
</div>
</div>
<asp:XmlDataSource runat="server" ID="XmDaSoStructure" DataFile="~/XML/Folders.xml">
</asp:XmlDataSource>
</form>

<script type="text/javascript">
function closewindow()
{
window.opener = this;
window.close();
}

</script>

</body>


Hi c.kr

It is not recommended to add the line number in your source code. Would you please modify it and provide more C# code and XML file related to your page ?


Hi, sorry for the line numbers, I removed it.

This is the used xml file for the treeview:

<Folder Name="foobar" GUID="some guid">
<Folder Name="foobar2" GUID="some guid2"></Folder>
<Folder Name="foo" GUID="5871D39C-7DD0-DB11-A445-0003FF6D5330">
<Folder Name="bar" GUID="E8C495C8-7DD0-DB11-A445-0003FF6D5330">
</Folder>
</Folder>
</Folder>
 This is the code behind file for the webpage:
public partialclass FolderChoice : System.Web.UI.Page
{
string _objectId =string.Empty;
CrmService _service;

private SessionData sessionData
{
get {return Session["SessionData"] ==null ?null : (SessionData)Session["SessionData"];
}
set { Session["SessionData"] =value;
}
}

protected void Page_Load(object sender, EventArgs e)
{
sessionData = CRMplusServiceConnector.GetSessionData(Request.ServerVariables["HTTP_ACCEPT_LANGUAGE"]);
_objectId = Server.UrlDecode(Request.QueryString["oId"].ToString());

LaHeader.Text = sessionData.Translation["folderchoice.LaHeader"];
BuClose.Text = sessionData.Translation["folderchoice.BuClose"];
}

private void ConnectToCrm()
{
_service =new CrmService();

_service.Url = CRMplusServiceConnector.Configuration["crmServiceUrl"];
_service.Credentials = System.Net.CredentialCache.DefaultCredentials;

//----------------------
// Gets the Current User's Information
//---------------------- WhoAmIRequest userRequest =new WhoAmIRequest();
WhoAmIResponse userResp = (WhoAmIResponse)_service.Execute(userRequest);

//----------------------
// Set UserId of current User as CallerId
//---------------------- _service.CallerIdValue =new CallerId();
_service.CallerIdValue.CallerGuid = userResp.UserId;

//----------------------
// Cache credentials so we don't have to re-authenticate on each request.
//---------------------- _service.PreAuthenticate =true;
}

protected void TrViStructure_SelectedNodeChanged(object sender, EventArgs e)
{
this.PaMessage.Visible =false;

PaButton.Visible =false;
TrViStructure.Enabled =false;
TrViStructure.EnableClientScript =false;

SelectFolder();

TrViStructure.Enabled =true;
TrViStructure.EnableClientScript =true;
PaButton.Visible =true;
}

private void SelectFolder()
{
try { ConnectToCrm();// Create the target object for the request TargetRetrieve<someEntitiy> targetDoc =new TargetRetrieve<someEntity>();

// Set the target object's IDstring guiddoc = _objectId.Replace('{',' ');
guiddoc = guiddoc.Replace('}',' ');
guiddoc = guiddoc.Trim();
targetDoc.EntityId =new Guid(guiddoc);

// Create the request object RetrieveRequest reqDoc =new RetrieveRequest();

// Set the request object's properties reqDoc.Target = targetDoc; reqDoc.ColumnSet =new AllColumns();

// Execute the request RetrieveResponse retDoc = (RetrieveResponse)_service.Execute(reqDoc); <someEntity> curDoc =new <someEntity>();
if ( retDoc.BusinessEntity !=null )
{
curDoc = (<someEntity>)retDoc.BusinessEntity;
}
else { Environment.Exit(1); } curDoc.new_documentfolderid =new Lookup();
curDoc.new_documentfolderid.type = EntityName.new_folder.ToString();
curDoc.new_documentfolderid.Value =new Guid(TrViStructure.SelectedNode.Value.ToString());
_service.Update(curDoc);
}
catch ( System.Web.Services.Protocols.SoapException exc )
{
ShowException(exc);
}
}

private void ShowException(System.Web.Services.Protocols.SoapException exc)
{
this.PaMessage.Visible =true;
this.laErrorHeader.Text = sessionData.Translation["folderchoice.LaError"];
this.laErrorMessage.Text = exc.Detail.InnerText;
}
}

I replaced one of our classes with <someEntity>. The service which is called belongs to Microsoft Dynamics CRM.

Hi c.kr,

Sorry for the delay.I'm failed to reproduce your problem after wholly copied your code into a new project. The best way to indicate the exact root cause is dubugging it step by step in VS2005. By the way, Treeview control is not support very well inside UpdatePanel.http://ajax.asp.net/docs/overview/UpdatePanelOverview.aspx please focus on "Controls that Are Not Compatible with UpdatePanel Controls ".

If you has found it , please share it with us.

Invoke an exe file on server side

I created a page with a button. The user presses this button and it is supposed to invoke an exe file that works on the server side. I tried the following code behind:

Label2.Text ="The bot began it's work. Pleas wait..."Dim startInfo As System.Diagnostics.ProcessStartInfoDim pStart As New System.Diagnostics.ProcessstartInfo = New System.Diagnostics.ProcessStartInfo("http://.../files/BotScript1.exe")pStart.StartInfo = startInfopStart.Start()pStart.WaitForExit()Label2.Text = "The bot has finished it's work"

My problem is that this doesn't work on the server side: Pressing the button asks the user if he wants to open the file. I want this file to work on the server.

If this can't be done for security reasons (I don't see why not - this file has nothing to do with the user, but is part of the server script), I would like to use the source code of this exe file and run it on the server. The problem doing it this way is that the script is in c# and my pages are in VB.NET.

Thanks
Yoni

If the .exe is on your web server, try using Server.MapPath in the ProcessStartInfo() to get the actual file location, instead of the HTTP (virtual) location.


doyleits:

If the .exe is on your web server, try using Server.MapPath in the ProcessStartInfo() to get the actual file location, instead of the HTTP (virtual) location.

I tried that, and the exe runs, but as a diff problem came up, I decided to put the source code in my code behind page. I now face a new problem:

I have created a listbox inside an update panel, but when I use the code behind to add items to the listbox (in order to notify the user whats going on) - they added items don't appear until the server is done with the code. How can I get the listbox to refresh itself every time I add/remove/edit items from it?

Thanks,
Yoni


Put the ListBox inside UpdatePanel. Also set the UpdateMode property toConditional

When items will be added/deleted call UpdatePanel1.Update()

http://www.asp.net/ajax/documentation/live/mref/M_System_Web_UI_UpdatePanel_Update.aspx


chetan.sarode:

Put the ListBox inside UpdatePanel. Also set the UpdateMode property toConditional

When items will be added/deleted call UpdatePanel1.Update()

http://www.asp.net/ajax/documentation/live/mref/M_System_Web_UI_UpdatePanel_Update.aspx

I did as you said: I added a UpdateMode="Conditional" property to the Update Panel and used the Update() function after every change I did to the list - but still nothing. Any ideas?

Thanks
Yoni


Hi Yoni,

I recommend copying those source code into a class library. And reference the assembly in your web application. It's better than changing security settings.

After the class library has been compiled into an assembly, it can be used regardless of what language it's written in.


Sorry, I didn't notice that you've solved the running exe issue.

yonidebest:

I tried that, and the exe runs, but as a diff problem came up, I decided to put the source code in my code behind page. I now face a new problem:

I have created a listbox inside an update panel, but when I use the code behind to add items to the listbox (in order to notify the user whats going on) - they added items don't appear until the server is done with the code. How can I get the listbox to refresh itself every time I add/remove/edit items from it?

Thanks,
Yoni

I think you can add a timer on the page to refresh the page at a specific interval.

Is anybody testing these controls to be valid HTML?

I am using the accordion pane control and the output rendered out is falling over on validation. There is block level elements being created inside of inline elements which is against the spec.Sad What is the reason for doing this as apposed to using a div but still have well formed HTML?

1<div id="ctl00_SampleContent_MyAccordion">
2 <input type="hidden" name="ctl00$SampleContent$MyAccordion_AccordionExtender_ClientState" id="ctl00_SampleContent_MyAccordion_AccordionExtender_ClientState" value="0" />
3 <span id="ctl00_SampleContent_AccordionPane1">
4 <div>
5 <div class="accordionHeader">
6 <a href="http://links.10026.com/?link=" onclick="return false;" class="accordionLink">1. Accordion</a>
7 </div>
8 </div>
9 <div>
10 <div class="accordionContent">
11 The Accordion is a web control that allows you to provide multiple panes and display them one at a time.
12 It is like having several <a href="../CollapsiblePanel/CollapsiblePanel.aspx">CollapsiblePanels</a>
13
14 where only one can be expanded at a time. The Accordion is implemented as a web control that contains
15 AccordionPane web controls. Each AccordionPane control has a template for its Header and its Content.
16 We keep track of the selected pane so it stays visible across postbacks.
17 </div>
18 </div>
19 </span>
20</div>
The above code should out output like

1 <div id="ctl00_SampleContent_MyAccordion">2 <input type="hidden" name="ctl00$SampleContent$MyAccordion_AccordionExtender_ClientState" id="ctl00_SampleContent_MyAccordion_AccordionExtender_ClientState" value="0" />3 <div id="ctl00_SampleContent_AccordionPane1">4 <div>5 <div class="accordionHeader">6 <a href="http://links.10026.com/?link=" onclick="return false;" class="accordionLink">1. Accordion</a>7 </div>8 </div>9 <div>10 <div class="accordionContent">11 The Accordion is a web control that allows you to provide multiple panes and display them one at a time.12 It is like having several <a href="../CollapsiblePanel/CollapsiblePanel.aspx">CollapsiblePanels</a>1314 where only one can be expanded at a time. The Accordion is implemented as a web control that contains15 AccordionPane web controls. Each AccordionPane control has a template for its Header and its Content.16 We keep track of the selected pane so it stays visible across postbacks.17 </div>18 </div>19 </div>20 </div>
With a complete lack of spans.Is it actually creating a problem for you?

Jonathan Allen:

Is it actually creating a problem for you?

It is not valid HTML. It is that cut and dry. To me not passing validation is the same to me as if the control had another bug and failed to work at all. The only difference between it and other bugs is that browsers have become too lax with what they should consider valid and renderable code.


I see your point but it is not a critical factor and I wouldn't classify it as a bug or anything unless it does strange stuff which I don't believe it is. At least I haven't had any troubles with it. I'd rather get something working correctly than worry about whether it follows some ideaology and then think about minor things as validity. You know, the source code is available so you are welcomed to edit it yourself until you are satisfied or you could submit an issue about it. I don't see anything happening here as it isn't the correct place.

Well it really is a shame that browsers are so lenient on incorrectly written code, and thats what it is plain and simple. Just because a browser does not fall over on it it does not mean the code is correct. Do you let other bugs just go in your logic layer just because a browser doesn't fall over on them even though it gives back an incorrect result? What if i said that 1+1=5 and I can justify that by saying that my browser still runs if I feed it some data like that?Indifferent

I need to look into the code as there is some other things that the accordion pane is falling over on for me too when it comes to rendering content in the content area.


You are being silly. For all practial purposes, valid HTML is that which is accepted by the browsers that you are targeting. The spec doesn't really mean a whole lot to app developers, as no browser actually implements it 100%. Obsessing over it just wastes time.


I agree with Custa, Its adherence to standards will only improve the toolkit.

If the accordian control is outputting incorrectly formatted HTML, it should be flagged as a bug. It seems that, there are many problems with the accordion control, the causes of which are not all known. Ignoring html that fails validation seems pretty backwards to me.

But then I guess thats the difference between professionals and amateurs. Sure, if you are designing a online shopping list for your grandma, then who cares... I take pride in my work, and if I am to put my name next to any system, and proudly say that I engineered it, I would not knowingly ignore a potential problem.

-Steve



Jonathan Allen:

You are being silly. For all practial purposes, valid HTML is that which is accepted by the browsers that you are targeting. The spec doesn't really mean a whole lot to app developers, as no browser actually implements it 100%. Obsessing over it just wastes time.

That really is a poor attitude and probably the reason why I cringe whenever I'd look at somebody like your code. If you are an "app developer" maybe you should stay off the web platform and leave it to the people earning a real living in it. Those that car about having correct code. I am guessing as you claim to be an "app developer" than you probably target only IE as a platform too. Very sad.


Note this issue has been addressed and will be included in our next release (hopefully done by next week).

Open discussion and sharing different points of view are definitely some of the main purposes for the forums but please let's all make sure it's done in a respectful and professional way.


We are tracking this and will be making sure that our sample web site pages and in turn the toolkit controls are xhtml compliant.

http://www.codeplex.com/AtlasControlToolkit/WorkItem/View.aspx?WorkItemId=8156


Thanx sburke. Good to see those that are putting the controls together do care. I know there was a rush to get them out but I am glad you are taking the time to go back and get them spot on.

Thanx for that. I guess everybody keeps harping about XHTML and thats what I do target but even targeting HTML it was still an issue of having block elements inside of inline ones.

I am not sure if you have seen my other post in relation to the accordion pane. I am having issues with having content inside them that extend outside of the pane with overflow: hidden; causing my flyout menus to be cut off. Is this something that you think could be fixed at all?


Cool, this has been bugging me as well.

Those that don't care about standard's compliance immeidately identifythemselves as Visual Basic developers creating intranet apps againstInternet Explorer :)

I'm PARTIALLY kidding but seriouslyguys, standards compliance is important and makes the web as a wholebetter. The more technologies that adhere to this concept thebetter, and the better and easier coding for the web, buildingbrowsers, etc. will be.


FYI, this has been fixed in the Development branch and will be included with the next Toolkit release.


I completely agree with this strong push for standards compliance. I don't care if I'm developing an IE-only intranet application, I want it to be standards compliant. Ask all the IE6-only app developers how they felt once IE7 was released and they had to rewrite all their code that was suddenly revealed to be broken.

Wednesday, March 21, 2012

Is Atlas a Regular ASP.NET Page?

I created a website and selected the Atlas Website template. I don't know if I will use Atlas, but thought I might. Is it still a regular ASP.NET website? Or should I have selected ASP.NET website and added Atlas later. It might be out of beta before I use it. How hard it is to add Atlas later?

Thank you for any help.

When you use the atlas template, all your doing is setting up a solution with the atlas dll already included in your bin folder, all the proper declarations already setup in your web.config, and a script manager registered on your default.aspx page for you. Nothing says you have to use atlas, in fact, untill you add some atlas components, your not. It's for all intents and purposes a standard asp.net page.
Does anyone know when Atlas goes into production?

hello.

yes, this is true. however, if you're not using atlas, then you'd probably be better to use a normal web site (the altas dll + web.config entries introduce some handlers that will intercept some requests unnecessarily).

one more thing: there's already a go live licence for atlas so you can use it in production.

Is it possible to add a ScriptManager to a page dynamically?

As per the title, is it possible to add a script manager to a page from code?

I have it working OK if the UpdatePanel is also created in code (explicitly after the script manager is created) but not if the UpdatePanel is defined in the aspx template. In that case, if I put my code in "OnInit", the page raises an exception saying that "the Script manager needs to be added (to the page's control tree) before the UpdatePanel", whereas if I move the code to "OnPreInit" then the controls collection is not even created yet.

In other words, adding the Script Manager "OnPreInit" is too early but adding it "OnInit" is too late IF the UpdatePanel is defined in the aspx.

The reason I'm asking is that it would be nice to be able to write controls that could detect if the Page they are hosted in has a Script Manager (or proxy?) and if not, and if they need to use AJAX, then the control can add one, theus removing this dependancy and "knowledge of the implementation" from the client using the control.

Any ideas?

Many thanks

I use a simple workaround-- add a property that says UseAJAX (boolean), and in the XML documentation for the control I say that if the control is on a page with a ScriptManager, or in an UpdatePanel, to set this value to true.

Then the control takes this into account when instantiating and building the control structure, as well as when registering scripts.


OK thanks, that would be OK - obviously this is something you've already come across and worked around.

I did have some ideas on these lines myself, like having an IAjaxControl interface that had a method like "EnableAjax()" that would create & append the UpdatePanels to the control - one of the reasons being that the UpdatePanels, once created and added to the control tree CANNOT be moved so if the client wants to take the control and move it to another part of the tree then it will cause an exception. Having the method, rather than a property, gives the client some control as to WHEN to trigger the creation of the Ajax components (ideally after the control tree is "set in stone").

With hindsight, I think I like your idea of a simple boolean property (but defined in the IAjaxControl interface) and always create the UpdatePanels in the OnLoad (if the boolean is true) rather than beforehand - hopefully then the control tree is final and we are safe to do it, and the GUI designer can support the boolean property withought the need for coding from the client.

I felt the interface was needed for scenarios like where a different control CONTAINED your Ajax enabled control - it too would then need to support the property (and pass it down to your control it was containing).


Did you find a solution (Like you, I try the OnInit and the PreOnInit) ?

All my pages inherits the same class (let's say PageAncestry). I want to add the scriptmanager with code in PageAncestry so all my pages will automatically be able to use ajax.


After some google search, I finally found a solution on this page http://www.capdes.com/2007/02/microsoft_office_sharepoint_se.html

Add the ScriptManager in the PreInit at the HtmlForm first position :

Private Sub Page_PreInit(ByVal poSender As Object, ByVal poArguments As System.EventArgs) Handles Me.PreInit

' Get current ScriptManager if exist
Dim oScriptManagerAjax As ScriptManager = ScriptManager.GetCurrent(Me)
' If not exist
If oScriptManagerAjax Is Nothing Then
' Create one
oScriptManagerAjax = New ScriptManager
' Get page form
Dim oForm As HtmlForm = Me.Form
' If form present
If Not IsNothing(oForm) Then
' Add it at first position
oForm.Controls.AddAt(0, oScriptManagerAjax)
Else
' Manage if not (impossible to use Ajax)
End If
End If


End Sub


Hmm, from what I was saying:

"whereas if I move the code to "OnPreInit" then the controls collection is not even created yet."

and yet, in "PreInit" you have code:

oForm.Controls.AddAt(0, oScriptManagerAjax)

Are you sure thius works? According to my original post "oForm.Controls.Add" should have raised an exception as the "Controls" collection is not yet created. Are you sure your code works?

My page also uses a MasterPage - does yours? Does that make a difference (i wonder??)

I'll give it a try tomorrow. Thanks for the post :)


Yes it's working for me.

I don't have a master page, so I don't know if it's working with.

The most important thing is theControls.addat(0, it put the ScriptManager before all other controls define in the form (even the one in design). It's not working if you use only Controls.add


I'm pretty sure that "Controls.AddAt(0..." is what I was using before - as I said though, I believe the "Controls" collection was null at PreInit.

Anyway, I will try again and post my results :)


No mate, this just doesn't work, not in C# anyway.

The isssue is as before but I was mistaken, it's not the Control collection that is not created, it is the Form object itself.

Here is my ASPX Template:

<%@. Page Language="C#" AutoEventWireup="true" CodeFile="Page2.aspx.cs" Inherits="Page2" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" ><head runat="server"> <title>Untitled Page</title></head><body> <form id="form1" runat="server"> <div> Page 2<br /> <br /> <asp:UpdatePanel ID="UpdatePanel1" runat="server"> <ContentTemplate> <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label><br /> <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" /> </ContentTemplate> </asp:UpdatePanel> </div> </form></body></html>

And here is my code behind:

using System;using System.Data;using System.Configuration;using System.Collections;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Web.UI.HtmlControls;public partialclass Page2 : Page{protected override void OnPreInit(EventArgs e) {// Pop a script manager on the page if one does not yet exist. ScriptManager scriptManager = ScriptManager.GetCurrent(this);if (scriptManager ==null) { scriptManager =new ScriptManager(); HtmlForm form =this.Form;if (form !=null) form.Controls.AddAt(0, scriptManager); }base.OnPreInit(e); }protected void Button1_Click(object sender, EventArgs e) { Label1.Text = DateTime.Now.ToLongTimeString(); }}

As you see here, if "form" is null we can't add the script manager, and this.Form IS null at "PreInit":

if

(form !=null)
form.Controls.AddAt(0, scriptManager);

The only way I could get this to work is doing it in the "Onint" where the ScriptManager is created first and then the UpdatePanel created IN CODE afterwards (NOT defined in the aspx). Unfortunately, defining the Update Panel in the aspx means that "Oninit" is too late to add the script manager, but "PreInit" is too early as the form is not yet created.

Please tell me I'm wrong about this - how have you got this to work? I don't get it. Can you post your ASPX & VB code?



Not works!!!

Obviously the code is in the OnInit andnot in OnPreInit at http://www.capdes.com/2007/02/microsoft_office_sharepoint_se.htmlSmile

I think the msdn documentation not correct about the preinit event, this is an excerpt of my offline msdn library (seeit online):

PreInit

Use this event for the following:

Check theIsPostBack property to determine whether this is the first time the page is being processed.


Yes stmarti, although I think the documentation is (technically) correct in that you can CREATE controls at OnPreInit but you CANNOT add them to your Form, as it does not yet exist!

If you do this in OnPreInit:

Label label =newLabel();
label.Text ="Hello PreInit world";
this.Controls.Add(label);

and you'll see that the label ends up rendering AFTER ALL HTML MARKUP!!!! (ie was added to the control tree FIRST, then the Form was Added AT(0) with all real content then added to the form - leaving your poor Label "out in the cold".

So if the Form is not yet created at OnPreInit, I can't see how the VB code posted above could work.


Just tested this:

Private Sub Page_PreInit(ByVal poSender As Object, ByVal poArguments As System.EventArgs) Handles Me.PreInit

' Get current ScriptManager if exist
Dim oScriptManagerAjax As ScriptManager = ScriptManager.GetCurrent(Me)
' If not exist
If oScriptManagerAjax Is Nothing Then
' Create one
oScriptManagerAjax = New ScriptManager
' Get page form
Dim oForm As HtmlForm = Me.Form
' If form present
If Not IsNothing(oForm) Then
' Add it at first position
oForm.Controls.AddAt(0, oScriptManagerAjax)
Else
' Manage if not (impossible to use Ajax)
End If
End If

End Sub

And it works.... only when you havealreadya scriptmanager in the aspx. Obviously this code in real do nothing special because:

- if you have already a scriptmanager on the page the code does nothing, and your page is just fine...

- if you have not a scriptmanager in the aspx, the following code

' Add it at first position
oForm.Controls.AddAt(0, oScriptManagerAjax)

neverwill be executed because oForm is null in preinitSmile! Anyway your page will throw exception and cry for a scriptmanager...


VR2:

Yes stmarti, although I think the documentation is (technically) correct in that you can CREATE controls at OnPreInit but you CANNOT add them to your Form, as it does not yet exist!

You are right. Technically it's correct. The doc (at least this entry in msdn) suggest preinit for creating dynamic controls, and init for setting control properties. This is not true for the form's controls, would be nice a remark about it in the future.


I try your C# code and it's not working :(

But I found the difference with my vb code :) (I can't post it, it's included in a bigger class)

I use FindControl to search the Form !

Just change the OnPreInit in your code by this one and it's workingBig Smile
protected override void OnPreInit(EventArgs e) { ScriptManager scriptManager = ScriptManager.GetCurrent(this);if (scriptManager ==null) { scriptManager =new ScriptManager(); Control oControl =this.FindControl("Form1");if (oControl !=null) { oControl.Controls.AddAt(0, scriptManager); } }base.OnPreInit(e); }

It works!!! Like thisBig Smile:

protected override void OnPreInit( EventArgs e )
{
HtmlForm form1 = ( HtmlForm )this.FindControl( "Form1" );

ScriptManager temp = new ScriptManager( );
temp.EnablePageMethods = true;

form1.Controls.AddAt( 0, temp );

base.OnPreInit( e );
}

Great work gbarry! The problem solved and the answere for:

Is it possible to add a ScriptManager to a page dynamically?

is:yes! Yes