To use webservice I added a web service reference and then added the following code to my MainPage.xaml.cs file.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
namespace WebServiceTest
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
}
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
try
{
ServiceReference.PDAServiceSoapClient ws =
new ServiceReference.PDAServiceSoapClient();
ws.GetResoureAroudCompleted +=
new EventHandler<ServiceReference.GetResoureAroudCompletedEventArgs>(ws_GetResoureAroudCompleted);
ws.GetResoureAroudAsync("基站,机楼", 113, 23, 10000);
}
catch
{
System.Windows.MessageBox.Show("error!");
}
}
void ws_GetResoureAroudCompleted(object sender, ServiceReference.GetResoureAroudCompletedEventArgs e)
{
if (e.Error != null)
{
var result = e.Result;
}
}
}
}
Then I ran PhoneApplication and got this exception:
System.InvalidOperationException was unhandled
Message=There was an error reflecting type 'WebServiceTest.ServiceReference.GetResoureAroudResponseGetResoureAroudResult'.
InnerException: System.InvalidOperationException
Message=There was an error reflecting property 'Any1'.
in Reference.cs
Code:
public WebServiceTest.ServiceReference.GetResoureAroudResponseGetResoureAroudResult EndGetResoureAroud(System.IAsyncResult result) {
object[] _args = new object[0];
**WebServiceTest.ServiceReference.GetResoureAroudResponseGetResoureAroudResult _result = ((WebServiceTest.ServiceReference.GetResoureAroudResponseGetResoureAroudResult)(base.EndInvoke("GetResoureAroud", _args, result)));**
return _result;
}
It's not caught by try-catch, anybody know why?
I have faced the same problem and after investigating I did the following which solved the issue:
usually you will find two properties in the class causing the error:
private System.Xml.Linq.XElement[] anyField;
private System.Xml.Linq.XElement any1Field;
What I did was the following:
1- change the first property from an array to a single value variable as follows
private System.Xml.Linq.XElement anyField;
2- change the getter and setter methods of this property , to match your changes
[System.Xml.Serialization.XmlAnyElementAttribute(Namespace="http://www.w3.org/2001/XMLSchema", Order=0)]
public System.Xml.Linq.XElement Any {
get {
return this.anyField;
}
set {
this.anyField = value;
this.RaisePropertyChanged("Any");
}
}
3- remove or comment out the second property
// private System.Xml.Linq.XElement any1Field;
4- remove or comment out the second property's getter and setter methods
/*
[System.Xml.Serialization.XmlAnyElementAttribute(Namespace="urn:schemas-microsoft-com:xml-diffgram-v1", Order=1)]
public System.Xml.Linq.XElement Any1 {
get {
return this.any1Field;
}
set {
this.any1Field = value;
this.RaisePropertyChanged("Any1");
}
}
*/
At this point you can now access the resulting XML as follows by calling the "Any" property which will return an xml which you can manipulate :
ex, in my case it was the following class causing the problems
public partial class GetUserBalancesClassAccounts
in my method I was able to access the xml as follows
GetUserBalancesClassAccounts accts = balances.Accounts;
XElement doc = accts.Any;
foreach( XElement docElement in doc.Elements()){
foreach (XElement account in docElement.Elements("Account"))
{
... do something ...
}
}
The exception is not caught by your exception handler because it occurs in the framework and is out of scope. Depending on whether the webservice conforms to best practice, it may surface an Error object and if so you should inspect this prior to attempting to retrieve any data.
This can produce symptoms similar to yours, but I'm not certain this is the problem you face.
Related
I am trying to write a visualizer that maps expressions in an expression tree to Roslyn syntax nodes, in order to generate code for the expression tree. Part of the syntax tree generation is a call to the AdhocWorkspace constructor.
When I run the visualizer using the VisualizerDevelopmentHost, everything works just fine:
using Microsoft.VisualStudio.DebuggerVisualizers;
using System;
using System.Linq.Expressions;
namespace _testVisualizer {
class Program {
[STAThread]
static void Main(string[] args) {
Expression<Func<bool>> expr = () => true;
var data = new TestVisualizerData(expr);
var visualizerHost = new VisualizerDevelopmentHost(data, typeof(TestVisualizer));
visualizerHost.ShowVisualizer();
Console.ReadKey(true);
}
}
}
But when I try to use the visualizer through the Visual Studio UI (by hovering over expr, clicking on the magnifying glass icon and choosing my visualizer), I get the following message:
Unable to perform function evaluation on the process being debugged.
Additional information
The function evaluation requires all threads to run.
I've identified the following as triggering the error:
workspace = new AdhocWorkspace();
which assigns to the workspace field on my Mapper class (source).
Why does calling the AdhocWorkspace constructor trigger this warning? How can I work around this?
This is an MCVE that demonstrates the issue:
using Microsoft.CodeAnalysis;
using Microsoft.VisualStudio.DebuggerVisualizers;
using System;
using System.Diagnostics;
using System.IO;
using System.Windows;
using System.Windows.Controls;
[assembly: DebuggerVisualizer(typeof(_testVisualizer.TestVisualizer), typeof(_testVisualizer.TestVisualizerDataObjectSource), Target = typeof(System.Linq.Expressions.Expression), Description = "Test Visualizer")]
namespace _testVisualizer {
public class TestVisualizer : DialogDebuggerVisualizer {
protected override void Show(IDialogVisualizerService windowService, IVisualizerObjectProvider objectProvider) {
var data = (TestVisualizerData)objectProvider.GetObject();
var txt = new TextBlock();
txt.SetBinding(TextBlock.TextProperty, "Status");
var window = new Window {
DataContext = data,
Content = txt
};
window.ShowDialog();
}
}
[Serializable]
public class TestVisualizerData {
public TestVisualizerData() { }
public TestVisualizerData(System.Linq.Expressions.Expression expr) {
var workspace = new AdhocWorkspace();
Status = "Success";
}
public string Status { get; set; }
}
public class TestVisualizerDataObjectSource : VisualizerObjectSource {
public override void GetData(object target, Stream outgoingData) {
var expr = (System.Linq.Expressions.Expression)target;
var data = new TestVisualizerData(expr);
base.GetData(data, outgoingData);
}
}
}
Perhaps the AdhocWorkspace alternate constructor could be leveraged to use the SyntaxNode API in a single thread.
I've filed an issue.
I have the following code:
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using OpenFridge.Portable.Data.Interfaces.Entities;
using OpenFridge.Portable.Data.Parse.Entities;
using Parse;
using AutoMapper;
namespace OpenFridge.Portable.Data.Parse.Entities
{
[ParseClassName("_User")]
public class ParseUserEntity : ParseUserEntityBase, IUserEntity
{
private string _password;
[ParseFieldName("password")]
public new string Password
{
get { return _password; }
set
{
_password = value;
base.Password = value;
}
}
Lazy<IEnumerable<IBankAccountEntity>> _bankAccounts;
[ParseFieldName("bankAccounts")]
public Lazy<IEnumerable<IBankAccountEntity>> BankAccounts
{
get
{
var relation = GetRelation<ParseBankAccountEntity>("BankAccount");
if (relation == null) return null;
var result = relation.Query.FindAsync().Result;
var _bankAccounts = new Lazy<IEnumerable<IBankAccountEntity>>(() => relation.Query.FindAsync().Result);
return _bankAccounts;
}
set
{
_bankAccounts = value;
}
}
}
}
And it all seems to work quite fine, however.. once I use the .BankAccounts property I get the following exception:
Must specify a ParseObject class name when creating a ParseQuery.\r\nParameter name: className
Which I find strange since there is no way for me to define a classname with in that line of code:
(That line of code beeing:)
relation.Query.FindAsync().Result
So.. is this a bug?.. Am I doing something wrong or using it wrong?
Any ideas?
Br,
Inx
I have a problem where my relation keeps returning zero relational objects (in this case bank accounts).
Could someone take a quick look at my code and see if I'm doing something wrong?
The reason to the business logic in the property is due to a de-coupling of the database and the business logic.
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using OpenFridge.Portable.Data.Interfaces.Entities;
using OpenFridge.Portable.Data.Parse.Entities;
using Parse;
using AutoMapper;
namespace OpenFridge.Portable.Data.Parse.Entities
{
[ParseClassName("_User")]
public class ParseUserEntity : ParseUserEntityBase, IUserEntity
{
private string _password;
[ParseFieldName("password")]
public new string Password
{
get { return _password; }
set
{
_password = value;
base.Password = value;
}
}
Lazy<IEnumerable<IBankAccountEntity>> _bankAccounts;
[ParseFieldName("bankAccounts")]
public Lazy<IEnumerable<IBankAccountEntity>> BankAccounts
{
get
{
var relation = GetRelation<ParseBankAccountEntity>("bankAccounts");
if (relation == null)
return null;
var _bankAccounts = new Lazy<IEnumerable<IBankAccountEntity>>(() => relation.Query.FindAsync().Result);
return _bankAccounts;
}
set
{
_bankAccounts = value;
}
}
}
}
I suspect that this keeps getting returned as empty due to the fact that
this.ObjectId hasn't been set yet before the BankAccounts code executes..
Any ideas of how to get this working?
im having a Problem creating a Class at runtime. Everytime i debug the code below i get the following error message at var cls = results.CompiledAssembly.GetType("test.DummyHelloWorldHandler");
Could not load file or assembly 'file:///C:\Users\MyName\AppData\Local\Temp\1ivc3qic.dll' or one of its dependencies. Das System kann die angegebene Datei nicht finden.
the Name of the *.dll file differs everytime i debug the programm
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
using System.Reflection;
namespace DynamicNS
{
class Program
{
static void Main(string[] args)
{
CSharpCodeProvider provider = new CSharpCodeProvider();
CompilerParameters parameters = new CompilerParameters();
parameters.GenerateInMemory = true;
parameters.ReferencedAssemblies.Add("System.Collections.dll");
CompilerResults results = provider.CompileAssemblyFromSource(parameters, GetCode());
var cls = results.CompiledAssembly.GetType("test.DummyHelloWorldHandler");
var method = cls.GetMethod("Received", BindingFlags.Static | BindingFlags.Public);
object[] parms = { "Hallo Welt" };
method.Invoke(null, parms);
Console.ReadLine();
}
static string[] GetCode()
{
return new string[]
{
#"using System.Collections;
namespace test
{
public class DummyHelloWorldHandler
{
protected internal Queue _queue;
public void Received(string message)
{
lock (_queue)
{
_queue.Enqueue(message);
}
Console.WriteLine('Enqueued');
}
public DummyHelloWorldHandler()
{
_queue = new Queue();
}
}
}"
};
}
}
}
The code returned by GetCode does not compile because of the wrong quotes.
You can check that by iterating over the Errors property of your CompilerResults.
You have to remove this line:
parameters.ReferencedAssemblies.Add("System.Collections.dll");
and change the GetCode() method like this:
private static string[] GetCode()
{
return new string[]
{
#"using System;
using System.Collections;
namespace test
{
public class DummyHelloWorldHandler
{
protected internal Queue _queue;
public void Received(string message)
{
lock (_queue)
{
_queue.Enqueue(message);
}
Console.WriteLine(""Enqueued"");
}
public DummyHelloWorldHandler()
{
_queue = new Queue();
}
}
}"
};
}
#"using System.Collection
Should probably be
#"using System.Collections;
Also: Console.WirteLine()? Hmmm. Perhaps you should paste that entire GetCode() string into a test program, make it compile, and then paste it back into your original project.
After your edits, this still won't compile:
Console.WriteLine('Enqueued');
It's got single quotes instead of double quotes around the string.
Are you sure your code could actually be compiled? You seem to be missing a semicolon after your using statement.
Check the Errors property of your results, it contains the errors that were encountered while compiling your source.
I'm trying to create a simple service using the code provided but i don't understand why have an exception when binding.
10-19 11:42:09.148 I/mono-stdout( 1622): MvxBind:Error: 10.40 Exception thrown during the view binding
MvxBindingLayoutInflatorFactory Line 133!
I need some help please :)
My Source:
DataStore Interface:
using Core.Models;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
namespace Core.Interfaces
{
public interface IDataStore
{
void UpdateFeed(FeedModel feedModel);
void DeleteFeed(FeedModel feedModel);
void CreateFeed(FeedModel feedModel);
FeedModel GetFeed(Uri uri);
ObservableCollection<FeedModel> Feeds { get; }
}
}
DataStore Class:
using System;
using System.Collections.Generic;
using System.Linq;
using Core.Interfaces;
using System.Collections.ObjectModel;
using Cirrious.MvvmCross.Interfaces.ServiceProvider;
using Cirrious.MvvmCross.Interfaces.Platform;
using Cirrious.MvvmCross.Interfaces.Localization;
using Cirrious.MvvmCross.ExtensionMethods;
using Core.Helpers;
using System.Xml.Serialization;
using System.Xml.Linq;
using System.IO;
namespace Core.Models
{
public class DataStore
: IDataStore
, IMvxServiceConsumer<IMvxSimpleFileStoreService>
, IMvxServiceConsumer<IMvxResourceLoader>
{
public DataStore()
{
Load();
}
public void UpdateFeed(FeedModel feedModel)
{
var toUpdate = this.m_feeds.First(feed => feed.Url == feedModel.Url);
toUpdate.CloneFrom(feedModel);
Save();
}
public void DeleteFeed(FeedModel feedModel)
{
this.m_feeds.Remove(this.m_feeds.First(feed => feed.Url == feedModel.Url));
Save();
}
public void CreateFeed(FeedModel feedModel)
{
this.m_feeds.Add(feedModel);
Save();
}
public FeedModel GetFeed(Uri uri)
{
return this.m_feeds.First(feed => feed.Url == uri);
}
private void Load()
{
var fileService = this.GetService<IMvxSimpleFileStoreService>();
if (!fileService.TryReadBinaryFile(LocationDataService.StoreFileName, LoadFrom))
{
var resourceLoader = this.GetService<IMvxResourceLoader>();
resourceLoader.GetResourceStream(LocationDataService.ResourceFileName, (inputStream) => LoadFrom(inputStream));
}
}
private bool LoadFrom(Stream inputStream)
{
try
{
var loadedData = XDocument.Load(inputStream);
if (loadedData.Root == null)
return false;
using (var reader = loadedData.Root.CreateReader())
{
var list = (List<FeedModel>)new XmlSerializer(typeof(List<FeedModel>)).Deserialize(reader);
this.m_feeds = new ObservableCollection<FeedModel>(list);
return true;
}
}
catch
{
return false;
}
}
private void Save()
{
var fileService = this.GetService<IMvxSimpleFileStoreService>();
fileService.WriteFile(LocationDataService.StoreFileName, (stream) =>
{
var serializer = new XmlSerializer(typeof(List<FeedModel>));
serializer.Serialize(stream, m_feeds.ToList());
});
}
private ObservableCollection<FeedModel> m_feeds;
public ObservableCollection<FeedModel> Feeds
{
get { return this.m_feeds; }
}
}
}
BaseViewModel:
using Cirrious.MvvmCross.Commands;
using Cirrious.MvvmCross.ExtensionMethods;
using Cirrious.MvvmCross.Interfaces.Commands;
using Cirrious.MvvmCross.Interfaces.ServiceProvider;
using Cirrious.MvvmCross.ViewModels;
using Core.Interfaces;
namespace Core.ViewModels
{
public class BaseViewModel
: MvxViewModel
, IMvxServiceConsumer<IDataStore>
{
protected IDataStore DataStore
{
get { return this.GetService<IDataStore>(); }
}
}
}
FeedManagerViewModel:
using Cirrious.MvvmCross.Commands;
using Cirrious.MvvmCross.Interfaces.Commands;
using Core.Controls;
using Core.Models;
using System;
using System.Collections.ObjectModel;
namespace Core.ViewModels
{
public class FeedsManagerViewModel
: BaseViewModel
{
public ObservableCollection<FeedModel> Feeds { get { return this.DataStore.Feeds; } }
...
}
}
View xml:
<Mvx.MvxBindableListView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
local:MvxBind="{'ItemsSource':{'Path':'Feeds'}, 'ItemClick':{'Path':'DisplayItemCommand'}}"
local:MvxItemTemplate="#layout/feedlist_viewmodel" />
This is most likely an error in your XML... but it's hard to tell from just that one line of trace.
What version of MvvmCross are you running?
The tip version of both Master and vNext show line 133 as
MvxBindingTrace.Trace(MvxTraceLevel.Error, "Exception during creation of {0} from type {1} - exception {2}", name, viewType.FullName, exception.ToLongString());
So hopefully if you use the tip, then that should give you a lot more information about what is going wrong.
Beyond that, you can always try setting a breakpoint on the offending line to extract more information.
If the exception is on line 99 then change the error logging there from:
MvxBindingTrace.Trace(MvxTraceLevel.Error, "Exception thrown during the view binding ", exception.ToLongString());
to:
MvxBindingTrace.Trace(MvxTraceLevel.Error, "Exception thrown during the view binding {0}", exception.ToLongString());
The error will be in there somewhere :)
Another good debugging technique is to comment out lines one-by-one until the problem goes away - this helps identify where the problem is.
You've got a working development environment and a really powerful debugger - using it is a good skill to learn. 'Code Complete' is one of my favourite books ever :)