Does anyone know how to reuse the code from one aspx.cs class in another aspx page?
It all depends on what you're ultimately doing, but one option would be to build a re-usable class in your App_Code folder and use it across your entire site.
Ideally you should put your reusable methods in a seperate class in a seperate cs file.
But what you are asking for can also be easily done, here is an example:
Page1.aspx.cs
public partial class MyPage1: System.Web.UI.Page
{
public static void MyTestFunction()
{
//Code Here
}
public void MyTestFunction2()
{
//Code Here
}
}
Page2.aspx.cs
public partial class MyPage2: System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
MyPage1.MyTestFunction(); // static function call
//or
MyPage1 page1 = new MyPage1();
page1.MyTestFunction2();
}
}
There are several options for reuse in ASP.NET:
Master pages
user controls
composite controls
create a custom class which inherits from the Page class and have your pages inherit from that custom class
Create a helper class which has reusable methods which you can use in your different webforms
Reusing code in multiple pages should be done in a separate class as mentioned or by using another mechanism such as master pages, etc. Trying to call code from multiple aspx pages without using backend classes is risky going forward with upgrades as it makes your app more brittle and harder to maintain over time. frontend pages such as ASPX pages should contain their own independent codebehind only. They should not reference another ASPX page. A better model is to set up an object model prior to the GUI layer, then call into the object model from various pages. That way, the page code is responsible only for it's own local page elements and any business logic needed across pages is housed elsewhere. Again, if you need UI logic to be shared, use something like old-style include files, master pages, or user controls which can be very useful at sharing as well as separating out the concerns of each piece (that separation of concerns principle is very important and when done right can help your app remain clean and easy to upgrade later!)
see here How many classes can you inherit from in C#?
Related
I am new to .NET MVC and am looking for a code or non-code answer to a this question. My web application will have hundreds of controllers, partial controllers, etc. All the controllers will share a common layout. I am currently adding a Menu object to the ViewBag from the page's controller.
I'd like to know what is best practice for re-using an object multiple times in an MVC Layout view (similar to the Menu object in my example, below)?
#Html.Header(ViewBag.Menu as IR.Web.Portal.Models.Navigation.Menu)
#Html.SideNav(ViewBag.Menu as IR.Web.Portal.Models.Navigation.Menu)
#Html.Footer(ViewBag.Menu as IR.Web.Portal.Models.Navigation.Menu)
I want to initialize the object only once but use it many times.
I do not want to add code to every controller to make it work. Inheritance a base controller might be a good solution.
The Menu object does not need to be in the ViewBag as it is in my example.
The Menu object will be different for every user of the site. So, Static or Singleton classes are probably out of consideration.
Authentication and Logging are good fits for a Controller Base. However, I think it is a good idea to create a Custom PageBaseType as well. There are many things a Page should do but not a controller... Theme, Logo, Layout, Load Scripts, Possibly Get Menus, etc.
Add the following to the \Views\Web.config:
<system.web.webPages.razor>
<pages pageBaseType="MyPageBase">
</system.web.webPages.razor>
Create a class:
public abstract class MyPageBase<T> : WebViewPage<T>
{
protected override void InitializePage()
{
ViewBag.Menu = new Menu();
base.InitializePage();
}
}
I have a generic editor in ASP.NET page for editing lookup values for different database tables.
The code behind uses a base class which handles 99% of the work across all the different lookups in the system.
A C# class is passed in to the base class from the code behind as below.
public class LookupPageBase : System.Web.UI.Page
{
protected IEditableLookupManager LookupManager
{
get
{
return this.lookupManager;
}
set
{
this.lookupManager = value;
}
}
}
public partial class LookupsEditor : LookupPageBase
{
this.LookupManager = new ConcreteManagerClass();
}
A different C# class is passed into the lookup Manager property for each lookup. I could use the factory pattern to avoid a big if then else in the code behind. However, I was wondering if the same effect could be achieved via a subclass of the code behind e.g.
public partial class LookupsEditorSubClass : LookupsEditor
{
public LookupsEditorSubClass() {
base.LookupManager = new ConcreteManagerClass();
}
}
Questions:
1) This would require the code behind class to be dynamically set..... Can the code behind class be dynamically set and is it even possible to inherit from a partial class?
2) If using a factory instead do I just need to accept a big if then else?
Any chance that you could use MVC for this? I see that you have included .NET 3.5 in the tags, so there is no real technical reason why you shouldn't.
The reason I ask is that this problem would be easily solved using MVC. Only the model would change between your different cases.
Update: Following your comments, I think that the Factory approach is probably best for you. Messing around with the codebehind classes has resulted in nothing but trouble for me in the past. Rather than changing the codebehind class, why don't you use usercontrols for the editing. Then, you could load a different usercontrol depending on the particular requirements of the entity that you are editing. This could be provided by a factory.
I've read the questions/answers explaining that there is no multiple inheritance in C#, that we don't even need it, and that it causes too much problems.
Now, I'm working on a project where I don't really understand how can I do things without multiple inheritance, without duplicating code.
Here's the situation. There is a website with a home page and other pages inheriting from a masterpage (the home page does not inherit from). Both the page and the masterpage are performing some stuff: custom login, statistics, loading of users settings for customization, etc. For the moment, the solution is crappy, since the source code for those tasks is just copied twice.
The home page class inherits from Page. The masterpage, on the other hand, inherits from Masterpage. Logically, it would be great to inherit from a common class too, but it's multiple inheritance, so it's impossible.
So what to do instead?
I thought about several ways, but dislike them:
Create a standalone class which will be called from the page/masterpage class. So for example instead of writing bool isDisplayingTips = this.CurrentUser.IsDisplayingTips, I would write bool isDisplayingTips = this.SharedObjects.CurrentUser.IsDisplayingTips. I don't like it, since it's longer to write.
Create a "real", empty, common masterpage, and inherit both the home page and the masterpage from it. Not only it will require to write more code to access masterpage parameters, but it will also slow the things down, requiring an additional masterpage on each request.
Any idea?
MasterPage is a just control (that get embedded into the actual page) so you can not have the later approach. However, first approach of creating another helper class is quite feasible.
Yet another approach that we typically use is to have
Common base page class - all pages will inherit from the common base page.
Put common functionality in base page class
From master page, the base page can be referred by casting - for example, myBasePage = (BasePage)this.Page;. This way master page may access common functionality from base page class.
I don't find your 2nd option that dislikable.
I presume you mean creating a base class, e.g. MasterPageBase, derived from System.Web.UI.MasterPage, and creating an empty MasterPage for your homepage, that will inherit from this MasterPageBase.
If done right, it shouldn't slow things down...
I suggest you to use the first of your option. If you (understandably)
don't feel comfortable with increased level of indirection, you could just create new methods on your standalone classe, e.g:
public bool IsDisplayingTips(){
return CurrentUser.IsDisplayingTips;
}
and the from your pages just call
bool isDisplayingTips = this.SharedObjects.IsDisplayingTips()
Use:
standalone class which will be called
from the page/masterpage class
but instead of stopping there, add a base page and a base master page. Both use the shared class, and keep the specific pages/master pages code from the indirection.
I strongly believe that, reading code and reading good code is key to great programming. If not one of the many.
I had been facing some problems in visualizing and having a "feel" of using inheritance to better my code architecture.
Can somebody give me some link to good code to emulate, where folks have used inheritance in an absolute "kung-fooey ruthless" manner [in a good way]
I strongly believe that, reading code and reading good code is key to great programming
Hard to disagree.
Actually the qestion is pretty hard - becouse there is some alternatives to inheritance, such as composite reuse principle, so sometimes it's very hard to diside if inheritance is used in "kung-fooey ruthless" manner or there ware some better way to implement the same wich will make code esier to understand/test/make it lossely coupled and so on.
In my humble opinion Enterprise Library Application validation block whith it's Microsoft.Practices.EnterpriseLibrary.Validation.Validator class with all it's descendants
is a very good example of inheritance, becouse
concept of validation is easy to understand
there is good example how to find common in objects of with pretty different nature (i.e. OrCompositeValidator/DateTimeRangeValidator/ObjectCollectionValidator)
many of us tried to implement something more or less like this, so this background will give more quality for understanding
this is clear(for me, but I can be wrong:) that inheritance has no alternatives there
You can download source code from codeplex.
An example of good usage of inheritance would be the .NET framework classes. You can download the MONO project to gain access to some source code. If you want to better your code architecture, invest some time in studying architectural design patterns.
Here is a personal example where I've made use of inheritance to greatly benefit a development situation:
I needed to develop a asp.net (c#) form control set, which would allow both standard web forms (bunch of form fields with submit button), as well as a secure version which talks to a web service to submit the information over SSL.
Because of all of the similarities between the controls and concepts, I developed a number of classes:
BaseWebControl
custom base control class that inherits from System.Web.UI.WebControl class (part of .NET framework
has custom properties and methods that are used in our application by all custom controls (control state info, etc.)
BaseFormControl
inherits from BaseWebControl, gaining all of its underlying functionality
handles base form functionality, such as dynamically adding fieldsets, marking required fields, adding submit button, etc. etc.
contains a label and associated control index for easy lookups
marked as an abstract class, with abstract method called SubmitForm. This method is not defined on this class, however it is called by the submit button click event. This means that any specific form control class that inherits from this base class can implement the abstract SubmitForm functionality as needed.
EmailFormControl
Inherits from BaseFormControl, so it gains all underlying functionality above without any duplication
contains very little, except overrides the abstract method SubmitForm, and generates an email based on the form fields.
all other control functionality and event handling is dealt with by the base class. In the base class when the submit button is clicked and handled, it calls this specific implementation of SubmitForm
SecureFormControl
Again inherits from BaseFormControl, so it gains all underlying functionality above without any duplication
In its implementation of SubmitForm, it connects to a WCF web service and passes the information in over SSL.
no other functionality is required because base class handles the rest.
In stripped down code form, the general outline is as such:
public class BaseWebControl : System.Web.UI.WebControl
{
//base web control with application wide functionality built in
}
public abstract class BaseFormControl : BaseWebControl
{
//handles all 'common' form functionality
//...
//...
//event handler for submit button calls abstract method submit form,
//which must be implemented by each inheriting class
protected void btnSubmit_Click(object sender, EventArgs e)
{
SubmitForm();
}
protected abstract SubmitForm();
}
public class EmailFormControl : BaseFormControl
{
protected override SubmitForm()
{
//implement specific functionality to email form contents
}
}
public class SecureFormControl : BaseFormControl
{
protected override SubmitForm()
{
//connect to WCF web service and submit contents
}
}
As a result of the above, BaseFormControl has about 1000 lines of code in a whole bunch of methods, properties, etc. SecureFormControl and EmailFormControl each have about 40 lines. All other functionality is shared and controlled by the base class. This promotes:
maintainability
efficiency
flexibility
consistency
Now I can create any type of web form, such as DataBaseFormControl, etc. etc. very easily. I can add great new functionality to all forms by adding methods and properties to the base classes, etc.
And the list goes on.
Phew that was a lot of typing. Hope this helps give you a good example. This was one instance where I found inheritance to be a key success point in a project.
I agree with the recommendation to look at the .NET base class library, as it has excellent examples of abstraction via both inheritance and interfaces. The goal is to insulate consumer code from having to care about the details of a particular implementation. The WinForms designer works with Controls, but it has no idea what specific kinds of Controls will be implemented. It doesn't care, because inheritance abstracts away the unnecessary details. LINQ works similarly with IEnumerable; it doesn't really matter what's being enumerated, as there are algorithms you can write that work with anything enumerable. Both are excellent examples of abstraction used well.
I have a set of functions I want to be available to my web pages and user controls in my c# .net 3.5 web project. My standard approach for pages is to create a "base page" that extends the System.Web.UI.Page class and then have my pages inherit from this, rather than directly from the Page class.
I now want to expose some of these functions to my web controls (ascx) and web services. I can think of a number of ways to do this, but they seem a little clumsy and I think I'm missing a trick.
Is there an easy way to provide some common functions to both my pages, web services and controls using inheritance, or do I need to wrap these functions in a class that all of them can access?
An example to clarify:
I have a singleton that handles most functionality for my web application.
At the start of each request I want to check that the class exists in the web cache and initialise it if not.
Initially this was handled in a page base that the pages all used. Now I need to be able to access my singleton safely from services and controls, with the same checks. I have therefore extracted the checking and initialisation logic into another class, that then each of my base page, control and web service, all instantiate. Even with this model I have the same code repeated in 3 places (each of my base classes for controls, ws and pages), albeit not much code, this seems wrong too!
It works, but it seems clumsy...I look forward to you guys humbling me with your wisdom!
Sounds to mee like a case of aspect-oriented programming. .NET is ill equipped for this. I'm afraid that your solution is one of the best.
Alternatively perhaps you can move all or some of those functions to a static class/singleton and then use that class from your aspx/ascx/asmx? Not much in the way of inheritance, but at least less code duplication.
My solution to this is to put all the methods and functions I want to share in my base master page class. I then put an equivalent for each method and function in the user control base class as follows:
//Property in masterpage base
public string QsSearchTerm
{
get
{
if (!String.IsNullOrEmpty(Request.QueryString["q"]))
{
return Helpers.SanitiseString(Server.UrlDecode(Request.QueryString["q"]));
}
return String.Empty;
}
}
//Property in usercontrol base
public string QsSearchTerm
{
get
{
if (Page.Master is BaseMasterPage)
{
return ((BaseMasterPage)Page.Master).QsSearchTerm;
}
return string.Empty;
}
}
What this doesn't help with, is your code repetition with web service base classes. I would think that refactoring the above into a class with a constructor that accepts an HttpContext instance would be the way forward. You can then expose a singleton instance of this class in your base web service, master page, user control, page etc.
Hope this helps, but I too would be interested in hearing if there's a better way.
In your Singleton you could provide a Strategy interface to allow variations of the code depending on the configured environment. This would allow you to switch between web/windows/wcf...and so on.
I think using a BasePage is the right approach.
I have multiple base pages and custom user controls that load differently depending on which basepage is used by the current page.
In your custom user control you can use something like:
if (this.Page is BasePageName)
{
BasePageName bp = (BasePageName)this.Page;
bp.BasePageFunction();
}
No you can get ride of the repetitive code in the custom user control and just call it from the base page.
You can also have a hierarchy of inherited base pages depending on page functionality and needs. ie.) BasePageName2 : BasePageName