StreamSocket crash on Windows 8.1 store app - c#

I have a server-client connection which works on both sides with Windows.Networking.Sockets.StreamSocket. On Windows 10, as Universal App, the connection is successful and data flows in back and forth without problems. On Windows 8.1, as a Windows Store app, the reading part of the StreamSocket fails at first attempt to read incoming data. The app closes and VS 2015 do not report any Exception nor the Output Window contains any useful information, other than Program has exited with code 1. Also, putting a breakpoint and then stepping through code doesn't work. Locals are not displayed and VS shows a message dialog:
Unable to start debugging. The object invoked has disconnected from its clients.
Here is the reading code:
public IAsyncAction Read()
{
return Task.Run(() =>
{
try
{
const uint length = 65536;
string request = string.Empty;
var socket = _signalingSocketService.GetSocket();
var readBuf = new Windows.Storage.Streams.Buffer(length);
var readOp = socket.InputStream.ReadAsync(readBuf, length, InputStreamOptions.Partial);
readOp.Completed = (IAsyncOperationWithProgress<IBuffer, uint> asyncAction, AsyncStatus asyncStatus) =>
{
if(asyncStatus == AsyncStatus.Completed)
{
var localBuffer = asyncAction.GetResults();
var dataReader = DataReader.FromBuffer(localBuffer);
request = dataReader.ReadString(dataReader.UnconsumedBufferLength);
_signalingSocketService.HandoffSocket(socket);
List<string> requests;
var fileTask = BufferFileExists().AsTask();
fileTask.Wait();
if (fileTask.Result)
{
var bufferFileTask = GetBufferFile().AsTask();
bufferFileTask.Wait();
var bufferFile = bufferFileTask.Result;
var task = FileIO.AppendTextAsync(bufferFile, request).AsTask();
task.Wait();
var readLinesTask = FileIO.ReadLinesAsync(bufferFile).AsTask();
readLinesTask.Wait();
requests = (readLinesTask.Result).ToList();
var deleteTask = bufferFile.DeleteAsync().AsTask();
deleteTask.Wait();
}
else
{
requests =
request.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries).ToList();
}
} // if (asyncStatus == AsyncStatus.Completed)
}; // readOp.Completed
}
catch (Exception ex)
{
}
}
}
What can cause such an odd behavior?

Related

BLE Read operation not working in view model for Xamarin forms

I'm trying to do BLE implementation in Xamarin forms. So I am able to connect and do write operation successfully but when I do read operation the app crashes. The read operation works in code behind that is xaml.cs but it crashes in viewmodel. This is exception I'm getting
Assertion at
/Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/mono/mini/debugger-agent.c:4660,
condition is_ok (error)' not met, function:get_this_async_id, Could not execute the method because the containing type 'System.Runtime.CompilerServices.AsyncTaskMethodBuilder1[TReturn_REF]',
is not fully instantiated. assembly: type: member:(null) [libc] Fatal signal 6 (SIGABRT), code -1
(SI_QUEUE) in tid 24845 (twell.touchless), pid 24845 (twell.touchless)
This is my code in viewmodel
private async Task<string> ProcessDeviceInformationService(IService deviceInfoService)
{
try
{
await adapter.ConnectToDeviceAsync(device);
var sb = new StringBuilder("Getting information from Device Information service: \n");
var characteristics = await deviceInfoService.GetCharacteristicsAsync();
var characteristic = await deviceInfoService.GetCharacteristicAsync(Guid.Parse("00002A39-0000-1000-8000-00805F9B34FB"));
// characteristic.CanWrite = true;
//foreach (var characteristic in characteristics)
//{
try
{
if (Device.RuntimePlatform==Device.iOS)
{
characteresticnativedata = DependencyService.Get<ICharacteristiciOS>();
characteresticnativedata.OpeniosBluetooth(device);
}
if (characteristic != null)
{
var sbnew = new StringBuilder("BLE Characteristics\n");
byte[] senddata = Encoding.UTF8.GetBytes(string.IsNullOrEmpty(SendMessageLabel.Text) ? "0ab" : SendMessageLabel.Text);
if (MainThread.IsMainThread)
{
var newbytes = await characteristic.WriteAsync(senddata);
}
var charvalue = Characteristic.Value;
var bytes = await characteristic.ReadAsync();
string str = Encoding.UTF8.GetString(charvalue);
sbnew.AppendLine($"Characteristics found on this device: {string.Join(", ", str.ToString())}");
CharactericsLabel.Text = sbnew.ToString();
}
}
catch (Exception ex)
{
return ex.Message;
}
return CharactericsLabel.Text;
}
catch (Exception ex)
{
return ex.ToString();
}
}
This same code var bytes = await characteristic.ReadAsync(); works in xaml.cs but it crashes in viewmodel. I even used GetAwaiter().GetResult() instead of await. But still it crashes.
var bytes = characteristic.ReadAsync.GetAwaiter().GetResult();
I have no clue how to fix this any suggestions?

M2MQTT client disconnecting without an exception or error message

I'm trying to create an API that consumes various topics.
For this, I'm trying to multi-thread things, so that the whole thing can be scalable into multiple APIs, later on, but that's very besides the point.
I'm using ASP.net Core 4.0, if that's got anything to do with it. Entity Framework as well.
My problem is based on my connection to my Mosquitto server being broken without throwing an exception or anything of the like, after a minute or so. It doesn't matter how big the messages are, or how many are exchanged. I have no idea of how I can create a callback or anything of the kind to know what's going on with my connection. Can anyone help?
I'll link the code I use to establish a connection and subscribe to a connection below. Using the Subscribe method or doing it manually also changes nothing. I'm at a loss, here.
Thanks in advance!
Main.cs:
Task.Factory.StartNew(() => DataflowController.ResumeQueuesAsync());
BuildWebHost(args).Run();
DataflowController.cs:
public static Boolean Subscribe(String topic)
{
Console.WriteLine("Hello from " + topic);
MqttClient mqttClient = new MqttClient(brokerAddress);
byte code = mqttClient.Connect(Guid.NewGuid().ToString());
// Register to message received
mqttClient.MqttMsgPublishReceived += client_recievedMessageAsync;
string clientId = Guid.NewGuid().ToString();
mqttClient.Connect(clientId);
// Subscribe to topic
mqttClient.Subscribe(new String[] { topic }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
System.Console.ReadLine();
return true;
}
public static async Task ResumeQueuesAsync()
{
var mongoClient = new MongoClient(connectionString);
var db = mongoClient.GetDatabase(databaseName);
var topics = db.GetCollection<BsonDocument>(topicCollection);
var filter = new BsonDocument();
List<BsonDocument> result = topics.Find(filter).ToList();
var resultSize = result.Count;
Task[] subscriptions = new Task[resultSize];
MqttClient mqttClient = new MqttClient(brokerAddress);
byte code = mqttClient.Connect(Guid.NewGuid().ToString());
// Register to message received
mqttClient.MqttMsgPublishReceived += client_recievedMessageAsync;
string clientId = Guid.NewGuid().ToString();
mqttClient.Connect(clientId);
int counter = 0;
foreach(var doc in result)
{
subscriptions[counter] = new Task(() =>
{
Console.WriteLine("Hello from " + doc["topic"].ToString());
// Subscribe to topic
mqttClient.Subscribe(new String[] { doc["topic"].ToString() }, new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE });
System.Console.ReadLine();
});
counter++;
}
foreach(Task task in subscriptions)
{
task.Start();
}
}
static async void client_recievedMessageAsync(object sender, MqttMsgPublishEventArgs e)
{
// Handle message received
var message = System.Text.Encoding.Default.GetString(e.Message);
var topic = e.Topic;
var id = topic.Split("/")[2];
BsonDocument doc = new BsonDocument {
{"Plug ID", id },
{"Consumption", message }
};
await Save(doc, "smartPDM_consumption");
System.Console.WriteLine("Message received from " + topic + " : " + message);
}
This line was the issue:
byte code = mqttClient.Connect(Guid.NewGuid().ToString());
Deleted it, and it just worked.

WCF Websocket project fails upon Entity Framework data access attempt

I am new to WebSockets (this AM) and have set up a WCF WebSocket app that works when doing a trivial example I found online (http://www.codeproject.com/Articles/619343/Using-WebSocket-in-NET-Part).
I added Entity Framework and as soon as I add code to try to access data the process (just sending a message back and forth) no longer works.
Could there be some fundamental concept I could be missing?
Does anyone have any good ideas for troubleshooting?
namespace PBWebSocket
{
public class PBWebSocket : IBWebSocket
{
private SPEntities db = new SPEntities();
public async Task SendMessageToServer(Message msg)
{
var callback = OperationContext.Current.GetCallbackChannel<IPBCallback>();
if (msg.IsEmpty || ((IChannel)callback).State != CommunicationState.Opened)
{
return;
}
byte[] body = msg.GetBody<byte[]>();
string msgTextFromClient = Encoding.UTF8.GetString(body);
var reqId = Int32.Parse(msgTextFromClient);
// *** The below line breaks it ***
var req = db.Requests.Where(r => r.Id == 164).FirstOrDefault();
reqId = reqId + 2;
Message newMsg = ByteStreamMessage.CreateMessage(
new ArraySegment<byte>(Encoding.UTF8.GetBytes(reqId.ToString())));
newMsg.Properties["WebSocketMessageProperty"] =
new WebSocketMessageProperty
{ MessageType = WebSocketMessageType.Text };
await callback.SendMessageToClient(newMsg);
}
}
}

C# : Bluetooth GATT communication. GattCharacteristic.ValueChanged doesnt gets hit after sometime

I am working on wpf application that uses GATT for bluetooth communication. I am using GattCharacteristic.ValueChanged to handle any value from device. It works for sometime and the event handler doesnt gets called after 1 minute. This problem observed in windows 8.1, but working in windows 10.
I am made GattCharacteristic member variable, so the GC doesnt collect the variable. Still the problem exists.
Can anyone tell me what could be the potential problem here?
private GattCharacteristic m_DataSenderCharacteristics;
foreach (var service in serviceInfo)
{
var uuid = MjGattDeviceService.UuidFromServiceInformation(service);
//Battery Service
if (uuid.ToString() == BatteryUUID)
{
var bService = await GattDeviceService.FromIdAsync(service.Id);
m_Device.batteryService = bService;
}
if (uuid.ToString() == CustomServiceUUID)
{
m_Device.gattService = await GattDeviceService.FromIdAsync(service.Id);
Guid controlGUID = new Guid(ControlUUID);
var controlGattCharacteristics = m_Device.gattService.GetCharacteristics(controlGUID);
Byte[] bsdata = new Byte[] { 0x0b, 0x00, 0x02 };
IBuffer buffUTF8 = CryptographicBuffer.CreateFromByteArray(bsdata);
GattCommunicationStatus status = await controlGattCharacteristics[0].WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify);
if (status == GattCommunicationStatus.Unreachable)
{
m_Device.isConnected = false;
nextPage = "Unreachable";
}
else if (status == GattCommunicationStatus.Success)
{
var ctrlStatus = await controlGattCharacteristics[0].WriteValueAsync(buffUTF8);
Guid guuid1 = new Guid(DataSenderUUID);
m_DataSenderCharacteristics = m_Device.gattService.GetCharacteristics(guuid1)[0];
GattCommunicationStatus notifyStatus = await m_DataSenderCharacteristics.
WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify);
//This event handler will be called for some 1 minute. After it falls dead
m_DataSenderCharacteristics[0].ValueChanged += GestureValueChanged;
if (notifyStatus == GattCommunicationStatus.Success)
{
nextPage = "Connected";
}
}
}
}

First time creating a method that uses parallel linq and getting out of memory exception

I wrote a method to download data from the internet and save it to my database. I wrote this using PLINQ to take advantage of my multi-core processor and because it is downloading thousands of different files in a very short period of time. I have added comments below in my code to show where it stops but the program just sits there and after awhile, I get an out of memory exception. This being my first time using TPL and PLINQ, I'm extremely confused so I could really use some advice on what to do to fix this.
UPDATE: I found out that I was getting a webexception constantly because the webclient was timing out. I fixed this by increasing the max amount of connections according to this answer here. I was then getting exceptions for the connection not opening and I fixed it by using this answer here. I'm now getting connection timeout errors for the database even though it is a local sql server. I still haven't been able to get any of my code to run so I could totally use some advice
static void Main(string[] args)
{
try
{
while (true)
{
// start the download process for market info
startDownload();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
}
}
public static void startDownload()
{
DateTime currentDay = DateTime.Now;
List<Task> taskList = new List<Task>();
if (Helper.holidays.Contains(currentDay) == false)
{
List<string> markets = new List<string>() { "amex", "nasdaq", "nyse", "global" };
Parallel.ForEach(markets, market =>
{
Downloads.startInitialMarketSymbolsDownload(market);
}
);
Console.WriteLine("All downloads finished!");
}
// wait 24 hours before you do this again
Task.Delay(TimeSpan.FromHours(24)).Wait();
}
public static void startInitialMarketSymbolsDownload(string market)
{
try
{
List<string> symbolList = new List<string>();
symbolList = Helper.getStockSymbols(market);
var historicalGroups = symbolList.AsParallel().Select((x, i) => new { x, i })
.GroupBy(x => x.i / 100)
.Select(g => g.Select(x => x.x).ToArray());
historicalGroups.AsParallel().ForAll(g => getHistoricalStockData(g, market));
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
}
}
public static void getHistoricalStockData(string[] symbols, string market)
{
// download data for list of symbols and then upload to db tables
Uri uri;
string url, line;
decimal open = 0, high = 0, low = 0, close = 0, adjClose = 0;
DateTime date;
Int64 volume = 0;
string[] lineArray;
List<string> symbolError = new List<string>();
Dictionary<string, string> badNameError = new Dictionary<string, string>();
Parallel.ForEach(symbols, symbol =>
{
url = "http://ichart.finance.yahoo.com/table.csv?s=" + symbol + "&a=00&b=1&c=1900&d=" + (DateTime.Now.Month - 1) + "&e=" + DateTime.Now.Day + "&f=" + DateTime.Now.Year + "&g=d&ignore=.csv";
uri = new Uri(url);
using (dbEntities entity = new dbEntities())
using (WebClient client = new WebClient())
using (Stream stream = client.OpenRead(uri))
using (StreamReader reader = new StreamReader(stream))
{
while (reader.EndOfStream == false)
{
line = reader.ReadLine();
lineArray = line.Split(',');
// if it isn't the very first line
if (lineArray[0] != "Date")
{
// set the data for each array here
date = Helper.parseDateTime(lineArray[0]);
open = Helper.parseDecimal(lineArray[1]);
high = Helper.parseDecimal(lineArray[2]);
low = Helper.parseDecimal(lineArray[3]);
close = Helper.parseDecimal(lineArray[4]);
volume = Helper.parseInt(lineArray[5]);
adjClose = Helper.parseDecimal(lineArray[6]);
switch (market)
{
case "nasdaq":
DailyNasdaqData nasdaqData = new DailyNasdaqData();
var nasdaqQuery = from r in entity.DailyNasdaqDatas.AsParallel().AsEnumerable()
where r.Date == date
select new StockData { Close = r.AdjustedClose };
List<StockData> nasdaqResult = nasdaqQuery.AsParallel().ToList(); // hits this line
break;
default:
break;
}
}
}
// now save everything
entity.SaveChanges();
}
}
);
}
Async lambdas work like async methods in one regard: They do not complete synchronously but they return a Task. In your parallel loop you are simply generating tasks as fast as you can. Those tasks hold onto memory and other resources such as DB connections.
The simplest fix is probably to just use synchronous database commits. This will not result in a loss of throughput because the database cannot deal with high amounts of concurrent DML anyway.

Categories