Cannot add property to INamingContainer in Web User Control - asp.net

The code I have (below) works except for when I add the ref="abc" to the TemplateItem tag. When it is included I get this error:
Property 'TemplateItem' does not have a property named 'ref'
How do I resolve this issue?
Default.aspx
<%# Register Src="~/message.ascx" TagName="Message" TagPrefix="uc" %>
<uc:Message ID="msg" runat="server" abc="123" >
<TemplateItem ref="abc">Hi</TemplateItem>
</uc:Message>
message.ascx
<asp:placeholder runat="server" id="PlaceHolder1" />
message.ascx.vb
Partial Class message
Inherits System.Web.UI.UserControl
Public Property abc() As String
Sub Page_Init()
If TemplateItem IsNot Nothing Then
TemplateItem.InstantiateIn(PlaceHolder1)
End If
End Sub
Private m_TemplateItem As ITemplate = Nothing
<TemplateContainer(GetType(TemplateItem2))> _
Public Property TemplateItem() As ITemplate
Get
Return m_TemplateItem
End Get
Set(ByVal value As ITemplate)
m_TemplateItem = value
End Set
End Property
Public Class TemplateItem2
Inherits Control
Implements INamingContainer
Public Property ref() As String
End Class
End Class

Are you sure it should be:
Public Class TemplateItem2
at the bottom there, and not just the following?:
Public Class TemplateItem
(If you just want a different name from the property, maybe something like TemplateItemImplementation or just TemplateItemImpl would be more clear?)
Also, I'm not sure how this works:
TemplateItem.InstantiateIn(PlaceHolder1)
The MSDN page on CompiledTemplate.InstantiateIn() says: This API supports the .NET Framework infrastructure and is not intended to be used directly from your code. I guess this is a sidenote though, and I'm assuming you've gotten it to work the way you want...
I think the problem is related to the instantiation of TemplateItem in that line though; I can not see how TemplateItem2 (which contains the property ref()) is related to ITemplateItem. Maybe you just need to make TemplateItem2 also implement ITemplateItem?
Another thing to try is to make ref() a property of ITemplateItem, if possible. Maybe that Interface becomes the Type of <TemplateItem />, which would explain why it does not contain the property Ref?.
(That is assuming the type is specified by the return type of the property TemplateItem()).

Related

Can you create and call statics inside a module in VB.Net

My module is a page directory to strongly type pages in a large ASP.Net webforms application using VB.Net.
Public Module PageDirectory
Public Module Sub
Private _subDirectory As String = "/sub/"
Public ReadOnly Property MyPage As String
Get
Return _subDirectory + "mypage.aspx"
End Get
End Property
End Module
End Module
I want to declare it like this on a page Response.Redirect(PageDirectory.Sub.MyPage)
but i can't seem to get a module inside a module. My assumption was that a module is the equivalent to a c# static.
Module already says that everything in the class is static, that's why you can't have modules inside of modules.
If you want specific class member be static, you use "shared" on that class member.
https://msdn.microsoft.com/en-us/library/7825002w(v=vs.90).aspx
I think I've worked out the answer. But unsure if its the 'right' way to do this.
Public Module PageDirectory
Private _subDirectory As String = "/sub/"
Public Structure SubStruct
Public Shared ReadOnly Property MyPage As String
Get
Return _subDirectory + "mypage.aspx"
End Get
End Property
End Module
End Module

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

ASP: passing values between web forms

Im trying to pass a value of a date control from form1 to form2.
on form 1.aspx.vb:
Public ReadOnly Property Property1() As Date
Get
Return StartDate.SelectedDate
End Get
End Property
On Form2.aspx:
<%# PreviousPageType VirtualPath="~/form1.aspx" %>
On form2.aspx.vb:
Label14.Text = PreviousPage.Property1
when I run it, the compiler gives me an error:
"Object reference not set to an instance of an object."
with marking in red:
Label14.Text = PreviousPage.Property1
Tried to assign the property to a string, it did not work either.
Any suggestions ???
Regards.
When the Form2.aspx page is accessed directly without cross-page posting, then PreviousPage property is null. You should add this check before retrieving value of Property1:
if (PreviousPage != null && PreviousPage.IsCrossPagePostBack) {
Label14.Text = PreviousPage.Property1
}
Using PreviousPageType VirtualPath="~/form1.aspx" directive is a little bit dangerous when other page than Form1.aspx do cross-page post to Form2. PreviousPage property throws InvalidCastException (it expects Form1 page but it gets something else).
For more information see: http://msdn.microsoft.com/en-us/library/ms178139.aspx.
I think Startdate isn't declared / initialized, how do you set the data for this readonly property?

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...:)

Extend System.Web.HttpContext.User

I would like to extend the System.Web.HttpContext.User object (ASP.NET/VB.NET) so that it contains other fields besides just Name. I understand I can create an object that inherits the System.Security.Principal.GenericPrincipal class, but how do I store that in the Current.User object in a usable fashion. ie, I can do something like Current.User.UserID.
So far to achieve this I've created a kludgy workaround by using | delimited strings in the User.Name property and then splitting them, but it's getting kind of ridiculous.
Any suggestions?
Thanks!
EDIT: I have tried the following to no avail:
Imports System.Security.Principal
Public Class CurrentUser : Inherits GenericPrincipal
Private _totalpoints As Integer
Private _sentencecount As Integer
Private _probationuntil As DateTime
Public ReadOnly Property TotalPoints() As Integer
Get
Return _totalpoints
End Get
End Property
Public ReadOnly Property SentenceCount() As Integer
Get
Return _sentencecount
End Get
End Property
Public ReadOnly Property ProbationUntil() As DateTime
Get
Return _probationuntil
End Get
End Property
Public Sub New(ByVal principle As IIdentity, ByVal roles() As String, _
ByVal points As Integer, ByVal sentences As Integer, ByVal probationTil As DateTime)
MyBase.New(principle, roles)
_totalpoints = points
_sentencecount = sentences
_probationuntil = FixDBNull(probationTil)
End Sub
End Class
setting the object in my Global.asax Application_AuthenticateRequest function like so:
HttpContext.Current.User = New CurrentUser(User, userRoles, _
points, sentenceCount, probationUntil)
with a direct cast wherever the object is needed like so:
Dim thisUser As CurrentUser = DirectCast(Current.User, CurrentUser)
i also tried CType and it didn't work... my error is
[InvalidCastException: Unable to cast object of type 'System.Security.Principal.GenericPrincipal' to type 'myProject.CurrentUser'.]
i'm losing my mind here ... :( thanks guys...
anyone?
You can create your own Principal class with the required properties, that inherits from a Generic Principal, and then set the User property of your Current Context to be the a user of that type.
The example below is for ASP.Net MVC but a similar approach could be used with webforms.
You can do this in the PostAuthenticateRequest after a user is authenticated (in the Global.asax)
private void MvcApplication_PostAuthenticateRequest(object sender, EventArgs e)
{
SomePrincipal newUser = new SomePrincipal(User.Identity, tmpRoles);
senderRef.Context.User = newUser;
System.Threading.Thread.CurrentPrincipal = newUser;
}
You could then add a property or method in a base class of your page (or controller) for example that to wrap and type the Context.User principal to your Principal type and make sure you call it rather than calling the one on the HttpContext.
There are probably other solutions too!
Would this approach work for you? It looks a little involved but it really doesn't take too long to setup:
Create a 'base' class of your own, and have your pages inherit from that. For example, create a base class called 'BasePage' which inherits from System.Web.UI.Page.
Have your ASP.net pages inherit from your new BasePage class.
In the BasePage class, you can have a public property which contains the extra fields you want to store for your user (eg. BasePage.FirstName, BasePage.LastName). Better still, create a User object containing the extra fields, and expose that via BasePage, eg. "BasePage.Customer". This keeps things tidy if you plan to extend BasePage later.
You can then override the OnInit() of the base class to check for HTTPContext.Current.User.Name property, and fetch the necessary info from your DB to initialise your custom properties.
You can modify the code so that it won't need to hit the database each time the page is refreshed by using ControlState to check whether the custom fields have values before populating them again from the database.
Hope this helps...
Richard.

Resources