Showing posts with label method. Show all posts
Showing posts with label method. Show all posts

Saturday, March 31, 2012

System.InvalidCastException: Specified cast is not valid

I keep geting the exception:

System.InvalidCastException: Specified cast is not valid.

I get this when I try to pass a DataRow into an object method. The line that
causes this error is:

policy.SetValues(dr);

Here is part of the class that contains the method that I want to call:

using System;
using System.Data;
using System.Collections;

namespace IDUL.Policies
{

/// <summary>
/// </summary>
public class Policy
{
private int _qid;
private int _cid;
private string _policy_number;
private string _inception_date;
private string _expiry_date;
private float _raw_premium;
private float _policy_fee;
private float _admin_fee;
private float _ipt;
private float _total_premium;
private bool _is_renewal;
private string _operator;
private string _date_quoted;
private bool _on_cover;
private string _on_cover_date;
private string _on_cover_operator;

/// <summary>
/// </summary>
public Policy()
{
Trace.Constructor("Policy()");
}

/// <summary>
/// </summary>
public Policy(DataRow dr)
{
Trace.EnterConst("Policy(dr)");

if (dr != null)
{
SetValues(dr);
}

Trace.LeaveConst("Policy(dr)");
}

public void SetValues(DataRow dr)
{
_qid = (int)dr["qid"];
_cid = (int)dr["cid"];
_policy_number = dr["policy_number"].ToString();
_inception_date = dr["inception_date"].ToString();
_expiry_date = dr["expiry_date"].ToString();
_raw_premium = (float)dr["raw_premium"];
_policy_fee = (float)dr["policy_fee"];
_admin_fee = (float)dr["admin_fee"];
_ipt = (float)dr["ipt"];
_total_premium = (float)dr["total_premium"];
_is_renewal = (bool)dr["is_renewal"];
_operator = dr["operator"].ToString();
_date_quoted = dr["date_quoted"].ToString();
_on_cover = (bool)dr["on_cover"];
_on_cover_date = dr["on_cover_date"].ToString();
_on_cover_operator = dr["on_cover_operator"].ToString();
}
}

The code that instantiates the class and calls the method is in here:

foreach (DataTable dt in dsPolicies.Tables)
{
foreach (DataRow dr in dt.Rows)
{
Policy policy = new Policy();

policy.SetValues(dr);

arrPolicies.Add(policy);
}
}

Any ideas what is causing this exception?Floela <floela@.benjamin.com> wrote:
> I keep geting the exception:
> System.InvalidCastException: Specified cast is not valid.
>
> I get this when I try to pass a DataRow into an object method. The line that
> causes this error is:
> policy.SetValues(dr);

I'm sure that's one part of the stack, but I don't think that's going
to be the actual direct causal line. I suspect it's somewhere within
SetValues itself. Have you tried stepping through SetValues to see
where the exception is thrown?

--
Jon Skeet - <skeet@.pobox.com>
http://www.pobox.com/~skeet/
If replying to the group, please do not mail me too

> I get this when I try to pass a DataRow into an object method. The line
that
> causes this error is:
> policy.SetValues(dr);
Inside SetValues there are many cast without checking,
i wonder if they are all safe ?

> public void SetValues(DataRow dr)
> {
> _qid = (int)dr["qid"];
> _cid = (int)dr["cid"];
> _raw_premium = (float)dr["raw_premium"];
> _policy_fee = (float)dr["policy_fee"];
> _admin_fee = (float)dr["admin_fee"];
> _ipt = (float)dr["ipt"];
> _total_premium = (float)dr["total_premium"];
> _is_renewal = (bool)dr["is_renewal"];
> _on_cover = (bool)dr["on_cover"];
> }
Floela <floela@.benjamin.com> wrote:
> > I'm sure that's one part of the stack, but I don't think that's going
> > to be the actual direct causal line. I suspect it's somewhere within
> > SetValues itself.
> SetValues is pretty simple - just assigning the values from the DataRow to
> private variables within the class (see my original post). There's nothing
> glaring as to where the problem could be within this method.

Yes there is - you've got lots of casts in SetValues. I'm sure it'll be
one of those which is failing.

> > Have you tried stepping through SetValues to see
> > where the exception is thrown?
> No I haven't, as I'm actually coding the application using TextPad, not
> VS.NET.

Ah. That's a pain. Can you print out a stack trace to show exactly
where it's failing?

--
Jon Skeet - <skeet@.pobox.com>
http://www.pobox.com/~skeet/
If replying to the group, please do not mail me too

Wednesday, March 28, 2012

System.IO.File.Move

Could someone tell me if the above method leaves the fiel in the original location as well or if it is deleted?Since there is a system.io.file.copy i think its pretty safe to assume that move does not leave the source file in the original directory.

MSDN (http://msdn2.microsoft.com/en-us/library/system.io.directory.move.aspx)

Monday, March 26, 2012

system.net permissions error

hey all,
i'm getting a systems.net permissions error on my page and not sure how to
resolve it. i've narrowed it down to one method. do i need to add an
attribute to that method for it to work or something?

thanks,
rodcharShow us your exact error - - -

--
David Wier
MVP/ASPInsider
http://aspnet101.com
http://aspexpress.com
"rodchar" <rodchar@.discussions.microsoft.comwrote in message
news:3E53D057-5BCA-44FB-BFDD-FA62C00CD4F0@.microsoft.com...

Quote:

Originally Posted by

hey all,
i'm getting a systems.net permissions error on my page and not sure how to
resolve it. i've narrowed it down to one method. do i need to add an
attribute to that method for it to work or something?
>
thanks,
rodchar


Description: The application attempted to perform an operation not allowed by
the security policy. To grant this application the required permission
please contact your system administrator or change the application's trust
level in the configuration file.

Exception Details: System.Security.SecurityException: Request for the
permission of type 'System.Net.WebPermission, System, Version=2.0.0.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.

"David Wier" wrote:

Quote:

Originally Posted by

Show us your exact error - - -
>
--
David Wier
MVP/ASPInsider
http://aspnet101.com
http://aspexpress.com
>
>
"rodchar" <rodchar@.discussions.microsoft.comwrote in message
news:3E53D057-5BCA-44FB-BFDD-FA62C00CD4F0@.microsoft.com...

Quote:

Originally Posted by

hey all,
i'm getting a systems.net permissions error on my page and not sure how to
resolve it. i've narrowed it down to one method. do i need to add an
attribute to that method for it to work or something?

thanks,
rodchar


>
>
>


i posted more details on my site:
http://www25.brinkster.com/rodchar/test.htm
the gist is i'm using Authorize.Net's credit card validation script for
asp.net and i'm deploying to NetworkSolutions Host Servers and i'm getting
this error. But it works on my local machine(that's a new one huh?)

any ideas would be greatly appreciated

"rodchar" wrote:

Quote:

Originally Posted by

Description: The application attempted to perform an operation not allowed by
the security policy. To grant this application the required permission
please contact your system administrator or change the application's trust
level in the configuration file.
>
Exception Details: System.Security.SecurityException: Request for the
permission of type 'System.Net.WebPermission, System, Version=2.0.0.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.
>
"David Wier" wrote:
>

Quote:

Originally Posted by

Show us your exact error - - -

--
David Wier
MVP/ASPInsider
http://aspnet101.com
http://aspexpress.com
"rodchar" <rodchar@.discussions.microsoft.comwrote in message
news:3E53D057-5BCA-44FB-BFDD-FA62C00CD4F0@.microsoft.com...

Quote:

Originally Posted by

hey all,
i'm getting a systems.net permissions error on my page and not sure how to
resolve it. i've narrowed it down to one method. do i need to add an
attribute to that method for it to work or something?
>
thanks,
rodchar


System.Net.Mail.SmtpClient Send method causing an Application popu

Peter,
thanks for your response. I checked my web.config and debug is set to
false. I did some searching on google for the proper reg key to modify
to disable this behavior, but was unsuccessful. Aside from needing to
figure out how to fix this, I'd love to also know *why* it's happening.
All other exceptions thrown in my web app get caught by exception
handlers except this one.
: (There is some unmanaged code stuff going on at the lower levels. My
experience with smtp and the .net controls led me to test locally and I had
to use devmail.net's product to get my sends to work. Even with a detail
trace on what was going on at the port level, I never could sort out my
issue. -greg
<ticketdirector@.gmail.com> wrote in message
news:1145937326.974099.280800@.i40g2000cwc.googlegroups.com...
> Peter,
> thanks for your response. I checked my web.config and debug is set to
> false. I did some searching on google for the proper reg key to modify
> to disable this behavior, but was unsuccessful. Aside from needing to
> figure out how to fix this, I'd love to also know *why* it's happening.
> All other exceptions thrown in my web app get caught by exception
> handlers except this one.
> : (
>

Saturday, March 24, 2012

System.Net.WebException: The remote server returned an error: (500) Internal Server Error.

Hi
I am trying to consume a web service from asp.net web page through
HTTP POST method and I am getting the following error message

"System.Net.WebException: The remote server returned an error: (500)
Internal Server Error."

I have been searchign the web and followed all the options which worked

for others

1. Changed the web.config of the web service to accomodate HttpPost
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices
2. Used the HttpRequest.Credentials =
CredentialCache.DefaultCredentials;

I am not sure what is wrong there it fails while the request is sent to

the web service. The web service works fine with other web clients

Let me know your ideas

thanks
MohanOther web clients? What is different? Run the debugger on the server,
set a breakpoint and POST from your client, and step through the code
sirfunusa wrote:
> Other web clients? What is different? Run the debugger on the server,
> set a breakpoint and POST from your client, and step through the code

Other clients I mean when I reference the web service and access the
web method it works fine...But when I use an ASP.NET page with the
HTTPReuest Object as shown below it throws the error

"System.Net.WebException: The remote server returned an error: (500)
Internal Server Error."

Code :

HttpWebRequest wr =
(HttpWebRequest)WebRequest.Create("http://localhost//SubtractNumbers//Service1.asmx//Subtract");

wr.Method = "POST";
wr.ContentType = "application/x-www-form-urlencoded";
//wr.ContentLength = bytes.Length;

StreamWriter writer = new
StreamWriter(wr.GetRequestStream(),System.Text.Enc oding.UTF8);
//// Write the xml text into the stream
writer.WriteLine("Hi");
writer.Close();

WebResponse wrs = wr.GetResponse();
Stream strm = wrs.GetResponseStream();
StreamReader sr = new StreamReader(strm);
String line;
while( (line = sr.ReadLine()) != null)
Response.Write(line);
strm.Close();
sirfunusa wrote:
> Other web clients? What is different? Run the debugger on the server,
> set a breakpoint and POST from your client, and step through the code

Other clients I mean when I reference the web service and access the
web method it works fine...But when I use an ASP.NET page with the
HTTPReuest Object as shown below it throws the error

"System.Net.WebException: The remote server returned an error: (500)
Internal Server Error."

Code :

HttpWebRequest wr =
(HttpWebRequest)WebRequest.Create("http://localhost//SubtractNumbers//Service1.asmx//Subtract");

wr.Method = "POST";
wr.ContentType = "application/x-www-form-urlencoded";
//wr.ContentLength = bytes.Length;

StreamWriter writer = new
StreamWriter(wr.GetRequestStream(),System.Text.Enc oding.UTF8);
//// Write the xml text into the stream
writer.WriteLine("Hi");
writer.Close();

WebResponse wrs = wr.GetResponse();
Stream strm = wrs.GetResponseStream();
StreamReader sr = new StreamReader(strm);
String line;
while( (line = sr.ReadLine()) != null)
Response.Write(line);
strm.Close();
Are you sending the proper XML message (SOAP)? If your message isn't
formatted properly, you will definately get a server 500 error back.
It looks liek you are actually just sending text ("Hi"). That's not a
proper SOAP message. Here is a sample of a SOAP message:
http://www.w3.org/2004/06/03-google-soap-wsdl.html .

I personally much of web services manually because it's just easier to
interop with COM that way.

Here's part of what I do... (also be sure to set your SOAPAction in the
http header!) messageData hold my XML message I'm sending.

ASCIIEncoding encoding = new ASCIIEncoding( );
byte[] buffer = encoding.GetBytes(messageData);

HttpWebRequest myRequest =
(HttpWebRequest)WebRequest.Create(this.EndPoint);
myRequest.Method = "POST";
myRequest.ContentType = "text/xml";
myRequest.ContentLength = buffer.Length;
myRequest.Headers.Add(String.Format("SOAPAction: \"{0}\"",
operationName));
myRequest.Timeout = 10000;

using (Stream newStream = myRequest.GetRequestStream( )) {
newStream.Write(buffer, 0, buffer.Length);
newStream.Close( );
}

HttpWebResponse myHttpWebResponse =
(HttpWebResponse)myRequest.GetResponse( );

string rawResponse =
GetWebResponseString(myHttpWebResponse);

myHttpWebResponse.Close( );

Here is the GetWebResponseString method...

private static string GetWebResponseString(WebResponse
myHttpWebResponse) {
StringBuilder rawResponse = new StringBuilder( );
using (Stream streamResponse =
myHttpWebResponse.GetResponseStream( )) {
using (StreamReader streamRead = new
StreamReader(streamResponse)) {
Char[] readBuffer = new Char[256];
int count = streamRead.Read(readBuffer, 0, 256);

while (count > 0) {
String resultData = new String(readBuffer, 0,
count);
rawResponse.Append(resultData);
count = streamRead.Read(readBuffer, 0, 256);
}
}
}
return rawResponse.ToString( );
}

Look closely at what is returned. You may actually be getting the
reason for the fault in the message.

Also, if all is successful, you will get an XML message back. Are you
prepared to parse it?

You may want to actually use the .NET web service mechanism if you
don't want to do everything manually. Since you aren't using the .NET
web service mechanism the web.config configuration doesn't apply.

If you are intending to use .NET for web services, then all you have to
do is add the WSDL file as a web reference and use it as though it were
local. There's not really much work to it. If that is the case then
everything I said above is void, since this is the manual way to do it.

System.Nullable 2.0 Framework

The 2.0 Framework has a new type called System.Nullable. This allows
something to Not exist, basically you can pass 'Nothing' to a method whose
parameters as System.Nullable.
Im looking at table adapters ; you know those clever little things which
allow you to contrsuct methods for manipulating data use this. So a method
might be declared someting like this.
Private Sub myMethod(ByVal myYear As System.Nullable(Of Integer), ByVal
myw As System.Nullable(Of Integer))
End Sub
My question is. How to I translate this into a practical method call for a
value which may or may not exits. Lets say we have two text boxes.
yearTextBox and wTextBox.
How to I assign an integer value or nothing depending on if the box is
emtpy, because you cant assign nothing to an integer. I dont want multiple
call lines to the one method, just one.
Goofy
GoofyGot it
Dim year As System.Nullable(Of Single)
Dim w As System.Nullable(Of Integer)
"Goofy" <me@.mine.com> wrote in message
news:%23X%23OA%23DJHHA.320@.TK2MSFTNGP06.phx.gbl...
> The 2.0 Framework has a new type called System.Nullable. This allows
> something to Not exist, basically you can pass 'Nothing' to a method whose
> parameters as System.Nullable.
> Im looking at table adapters ; you know those clever little things which
> allow you to contrsuct methods for manipulating data use this. So a method
> might be declared someting like this.
> Private Sub myMethod(ByVal myYear As System.Nullable(Of Integer), ByVal
> myw As System.Nullable(Of Integer))
> End Sub
> My question is. How to I translate this into a practical method call for a
> value which may or may not exits. Lets say we have two text boxes.
> yearTextBox and wTextBox.
> How to I assign an integer value or nothing depending on if the box is
> emtpy, because you cant assign nothing to an integer. I dont want multiple
> call lines to the one method, just one.
> --
> Goofy
>
> --
> Goofy
>
"Goofy" <me@.mine.com> wrote in message
news:uMXc8jEJHHA.3872@.TK2MSFTNGP06.phx.gbl...

> Got it
> Dim year As System.Nullable(Of Single)
> Dim w As System.Nullable(Of Integer)
Not sure about VB.NET, but in C# v2 you can do this simply by appending a
question mark to the datatype e.g.
Int32 intYear = 0; // not nullable
Int32? intYear = null; // nullable
Didnt know that, but then I dont code in C# normally. This nullable facility
is really usefull in some situations I find.
"Mark Rae" <mark@.markNOSPAMrae.com> wrote in message
news:utmozHFJHHA.536@.TK2MSFTNGP02.phx.gbl...
> "Goofy" <me@.mine.com> wrote in message
> news:uMXc8jEJHHA.3872@.TK2MSFTNGP06.phx.gbl...
>
> Not sure about VB.NET, but in C# v2 you can do this simply by appending a
> question mark to the datatype e.g.
> Int32 intYear = 0; // not nullable
> Int32? intYear = null; // nullable
>
"Goofy" <me@.mine.com> wrote in message
news:%23r$GlYOJHHA.3264@.TK2MSFTNGP02.phx.gbl...

> Didnt know that, but then I dont code in C# normally.
Conversely, I never go anywhere near VB.NET... :-)

> This nullable facility is really usefull in some situations I find.
I couldn't agree more! One of the most important enhancements in v2, along
with generics.

System.Nullable 2.0 Framework

The 2.0 Framework has a new type called System.Nullable. This allows
something to Not exist, basically you can pass 'Nothing' to a method whose
parameters as System.Nullable.

Im looking at table adapters ; you know those clever little things which
allow you to contrsuct methods for manipulating data use this. So a method
might be declared someting like this.

Private Sub myMethod(ByVal myYear As System.Nullable(Of Integer), ByVal
myweek As System.Nullable(Of Integer))

End Sub

My question is. How to I translate this into a practical method call for a
value which may or may not exits. Lets say we have two text boxes.
yearTextBox and weekTextBox.

How to I assign an integer value or nothing depending on if the box is
emtpy, because you cant assign nothing to an integer. I dont want multiple
call lines to the one method, just one.

--
Goofy

--
GoofyGot it

Dim year As System.Nullable(Of Single)

Dim week As System.Nullable(Of Integer)

"Goofy" <me@.mine.comwrote in message
news:%23X%23OA%23DJHHA.320@.TK2MSFTNGP06.phx.gbl...

Quote:

Originally Posted by

The 2.0 Framework has a new type called System.Nullable. This allows
something to Not exist, basically you can pass 'Nothing' to a method whose
parameters as System.Nullable.
>
Im looking at table adapters ; you know those clever little things which
allow you to contrsuct methods for manipulating data use this. So a method
might be declared someting like this.
>
Private Sub myMethod(ByVal myYear As System.Nullable(Of Integer), ByVal
myweek As System.Nullable(Of Integer))
>
End Sub
>
My question is. How to I translate this into a practical method call for a
value which may or may not exits. Lets say we have two text boxes.
yearTextBox and weekTextBox.
>
How to I assign an integer value or nothing depending on if the box is
emtpy, because you cant assign nothing to an integer. I dont want multiple
call lines to the one method, just one.
>
--
Goofy
>
>
>
--
Goofy
>


"Goofy" <me@.mine.comwrote in message
news:uMXc8jEJHHA.3872@.TK2MSFTNGP06.phx.gbl...

Quote:

Originally Posted by

Got it
>
Dim year As System.Nullable(Of Single)
>
Dim week As System.Nullable(Of Integer)


Not sure about VB.NET, but in C# v2 you can do this simply by appending a
question mark to the datatype e.g.

Int32 intYear = 0; // not nullable
Int32? intYear = null; // nullable
Didnt know that, but then I dont code in C# normally. This nullable facility
is really usefull in some situations I find.

"Mark Rae" <mark@.markNOSPAMrae.comwrote in message
news:utmozHFJHHA.536@.TK2MSFTNGP02.phx.gbl...

Quote:

Originally Posted by

"Goofy" <me@.mine.comwrote in message
news:uMXc8jEJHHA.3872@.TK2MSFTNGP06.phx.gbl...
>

Quote:

Originally Posted by

>Got it
>>
>Dim year As System.Nullable(Of Single)
>>
>Dim week As System.Nullable(Of Integer)


>
Not sure about VB.NET, but in C# v2 you can do this simply by appending a
question mark to the datatype e.g.
>
Int32 intYear = 0; // not nullable
Int32? intYear = null; // nullable
>


"Goofy" <me@.mine.comwrote in message
news:%23r$GlYOJHHA.3264@.TK2MSFTNGP02.phx.gbl...

Quote:

Originally Posted by

Didnt know that, but then I dont code in C# normally.


Conversely, I never go anywhere near VB.NET... :-)

Quote:

Originally Posted by

This nullable facility is really usefull in some situations I find.


I couldn't agree more! One of the most important enhancements in v2, along
with generics.

System.Nullreference Exception

i have written the following code to call a method in a class like

in the aspx.cs page
List<string> surls = new List<string>();

Cweb.GetMainUrls(document,ref surls);
Response.Write(surls);

in the Cweb Class page the coding is like

public static void GetMainUrls(Htmldocument doc,ref List<string> urls)
{
//Some functionalities
}

i get the following error when i run the application like

System.NullReference Exception
object reference not set to an instance

so because of this error my method is not getting called from the class and hence no result

can anyone help me out in finding like why my method was not called

i google through several sites and found that
this may be due to the fact that the "surls" are null and hence the method was not called
i dont follow these sequence

so anybody plz help me on this regard
thanks
Rama

System.NullReference Exception means you have referred an object, while this object is not instantialized.
object reference not set to an instance"this may be due to the fact that the "surls" are null and hence the method was not called " --> i think it's probablely because of that. So, set a break point there and debug. then see what the value of urls is. (well, response.write maybe a easier way to do that)

Hope my suggestion helps :)

Tuesday, March 13, 2012

System.StackOverflowException: Exception of type System.StackO

Thx mate.
I get it when i work with VS.NET!
But works with asp.net
Do u know why?:)
"Psycho" wrote:
> this should happen when you have a cicling method which is never finishig.
> It should happen to have a property like this
> when i work with VS.NET
> private int a ;
> public int A{
> get{ return A;} instead of A put a
> set{ A = value;} instead of A put a
> }
> this is the most usuall content in which you get the error.
> "Patrick.O.Ige" wrote:
>it is throw when you make an infinite recurvise method.
http://msdn.microsoft.com/library/d...nclasstopic.asp
"Patrick.O.Ige" wrote:
> Thx mate.
> I get it when i work with VS.NET!
> But works with asp.net
> Do u know why?:)
>
> "Psycho" wrote:
>