Category Archives: App_Code

[RESOLVED] Using VB, how do I call a subroutine in codebehind in a content page from a subroutine in codebehind of a masterpage

I have  a subroutine in a content page that I want to be able to call from codebehind of a subroutine in a master page.

How do I do that?

Hi,

I suggest you to create a Class file in the App_Code directory and put the subroutine in it. You can call it from both the Master page as well as the content page.

Hope it helps u...

Hi,

You can consider to use delegate and event handler.

Check this code(I convert it to vb by using Convert C# to VB):

Master (SiteMaster)page.vb:

Public Partial Class SiteMaster
	Inherits System.Web.UI.MasterPage
	Public Event MyEventHandler As EventHandler
	Protected Sub Page_Load(sender As Object, e As EventArgs)

	End Sub

	Protected Sub Button1_Click(sender As Object, e As EventArgs)
		RaiseEvent MyEventHandler(sender, e)
	End Sub
End Class

Master page:

 <form runat="server" id="MasterForm">
          <asp:Button ID="Button1" runat="server" Text="MasterEvent" onclick="Button1_Click" />

        <div class="main">
            <asp:ContentPlaceHolder ID="MainContent" runat="server"/>
        </div>
 </form>

Content Page.vb:

Protected Sub Page_Load(sender As Object, e As EventArgs)
	Dim master As SiteMaster = TryCast(Me.Master, SiteMaster)
	master.MyEventHandler += New EventHandler(AddressOf master_MyEventHandler)

End Sub

Private Sub master_MyEventHandler(sender As Object, e As EventArgs)
	Me.TextBox1.Text = "aaa"
	Me.Button1.Text = "bbb"
End Sub

Content aspx:

<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    <asp:Button ID="Button1" runat="server" Text="Button" />
</asp:Content>

 

The main idea is to create a EventHandler in master page, then in content page, add a event method to it and call the EventHandler in master page.

Hope this can help you.

 Can you give me a spefice example. Also, I am trying to call a subroutine in codebehind of the content page from a subroutine in codebehind of the masterpage, not the other way around.

What I am trying to actually do is to use a subroutine in codebehind of the content page to place the name of a subroutine as a variable in a session, page_load subroutine in codebehind of the masterpage check for a value for the session, and f it see'sone, run the subroutine.  

Thanks!

Hi,

JAYHAWKER

What I am trying to actually do is to use a subroutine in codebehind of the content page to place the name of a subroutine as a variable in a session, page_load subroutine in codebehind of the masterpage check for a value for the session, and f it see'sone, run the subroutine.  

If I'm not misunderstood you, check this code:

Content Page.vb:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
	Session("method") = "ContentMethod"
End Sub

Public Sub ContentMethod()
	Response.Write("content method has invoked")
End Sub

Master Page.vb:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
	If Session("method") IsNot Nothing Then
		Dim methodName As String = Session("method").ToString()
		Dim method As MethodInfo = Me.Page.[GetType]().GetMethod(methodName)
		If method IsNot Nothing Then
			method.Invoke(Me.Page, Nothing)
                                                          'invoke the method in content page.

		End If
	End If
End Sub

Using .NET Reflection to invoke a method by passing the string of its name as parameter.

Check this link:http://msdn.microsoft.com/en-us/library/8zz808e6.aspx

Hope this can help you.

[RESOLVED] Thread class file in ASP.NET

I have a Threading class that I have written into a separate class file, call it File_01.cs, in the App_Code folder of the project.  Within this class file there is a using reference at the top of the file to another class in a separate file (File_02.cs) also in the App_Code using the namespace name in File_02.cs.  Other of the code behind files, i.e., the *.aspx.cs files, also use this File_02.cs reference.

The Threading class in File_01 is started from an *.aspx.cs file in response to a button click in the *.aspx file associated with it.

When the web site is copied to the temporary host location, the the using reference in File_01 is not seeing the class in File_02.  All the other *.aspx.cs files that use the class in File_02.cs do so without difficulty.

This web site works properly when tested on my local machine, i.e., localhost:50309, but not when deployed.

How do I fix this reference issue?

Thanks.

Thomas

 

Assuming that your a website project, is there any variance in the web.config file?

Bob,

Thanks for the reply.  Somehow I was not copying all the files when using Copy Web site.  The item is resolved.

Thomas

 

[RESOLVED] Session_Start executes again after an error occurs (when going to Custom Error page)

Hey everyone,

I'm having a wicked time trying to redirect the different error scenarios to a custom error page.  Basically, I have put some code in Application_Error in global.asax, and done the necessary web.config settings to use Custom Errors.

In global.asax on Application_Error, I stored the Server.GetLastError in Session.  The reason I have to store it in Session is because (as far as I know) you lose the exception when using "ResponseRedirect".  And the reason I have to use ResponseRedirect is because I am using an UpdatePanel with AJAX calls, and any exception during the AJAX call shows up as a JavaScript error, and doesn't get handled using the custom error page (see this post).

global.asax:  

 

<div style="outline-width: 0px; outline-style: initial; outline-color: initial; font-size: 12px; vertical-align: baseline; background-image: initial; background-attachment: initial; background-origin: initial; background-clip: initial; background-color: transparent; background-position: initial initial; background-repeat: initial initial; padding: 0px; margin: 0px; border: 0px initial initial;">
void Application_Error(object sender, EventArgs e)
{
   
////must perform this check to avoid the "Session state is not available in this context" errors
   
if (HttpContext.Current.Session != null)
   
{
       
Session["LastException"] = Server.GetLastError();
   
}
   
else
   
{
       
// (I think this happens when there are compile-time errors)
       
Server.Transfer("~/Oops.aspx");
   
}
}

void Session_Start(object sender, EventArgs e)
{
   
//must perform this check to avoid the "Session state is not available in this context" errors
   
if (HttpContext.Current.Session != null)
   
{
       
//initialize the session (http://forums.asp.net/t/1405077.aspx)
       
Session["LastException"] = "";
   
}
}
</div>

 

The problem is that if an exception occurs in: (1) a file within the App_Code directory, or (2) a method like Page_Load, my "LastException" gets lost.  I did some debugging, and it looks like Session is lost.  Session_Start runs again after the exception.

So for example of (1), if I had this in my ASPX:

<asp:Label ID="LabelSomeText" runat="server"
    Text='
<%# MyAppCodeClass.SomeMethod() %>'
    />

And, then in MyAppCodeClass:

public void SomeMethod()
{
   
throw new MyException("hello world!");
}

And for an example of (2), if I just had this in my code behind:

 

protected void Page_Load(object sender, EventArgs e)
{
   
throw new Exception("hello world!");
}

 

Both (1) and (2) goes to my custom error page fine, but Session has no keys, because Session_Start gets called after the exception is thrown.  Any ideas??

 

What does your .net error page say?  Is it the 'hello world' error or is it bombing out because of some of the error handling code?

mkubaryc

What does your .net error page say?

I actually just made some changes to the code (see my post above, where I use "ResponseRedirect" instead of "ResponseRewrite", and I no longer get yellow screened).  So the good news is that I now go to custom error page, the bad news is, I lose my exception details that I stored in Session :-/

@rwilson:

Take a look to the following article, and I would follow its methodology closely. Once you get it working, then you can modify it to your needs.

How to: Handle Application-Level Errors:

http://msdn.microsoft.com/en-us/library/24395wz3.aspx

Notice how you have to call Server.ClearError() prior to exiting the event to clear the error. You may also want to look at this, if you are having issues after deployment as well:

IIS 7 – Managed pipeline mode – Global.asax redirect not working:

http://praveenbattula.blogspot.com/2009/12/iis-7-managed-pipeline-mode-globalasax.html

Again, just get the basic MSDN sample working and then proceed to a more customized solution.

Hope this helps! Smile

 

[RESOLVED] Classes vs Methods

Hi all

I am confused to when I should use a class vs a method in this example. It appears the only advantage is the class can be called from any web page as the class lives in the app_code folder.

Below is an example where both return the same value, one is a class, the other is a method.

c#

{

CheckValue.Value(stringValue);
ReturnValue(stringValue);

}

public string ReturnValue (stringValue)

{

    return stringValue;

}

and in my code folder I have a class

 class CheckValue
    {
        public static string Value(string s)
        {
            return s;
        }

}

 

Any opinions on which is better and why?

Dave

i guess, question is method in same class vs method in separate class

anyways u r calling method in both the cases...

here, if value method in checkvalue class is required in many other pages, then its good to have common method of same functionality instead of creating simillar method in many pages

but if this method will be used in single page, then u can define the emthod in same page class..

hope this helps..

Thank you. That answers my question,

Dave

when we talk about classes we see how often they are resuable and also their access modifiers....

say you have a method in a page and that is private, event if that method is intended to reusable in other places, it cant be done because of private....

Then in that case if reusability is top priority you can either declare it public or you can go for new class with that method as public....the reason why we go for classes, is to consolidate the reusable logic....

Thanks.

DaveRook

Thank you. That answers my question,

Dave

Please mark as answered to the posts that help u.... it help other visiting the forum..

While the question has been fully answered I think it is important to add that you wrap up methods in a class. This means that not only do you have a nice block that you can have variables in and move around but you also define a namespace for all of those methods. Public methods in the App_Code folder have to have unique names and a namespace provides them that (not including reserved names).

 

Just my two cents.

Thank you for your input.

[RESOLVED] what gets executed during a postback

 I want to know if my variable "thepass" gets reinitialized each time there is a postback? code as follows:

Partial   Class showposts

 Inherits System.Web.UI.Page

 Public thepass As  String

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me .Load

 

 

 

blah

blah

blah

End sub

Hi,

 

Yes your variable will be initialized everytime during the postback.

Put a debug point and try to execute your code you can se that everytime execution will go through this code. If you wanted to assign any constant values you can put the code here.

 

How do I prevent this from happening? I want the var to keeps its value thoughout postbacks.

 

Hi,

 

Keep the value in session and clear the session when you no longer required.

 

Session["thepass"] ="123";

 

its not possible to keep alive global variable like that.... becoz http is stateless...

if u want some value to persist for single user, then u can use following...

1) session variable..

session["anyName"] = "value";

u can read this session variable anytime later (in other pages too) unless session is valid..

2) if u just want to keep value alive for that page only... then use viewstate

its like assigning value to some hidden field present on the same page...and reading it back after post back

3) if u want to share some value across all users of site.. then u can use static global variable declared in separate class in app_code directory.

like this

http://www.dotnetperls.com/global-variables-aspnet

hope this helps...

I was using session but wanted to avoid the timeout issue.

perhaps hidden field?

Actually it's a password so hidden fields are obviously not secure on 2nd thought.

I guess I have no choice but to use session.

Hi,

I hope your application is configured to timeout when session expires. If yes then you will be loosing value in the hidden field also.

Not sure about the architeture of your application just curious to know about this.

 

Use the ViewState, that's pretty much what it's there for. Generally, I create a property for the page that let's me get/set the viewstate for that variable easily as so:

private string MyString
{
get
{if(ViewState["MyString"] != null)
return ViewState["MyString"].ToString();
else
return string.Empty;
}
set {ViewState["MyString"] = value;}

}

 

The viewstate can also hold other values such as integers and you can cast them to get the original object out such as (int)ViewState["MyInteger"];

Keep in mind, unless you store something specifically somewhere everything gets initialized when you do a postback. The web is completely stateless so once the page has been served to the browser, that's it. The browser isn't connected anymore and the web server has effectively washed it's hands of the whole thing. The ViewState is an encrypted hidden field that lets you put serializable data into and get out of on each postback.

I got confused but isn't session same as viewstate?

Hi,

Fonzie

I got confused but isn't session same as viewstate?

Yes, both of them can maintain some information through client and server. But session is different to viewstate in the aspect of storage mechanism.

Simply speaking, session state store in server and use client cookie key to re-inflate it. On the other hand, viewstate variable store in page, actually in hidden field control with encrypt value.

You can check some article to have a clear understanding.

Session:http://msdn.microsoft.com/en-us/library/ms972429.aspx

ViewState:http://www.codeproject.com/KB/aspnet/aspnetviewstatepagecycle.aspx

ViewState is page level, if the your variable "thepass" is only use in this page scope, you can use viewstate or hiddenfied control to save it.

If  you need to get this variable in other page, use session or other state object for cross page value sharing.

Hope this can help you.

The ideal way for this is to declare a public property to the page. OVerride the LoadViewState and SaveViewState methods

In SaveViewState, Add the property to the ViewState

In LoadViewState, Retrieve the property from the ViewState

In this way, you can use the property as if it is a property of the page. (persistence across postbacks) and no overhead, if page object is released.