Showing posts with label string. Show all posts
Showing posts with label string. Show all posts

Saturday, March 31, 2012

System.FormatException: Input string was not in a correct format.

Is this a bug or am I going crazy??
WILL NOT WORK: DateTime.Now.ToString("h")
THIS ONE WILL THOUGH: DateTime.Now.ToString(" h")
But that space gets put in front of the hour.
Anything with "h" will work, as long as it's not by itself ??Shouldn't it be "hh" ?

"hh" returns the hour with a zero in front if less than 10. "h" is supposed to return the hour without the zero.
DateTime.Now.ToString(" h")
that works, but it won't work if the space is not in front of the h.
Have you tried using string.Format to see if it gives you the same results?
Here's a good reference for the format strings:
http://www.stevex.org/CS/blogs/dottext/articles/158.aspx
If I think of anything else, I'll let you know.

M$ doesn't seem to want you to know the current hour without the 0 in front of it.
I triedString.Format("{0:h}", DateTime.Now) and it has the same problem that theDateTime.Now.ToString("h") method has.
For some reason, you cannot use "h" all by itself. Luckily the way I'm using it allows me to leave it as " h" (with a space in front).
I'm using it in a JavaScript file like so:
var curH = <%= DateTime.Now.ToString(" h") %>;
So, the JavaScript removes the space for me.
My guess is it's a bug. Thanks for you help anyways, but I'm not going to worry about it.

northflacomps wrote:

Is this a bug or am I going crazy??
WILL NOT WORK: DateTime.Now.ToString("h")
THIS ONE WILL THOUGH: DateTime.Now.ToString(" h")
But that space gets put in front of the hour.
Anything with "h" will work, as long as it's not by itself ??


Actually, that behaviour appears to be "by design" and is documented in the MSDN help.
"DateTimeFormatInfo Class... Only format patterns listed in the second table above [which is the table with h and H and so on] can be used to create custom patterns; standard format characters listed in the first table [which is a table with the abbreviation codes such as T => Long Time Pattern] cannot be used to create custom patterns. Custom patterns are at least two characters long"
It appears that since the standard patterns are sometimes single-characters in length, they decided to force custom patterns to be at least 2 characters in length, to avoid collisions and ambiguity. And so on.
For padding, when the desired custom format pattern is only one character long, they apparently want one to use the "%" sign.
Here is some sample code.

PrivateSub TestFormatStringButton_Click( _
ByVal senderAs System.Object, _
ByVal eAs System.EventArgs _
)Handles TestFormatStringButton.Click

'RTE: "Input string was not the correct format".
'Me.Response.Write(DateTime.Now.ToString("h"))

'RTE: "Input string was not in a correct format".
'Me.Response.Write(DateTime.Now.ToString("H"))

'RTE: "Format specifier was invalid".
'Me.Response.Write(DateTime.Now.Hour.ToString("H"))

'This works.
Me.Response.Write(DateTime.Now.ToString("%h"))

EndSub


HTH.
--Mark Kamoski


http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vblr7/html/vafctFormat.asp
h
Displays the hour as a number without leading zeros using the 12-hour clock (for example,1:15:15 PM). Use%h if this is the only character in your user-defined numeric format.
Thanks for that information. I looked at MSDN for the DateTime structure but didn't see anything about the "%". Seems kinda dumb to me.

System.FormatException: Input string was not in a correct format.

Strange error mblè mblè :)


Dim SQL = "SELECT confermato, confrndnum FROM utenti WHERE confermato = 'false' AND confrndnum = " & Qs
Dim RsCommand = New OleDbCommand(Sql, Conn)
Dim RsRecordCount = RsCommand.ExecuteScalar()

If RsRecordCount = 0 Then
divErrEx.Visible = True
Else
SQL = "UPDATE utenti SET confermato = 'true' WHERE ConfRndNum = " & QS
RsCommand = New OleDbCommand(Sql, Conn)
RsCommand.ExecuteNonQuery()
Dim ReadCookie = Request.Cookies("tristizia_auth")
ltrUsername.Text = ReadCookie("Username")
divConfOp.Visible = TRUE
End If


the line "If RsRecordCount = 0 Then" gives error
The error is strange becouse if RsRecordCount is 0 the page works, if not it gives the error

Thanks for any answer
Bye
. AtariVerify that the following line is not returning NULL. If it is and you are trying to put it into a string then it won't work of course. The line below is defiantely your problem I think though.


ltrUsername.Text = ReadCookie("Username")

Ok tryed, but the error appears =

I tryed either so:


If RsRecordCount = 0 Then
divErrEx.Visible = True
Else
SQL = "UPDATE utenti SET confermato = 'true' WHERE ConfRndNum = " & QS
RsCommand = New OleDbCommand(Sql, Conn)
RsCommand.ExecuteNonQuery()
Dim ReadCookie = Request.Cookies("tristizia_auth")
If Not ReadCookie Is Nothing Then
ltrUsername.Text = ReadCookie("Username")
Else
ltrUsername.Text = "[Unsknown]"
End If
divConfOp.Visible = TRUE
End If

But however I get error either so :


If RsRecordCount = 0 Then
divErrEx.Visible = True
Else
Dim MyVar = "ewruowehr"
End If

Boh?!?!

Bye
. Atari
One more victim of the Visual Basic type sloppiness (which is a feature).
Try to Dim ReadCookie as HttpCookie, just to be sure you don't get a string instead.
Uhm nothing is changed...


Dim Conn = New OleDbConnection("Provider = Microsoft.Jet.OleDb.4.0;Data Source=" & Server.MapPath("/mdb-database/tristizia.mdb"))
Conn.Open()
Dim SQL = "SELECT confermato, confrndnum FROM utenti WHERE confermato = 'false' AND confrndnum = " & Qs
Dim RsCommand = New OleDbCommand(Sql, Conn)
Dim RsRecordCount = RsCommand.ExecuteScalar()

<b style="color:red;">If RsRecordCount = 0 Then</b>
divErrEx.Visible = True
Else
SQL = "UPDATE utenti SET confermato = 'true' WHERE ConfRndNum = " & QS
RsCommand = New OleDbCommand(Sql, Conn)
RsCommand.ExecuteNonQuery()
Dim ReadCookie As HttpCookie = Request.Cookies("tristizia_auth")
If Not ReadCookie Is Nothing Then
ltrUsername.Text = ReadCookie("Username")
Else
ltrUsername.Text = "[Sconosciuto]"
End If
divConfOp.Visible = TRUE
End If

But what's the problem? I need to declare AS [type] the variables ? If so what's RsRecordCount ? I tryed As Integer but doesn't work...

Bye
. Atari
It's always better to declare the type of your variables. Not declaring it is a source of bugs.
Why do you use ExecuteScalar here, whereas your query returns two different columns? ExecuteScalar returns the first column of the first row. Here, it would be confermato. Is this column an integer?
In this case, you can Dim RsRecordCount as Integer = CType(RsCommand.ExecuteScalar(), Integer), but I suspect this is not what you're trying to do...
Your query should probably be "SELECT COUNT(*) FROM utenti WHERE confermato = 'false' AND confrndnum = " & Qs

System.FormatException: Input String was not in a correct format.

I've got an error "System.FormatException: Input string was not in a correct
format." while I'm implementing a datagrid and a textbox
What's wrong with it?

Sub Button1_Click(sender As Object, e As EventArgs)
DataGrid1.DataSource = MyQueryMethod(CInt(TextBox1.Text))
DataGrid1.DataBind()
End Sub

Function MyQueryMethod(ByVal others As String) As System.Data.DataSet
Dim connectionString As String = "server='localhost'; user id='******';
password='******'; database='******'"
Dim dbConnection As System.Data.IDbConnection = New
System.Data.SqlClient.SqlConnection(connectionStri ng)
Dim queryString As String = "SELECT [Software].* FROM [Software] WHERE
([Software].[Others] like @dotnet.itags.org.Others)"
Dim dbCommand As System.Data.IDbCommand = New
System.Data.SqlClient.SqlCommand
dbCommand.CommandText = queryString
dbCommand.Connection = dbConnection
Dim dbParam_others As System.Data.IDataParameter = New
System.Data.SqlClient.SqlParameter
dbParam_others.ParameterName = "@dotnet.itags.org.Others" dbParam_others.Value = others
dbParam_others.DbType = System.Data.DbType.String
dbCommand.Parameters.Add(dbParam_others)

Dim dataAdapter As System.Data.IDbDataAdapter = New
System.Data.SqlClient.SqlDataAdapter
dataAdapter.SelectCommand = dbCommand
Dim dataSet As System.Data.DataSet = New System.Data.DataSet
dataAdapter.Fill(dataSet)
Return dataSet

End FunctionI would guess it is something to do with converting the TextBox1.Text to an
int data type. The textbox could potentially contain a value other than a
numeric value. This would cause this error. Also, MyQueryMethod looks like
it is expecting a value of a string data type. Since you are converting
TextBox1.Text to an int type, this may also cause the error.

-Darrin

"sbox" <s@.b.x> wrote in message
news:%23ibArp48DHA.712@.tk2msftngp13.phx.gbl...
> I've got an error "System.FormatException: Input string was not in a
correct
> format." while I'm implementing a datagrid and a textbox
> What's wrong with it?
> Sub Button1_Click(sender As Object, e As EventArgs)
> DataGrid1.DataSource = MyQueryMethod(CInt(TextBox1.Text))
> DataGrid1.DataBind()
> End Sub
> Function MyQueryMethod(ByVal others As String) As System.Data.DataSet
> Dim connectionString As String = "server='localhost'; user
id='******';
> password='******'; database='******'"
> Dim dbConnection As System.Data.IDbConnection = New
> System.Data.SqlClient.SqlConnection(connectionStri ng)
> Dim queryString As String = "SELECT [Software].* FROM [Software] WHERE
> ([Software].[Others] like @.Others)"
> Dim dbCommand As System.Data.IDbCommand = New
> System.Data.SqlClient.SqlCommand
> dbCommand.CommandText = queryString
> dbCommand.Connection = dbConnection
> Dim dbParam_others As System.Data.IDataParameter = New
> System.Data.SqlClient.SqlParameter
> dbParam_others.ParameterName = "@.Others" dbParam_others.Value = others
> dbParam_others.DbType = System.Data.DbType.String
> dbCommand.Parameters.Add(dbParam_others)
> Dim dataAdapter As System.Data.IDbDataAdapter = New
> System.Data.SqlClient.SqlDataAdapter
> dataAdapter.SelectCommand = dbCommand
> Dim dataSet As System.Data.DataSet = New System.Data.DataSet
> dataAdapter.Fill(dataSet)
> Return dataSet
> End Function
You should not have the ' ' in your connection string. Take a look at the
connection strings at

http://www.able-consulting.com/dotn...ManagedProvider

Ben Miller

--
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.

"sbox" <s@.b.x> wrote in message
news:%23ibArp48DHA.712@.tk2msftngp13.phx.gbl...
> I've got an error "System.FormatException: Input string was not in a
correct
> format." while I'm implementing a datagrid and a textbox
> What's wrong with it?
> Sub Button1_Click(sender As Object, e As EventArgs)
> DataGrid1.DataSource = MyQueryMethod(CInt(TextBox1.Text))
> DataGrid1.DataBind()
> End Sub
> Function MyQueryMethod(ByVal others As String) As System.Data.DataSet
> Dim connectionString As String = "server='localhost'; user
id='******';
> password='******'; database='******'"
> Dim dbConnection As System.Data.IDbConnection = New
> System.Data.SqlClient.SqlConnection(connectionStri ng)
> Dim queryString As String = "SELECT [Software].* FROM [Software] WHERE
> ([Software].[Others] like @.Others)"
> Dim dbCommand As System.Data.IDbCommand = New
> System.Data.SqlClient.SqlCommand
> dbCommand.CommandText = queryString
> dbCommand.Connection = dbConnection
> Dim dbParam_others As System.Data.IDataParameter = New
> System.Data.SqlClient.SqlParameter
> dbParam_others.ParameterName = "@.Others" dbParam_others.Value = others
> dbParam_others.DbType = System.Data.DbType.String
> dbCommand.Parameters.Add(dbParam_others)
> Dim dataAdapter As System.Data.IDbDataAdapter = New
> System.Data.SqlClient.SqlDataAdapter
> dataAdapter.SelectCommand = dbCommand
> Dim dataSet As System.Data.DataSet = New System.Data.DataSet
> dataAdapter.Fill(dataSet)
> Return dataSet
> End Function

System.FormatException: Input string was not in a correct format

I am getting above error

// Validate input
if ((userId.Trim() == string.Empty) || (password.Trim() == string.Empty))
return null;

// Get an instance of the account DAC using the DACFactory
IUserAccount dac = CData.DACFactory.FDACUserAccount.Create();

//On this line i am getting error.userId and Password are strings
UserAccountInfo userAccount = dac.Login(userId , password);
return userAccount;

Please sort out my problemI have made three assemblies. 1 is calling 2nd and 2nd is calling 3rd.
now when i call methods of 3rd from 1st through 2nd one i get "System.FormatException: Input string was not in a correct format" on every string manipulation. Even if it is throwing exceptions in string formats it gives that exception
When you use the Trim method, it expects the variable to be a string. When your variable is null, the Trim method would throw that FormatException. So you should rewrite your code to test your variable again null instead.
Ex:
<code>
if( userID == null )
{
//do something here
}

System.FormatException: Input string was not in a correct format

Hello all,

I'm looking for a long time to find out what's wrong, but I can't find the mistake...
The connection to the database works correctly (Select,..), but when I set up the Insert-Command by clicking a button I get the following exception. Does anybody can help me and tell me what's wrong?!

Thank you for helping!

Exception:
System.FormatException: Input string was not in a correct format. at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) at System.String.System.IConvertible.ToInt32(IFormatProvider provider) at System.Convert.ChangeType(Object value, Type conversionType, IFormatProvider provider) at System.Data.OleDb.OleDbParameter.GetParameterValue() at System.Data.OleDb.OleDbParameter.GetParameterScale() at System.Data.OleDb.OleDbParameter.BindParameter(Int32 i, DBBindings bindings, tagDBPARAMBINDINFO[] bindInfo) at System.Data.OleDb.OleDbCommand.CreateAccessor() at System.Data.OleDb.OleDbCommand.InitializeCommand(CommandBehavior behavior, Boolean throwifnotsupported) at System.Data.OleDb.OleDbCommand.ExecuteCommand(CommandBehavior behavior, Object& executeResult) at System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method) at System.Data.OleDb.OleDbCommand.ExecuteNonQuery() at roomplaner.ObjektHinzu.Anlegen_Click(Object sender, EventArgs e) in C:\Inetpub\...\ObjektHinzu.aspx.vb:line 107

line 107 --> Command.ExecuteNonQuery()


Dim Command As New OleDbCommand

'create OleDb database connection
Dim SQL_CONNECTION_STRING As String = "Provider=SQLOLEDB;Server=...;...."
Command.Connection = New OleDbConnection(SQL_CONNECTION_STRING)

'create SQL statement for INSERT into table
Command.CommandText = "INSERT INTO t_object (Name, ObjectType, Category, Manufactor, Length, Width, Height, Text_Short, Text_Long, URL_Pic_Small, URL_Pic_Big, URL_Pic_Plan, URL_VET, VET_ObjectName, Material, Color, Price, ObjectLink, Comment, MaxSceneCount) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
Command.CommandType = CommandType.Text

'add input parameters and values to INSERT statement
Command.Parameters.Add("@dotnet.itags.org.Name", OleDbType.VarChar, 100).Value = O_Name.Text
Command.Parameters.Add("@dotnet.itags.org.ObjectType", OleDbType.BigInt, 8).Value = O_ObjectType.SelectedValue
Command.Parameters.Add("@dotnet.itags.org.Category", OleDbType.BigInt, 8).Value = O_Category.SelectedValue
Command.Parameters.Add("@dotnet.itags.org.Manufactor", OleDbType.BigInt, 8).Value = O_Manufactor.SelectedValue
Command.Parameters.Add("@dotnet.itags.org.Length", OleDbType.Integer, 4).Value = O_Length.Text
Command.Parameters.Add("@dotnet.itags.org.Width", OleDbType.Integer, 4).Value = O_Width.Text
Command.Parameters.Add("@dotnet.itags.org.Height", OleDbType.Integer, 4).Value = O_Height.Text
Command.Parameters.Add("@dotnet.itags.org.Text_Short", OleDbType.VarChar, 100).Value = O_Text_Short.Text
Command.Parameters.Add("@dotnet.itags.org.Text_Long", OleDbType.VarChar, 500).Value = O_Text_Long.Text

Command.Parameters.Add("@dotnet.itags.org.URL_Pic_Small", OleDbType.VarChar, 100).Value = "0"
Command.Parameters.Add("@dotnet.itags.org.URL_Pic_Big", OleDbType.VarChar, 100).Value = "0"
Command.Parameters.Add("@dotnet.itags.org.URL_Pic_Plan", OleDbType.VarChar, 100).Value = "0"

Command.Parameters.Add("@dotnet.itags.org.URL_VET", OleDbType.VarChar, 100).Value = "0"
Command.Parameters.Add("@dotnet.itags.org.VET_ObjectName", OleDbType.VarChar, 50).Value = O_VET_ObjectName.Text
Command.Parameters.Add("@dotnet.itags.org.Material", OleDbType.BigInt, 8).Value = O_Material.SelectedValue
Command.Parameters.Add("@dotnet.itags.org.Color", OleDbType.BigInt, 8).Value = O_Color.SelectedValue
Command.Parameters.Add("@dotnet.itags.org.Price", OleDbType.VarChar, 50).Value = O_Price.Text
Command.Parameters.Add("@dotnet.itags.org.ObjectLink", OleDbType.VarChar, 100).Value = O_ObjectLink.Text
Command.Parameters.Add("@dotnet.itags.org.Comment", OleDbType.VarChar, 100).Value = O_Comment.Text
Command.Parameters.Add("@dotnet.itags.org.MaxSceneCount", OleDbType.Integer, 4).Value = O_MaxSceneCount.Text

Try
Command.Connection.Open()
Command.ExecuteNonQuery() 'save record

Catch ex As Exception
Response.Write("Exception:")
Response.Write(ex.ToString)
End Try

Command.Connection.Close()
End Sub

The error is associated with a call to System.Number.ParseInt32(). That tells me that one of the parameters is expected to contain an integer or a string representation of an integer but does not. Identify integer parameters. Then in the debugger, determine if any of them are:
1. Not assigned. If a string is provided, is it an empty string?
2. Contains other characters than digits?
These two cases will generate that exception. (The .net docs for Convert.ToInt32 say FormatException will occur when:value does not consist of an optional sign followed by a sequence of digits (zero through nine).)

System.FormatException: Invalid character in a Base-64 string...

Problem:
Enter the URL to a small image file (or any file), retrieve the file and encode the data as base64, then decode the base64 to get the original files data.

When the page below is executed, the file is retrieved and encoded, however when the decode_base64() subroutine is called, the system displays the following exception:

System.FormatException: Invalid character in a Base-64 string.
at System.Convert.FromBase64String(String s)
at ASP.test_base64_aspx.decode_base64()

Obviously, there is an invalid character in the Base-64 string -- the strange thing is if I increase "k_buf_size" from 4096 to something like 32000 (in the encode_base64 subroutine) and execute the page everything works just fine!!

So my question is, why will this code NOT work with smaller buffer sizes?? Hopefully, I have made a simple programming error that someone will point out as I have stared at this for too long ...

ANY help would be appreciated!

<%@dotnet.itags.org. Page Language="VB" Explicit="true" Strict="true" Trace="true" %>

<%@dotnet.itags.org. Import Namespace="System.IO" %>
<%@dotnet.itags.org. Import Namespace="System.Data" %>
<%@dotnet.itags.org. Import Namespace="System.Net" %>

<script language="VB" runat="server">

' The base64 encoded data ...
private m_encoded_data as StringBuilder

' The size of the file that was encoded ...
private m_file_size as Integer


'----------------
'
private sub do_test( Sender as Object, e as EventArgs )

' Init ...
m_encoded_data = new StringBuilder()
m_file_size = 0

' Attempt to encode the input file ...
encode_base64()

' If a file was encoded, attempt to decode ...
if ( m_encoded_data.length > 0 ) then

decode_base64()

end if

end sub


'----------------
'
private sub encode_base64()

const k_buf_size as Integer = 4096

dim bytes_read as Integer
dim n as Integer

dim err_msg as String
dim s as String
dim url as String

dim sr as Stream

dim wc as WebClient

Trace.Warn( ">", "==============" )
Trace.Warn( ">", "encode_base64:" )

' Get URL ...
url = fld_url.text.Trim()
if ( url.length = 0 )
exit sub
end if

' Attempt to get the data file and encode as base 64 ...
try

wc = Nothing
sr = Nothing
m_file_size = 0

' Create space to hold data ...
dim data_array( k_buf_size ) as Byte

' Create web client ...
wc = new WebClient()

' Create stream from URL ...
sr = wc.OpenRead( url )

' Loop to encode data stream ...

' Read a chunk from the data steam into array ...
bytes_read = sr.Read( data_array, 0, k_buf_size )

do while ( bytes_read > 0 )

Trace.Warn( ">", "bytes_read = " & bytes_read.ToString() )

m_file_size = m_file_size + bytes_read

' Convert data chunk to base 64 string. Remove any padding characters (=)
' that may have been added ...
s = System.Convert.ToBase64String( data_array, 0, bytes_read )
n = s.IndexOf( "=" )

if ( n > 0 ) then
m_encoded_data.Append( s.Substring( 0, n ) )
else
m_encoded_data.Append( s )
end if

bytes_read = sr.Read( data_array, 0, k_buf_size )

loop

' Encoded output length must be a multiple of 4 bytes, so pad if necessary ...
n = m_encoded_data.length Mod 4
if ( n <> 0 ) then
m_encoded_data.Append( new String( "="C, 4 - n ) )
end if

' Clean up ...
data_array = Nothing

Trace.Warn( ">", "File size = " & m_file_size.ToString() )
Trace.Warn( ">", "Encoded data length = " & m_encoded_data.length.ToString() )

catch ex as Exception
Trace.Warn( ">", ex.ToString() )

finally
if ( not sr is Nothing ) then
sr.Close()
sr = Nothing
end if
if ( not wc is Nothing ) then
wc.Dispose()
wc = Nothing
end if

end try

end sub


'----------------
'
private sub decode_base64()

dim data_array() as Byte

Trace.Warn( ">", "==============" )
Trace.Warn( ">", "decode_base64:" )

' Attempt to decode from base64 ...
try

data_array = Convert.FromBase64String( m_encoded_data.ToString() )

Trace.Warn( ">", "data_array.length = " & data_array.length.ToString() )

if ( data_array.length = m_file_size ) then
Trace.Warn( ">", "DECODE OK" )
else
Trace.Warn( ">", "DECODE FAILED!" )
end if

catch ex as Exception
Trace.Warn( ">", ex.ToString() )

end try

end sub
</script>
<html>
<head>
<title>Attempt to encode/decode using Base 64</title>
</head>
<body>
<blockquote>

<form runat="server">
Enter the URL to a file, preferably a small image JPG or GIF file.
<hr noshade size="1">
<table width="90%" border="0" cellpadding="2" cellspacing="1">
<tr>
<td width="20%" align="right" valign="top" >
URL:
</td>
<td width="80%" align="left" valign="top" >
<asp:TextBox id="fld_url" text="" size="100" maxlength="200" runat="server" />
</td>
</tr>
</table>
<hr noshade size="1">
<table width="90%" border="0" cellpadding="2" cellspacing="1">
<tr>
<td width="20%"> </td>
<td width="80%" valign="top">
<asp:Button OnClick="do_test" text="Do Base64 Test" runat="server" />
</td>
</tr>
</table>
</form>

</blockquote>
</body>
</html>

Ok - here is one solution (may not be the best, but it works)...

The problem with base 64 encoding is that one has to be careful when reading data in "chunks" and then encoding each chunk (as base 64) and then appending each chunk to form the final encoded string -- this is what I was doing initially. The code would work whenever I changed the buffer size to anything larger than the file being read, ie: whenever the entire file was read in one chunk. In any case, the solution is shown below for anyone that comes across this problem. Please note that the solution below limits the file sizes that can be encoded to 2 megabytes.

<%@. Page Language="VB" Explicit="true" Strict="true" Trace="true" %>

<%@. Import Namespace="System.IO" %>
<%@. Import Namespace="System.Data" %>
<%@. Import Namespace="System.Net" %>

<%@. Import Namespace="rentsys" %>

<script language="VB" runat="server">

' The base64 encoded data ...
private m_encoded_data as String

' The size of the file that was encoded ...
private m_file_size as Long


'----------------
'
private sub do_test( Sender as Object, e as EventArgs )

' Init ...
m_encoded_data = String.Empty
m_file_size = 0

' Attempt to encode the input file ...
encode_base64()

' If a file was encoded, attempt to decode ...
if ( m_encoded_data.length > 0 ) then

decode_base64()

end if

end sub


'----------------
'
private sub encode_base64()

' Maximum file size is 2 MB ...
const k_max_file_size as Long = 2000000

' Buffer used to read file in chunks ...
const k_data_buf_size as Integer = 4096
dim data_buf( k_data_buf_size ) as Byte

dim bytes_read as Integer

dim err_msg as String
dim s as String
dim url as String

dim ms as MemoryStream

dim sr as Stream

dim wc as WebClient


Trace.Warn( ">", "==============" )
Trace.Warn( ">", "encode_base64:" )

' Get URL ...
url = fld_url.text.Trim()
if ( url.length = 0 )
exit sub
end if


' Get the size of the remote file, unfortunately, the only way
' to reliably get this is to read the entire file. We could issue
' an HTTP HEAD request to get the content length, but some servers
' may not return file headers ...
try

wc = Nothing
sr = Nothing
m_file_size = 0

' Create web client ...
wc = new WebClient()

' Create stream from URL ...
sr = wc.OpenRead( url )

' Loop to determine file size ...
bytes_read = sr.Read( data_buf, 0, k_data_buf_size )
do while ( bytes_read > 0 )
m_file_size = m_file_size + bytes_read
bytes_read = sr.Read( data_buf, 0, k_data_buf_size )
loop

catch ex as Exception
Trace.Warn( ">", ex.ToString() )

finally
if ( not sr is Nothing ) then
sr.Close()
sr = Nothing
end if
if ( not wc is Nothing ) then
wc.Dispose()
wc = Nothing
end if

end try


' Check if we can handle the file size ...
Trace.Warn( ">", "File size = " & m_file_size.ToString() )

if ( m_file_size > k_max_file_size ) then
Trace.Warn( ">", "File size exceeds maximum allowed" )
exit sub
end if


' Attempt to read the file contents and encode as base 64 ...
try

wc = Nothing
sr = Nothing
ms = Nothing

' Create web client ...
wc = new WebClient()

' Create stream from URL ...
sr = wc.OpenRead( url )

' Create memory stream to hold file contents ...
ms = new MemoryStream()

' Loop to read data into memory stream. Note that we
' CANNOT convert each chunk read into base 64 and append
' to a string as this would lead to an invalid base 64
' string due to the nature of the algorithm and padding
' characters that would be present in the final string ...

bytes_read = sr.Read( data_buf, 0, k_data_buf_size )
do while ( bytes_read > 0 )

ms.Write( data_buf, 0, bytes_read )

bytes_read = sr.Read( data_buf, 0, k_data_buf_size )

loop

' Convert the data to base 64 ...
m_encoded_data = Convert.ToBase64String( ms.ToArray() )

catch ex as Exception
Trace.Warn( ">", ex.ToString() )

finally
if ( not ms is Nothing ) then
ms.Close()
ms = Nothing
end if
if ( not sr is Nothing ) then
sr.Close()
sr = Nothing
end if
if ( not wc is Nothing ) then
wc.Dispose()
wc = Nothing
end if

end try

end sub


'----------------
'
private sub decode_base64()

dim data_array() as Byte

Trace.Warn( ">", "==============" )
Trace.Warn( ">", "decode_base64:" )

' Attempt to decode from base64 ...
try

data_array = Convert.FromBase64String( m_encoded_data )

Trace.Warn( ">", "data_array.length = " & data_array.length.ToString() )

if ( data_array.length = m_file_size ) then
Trace.Warn( ">", "DECODE OK" )
else
Trace.Warn( ">", "DECODE FAILED!" )
end if

catch ex as Exception
Trace.Warn( ">", ex.ToString() )

end try

end sub
</script>
<html>
<head>
<title>Attempt to encode/decode using Base 64</title>
</head>
<body>
<blockquote>

<form runat="server">
Enter the URL to a file, preferably a small image JPG or GIF file.
<hr noshade size="1">
<table width="90%" border="0" cellpadding="2" cellspacing="1">
<tr>
<td width="20%" align="right" valign="top" class="form_label_1">
URL:
</td>
<td width="80%" align="left" valign="top" class="form_field_1">
<asp:TextBox id="fld_url" text="" size="100" maxlength="200" runat="server" />
</td>
</tr>
</table>
<hr noshade size="1">
<table width="90%" border="0" cellpadding="2" cellspacing="1">
<tr>
<td width="20%"> </td>
<td width="80%" valign="top">
<asp:Button OnClick="do_test" text="Do Base64 Test" runat="server" />
</td>
</tr>
</table>
</form>

</blockquote>
</body>
</html>

System.FormatException: Input string was not in a correct format....?

I've been working on this for a while, googled and everything, and i still can't work out what is wrong with this string... I keep getting this error:

System.FormatException: Input string was not in a correct format


public void btnCalculate_Click(object sender, System.EventArgs e)
{
double Label = Convert.ToDouble((Convert.ToInt32(lblQrtrs.Text)) + (Convert.ToInt32(lblOnes.Text)) + (Convert.ToInt32(lblTwos.Text)) + (Convert.ToInt32(lblFives.Text)) + (Convert.ToInt32(lblTens.Text)) + (Convert.ToInt32(lblTwenties.Text)) + (Convert.ToInt32(lblFifties.Text)) + (Convert.ToInt32(lblHundreds.Text)));
lblCalculate.Text = string.Format("{0:c}", Label);

Can anybody tell what i'm doing wrong here? Thanks,
Austin W.I should specify that each of those labels was already converted into a currency format from a textbox, like:


double Label = Convert.ToDouble(Convert.ToInt32(tbHundreds.Text) * 100);
lblHundreds.Text = string.Format("{0:c}", Label);

Just an update...

Ive converted my code to this...Its still not working but i feel like its on a better track than it was before, anybody got any ideas?


double Qrtrs = Convert.ToDouble(lblQrtrs.Text);
double Ones = Convert.ToDouble(lblOnes.Text);
double Twos = Convert.ToDouble(lblTwos.Text);
double Fives = Convert.ToDouble(lblFives.Text);
double Tens = Convert.ToDouble(lblTens.Text);
double Twenties = Convert.ToDouble(lblTwenties.Text);
double Fifties = Convert.ToDouble(lblFifties.Text);
double Hundreds = Convert.ToDouble(lblHundreds.Text);

double Label = (Qrtrs + Ones + Twos + Fives + Tens + Twenties + Fifties + Hundreds);
lblCalculate.Text = string.Format("{0:c}", Label);


Hi,
I am having the same problem, 'input string was not in a correctformat' when I try to convert something to double usingConvert.ToDouble(). I have a text box and if I enter something likethis, 123.45 and click on the submit button I get this error. Any help.
Thanks.


I think I got your answer. Now first I dontknow whats the string of your Label. Let's say that the label has"23.45" okay and you try to do the following:
string someString = Label1.Text;
int someInt = Int32.Parse(someString); // This will give error
It will give error since it was not able to parse the string as Int32. If you try to parse it as Double than it will run okay.
string someString = "23.45";
Double myDouble = Double.Parse(someString); // This will work fine.
Now if your lblhundred contains "100" without any decimal points than you can simply do this and it will work.
string someString = "455";
int someInt = Int32.Parse(someString);
Hope this will help!

Also check using the WebControl Type "Label" as a variable, like maybe change these two lines to:

double LabelValue = (Qrtrs + Ones + Twos + Fives + Tens + Twenties + Fifties + Hundreds);
lblCalculate.Text = string.Format("{0:c}", LabelValue);
NC...