C# Insert block of code to every aspx page - c#

I'm having a web application project which is running .NET 4.0. I've plenty of .aspx page and now I would like to add in a block of script code to all the .aspx page header, for example Google Analytics.
I know there is a solution to do is add in every single page, but I would like to know is there any other's way to do this instead modify every single .aspx page?
*My header is not runat server
I got an idea to do but not sure it's work or not.
Get the page class in Global.asax
Get the output stream from the page class.
Insert the Google Analytics code in the HTML header.
I couldn't get the Page.Response in the Global.asax as I tried in the Application_PostRequestHandlerExecute & also Application_EndRequest. Does anyone know is this work and how it's work?
Thanks.

Use master pages. This is the ASP.NET way of putting the same content on multiple pages without repeating yourself.

All of our aspx pages code-behind classes inherit from the same base class, which allows us to inject standard client side elements (controls, script, etc) into every page using a single point of control.
Our design was implemented before the advent of master pages, but while it could possibly be converted to a master-page design, we have found this implementation to be extremely flexible and responsive to changing needs.
For example, we have two completely separate application designs (different skin, some different behavior) that is based off of the same code base and page sets. We were able to dynamically swap out banners and other UI and script elements by simple modifications to the base class in order to support this without having to duplicate every page.
Unfortunately, if you want the script to be in the head element, you will need to ensure that they are all marked as runat=server.
Our base class itself inherits from Page, so it can intercept all of the page's events and act on them either instead of or in addition to the inheriting classes (we actually have internal overrideable methods that inheritors should use instead of the page events in order to ensure order of execution).
This is our (VB) code for adding script to the header (in the Page's LoadComplete method):
' sbscript is a stringbuilder that contains all of the javascript we want to place in the header
Me.Page.Header.Controls.Add(New LiteralControl(sbScript.ToString))
If it is not possible to change the heads to runat server, you could look into ClientScriptManager method RegisterClientScriptBlock which places the script at the top of the page.

You can create a basic page with the header with the custom code such as Google analytics and have the other pages inherit from that. It will facilitate two things:
1) In case you ever want to change the custom code you will only have to do it in one place
2) No repetitive code hence more maintainable

I am trying to do the same thing on a legacy app that we're trying to decommission. I need to display a popup on all the old pages to nag users to update their bookmarks to use the new sites, without forcing them to stop using the legacy site (yet). It is not worth the time to convert the site to run on a master page when I can just plop in a popup script, since this whole thing is getting retired soon. The main new site uses a master page, which obviously simplifies things there.
I have this line in a file that has some various constants in it.
Public Shared ReadOnly RetirementNagScript As String = "<Script Language='javascript'> alert('[app name] is being retired and will be shut down [in the near future]. Please update your bookmarks and references to the following URL: [some URL]'); </script>"
Then I am inserting it in Global.asax, in Application_PostAcquireRequestState:
Response.Write(Globals.RetirementNagScript)
Hopefully this is useful to you; I still need to be able to present a clickable URL to the user that way, on each page of the legacy site, and JS alert doesn't do that for me.

Related

how to create a decorator proxy page in asp.net 3.5

I am trying to make this feature, and I'm really stuck.
I have two applications that run on the same domain. and I need to have one application load pages from the other one inside it's own (the first) master page.
I have full control of the code of both sides, of course.
I have tries using HTTPRequest, and HTTPResponse, and I have tried using WebBrowser. Both work great as long as I have static(plain HTML) pages. However,
those pages are actually dynamic. the user need to press server-side buttons (postback) and generally use the session, viewstate, and/or cookies.
because of that, HTTPRequest and WebBrowser fail me, as they do not cause postback, and therefore those server-side controls are not working. more so, if I try to "fake" a postback by saving the ViewState after each response and than resend it on the next request, after a few (3-4) times the original page will return a "The state information is invalid for this page and might be corrupted" error, even if I use
EnableViewStateMac ="false" EnableSessionState="True" EnableEventValidation ="false" ValidateRequest ="false" ViewStateEncryptionMode ="Never
So... any ideas how can I solve this issue?
Thanks in advance
What is the main desire here?
Wrap one site's content in another without any architecture changes?
ANSWER: Iframe
Have a single submit button submit from two sites?
ANSWER: Not a good idea. You might be able to kludge this by creating a scraper and parser, but it would only be cool as an "I can do it trophy". Better to rearchitect the solution. But assuming you really want to do this, you will have to parse the result from the embedded site and redirect the submit to the new site. That site will then take the values and submit the form to the first site and wait for the result, which it will scrape to give a response to the user. It is actually quite a bit more complex, as you have to parse the HTML DOM (easier if all of the HTML is XHTML compliant, of course) to figure out what to intercept.
Caveat: Any changes to the embedded site can blow up your code, so the persons who maintain the first site must be aware of this artificially created dependency so they don't change anything that might cause problems. Ouch, that sounds brittle! ;-)
Other?
If using an iFrame does not work, then I would look at the business problem and draw up an ideal architecture to solve it, which might mean making the functionality of the embedded site available via a web service for the second site.

Header equivalent of PHP include

I originally come from PHP and I have just started with ASP/.NET. I am aware that a direct equivalent of include("filename.php"); does not exist, but that's not exactly what I want to achieve.
I am attempting to create a header file which I can use on every page. I have read from many sources that making a user control is the solution. After creating all of the necessary code to make this work, I arrived at a point where the actual element on the page isn't actually created at the point when I call .InnerHtml. For example:
breadcrumbContainer.InnerHtml = "testing text";
The above code does not work when called within my file which is called header.ascx.cs even though there is a div on the page with runat="server" and the correct ID.
I am trying to find out if there is an easier way to resolve this problem. I have been told that I should avoid masterpages (even though I don't know if they are relevant in this situation). Should I create some sort of method which creates the html for the header, this way I can easily call it on every page? Are there any other solutions I haven't thought of?
If there are any good articles which clearly explain this problem, I would love the links. I have literally searched hundreds of pages on the web and found nothing that is giving me a clear understanding of how to resolve this problem.
Master pages can be relevant and very helpful in this case. Check out them out.!
When someone says "don't do something" always ask why. Do not take such advice at face value. That's exactly how phantom fears are spread and thousands of developers end of treating some programmer's pet peeve as an an absolute rule! Besides, asking "why?" will strengthen your own as well as the more senior developer's understanding of the issue at hand.
From the link:
ASP.NET master pages allow you to create a consistent layout for the
pages in your application. A single master page defines the look and
feel and standard behavior that you want for all of the pages (or a
group of pages) in your application. You can then create individual
content pages that contain the content you want to display. When users
request the content pages, they merge with the master page to produce
output that combines the layout of the master page with the content
from the content page.

when do you need .ascx files and how would you use them?

When building a website, when would it be a good idea to use .ascx files? What exactly is the .ascx and what is it used for? Examples would help a lot thanks!
It's an extension for the User Controls you have in your project.
A user control is a kind of composite control that works much like an ASP.NET Web page—you can add existing Web server controls and markup to a user control, and define properties and methods for the control. You can then embed them in ASP.NET Web pages, where they act as a unit.
Simply, if you want to have some functionality that will be used on many pages in your project then you should create a User control or Composite control and use it in your pages. It just helps you to keep the same functionality and code in one place. And it makes it reusable.
We basically use user controls when we have to use similar functionality on different locations of an app. Like we use master pages for consistent look and feel of app, similarly to avoid repeating the same functionality and UI all over the app, we use usercontrols. There might me much more usage too, but I know this one only...
For example, let's say your site has 4 levels of users and for each user there are different pages under different directories with different access mechanisms. Say you are requesting address info for all users, then creating address fields like Street, City, State, Zip, etc on each page. That would be a repetitive job. Instead you can create it as an ascx file (ext for user control) and in this control put the necessary UI and business code for add/update/delete/select the address role wise and then simply reference it all required page.
So, thought user controls, one can avoid code repetition for each role and UI creation for each role.
Ascx-files are called User Controls and are meant for reusability and also for making complex aspx-pages less complex (lift out some part of the page). They could also be beneficial for something called donut caching, that is when you would like to cache a certain part of a page.
If you have a block of code+html that appears on several pages and is sort of independent of that page (say a block of latest news items), you could copy/paste the code to every page.
It is however better to put that code in its own block and just include that block on every page that needs it. That "block" is an ascx file.
One more use of .ascx files is, they can be used for Partial Page caching in ASP.NET pages. What we have to do is to create an ascx file and then move the controls or portion of the page we need to cache into that control. Then add the #OutputCache directive in the ascx control and it will be cached separately from the parent page. It is used when you don't want to cache the whole page but only a specific portion of the page.
ASCX files are server-side Web application framework designed for Web development to produce dynamic Web pages.They like DLL codes but you can use there's TAGS
You can write them once and use them in any places in your ASP pages.If you have a file named "Controll.ascx" then its code will named "Controll.ascx.cs".
You can embed it in a ASP page to use it:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="Controll.ascx.cs"%>
When you are building a basic asp.net website using webcontrols is a good idea when you want to be able to use your controls at more then one location in your website.
Separating code from the layout ascx files will be holding the controls that are used to display the layout, the cs files that belong to the ascx files will be holding the code that fills those controls.
For some basic understanding of usercontrols you can try this website

Can two ASPX pages inherit the same code behind class?

I'm just starting out learning ASP.NET. From what I understand, ASP.NET differs from old school ASP in that the logic code for a page exists in as separate file rather then being embedded in the ASP page. So when a user requests a page like ShoppingCart.aspx the server reads the directive at the top ...
<%# Page Title="" Language="C#" MasterPageFile="~/Styles/Site.Master" AutoEventWireup="true"
CodeBehind="MyShoppingCart.aspx.cs" Inherits="TailspinSpyWorks.MyShoppingCart" %>
This tells the server what file and what class in the file is associated with the page. The code behind class also has member variables that correspond to each control on the page, and provide a way for code in the code behind file to manipulate the controls.
First, do I understand this correctly?
Second, could a site be setup with two separate ASPX pages with identically named controls, which both had a directive pointing to the same file and class? Would you even want to do this? Both pages could have the same functionality but a different layout. I was thinking this could be a way to create separate "desktop" and "mobile" versions of a page with out duplicating content in the code behind files.
I guess ultimately what I'm wondering, is if there a way to define an abstract page? Say create an abstract page definition that says a page must have controls "cart_list", "total_lbl", but then be able to have multiple pages that inherit from this abstract page?
Yes, two pages can inherit from the same class. Like it can inherit from Page class directly and do not even have an associated .cs file (useful when you have a page which is not static, but which does not handle events or something which may require a code-behind class).
In practice, I think it's not a good idea to inherit several ASP.NET pages from the same class directly. This is not something common, so:
the code will be more difficult to understand and impossible to extend,
will be difficult to manage within Visual Studio, especially when it comes to events, controls, etc.
will cause much pain with existing/missing controls. See the detailed Guffa answer below.
If several pages of your website share the same logic,
make one class per page, and inherit those classes from a common parent class which will contain common methods and properties and which will inherit from Page class. You will obtain an extensive and easy-to-understand solution.
or create a masterpage if the case is a good candidate for a masterpage.
I'm just starting out learning ASP.NET. From what I understand, ASP.NET differs from old school ASP in that the logic code for a page exists in as separate file rather then being embedded in the ASP page
Classic ASP and ASP.NET differ in a lot of ways, the primary way being that classic ASP pages are (for the most part) a procedural, script-based, unmanaged code whereas ASP.NET pages are compiled, managed, and event-driven. Typically ASP.NET pages separate out the markup and the server-side code into two separate files, but this isn't a necessity. It is quite possible to put the server-side code in the .aspx page in a <script runat="server"> block.
the directive at the top ...
<%# Page Title="" Language="C#" MasterPageFile="~/Styles/Site.Master" AutoEventWireup="true" CodeBehind="MyShoppingCart.aspx.cs" Inherits="TailspinSpyWorks.MyShoppingCart" %>
tells the server what file and what class in the file is associated with the page. The code behind class also has member variables that correspond to each control on the page, and provide a way for code in the code behind file to manipulate the controls. First, do I understand this correctly?
Yes, you understand this correctly.
Second, could a site be setup with two separate ASPX pages with identically named controls, which both had a directive pointing to the same file and class?
Yes, you could do this.
Would you even want to do this?
Probably not. In fact, even if there are two separate ASPX pages that both inherit from the same base page there's nothing that forces them to have the same set of controls. In fact, they could have different controls and the page will render without error. (If you try to access a control in the code-behind that does not exist in one of the pages you'll get a runtime error.)
I guess ultimately what I'm wondering, is if there a way to define an abstract page? Say create an abstract page definition that says a page must have controls "cart_list", "total_lbl", but then be able to have multiple pages that inherit from this abstract page?
There's not (to my knowledge) a way to accomplish this. What might come close, though, is having a base Page class, which is a good practice to get use even if you don't have this particular scenario at hand. For more on creating and using base Page classes, see: Using a Custom Base Class for your ASP.NET Pages' Code-Behind Classes.
Happy Programming!
You might want to check this out, if you're using .NET 4.0. It describes Request.Browser.IsMobileDevice and Request.Browser.MobileDeviceModel.
You could put some logic into the code-behind, or the ASPX mark-up, to detect if you're running on a mobile device. That will allow you to have all the code in one file, but can select which HTML elements to display, etc.
Yes, and no.
You can use the same class for different pages, however the binding between the page controls and the variables in the class is not strict.
The control references will simply be assigned to the variables if they exist and have a matching type, but you can't make any restrictions that the page has to contain certain controls. You can however check if the variables has been assigned or if they contain null references the first you do in the code.
I have used the same class for different pages at some rare occasion, but it's not common practice. Usually there is little gain in doing this, and if you want to reuse code in the pages, you can put it in a class file and use it from the separate pages.

Using Admin Panel How we can create a aspx page in sitefinity?

how we can create the dynamic page ex. help.aspx and write the code in sitefinity. Because i facing a problem I create a page but i unable to know in which directory the page is lived. If any one help me Suggest.
http://abc.com/sitefinity/admin/pages.aspx
I'm not exactly sure I understand your question correctly. When you create a page in Sitefinity, it doesn't create an ASPX file. The data for the page is kept in the database and served from there. There are no physical files involved.
If you want to write some code that executes when a page loads, you have two options:
Put the code into a control and drop the control on a page created from within Sitefinity
Create a regular ASPX page from Visual Studio and include it as an external page in Sitefinity.
I would recommend the first option, as this would provide you with all the Sitefinity goodness that all pages use - templates, editing through the browser, etc.
If you wanted something else and I misunderstood, please be more specific.
Slavo, The Sitefinity Team

Categories