Concatenating string in Text or Label property - asp.net

How would you concatenate a string from a resource assembly to an asterisk(*) in the Text property in an asp:Label control?
For example:
<asp:Label ID="someLabel" ...
Text="<%$ ExternalAssembly|FileName, resourceName %>*" runat="server".../>
End result is to display 'Name*'
Thanks

Reference a server-side function to return the desired string.
I apolgize, but this will be in vb.net. However, it is minimal code so I don't think it will be too hard to translate into C# if that's what you need.
Steps
Create the ASP.NET tag for the label control.
Inside the text attribute, insert a data-binding expression for the function getAssembly() . Example: Text='<%# getAssembly("Fullname")%>' We will build this function in a moment. Also note that it accepts a parameter to identify what piece of information you need regarding the assembly. Another common mistake is not using single quotes for the inline expression (because double quotes will conflict with the string parameter).
Import the necessary namespaces System and System.Reflection into the code-behind.
Create the function getAssembly(ByVal InfoItem as String) in the code-behind (details for this function are below).
Add a line in the Sub Page_Load() to bind data to the assemblyLabel control when the page is loaded.
Here is the necessary code in detail for each step:
ASP.NET Tag
<asp:Label ID="assemblyLabel" runat="server" Text='<%# getAssembly("Fullname")%>'></asp:Label>
Function in the Code-Behind
Public Function getAssembly(ByVal InfoItem As String) As String
Dim a As AssemblyName = Assembly.GetExecutingAssembly.GetName()
Select Case InfoItem
Case "Name"
Return a.Name
Case "Fullname"
Return a.FullName
Case "Version"
Return a.Version.ToString
Case Else
Return ""
End Select
End Function
Necessary imports:
Imports System
Imports System.Reflection
Bind the data in Page_Load:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
assemblyLabel.DataBind()
End Sub
The entire code-behind...
Imports System
Imports System.Reflection
Public Class WebForm1
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
assemblyLabel.DataBind()
End Sub
Public Function getAssembly(ByVal InfoItem As String) As String
Dim a As AssemblyName = Assembly.GetExecutingAssembly.GetName()
Select Case InfoItem
Case "Name"
Return a.Name
Case "Fullname"
Return a.FullName
Case "Version"
Return a.Version.ToString
Case Else
Return ""
End Select
End Function
End Class

Related

Error attempting to override HtmlGenericControl in ASP.NET 4.5

I have the following class:
Public Class HtmlGenericSelfClosingTag
Inherits HtmlGenericControl
Public Sub New()
MyBase.New()
End Sub
Public Sub New(tag As String)
MyBase.New(tag)
End Sub
Public Shadows Property TagName As String
Get
Return MyBase.TagName
End Get
Set(value As String)
MyBase.TagName = value
End Set
End Property
Public Overrides ReadOnly Property Controls As ControlCollection
Get
Throw New Exception("HtmlGenericSelfClosingTag cannot have child controls.")
End Get
End Property
Public Overrides Property InnerHtml As String
Get
Return String.Empty
End Get
Set(value As String)
Throw New Exception("InnerHtml cannot be set on an HtmlGenericSelfClosingTag")
End Set
End Property
Public Overrides Property InnerText As String
Get
Return String.Empty
End Get
Set(value As String)
Throw New Exception("InnerText cannot be set on an HtmlGenericSelfClosingTag")
End Set
End Property
Public Overrides Sub RenderControl(writer As HtmlTextWriter)
MyBase.Render(writer)
writer.Write(HtmlTextWriter.TagLeftChar & Me.TagName)
Attributes.Render(writer)
writer.Write(HtmlTextWriter.SelfClosingTagEnd)
End Sub
End Class
I have declared the control as:
Protected WithEvents MyElement As HtmlGenericSelfClosingTag
I have the html tag defined as:
<HtmlGenericSelfClosingTag ID="MyElement" runat="server" />
I am getting the following error during page render:
The base class includes the field 'MyElement', but its type (MyClass.HtmlGenericSelfClosingTag) is not compatible with the type of control (System.Web.UI.HtmlControls.HtmlGenericControl).
I have searched DuckDuckGo (and, by extension, Google, etc) to find out what else I need to override to make my class compatible with the HtmlGenericControl class, but no dice. I have also checked the MSDN docs but no mention of override requirements. Any ideas?
I was able to resolve the issue by removing the <HtmlGenericSelfClosingTag ID="MyElement" runat="server" /> tag from the aspx file, and simply adding the control directly in code, as in:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Me.head.Controls.AddAt(0, BaseElement)
End Sub
And to avoid rendering the control twice, I modified the Render code:
Public Overrides Sub RenderControl(writer As HtmlTextWriter)
writer.Write(HtmlTextWriter.TagLeftChar & Me.TagName)
Attributes.Render(writer)
writer.Write(HtmlTextWriter.SelfClosingTagEnd)
End Sub

How to access controls and variables, across Class and Code-behind?

i have ASP.NET page, its code-behind, and a Class file:
Folder1/page.aspx (asp.net page), it contains a label:
<asp:Label runat="server" ID="Label1" Visible="false"></asp:Label>
Folder1/page.aspx.vb (code-behind), it calls connection.vb like this:
Dim x As New Connection
Protected Sub button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles button1.Click
x.checkusernameExists(TextBoxUsername.Text)
' I try to access `Boolean variable` Flag from Class file but I can't.
End Sub
App_Code/connection.vb (a class file that i created):
Public Class Connection
Public Sub checkusernameExists(ByVal username1 As String)
Dim flag as Boolean
' I try to access here `Label1.text` & `Label1.visible` to work on it but I can't.
End Sub
End Class
My Questions
1 - How can I access the Label1 from the ASP.NET page in Connection.vb?
2 - How can I access the Boolean variable from Connection.vb in page.aspx.vb (code behind)?
I am really stuck in this.
Thank you.
Use (public) properties or method parameters.
You have to ask yourself following: why should a class that is responsible for a connection(i assume to database) have access to your GUI at all? Don't hardlink different layers with each other, otherwise you won't be able to use them alone.
I would suggest to let the connection class do it's work and that is not to modify your frontend. Instead the controller (the aspx page) should manage it's GUI and call the connection class, using the return value to determine what to do next with the Label.
So return a Boolean to indicate if the user is valid:
Public Class Connection
Public Shared Function checkusernameExists(ByVal username1 As String)As Boolean
Dim userExists As Boolean
' acces db to check if the username exists '
Return userExists
End Sub
End Class
in your page:
Protected Sub button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles button1.Click
Dim userExists As Boolean = Connection.checkusernameExists(TextBoxUsername.Text)
Label1.Visible = userExists
If Label1.Visible Then Label1.Text = "Hello again " & TextBoxUsername.Text
End Sub
make flag as property and set this property in checkusernameExists function
Public Class Connection
Public Property Flag as Boolean
Public Sub checkusernameExists(ByVal username1 As String)
// set flag here
Flag = True // or whateever value returned from the database
' I try to access here `Label1.text` & `Label1.visible` to work on it but I can't.
End Sub
End Class
and access this instance level property in page.aspx.vb file
Dim x As New Connection
Protected Sub button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles button1.Click
x.checkusernameExists(TextBoxUsername.Text)
Label1.Visible= x.Flag;
' I try to access `Boolean variable` Flag from Class file but I can't.
End Sub
You can use Function to return value and pass label as parameter.
Public Function SaveChanges(ByRef Label1 As Label, ByVal username1 As String) As Boolean
{
Return True
}
It would be better if you pass the label properties to function instead of passing the object of label as it couple up two classes.

Object not queryable

I have a database "Pubs" with a table "authors". I have made a dbml file from the database by dragging over "authors".
Here is the "Default.aspx.vb"
Public Class _Default
Inherits System.Web.UI.Page
Dim author As Object
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim db As New PubsContext
Dim authors = From p In dbo.authors _
Select p
GridView1.DataSource = author
GridView1.DataBind()
End Sub
End Class
Here is the class for it: "Class1.vb"
Partial Public Class PubsContext
Dim authors As Object
Public Function GetProductsByCategory(ByVal id1 As Integer) As IEnumerable(Of authors)
Return From p In Me.authors _
Where p.au_id = id1 _
Select p
End Function
End Class
Error code:
"Expression of type 'Object' is not queryable. Make sure you are not missing an assembly reference and/or namespace import for the LINQ".
In references there is already a "System.Data.Linq". What should I do?
Well this is the problem:
Dim authors As Object
That's just an object. What does it mean to call Select, Where etc on that? Where are you even giving it a value? Work out what the type should really be, make sure you give it an appropriate value to start with, and you should be fine.
It's not clear why you're introducing your own authors field at all, to be honest - I'd expect the generated context to have an Authors property of type Table<Author> or something similar.
(I note that you're also trying to set GridView1.DataSource to author rather than authors, by the way... Why are you doing that? What value are you expecting the author field in _Default to have?)

Populate TextBox From Public Property From Code-Behind

I am trying to use a property from the code-behind to populate a textbox instead of using in the code-behind textbox.text=. I am using vb.net. Here is the code for the aspx page:
<asp:Content ID="Content2" ContentPlaceHolderID="MainContentPlaceHolder" runat="server">
<asp:TextBox runat="server" ID="roleTextBox" Text='<%# CurrentRole.Name%>'></asp:TextBox>
</asp:Content>
Here is the code behind code:
Imports Compass.UI.components
Imports Compass.Core.Domain
Imports Compass.Core.Domain.Model
Namespace app.administration.Roles
Partial Public Class edit
Inherits ClaimUnlockPage
Private _roleRepository As IRoleRepository
Private _roleId As Integer
Private _role As Role
Public Property CurrentRole() As Role
Get
Return _role
End Get
Set(ByVal value As Role)
_role = value
End Set
End Property
Public Property RoleRepository() As IRoleRepository
Get
Return _roleRepository
End Get
Set(ByVal value As IRoleRepository)
_roleRepository = value
End Set
End Property
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
LoadRole()
End Sub
Private Sub LoadRole()
_roleId = Config.RequestVal("id", Request)
_role = _roleRepository.GetById(_roleId)
End Sub
End Class
End Namespace
When I run the page the text box is empty.
I didn't see roleTextBox.text=value in your code! in LoadRole or anywhere.
And if you try to bind it, you need a static class for Role.
Just for testing try to add the following line in LoadRole
Private Sub LoadRole()
_roleId = Config.RequestVal("id", Request)
_role = _roleRepository.GetById(_roleId)
roleTextBox.text =CrrentRole.Name;
End Sub
if the roleTextBox is still empty then the CurrentRole.Name is empty.
As far as I know you can't bind a property of a control like this (I wish you could but I've never been able to figure out or find an example how to). The way I've always done it is create a protected function to return e.g.
Protected Function GetCurrentRoleName() As String
Return CurrentRole.Name
End Function
And in your markup bind like so
Text='<%# GetCurrentRoleName() %>'
You have to DataBind the container-control which contains your Textbox(f.e. a GridView,UserControl,etc.). So at least your aspx-page must be databound.
"When called on a server control, this method resolves all data-binding expressions in the server control and in any of its child controls."
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Me.CurrentRole = New Role("Administrator")
Me.DataBind() '!!!!!!!
End Sub
Private _currentRole As Role
Protected Property CurrentRole() As Role
Get
Return _currentRole
End Get
Set(ByVal value As Role)
_currentRole = value
End Set
End Property
Public Class Role
Public Sub New(ByVal name As String)
Me.Name = name
End Sub
Public Name As String
End Class
Then you can use your aspx-code to set the TextBox'-text property.

ASP.NET UserControl Uri property

I want to pass a property of the type System.Uri to an WebControl from inside an aspx page.
Is it possible to pass the property like that:
<MyUserControl id="myusercontrol" runat="server">
<MyUrlProperty>
<System.Uri>http://myurl.com/</System.Uri>
</MyUrlProperty>
</MyUserControl>
instead of:
<MyUserControl id="myusercontrol" runat="server" MyUrlProperty="http://myurl.com/" />
which can't be casted from System.String to System.Uri
EDIT
The control is a sealed class and I don't want to modify it or write an own control. The goal is to set the url-property which is of the type System.Uri and not System.String.
To answer your actual question: no, you can't change the way you pass in the value of a property, like your example shows, without changing the code behind how that property is defined. Now on to your actual issue...
I didn't have any problem passing a string into a property of type URI on my user control and having it be auto converted from string to uri. Are you sure that the Uri you are passing in is valid? If the string you are passing in, like in a databinding scenario, wasn't properly formatted I could see this issue arising maybe.
Sample Code I used to test:
<uc1:WebUserControl ID="WebUserControl1" runat="server" MyUrlProperty="http://www.example.com" />
Code Behind:
Partial Class WebUserControl
Inherits System.Web.UI.UserControl
Public Property MyUrlProperty() As Uri
Get
Dim o As Object = ViewState("m")
If o IsNot Nothing Then
Return DirectCast(o, Uri)
Else
Return Nothing
End If
End Get
Set(ByVal value As Uri)
ViewState("m") = value
End Set
End Property
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Response.Write(MyUrlProperty)
End Sub
End Class
--Peter

Resources