Declaring a public variable - asp.net

When I try to move 'UserName' from local scope 'dim' to public, I get 'Object reference not set to an instance of an object.' What is causing this?
Going from this:
Dim UserName As TextBox = DirectCast(LoginUser.FindControl("UserName"), TextBox)
to this:
Public UserName As TextBox = DirectCast(LoginUser.FindControl("UserName"), TextBox)
Then accessing variable like this:
If (Request.Cookies("Username") IsNot Nothing) Then
UserName.Text() = Request.Cookies("Username").Value.ToString()
End If

You have 3 potential problems with your code:
It should be UserName.Text i.e. not .Text()
Request.Cookies("Username").Value.ToString()
If "username" is not found in the cookie collection you will get a
Value of nothing. Then you call ToString on nothing which
gives you Object Reference error.
Make sure that the UserName TextBox is initalized and not nothing when
you try to access it.

Related

Validation Summary

I use a login entrance in my Asp.Net project
And I use validationSummary for User Name and password.
Everything goes well but.
What I want is to know if the ValidationSummary has errors to show me or not before the appearance of the errors window
I use vb.net to build the project
I don't have any code to show. And also I can't find anything relative in on the Internet to assist me on this issue.
You are probably using the ValidationSummary method in your Razor views, which - as per MSDN
Returns an unordered list (ul element) of validation messages in the ModelStateDictionary object.
So, if you want to know if there will be any errors shown by the ValidationSummary method, you can check this ModelStateDictionary in your controller before delivering your response to the browser. Doing this is described i.e. here (in C#).
In your controller method you can access ModelState.IsValid if you want to know if there are any errors which will be displayed.
This does directly answer your question, but this might not be the optimal way to achieve what you want when looking at the bigger picture. If you want to i.e. do something special if the login fails in your controller you should check directly if the login failed, not if some other method added model errors. To provide an answer, which might be more on point, you need to clarify your question and add more details about what you specifically want to do and possibly add some of your code too.
The idea to use the code I post is finally correct.
Public Sub IsGroupValid(ByVal sValidationGroup As String, ByVal sender As Object, ByVal e As EventArgs)
For Each validator As BaseValidator In Validators
If validator.ValidationGroup = sValidationGroup Then
Dim fValid As Boolean = validator.IsValid
Dim CtrlToValidate As String = validator.ControlToValidate
validator.DataBind()
If Not fValid And CtrlToValidate = ServerHandler.UName Then
validator.Validate()
fValid = validator.IsValid
ModelState.AddModelError(CtrlToValidate, validator.ID)
ElseIf Not fValid And CtrlToValidate = "Password" And validator.ID = ServerHandler.PwdRq Then
validator.Validate()
fValid = validator.IsValid
ModelState.AddModelError(CtrlToValidate, validator.ID)
ElseIf Not fValid And CtrlToValidate = "Password" And validator.ID = ServerHandler.PwdRegEx Then
validator.Validate()
fValid = validator.IsValid
ModelState.AddModelError(CtrlToValidate, validator.ID)
End If
End If
Next
End Sub
But has condition that someone or something give him the error list from ValidationSummaryGroup
And this is done with the following code
Public Function LoadModel(ByVal sender As Object, ByVal e As EventArgs) As Boolean
Dim retVal As New Boolean
Try
If Not ModelState.IsValid Then
Dim result As StringBuilder = New StringBuilder()
For Each item In ModelState
Dim key As String = item.Key
Dim errors = item.Value.Errors
For Each [vError] In errors
ModelAnswer.Add(key & "^" & [vError].ErrorMessage)
retVal = True
Next
Next
End If
ModelState.Clear()
Catch ex As Exception
Environment.AssemblyInfo.ErrorAnswer = ServerHandler.ErrHandler.GetError(3, Nothing, Nothing, ex, Nothing)
Environment.AssemblyInfo.ErrorAnswer = Environment.AssemblyInfo.ErrorAnswer & "\r\n ifExistConsistencyRecord "
ServerHandler.ErrProperty._InnerError = Environment.AssemblyInfo.ErrorAnswer
Environment.AssemblyInfo.errorCall = True
retVal = False
End Try
Return retVal
End Function
Of course ModelAnswer is an ArrayList and declared as Public
And all this under the very basic prerequisite, all the processes to work within the main page and NOT in a "class"
Thank you very much for those who helped to solve this puzzle

Simple bind value to textbox in code behind using Telerik OpenAccess

I cannot find a complete example. Found tons on grid and combobox, but not textbox. This test is to lookup a “PhoneTypeName” from a UserPhoneType table with TypeCode = “0” and assign that first value to a asp.net textbox.
Currently, I am getting “Object reference not set to an instance of an object” when setting the text box to "phonetype.FirstOrDefault.PhoneTypeName.ToString"
Using dbContext As New EntitiesModel()
Dim phonetype As IEnumerable(Of User_PhoneType) = dbContext.User_PhoneTypes.Where(Function(c) c.PhoneTypeCode = "O")
mytextbox.Text = phonetype.FirstOrDefault.PhoneTypeName.ToString
End Using
----EDIT----
I changed as suggested. I ALSO successfully bound the entire list of PhoneTypes to a droplist control...to confirm the data is accessible. It must be the way I am going about querying the table for a single record here.
I get the same error, but at "Dim type = phonetype.First..."
The record is in the table, but it does not appear to be extracted with my code.
Dim phonetype As IEnumerable(Of User_PhoneType) = dbContext1.User_PhoneTypes.Where(Function(c) c.PhoneTypeCode = "M")
Dim type = phonetype.FirstOrDefault
If Object.ReferenceEquals(type, Nothing) = False And Object.ReferenceEquals(type.PhoneTypeName, Nothing) = False Then
mytextbox.Text = type.PhoneTypeName.ToString
End If
In general there are the following two possible reasons for getting this exception:
1) The phonetype list is empty and the FirstOrDefault method is returning a Nothing value.
2) The PhoneTypeName property of the first element of the phonetype list has a Nothing value.
In order to make sure that you will not get the Object reference not set to an instance of an object exception I suggest you add a check for Nothing before setting the TextBox value. It could be similar to the one below:
Dim type = phonetype.FirstOrDefault
If Object.ReferenceEquals(type, Nothing) = False And Object.ReferenceEquals(type.PhoneTypeName, Nothing) = False Then
mytextbox.Text = type.PhoneTypeName.ToString
End If
Fixed it.
I was able to view the SQL string being generated by using this:
mytextbox.text = phonetype.tostring
I saw that the SQL contained "NULL= 'O'"
I did it like the example?!? However, when I added .ToString to the field being queried, it worked.
So the final looks like this:
Using dbContext As New EntitiesModel()
Dim phonetype As IEnumerable(Of User_PhoneType) = dbContext.User_PhoneTypes.Where(Function(c) c.PhoneTypeCode.**ToString** = "O")
mytextbox.Text = phonetype.FirstOrDefault.PhoneTypeName.ToString
End Using
BTW, Dimitar point to check for null first is good advice (+1). The value was nothing as he said.

.Net: code for BtnLock_Click

I have been trying to apply a solution to some functionality that a user requires on their system.
A user requires me to implement a locking system on their system. They have multiple users which may require to access the site, but the user would like the ability for them to independently lock a records in the web site site, for them to add notes to and to then unlock this so other users are able to do the same.
I have a button on my web page simply named btnLock and i have added an additional column in my database called LockedBy and have the following stored procedure...
ALTER PROCEDURE LockWeeklyTest
(
#AgendaID BIGINT,
#LockingUser VARCHAR(20)
)
AS
BEGIN
SET NOCOUNT ON
UPDATE
WeeklyAgenda
SET
LockedBy = #LockingUser
WHERE
AgendaID = #AgendaID
AND
LockedBy IS NULL
END
I have a class named Weekly Class and have the following code...
Public Shared Sub LockWeeklyAgenda(ByVal WeeklyClass As WeeklyClass)
Using dbConnection As New SqlConnection(ConfigurationManager.AppSettings("dbConnection"))
dbConnection.Open()
Dim dbTrans As SqlTransaction
dbTrans = dbConnection.BeginTransaction()
Using dbCommand As SqlCommand = dbConnection.CreateCommand
With dbCommand
.Transaction = dbTrans
.CommandType = CommandType.StoredProcedure
.CommandText = "LockWeeklyTest"
'Add Parameters for Update
.Parameters.AddWithValue("#AgendaID", WeeklyClass.AgendaID)
.Parameters.AddWithValue("#LockingUser", WeeklyClass.LockedBy)
dbCommand.ExecuteNonQuery()
End With
End Using 'dbCommand
dbTrans.Commit()
End Using
End Sub
I was thinking that the below code for the butlock would populate my Loggedby field with the username but this isnt the case.
Protected Sub btnLock_Click(sender As Object, e As System.EventArgs) Handles btnLock.Click
Dim lock As New WeeklyClass
If lock.LockedBy = "Null" Then
lock.LockedBy = System.Environment.UserName
'lock.AgendaID = AgendaID
End If
' save to the database using the Class DAL
WeeklyClassDAL.LockWeeklyAgenda(lock)
End Sub
I know that the Stored Procedure works as i have tested with the following statement as an example...
EXEC LockWeeklyTest 11, 'Betty'
Im sure that its something to do with the btnlock_click, but im not 100% sure what this is.
Any help is much appriechiated.
Your problem is this line:
If lock.LockedBy = "Null" Then
"Null" is actually a string containing the word Null. What you're after is:
If String.IsNullOrEmpty(lock.LockedBy) Then
That way, if it is actually null or empty, your LockedBy will be set. Currently, it's only setting the LockedBy if LockedBy already equals the string value "Null", which it won't directly after being declared. Is this logic really necessary considering LockedBy will always be null directly after you've declared the WeeklyClass?
Something doesn't look quite right with the AgendaID:
During the button click event the value has been commented out but is still passed through to the stored procedure inside the data layer's 'LockWeeklyAgenda' method.
It's also not defined as a nullable parameter inside the stored procedure itself, so the value that's being sent would depend on the WeeklyClass class' constructor..
can you please also show how the WeeklyClass code looks like?

How to use findcontrol in createuserwizard1 complete step ...?

Is this the right declaration of findcontrol for complete step of createuserwizard1 ?
Dim UserName As TextBox = CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Label11")
But when i use it its shows the error object expected !
What was the problem ?
You can't set the value of a Textbox to a generic control (especially one that is really a label). Plus you forgot the New keyword when initializing UserName. Depending on exactly what you're trying to do, you may want to try the following...
'This will set the textbox's Text to the label's text.
Dim UserName As New Textbox
UserName.Text = CType(CreateUserWizard1.CreateUserStep.ContentTemplateContainer.FindControl("Label11"), Label).Text
Or
'This will cast the label to a new label control you define in code.
Dim UserName as New Label
UserName = CType(CreateUserWizard2.CreateUserStep.ContentTemplateContainer.FindControl("Label11"), Label)

Dynamically Reference an Object Property Using a String

I'm trying to reference a public property from a string. How can this be done in vb.net?
I have the text value of "FirstName" stored in strucParam(i).TxtPropertyName.
This is what I'm currently doing:
Dim tmpValue As String
Dim ucAppName As UserControl_appName = CType(Parent.FindControl(strucParam(i).ParentFindControl), UserControl_appName)
tmpValue = ucAppName.FirstName.Text
How can I use the value in strucParam(i).TxtPropertyName so that I can remove ".FirstName" from my code? Thanks!
This is basically a duplicate of this question, but I'll answer it for you since you're a VB user and probably didn't consider C# in your searches.
Suppose you have an object of any type stored in a variable called objObject, and the name of the property stored in a variable called strPropertyName. You do the following:
tmpValue = objObject.GetType().GetProperty(strPropertyName).GetValue(objObject, Nothing)
As a final note: please, please consider dropping pseudo-Hungarian notation. It's of no value when working with a statically typed language like VB.NET.
Edit:
The FirstName property is in reality a text box. So don't I need to somehow reference .Text in the code?
tmpFirstName = ucAppName.GetType().GetProperty(strucParam(i).PropertyName).GetValue(objAppNav, Nothing)
Try this:
Dim textBox as TextBox
Dim tmpValue as String
textBox = CType(ucAppName.GetType().GetProperty(strucParam(1).PropertyName).GetValue(objAppNav, Nothing), TextBox)
tmpValue = textBox.Text
Basically, you have to cast the value of the property to a TextBox type, then grab the Text property from it.

Resources