I'm totally new in xamarin.
I use Visual Studio 2017 Community and I write a very simple code: I want to connect to a basic WCF service.
The link to the service:
http://services.adserviceitalia.it/Service1.svc
(method GetHello, input string and return string... very basic method)
I read a lot of samples... I add a reference to the services, generate the proxy class... ok!!
public partial class MainPage : ContentPage
{
private wcfs.Service1Client ws;
public MainPage()
{
InitializeComponent();
var endpoint = new EndpointAddress("http://services.adserviceitalia.it/Service1.svc");
var binding = new BasicHttpBinding
{
Name = "basicHttpBinding",
MaxBufferSize = 2147483647,
MaxReceivedMessageSize = 2147483647
};
TimeSpan timeout = new TimeSpan(0, 0, 30);
binding.SendTimeout = timeout;
binding.OpenTimeout = timeout;
binding.ReceiveTimeout = timeout;
ws = new wcfs.Service1Client(binding,endpoint);
ws.GetHelloCompleted += Handle_HelloWorldCompleted;
}
private void Button_Clicked(object sender, EventArgs e)
{
ws.GetHelloAsync("Mark");
}
private void Handle_HelloWorldCompleted(object sender, wcfs.GetHelloCompletedEventArgs args)
{
label1.Text = args.Result;
}
}
}
It works in UWP debug...
Connection with WCF... Hello World working in UWP
I got an unhandled exception in Android...
In Android Manifest all permission are cheched. The Android emulator is connected to internet...
Every help would be extremely appreciated!! Thanks in advance... and excuse me form my english.
Ops...
First: thanks to all!!
In my log i read this:
04-27 14:11:30.106 E/mono-rt ( 5308): [ERROR] FATAL UNHANDLED EXCEPTION: Android.Util.AndroidRuntimeException: Only the original thread that created a view hierarchy can touch its views.
Seems that problem is that I try to update the interface directly in Handle_HelloWorldCompleted with WCF respose:
label1.Text = args.Result;
... in I modify the code in this way:
//label1.Text = args.Result;
System.Diagnostics.Debug.WriteLine(args.Result);
I can see that arg.Result is populated by the WCF response "Hola Mark" (ergo: the connection with the service works!!) .
Notice i've this behavior in Android debug only.
How I can update that label1 ??
Related
I just started working on xamarin not long ago.
Now I met a problem on Xamarin consuming AX2012 Webservice.
I’m in a project that need an android device connect with AX2012 R3 Inbound port.
I made a very simple webservice like below and tested successfully by using C# project.
AX Webservice code
[SysEntryPointAttribute(true)]
public ItemNameAlias GetItemName(ItemId itemId)
{
return InventTable::find(itemId).NameAlias;
}
C# invoke code(successful)
static void Main(string[] args)
{
TestWebservice.TestWebserviceClient client = new TestWebservice.TestWebserviceClient();
TestWebservice.CallContext cpny = new TestWebservice.CallContext() { Company = "USMF" };
client.ClientCredentials.Windows.ClientCredential.UserName = #"sagcn\wangy";
client.ClientCredentials.Windows.ClientCredential.Password = "aoc-111";
string itemName = client.GetItemName(cpny, "C0004");
Console.WriteLine($"Item Name: {itemName}");
Console.ReadKey(false);
}
When I add this service reference to an Xamarin.form project, it was been used very like in C# project.
But when the code invoked the webservice function, it throws a System.NotImplementedException exception.
System.NotImplementedException
Message=The method or operation is not implemented.
Xamarin code (throw NotImplementedException exception)
private void Button_Clicked(object sender, EventArgs e)
{
string itemName = "";
Debug.WriteLine("Start");
ASMXService.TestWebserviceClient client = new ASMXService.TestWebserviceClient();
ASMXService.CallContext cpny = new ASMXService.CallContext() { Company = "USMF" };
client.ClientCredentials.Windows.ClientCredential.UserName = #"sagcn\wangy";
client.ClientCredentials.Windows.ClientCredential.Password = "aoc-111";
// throw exception here
itemName = client.GetItemName(cpny, "C0004");
Debug.WriteLine($"Item Name: {itemName}");
Debug.WriteLine("End");
}
I searched many places but still don’t know the reasons why.
Does anyone have the same experience or can give me some advice?
Thanks a million.
AX Webservice code
C# project add web reference
C# project code success
Xamarin add WCF Webservice
Xamarin add WCF Webservice2
Xamarin invoke webservice
Error exception
i programming an Application for my study.
I try to use gRPC in Xamarin.Forms.
The gRPC is in a seperate Libyry (.NET Standart 2.1).
If i use the code in WPF-Core Project every thing works fine.
But if I try to use the same in my Xamarin.Forms-Project the Connection don't work.
if I use the connectionString "http://my.server.com:5050" I get these Exception
Error starting gRPC call: unexpected end of stream on Connection{my.server.com:5050, proxy=DIRECT hostAddress=5.189.149.82 cipherSuite=none protocol=http/1.1} (recycle count=0)
if I the SSL Version"https://my.server.com:5050" I get these Exception
Error starting gRPC call: Connection closed by peer
Here is the Code of the gRPC-Libary
...
if (connectionString.Contains("http://"))
AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
channel = GrpcChannel.ForAddress(connectionString);
client = new Haushaltsbuch.HaushaltsbuchClient(channel);
SuccsessReply reply = new SuccsessReply { Result = false };
try
{
reply = client.Login(new UserRequest
{
User = new GRPC_User
{
Username = username,
PassHash = passHash
}
});
}
catch (RpcException e) when (e.Status.Detail.Contains("The SSL connection could not be established"))
{
client = null;
throw new CommunicationException("Fehler mit SSL-Zertifikat des Servers", e);
}
catch (RpcException e)
{
client = null;
throw new CommunicationException("Server nicht erreichbar", e);
}
...
I am only a student and if I google, then it says that Xamarin Forms is supporting gRPC.
But why is it not working?
the .Android Project has the GRPC.Core package from NuGet istalled.
Solved it by Replacing
channel = GrpcChannel.ForAddress(connectionString);
with
if (connectionString.Contains("http://"))
{
AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
string newConString = connectionString.Replace("http://", "");
return new Channel(newConString, ChannelCredentials.Insecure);
}
else
{
string newConString = connectionString.Replace("https://", "");
return new Channel(newConString, new SslCredentials());
}
It seems like the GrpcChannel Class isn't working on Andriod.
Update: May, 2021
Xamarin does not fully support gRPC, so be aware of this when developing your software on Xamarin.Forms.
Starting w/ gRPC version 2.34.X, gRPC has started partial support for Xamarin.Forms w/ Android and iOS devices.
Please see this for more information.
I am trying to transfer a file to my iphone using 32feet bluetooth, but cannot seem to get past the ObexWebResponse.
I have read many post on this but none of the solutions seem to work for me.
The Error i get is
// Connect failed
// The requested address is not valid in its context "address:Guid"
private BluetoothClient _bluetoothClient;
private BluetoothComponent _bluetoothComponent;
private List<BluetoothDeviceInfo> _inRangeBluetoothDevices;
private BluetoothDeviceInfo _hlkBoardDevice;
private EventHandler<BluetoothWin32AuthenticationEventArgs> _bluetoothAuthenticatorHandler;
private BluetoothWin32Authentication _bluetoothAuthenticator;
public BTooth() {
_bluetoothClient = new BluetoothClient();
_bluetoothComponent = new BluetoothComponent(_bluetoothClient);
_inRangeBluetoothDevices = new List<BluetoothDeviceInfo>();
_bluetoothAuthenticatorHandler = new EventHandler<BluetoothWin32AuthenticationEventArgs>(_bluetoothAutenticator_handlePairingRequest);
_bluetoothAuthenticator = new BluetoothWin32Authentication(_bluetoothAuthenticatorHandler);
_bluetoothComponent.DiscoverDevicesProgress += _bluetoothComponent_DiscoverDevicesProgress;
_bluetoothComponent.DiscoverDevicesComplete += _bluetoothComponent_DiscoverDevicesComplete;
ConnectAsync();
}
public void ConnectAsync() {
_inRangeBluetoothDevices.Clear();
_hlkBoardDevice = null;
_bluetoothComponent.DiscoverDevicesAsync(255, true, true, true, false, null);
}
private void PairWithBoard() {
Console.WriteLine("Pairing...");
bool pairResult = BluetoothSecurity.PairRequest(_hlkBoardDevice.DeviceAddress, null);
if (pairResult) {
Console.WriteLine("Success");
Console.WriteLine($"Authenticated equals {_hlkBoardDevice.Authenticated}");
} else {
Console.WriteLine("Fail"); // Instantly fails
}
}
private void _bluetoothComponent_DiscoverDevicesProgress(object sender, DiscoverDevicesEventArgs e) { _inRangeBluetoothDevices.AddRange(e.Devices); }
private void _bluetoothComponent_DiscoverDevicesComplete(object sender, DiscoverDevicesEventArgs e) {
for (int i = 0; i < _inRangeBluetoothDevices.Count; ++i) {
if (_inRangeBluetoothDevices[i].DeviceName == "Uranus") {
_hlkBoardDevice = _inRangeBluetoothDevices[i];
PairWithBoard();
TransferFile();
return;
}
}
// no devices found
}
private void _bluetoothAutenticator_handlePairingRequest(object sender, BluetoothWin32AuthenticationEventArgs e) {
e.Confirm = true; // Never reach this line
}
// not working
// transfers a file to the phone
public void TransferFile() {
string file = "E:\\test.txt",
filename = System.IO.Path.GetFileName(file);
string deviceAddr = _hlkBoardDevice.DeviceAddress.ToString();
BluetoothAddress addr = BluetoothAddress.Parse(deviceAddr);
_bluetoothClient.Connect(BluetoothAddress.Parse(deviceAddr), BluetoothService.SerialPort);
Uri u = new Uri($"obex://{deviceAddr}/{file}");
ObexWebRequest owr = new ObexWebRequest(u);
owr.ReadFile(file);
// error:
// Connect failed
// The requested address is not valid in its context ...
var response = (ObexWebResponse)owr.GetResponse();
Console.WriteLine("Response Code: {0} (0x{0:X})", response.StatusCode);
response.Close();
}
The pairing and authentication works just fine, and I can get the BluetoothService.Handsfree to make a call for me but the transferring of the file fails. Not knowing what the actual error is, I tried almost every service available with no luck.
Can you help me figure out what is going on? This is my first attempt working with Bluetooth services so I still have a ton to learn.
Is it possible to transfer a file from iPhone to Windows desktop via Bluetooth?
However, in case you need to transfer media files (images, videos, etc) from Android device, you can use ObexListener class provided by 32Feet library for this purpose, and then you can simply call _obexListener.GetContext() method that will block and wait for incoming connections.
Once a new connection is received, you can save the received file to local storage, as shown in the below example:
ObexListener _listener = new ObexListener();
_listener.Start();
// This method will block and wait for incoming connections
ObexListenerContext _context = _listener.GetContext();
// Once new connection is received, you can save the file to local storage
_context.Request.WriteFile(#"c:\sample.jpg");
NOTE: When working with OBEX on Windows, make sure to disable the "Bluetooth OBEX Service" Windows service, in order not to let it handle the incoming OBEX requests instead of the desired application.
I walked away from this for a while. and started Trying to use xamiren but then had to create a virtual Mac so that I could have the apple store to just load software on my phone. From there xamerin 'should' work well but its another field and tons more to firgure out.
Here I am put my code which is "An exception occurred during a WebClient request" i put breakpoint and check .it will so this error .for developing i am using visual studio 2012 ultimate with windows phone sdk8.0 and if request is done successful than my response is in json string .that will show in messagebox .now it show me "System.Net.Webexception:An exception occurred during a WebClient request."
public match()
{
InitializeComponent();
Loaded += new RoutedEventHandler(profile1_loaded);
}
void profile1_loaded(object sender, RoutedEventArgs e)
{
WebClient wc2 = new WebClient();
var URI = new Uri("http://192.168.1.17/eyematch/rest1-7-2/api/match");
wc2.Headers["Content-Type"] = "application/x-www-form-urlencoded";
wc2.UploadStringCompleted +=
new UploadStringCompletedEventHandler(wc2_UploadStringCompleted);
wc2.UploadStringAsync(
URI, "GET", "action=getMatchNotificationData&sKey=" +
GlobalVariables.skey + "&uKey=" + GlobalVariables.ukey);
}
private void wc2_UploadStringCompleted(object sender, UploadStringCompletedEventArgs er)
{
try
{
MessageBox.Show(er.Result);
}
catch (Exception eu)
{
MessageBox.Show(eu.ToString());
}
}
thank you in advance....
Are you testing this in the emulator or on a physical device? Chances are the address is inaccessible given your network configuration (especially since it is a local network IP).
A helpful hint to other people running into this error message: the exception has a .InnerException, so if you change the code above to also output "eu.InnerException", you can get more info.
I never used fiddler core before. But after first time using it into my application, a weird problem is happening. Whenever my application is running web browsers are working fine. But other time those all showing error page. I know I did something wrong with fiddler core. I am sending my codes here. Codes are working perfectly. But there is something into my code so that I getting this problem. Please see the code and let me know what am I doing wrong.
static bool bUpdateTitle = true;
static Proxy oSecureEndpoint;
static string sSecureEndpointHostname = "localhost";
static int iSecureEndpointPort = 1106;
private void button1_Click(object senderr, EventArgs e)
{
List<Fiddler.Session> oAllSessions = new List<Fiddler.Session>();
Fiddler.FiddlerApplication.OnNotification += delegate(object sender, NotificationEventArgs oNEA) { MessageBox.Show("** NotifyUser: " + oNEA.NotifyString); };
Fiddler.FiddlerApplication.BeforeRequest += delegate(Fiddler.Session oS)
{
oS.bBufferResponse = false;
Monitor.Enter(oAllSessions);
oAllSessions.Add(oS);
Monitor.Exit(oAllSessions);
if (oS.hostname=="localhost")
{
oS.utilCreateResponseAndBypassServer();
oS.oResponse.headers.HTTPResponseStatus = "200 Ok";
oS.oResponse["Content-Type"] = "text/html; charset=UTF-8";
oS.oResponse["Cache-Control"] = "private, max-age=0";
oS.utilSetResponseBody("<html><body><font size=10>Restricted</font></body></html>");
}
};
Fiddler.CONFIG.IgnoreServerCertErrors = false;
FiddlerApplication.Prefs.SetBoolPref("fiddler.network.streaming.abortifclientaborts", true);
FiddlerCoreStartupFlags oFCSF = FiddlerCoreStartupFlags.Default;
Fiddler.FiddlerApplication.Startup(0, oFCSF);
oSecureEndpoint = FiddlerApplication.CreateProxyEndpoint(iSecureEndpointPort, true, sSecureEndpointHostname);
}
public static void DoQuit()
{
if (null != oSecureEndpoint) oSecureEndpoint.Dispose();
Fiddler.FiddlerApplication.Shutdown();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
DoQuit();
}
As mentioned in the response to your same message left in the Fiddler discussion group, this means that you ran your program at least once without properly calling Shutdown() (e.g. because it crashed). Clear the incorrect proxy settings from Tools > Internet Options > Connections > LAN Settings when your program isn't running.