Thursday, March 29, 2012
please can someone explain the following code.
Thanks for the reply, but this is what I don't understand.... (by the way
there was a typo in my last message: "dpPageInit" should be "doPageInit").
I am new to inheritance, but I understand that if I create a classA that
inherits from classB then classA will expose properties/methods of classB.
The things I don't understand are code like:
a) override
b) +=
c) this.Init += new System.EventHandler
I am trying to create a page template (ie: a template page that contains a
header and footer), and then I want each of my pages to inherit the template
page so all I have to do is add the main body of the ASP page (the header
and footer will automatically be rendered by the template page).
I have downloaded the code from the following place
http://www.aspnetui.com/templates/ but I cant get it to work when I try it
myself. On top of that I think they have made the example more complex than
it needs to be.
All I want is a template that looks just like their red example. If someone
could post a simplified version of it it would be great.
"Christian" <pleasenononospamcmillotti@dotnet.itags.org.novasoftware.it> wrote in message
news:%23go0RMpVDHA.2316@dotnet.itags.org.TK2MSFTNGP09.phx.gbl...
> Hi Suzy
> It seems to me that you are in an inherited class, you are overriding
> virtual method OnInit in order to subscribe dbPageInit to be called in the
> Init Event, dbPageLoad to be called In the Load Event and calling OnInit
> method on base class ( that inherited from )...
> What else aren't you understanding?
> In case give details..
> Christian.
> "suzy" <me@dotnet.itags.org.nospam.com> ha scritto nel messaggio
> news:%23%23Wf4EpVDHA.532@dotnet.itags.org.TK2MSFTNGP09.phx.gbl...
> > please can someone explain the following code to a newbie... thanks
> > override protected void OnInit(EventArgs e)
> > {
> > this.Init += new System.EventHandler(dpPageInit);
> > this.Load += new System.EventHandler(doPageLoad);
> > base.OnInit(e);
> > }a) override:
If you have:
Class MyClass
{
...
protected virtual void MyMethod()
{
// Some instructions
...
}
}
MyMethod is the first implementation of the method.
You could have your ownn MyMethod in your class:
Class MySecondClass : Myclass
{
protected override void MyMethod()
{
// other instructions
...
}
}
You can override only virtual methods.
b) += :
add something to... for example:
c) this.Init += new System.EventHandler( doPageInit ):
add doPageInit method to delegate list called by Init event.
( Is Init an event ? )
When Init event is fired your class iterates through delegate: (
System.EventHandler is our delegate )
and call all methods subscribed
you subscribe your own method ( that must have the signature given by
delegate as return type, parameters, etc ) by writng
... += new System.EventHandler( doPageInit ):
Do you know what delegates are?
"suzy" <me@.nospam.com> ha scritto nel messaggio
news:eOF6lbpVDHA.2328@.TK2MSFTNGP12.phx.gbl...
> Hi Christian,
> Thanks for the reply, but this is what I don't understand.... (by the way
> there was a typo in my last message: "dpPageInit" should be "doPageInit").
> I am new to inheritance, but I understand that if I create a classA that
> inherits from classB then classA will expose properties/methods of classB.
> The things I don't understand are code like:
> a) override
> b) +=
> c) this.Init += new System.EventHandler
>
> I am trying to create a page template (ie: a template page that contains a
> header and footer), and then I want each of my pages to inherit the
template
> page so all I have to do is add the main body of the ASP page (the header
> and footer will automatically be rendered by the template page).
> I have downloaded the code from the following place
> http://www.aspnetui.com/templates/ but I cant get it to work when I try it
> myself. On top of that I think they have made the example more complex
than
> it needs to be.
> All I want is a template that looks just like their red example. If
someone
> could post a simplified version of it it would be great.
> > "suzy" <me@.nospam.com> ha scritto nel messaggio
> > news:%23%23Wf4EpVDHA.532@.TK2MSFTNGP09.phx.gbl...
> > > please can someone explain the following code to a newbie... thanks
> > > > override protected void OnInit(EventArgs e)
> > > {
> > > > this.Init += new System.EventHandler(dpPageInit);
> > > this.Load += new System.EventHandler(doPageLoad);
> > > base.OnInit(e);
> > > }
> >
> Thanks for your reply. No I don't know what delegates are. :-(
should take a look..
> Also, in your example of MyClass/MyMethod in which order will the code be
> run?
MyClass.MyMethod is 1 implementation
MySecondClass.MyMethod is another 1
they are not tied
public Class MyClass
{
...
protected virtual void MyMethod()
{
// Some instructions
MessageBox.Show( "1" );
}
protected virtual void AnotherMethod()
{
MessageBox.Show( "Hello" );
}
}
MyMethod is the first implementation of the method.
You could have your ownn MyMethod in your class:
public Class MySecondClass : Myclass
{
protected override void MyMethod()
{
// other instructions
MessageBox.Show( "2" );
...
}
protectd override AnotherMethod()
{
base.AnotherMethod();
MessageBox.Show( "Suzy" );
}
}
MyClass cl = new MyClass();
cl.MyMethod(); // displays 1
cl.AnotherMethod(); // displays Hello
MySecondClass cl2 = new MySecondClass();
cl2.MyMethod(); // displays 2
cl2.AnotherMethod(); // displays Hello and then Suzy
talking about delegates and events
this.Load += new System.EventHandler(doPageLoad);
this.Load += new System.EventHandler(doPageAnotherLoad);
this.Load += new System.EventHandler(doPageAnotherOneLoad);
On Load Fired will be executed
doPageLoad(), doPageAnotherLoad(), doPageAnotherOneLoad(), i think in order
of submission
> Someone said the following code would create a template if placed in a
page
> template class:
Sorry, i'm not the proper person for help you with asp... never worked :-(
Repost for detailed and specific helps.
> protected override void OnInit (EventArgs args)
> {
> this.Controls.AddAt(0, LoadControl("path to header.ascx " );
> base.OnInit(e);
> this.Controls.Add(LoadControl("path to footer.ascx"));
> }
> And the code in my page that inherited the above contained the
following...:
> override protected void OnInit(EventArgs e)
> {
> InitializeComponent();
> base.OnInit(e);
> }
> private void Page_Load(object sender, System.EventArgs e)
> {
> placeholder.Controls.Add (grdDataGrid);
> }
> They said this should place my placeholder/datagrid between a
header/footer.
Thanks, that explains a lot! Much appreciated!
I think I am right in saying that if I inherited a template class containing
the code below in it, then it won't place a header/footer around my ASP code
(of the page that inherits the template class).
protected override void OnInit (EventArgs args)
{
this.Controls.AddAt(0, LoadControl("path to header.ascx" );
base.OnInit(e);
this.Controls.Add(LoadControl("path to footer.ascx"));
}
"Tom" <TomRemoveThisClement@.sbcglobal.net> wrote in message
news:uMKACrzVDHA.2156@.TK2MSFTNGP11.phx.gbl...
> Hi Susy,
> A delegate (or an event) is an kind of pointer to functions. The
difference
> between an event and an ordinary pointer is that inside of the event is a
> list of pointers to functions. If you "call" the event it's called
raising
> the event and every function that has been added to the event is called in
> order.
> The way this is typicaly used in C# is if you have a class in which things
> can occur that might be of interest to others, you can declare a public
> event (like "event EventHandler Load;") Any other object that is
interested
> in (i.e wants to be notified of) this occurance (Load) registers this
> interest by adding a pointer to a function in the event. So when you see
> the code:
> this.Load += new System.EventHandler(doPageLoad);
> you are looking at an expression of interest in the Load event. When it
> occurs, the doPageLoad() function will be called (along with any other
> functions that have been registered with the Load event using the +=
syntax.
> The odd thing about this code is that it it registering with an event on
the
> same object as the current instance. There are better (or at least more
> natural) ways of accomplishing this. First, if (as is likely) the Load
> event is declared in a superclass (a class from which this current class
was
> derived - directly or indirectly) you would typically override a protected
> OnLoad() method to obtain the notification of Load. Second, if the event
is
> declared in the same object as the += code, you'd typically just call a
> function directly instead of raising an event and receiving notification
for
> it.
> Tom
> "suzy" <me@.nospam.com> wrote in message
> news:%23PoQfkrVDHA.3088@.tk2msftngp13.phx.gbl...
> > great, i am starting to understand more:
> > i thought it worked the way you say it worked, that's why i didn't
> > understand the theory behind he code that was submitted to me regarding
> the
> > page hearder/footer (shown below):
> > > protected override void OnInit (EventArgs args)
> > > {
> > > this.Controls.AddAt(0, LoadControl("path to header.ascx " );
> > > base.OnInit(e);
> > > this.Controls.Add(LoadControl("path to footer.ascx"));
> > > }
> > if the above code is in my base/template class (A), i can't see how i
can
> > write code in a class that inherits from it (B), so that my code from B
> gets
> > inserted between the header/footer.
> > i know you said you haven't done asp.net, but doesn't the theory of it
> sound
> > wrong to you?
> > "Christian" <pleasenononospamcmillotti@.novasoftware.it> wrote in message
> > news:uE5jGJrVDHA.532@.TK2MSFTNGP10.phx.gbl...
> > > > > Thanks for your reply. No I don't know what delegates are. :-(
> > > > should take a look..
> > > > > > Also, in your example of MyClass/MyMethod in which order will the
code
> > be
> > > > run?
> > > MyClass.MyMethod is 1 implementation
> > > MySecondClass.MyMethod is another 1
> > > they are not tied
> > > public Class MyClass
> > > {
> > > ...
> > > protected virtual void MyMethod()
> > > {
> > > // Some instructions
> > > MessageBox.Show( "1" );
> > > }
> > > protected virtual void AnotherMethod()
> > > {
> > > MessageBox.Show( "Hello" );
> > > }
> > > }
> > > MyMethod is the first implementation of the method.
> > > You could have your ownn MyMethod in your class:
> > > public Class MySecondClass : Myclass
> > > {
> > > protected override void MyMethod()
> > > {
> > > // other instructions
> > > MessageBox.Show( "2" );
> > > ...
> > > }
> > > protectd override AnotherMethod()
> > > {
> > > base.AnotherMethod();
> > > MessageBox.Show( "Suzy" );
> > > }
> > > }
> > > MyClass cl = new MyClass();
> > > cl.MyMethod(); // displays 1
> > > cl.AnotherMethod(); // displays Hello
> > > MySecondClass cl2 = new MySecondClass();
> > > cl2.MyMethod(); // displays 2
> > > cl2.AnotherMethod(); // displays Hello and then Suzy
> > > > talking about delegates and events
> > > > this.Load += new System.EventHandler(doPageLoad);
> > > this.Load += new System.EventHandler(doPageAnotherLoad);
> > > this.Load += new System.EventHandler(doPageAnotherOneLoad);
> > > > On Load Fired will be executed
> > > doPageLoad(), doPageAnotherLoad(), doPageAnotherOneLoad(), i think in
> > order
> > > of submission
> > > > > > > Someone said the following code would create a template if placed in
a
> > > page
> > > > template class:
> > > Sorry, i'm not the proper person for help you with asp... never worked
> :-(
> > > Repost for detailed and specific helps.
> > > > > protected override void OnInit (EventArgs args)
> > > > {
> > > > this.Controls.AddAt(0, LoadControl("path to header.ascx " );
> > > > base.OnInit(e);
> > > > this.Controls.Add(LoadControl("path to footer.ascx"));
> > > > }
> > > > > > And the code in my page that inherited the above contained the
> > > following...:
> > > > > > override protected void OnInit(EventArgs e)
> > > > > > {
> > > > > > InitializeComponent();
> > > > > > base.OnInit(e);
> > > > > > }
> > > > > > private void Page_Load(object sender, System.EventArgs e)
> > > > > > {
> > > > > > placeholder.Controls.Add (grdDataGrid);
> > > > > > }
> > > > > > They said this should place my placeholder/datagrid between a
> > > header/footer.
> > > >
Please explain ApplicationID of aspnetdb
Web site? For example, what and when generates application ID?
Any pointers to on-line docs would also be appreciated.
Thanks,
Dan<membership defaultProvider="AccessMembershipProvider">
<providers>
<add name="AccessMembershipProvider"
type="Samples.AccessProviders.AccessMembershipProvider,
AccessProvider"
connectionStringName="AccessFileName"
enablePasswordRetrieval="false"
enablePasswordReset="false" requiresUniqueEmail="false"
requiresQuestionAndAnswer="false"
minRequiredPasswordLength="1"
minRequiredNonalphanumericCharacters="0"
applicationName="SampleSite" hashAlgorithmType="SHA1"
passwordFormat="Hashed"/>
</providers>
</membership>
I believe the ApplicationId is just a primary key for a distinct
"applicationName" in the config file.
"SampleSite" from the above entry.
"Dan" <dan@.nospam.co> wrote in message
news:uDVXrRFiIHA.1168@.TK2MSFTNGP02.phx.gbl...
> Could someone please explain the relationship between ApplicationID and a
> Web site? For example, what and when generates application ID?
> Any pointers to on-line docs would also be appreciated.
> Thanks,
> Dan
>
ApplicationID is a unique id for a website (iis site path). the storedproc
adds a row if it doesn't exist during the lookup.
-- bruce (sqlwork.com)
"Dan" wrote:
> Could someone please explain the relationship between ApplicationID and a
> Web site? For example, what and when generates application ID?
> Any pointers to on-line docs would also be appreciated.
> Thanks,
> Dan
>
>
please explain "What is Singleton Design Pattern? What does volatile provide? "
Can any body please explain me "What is Singleton Design Pattern? What does volatile provide? " in C# 2.0
-Sanjeev
Hi,
take a look at this page:http://www.dofactory.com/Patterns/PatternSingleton.aspx.
Grz, Kris.
Many Thanks
But What does volatile provide?
Hi,
sanjeev_asp.net:
But What does volatile provide?
You can just look it up in the documentation:http://msdn2.microsoft.com/en-us/library/x13ttww7(VS.80).aspx.
Grz, Kris.
Please Explain
Hi All
Can anyone help me in understanding the highlighted text please.
For Each row As DataRow In ds.Tables(0).Rows
Dim arr() As Object = row.ItemArray()
For i As Integer = 0 To arr.Length - 1
If arr(i).ToString().IndexOf(",") > 0 Then ' I m unable to get this line of code.
record = record & Chr(34) & arr(i).ToString() & Chr(34) & ","
Else
record = record & arr(i).ToString() & ","
End If
Next
body = body & record.Substring(0, record.Length - 1) & vbCrLf
record = ""
Next
Thanks
Asif Ali.
take the object in Array arr at position indicated by i
convert to a string
find the index (position) of a comma character
see if the comma occurred after the first character position
Hi there
Fantastic explanation..
Thanks Again
Asif.
Please Explain Difference Between ASP.Net and ASP and Also with PHP
Hello dears if some one have time and know about following question then explain in detail of post some links,
Please Explain Difference Between ASP.Net and ASP and Also with PHP
Note: don't post wrong links or notes.
Best Regards.
Wikipedia: ASP
Wikipedia: PHP
Wikipedia: ASP.NET
You may also wish to visit the following webpage, which allows software engineers--such as yourself, apparently--to answer their own questions:Google.
Please explain Delegates
if you wnat a method of one object to be called by third object. you give to this third object delegate to the method of the first object.
Hi,
Delegates are like function pointers in C++. They are used to pass the functions as parameter to the other function. There are so many articles on this topic. please visit
http://www.csharpfriends.com/Articles/getArticle.aspx?articleID=141
Thanks,
Sridhar!!
Please explain me following lines
Hi All,
Please explain me following two lines:
if (combined.Length != 0)prefix += appendAnd ? " and " : " ";
In above line what is the use of '?' and ':'
Thanks and regards,
Swapnil.
That is aTernary Expression.
If means,
If the var appendAnd evaluates to True
then perform the operation (+=) with the data directly after the question mark
else
perform the oprtation with the data after the colon :
Please explain strange viewstate behavior...
The problem is the first time I add it with a given value and submit it then
change the value within the Page_Load event it still has the original value.
I am guessing this has something to do with viewstate. I have turned off
viewstate at the page level, but the issue still occurs. Any suggestions?
The code is basic:
HtmlInputHidden phihAction = new HtmlInputHidden();
phihAction.ID = "hdnAction";
phihAction.Value = ((short)pactAction).ToString();
mfrmUser.Controls.Add( phihAction );
pactAction is an enumeration that changes based on action (i.e. 1=Add, 2=Edi
t)
Any help in understanding why it does what it does and how to work around it
would be greatly appreciated.
RobertRobert,
You need to check IsPostBack property befory assigning the value:
HtmlInputHidden phihAction = new HtmlInputHidden();
phihAction.ID = "hdnAction";
if (IsPostBack)
phihAction.Value = ((short)pactAction).ToString();
mfrmUser.Controls.Add( phihAction );
Eliyahu
"rgrandidier" <rgrandidier@.discussions.microsoft.com> wrote in message
news:E0B96D78-C2B6-4A46-BE08-E7E7B7FD1893@.microsoft.com...
> I am dynamically adding an HtmlInputHidden element with different values.
> The problem is the first time I add it with a given value and submit it
then
> change the value within the Page_Load event it still has the original
value.
> I am guessing this has something to do with viewstate. I have turned off
> viewstate at the page level, but the issue still occurs. Any suggestions?
> The code is basic:
> HtmlInputHidden phihAction = new HtmlInputHidden();
> phihAction.ID = "hdnAction";
> phihAction.Value = ((short)pactAction).ToString();
> mfrmUser.Controls.Add( phihAction );
> pactAction is an enumeration that changes based on action (i.e. 1=Add,
2=Edit)
> Any help in understanding why it does what it does and how to work around
it
> would be greatly appreciated.
> --
> Robert
Please explain strange viewstate behavior...
The problem is the first time I add it with a given value and submit it then
change the value within the Page_Load event it still has the original value.
I am guessing this has something to do with viewstate. I have turned off
viewstate at the page level, but the issue still occurs. Any suggestions?
The code is basic:
HtmlInputHiddenphihAction = new HtmlInputHidden();
phihAction.ID = "hdnAction";
phihAction.Value = ((short)pactAction).ToString();
mfrmUser.Controls.Add( phihAction );
pactAction is an enumeration that changes based on action (i.e. 1=Add, 2=Edit)
Any help in understanding why it does what it does and how to work around it
would be greatly appreciated.
--
RobertRobert,
You need to check IsPostBack property befory assigning the value:
HtmlInputHidden phihAction = new HtmlInputHidden();
phihAction.ID = "hdnAction";
if (IsPostBack)
phihAction.Value = ((short)pactAction).ToString();
mfrmUser.Controls.Add( phihAction );
Eliyahu
"rgrandidier" <rgrandidier@.discussions.microsoft.com> wrote in message
news:E0B96D78-C2B6-4A46-BE08-E7E7B7FD1893@.microsoft.com...
> I am dynamically adding an HtmlInputHidden element with different values.
> The problem is the first time I add it with a given value and submit it
then
> change the value within the Page_Load event it still has the original
value.
> I am guessing this has something to do with viewstate. I have turned off
> viewstate at the page level, but the issue still occurs. Any suggestions?
> The code is basic:
> HtmlInputHidden phihAction = new HtmlInputHidden();
> phihAction.ID = "hdnAction";
> phihAction.Value = ((short)pactAction).ToString();
> mfrmUser.Controls.Add( phihAction );
> pactAction is an enumeration that changes based on action (i.e. 1=Add,
2=Edit)
> Any help in understanding why it does what it does and how to work around
it
> would be greatly appreciated.
> --
> Robert
Please explain why AddHandler works in Page_Load, but not Butt
that would look a bit like google. State 1, you see a textbox and button, yo
u
type a search value and press the button, State 2, a list of search results
is displayed (a table with a LinkButton in each row), you click on the
selected row's LinkButton. State 3, The details about the selected item are
displayed along with a button to go back to state 1.
The database search after state 1 and the insertion of the results and
LinkButtons in the table must take place in the Button's Click event, the
table duly appears with the data and LinkButtons. At the end of state 2, the
LinkButtons cause a post, but no event is fired, also the entire contents of
the table no longer exist - this does not matter as I only want to know the
ID of the button.
Is the idea of linking the dynamically created LinkButtons to an event the
wrong approach? Should I be looking at the request.form(0) value? Or is my
whole approach wrong, am I thinking too much along Windows Forms lines?
--
John Austin
"Cowboy (Gregory A. Beamer)" wrote:
> It has to do with the order of events in .NET. By the time you hit button
> events, you have already configured controls. Under "sender", you can find
> out which button was clicked and adjust appropriately in Page_Load. Be
> careful, however, with overloading Page_Load with too much, as you can end
> up with disaster.
> --
> Gregory A. Beamer
> MVP; MCP: +I, SE, SD, DBA
> http://gregorybeamer.spaces.live.com
> ****************************************
*********
> Think outside of the box!
> ****************************************
*********
> "John Austin" <John.Austin@dotnet.itags.org.nospam.nospam> wrote in message
> news:08B9C89B-CB28-41CE-899E-4AF85F704B84@dotnet.itags.org.microsoft.com...
>
>Hi John,
First, I recommend you to use [1] as your starting point to learn ASP.NET.
Though it's written for ASP.NET 1.x, it should get you started.
Since ASP.NET page is stateless, a page class instance and its controls
will need to be created at the server side every time the page is posted
back. See following steps to get an overview of the page life cycle:
1) POST Request is issued by client
2) Page-derived class is created, constructor is invoked
3) IHttpHandler.ProcessRequest is invoked (implemented by Page)
4) Page.Init()
5) Page.CreateChildControls()
6) Server-side control state is restored from POST variables and VIEWSTATE
7) Page.Load()
8) Page.Validate()
9) Server-side control events are fired
10) Page.PreRender()
11) Page.Render()
12) Page.RenderChildren()
13) HTTP Response is issued to client
14) Page.Unload()
15) Instance of Page-derived class is discarded
Each control will have a unique ID, this ID will be used to restore the
state from POST variables and VIEWSTATE (step 6) to the re-created controls
(step 5).
During load (step 7), if the current request is a postback, control
properties are loaded with information recovered from view state and
control state. (See [2] fore more information)
For your dynamically added controls to restore state correctly, you must
make sure the controls are added before the Load event. It's a best
practice to re-create them in Page.Load.
Regarding your issue, the LinkButtons are created in Button's Click event,
they are displayed in the result for the first time since Render is taken
place after that (step 11 and step 9). When the LinkButton is clicked and
caused a postback, the LinkButtons are not re-created, and the POST
variables related to them are lost. You could check the Request.Form for
the field that caused the postback, but there're better way to fulfil your
requirement.
Actually your requirement can be best handled by the Repeater [3] control
and DataBinding:
<asp:Button ID="Button1" runat="server" Text="Button"
OnClick="Button1_Click" />
<br />
<asp:Repeater ID="Repeater1" runat="server"
OnItemCommand="Repeater1_ItemCommand">
<HeaderTemplate>
<ul>
</HeaderTemplate>
<ItemTemplate>
<li>
<asp:LinkButton ID="link1" runat="server" CommandName="Link1"
CommandArgument='<%# Eval("Description") %>' Text='<%# Eval("Name") %>'
></asp:LinkButton>
</li>
</ItemTemplate>
<FooterTemplate>
</ul>
</FooterTemplate>
</asp:Repeater>
protected void Button1_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("Name");
dt.Columns.Add("Description");
dt.Rows.Add("First", "This is the first item");
dt.Rows.Add("Second", "This is the second item");
Repeater1.DataSource = dt;
Repeater1.DataBind();
}
protected void Repeater1_ItemCommand(object source,
RepeaterCommandEventArgs e)
{
if (e.CommandName == "Link1")
{
Response.Write(e.CommandArgument);
}
}
LinkButton's Click event will be bubbled up to the Repeater and fire
ItemCommand instead. Using the CommandName and CommandArgument, we can
differentiate which LinkButton is clicked.
I hope this could help you get familiar with how ASP.NET works and how to
handle such scenario using appropriate controls. Please feel free to let me
know whether or not you need further information. Thank you.
References:
[1] INFO: ASP.NET Roadmap
http://support.microsoft.com/kb/305140/
[2] ASP.NET Page Life Cycle Overview
http://msdn2.microsoft.com/en-us/library/ms178472.aspx
[3] Repeater Web Server Control Overview
http://msdn2.microsoft.com/en-us/library/x8f2zez5.aspx
Sincerely,
Walter Wang (wawang@.online.microsoft.com, remove 'online.')
Microsoft Online Community Support
========================================
==========
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscript...ault.aspx#notif
ications. If you are using Outlook Express, please make sure you clear the
check box "Tools/Options/Read: Get 300 headers at a time" to see your reply
promptly.
Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscript...t/default.aspx.
========================================
==========
This posting is provided "AS IS" with no warranties, and confers no rights.
Thank you Walter for your excellent reply. Whilst checking request.form(0) i
n
Page_Load was a work around (after they click, I don't want the table
anyway), the Repeater is a better solution for me as I can use the event
driven methodology that I am used to with Windows Forms applications.
Thanks once again,
--
John Austin
"Walter Wang [MSFT]" wrote:
> Hi John,
> First, I recommend you to use [1] as your starting point to learn ASP.NET.
> Though it's written for ASP.NET 1.x, it should get you started.
> Since ASP.NET page is stateless, a page class instance and its controls
> will need to be created at the server side every time the page is posted
> back. See following steps to get an overview of the page life cycle:
> 1) POST Request is issued by client
> 2) Page-derived class is created, constructor is invoked
> 3) IHttpHandler.ProcessRequest is invoked (implemented by Page)
> 4) Page.Init()
> 5) Page.CreateChildControls()
> 6) Server-side control state is restored from POST variables and VIEWSTATE
> 7) Page.Load()
> 8) Page.Validate()
> 9) Server-side control events are fired
> 10) Page.PreRender()
> 11) Page.Render()
> 12) Page.RenderChildren()
> 13) HTTP Response is issued to client
> 14) Page.Unload()
> 15) Instance of Page-derived class is discarded
> Each control will have a unique ID, this ID will be used to restore the
> state from POST variables and VIEWSTATE (step 6) to the re-created control
s
> (step 5).
> During load (step 7), if the current request is a postback, control
> properties are loaded with information recovered from view state and
> control state. (See [2] fore more information)
> For your dynamically added controls to restore state correctly, you must
> make sure the controls are added before the Load event. It's a best
> practice to re-create them in Page.Load.
> Regarding your issue, the LinkButtons are created in Button's Click event,
> they are displayed in the result for the first time since Render is taken
> place after that (step 11 and step 9). When the LinkButton is clicked and
> caused a postback, the LinkButtons are not re-created, and the POST
> variables related to them are lost. You could check the Request.Form for
> the field that caused the postback, but there're better way to fulfil your
> requirement.
> Actually your requirement can be best handled by the Repeater [3] control
> and DataBinding:
>
> <asp:Button ID="Button1" runat="server" Text="Button"
> OnClick="Button1_Click" />
> <br />
> <asp:Repeater ID="Repeater1" runat="server"
> OnItemCommand="Repeater1_ItemCommand">
> <HeaderTemplate>
> <ul>
> </HeaderTemplate>
> <ItemTemplate>
> <li>
> <asp:LinkButton ID="link1" runat="server" CommandName="Link1"
> CommandArgument='<%# Eval("Description") %>' Text='<%# Eval("Name") %>'
> </li>
> </ItemTemplate>
> <FooterTemplate>
> </ul>
> </FooterTemplate>
> </asp:Repeater>
>
> protected void Button1_Click(object sender, EventArgs e)
> {
> DataTable dt = new DataTable();
> dt.Columns.Add("Name");
> dt.Columns.Add("Description");
> dt.Rows.Add("First", "This is the first item");
> dt.Rows.Add("Second", "This is the second item");
> Repeater1.DataSource = dt;
> Repeater1.DataBind();
> }
> protected void Repeater1_ItemCommand(object source,
> RepeaterCommandEventArgs e)
> {
> if (e.CommandName == "Link1")
> {
> Response.Write(e.CommandArgument);
> }
> }
> LinkButton's Click event will be bubbled up to the Repeater and fire
> ItemCommand instead. Using the CommandName and CommandArgument, we can
> differentiate which LinkButton is clicked.
> I hope this could help you get familiar with how ASP.NET works and how to
> handle such scenario using appropriate controls. Please feel free to let m
e
> know whether or not you need further information. Thank you.
> References:
> [1] INFO: ASP.NET Roadmap
> http://support.microsoft.com/kb/305140/
> [2] ASP.NET Page Life Cycle Overview
> http://msdn2.microsoft.com/en-us/library/ms178472.aspx
> [3] Repeater Web Server Control Overview
> http://msdn2.microsoft.com/en-us/library/x8f2zez5.aspx
> Sincerely,
> Walter Wang (wawang@.online.microsoft.com, remove 'online.')
> Microsoft Online Community Support
> ========================================
==========
> Get notification to my posts through email? Please refer to
> [url]http://msdn.microsoft.com/subscriptions/managednewsgroups/default.aspx#notif[/ur
l]
> ications. If you are using Outlook Express, please make sure you clear the
> check box "Tools/Options/Read: Get 300 headers at a time" to see your repl
y
> promptly.
> Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
> where an initial response from the community or a Microsoft Support
> Engineer within 1 business day is acceptable. Please note that each follow
> up response may take approximately 2 business days as the support
> professional working with you may need further investigation to reach the
> most efficient resolution. The offering is not appropriate for situations
> that require urgent, real-time or phone-based interactions or complex
> project analysis and dump analysis issues. Issues of this nature are best
> handled working with a dedicated Microsoft Support Engineer by contacting
> Microsoft Customer Support Services (CSS) at
> http://msdn.microsoft.com/subscript...t/default.aspx.
> ========================================
==========
> This posting is provided "AS IS" with no warranties, and confers no rights
.
>
Hello Walter,
The Data Repeater works fine, but thinking further about the issue, it would
make sense for state 1 to build a query string from input criteria and store
the select statement in viewstate so that the Page_Load in state 2 can query
the database and generate results (this means that pressing Back in the
browser from state 3 would re-query the database and include any changes).
This would also avoid my original problem; but when in state 1, the button
press would need to build the query string, change the state to 2 and then
force a reload of the current page. How could I force the page to be re-buil
d
from the Button_Click event?
John Austin
"Walter Wang [MSFT]" wrote:
> Hi John,
> First, I recommend you to use [1] as your starting point to learn ASP.NET.
> Though it's written for ASP.NET 1.x, it should get you started.
> Since ASP.NET page is stateless, a page class instance and its controls
> will need to be created at the server side every time the page is posted
> back. See following steps to get an overview of the page life cycle:
> 1) POST Request is issued by client
> 2) Page-derived class is created, constructor is invoked
> 3) IHttpHandler.ProcessRequest is invoked (implemented by Page)
> 4) Page.Init()
> 5) Page.CreateChildControls()
> 6) Server-side control state is restored from POST variables and VIEWSTATE
> 7) Page.Load()
> 8) Page.Validate()
> 9) Server-side control events are fired
> 10) Page.PreRender()
> 11) Page.Render()
> 12) Page.RenderChildren()
> 13) HTTP Response is issued to client
> 14) Page.Unload()
> 15) Instance of Page-derived class is discarded
> Each control will have a unique ID, this ID will be used to restore the
> state from POST variables and VIEWSTATE (step 6) to the re-created control
s
> (step 5).
> During load (step 7), if the current request is a postback, control
> properties are loaded with information recovered from view state and
> control state. (See [2] fore more information)
> For your dynamically added controls to restore state correctly, you must
> make sure the controls are added before the Load event. It's a best
> practice to re-create them in Page.Load.
> Regarding your issue, the LinkButtons are created in Button's Click event,
> they are displayed in the result for the first time since Render is taken
> place after that (step 11 and step 9). When the LinkButton is clicked and
> caused a postback, the LinkButtons are not re-created, and the POST
> variables related to them are lost. You could check the Request.Form for
> the field that caused the postback, but there're better way to fulfil your
> requirement.
> Actually your requirement can be best handled by the Repeater [3] control
> and DataBinding:
>
> <asp:Button ID="Button1" runat="server" Text="Button"
> OnClick="Button1_Click" />
> <br />
> <asp:Repeater ID="Repeater1" runat="server"
> OnItemCommand="Repeater1_ItemCommand">
> <HeaderTemplate>
> <ul>
> </HeaderTemplate>
> <ItemTemplate>
> <li>
> <asp:LinkButton ID="link1" runat="server" CommandName="Link1"
> CommandArgument='<%# Eval("Description") %>' Text='<%# Eval("Name") %>'
> </li>
> </ItemTemplate>
> <FooterTemplate>
> </ul>
> </FooterTemplate>
> </asp:Repeater>
>
> protected void Button1_Click(object sender, EventArgs e)
> {
> DataTable dt = new DataTable();
> dt.Columns.Add("Name");
> dt.Columns.Add("Description");
> dt.Rows.Add("First", "This is the first item");
> dt.Rows.Add("Second", "This is the second item");
> Repeater1.DataSource = dt;
> Repeater1.DataBind();
> }
> protected void Repeater1_ItemCommand(object source,
> RepeaterCommandEventArgs e)
> {
> if (e.CommandName == "Link1")
> {
> Response.Write(e.CommandArgument);
> }
> }
> LinkButton's Click event will be bubbled up to the Repeater and fire
> ItemCommand instead. Using the CommandName and CommandArgument, we can
> differentiate which LinkButton is clicked.
> I hope this could help you get familiar with how ASP.NET works and how to
> handle such scenario using appropriate controls. Please feel free to let m
e
> know whether or not you need further information. Thank you.
> References:
> [1] INFO: ASP.NET Roadmap
> http://support.microsoft.com/kb/305140/
> [2] ASP.NET Page Life Cycle Overview
> http://msdn2.microsoft.com/en-us/library/ms178472.aspx
> [3] Repeater Web Server Control Overview
> http://msdn2.microsoft.com/en-us/library/x8f2zez5.aspx
> Sincerely,
> Walter Wang (wawang@.online.microsoft.com, remove 'online.')
> Microsoft Online Community Support
> ========================================
==========
> Get notification to my posts through email? Please refer to
> [url]http://msdn.microsoft.com/subscriptions/managednewsgroups/default.aspx#notif[/ur
l]
> ications. If you are using Outlook Express, please make sure you clear the
> check box "Tools/Options/Read: Get 300 headers at a time" to see your repl
y
> promptly.
> Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
> where an initial response from the community or a Microsoft Support
> Engineer within 1 business day is acceptable. Please note that each follow
> up response may take approximately 2 business days as the support
> professional working with you may need further investigation to reach the
> most efficient resolution. The offering is not appropriate for situations
> that require urgent, real-time or phone-based interactions or complex
> project analysis and dump analysis issues. Issues of this nature are best
> handled working with a dedicated Microsoft Support Engineer by contacting
> Microsoft Customer Support Services (CSS) at
> http://msdn.microsoft.com/subscript...t/default.aspx.
> ========================================
==========
> This posting is provided "AS IS" with no warranties, and confers no rights
.
>
Hi John,
See if following code answers your question:
protected void Page_Load(object sender, EventArgs e)
{
RebindData();
}
protected void Button1_Click(object sender, EventArgs e)
{
QueryStatement = "foo sql statement";
RebindData();
}
void RebindData()
{
string sql = QueryStatement;
if (string.IsNullOrEmpty(sql))
{
Repeater1.DataSource = null;
}
else
{
// you need to do sql query in real app; here I'm just
returning a DataTable for test purpose
DataTable dt = new DataTable();
dt.Columns.Add("Name");
dt.Columns.Add("Description");
dt.Rows.Add("First", "This is the first item");
dt.Rows.Add("Second", "This is the second item");
Repeater1.DataSource = dt;
}
Repeater1.DataBind();
}
string QueryStatement
{
get { reutrn ViewState["QueryStatement"] as string; }
set { ViewState["QueryStatement"] = value; }
}
protected void Repeater1_ItemCommand(object source,
RepeaterCommandEventArgs e)
{
if (e.CommandName == "Link1")
{
Response.Write(e.CommandArgument);
}
}
Regards,
Walter Wang (wawang@.online.microsoft.com, remove 'online.')
Microsoft Online Community Support
========================================
==========
When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.
========================================
==========
This posting is provided "AS IS" with no warranties, and confers no rights.
Sorry Walter, putting the creation of the results table in a subroutine is a
far simpler solution - I guess that getting my head round the way web app
work clouded the brain!
Many thanks,
John Austin
"Walter Wang [MSFT]" wrote:
> Hi John,
> See if following code answers your question:
> protected void Page_Load(object sender, EventArgs e)
> {
> RebindData();
> }
> protected void Button1_Click(object sender, EventArgs e)
> {
> QueryStatement = "foo sql statement";
> RebindData();
> }
> void RebindData()
> {
> string sql = QueryStatement;
> if (string.IsNullOrEmpty(sql))
> {
> Repeater1.DataSource = null;
> }
> else
> {
> // you need to do sql query in real app; here I'm just
> returning a DataTable for test purpose
> DataTable dt = new DataTable();
> dt.Columns.Add("Name");
> dt.Columns.Add("Description");
> dt.Rows.Add("First", "This is the first item");
> dt.Rows.Add("Second", "This is the second item");
> Repeater1.DataSource = dt;
> }
> Repeater1.DataBind();
> }
> string QueryStatement
> {
> get { reutrn ViewState["QueryStatement"] as string; }
> set { ViewState["QueryStatement"] = value; }
> }
> protected void Repeater1_ItemCommand(object source,
> RepeaterCommandEventArgs e)
> {
> if (e.CommandName == "Link1")
> {
> Response.Write(e.CommandArgument);
> }
> }
> Regards,
> Walter Wang (wawang@.online.microsoft.com, remove 'online.')
> Microsoft Online Community Support
> ========================================
==========
> When responding to posts, please "Reply to Group" via your newsreader so
> that others may learn and benefit from your issue.
> ========================================
==========
> This posting is provided "AS IS" with no warranties, and confers no rights
.
>
Please explain what "Empty path has no directory" means with Server.MapPath
I have the following line of code in a script...
litMsg.Text = Server.MapPath("/");
where litMsg is an ASP.Net Literal control. When I try and run this
page, I get the error ...
System.ArgumentException: Empty path has no directory.
Anyone any idea what this means? I have used Server.MapPath many times
before without error, I'm not sure why it suddenly stopped working here.
I'm sure I'm missing something blindingly obvious and would be grateful
if anyone could point it out!! TIA.
--
Alan Silver
(anything added below this line is nothing to do with me)IN case it's of any use to anyone, I found out that the problem was
caused by me having the following two lines in Page_Load...
HttpContext myContext = HttpContext.Current;
myContext.RewritePath("/");
I'm not actually sure *why* I had those lines there, they must have been
from something I was doing before. As soon as I removed them, the
Server.MapPath worked fine.
If anyone has an explanation, I would like to hear it ;-)
>Hello,
>I have the following line of code in a script...
>litMsg.Text = Server.MapPath("/");
>where litMsg is an ASP.Net Literal control. When I try and run this
>page, I get the error ...
>System.ArgumentException: Empty path has no directory.
>Anyone any idea what this means? I have used Server.MapPath many times
>before without error, I'm not sure why it suddenly stopped working here.
>I'm sure I'm missing something blindingly obvious and would be grateful
>if anyone could point it out!! TIA.
--
Alan Silver
(anything added below this line is nothing to do with me)
Please explain why AddHandler works in Page_Load, but not Button_C
click event, it will work in Page_Load, but not in a Button_Click.
The idea is that the user types some data, presses the button, gets a list
of results (each with a LinkButton) and can then press one of the link
buttons to get further information. The newly added link buttons appear, but
the click event added with AddHandler does not fire.
A control added in Page_Load with an event handler added with AddHandler
works fine.
I have not writted a web app previously and I guess that I do not understand
how dynamically added handlers work (or dont work).
--
John AustinIt has to do with the order of events in .NET. By the time you hit button
events, you have already configured controls. Under "sender", you can find
out which button was clicked and adjust appropriately in Page_Load. Be
careful, however, with overloading Page_Load with too much, as you can end
up with disaster.
--
Gregory A. Beamer
MVP; MCP: +I, SE, SD, DBA
http://gregorybeamer.spaces.live.com
*************************************************
Think outside of the box!
*************************************************
"John Austin" <John.Austin@.nospam.nospamwrote in message
news:08B9C89B-CB28-41CE-899E-4AF85F704B84@.microsoft.com...
Quote:
Originally Posted by
>I need to understand why if I add a control and use AddHandler to connect
>its
click event, it will work in Page_Load, but not in a Button_Click.
>
The idea is that the user types some data, presses the button, gets a list
of results (each with a LinkButton) and can then press one of the link
buttons to get further information. The newly added link buttons appear,
but
the click event added with AddHandler does not fire.
>
A control added in Page_Load with an event handler added with AddHandler
works fine.
>
I have not writted a web app previously and I guess that I do not
understand
how dynamically added handlers work (or dont work).
>
--
John Austin
the key to understanding asp.net is to know that its stateless, and a form
instance is only used for one request. so if you add a link in a button
click, and the user clicks on that link, a new form is built to process that
request. your code must know to add the handler when that happens. usually
you'd store a flag in viewstate or session to known when to add the handler
(you must also re-add the link control).
-- bruce (sqlwork.com)
"John Austin" <John.Austin@.nospam.nospamwrote in message
news:08B9C89B-CB28-41CE-899E-4AF85F704B84@.microsoft.com...
Quote:
Originally Posted by
>I need to understand why if I add a control and use AddHandler to connect
>its
click event, it will work in Page_Load, but not in a Button_Click.
>
The idea is that the user types some data, presses the button, gets a list
of results (each with a LinkButton) and can then press one of the link
buttons to get further information. The newly added link buttons appear,
but
the click event added with AddHandler does not fire.
>
A control added in Page_Load with an event handler added with AddHandler
works fine.
>
I have not writted a web app previously and I guess that I do not
understand
how dynamically added handlers work (or dont work).
>
--
John Austin
Sorry, but I still don't get it. What I have in mind is a form with 3 states
that would look a bit like google. State 1, you see a textbox and button, you
type a search value and press the button, State 2, a list of search results
is displayed (a table with a LinkButton in each row), you click on the
selected row's LinkButton. State 3, The details about the selected item are
displayed along with a button to go back to state 1.
The database search after state 1 and the insertion of the results and
LinkButtons in the table must take place in the Button's Click event, the
table duly appears with the data and LinkButtons. At the end of state 2, the
LinkButtons cause a post, but no event is fired, also the entire contents of
the table no longer exist - this does not matter as I only want to know the
ID of the button.
Is the idea of linking the dynamically created LinkButtons to an event the
wrong approach? Should I be looking at the request.form(0) value? Or is my
whole approach wrong, am I thinking too much along Windows Forms lines?
--
John Austin
"Cowboy (Gregory A. Beamer)" wrote:
Quote:
Originally Posted by
It has to do with the order of events in .NET. By the time you hit button
events, you have already configured controls. Under "sender", you can find
out which button was clicked and adjust appropriately in Page_Load. Be
careful, however, with overloading Page_Load with too much, as you can end
up with disaster.
>
--
Gregory A. Beamer
MVP; MCP: +I, SE, SD, DBA
http://gregorybeamer.spaces.live.com
>
*************************************************
Think outside of the box!
*************************************************
"John Austin" <John.Austin@.nospam.nospamwrote in message
news:08B9C89B-CB28-41CE-899E-4AF85F704B84@.microsoft.com...
Quote:
Originally Posted by
I need to understand why if I add a control and use AddHandler to connect
its
click event, it will work in Page_Load, but not in a Button_Click.
The idea is that the user types some data, presses the button, gets a list
of results (each with a LinkButton) and can then press one of the link
buttons to get further information. The newly added link buttons appear,
but
the click event added with AddHandler does not fire.
A control added in Page_Load with an event handler added with AddHandler
works fine.
I have not writted a web app previously and I guess that I do not
understand
how dynamically added handlers work (or dont work).
--
John Austin
>
>
>
Hi John,
First, I recommend you to use [1] as your starting point to learn ASP.NET.
Though it's written for ASP.NET 1.x, it should get you started.
Since ASP.NET page is stateless, a page class instance and its controls
will need to be created at the server side every time the page is posted
back. See following steps to get an overview of the page life cycle:
1) POST Request is issued by client
2) Page-derived class is created, constructor is invoked
3) IHttpHandler.ProcessRequest is invoked (implemented by Page)
4) Page.Init()
5) Page.CreateChildControls()
6) Server-side control state is restored from POST variables and VIEWSTATE
7) Page.Load()
8) Page.Validate()
9) Server-side control events are fired
10) Page.PreRender()
11) Page.Render()
12) Page.RenderChildren()
13) HTTP Response is issued to client
14) Page.Unload()
15) Instance of Page-derived class is discarded
Each control will have a unique ID, this ID will be used to restore the
state from POST variables and VIEWSTATE (step 6) to the re-created controls
(step 5).
During load (step 7), if the current request is a postback, control
properties are loaded with information recovered from view state and
control state. (See [2] fore more information)
For your dynamically added controls to restore state correctly, you must
make sure the controls are added before the Load event. It's a best
practice to re-create them in Page.Load.
Regarding your issue, the LinkButtons are created in Button's Click event,
they are displayed in the result for the first time since Render is taken
place after that (step 11 and step 9). When the LinkButton is clicked and
caused a postback, the LinkButtons are not re-created, and the POST
variables related to them are lost. You could check the Request.Form for
the field that caused the postback, but there're better way to fulfil your
requirement.
Actually your requirement can be best handled by the Repeater [3] control
and DataBinding:
<asp:Button ID="Button1" runat="server" Text="Button"
OnClick="Button1_Click" />
<br />
<asp:Repeater ID="Repeater1" runat="server"
OnItemCommand="Repeater1_ItemCommand">
<HeaderTemplate>
<ul>
</HeaderTemplate>
<ItemTemplate>
<li>
<asp:LinkButton ID="link1" runat="server" CommandName="Link1"
CommandArgument='<%# Eval("Description") %>' Text='<%# Eval("Name") %>'
Quote:
Originally Posted by
></asp:LinkButton>
</li>
</ItemTemplate>
<FooterTemplate>
</ul>
</FooterTemplate>
</asp:Repeater>
protected void Button1_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("Name");
dt.Columns.Add("Description");
dt.Rows.Add("First", "This is the first item");
dt.Rows.Add("Second", "This is the second item");
Repeater1.DataSource = dt;
Repeater1.DataBind();
}
protected void Repeater1_ItemCommand(object source,
RepeaterCommandEventArgs e)
{
if (e.CommandName == "Link1")
{
Response.Write(e.CommandArgument);
}
}
LinkButton's Click event will be bubbled up to the Repeater and fire
ItemCommand instead. Using the CommandName and CommandArgument, we can
differentiate which LinkButton is clicked.
I hope this could help you get familiar with how ASP.NET works and how to
handle such scenario using appropriate controls. Please feel free to let me
know whether or not you need further information. Thank you.
References:
[1] INFO: ASP.NET Roadmap
http://support.microsoft.com/kb/305140/
[2] ASP.NET Page Life Cycle Overview
http://msdn2.microsoft.com/en-us/library/ms178472.aspx
[3] Repeater Web Server Control Overview
http://msdn2.microsoft.com/en-us/library/x8f2zez5.aspx
Sincerely,
Walter Wang (wawang@.online.microsoft.com, remove 'online.')
Microsoft Online Community Support
==================================================
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscript...ault.aspx#notif
ications. If you are using Outlook Express, please make sure you clear the
check box "Tools/Options/Read: Get 300 headers at a time" to see your reply
promptly.
Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscript...rt/default.aspx.
==================================================
This posting is provided "AS IS" with no warranties, and confers no rights.
Thank you Walter for your excellent reply. Whilst checking request.form(0) in
Page_Load was a work around (after they click, I don't want the table
anyway), the Repeater is a better solution for me as I can use the event
driven methodology that I am used to with Windows Forms applications.
Thanks once again,
--
John Austin
"Walter Wang [MSFT]" wrote:
Quote:
Originally Posted by
Hi John,
>
First, I recommend you to use [1] as your starting point to learn ASP.NET.
Though it's written for ASP.NET 1.x, it should get you started.
>
Since ASP.NET page is stateless, a page class instance and its controls
will need to be created at the server side every time the page is posted
back. See following steps to get an overview of the page life cycle:
>
1) POST Request is issued by client
2) Page-derived class is created, constructor is invoked
3) IHttpHandler.ProcessRequest is invoked (implemented by Page)
4) Page.Init()
5) Page.CreateChildControls()
6) Server-side control state is restored from POST variables and VIEWSTATE
7) Page.Load()
8) Page.Validate()
9) Server-side control events are fired
10) Page.PreRender()
11) Page.Render()
12) Page.RenderChildren()
13) HTTP Response is issued to client
14) Page.Unload()
15) Instance of Page-derived class is discarded
>
Each control will have a unique ID, this ID will be used to restore the
state from POST variables and VIEWSTATE (step 6) to the re-created controls
(step 5).
>
During load (step 7), if the current request is a postback, control
properties are loaded with information recovered from view state and
control state. (See [2] fore more information)
>
For your dynamically added controls to restore state correctly, you must
make sure the controls are added before the Load event. It's a best
practice to re-create them in Page.Load.
>
Regarding your issue, the LinkButtons are created in Button's Click event,
they are displayed in the result for the first time since Render is taken
place after that (step 11 and step 9). When the LinkButton is clicked and
caused a postback, the LinkButtons are not re-created, and the POST
variables related to them are lost. You could check the Request.Form for
the field that caused the postback, but there're better way to fulfil your
requirement.
>
Actually your requirement can be best handled by the Repeater [3] control
and DataBinding:
>
>
<asp:Button ID="Button1" runat="server" Text="Button"
OnClick="Button1_Click" />
<br />
<asp:Repeater ID="Repeater1" runat="server"
OnItemCommand="Repeater1_ItemCommand">
<HeaderTemplate>
<ul>
</HeaderTemplate>
<ItemTemplate>
<li>
<asp:LinkButton ID="link1" runat="server" CommandName="Link1"
CommandArgument='<%# Eval("Description") %>' Text='<%# Eval("Name") %>'
Quote:
Originally Posted by
</asp:LinkButton>
</li>
</ItemTemplate>
<FooterTemplate>
</ul>
</FooterTemplate>
</asp:Repeater>
>
>
protected void Button1_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("Name");
dt.Columns.Add("Description");
dt.Rows.Add("First", "This is the first item");
dt.Rows.Add("Second", "This is the second item");
Repeater1.DataSource = dt;
Repeater1.DataBind();
}
protected void Repeater1_ItemCommand(object source,
RepeaterCommandEventArgs e)
{
if (e.CommandName == "Link1")
{
Response.Write(e.CommandArgument);
}
}
>
LinkButton's Click event will be bubbled up to the Repeater and fire
ItemCommand instead. Using the CommandName and CommandArgument, we can
differentiate which LinkButton is clicked.
>
I hope this could help you get familiar with how ASP.NET works and how to
handle such scenario using appropriate controls. Please feel free to let me
know whether or not you need further information. Thank you.
>
References:
>
[1] INFO: ASP.NET Roadmap
http://support.microsoft.com/kb/305140/
>
[2] ASP.NET Page Life Cycle Overview
http://msdn2.microsoft.com/en-us/library/ms178472.aspx
>
[3] Repeater Web Server Control Overview
http://msdn2.microsoft.com/en-us/library/x8f2zez5.aspx
>
Sincerely,
Walter Wang (wawang@.online.microsoft.com, remove 'online.')
Microsoft Online Community Support
>
==================================================
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscript...ault.aspx#notif
ications. If you are using Outlook Express, please make sure you clear the
check box "Tools/Options/Read: Get 300 headers at a time" to see your reply
promptly.
>
Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscript...rt/default.aspx.
==================================================
>
This posting is provided "AS IS" with no warranties, and confers no rights.
>
>
Hello Walter,
The Data Repeater works fine, but thinking further about the issue, it would
make sense for state 1 to build a query string from input criteria and store
the select statement in viewstate so that the Page_Load in state 2 can query
the database and generate results (this means that pressing Back in the
browser from state 3 would re-query the database and include any changes).
This would also avoid my original problem; but when in state 1, the button
press would need to build the query string, change the state to 2 and then
force a reload of the current page. How could I force the page to be re-build
from the Button_Click event?
--
John Austin
"Walter Wang [MSFT]" wrote:
Quote:
Originally Posted by
Hi John,
>
First, I recommend you to use [1] as your starting point to learn ASP.NET.
Though it's written for ASP.NET 1.x, it should get you started.
>
Since ASP.NET page is stateless, a page class instance and its controls
will need to be created at the server side every time the page is posted
back. See following steps to get an overview of the page life cycle:
>
1) POST Request is issued by client
2) Page-derived class is created, constructor is invoked
3) IHttpHandler.ProcessRequest is invoked (implemented by Page)
4) Page.Init()
5) Page.CreateChildControls()
6) Server-side control state is restored from POST variables and VIEWSTATE
7) Page.Load()
8) Page.Validate()
9) Server-side control events are fired
10) Page.PreRender()
11) Page.Render()
12) Page.RenderChildren()
13) HTTP Response is issued to client
14) Page.Unload()
15) Instance of Page-derived class is discarded
>
Each control will have a unique ID, this ID will be used to restore the
state from POST variables and VIEWSTATE (step 6) to the re-created controls
(step 5).
>
During load (step 7), if the current request is a postback, control
properties are loaded with information recovered from view state and
control state. (See [2] fore more information)
>
For your dynamically added controls to restore state correctly, you must
make sure the controls are added before the Load event. It's a best
practice to re-create them in Page.Load.
>
Regarding your issue, the LinkButtons are created in Button's Click event,
they are displayed in the result for the first time since Render is taken
place after that (step 11 and step 9). When the LinkButton is clicked and
caused a postback, the LinkButtons are not re-created, and the POST
variables related to them are lost. You could check the Request.Form for
the field that caused the postback, but there're better way to fulfil your
requirement.
>
Actually your requirement can be best handled by the Repeater [3] control
and DataBinding:
>
>
<asp:Button ID="Button1" runat="server" Text="Button"
OnClick="Button1_Click" />
<br />
<asp:Repeater ID="Repeater1" runat="server"
OnItemCommand="Repeater1_ItemCommand">
<HeaderTemplate>
<ul>
</HeaderTemplate>
<ItemTemplate>
<li>
<asp:LinkButton ID="link1" runat="server" CommandName="Link1"
CommandArgument='<%# Eval("Description") %>' Text='<%# Eval("Name") %>'
Quote:
Originally Posted by
</asp:LinkButton>
</li>
</ItemTemplate>
<FooterTemplate>
</ul>
</FooterTemplate>
</asp:Repeater>
>
>
protected void Button1_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("Name");
dt.Columns.Add("Description");
dt.Rows.Add("First", "This is the first item");
dt.Rows.Add("Second", "This is the second item");
Repeater1.DataSource = dt;
Repeater1.DataBind();
}
protected void Repeater1_ItemCommand(object source,
RepeaterCommandEventArgs e)
{
if (e.CommandName == "Link1")
{
Response.Write(e.CommandArgument);
}
}
>
LinkButton's Click event will be bubbled up to the Repeater and fire
ItemCommand instead. Using the CommandName and CommandArgument, we can
differentiate which LinkButton is clicked.
>
I hope this could help you get familiar with how ASP.NET works and how to
handle such scenario using appropriate controls. Please feel free to let me
know whether or not you need further information. Thank you.
>
References:
>
[1] INFO: ASP.NET Roadmap
http://support.microsoft.com/kb/305140/
>
[2] ASP.NET Page Life Cycle Overview
http://msdn2.microsoft.com/en-us/library/ms178472.aspx
>
[3] Repeater Web Server Control Overview
http://msdn2.microsoft.com/en-us/library/x8f2zez5.aspx
>
Sincerely,
Walter Wang (wawang@.online.microsoft.com, remove 'online.')
Microsoft Online Community Support
>
==================================================
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscript...ault.aspx#notif
ications. If you are using Outlook Express, please make sure you clear the
check box "Tools/Options/Read: Get 300 headers at a time" to see your reply
promptly.
>
Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscript...rt/default.aspx.
==================================================
>
This posting is provided "AS IS" with no warranties, and confers no rights.
>
>
Hi John,
See if following code answers your question:
protected void Page_Load(object sender, EventArgs e)
{
RebindData();
}
protected void Button1_Click(object sender, EventArgs e)
{
QueryStatement = "foo sql statement";
RebindData();
}
void RebindData()
{
string sql = QueryStatement;
if (string.IsNullOrEmpty(sql))
{
Repeater1.DataSource = null;
}
else
{
// you need to do sql query in real app; here I'm just
returning a DataTable for test purpose
DataTable dt = new DataTable();
dt.Columns.Add("Name");
dt.Columns.Add("Description");
dt.Rows.Add("First", "This is the first item");
dt.Rows.Add("Second", "This is the second item");
Repeater1.DataSource = dt;
}
Repeater1.DataBind();
}
string QueryStatement
{
get { reutrn ViewState["QueryStatement"] as string; }
set { ViewState["QueryStatement"] = value; }
}
protected void Repeater1_ItemCommand(object source,
RepeaterCommandEventArgs e)
{
if (e.CommandName == "Link1")
{
Response.Write(e.CommandArgument);
}
}
Regards,
Walter Wang (wawang@.online.microsoft.com, remove 'online.')
Microsoft Online Community Support
==================================================
When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.
==================================================
This posting is provided "AS IS" with no warranties, and confers no rights.
Sorry Walter, putting the creation of the results table in a subroutine is a
far simpler solution - I guess that getting my head round the way web app
work clouded the brain!
Many thanks,
--
John Austin
"Walter Wang [MSFT]" wrote:
Quote:
Originally Posted by
Hi John,
>
See if following code answers your question:
>
protected void Page_Load(object sender, EventArgs e)
{
RebindData();
}
protected void Button1_Click(object sender, EventArgs e)
{
QueryStatement = "foo sql statement";
RebindData();
}
>
void RebindData()
{
string sql = QueryStatement;
if (string.IsNullOrEmpty(sql))
{
Repeater1.DataSource = null;
}
else
{
// you need to do sql query in real app; here I'm just
returning a DataTable for test purpose
DataTable dt = new DataTable();
dt.Columns.Add("Name");
dt.Columns.Add("Description");
dt.Rows.Add("First", "This is the first item");
dt.Rows.Add("Second", "This is the second item");
Repeater1.DataSource = dt;
}
Repeater1.DataBind();
}
>
string QueryStatement
{
get { reutrn ViewState["QueryStatement"] as string; }
set { ViewState["QueryStatement"] = value; }
}
>
protected void Repeater1_ItemCommand(object source,
RepeaterCommandEventArgs e)
{
if (e.CommandName == "Link1")
{
Response.Write(e.CommandArgument);
}
}
>
Regards,
Walter Wang (wawang@.online.microsoft.com, remove 'online.')
Microsoft Online Community Support
>
==================================================
When responding to posts, please "Reply to Group" via your newsreader so
that others may learn and benefit from your issue.
==================================================
>
This posting is provided "AS IS" with no warranties, and confers no rights.
>
>
Please explain why AddHandler works in Page_Load, but not Button_C
s
click event, it will work in Page_Load, but not in a Button_Click.
The idea is that the user types some data, presses the button, gets a list
of results (each with a LinkButton) and can then press one of the link
buttons to get further information. The newly added link buttons appear, but
the click event added with AddHandler does not fire.
A control added in Page_Load with an event handler added with AddHandler
works fine.
I have not writted a web app previously and I guess that I do not understand
how dynamically added handlers work (or dont work).
John Austinthe key to understanding asp.net is to know that its stateless, and a form
instance is only used for one request. so if you add a link in a button
click, and the user clicks on that link, a new form is built to process that
request. your code must know to add the handler when that happens. usually
you'd store a flag in viewstate or session to known when to add the handler
(you must also re-add the link control).
-- bruce (sqlwork.com)
"John Austin" <John.Austin@.nospam.nospam> wrote in message
news:08B9C89B-CB28-41CE-899E-4AF85F704B84@.microsoft.com...
>I need to understand why if I add a control and use AddHandler to connect
>its
> click event, it will work in Page_Load, but not in a Button_Click.
> The idea is that the user types some data, presses the button, gets a list
> of results (each with a LinkButton) and can then press one of the link
> buttons to get further information. The newly added link buttons appear,
> but
> the click event added with AddHandler does not fire.
> A control added in Page_Load with an event handler added with AddHandler
> works fine.
> I have not writted a web app previously and I guess that I do not
> understand
> how dynamically added handlers work (or dont work).
> --
> John Austin
It has to do with the order of events in .NET. By the time you hit button
events, you have already configured controls. Under "sender", you can find
out which button was clicked and adjust appropriately in Page_Load. Be
careful, however, with overloading Page_Load with too much, as you can end
up with disaster.
Gregory A. Beamer
MVP; MCP: +I, SE, SD, DBA
http://gregorybeamer.spaces.live.com
****************************************
*********
Think outside of the box!
****************************************
*********
"John Austin" <John.Austin@.nospam.nospam> wrote in message
news:08B9C89B-CB28-41CE-899E-4AF85F704B84@.microsoft.com...
>I need to understand why if I add a control and use AddHandler to connect
>its
> click event, it will work in Page_Load, but not in a Button_Click.
> The idea is that the user types some data, presses the button, gets a list
> of results (each with a LinkButton) and can then press one of the link
> buttons to get further information. The newly added link buttons appear,
> but
> the click event added with AddHandler does not fire.
> A control added in Page_Load with an event handler added with AddHandler
> works fine.
> I have not writted a web app previously and I guess that I do not
> understand
> how dynamically added handlers work (or dont work).
> --
> John Austin
Monday, March 26, 2012
PLEASE help - simple problem
<cod>
Function GetValue(ByVal field As String, ByVal type As String) As String
Dim value As String = ""
If (type = "Text") Then
value = CType(MyFormView.FindControl("HomeWidthText"), TextBox).Text.ToString
'value = CType(MyFormView.FindControl(field), TextBox).Text.ToString
End If
...
Return value
End Function
Sub validateAllFields()
If (GetValue("HomeWidthText", "Text") = "") Then
...
End If
...
End Sub
</code
So, what's not working about that code you might ask? Well, absolutely nothing if you run the code as is. Now, replace the green with the red and you get the following error:
"Object reference not set to an instance of an object."
What? That doesn't make any sense at all to me as field is set to a string and is exactly that - "HomeWidthText". I just don't get it.
Aaroninstead of:
Function GetValue(ByVal field As String,
make field a control, in the function instead of a string
That would makes sense but that ignores the whole intention of that function...to reduce code!
You see, I didn't want to consistently have to write the following...
Dim homeWidth As String = GetValue(CType(MyForm.FindControl("HomeWidthText"), Control), "Text")
There are literally hundreds of these and I want to be able to do something like
Dim homeWidth As String = GetValue("HomeWidthText", "Text")And, it should take the "Text" parameter and determine that it is dealing with a text field and do that appropriately.
Can this not be done in ASP.Net 2.0?
Aaron
Saturday, March 24, 2012
Please help explain what an "application instance" really is in terms of static data
static data there and in another module used in the asp.net application and
I realize that static data is shared amongst child apps of an IIS
application and can be used by multiple users during the application life
cycle and for multiple page loads for the same or different page under a
root application.
What I don't understand and need to know is whether that static data would
be shared by ALL users of my application on a single server if my
application was loaded at all or whether it is possible to have my
application loaded multiple times such that each loading of my application
has its own set of static data that is potentially shared by multiple users.
Exactly what is an asp.net "application instance" in terms of windows
process, thread and object terminology which I understand well - is it a
user's sequenced use of the loaded assembly, concurrent thread usage of an
assembly or is it multiple loads of an assembly each of which can be used by
multiple users/threads?
As an analogy, let's say I write a multi threaded desktop app and allowed
multiple threads to use an object called X that was created by the main
thread. If that object X had static data then all threads in one process
that loaded my application would share that data in X even if each thread
had its own instance of X. But if I loaded 2 copies of my desktop
application (like running 2 copies of notepad.exe), each process would have
only one instance of object X static data no matter how many isntances of X
and each set of X static data would be shared by multiple threads in that
process but the staic data would not be shared between processes.
My concern is what scope I must lock at for all users of my asp.net
application on one machine. Can there be multiple copies of my static data?
One for each asp.net "application instance" or whether instance is just
referring to the fact that multiple users can be sharing the same static
data in the module that was loaded for the benefit of multiple users which I
believe I read are sequenced thru one at a time. Or do I really have to
worry about some users sharing one set of static data for one loading of my
application and another set of users sharing another set of static data
because my asp.net application was loaded again for them?
Hope I made myself clear. If I can have multiple sets of users each with
their own shared static data then I need to somehow lock across the multiple
copies of the static data.
So to summarize:
1. Can/must a C# lock be used for static data for ALL users on one machine -
depends if users are sequenced thru the application. Or is this totally
insufficient to protect a shared resource under asp.net?
2. Or rather must I somehow externally [like named semaphores] synchronize
across multiple application instances to protect that truly only one user at
a time on a given machine can modify a resource similar to what I would need
to do if I had multiple desktop processes running on one machine that had to
sequence use of a resource one at a time?
Whew...thanks!
Dave"static" means there is only one copy of the data. This is available to all
users of an application. If one user changes it, it is changed for all users.
You need to study the difference between the ASP.NET Application object vs.
what is "static" - they have similar features but are not the same thing. An
Application is a running instance of your web site in IIS, to put it in
simplest terms.
--Peter
"Inside every large program, there is a small program trying to get out."
http://www.eggheadcafe.com
http://petesbloggerama.blogspot.com
http://www.blogmetafinder.com
"Dave" wrote:
Quote:
Originally Posted by
I have a global.asax file with Application_Start defined and create some
static data there and in another module used in the asp.net application and
I realize that static data is shared amongst child apps of an IIS
application and can be used by multiple users during the application life
cycle and for multiple page loads for the same or different page under a
root application.
>
What I don't understand and need to know is whether that static data would
be shared by ALL users of my application on a single server if my
application was loaded at all or whether it is possible to have my
application loaded multiple times such that each loading of my application
has its own set of static data that is potentially shared by multiple users.
>
Exactly what is an asp.net "application instance" in terms of windows
process, thread and object terminology which I understand well - is it a
user's sequenced use of the loaded assembly, concurrent thread usage of an
assembly or is it multiple loads of an assembly each of which can be used by
multiple users/threads?
>
As an analogy, let's say I write a multi threaded desktop app and allowed
multiple threads to use an object called X that was created by the main
thread. If that object X had static data then all threads in one process
that loaded my application would share that data in X even if each thread
had its own instance of X. But if I loaded 2 copies of my desktop
application (like running 2 copies of notepad.exe), each process would have
only one instance of object X static data no matter how many isntances of X
and each set of X static data would be shared by multiple threads in that
process but the staic data would not be shared between processes.
>
My concern is what scope I must lock at for all users of my asp.net
application on one machine. Can there be multiple copies of my static data?
One for each asp.net "application instance" or whether instance is just
referring to the fact that multiple users can be sharing the same static
data in the module that was loaded for the benefit of multiple users which I
believe I read are sequenced thru one at a time. Or do I really have to
worry about some users sharing one set of static data for one loading of my
application and another set of users sharing another set of static data
because my asp.net application was loaded again for them?
>
Hope I made myself clear. If I can have multiple sets of users each with
their own shared static data then I need to somehow lock across the multiple
copies of the static data.
>
So to summarize:
>
1. Can/must a C# lock be used for static data for ALL users on one machine -
depends if users are sequenced thru the application. Or is this totally
insufficient to protect a shared resource under asp.net?
>
>
2. Or rather must I somehow externally [like named semaphores] synchronize
across multiple application instances to protect that truly only one user at
a time on a given machine can modify a resource similar to what I would need
to do if I had multiple desktop processes running on one machine that had to
sequence use of a resource one at a time?
>
Whew...thanks!
>
Dave
>
>
static data is visible to all threads in the same ApplicationDomain. the
appdomain represents an instance of the clr vm. each app domain has its
own memory, stack, code and heap (gc).
an actually program can host more have more than one appdomain, and
appdomain can talk to each other, but only thru remoting (even if in the
same nt process).
with asp.net there is a worker process per application pool. you can
config asp.net to use one pool (process) or more.
when an asp.net application is defined in IIS (its bound to a vdir), you
assign it to the pool. when the asp.net application (i'll call website
because there are too many application references) is started, an
appdomain is created and its loaded into it. normally there is only one
appdomain per website. so statics are shared between all users (threads)
of that website.
but when a website recycle happens (code changed, too much memory,etc),
a new appdomain is started, and the old one is shut down. if there any
request using the old appdomain, they complete while new requests use
the new appdomain. they do not see each others statics.
this last issue becomes important if you are referencing a unmanaged
dll. the unmanaged dll is actually loaded into the worker process, so
any statics in it are shared across both appdomains and in fact all
other websites using the same pool.
just to confuse things a little, there is a Application object, which
global.asx represents. the instances of these are maintained in a pool,
as each request gets its on unique instance. (this is for performace
reasons beyond the scope of this over simplified explanation). this is
why there is are begin and end events, hooking to create/dispose would
happen too often.
your application statics may or may not need locking. application begin
fires and completes before any other request has access to the
application. so read only can safely be loaded during this event without
locks. if it a read/write resource and does not sync access on its own,
then you need to use locks. c# has a lock statement you can use.
this is different than session, which has serialized access, as only one
request is processed at a time that uses the same session. this allows
concurrent request, just not to the same session data. this would be too
limiting for application access, so you need locks.
note: the application cache has serialized access to the object, but
does not sync methods/property accesses. the object should be thread
safe, or again you need to use locks.
-- bruce (sqlwork.com)
Dave wrote:
Quote:
Originally Posted by
I have a global.asax file with Application_Start defined and create some
static data there and in another module used in the asp.net application
and I realize that static data is shared amongst child apps of an IIS
application and can be used by multiple users during the application
life cycle and for multiple page loads for the same or different page
under a root application.
>
What I don't understand and need to know is whether that static data
would be shared by ALL users of my application on a single server if my
application was loaded at all or whether it is possible to have my
application loaded multiple times such that each loading of my
application has its own set of static data that is potentially shared by
multiple users.
>
Exactly what is an asp.net "application instance" in terms of windows
process, thread and object terminology which I understand well - is it a
user's sequenced use of the loaded assembly, concurrent thread usage of
an assembly or is it multiple loads of an assembly each of which can be
used by multiple users/threads?
>
As an analogy, let's say I write a multi threaded desktop app and
allowed multiple threads to use an object called X that was created by
the main thread. If that object X had static data then all threads in
one process that loaded my application would share that data in X even
if each thread had its own instance of X. But if I loaded 2 copies of my
desktop application (like running 2 copies of notepad.exe), each process
would have only one instance of object X static data no matter how many
isntances of X and each set of X static data would be shared by multiple
threads in that process but the staic data would not be shared between
processes.
>
My concern is what scope I must lock at for all users of my asp.net
application on one machine. Can there be multiple copies of my static
data? One for each asp.net "application instance" or whether instance is
just referring to the fact that multiple users can be sharing the same
static data in the module that was loaded for the benefit of multiple
users which I believe I read are sequenced thru one at a time. Or do I
really have to worry about some users sharing one set of static data for
one loading of my application and another set of users sharing another
set of static data because my asp.net application was loaded again for
them?
>
Hope I made myself clear. If I can have multiple sets of users each with
their own shared static data then I need to somehow lock across the
multiple copies of the static data.
>
So to summarize:
>
1. Can/must a C# lock be used for static data for ALL users on one
machine - depends if users are sequenced thru the application. Or is
this totally insufficient to protect a shared resource under asp.net?
>
>
2. Or rather must I somehow externally [like named semaphores]
synchronize across multiple application instances to protect that truly
only one user at a time on a given machine can modify a resource similar
to what I would need to do if I had multiple desktop processes running
on one machine that had to sequence use of a resource one at a time?
>
Whew...thanks!
>
Dave
>
Thanks so much Bruce. This clears up several issues understanding more what
happens. I forgot since this is managed code that the framework can do
things within a windows process that unmanaged code cannot such as
isolation. If you could bear with me I need clarification on a few points:
1. Sounds like in the normal case, ALL users of a website application shares
static data since there the code is loaded into only one appdomain. But
there could be 2 or more appdomains running the code in the case of recycle,
configuring multiple pools or I'm guessing in the case of a web garden in
which case there would be multiple instances of my static data loaded with
some users assigned to one and others to another. Did I understand that
right?
2. I understand the unmanaged dll situation and is not a concern for me.
3. I'm confused on your description of the Application object as to each
user getting their own instance. I thought that object was shared by all
users of the application even if there could possibly be multiple appdomains
running that application as in the cases you mentioned. 'Course they do say
"Application Instance" which I think is at the root of my confusion. What is
meant by "instance" in this case?
4. If Application_Start runs when the application is loaded for the first
user, does it not have to finish before any other user enters the code? If
so then why would it matter if any sort of locking ws used or not for
readonly or readwrite resoruces? I probably misunderstood. Am unclear if
asp.net code has to be rentrant as I read once that users are serialized
thru an application but have my doubts as that would not scale very well.
5. Am also thinking that using "lock (static myobject)" would only work
within a single appdomain and that if in fact multiple appdomains had my
code loaded it would not serialize access amongst appdomains but only for
threads within an appdomain if for no other reason than that they had their
own copy of "myobject". Did you mean to say that somehow the C# lock would
work between appdomains or did I misunderstand?
6. Given, let's say, the possibility of multiple appdomains running the same
code wanting to update a file shared by all the child applications in an IIS
application, what would you recommend for synchronization so they don't step
on each other? A named semaphore or named mutex?
Thanks again,
Dave
"bruce barker" <nospam@.nospam.comwrote in message
news:OBMF2aAKIHA.4592@.TK2MSFTNGP02.phx.gbl...
Quote:
Originally Posted by
static data is visible to all threads in the same ApplicationDomain. the
appdomain represents an instance of the clr vm. each app domain has its
own memory, stack, code and heap (gc).
>
an actually program can host more have more than one appdomain, and
appdomain can talk to each other, but only thru remoting (even if in the
same nt process).
>
with asp.net there is a worker process per application pool. you can
config asp.net to use one pool (process) or more.
>
when an asp.net application is defined in IIS (its bound to a vdir), you
assign it to the pool. when the asp.net application (i'll call website
because there are too many application references) is started, an
appdomain is created and its loaded into it. normally there is only one
appdomain per website. so statics are shared between all users (threads)
of that website.
>
but when a website recycle happens (code changed, too much memory,etc), a
new appdomain is started, and the old one is shut down. if there any
request using the old appdomain, they complete while new requests use the
new appdomain. they do not see each others statics.
>
this last issue becomes important if you are referencing a unmanaged dll.
the unmanaged dll is actually loaded into the worker process, so any
statics in it are shared across both appdomains and in fact all other
websites using the same pool.
>
just to confuse things a little, there is a Application object, which
global.asx represents. the instances of these are maintained in a pool, as
each request gets its on unique instance. (this is for performace reasons
beyond the scope of this over simplified explanation). this is why there
is are begin and end events, hooking to create/dispose would happen too
often.
>
your application statics may or may not need locking. application begin
fires and completes before any other request has access to the
application. so read only can safely be loaded during this event without
locks. if it a read/write resource and does not sync access on its own,
then you need to use locks. c# has a lock statement you can use.
>
>
this is different than session, which has serialized access, as only one
request is processed at a time that uses the same session. this allows
concurrent request, just not to the same session data. this would be too
limiting for application access, so you need locks.
>
note: the application cache has serialized access to the object, but does
not sync methods/property accesses. the object should be thread safe, or
again you need to use locks.
>
>
-- bruce (sqlwork.com)
>
>
Dave wrote:
Quote:
Originally Posted by
>I have a global.asax file with Application_Start defined and create some
>static data there and in another module used in the asp.net application
>and I realize that static data is shared amongst child apps of an IIS
>application and can be used by multiple users during the application life
>cycle and for multiple page loads for the same or different page under a
>root application.
>>
>What I don't understand and need to know is whether that static data
>would be shared by ALL users of my application on a single server if my
>application was loaded at all or whether it is possible to have my
>application loaded multiple times such that each loading of my
>application has its own set of static data that is potentially shared by
>multiple users.
>>
>Exactly what is an asp.net "application instance" in terms of windows
>process, thread and object terminology which I understand well - is it a
>user's sequenced use of the loaded assembly, concurrent thread usage of
>an assembly or is it multiple loads of an assembly each of which can be
>used by multiple users/threads?
>>
>As an analogy, let's say I write a multi threaded desktop app and allowed
>multiple threads to use an object called X that was created by the main
>thread. If that object X had static data then all threads in one process
>that loaded my application would share that data in X even if each thread
>had its own instance of X. But if I loaded 2 copies of my desktop
>application (like running 2 copies of notepad.exe), each process would
>have only one instance of object X static data no matter how many
>isntances of X and each set of X static data would be shared by multiple
>threads in that process but the staic data would not be shared between
>processes.
>>
>My concern is what scope I must lock at for all users of my asp.net
>application on one machine. Can there be multiple copies of my static
>data? One for each asp.net "application instance" or whether instance is
>just referring to the fact that multiple users can be sharing the same
>static data in the module that was loaded for the benefit of multiple
>users which I believe I read are sequenced thru one at a time. Or do I
>really have to worry about some users sharing one set of static data for
>one loading of my application and another set of users sharing another
>set of static data because my asp.net application was loaded again for
>them?
>>
>Hope I made myself clear. If I can have multiple sets of users each with
>their own shared static data then I need to somehow lock across the
>multiple copies of the static data.
>>
>So to summarize:
>>
>1. Can/must a C# lock be used for static data for ALL users on one
>machine - depends if users are sequenced thru the application. Or is this
>totally insufficient to protect a shared resource under asp.net?
>>
>>
>2. Or rather must I somehow externally [like named semaphores]
>synchronize across multiple application instances to protect that truly
>only one user at a time on a given machine can modify a resource similar
>to what I would need to do if I had multiple desktop processes running on
>one machine that had to sequence use of a resource one at a time?
>>
>Whew...thanks!
>>
>Dave
>>
Bruce, would dearly love to hear your view on my response to this message.
This one was so helpful. THe doc is not very clear on these sort of issues
or on reentrancy either. Thanks, Dave
"bruce barker" <nospam@.nospam.comwrote in message
news:OBMF2aAKIHA.4592@.TK2MSFTNGP02.phx.gbl...
Quote:
Originally Posted by
static data is visible to all threads in the same ApplicationDomain. the
appdomain represents an instance of the clr vm. each app domain has its
own memory, stack, code and heap (gc).
>
an actually program can host more have more than one appdomain, and
appdomain can talk to each other, but only thru remoting (even if in the
same nt process).
>
with asp.net there is a worker process per application pool. you can
config asp.net to use one pool (process) or more.
>
when an asp.net application is defined in IIS (its bound to a vdir), you
assign it to the pool. when the asp.net application (i'll call website
because there are too many application references) is started, an
appdomain is created and its loaded into it. normally there is only one
appdomain per website. so statics are shared between all users (threads)
of that website.
>
but when a website recycle happens (code changed, too much memory,etc), a
new appdomain is started, and the old one is shut down. if there any
request using the old appdomain, they complete while new requests use the
new appdomain. they do not see each others statics.
>
this last issue becomes important if you are referencing a unmanaged dll.
the unmanaged dll is actually loaded into the worker process, so any
statics in it are shared across both appdomains and in fact all other
websites using the same pool.
>
just to confuse things a little, there is a Application object, which
global.asx represents. the instances of these are maintained in a pool, as
each request gets its on unique instance. (this is for performace reasons
beyond the scope of this over simplified explanation). this is why there
is are begin and end events, hooking to create/dispose would happen too
often.
>
your application statics may or may not need locking. application begin
fires and completes before any other request has access to the
application. so read only can safely be loaded during this event without
locks. if it a read/write resource and does not sync access on its own,
then you need to use locks. c# has a lock statement you can use.
>
>
this is different than session, which has serialized access, as only one
request is processed at a time that uses the same session. this allows
concurrent request, just not to the same session data. this would be too
limiting for application access, so you need locks.
>
note: the application cache has serialized access to the object, but does
not sync methods/property accesses. the object should be thread safe, or
again you need to use locks.
>
>
-- bruce (sqlwork.com)
>
>
Dave wrote:
Quote:
Originally Posted by
>I have a global.asax file with Application_Start defined and create some
>static data there and in another module used in the asp.net application
>and I realize that static data is shared amongst child apps of an IIS
>application and can be used by multiple users during the application life
>cycle and for multiple page loads for the same or different page under a
>root application.
>>
>What I don't understand and need to know is whether that static data
>would be shared by ALL users of my application on a single server if my
>application was loaded at all or whether it is possible to have my
>application loaded multiple times such that each loading of my
>application has its own set of static data that is potentially shared by
>multiple users.
>>
>Exactly what is an asp.net "application instance" in terms of windows
>process, thread and object terminology which I understand well - is it a
>user's sequenced use of the loaded assembly, concurrent thread usage of
>an assembly or is it multiple loads of an assembly each of which can be
>used by multiple users/threads?
>>
>As an analogy, let's say I write a multi threaded desktop app and allowed
>multiple threads to use an object called X that was created by the main
>thread. If that object X had static data then all threads in one process
>that loaded my application would share that data in X even if each thread
>had its own instance of X. But if I loaded 2 copies of my desktop
>application (like running 2 copies of notepad.exe), each process would
>have only one instance of object X static data no matter how many
>isntances of X and each set of X static data would be shared by multiple
>threads in that process but the staic data would not be shared between
>processes.
>>
>My concern is what scope I must lock at for all users of my asp.net
>application on one machine. Can there be multiple copies of my static
>data? One for each asp.net "application instance" or whether instance is
>just referring to the fact that multiple users can be sharing the same
>static data in the module that was loaded for the benefit of multiple
>users which I believe I read are sequenced thru one at a time. Or do I
>really have to worry about some users sharing one set of static data for
>one loading of my application and another set of users sharing another
>set of static data because my asp.net application was loaded again for
>them?
>>
>Hope I made myself clear. If I can have multiple sets of users each with
>their own shared static data then I need to somehow lock across the
>multiple copies of the static data.
>>
>So to summarize:
>>
>1. Can/must a C# lock be used for static data for ALL users on one
>machine - depends if users are sequenced thru the application. Or is this
>totally insufficient to protect a shared resource under asp.net?
>>
>>
>2. Or rather must I somehow externally [like named semaphores]
>synchronize across multiple application instances to protect that truly
>only one user at a time on a given machine can modify a resource similar
>to what I would need to do if I had multiple desktop processes running on
>one machine that had to sequence use of a resource one at a time?
>>
>Whew...thanks!
>>
>Dave
>>