Showing posts with label variable. Show all posts
Showing posts with label variable. Show all posts

Saturday, March 31, 2012

Trimming

I am trying to trim a session variable to get the last three characters.Here is the code:

Dim CancelTrim()AsChar = {"","cc9"}

If Session("confirm").trimend(CancelTrim) ="ca1"Then

Label1.Text ="it was cancelled"

EndIf

It's not working though, go figure. So, how would I get these to trim off the last three characters so I can do what I need to do?

Thanks

Hello,

so what does it return from ther TrimEnd call? TrimEnd trims from the end of the string, so isn't that from the wrong direction if you want the last three characters? So maybe TrimStart would work better?

On the other hand, couldn't you write something like:

Dim ConfirmStringAs String = Cstr(Session("confirm"))Dim LastThreeCharsAs String = ConfirmString.Substring(ConfirmString.Length - 3)If LastThreeChars ="ca1"Then'CheckEnd If

Wednesday, March 28, 2012

Trouble accessing object before insertion into panel...

Hey everyone,

I have a script that presents the user with a variable number of text boxes (with the ID's "TextBox1", "TextBox2", "TextBox3", etc.) with an image button, and a label asking the user for input. All this is contained in a panel called Panel1. The user puts some text into the boxes and clicks the image button.

When clicked, the image button raises an event that tries and access the text the user entered in the text boxes, assign that text to a label, and display it in Panel2. It will then hide Panel1 and make Panel2 visible. The event generates an error however. I don't understand the error because the code seems straight forward. Here is the code (intTxtCount contains the number of text boxes that the user was presented with):


Public Sub cmdContinueToDeparturePoints(Sender As Object, e As System.Web.UI.ImageClickEventArgs)

Dim i As Integer
For i = 1 To intTxtCount
Dim lblName As New Label()
lblName.ID = "lblName" & i
Dim txtTemp As TextBox
txtTemp = FindControl("TextBox" & i)
lblName.Text = txtTemp.Text '''' Error Generating Line
Panel2.Controls.Add(lblName)
Panel2.Controls.Add(New LiteralControl("<br>"))
Next i

Panel1.Visible = False
Panel2.Visible = True

End Sub


Here is the Error:

System.NullReferenceException: Object reference not set to an instance of an object.

I think this error is telling me that a control called lblName does not exist physically in my panel, which is true. But if I reference lblName the object (the one I just declared in the sub) shouldn't that be okay? Am I wrong?

Bewildering...Mike :-/1. NullReferenceException is one of the most common programming errors. So it will help to really learn it well. It means that an object that is being dereferenced (the object followed by a period) is 'null' or 'nothing' in VB terms.

In this line, there are two objects being dereferenced:
lblName.Text = txtTemp.Text

lblName is created just above and you dereferenced it when you assigned the ID. So that's not it. txtTemp is the result of FindControl. You are assuming that you will find a control with the ID "TextBox1" (or whatever number 'i' is when this fails). It is returning null at some point.

2. Its likely that you have not recreated the same list of TextBoxes on post back before this loop executes. Also consider that you have a loop maximum in variable that may not reflect the true number of textboxes.

3. If you are going to write code, please consider using a debugger. Single-step through code and review the values of variables, parameters, and properties as things happen. The debugger would stop on the line with the error and let you open a Watch or Local Variable window to see what the values are in lblName and txtTemp.
Peter,

Thanks for such a great response. Yes, I should be using a debugger. If only my company were not so cheap as to let me code without VisualStudio.NET... :-(

Ok. So we have managed to conclude that lblName is not generating the Null Exception. It must be that no value is being assigned to txtTemp.Text from "TextBox1". Your comments in line item number 2 really interest me:

What do you mean by, "you have not recreated the same list of TextBoxes on post back before this loop executes"? I have never had to "recreate" a form for a PostBack event. I don't even know what you mean by that. And as for the maximum loop variable, I am positive this value is correct every time the script runs. The HTML that the server generages clearly shows me the correct number of text boxes, all with the correct names (TextBox1, T...2, T...3, etc.). I don't understand why when this form is submitted and I try to assign the boxes values they are null. Just don't get it.

Here is some code that works fine, this is what I based my current work on:


Sub Page_Load(sender As Object, e As EventArgs)

Dim t As New TextBox()
Dim i As Integer = 1
t.Text = "testtext" & i.ToString()
t.ID = "myTextBox" & i.ToString()
Panel1.Controls.Add(t)
ViewState("i") = i

End Sub

Sub GetTextBoxValueAndAssignToLabel(sender As Object, e As System.EventArgs)

Dim i As Integer
i = ViewState("i")
Dim txtTemp As TextBox
txtTemp = FindControl("myTextBox" & i)
lblTest.Text = txtTemp.Text

End Sub


As you can see, a text box is created that has an ID of "myTextBox1". The number i is passed via ViewState to the event code for the button, and the Text property of the text box is successfully assigned to the label. As far as I can see, the only difference between my code and the code here is that the label control already exists in the form instead of the on-the-fly label creation I used.
Let's start with that darn debugger issue. My sympathies about your situation. The time you waste without a debugger will easily exceed the cost of VS.NET.

In the meantime, did you know that .net framework comes with a debugger? Lookup "DbgClr.exe" at MSDN.Microsoft.com. I have not used it though, since I'm using VS.NET.

On to your code. I'm confused by this, perhaps because you simplified it. I though you had a loop going on. I'm interested in that loop. For example, if you are assigning ViewState("i") = i in each interation of the loop, you are not changing the key passed to ViewState, and thus overwriting the value.

Please do this too: set <@.Page Trace=true >. When the page is first generated, it will show you each control by its ID. FindControl will only search in the "naming container" of that method. In this case, whatever object contains GetTextBoxValueAndAssignToLabel() is the naming container you are searching. If you did Panel1.FindControl, you will be assured of getting values from Panel1. Another thing you can do is simply grab each unique item in Panel1.Controls.
Panel1.Controls(0) - contains TextBox1
Panel1.Controls(1) - contains TextBox2

Trouble Declaring and Setting Variable

I have a page that sends the value of a textbox in a form through GET.

My next page is supposed to grab that value, and put it in a variable. This is what I have for my next page:

1<%@dotnet.itags.org. Import namespace="System.IO"%>2<html>
3<head>
4<title>Uploading a File</title>
5678<script language="VB" runat="server">
9Dim strPath
10 strPath = Request.QueryString("path")
11
12 Dim savePath As String = StrPath
13Sub Upload_Click(source As Object, e As EventArgs)
1415 If Not (uploadedFile.PostedFile Is Nothing) Then
16 Try
17 Dim postedFile = uploadedFile.PostedFile
18 Dim filename As String = Path.GetFileName(postedFile.FileName)
19 Dim contentType As String = postedFile.ContentType
20 Dim contentLength As Integer = postedFile.ContentLength
2122 postedFile.SaveAs(savePath & filename)
23 message.Text = postedFile.Filename & " uploaded" & _
24 "<br>content type: " & contentType & _
25 "<br>content length: " & contentLength.ToString()
26 Catch exc As Exception
27 message.Text = "Failed uploading file"
28 End Try
29 End If
30End Sub
31</script>
32
33</head>
34<body>
35
36<form id="Form1" enctype="multipart/form-data" runat="server">
37 Select File to Upload:
3839 <input id="uploadedFile" type="file" runat="server">
40 <p>
41 <input type=button id="upload"
42 value="Upload"
43 OnServerClick="Upload_Click"
44 runat="server">
45 <p>
46 <asp:Label id="message" runat="server"/>
47</form>
48
49</body>
50</html>

I get a "declaration expected" on line 10. Any Ideas why?

A simle fix is to move both lines

Dim strPath as String = Request.QueryString("path")
Dim savePath As String = StrPath

to the top of Sub Upload_Click.


The actual error is that line 9 is not complete with a type declaration.

Dim strPathAs String

Also, you don't seem to need both strPath and savePath.

Dim savePath As String = Request.QueryString("path")
should be enough 


Gunteman, I must respectfully disagree. If you put

Dim savePath As String = Request.QueryString("path")

outside of Sub Upload_Click, you get the following exception:

"Request is not available in this context."

However, removing strPath does make sense.


Thanks to both of you. I still got a problem even after doing that, but adding "Context." before "Request" cleared things up.


louis210:

Gunteman, I must respectfully disagree. If you put

Dim savePath As String = Request.QueryString("path")

outside of Sub Upload_Click, you get the following exception:

"Request is not available in this context."

Quite right!

Monday, March 26, 2012

trouble executing SP, SqlDbType.Bit...

ASP.NET 2.0
This stored procedure fails because the variable type contains a number.
I've debugged the SP in VS2005 and it works if I change the 0/1 value of
type to true/false... How should I fix this' I cannot just replace type
with the phrase "false" or "true"... maybe using SqlDbType.Bit is wrong
This is header of this SP:
ALTER PROCEDURE dbo.DeleteMessage @dotnet.itags.org.id uniqueidentifier, @dotnet.itags.org.user int, @dotnet.itags.org.type
bit
Here is the ASP.NET code
public override void DeleteMessage(System.Guid id, int user, Boolean type)
{
using (SqlConnection cn = new SqlConnection(this.ConnectionString))
{
SqlCommand cmd = new SqlCommand("SendMessage", cn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@dotnet.itags.org.id", SqlDbType.UniqueIdentifier).Value = id;
cmd.Parameters.Add("@dotnet.itags.org.user", SqlDbType.Int).Value = user;
cmd.Parameters.Add("@dotnet.itags.org.type", SqlDbType.Bit).Value = type;
}
}
any suggetions?
JeffIt says boolean, so you need to pass true (with no quotation marks) or false
-- for the value.
Peter
Site: http://www.eggheadcafe.com
UnBlog: http://petesbloggerama.blogspot.com
Short urls & more: http://ittyurl.net
"Jeff" wrote:

> ASP.NET 2.0
> This stored procedure fails because the variable type contains a number.
> I've debugged the SP in VS2005 and it works if I change the 0/1 value of
> type to true/false... How should I fix this' I cannot just replace type
> with the phrase "false" or "true"... maybe using SqlDbType.Bit is wrong
> This is header of this SP:
> ALTER PROCEDURE dbo.DeleteMessage @.id uniqueidentifier, @.user int, @.type
> bit
> Here is the ASP.NET code
> public override void DeleteMessage(System.Guid id, int user, Boolean type)
> {
> using (SqlConnection cn = new SqlConnection(this.ConnectionString))
> {
> SqlCommand cmd = new SqlCommand("SendMessage", cn);
> cmd.CommandType = CommandType.StoredProcedure;
> cmd.Parameters.Add("@.id", SqlDbType.UniqueIdentifier).Value = id;
> cmd.Parameters.Add("@.user", SqlDbType.Int).Value = user;
> cmd.Parameters.Add("@.type", SqlDbType.Bit).Value = type;
> }
> }
> any suggetions?
> Jeff
>
>

trouble executing SP, SqlDbType.Bit...

ASP.NET 2.0

This stored procedure fails because the variable type contains a number.
I've debugged the SP in VS2005 and it works if I change the 0/1 value of
type to true/false... How should I fix this?? I cannot just replace type
with the phrase "false" or "true"... maybe using SqlDbType.Bit is wrong

This is header of this SP:
ALTER PROCEDURE dbo.DeleteMessage @dotnet.itags.org.id uniqueidentifier, @dotnet.itags.org.user int, @dotnet.itags.org.type
bit

Here is the ASP.NET code
public override void DeleteMessage(System.Guid id, int user, Boolean type)
{
using (SqlConnection cn = new SqlConnection(this.ConnectionString))
{
SqlCommand cmd = new SqlCommand("SendMessage", cn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@dotnet.itags.org.id", SqlDbType.UniqueIdentifier).Value = id;
cmd.Parameters.Add("@dotnet.itags.org.user", SqlDbType.Int).Value = user;
cmd.Parameters.Add("@dotnet.itags.org.type", SqlDbType.Bit).Value = type;
}
}

any suggetions?

JeffIt says boolean, so you need to pass true (with no quotation marks) or false
-- for the value.
Peter

--
Site: http://www.eggheadcafe.com
UnBlog: http://petesbloggerama.blogspot.com
Short urls & more: http://ittyurl.net
"Jeff" wrote:

Quote:

Originally Posted by

ASP.NET 2.0
>
This stored procedure fails because the variable type contains a number.
I've debugged the SP in VS2005 and it works if I change the 0/1 value of
type to true/false... How should I fix this?? I cannot just replace type
with the phrase "false" or "true"... maybe using SqlDbType.Bit is wrong
>
This is header of this SP:
ALTER PROCEDURE dbo.DeleteMessage @.id uniqueidentifier, @.user int, @.type
bit
>
Here is the ASP.NET code
public override void DeleteMessage(System.Guid id, int user, Boolean type)
{
using (SqlConnection cn = new SqlConnection(this.ConnectionString))
{
SqlCommand cmd = new SqlCommand("SendMessage", cn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@.id", SqlDbType.UniqueIdentifier).Value = id;
cmd.Parameters.Add("@.user", SqlDbType.Int).Value = user;
cmd.Parameters.Add("@.type", SqlDbType.Bit).Value = type;
}
}
>
any suggetions?
>
Jeff
>
>
>

Saturday, March 24, 2012

Trouble saving html in a string variable

I'm trying to allow a user to enter html text into a textBox (FreeTextBox) but am getting an error upon submitting:

A potentially dangerous Request.Form value was detected from the client (noteTextBox="<H2><FONT size=6>asd...").
Description:Request Validation has detected a potentially dangerous client input value, and processing of the request has been aborted. This value may indicate an attempt to compromise the security of your application, such as a cross-site scripting attack. You can disable request validation by setting validateRequest=false in the Page directive or in the configuration section. However, it is strongly recommended that your application explicitly check all inputs in this case.

Exception Details:System.Web.HttpRequestValidationException: A potentially dangerous Request.Form value was detected from the client (noteTextBox="<H2><FONT size=6>asd...").

Anybody know how to deal with this while still allowing me to save the html?

<%@. Page...... ValidateRequest="false".....%>


I think the reason for this error was that someone could enter a <script> tag in your textbox with javascript code, and then if you grab that value from the form and display directly it on another page, the code in the <script> tag would be executed on your user's computer... this could be potentially bad. i usually turn the error off though, like the previous poster. If you HtmlEncode() anything that you display that ultimately came from the user, it should be ok to turn it off.


How do I HtmlEncode() this text?


dim myText as String = Server.HtmlEncode(yourTextbox.Text)

Tuesday, March 13, 2012

Trouble With UrlReferrer

I'm trying to store a session variable to store the filename of the page where the user was before the current one.

The reasoning is that I'm trying to store the value so that if a users session times out, I have the redirected to the logon page. Once they've logged back in I'd like to automatically take them back to the page where they were before.

I've tried using Session("ref")=Request.UrlReferrer to store the value. To test that I have the referring page I've created a label and assigned it the value of Session("Ref") by using lblReferrer.Text=Session("ref").

At first I was just getting a nothing where I exprected to see the referrer on the page. Today it's throwing an error saying can't convert a Uri to a String.

I've had a look at the documentation for Uri's but can't see a way to get just the referrers url.

Im I going about this the wrong way, or is it something basic I've missed?

Thanks
JasonSession("ref")=Request.UrlReferrer.ToString()
I did have .ToString() in the code at some stage, but I obviously in the wrong place.

In any case, you've solved my problem. Thanks for your help.
Jason

Troubles with INSERT INTO Statement...

hey all, im currently trying to do an insert statement, using textbox's and a variable. the only thing is its inserting txtTextBox.Text into the db instead of the value of that textbox...and i get this error when trying to insert my variable...

Exception Details: System.Data.SqlClient.SqlException: The name 'RndmNum' is not permitted in this context. Only constants, expressions, or variables allowed here. Column names are not permitted.

Source Error:

Line 42: dbQuery = "INSERT INTO table (name, fault_type, fault_location, fault_description, fault_number) VALUES ('txtName.Text', 'txtType.Text', 'txtLocation.Text', 'txtDesc.Text', RndmNum)"
Line 43: dbCommand = New SqlCommand(dbQuery,dbConnection)
Line 44: dbCommand.ExecuteNonQuery()
Line 45: dbConnection.Close
Line 46:

this is my insert statement:

dbQuery = "INSERT INTO table (name, fault_type, fault_location, fault_description, fault_number) VALUES ('txtName.Text', 'txtType.Text', 'txtLocation.Text', 'txtDesc.Text', RndmNum)"

thanks everyone,
JustinYou are sending txtName.Text as a string. Your dbQuery needs to look like this:

dbQuery = "INSERT INTO table (name, fault_type, fault_location, fault_description, fault_number) VALUES ('" & txtName.Text & "', '" & txtType.Text & "', '" & txtLocation.Text & "', '" & txtDesc.Text & "', " & RndmNum & ")"