It is my first program on wifi direct so I made a simple program that just discover all nearby devices and then try to connect to one of them the discovery works fine and gets all the devices the problem is in the connection that always fails after using this function WiFiDirectDevice.FromIdAsync() it keeps paring for too long and then it fails always.
I was following the code on this microsoft tutorial: https://channel9.msdn.com/Events/Build/2015/3-98
Here is my code:
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
namespace App7
{
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
DeviceInformationCollection DevicesFound;
WiFiDirectAdvertisementPublisher pub;
WiFiDirectConnectionListener listener;
CancellationTokenSource m_CancellationTokenSource;
private async void button_Click(object sender, RoutedEventArgs e)
{
String DeviceSelector = WiFiDirectDevice.GetDeviceSelector(WiFiDirectDeviceSelectorType.AssociationEndpoint);
DevicesFound = await DeviceInformation.FindAllAsync(DeviceSelector);
if(DevicesFound.Count>0)
{
connectedDeviceslist.ItemsSource = DevicesFound;
var dialog = new MessageDialog(DevicesFound[0].Name);
await dialog.ShowAsync();
}
}
private async void button1_Click(object sender, RoutedEventArgs e)
{
int selectedIndex = connectedDeviceslist.SelectedIndex;
String deviceID = DevicesFound[selectedIndex].Id;
var selecetedDevice = DevicesFound[selectedIndex];
try
{
WiFiDirectConnectionParameters connectionParams = new WiFiDirectConnectionParameters();
connectionParams.GroupOwnerIntent = Convert.ToInt16("1");
connectionParams.PreferredPairingProcedure = WiFiDirectPairingProcedure.GroupOwnerNegotiation;
m_CancellationTokenSource = new CancellationTokenSource();
var wfdDevice = await WiFiDirectDevice.FromIdAsync(selecetedDevice.Id, connectionParams).AsTask(m_CancellationTokenSource.Token);
var EndpointPairs = wfdDevice.GetConnectionEndpointPairs();
}
catch(Exception ex)
{
await Dispatcher.RunAsync(CoreDispatcherPriority.High, async() =>
{
var dialog = new MessageDialog(ex.Message);
await dialog.ShowAsync();
});
}
}
private void button2_Click(object sender, RoutedEventArgs e)
{
pub = new WiFiDirectAdvertisementPublisher();
pub.Advertisement.ListenStateDiscoverability = WiFiDirectAdvertisementListenStateDiscoverability.Normal;
listener = new WiFiDirectConnectionListener();
listener.ConnectionRequested += OnConnectionRequested;
pub.Start();
}
private async void OnConnectionRequested(WiFiDirectConnectionListener sender, WiFiDirectConnectionRequestedEventArgs args)
{
try
{
var ConnectionRequest = args.GetConnectionRequest();
var tcs = new TaskCompletionSource<bool>();
var dialogTask = tcs.Task;
var messageDialog = new MessageDialog("Connection request received from " + ConnectionRequest.DeviceInformation.Name, "Connection Request");
// Add commands and set their callbacks; both buttons use the same callback function instead of inline event handlers
messageDialog.Commands.Add(new UICommand("Accept", null, 0));
messageDialog.Commands.Add(new UICommand("Decline", null, 1));
// Set the command that will be invoked by default
messageDialog.DefaultCommandIndex = 1;
// Set the command to be invoked when escape is pressed
messageDialog.CancelCommandIndex = 1;
await Dispatcher.RunAsync(CoreDispatcherPriority.High, async () =>
{
// Show the message dialog
var commandChosen = await messageDialog.ShowAsync();
tcs.SetResult((commandChosen.Label == "Accept") ? true : false);
});
var fProceed = await dialogTask;
if (fProceed == true)
{
var tcsWiFiDirectDevice = new TaskCompletionSource<WiFiDirectDevice>();
var wfdDeviceTask = tcsWiFiDirectDevice.Task;
// WriteToOutput("Connecting to " + ConnectionRequest.DeviceInformation.Name + "...");
WiFiDirectConnectionParameters ConnectionParams = new WiFiDirectConnectionParameters();
await Dispatcher.RunAsync(CoreDispatcherPriority.High, async () =>
{
try
{
ConnectionParams.GroupOwnerIntent = 14;
tcsWiFiDirectDevice.SetResult(await WiFiDirectDevice.FromIdAsync(ConnectionRequest.DeviceInformation.Id, ConnectionParams));
}
catch (Exception ex)
{
// WriteToOutput("FromIdAsync task threw an exception: " + ex.ToString());
}
});
WiFiDirectDevice wfdDevice = await wfdDeviceTask;
var EndpointPairs = wfdDevice.GetConnectionEndpointPairs();
/* m_ConnectedDevices.Add("dummy", wfdDevice);
WriteToOutput("Devices connected on L2, listening on IP Address: " + EndpointPairs[0].LocalHostName.ToString() + " Port: " + Globals.strServerPort);
StreamSocketListener listenerSocket = new StreamSocketListener();
listenerSocket.ConnectionReceived += OnSocketConnectionReceived;
await listenerSocket.BindEndpointAsync(EndpointPairs[0].LocalHostName, Globals.strServerPort);*/
}
else
{
/* // Decline the connection request
WriteToOutput("Connection request from " + ConnectionRequest.DeviceInformation.Name + " was declined");
ConnectionRequest.Dispose();*/
}
}
catch (Exception ex)
{
//WriteToOutput("FromIdAsync threw an exception: " + ex.ToString());
}
}
}
}
Related
I have this file that hangs, i have some idea that it is caused by the async task, but not sure how to fix it and debugging doesnt really work since it works correctly on visual studio but fails on IIS proper..
I tried to use ConfigureAwait(false); which i read somewhere should resolve the issue but to no avail,
I also tried other methods to set my response.redirect in my other pages and complete the request, but also to no avail..
Response.Redirect("Project.aspx", false);
Context.ApplicationInstance.CompleteRequest();
Here is my code.. appreciate if someone can point me to the right direction?
protected async void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
try
{
LoggingController.log("Before Init Project");
await InitProject().ConfigureAwait(false); ;
LoggingController.log("After Init Project");
}
catch (Exception ex)
{
LoggingController.log(ex);
}
}
else
{
if (Request.Params["__EVENTTARGET"].Equals("RedirectBoard"))
{
await Task.Run(() => gotoProject(Request.Params["__EVENTARGUMENT"])).ConfigureAwait(false); ;
}
}
}
protected async Task InitProject()
{
try
{
// Login - temporary for fast testing
if (Session["user"] == null)
{
Response.Redirect("Login.aspx", false);
Context.ApplicationInstance.CompleteRequest();
}
else
{
user = (Model.UserModel)Session["user"];
}
// Init variables
int userID = user.User_ID;
int role = user.Role;
lists = new StringBuilder("const userID=" + userID + ";");
// Start tasks
// var timer = System.Diagnostics.Stopwatch.StartNew();
// Task[] task = new Task[2];
Task task0 = Task.Run(() => loadProject(userID, role));
Task task1 = Task.Run(() => loadUser(userID));
// Profile area
var profile = (Image)Master.FindControl("profile");
profile.ToolTip = user.Name;
profile.ImageUrl = user.Avatar;
new LanbanAuthentication().Authenticate(Response, user);
// Wait all tasks to be completed
await Task.WhenAll(task0, task1).ConfigureAwait(false);
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "projectScript", lists.ToString(), true);
}
catch (Exception ex)
{
LoggingController.log(ex.Message + " # " + ex.Source + Environment.NewLine + ex.StackTrace);
}
}
//1. Load all projects
protected async Task loadProject(int userID, int role)
{
try
{
// Fetch all projects belong to or under supervised of this user
ProjectAccess myAccess = new ProjectAccess();
myAccess.fetchProject(userID, role);
var project = myAccess.MyDataSet.Tables["Project"];
Task task1 = Task.Run(() =>
{
for (int i = 0; i < project.Rows.Count; i++)
{
var row = project.Rows[i];
if (row != null)
projectbrowser.Controls.Add(ProjectBox(row));
}
});
// Send project list in JSON to client for further processing
Task task2 = Task.Run(() =>
{
StringBuilder projectList = new StringBuilder("var projectList = ");
if (project != null)
{
projectList.Append(JsonConvert.SerializeObject(project));
projectList.Append(";");
lists.Append(projectList);
}
});
await Task.WhenAll(task1, task2).ConfigureAwait(false); ;
myAccess.Dipose();
}
catch (Exception ex)
{
LoggingController.log(ex.Message + " # " + ex.Source + Environment.NewLine + ex.StackTrace);
}
LoggingController.log("loadProject completed");
}
private void loadUser(int userID)
{
// Fetch data from database
ProjectAccess myAccess = new ProjectAccess();
myAccess.fetchSharedProjectUser(userID);
var user = myAccess.MyDataSet.Tables["User"];
// Send user list in JSON to client for further processing
StringBuilder userList = new StringBuilder("var userList = ");
userList.Append(JsonConvert.SerializeObject(user));
userList.Append(";");
lists.Append(userList);
myAccess.Dipose();
LoggingController.log("loadUser completed");
}
One of my Async Handler
/// Async handler for request from client
public class ProjectHandler : IHttpAsyncHandler, IReadOnlySessionState
{
public bool IsReusable { get { return false; } }
public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback callback, Object state)
{
ProjectHandlerOperation operation = new ProjectHandlerOperation(callback, context, state);
operation.QueueWork();
return operation;
}
public void EndProcessRequest(IAsyncResult result)
{
}
public void ProcessRequest(HttpContext context)
{
throw new InvalidOperationException();
}
}
I am trying to download minecraft files libraries and assets using listbox to select version then download by click on the button but when I click on the button I get this error
"System.FormatException: 'Input string was not in a correct format.'"
on await MCDownload(files, ctoken.Token);
please reply what should I do.
Thanks!
private async void LaunchMinecraft1_Click(object sender, RoutedEventArgs e)
{
if (Directory.Exists(jsonloc + #"\versions\" + versionsList.SelectedItem.ToString()))
{
MessageBox.Show("Version already exists");
return;
}
ctoken = new CancellationTokenSource();
var files = await GetFiles(versionsList.SelectedItem.ToString(), totalPercentage.Content);
await MCDownload(files, ctoken.Token);
}
public List<string[]> urls = new List<string[]>();
public async Task MCDownload(List<string[]>urls, CancellationToken _ctsblock)
{
totalMB = 0;
_cts = new CancellationTokenSource();
sw.Start();
int count = urls.Count;
if (urls != null && urls.Count != 0)
{
System.Timers.Timer myTimer = new System.Timers.Timer();
myTimer.Elapsed += (s, e) =>
{
Application.Current.Dispatcher.Invoke(new Action(() =>
{
progressBar.Visibility = Visibility.Visible;
downloadedMB.Content = string.Format("{0} MB", ((totalMB / 1024f) / 1024f).ToString("0.00"));
}));
};
myTimer.Interval = 100; // 1000 ms is one second
myTimer.Start();
ServicePointManager.DefaultConnectionLimit = Int32.Parse(Settings.Default["download_threads"].ToString());
var block = new ActionBlock<string[]>(async url =>
{
try
{
await DownloadLibraries(url);
}
catch (WebException) { }
catch (OperationCanceledException) { }
catch (Exception e)
{
Application.Current.Dispatcher.Invoke(new Action(() =>
{
MessageBox.Show("There may have been some errors while downloading the game. It shouldn't be a problem though. If you experience any issue, try to reinstall again or contact us!");
}));
Console.WriteLine("ERRORE IN" + url[3] + "\r\n" + e);
}
}, new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = Int32.Parse(Properties.Settings.Default["download_threads"].ToString()), CancellationToken = _ctsblock });
foreach (var url in urls)
{
block.Post(url);
}
block.Complete();
try
{
await block.Completion;
}
catch (TaskCanceledException)
{
return;
}
myTimer.Stop();
Application.Current.Dispatcher.Invoke(new Action(() =>
{
downloadedMB.Content = null;
}));
progressBar.Value = 100;
progressBar.Visibility = Visibility.Hidden;
return;
}
}
I have a function called getMessages that can be called by a Button click (using the RelayCommand trigger) or that is called in a timer every 15s.
The desired behavior is:
webservice > deserialize answer > system notification > updatelistview > insert localDB
But when the function is called by the timer the updatelistview is not done. Why does this happen if the function is the same and works perfectly in the button command?
CODE:
// Get messages for the logged in user
public async void getMessages()
{
try
{
List<FriendGetMessage> msg = new List<FriendGetMessage>();
var response = await CommunicationWebServices.GetCHAT("users/" + au.idUser + "/get", au.token);
if (response.StatusCode == HttpStatusCode.OK) // If there are messages for me.
{
var aux = await response.Content.ReadAsStringAsync();
IEnumerable<FriendGetMessage> result = JsonConvert.DeserializeObject<IEnumerable<FriendGetMessage>>(aux);
if (result != null)
{
foreach (var m in result)
{
msg.Add(m);
}
//MsgList=msg;
foreach (var f in Friends)
{
if (f.msg == null || f.msg.Count() == 0)
{
f.msg = new ObservableCollection<Messages>();
}
foreach (var mess in msg)
{
if (mess.idUser == f.idUser)
{
Messages mm = new Messages();
mm.received = mess.message;
mm.timestamp = "Received " + mess.serverTimestamp;
mm.align = "Right";
// Add to the friend list.
f.msg.Add(mm);
// Add to Local DB
InsertMessage(null, au.idUser.ToString(), f.idUser, mess.message, mess.serverTimestamp);
var notification = new System.Windows.Forms.NotifyIcon()
{
Visible = true,
Icon = System.Drawing.SystemIcons.Information,
BalloonTipIcon = System.Windows.Forms.ToolTipIcon.Info,
BalloonTipTitle = "New Message from " + f.name,
BalloonTipText = "Message: " + mess.message,
};
// Display for 5 seconds.
notification.ShowBalloonTip(5);
// The notification should be disposed when you don't need it anymore,
// but doing so will immediately close the balloon if it's visible.
notification.Dispose();
}
}
}
counterChat = 1; // resets the counter
}
}
else {
counterChat = counterChat * 2;
}
//var sql = "select * from chat";
//var respo = GetFromDatabase(sql);
OnPropertyChanged("Friends");
}
catch (Exception e)
{
MessageBox.Show("GetMessages: " + e);
Debug.WriteLine("{0} Exception caught.", e);
}
}
CODE TIMER:
public void chatUpdate()
{
_timerChat = new DispatcherTimer(DispatcherPriority.Render);
_timerChat.Interval = TimeSpan.FromSeconds(15);
_timerChat.Tick += new EventHandler(timerchat_Tick);
_timerChat.Start();
}
public void timerchat_Tick(object sender, EventArgs e)
{
if (counterChat != incChat)
{
incChat++;
}
else
{
getMessages();
OnPropertyChanged("Friends");
incChat = 0;
}
}
ADDED - I've also tried this and didn't worked (it seems that is some kind of concurrency problem to the ObservableCollection called Friends (is a friendslist) each friend has an ObservableCollection of messages (is a chat))
public void chatUpdate()
{
_timerChat = new DispatcherTimer(DispatcherPriority.Render);
_timerChat.Interval = TimeSpan.FromSeconds(15);
_timerChat.Tick += new EventHandler(timerchat_Tick);
_timerChat.Start();
}
public async void timerchat_Tick(object sender, EventArgs e)
{
if (counterChat != incChat)
{
incChat++;
}
else
{
Application.Current.Dispatcher.Invoke((Action)async delegate { await getMessages(); });
incChat = 0;
}
}
Best regards,
I think you need to make the timer handler be an async method as follows:
public async void timerchat_Tick(object sender, EventArgs e)
{
if (counterChat != incChat)
{
incChat++;
}
else
{
await getMessages();
OnPropertyChanged("Friends");
incChat = 0;
}
}
This way OnPropertyChanged("Friends") is guaranteed to fire after the work in getMessages is done.
The methods need to change to:
DispatcherTimer _timerChat = new DispatcherTimer(DispatcherPriority.Render);
_timerChat.Interval = TimeSpan.FromSeconds(15);
_timerChat.Tick += new EventHandler(timerchat_Tick);
_timerChat.Start();
public async void timerchat_Tick(object sender, EventArgs e)
{
//...
await getMessages();
//...
}
public async Task getMessages()
{
try
{
// ... your code here
string result = await response.Content.ReadAsStringAsync();
// .... rest of your code
}
catch (Exception e)
{
MessageBox.Show("GetMessages: " + e);
}
}
It is solved. The problem was in my ViewModels I was opening multiple threads and sometimes the right one would update the UI and sometimes no.
Thanks for all the answers.
I having a little issue reading data from Nave32 Flight Controller, I'm able to send data to the card using the SerialDevice class but when the LoadAsync Method is call and there is no more data to read the app hung and does not move forward, there is not exception during the execution of the process. I look at the app state and there is a bunch a task block and I'm not sure why. See image below
UPDATE
Firmware source code is here
here is my example code
namespace Apps.Receiver
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
this.dataRecived.Text = DateTime.Now.ToString();
}
private async Task readAsync(SerialDevice serialPort)
{
string data = string.Empty;
using (var dataReaderObject = new DataReader(serialPort.InputStream))
{
try
{
dataReaderObject.InputStreamOptions = InputStreamOptions.None;
var hasData = true;
while (hasData)
{
var bytesRead = await dataReaderObject.LoadAsync(serialPort.DataBits);
if (bytesRead > 0)
data += dataReaderObject.ReadString(bytesRead);
else
hasData = false;
}
}
catch (Exception ex)
{
status.Text = "reading data fail: " + ex.Message;
closeDevice(serialPort);
}
}
dataRecived.Text = data;
}
private async void sendData_Click(object sender, RoutedEventArgs e)
{
var serialPort = await getSerialDevice("COM3");
if (dataToSend.Text.Length != 0)
{
using (var dataWriteObject = new DataWriter(serialPort.OutputStream))
{
try
{
if (dataToSend.Text.Equals("#", StringComparison.CurrentCultureIgnoreCase))
dataWriteObject.WriteString(dataToSend.Text);
else
dataWriteObject.WriteString(dataToSend.Text + "\n");
var bytesWritten = await dataWriteObject.StoreAsync();
if (bytesWritten > 0)
{
status.Text = dataToSend.Text + ", ";
status.Text += "bytes written successfully!";
}
await readAsync(serialPort);
}
catch (Exception ex)
{
status.Text = "writing data fail: " + ex.Message;
}
}
closeDevice(serialPort);
}
else
{
status.Text = "Enter the text you want to write and then click on 'WRITE'";
}
}
private void closeDevice(SerialDevice device)
{
device.Dispose();
device = null;
}
private async Task<SerialDevice> getSerialDevice(string portName)
{
var aqs = SerialDevice.GetDeviceSelector("COM3");
var devices = await DeviceInformation.FindAllAsync(aqs);
if (devices.Count == 0)
throw new Exception("Unablet to connect to device");
var serialPort = await SerialDevice.FromIdAsync(devices[0].Id);
if (serialPort == null)
throw new Exception("Unablet to Open to port " + portName);
serialPort.BaudRate = 115200;
serialPort.DataBits = 8;
return serialPort;
}
}
}
See this example, try if it helps doing it like this:
await reader.LoadAsync(8192);
while (reader.UnconsumedBufferLength > 0)
{
strBuilder.Append(reader.ReadString(reader.UnconsumedBufferLength));
await reader.LoadAsync(8192);
}
I am looking for a way to communicate either over TCP or HTTP between android and C# 2012. Here is what I have so far
JAVA CLIENT:
package com.example.test;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView tc;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button)this.findViewById(R.id.button1);
tc = (TextView) this.findViewById(R.id.textView1);
btn.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Thread th = new Thread(new Runnable() {
public void run() {
connect();
}
});
th.start();
}
});
}
private void connect() {
InetAddress[] server;
try {
server = InetAddress.getAllByName("192.168.1.100");
Socket socket = new Socket(server[0], 3975);
if (socket.isConnected()){
Log.d("connected", "connected");
}
PrintWriter w = null;
BufferedReader r = null;
w = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true);
r = new BufferedReader(new InputStreamReader(socket.getInputStream()));
w.println("test");
/*String m = null;
while ((m=r.readLine())!= null) {
w.write(m,0,m.length());
w.flush();
}*/
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("error", e.getMessage());
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
C# SERVER:
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached. The Parameter
/// property is typically used to configure the page.</param>
protected override void OnNavigatedTo(NavigationEventArgs e)
{
}
public async void ServiceButtonClick(object sender, RoutedEventArgs e)
{
StreamSocketListener listener = new StreamSocketListener();
listener.ConnectionReceived += OnConnection;
try
{
await listener.BindServiceNameAsync("3975");
lblMessage.Text = "We are listening for connections...";
}
catch (Exception ee)
{
lblMessage.Text = "Unable to bind service.. " + ee.Message;
}
}
private async void OnConnection(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
{
DataReader reader = new DataReader(args.Socket.InputStream);
this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
lblMessage.Text = "We are connected to the client";
});
try
{
while (true)
{
uint sizeFieldCount = await reader.LoadAsync(sizeof(uint));
if (sizeFieldCount != sizeof(uint))
{
this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
lblMessage.Text = "the underlying socket was closed before we were able to read the whole data - 1";
});
return;
}
uint stringLength = reader.ReadUInt32();
uint actualStringLength = await reader.LoadAsync(stringlength);
if (stringLength != actualStringLength)
{
this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
lblMessage.Text = "the underlying socket was closed before we were able to read the whole data - 2";
});
return;
}
string temp;
temp = reader.ReadString(actualStringLength);
this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
lblMessage.Text = "Client said - " + reader.ReadString(3);
});
}
}
catch (Exception e)
{
this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
lblMessage.Text = "ERROR: " + e.Message + " - " + e.Source + " - " + e.StackTrace;
});
}
}
}
Now when I click the button on the client, the socket is connected, but when I send data to the C# server from my phone, nothing shows up on the server. Is there anything I am doing wrong on the receiving or sending end? I am just trying to send basic strings over TCP.