Generics on ASP.NET page Class - asp.net

I want to implement Generics in my Page Class like :
Public Class MyClass(Of TheClass)
Inherits System.Web.UI.Page
But for this to work, I need to be able to instantiate the Class (with the correct Generic Class Type) and load the page, instead of a regular Response.Redirect. Is there a way to do this ?

I'm not sure to fully understand what you want to do.
If you want something like a generic Page, you can use a generic BasePage and put your generic methods into that BasePage:
Partial Public Class MyPage
Inherits MyGenericBasePage(Of MyType)
End Class
Public Class MyGenericBasePage(Of T As New)
Inherits System.Web.UI.Page
Public Function MyGenericMethod() As T
Return New T()
End Function
End Class
Public Class MyType
End Class

The answer that says to derive a type from the generic type is a good one. However, if your solution involves grabbing a page based upon a type determined at runtime then you should be able to handle the PreRequestHandlerExecute event on the current HttpApplication.
This event is called just before a Request is forwarded to a Handler, so I believe you can inject your page into the HttpContext.Current.Handler property. Then you can create the page however you wish.

Related

How can I run a method every page load in MVC3?

With WebForms, if I wanted to run a method on every page load, then I would call this method in the Page_Load() method of the main Master Page.
Is there an alternative, perhaps better solution, when using MVC3?
you could create a class base controller
public class BaseController : Controller
{
public BaseController()
{
// your code here
}
}
and let every new controller of yours impelement the base controller like
public class MyController: BaseController
also i have found the basecontroller very usefull to store other functions i need a lot in other controllers
I think the most appropriate way to do this in MVC is with filters
MSDN provides a good description of them, and there are dozens of articles and explanatins about them on the net, such as this one
EDIT
This sample is even better: It provides a simple action filter, which is then registered in global.asax, and executed on every request, before the actual Action in the relevan controller executes. Such concept allows you to access the request object, and modify whatever you want before the actual controller is executing.
You could put the code in the constructor of the controller.
Like this:
public class FooController : Controller
{
public FooController()
{
doThings();
}

User Control to Excute Page Class Method (Dynamicly)

I have many aspx pages which inherits a base Class.
base class has a method name "GetGroupID", This method returns different data depends which page i am on, now few pages need to override this method (which is fine).
Problem:
I have user control which is placed in almost all pages, now this user control Accessess GetGroupID method from page base class, which is fine as long as i know page class name, since I have so many pages, one base class and one user control...it would be niceif I can get Page Class name from UserControl and execute the base method dynamically.
Curreny I have following code which works within UserControl
Dim c As homepage = CType(Me.Page, homepage)
Call c.getGroupID
However in above example I know the Page Class name (homepage), but lets say i am on a different page which has a classname "portal", it would be impossible for me to keep track of so many pages.
I would like to excute the method in base class within user control, and I would like to override this method for certain pages.
please advise.
You could let the base-page implement a custom interface, for example IGroupable with a method GetgroupId. Then you only have to know in the UserControl that it's Page is IGroupable(either directly or through inheritance) and you know for sure that it has a method GetgroupId.
Public Interface IGroupable
Function GetGroupId() As Int32
End Interface
Class BasePage
Inherits Page
Implements IGroupable
Public Overridable Function GetGroupId() As Integer Implements IGroupable.GetGroupId
Return 1
End Function
End Class
Class ChildPage
Inherits BasePage
' default implementation of GetGroupId from base page '
End Class
Class SpecialPage
Inherits BasePage
' override it here since it has a different implementation than in the base page '
Public Overrides Function GetGroupId() As Integer
Return 2
End Function
End Class
You get the id in the UserControl in this way:
Class UserControl1
Inherits UserControl
Dim id As Int32 = DirectCast(Me.Page, IGroupable).GetGroupId()
End Class

where can i find in reflector the initiations of a Page?

if i have
public partial class MyLittlePage: System.Web.UI.Page
{...
and i have overriden for example the OnLoad...
my question : where in the code(reflector) does the compiler creates this :
System.Web.UI.Page= new MyLittlePage(); ??
i want to see all the chain of the polymorphic affect..
(or in other words : i'm overloading OnLoad for what virtual function ? )
i know the virtual function is on the Control Page
but i wasn't able to see the Polymorphic creation pattern of :
Class1 x = new Class2();
In the depths of ASP.NET 4...
HttpApplication uses the nested MaterializeHandlerExecutionStep class to populate HttpContext.Handler from an IHttpHandlerFactory.
Through a layer of caching, requests for Page (and all types implementing IHttpHandler) use an instance of System.Web.Configuration.HandlerFactoryWrapper.
HandlerFactoryWrapper.GetHandler() in turn calls HttpRuntime.CreateNonPublicInstance(), which uses Activator.CreateInstance() to instantiate the class.

access a public function in .ascx

how can i access a public function in an .ascx file using C#?
Thanks
If the function is not static you will need to first obtain an instance of the class containing the function and then invoke the function on this instance. For example:
<%
// obtain an instance of the type containing the function
Foo instance = new Foo();
// invoke the function on this instance
string result = instance.Bar();
%>
Obviously it would be better to do this in the code behind file instead of polluting your markup.
Like other public functions in .NET Framework - via object reference. But sometimes Visual Studio doesn't automatically see your User Control's public members. Try to rebuild your user control and the site if IntelliSense window doesn't show it to you.
Where are you calling the function from? The containing page? Masterpage? Parent control? The control itself? Regardless, you'll need to somehow obtain a reference to the control instance (unless the method is static) in order to invoke this method. And the type of your reference must match that of the class that defines the method.
Edit:
MyControl myControl = (MyControl)Page.FindControl("Id_Of_The_Control");
if (myControl != null)
{
myControl.TheMethod();
}
if you don't want to add your ascx control into a placeholder programmatically, just implement IAttributeAccessor and IUserControlDesignerAccessor interfaces to your user control class like;
public partial class yourascxclassname: System.Web.UI.UserControl, IAttributeAccessor, IUserControlDesignerAccessor
you can access only public members of your ascx control.

fluent nhibernate Exception error

am trying to implement fluent nhibernate in MVC project...there were no build errors... but when i run the project i get this exception
System.Xml.Schema.XmlSchemaValidationException: The element 'class' in namespace 'urn:nhibernate-mapping-2.2' has incomplete content. List of possible elements expected: 'meta, subselect, cache, synchronize, comment, tuplizer, id, composite-id' in namespace 'urn:nhibernate-mapping-2.2'.
have no idea what am doing wrong here... the following is the code for opening session factory...
Private Function CreateSessionFactory() As ISessionFactory
Dim sessionFactoryObject As ISessionFactory
sessionFactoryObject = Fluently.Configure().Database(FluentNHibernate.Cfg.Db.MsSqlConfiguration.MsSql2005.ConnectionString("Data Source=.\sqlexpress;Initial Catalog=Designs;User ID=sa;Password=root")).Mappings(Function(x) x.FluentMappings.Add(GetType(DesignMap))).BuildSessionFactory()
Return sessionFactoryObject
End Function
this is really driving me nuts....thanks in advance...:)
update-the mappings
the design table map
Public Class DesignMap
Inherits ClassMap(Of Design)
Public Sub DesignMap()
Table("DesignList")
Id(Function(x) x.DesignId)
Map(Function(x) x.DesignType)
References(Function(x) x.Designer, "DesignerId")
End Sub
End Class
the designer table map
Public Class DesignerMap
Inherits ClassMap(Of Designer)
Public Sub DesignerMap()
Table("DesignerList")
Id(Function(x) x.DesignerId)
Map(Function(x) x.DesignerName)
Map(Function(x) x.DesignerCompany)
HasMany(Function(x) x.DesignersDesigns)
End Sub
End Class
new edit-- the entity property looks like this
Public Overridable Property Name() As String
Get
Return _name
End Get
Protected Set(ByVal value As String)
_name = value
End Set
End Property
am i going the right way..?
I'm not quite sure as the mappings seem ok. I can see one error tough, you have only mapped one of your classes:
.Mappings(Function(x) x.FluentMappings.Add(GetType(DesignMap)))
That should not cause this type of error tough. If you add both your mappings and call the method .ExportTo(#"C:\your\export\path") you will get the actual xml mappings. This way it's easier to see the error. You can do that like this:
.Mappings(Function(x) x.FluentMappings.Add(GetType(DesignMap)).Add(GetType(DesignerMap
).ExportTo(#"C:\your\export\path"))
You can also use the method AddFromAssemblyOf (or some other. There is a few choices) if you don't want to add the mappings one by one.
Try exporting the mappings and see if you can find any error. Or you can post the xml mappings and someone else might find something.
There are several things that can cause this. When using automappings, you will get this if you incorrectly specify the assemblies and namespaces to look in. Other things (more likely in your case) that could cause it, are entity properties that aren't marked as public virtual, having an entity constructor with arguments, but neglecting to make a default constructor, or inheriting your entities from a base class.
I would probably first check to make sure all of your entity properties are "public virtual".
found the problem...the constructor for the map was wrong...it should be like this...
Public Class DesignMap
Inherits ClassMap(Of Design)
Public Sub New()
Table("DesignList")
Id(Function(x) x.DesignId)
Map(Function(x) x.DesignType)
References(Function(x) x.Designer, "DesignerId")
End Sub
End Class
problems of working in both C# and vb.net at the same time i guess..!!
and "Matthew Talbert" was correct...making all the properties Overrideable is important..
thanks guys...:)

Resources