Calling webservice and WCF in windows phone? - c#

I seen one method of web service that is to call from a MCWebServiceSoapClient.
//getting the different points for the map when checkbox is checked
private void polyc_Checked(object sender, RoutedEventArgs e)
{
testingwcf.MCWebServiceSoapClient ob = new TestMap.testingwcf.MCWebServiceSoapClient();
ob.getPolytechnicPointsAsync();
ob.getPolytechnicPointsCompleted += new EventHandler<testingwcf.getPolytechnicPointsCompletedEventArgs>(ob_getPolyPointsCompleted);
}
However what I am implementing to call is WCF. How to do convert this method to a WCF ? My WCF is here http://kailun92wcf.cloudapp.net/Service1.svc. Is it possible to call from a WCF into windows phone ersi map ? To plot the points ?

You want to consume a WCF service from a WP app?
Firstly, generate your client proxy via visual studio, right click on "references", select "Add service reference", select the "Go" button, this wizard should discover your service if it is online.
Select the advanced button, and select the options below
in your code behind, hook up to a click event,
private void LoadWebService(object sender, RoutedEventArgs e)
{
var service = new Service1Client();
service.getRecommendPlaceAsync(new getRecommendPlaceRequest { activityId = 1}); //Provide your id here
service.getRecommendPlaceCompleted += new EventHandler<MyCloundService.getRecommendPlaceCompletedEventArgs>(RecommendedPlaceRequestComplete);
}
void RecommendedPlaceRequestComplete(object sender, MyCloundService.getRecommendPlaceCompletedEventArgs e)
{
if (e.Error == null)
{
var result = String.Join(",", (from place in e.Result.getRecommendPlaceResult select place.Name).ToArray());
MessageBox.Show(result);
}
else
{
MessageBox.Show("An error occured: " + e.Error.Message);
}
}
See a tutorial here

Seems like what you are trying to do is call a function on the phone from the WCF service you cant use event handlers over the wire like that especially not on a phone.
Because the phones run on battery you may want to use something like push notifications as detailed below:
Sending push notifications for Windows Phone
Setting up your app to receive push notifications for Windows Phone

Related

C# - Force windows around 20s delay to realize bluetooth not connected

I'm currently using the 32feet library for bluetooth in my application. I'm trying to check whether the device is still alive before it takes windows the 20s to change the status from "Connected" --> "Paired".
"True" --> "False"
I'm forcing a device refresh with:
holders.storedDevice.Refresh();
but it seems that the refresh isn't actually forcing windows to do anything. For reference storedDevice is of type
BluetoothDeviceInfo name {get; set;}
Timer code:
private void refreshDevice(object Sender, EventArgs e)
{
holders.StoredDevice.Refresh();
if(!holders.StoredDevice.Connected)
{
deviceRefreshTimer.Enabled = false;
updateTextBox( connectButton ,"Disconnecting...");
ExecuteSecure(() => connectButton.Enabled = false);
updateTextBox(statusTextBox, "Lost connection");
readBackgroundWorker.CancelAsync();
holders.localClient.Close();
storedStream = null;
}
}

c# with dotras - Status Box not updating automatically after dial connect/disconnect

Greeting,
OS: Windows 7 /64bit
Application: Visual Studio 2012 / C# and DotRas 1.3 Library
I am very new to c# or VS thing so please bear with me. After doing many hours R&D, I have finaly made a pppoe dialer program in C# / Dotras. This program have 3 main buttons
Create /Add PPPoE Internet Dialer Connection in network connections , working fine
Dial button, which connects the newly created dialer , working Fine
Disconnect working fine
I have added StatuBox where dialup events should appear as showed on dotras youtube video tutorial (which was for vpn, but my project is for pppoe dialer)
StatusBox Not updating the dialup events like connecting/password error/connected etc. This is the part where I am finally confused.
Following is my Code.
// Dial Button Action
private void button2_Click_1(object sender, EventArgs e)
{
using (RasDialer dialer = new RasDialer())
{
// I had to add below line to update statusTextBox Manualy , want to get rid of it by adding auto status update
this.StatusTextBox.AppendText(string.Format("{0}\r\n\r\n", "Connection in progress ...", "{0}\r\n\r\n"));
dialer.EntryName = ("pppoe2");
string username = textBox1.Text;
string passwd = textBox2.Text;
// If username is empty dont connect
if (string.IsNullOrWhiteSpace(textBox1.Text))
{
this.StatusTextBox.AppendText(string.Format("{0}\r\n", "Cancelled. Cannot continue with username/password.", "{0}\r\n"));
MessageBox.Show("Enter username.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
dialer.Credentials = new System.Net.NetworkCredential(textBox1.Text, textBox2.Text);
dialer.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.User);
dialer.Timeout = 1000;
dialer.AllowUseStoredCredentials = true;
// start dialing,
dialer.Dial();
// If dialer connects successfully update StatuTextbox
this.StatusTextBox.AppendText(string.Format("{0}\r\n\r\n", "Connected."));
}
}
private void rasDialer1_StateChanged(object sender, StateChangedEventArgs e)
{
this.StatusTextBox.AppendText(string.Format("{0}\r\n", "Status Changed"));
}
private void rasDialer1_Error(object sender, System.IO.ErrorEventArgs e)
{
this.StatusTextBox.AppendText(string.Format("{0}\r\n", "STATUS UPDATE TEXT XYZ"));
}
private void rasDialer1_DialCompleted(object sender, DialCompletedEventArgs e)
{
this.StatusTextBox.AppendText(string.Format("{0}\r\n", "STATUS UPDATE TEXT XYZ"));
}
Any help would be highly appreciable.
Ok I have managed to enable status box text append work fine.
this.Invoke((MethodInvoker)delegate
{
this.StatusTextBox.AppendText(string.Format(e.State.ToString() + "\r\n"));
});
}
Depending on how you were using it, if the background thread from the OS isn’t marshaled back to the UI thread it won’t update. Similarly to what you had done, the SynchronizingObject property on the RasDialer can be set to your form and the thread synchronization will occur automatically.

Enumerating IPP Printers

I'm looking into DNS based service discovery in Windows 10 and found this video from Build. The only change I made to discovery was changing the service name to "_ipp._tcp". However I don't get any hits even though I know I have > 15 IPP enabled printers on the network (I can successfully identify these using the ipptool, IOS and Android code).
I've checked and double checked for typos. I've included all networking capabilities in the appxmanifest file.
Here's my code, pretty straight forward:
public sealed partial class MainPage : Page
{
static Guid DnsSdProtocol = new Guid("{4526e8c1-8aac-4153-9b16-55e86ada0e54}");
string queryString = "System.Devices.AepService.ProtocolId:={" + DnsSdProtocol + "} AND " +
"System.Devices.Dnssd.Domain:=\"local\" AND System.Devices.Dnssd.ServiceName:=\"_ipp._tcp\"";
DeviceWatcher watcher;
public MainPage()
{
this.InitializeComponent();
}
private void button_Click(object sender, RoutedEventArgs e)
{
watcher = DeviceInformation.CreateWatcher(queryString,
new String[]
{
"System.Devices.Dnssd.HostName",
"System.Devices.Dnssd.ServiceName",
"System.Devices.Dnssd.TextAttributes",
"System.Devices.IpAddress" },
DeviceInformationKind.AssociationEndpointService
);
watcher.Added += Watcher_Added;
watcher.Start();
}
private void Watcher_Added(DeviceWatcher sender, DeviceInformation args)
{
System.Diagnostics.Debug.WriteLine("found device");
}
}
Does anybody else have experience with this and can help figure out why no devices are found? Is my query correct? Do I need to do anything else when setting up the DeviceWatcher?
update
I've verified the requests are being created since they are showing up in Wireshark. They look to be identical to other mdns requests being created. I've also verified I can create SSDP requests that return discovered devices so I doubt it's an issue with networking permissions via app capabilities.
Try using the watcher.Updated handler. Even if it is empty, the presence of an Updated handler can cause the Added handler to be triggered.

Using HitTest to remote control WPF

I am developing a mobile app to remotely control a WPF UI.
The UI is managed by a third party and that third party can add\remove buttons any time.
I am streaming the UI to the client Windows store app and it is sending the touch coordinates to server.
Server then use HitTest to get the element on WPF UI and run the action.
It works most of the time, but the filter callback is not getting called some times.
This is a dummy code.
private void Button_Click_1(object sender, RoutedEventArgs e)
{
Point p = new Point(77, 45);
// Coordinates received on server comes here
VisualTreeHelper.HitTest(this,
new HitTestFilterCallback(FilterCallback),
new HitTestResultCallback(ResultCallback),
new PointHitTestParameters(p));
}
private HitTestFilterBehavior FilterCallback( DependencyObject target)
{
System.Diagnostics.Debug.WriteLine(target.GetType());
if (typeof(Button) == target.GetType())
{
Button b = (Button)target;
Button_Click(b, null);
return HitTestFilterBehavior.Stop;
}
else
{
return HitTestFilterBehavior.Continue;
}
}
private HitTestResultBehavior ResultCallback(HitTestResult result)
{
System.Diagnostics.Debug.WriteLine(result.VisualHit.GetType());
return HitTestResultBehavior.Stop;
}
You have to return Continue from your HitTestResultCallback. Otherwise hit testing won't traverse the complete visual tree, and may stop before it has reached the Button control.
private HitTestResultBehavior ResultCallback(HitTestResult result)
{
return HitTestResultBehavior.Continue;
}
See the Hit Testing in the Visual Layer article on MSDN for details.

problem with RX and web service collection loading wp7

I'm beginner with C# and wp7 platform and I have some problem with good idea to get request from web service.
I made webservice in PHP (nusoap - WSDL) and everything is working fine in "normal" using.
Now I have ObservableCollection saved in IsolatedStorage with I load when Page is open (List of watched stacks exchange). Then I want to refresh data for every item from web service.
I don't know whether this is a good idea.
Code:
private GPWWebservicePortTypeClient client = new GPWWebservicePortTypeClient();
private ObservableCollection<WebServiceClass.ItemGetValues> StoredStock =
new ObservableCollection<WebServiceClass.ItemGetValues>();
public const string _fileName = "listaObserwowanych.xml";
public Page()
{
InitializeComponent();
DataContext = App.ViewModel;
this.Loaded += new RoutedEventHandler(Page_Loaded);
client.GetLastValueCompleted +=
new EventHandler<GetLastValueCompletedEventArgs>(client_GetLastValueCompleted);
foreach (var itemGetValuese in App.ViewModel.Items)
{
client.GetLastValueAsync(itemGetValuese.name);
}
var o =
Observable.FromEvent<GetLastValueCompletedEventArgs(client,"GetLastValueCompleted")
.Subscribe(setList);
}
void client_GetLastValueCompleted(object sender, GetLastValueCompletedEventArgs e)
{
if (e.Error != null)
{
MessageBox.Show(Convert.ToString(e.Error));
}
else
{
ObservableCollection<WebServiceClass.ItemGetValues> ListValues =
(ObservableCollection<WebServiceClass.ItemGetValues>)
JsonConvert.DeserializeObject(e.Result,
typeof(ObservableCollection<WebServiceClass.ItemGetValues>));
StoredStock.Add(ListValues[0]);
}
}
private void setList(IEvent<GetLastValueCompletedEventArgs> ex)
{
List.ItemsSource = StoredStock;
}
void Page_Loaded(object sender, RoutedEventArgs e)
{
App.ViewModel.LoadData();
List.ItemsSource = App.ViewModel.Items;
}
Like u see I use RX to call method client_GetLastValueCompleted add store result to auxiliary variable (StoredStock). Then refresh List in setList method, but that method is client_GetLastValueCompleted what is not soo good idea, becouse I need to run that method only when all of runned GetLastValueAsync in foreach is completed.
Second problem: becouse of async web service method StoredStock sometime have different order than App.ViewModel.Items .
Any good idea how to do that in right way?
Best regards,
Lukas
You're really mixing up a number of ways to call web services and Rx. You really need to decide on a single way and stick to it.
If you're going to use Rx, then you'll have something like this:
public Page()
{
InitializeComponent();
DataContext = App.ViewModel;
this.Loaded += new RoutedEventHandler(Page_Loaded);
}
void Page_Loaded(object sender, RoutedEventArgs e)
{
App.ViewModel.LoadData();
var storedStock =
new ObservableCollection<WebServiceClass.ItemGetValues>();
List.ItemsSource = storedStock;
var values =
Observable.Using<WebServiceClass.ItemGetValues, GPWWebservicePortTypeClient>
(() => new GPWWebservicePortTypeClient(), ws =>
{
var clientGetLastValue = Observable
.FromAsyncPattern<string, GetLastValueResponse>
(ws.BeginGetLastValue, ws.EndGetLastValue);
Func<string, WebServiceClass.ItemGetValues> deserializeFirst = r =>
((List<WebServiceClass.ItemGetValues>)JsonConvert
.DeserializeObject(r,
typeof(List<WebServiceClass.ItemGetValues>)))
.First();
return
from item in App.ViewModel.Items
from e in clientGetLastValue(item)
select deserializeFirst(e.Result);
});
values.Subscribe(storedStock.Add);
}
You'll have to get the right method call names for your web service client, but the code should roughly be right. Let me know how you go.
I corrected the code above. Should have returned the query inside the Using call rather than assign it to values.
I corrected the call to FromAsyncPattern to use the correct method names and return type from the actual web service reference class sent via email.
It should look like this:
Observable.FromAsyncPattern<string, GetLastValueResponse>
(ws.BeginGetLastValue, ws.EndGetLastValue);
If you're a beginner with C#, try to avoid RX for the time being. It is a cool technology, but if you use it without clear understanding of what is going on, it will bring more problems than solve.
Use a simple event, and when each async item arrives, locate and update the correspondent one in the stored list.

Categories

Resources