Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Question
Tuesday, December 27, 2011 4:57 AM
I am new to web service it show error like this....
pls reply soon as possible....
my source is:-
[WebMethod]
public string[] ValidateUser(string user_name, string password)
{
try
{
using (SqlCon)
{
SqlCon.Open();
SqlDataAdapter da = new SqlDataAdapter("EXEC MASTER.WEB_OF_CHECKUSERNAMEPWD " + "'" + user_name.Trim().ToString() + "'" + "," + "'" + password.Trim().ToString() + "'", SqlCon);
DataTable dt = new DataTable();
da.Fill(dt);
string[] items = new string[dt.Rows.Count];
int i = 0;
foreach (DataRow dr in dt.Rows)
{
items.SetValue(dr[
"USER_LEVEL_NAME"].ToString(), i);
i++;
}
//error = null;
//return items.ToArray();
return items;
}
}
catch (Exception e)
{
return (e.Message.);
//return null;
}
finally
{
SqlCon.Close();
}
}
All replies (31)
Thursday, December 29, 2011 12:30 AM ✅Answered
Please try this code:
catch (Exception e)
{
string[] items = new string[]{};
return items;
}
Thursday, December 29, 2011 9:29 PM ✅Answered
return (e.Message.); // this is NOT a string[] !!!!!!!!!!!!!
@ lamado
you're correct; i've validated this via experimentation ... via LINQPad 4 all of this is valid:
string[] three_items = new string[3];
string[] one_item = new string[1];
string[] zero_items = new string[0];
string[] result_array;
result_array = three_items;
result_array.Dump("result array for three_items");
result_array = one_item;
result_array.Dump("result array for one_item");
result_array = zero_items;
result_array.Dump("result array for zero_items");
three_items.Dump("three_items");
one_item.Dump("one_item");
zero_items.Dump("zero_items");
FWIW, i personally would never create a zero items array because i have not yet found a scenario where doing so makes sense.
lamado, your reply to my speculation has led me to re-examine the O.P. ... this has in turn led me to notice a serious flaw.
i previously stated: FWIW, with string[], above, you've made a promiss to return a string array.
there is a place in the O.P. where this promise has been broken:
return (e.Message.); // e.Message is NOT a string array !!!!!
http://msdn.microsoft.com/en-us/library/system.exception.message.aspx "Exception.Message Property"
Property Value
Type: System.String
The error message that explains the reason for the exception, or an empty string("").
@ jafferpg
it looks like your problem is the return (e.Message) statement.
TIMTOWTDI =. there is more than one way to do it
Reformat your promise:
public bool ValidateUser(string user_name, string password, out string[] rows)
(a) if you succeed, return true with your **string[] **as the out parameter containing 1 to n rows.
(b) if you have zero rows, return false with your string[] as the out parameter where string[0] = "zero rows found".
(c) if you fail, return false with your string[] as the out parameter where string[0] = e.Message.
g.
http://msdn.microsoft.com/en-us/library/ee332485.aspx "out parameter modifier (C# Reference)"
Monday, January 2, 2012 6:59 AM ✅Answered
Hi frnds..
Thanks a lot...
sorry for late reply... problem solved..
thanks once again... every one gave valuable suggestion ...
but this(Anna) suggestion works finely....
** catch (Exception e)
{
string[] items = new string[]{};
return items;
}**
Monday, January 2, 2012 11:39 AM ✅Answered
@ jafferpg
sorry, but imho, your chosen solution is not a good solution because it ignores the fact that an Exception has occurred.
generally, (a) exceptions should NEVER be ignored, (b) methods that might experience an exception should return an indication of success or failure, and (c) the calling code MUST analyze the returned values (plural) and take appropriate action based on those returned values.
For example, as per my previous reply in this thread (TIMTOWTDI =. there is more than one way to do it):
You could reformat your promise:
public bool ValidateUser(string user_name, string password, out string[] rows)
(a) if you succeed, return true with your **string[] **as the out parameter containing 1 to n rows.
(b) if you have zero rows, return false with your string[] as the out parameter where string[0] = "zero rows found".
(c) if you fail, return false with your string[] as the out parameter where string[0] = e.Message.
With the above strategy, your calling code could analyze the success or failure and then take appropriate action, for example:
(in your calling code):
string**[] rows;
bool success = ValidateUser(user_name, password, out rows);**
if (success)
{
// take appropriate action for successful validation
}
else
{
if (rows[0] == "zero rows found")
{
// take appropriate action for user not found
}
else // rows[0] contains the value of e.Message
{
// take appropriate action because an exception has occurred *
}
}
* for example, you could log the exception .Message text and/or e-mail it to your help desk.
g.
Tuesday, December 27, 2011 5:05 AM
Hello.
I´m guessing that it´s you SetValue that gives you the trubble...
Try:
items[i] = your data row value...
Edit: maybe that not it btw... :) I believe that you may be getting an exception... and then you try to return the exception message (that is a string...) and then you get your error.
Regards
Uffe
Tuesday, December 27, 2011 5:08 AM
Hi Friend,
I didn't find any error in your code. items is an string array and you are adding values using index.
If possible provide me few more information.
Thanks.
Tuesday, December 27, 2011 5:12 AM
public string[] ValidateUser(string user_name, string password)
{
try
{
string SqlCon = "xczxx";
using (SqlCon)
{
SqlCon.Open();
SqlDataAdapter da = new SqlDataAdapter("EXEC MASTER.WEB_OF_CHECKUSERNAMEPWD " + "'" + user_name.Trim().ToString() + "'" + "," + "'" + password.Trim().ToString() + "'", SqlCon);
DataTable dt = new DataTable();
da.Fill(dt);
string[] items = new string[dt.Rows.Count];
int i = 0;
foreach (DataRow dr in dt.Rows)
{
items.SetValue(dr[
"USER_LEVEL_NAME"].ToString(), i);
i++;
}
//error = null;
//return items.ToArray();
return items;
}
}
catch (Exception e)
{
//return (e.Message);
return null;
}
finally
{
SqlCon.Close();
}
}
Tuesday, December 27, 2011 5:14 AM
Hi,
Here is the sample Code for Web service,
[WebMethod]
public string[] GetClientName(string prefixText, int count)
{
DataSet dataSet = objManager.GetSearchData(objComplete);
List<string> items = new List<string>(dataSet.Tables[0].Rows.Count);
if (dataSet.Tables[0] != null)
{
for (int i = 0; i <= dataSet.Tables[0].Rows.Count - 1; i++)
{
if (!items.Contains(dataSet.Tables[0].Rows[i]["DisplayName"].ToString().Trim()))
items.Add(dataSet.Tables[0].Rows[i]["DisplayName"].ToString().Trim());
}
}
return items.ToArray();
}
Tuesday, December 27, 2011 5:27 AM
Hi friends...
thanks for your quick reponse...
My coding is correct.
but it show error in catch exception only....
pls tel me what i can do?...
Tuesday, December 27, 2011 5:30 AM
hi sunilgurjar,
your coding is correct... but if i use return null in catch exception then it will not show error...
Tuesday, December 27, 2011 5:37 AM
Hi jafferpg,
Set a breakpoint in your function. and Please tell us what error you are getting and which line.
Tuesday, December 27, 2011 6:01 AM
Hi kuber manral,
My function is correct... i need to throw the error in catch exception.....
catch (Exception e)
{
return e.Message;
}
it show error Cannot implicitly convert type 'string' to 'string[]' into return e.message only....... instead if that what can i use???....
if i use return null means it will not throw error...
pls reply.....
Tuesday, December 27, 2011 6:39 AM
Hi,
Please find my Modified method here. Please make a try and let us know the reult. However it is not tested.
public string[] GetClientName(string prefixText, int count, ref string strErrorMessage)
{
strErrorMessage = "";
try
{
objBMAutoComplete.SearchString = prefixText;
objBMAutoComplete.RequestFrom = "CL";
objBMAutoComplete.SearchFor = "NAME";
DataSet dataSet = objBMAutoCompleteManager.GetINCAutoSearchData(objBMAutoComplete);
List<string> items = new List<string>(dataSet.Tables[0].Rows.Count);
if (dataSet.Tables[0] != null)
{
for (int i = 0; i <= dataSet.Tables[0].Rows.Count - 1; i++)
{
if (!items.Contains(dataSet.Tables[0].Rows[i]["DisplayName"].ToString().Trim()))
items.Add(dataSet.Tables[0].Rows[i]["DisplayName"].ToString().Trim());
}
}
return items.ToArray();
}
catch (SoapException ex)
{
strErrorMessage = ex.Message;
return null;
}
}
Tuesday, December 27, 2011 6:54 AM
Hello, as I stated earlier your issue is "return e.Message"
I would use a wrapper for my response with the error attached... But if you just want it to work return "return new List<string>{e.Message};"
Tuesday, December 27, 2011 7:08 AM
Hi,
Have you noticed ref parameter there. like :
public string[] GetClientName(string prefixText, int count, ref string strErrorMessage)
If any Exception would occur, it would save into this string and returned.
Sorry If I mis-understood!!!
Tuesday, December 27, 2011 8:12 AM
Hi jafferpg,
Cannot implicitly convert type 'string' to 'string[]'
The error indicates that somewhere in your code (ToString()) the multiple strings are not looped.
Error solution could be:
giving the ToString() method a splitter (, or ) like this:
ToString("<array_splitter>.ToCharArray()");
please verify the sytax that works for you.
hope this helps you!!
Tuesday, December 27, 2011 6:18 PM
Delete the catch block. Let the exception propagate.
Use the return value from the method as the normal case, you are trying to use the return value during the exceptional case.
Wednesday, December 28, 2011 6:50 AM
Hi all,
sorry to tel no one tel the correct answer.. i think i am not explainig clearly....
simple... my coding is correct... but exception error would not showin error in catch exception .....
what i want to write in catch exception to avoid Cannot implicitly convert type 'string' to 'string[]' .....pls i need only answer i think its only one word ... i am new to web service thats why struggling....
Thanks ...
Wednesday, December 28, 2011 7:02 AM
Give try to cast or conversion inner exception. To reproduce and check pls let us know the version of framework,
InvalidCastException
verify and let us know.
Wednesday, December 28, 2011 7:11 AM
Hi,
if just want to remove this error, don't need to set anything (like for ex.Message). Just return NULL there. and if you want to return some message from there, create a ref parameter in argument list and set its value. As I have specified in my previous example.
Correct Me, If I am Wrong !!!
Wednesday, December 28, 2011 7:23 AM
Hi Kuber,
S i want to return some exception message from there so i cant use null.....
As you said earlier example i tried ref parameter in argument list and set a value..
but thats not working... its show empty ....
Thursday, December 29, 2011 5:34 AM
@ jafferpg
public string[] ValidateUser(string user_name, string password)
FWIW, with string[], above, you've made a promiss to return a string array.
imho, i'd make this change:
public List<string> ValidateUser(string user_name, string password)
i.e., i'd promiss to return a list of strings.
i'm making an assumption that you could return an empty list if zero data rows are found.
string[] items = new string[dt.Rows.Count]; // what if dt.Rows.Count == 0?
1.8 Arrays
An array is a data structure that contains a number of variables that are accessed through computed indices.
The variables contained in an array, also called the elements of the array, are all of the same type, and this type is called the element type of the array.
Array types are reference types, and the declaration of an array variable simply sets aside space for a reference to an array instance.
Actual array instances are created dynamically at run-time using the new operator.
The new operation specifies the length of the new array instance,
which is then fixed for the lifetime of the instance.
The indices of the elements of an array range from 0 to Length - 1.
The index for string[] items = new string[1] is 0.
The indices for string[] items = new string[3] would be 0, 1, and** 2**.,
The index for string[] items = new string[0] is likely undefined.
Since dt.Rows.Count could be zero, AFAIK, your best choice is to use a list of strings instead of string[].
You would .Add each row and return your List<string>.
your calling code would need to check whether .Count is greater than zero.
http://msdn.microsoft.com/en-us/library/6sh4ey19.aspx "List<T> Class"
http://msdn.microsoft.com/en-us/library/27b47ht3.aspx "List<T>.Count Property"
g.
Thursday, December 29, 2011 7:35 AM
i do not think that there is a big problem for using string[] instead if List<string> , because string is initiated by :
string[] items = new string[dt.Rows.Count];
which means that it could contain zero items just fine
@ the topic starter
what line of code does the exception occures ?
use the debugger ?
Thursday, December 29, 2011 8:48 AM
Hi jafferpg,
If my code is not working (As you said it is not returning anything), it may be because i havn't tested that. So Now, My Suggestion is that you should remove try-catch block from your web service and let generate the Exception. You should handle this exception at page level, where you are using that particular exception.
Now i have some point here:
First, we should not bother about any error message text, that is only helpful at developer level. As far as user is concern, we would not show that particular message to user. So we are jsut handling it and showing any custom message to user.
Second,I have used So many web services(Also third party concern here), they generally used to provide some Error code, and then on the basis of that Error Code, we here decide what error message should be there on screen to user.
Correct Me, If I am Wrong!!!
Thursday, December 29, 2011 9:45 PM
First, we should not bother about any error message text,
that is only helpful at developer level.
let me rephrase this: i think you want to say something like: as much as possible, avoid error messages that might confuse a non-technical end user ...
basically, an error message is absolutely essential ... this in turn means that in our catch block, we must analyse e.Message for messages that we expect and recognize and re-interpret such messages into ones that are meaningul to end users ... for unrecognized values of e.Message, we should return something like "unexpected error: " + e.Message.
g.
Thursday, December 29, 2011 9:50 PM
Without going into the merit of the solution, if you just want to get rid of the error, change the code in the exception handler to the following:
catch (Exception e)
{
return (new String[] {e.Message});
}
Instead of returning the exception message as a string, I am returning it as a String[] to match the return type of your function
Thursday, December 29, 2011 10:58 PM
technically, the following works, but it is not a good idea:
catch (Exception e)
{
return (new String[] {e.Message}); // not a good idea
}
the problem with the above solution is that the calling code can not easily determine whether the returned string[] is an error message from the catch block or data from the SQL database.
g.
Thursday, December 29, 2011 11:11 PM
I am aware of that and have said so in my post.
Monday, January 2, 2012 7:11 AM
i am getting the same error as the one posted here
this is my code.
ublic string employee(string name)
{
string[] emp = new string[5];
for (int i = 0; i < emp.Length; i++)
return emp;
}
Monday, January 2, 2012 11:08 AM
@ Oman88
Your error is the opposite ... ypur promised to return a string ...
public string employee(string name)
but instead you are trying to return an array of strings, i.e., string[]
**N.B.: ** if you really want to return an array of strings, then you must change your method definition to:
public sting[] employee(string name)
g.
Monday, January 2, 2012 12:26 PM
@Gerrylowry
yes, you are absolutely correct...