How to code reuse apsx? - c#

I know in C# I can make a factory but I don't not know how to reuse code in aspx. My code was originally purposed for ARList only, but now has IcnList. I thought about making a switch statement but isn't there something better to code?
The Function
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
ARExtractionController arController = new ARExtractionController();
Dictionary<int, string> ARDictionary = arController.GetTickets();
List<int> sortedARList = new List<int>();
foreach (KeyValuePair<int, string> kv in ARDictionary)
{
sortedARList.Add(kv.Key);
}
sortedARList.Sort();
sortedARList.Reverse();
ARList.DataSource = sortedARList;
ARList.DataBind();
ARList.Items.Insert(0, " ");
ARList.AutoPostBack = true;
}
}

If you just want to be able to reuse the code, add a class to your project for utility methods and dump it in there for both pages to use.
If you're trying to reuse code with and associated UI, look into User Controls (ascx files) which allow you to do just that.
It isn't clear which is right for you from the question.

In TicketExtractionWeb, create a BasePage class.
BasePage.cs:
public class BasePage : System.Web.UI.Page
{
// Add methods that are used on all your pages in here.
protected DateTime GetCurrentDate()
{
return DateTime.Now;
}
}
And a page (we'll call it MyPage):
public class MyPage : BasePage
{
protected Page_Load(object sender, EventArgs e)
{
var currentDate = this.GetCurrentDate();
}
}
So when you create another aspx page, it will default to:
public class MyNewPage : System.Web.UI.Page
{
// ...
}
Just change : System.Web.UI.Page to : BasePage

You should be able to inherit from a single page to reuse the code.
Top of aspx file:
<%# Page Language="C#" AutoEventWireup="true" Inherits="MyNamespace.CommonCode" %>

If you want to reuse html , please use a user control file (.ascx) , which can be reused muliple times
when do you need .ascx files and how would you use them?

Related

Global objects in C# ASP.Net - always null when read back

In an ASP.Net project, using C#, I have a class (PlcComms.cs) for talking to a Controller (a PLC).
I want the one class object to be globally available, for each web page in my project.
I see from reading various forum posts that I should be able to create a public static object of my class type, i.e. PlcComms, in Global.asax.cs, or in a class in the App_Code folder. I've tried both and I write to the object ok, but when I go to read from it (from a timer in an update panel on the home web page) then it always read back as null.
I'm at a loss to know what to do at this point. can anyone help?
Currently, this is a class I have in the App_Code folder...
namespace SpearheadWeb
{
public static class AppGlobal
{
public static SpearheadWeb.PlcComms PlcCommsObject { get; set; }
}
}
this I have on my web page - it seems to create the object OK...
namespace SpearheadWeb
{
public partial class _Default : Page
{
private PlcComms CurrentPLC;
//some other here including ComPorts
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
try
{
//some settings reading and setup here
CurrentPLC = new PlcComms(Global.CommsSettings.CpuType1,Global.CommsSettings.Network1,ComPorts[0], Global.CommsSettings.IPAddress1, Global.CommsSettings.Path1,UpdatePanel.Controls[0].Controls, 1, Global.CommsSettings.MsUpdate1);
AppGlobal.PlcCommsObject = CurrentPLC;
but in my timer (the timer within an updatepanel) PLCComms1 is always null here...
protected void TimerUpdate_Tick(object sender, EventArgs e)
{
PlcComms PLCComms1 = AppGlobal.PlcCommsObject;

C# - Easy way to execute code in all pages in the Page_Load method

I'm looking for a way to add some code to execute in all Page_Load events on all pages of my web application, without have to write it in all the pages.
The code must execute before the Page_Load methods on the pages.
Thanks for the attention.
You can create one Class let say BasePage.cs, and here you will have one virtual method Page_Load:
public class BasePage: System.Web.UI.Page
{
protected virtual void Page_Load(object sender, EventArgs e)
{
//Some logic here that you want to execute for all pages
}
}
Then, in every page where you want to execute this code on PageLoad, make that page to inherit from BasePage and override the PageLoad method, like this:
in file somePage.aspx.cs do this:
public partial class somePage : BasePage
{
protected override void Page_Load(object sender, EventArgs e)
{
base.Page_Load(sender, e); //This line will execute page load from BasePage class
//The rest of code you want to execute on this page load
}
}
You could create a master page, set all the pages you want the code to be executed as "childs" of your master page, and them put the code you want to be executed on the Page_Load event of your master page.
To see how master pages work: http://msdn.microsoft.com/en-us/library/ie/wtxbf3hh.aspx

Calling a Web Method from ASPX Code Behind

I'm trying to figure out a way that I can call a Web Method (located as a public static method in the code behind of an aspx page) from another ASPX Code Behind page.
This is the code behind of Page A.aspx
public partial class PageA : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// other code not relevant is here
}
[WebMethod(true)]
public static string GetStringInfo()
{
// do some stuff here to build my string
// return string
}
}
On page B, I need to be able to call GetStringInfo() during page load or some other event to get the information. the GetStringInfo() is fairly complex and for reasons outside of my control, can't be moved elsewhere or rebuilt presently.
How can I consume the web method above from another page's code behind?
I've tried instantiating a copy of the other page (PageB), such as:
public partial class PageB : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
PageA page = new PageA();
page.GetStringInfo();
}
}
The problem here is since it's dynamically compiled, I don't have an easy namespace to reference and access. I've tried adding one, and it ignores it.
This project is on .net 3.5, C#, and is a web site project (not a web application).
Any help is appreciated!
If the GetStringInfo method is static you don't need an instance of PageA to invoke it:
public partial class PageB : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string info = PageA.GetStringInfo();
}
}

How to handle master page button event in content page?

There's more than question and article about the same exact question but I have a couple more related questions and was hoping to get some answers.
I've heard of two approaches to find the button and add the handler or use an interface (Check both approaches from here) .. Which one do you suggest ?
If you could please illustrate the 'Interface' option with some code and where to class the interface file cause it's not readable in the page when I try to inherit it!
Second aproach is IMO better. The first choice couples a page to the specific master page, and it is not nice.
All files are placed in the same folder.
IPageInterface.cs:
namespace CallFromMasterPage
{
public interface IPageInterface
{
void DoSomeAction();
}
}
Default.aspx.cs:
namespace CallFromMasterPage
{
public partial class Default : System.Web.UI.Page, IPageInterface
{
public void DoSomeAction()
{
throw new NotImplementedException();
}
}
}
Site.Master.cs:
namespace CallFromMasterPage
{
public partial class SiteMaster : System.Web.UI.MasterPage
{
protected void Button1_Click(object sender, EventArgs e)
{
IPageInterface pageInterface = Page as IPageInterface;
if (pageInterface != null)
{
pageInterface.DoSomeAction();
}
}
}
}
There are other approaches. E.g. you can publish an event via event broker.
See From My Openion it will be best if you make use of event handlers...and even with the custom delegate..
like this
public delegate ReturnType MasterPageButtonHandler(CustomEventArgs ObjPriargs);
public event MasterPageButtonHandler MasterPagebuttonClick;
.
.
.
.
Button.click+=new EventHandler(Button1_Click);
.
.
.
protected void Button1_Click(Object sender,EventArgs e)
{
if(MasterPagebuttonClick!=null)
{
CustomEventArgs ObjPriargs=new CustomEventArgs();
ObjPriargs.Property1=SomeValu1;
ObjPriargs.Property2=SomeValu2;
MasterPagebuttonClick.Invoke(ObjPriargs);
}
}
.
.
.
public class CustomEventArgs
{
Public DataType Property1{get;set;}
Public DataType Property2{get;set;}
Public DataType Property3{get;set;}
}
.
.
.
// Now in your aspx Page
MyMaster m=Page.Master as MyMaster;
m.MasterPagebuttonClick+=new MasterPageButtonHandler(MasterPageHandler_Click);
.
.
.
protected void MasterPageHandler_Click(CustomEventArgs ObjPriargs)
{
//You code/////
}
going through this manner give some flexibility like in case if in future you want to pass some data tour content page when clicked..its easily possible.
I have a calendar in my MasterPage, but I need to use this date to bind a datagrid in a ContentPage.
MasterPage html:
<asp:Calendar ID="calAgenda" DefaultView="Days" Format="dd/MM/yyyy" runat="server" BackColor="White" CssClass="templeteCalendar" Visible="false" OnSelectionChanged="calAgenda_SelectionChanged"></asp:Calendar>
ContentPage html:
<asp:TextBox runat="server" ID="txtFechaBusqueda" CssClass="form-control templeteLabel" MaxLength="10" />
MasterPage C# Code:
protected void calAgenda_SelectionChanged(object sender, EventArgs e)
{
TextBox txtCalendarDate = (TextBox)ContentPlaceHolder1.FindControl("txtFechaBusqueda");
txtCalendarDate.Text = calAgenda.SelectedDate.ToString().Substring(0, 10);
}
Here We have use a EventHandler in the ContentPage to catch the event click in the MaserPage.
ContentPage C# Code:
Calendar btnCalendar = Master.FindControl("calAgenda") as Calendar;
btnCalendar.SelectionChanged += new EventHandler(btnCalendar_Click);
Then We need to define the btnCalendar_Click function.
protected void btnCalendar_Click(object sender, EventArgs e)
{
DoSomething();
}

ASP.NET: Call function in MasterPage through UserControl

Calling a function from the MasterPage in a Page is quite straigt forward but how do I call it for a UserControl:
Adding <%# MasterType VirtualPath="~/MasterPage.master" %>, doesn't work on UserControls.
So this.Page.Master.MyFunction() fails :(
You have to cast the this.Page.Master first as the Master property of the Page is of type System.Web.UI.MasterPage.
e.g.
((MyMaster)this.Page.Master).MyFunction();
You could check the type of the underlying master page by adding a property to the code behind of the user control:
public string MType
{
get { return this.Page.Master.GetType().FullName; }
}
and print the result out in the User control markup, e.g. add this line to make it print out as a comment in the source code:
<!-- <%= MType %> //-->
Niels,
Leverage reflection (as suggested by JDunkerley) is one approach to the problem. Another you might consider is implementing an interface:
Create an interface that includes your method.
Implement the interface in your master page
From your control, reference this.Page.Master via the interface type.
Call your method.
This is a better OO approach, leads to less coupling, and will certainly perform better than runtime reflection.
I hope this helps!
You are couppling your code very thighly if you call a function on the masterpage from within your user control.
The Control can only be used on pages that are based on that master. I think this is usually a bad design, and it will violate at least the law of demeter.
What exactly do you want to accomplish in your control?
JDunkerley has it right. But allow me to explain how to decouple it using MVP so you can work toward avoiding the design issue Heiko Hatzfeld is talking about.
Basically, implement the MVP pattern for both your control and your master page. See here for instructions on how to do that. Declare the method you want to call in the master's interface (IMasterView). Next create a class that will control the relationship between the two components; we'll call it the PageController class. Place an instance of this class in request state for each request by adding the following line to global.asax.cs:
/* global.asax.cs */
protected void Application_BeginRequest(object sender, EventArgs e)
{
// ...
HttpContext.Current.Items["Controller"] = new PageController();
// ...
}
You can then access this instance from each of the presenters (master and control) via the following line of code:
var controller = HttpContext.Current.Items["Controller"] as PageController;
You can then implement an event or some other mechanism to allow the control to invoke the method on the master in a decoupled manner through this shared object. For example:
/* PageController.cs */
public event EventHandler SomeEvent;
protected virtual void OnSomeEvent(EventArgs e)
{
Debug.Assert(null != e);
var handler = this.SomeEvent;
if (null != handler)
handler(this, e);
}
public void FireSomeEvent()
{
this.OnSomeEvent(EventArgs.Empty);
}
/* ControlPresenter.cs */
public ControlPresenter(IControlView view)
: base()
{
view.EventFired += (sender, e) =>
{
var controller = HttpContext.Current.Items["Controller"] as PageController;
controller.FireSomeEvent();
};
}
/* MasterPresenter.cs */
public MasterPresenter (IMasterView view)
: base()
{
var controller = HttpContext.Current.Items["Controller"] as PageController;
controller.SomeEvent += (sender, e) => view.MyFunction();
}
Make sure the "EventFired" event is declared in your control's interface (IControlView) and implemented in the control. Then all you have to do to affect the master (call its method), is fire this event and the MVP + the PageContoller will take care of the rest.
Cheers
I couldn't get the above answers to work, so here is what worked for me:
You want to reference a master page property from a user control.
Firstly, your master page will have a public property like so :
public string BodyClass
{
set
{
this.masterBody.Attributes.Add("class", value);
}
}
Now add a reference to the master page in the user control ASCX file like so :
<%# Register Src="~/Source/MasterPages/Main.master" TagPrefix="MSTR" TagName="MasterPage" %>
Then in the code behind (C# in my case) you have this code :
Main masterPage = (Main)this.Page.Master;
masterPage.BodyClass = "container";
Without the reference to the master page above your user control will not be able to find the master page class.

Categories