Cannot Convert from 'List<T>' to 'T[]' - c#

I am trying to pass a list object of type List<UploadQueue> to a WCF SOAP
method of the same parameter type and I am getting the error:
Cannot Convert from
'System.Collections.Generic.List'
to 'WebAPI.Upload.UploadQueue[]'
I don't understand this because my WCF method's (below) parameter type is List<UploadQueue>:
IService.DoUpload(List<UploadQueue> request)
Here is the code that calls "DoUpload" which returns the above error.
List<UploadQueue> results = new List<UploadQueue>();
HttpPostedFile m_objFile = default(HttpPostedFile);
int m_objFlag = default(int);
Guid m_objGuid = Guid.NewGuid();
DateTime m_objDate = DateTime.Now;
try
{
if (Request.Files.Count > 0)
{
for (var j = 0; i <= (Request.Files.Count - 1); j++)
{
m_objFile = Request.Files[j];
if (!(m_objFile == null | string.IsNullOrEmpty(m_objFile.FileName) | m_objFile.ContentLength < 1))
{
results.Add(new UploadQueue(
m_objGuid,
m_objFlag,
m_objFile.ContentLength,
m_objFile.FileName,
m_objDate)
);
}
}
}
}
catch (Exception ex)
{
//handle error
}
retParam = upload.DoUpload(results);
Ideas? Thanks.

In your client project, you need to right click on the service reference and select "Configure Service Reference". On configuration screen, in the Data Type section, you need to set the collection type to System.Collections.Generic.List instead of System.Array.

The generated client has replaced the List with an Array (The default behaviour). With VS.NET 2008 you have the option of generating this with a List instead- look at the Configure Service Dialog Box. As other have said ToArray will work.

Try doing results.ToArray(). That will probably fix it.
upload.DoUpload(results.ToArray());
The problem is that the soap service says that it wants an array of objects, and not a list. When the proxy class is built from the WSDL, it converts it to the most basic object it can that satisfies the needs of the service which is an array.

retParam = upload.DoUpload(results.ToArray());
...or similar.

Related

Unable to cast object of type 'System.Collections.ObjectModel.ObservableCollection`1[System.Int32]' to type 'System.IConvertible'

I have wcf service for login user that is returning two int type values that is working fine , but the problem is when the response is sent via windows 8.1 app its throws an exception :
Unable to cast object of type 'System.Collections.ObjectModel.ObservableCollection`1[System.Int32]' to type 'System.IConvertible
code :
loginCS _login = new loginCS();
_login.Email = tEmailtxt.Text;
_login.Password = tPasstxt.Text;
var result = await _client.UserSignInAsync(_login);
try
{
GlobalClass.GlobalSchid = Convert.ToInt32(result);
GlobalClass.GlobalUid = Convert.ToInt32(result);
this.Frame.Navigate(typeof(HubPage));
}
catch { }
the code :
GlobalClass.GlobalSchid = Convert.ToInt32(result);
is throwing exception.
You are trying to cast the entire selection to an int.
Access the data inside of the collection and then cast that data, not the collection itself.

client service reference not working ToArray

I am trying to fix this problem with my client
I got the error : Cannot implicitly convert type 'DentistServiceReference.Dentist[]' to 'DentistServiceReference.DentistServiceClient[]'
Here is the code:
private List<DentistServiceReference.DentistServiceClient> DentistDetail()
{
DentistServiceReference.DentistServiceClient client = new
DentistServiceReference.DentistServiceClient();
DentistServiceReference.DentistServiceClient[] dentists = client.DentistDetail(); <== error
return dentists.ToList();
I also tried to change the client.DentistDetail().ToArray but still have an error.
Cannot convert method group 'ToArray' to non-delegate type 'DentistServiceReference.DentistServiceClient[]'. Did you intend to invoke the method?
I went under App_WebReferences, right click Add Service Reference, Discover choose my DentistService.svc, go to Advanced tab and under Collection Type: System.Array, Should I change it to system.collections.generic.list ? I saw also System.Collections.ArrayList can you explain me what are the difference and what will be resolve my problem ? Thanks a lot
Here is the DentistService.cs
public class DentistService : IDentistService
{
/* public List<Dentist> DentistDetail() */ use to be like this before the change
public List<DentistServiceReference.Dentist> DentistDetail()
{
using (DentistDataContext db = new DentistDataContext())
{
return (from dentist in db.Dentists
select new Dentist()
{
Id = dentist.Id,
Dentist_name = dentist.Dentist_name
}).ToList(); <=== error after the change
}
}
}

changing webservice calls to test or prod via radio button

I have created a vsto application that calls a webservice. everything seems to work just fine, but i would like to extend the functionality to call the test service version of my production service.
code snippet that works that calls my test service.
//how do i change here to be dynamic?
npfunctions.finfunctions service = new npfunctions.finfunctions();
var Results = service.ValidateFoapal(index.ToArray(), fund.ToArray(), org.ToArray(), prog.ToArray(), acct.ToArray(), row.ToArray());
/* if their are no error then return a "Y" for success.*/
if (Results.Count() < 0) { return LocallErrorInd; }
/*well we have encountered errors lets adjust the spreadsheet to notify the user.*/
else{
//REMOVE ANY VISUAL ERRORS
Microsoft.Office.Interop.Excel.Range delRng = Globals.ThisAddIn.Application.Range["R:S"];
delRng.Delete(XlDeleteShiftDirection.xlShiftToLeft);
for (int i = 0; i < Results.Count(); i++)
{//set the error indicator
LocallErrorInd = "Y";
//account error:
if (Results[i].FVALJOR_FUND_WARNING == "Y")
{
Microsoft.Office.Interop.Excel.Range WrkRng = Globals.ThisAddIn.Application.Range[Results[i].FVALJOR_ROW];
WrkRng.Offset[0, 17].Value2 = "Invalid Account";
}
i have seen this post How can I dynamically switch web service addresses in .NET without a recompile?
but it requires me to change my config file i would really like to change the service variable to point to another location based on a variable and basically flip from prod to test on my command. as i see it right now it appears that i would have to duplicate the code but i know there has got to be a better way. i like it to be something like.
if (TestBtn.Checked == true)
{
npfunctions.finfunctions service = new npfunctions.finfunctions();
Results = service.ValidateFoapal(index.ToArray(), fund.ToArray(), org.ToArray(), prog.ToArray(), acct.ToArray(), row.ToArray());
}
if (PrdBtn.Checked == true)
{
prdFunctions.finfunctions service = new prdFunctions.finfunctions();
Results = service.ValidateFoapal(index.ToArray(), fund.ToArray(), org.ToArray(), prog.ToArray(), acct.ToArray(), row.ToArray());
}
/* if their are no error then return a "Y" for success.*/
if (Results.Count() < 0) { return LocallErrorInd; }
Does your service object not have a URL property?
2nd option, you can use a config file transformation so you do not need to manually change the settings(after the intial setup of course).
npfunctions.finfunctions service = new npfunctions.finfunctions();
if (TestBtn.Checked == true)
{
service.url="<testurl>";
}
else
{
service.url="<produrl>";
}
Results = service.ValidateFoapal(index.ToArray(), fund.ToArray(), org.ToArray(), prog.ToArray(), acct.ToArray(), row.ToArray());
In our test client we have a drop-down to select between dev or tst. We also have buttons to select proxy or net.tcp. (We have many different people using our service using different methods).
In the app.config the names of the endpoints correlate with different selectable options.
Eg. name="BasicHttpBinding_IInterface_PROXY_DEV"
You can then dynamically build up which endpoint you would like to use and go with that.

Currency Convertor Web Service

I am trying to make use of a currency conversion web service in my website. I have added a reference to the .asmx file.
Here is my code:
net.webservicex.www.CurrencyConvertor Convertor; //creating instance of web service
float new_donation = donation * Convertor.ConversionRate("EUR", "GBP"); //converting donation to new value
The problem is that the second line I posted is giving me the following errors:
The best overloaded method match for 'abc.net.webservicex.www.CurrencyConvertor.ConversionRate(abc.net.webservicex.www.Currency, abc.net.webservicex.www.Currency)' has some invalid arguments
Argument 1: cannot convert from 'string' to 'abc.net.webservicex.www.Currency'
Argument 2: cannot convert from 'string' to 'abc.net.webservicex.www.Currency'
Here is the link to the web service description:
http://www.webservicex.net/ws/wsdetails.aspx?wsid=10
How can I solve this problem? Thank you in advance.
It's telling you clear as day... you're passing in 2 strings to you're ConversionRate(...) method when it is expecting 2 Currencys.
This seems like it might not be a WebService you are in control of, but just a consumer of...
First, the easiest way to handle consuming this WebService is to use the "Add Service Reference..." in your project (WSDL Address: http://www.webservicex.net/CurrencyConvertor.asmx?WSDL) ...
But, if you want to do it manually then create an enumeration to use and pass in an enumeration value...
public enum Currency
{
AFA,
ALL,
...
}
Convertor.ConversionRate(Currency.EUR, Currency.GBP);
Instead of use string "EUR" use Convertor.Currency.EUR.
I'm pretty new to C# and WPF so I went through the same phase as you did.
Let me try to give a step by step method to make it work.
As some of the other posts said already, first you will need to add the web reference. You can do this by going to your Solution Explorer, right click on "Service References", and click "Add Service Reference". In the new window, click "Advanced" at the bottom, and in the next window click "Add Web Reference" at the bottom. Then type URL:
"http://www.webservicex.net/CurrencyConvertor.asmx?WSDL"
Normally by now it should be looking for available services related to this URL, and find one: "CurrencyConverter". Give it a reference name such as "net.webservicex.www" and click "Add Reference". Now you can use it in your code.
Let's go to the code now. If you would like to display, for example, the Euro / US Dollar exchange rate, all you need is this code:
net.webservicex.www.CurrencyConvertor conver = new net.webservicex.www.CurrencyConvertor();
MessageBox.Show((conver.ConversionRate(net.webservicex.www.Currency.EUR, net.webservicex.www.Currency.USD)).ToString());
conver.dispose();
Hope this helps!
I wrote this a while back, I call the current currencies and store them in the class as the json object. This makes calculations across multiple currencies faster as you are doing on the platform.
getCurrencies -> returns string[] "EUR","USD" etc
calculate -> ("USD","EUR",1.0) converts 1 dollar into euros
class CurrencyConvertor
{
public string[] currencyList;
RestClient client = new RestClient ("http://finance.yahoo.com/webservice/v1/symbols/allcurrencies/quote?format=json");
RestRequest request = new RestRequest ("",Method.GET);
JObject json;
public CurrencyConvertor()
{
var response = client.Execute(request);
json = JObject.Parse (response.Content);
}
public string[] getCurrencies()
{
ArrayList currencies = new ArrayList ();
foreach (var item in json["list"]["resources"]) {
string tempN = item ["resource"] ["fields"] ["name"].ToString ().Replace ("USD/", "");
if(tempN.Length < 4)
currencies.Add (tempN);
}
currencies.Sort ();
currencyList = (string[])currencies.ToArray(typeof(string));
return currencyList;
}
public string calculate(string Base, string Target, decimal amount)
{
decimal temp1 = 1;
decimal temp2 = 1;
Console.WriteLine (Base + "to"+Target);
foreach (var item in json["list"]["resources"]) {
if (item["resource"]["fields"]["name"].ToString().Contains("/"+Base)) {
temp1 = decimal.Parse(amount.ToString()) * decimal.Parse(item ["resource"] ["fields"] ["price"].ToString(), CultureInfo.InvariantCulture.NumberFormat);
}
if (item ["resource"] ["fields"] ["name"].ToString().Contains("/"+Target)) {
temp2=decimal.Parse(amount.ToString()) * decimal.Parse(item ["resource"] ["fields"] ["price"].ToString(), CultureInfo.InvariantCulture.NumberFormat);
}
}
var dec = ((decimal)temp2 / (decimal)temp1);
return (Math.Round(dec*amount,5) ).ToString().Replace(",",".");
}
}

sending a SOAP request with c#

I'm trying to send a SOAP request to a 3rd party web service. I've successfully send and received data from other interfaces in the same service, but I'm having problems with this particular one:
<SP_GoodsMovement xmlns="http://services.hnseu.com">
<GoodsMoved xmlns="http://tempuri.org/SP_GoodsMoved.xsd">
<SerialNumberedGoodsMovements>
<SerialNumbered>
<PartNumber>string</PartNumber>
<SerialNumber>string</SerialNumber>
<MovementType>string</MovementType>
<FromLocation>string</FromLocation>
<FromLocationCategory>string</FromLocationCategory>
<ToLocation>string</ToLocation>
<ToLocationCategory>string</ToLocationCategory>
<AssetMovementTimestamp>dateTime</AssetMovementTimestamp>
<GoodsInReference>string</GoodsInReference>
</SerialNumbered>
<SerialNumbered>
<PartNumber>string</PartNumber>
<SerialNumber>string</SerialNumber>
<MovementType>string</MovementType>
<FromLocation>string</FromLocation>
<FromLocationCategory>string</FromLocationCategory>
<ToLocation>string</ToLocation>
<ToLocationCategory>string</ToLocationCategory>
<AssetMovementTimestamp>dateTime</AssetMovementTimestamp>
<GoodsInReference>string</GoodsInReference>
</SerialNumbered>
</SerialNumberedGoodsMovements>
<NonSerialNumberedGoodsMovements>
<NonSerialNumbered>
<PartNumber>string</PartNumber>
<Quantity>unsignedInt</Quantity>
<MovementType>string</MovementType>
<FromLocation>string</FromLocation>
<FromLocationCategory>string</FromLocationCategory>
<ToLocation>string</ToLocation>
<ToLocationCategory>string</ToLocationCategory>
<Used>boolean</Used>
<AssetMovementTimestamp>dateTime</AssetMovementTimestamp>
<GoodsInReference>string</GoodsInReference>
</NonSerialNumbered>
<NonSerialNumbered>
<PartNumber>string</PartNumber>
<Quantity>unsignedInt</Quantity>
<MovementType>string</MovementType>
<FromLocation>string</FromLocation>
<FromLocationCategory>string</FromLocationCategory>
<ToLocation>string</ToLocation>
<ToLocationCategory>string</ToLocationCategory>
<Used>boolean</Used>
<AssetMovementTimestamp>dateTime</AssetMovementTimestamp>
<GoodsInReference>string</GoodsInReference>
</NonSerialNumbered>
</NonSerialNumberedGoodsMovements>
</GoodsMoved>
</SP_GoodsMovement>
so my code is as follows (i can expand this if necesssary):
...
if (requestType == "SP_GoodsMovement")
{
GoodsMoved SOAP_GoodsMoved = new GoodsMoved();
SOAP_GoodsMoved.SerialNumberedGoodsMovements[0].PartNumber = partNumber[0].InnerXml;
...
string SOAPMessage;
SOAPMessage = request.SP_GoodsMovement(header, SOAP_GoodsMoved).Message;
}
When I run this code I get an 'Object reference not set to an instance of an object' error.
I think i'm not referencing the PartNumber parameter properly, but i've tried a few things without success.
Any ideas?
SOAP_GoodsMoved.SerialNumberedGoodsMovements[0]
doesn't appear to be initialised.
maybe try
GoodsMoved SOAP_GoodsMoved = new GoodsMoved();
SOAP_GoodsMoved.SerialNumberedGoodsMovements = new WhateverObject[1];
SOAP_GoodsMoved.SerialNumberedGoodsMovements[0] = new WhateverObject();
SOAP_GoodsMoved.SerialNumberedGoodsMovements[0].PartNumber = partNumber[0].InnerXml;
or you could right an overload for your GoodsMoved() ctor that ensures that the SerialNumberedGoodsMovements array gets initialized with a certain size.

Categories

Resources