My mobile apps are based on Xamarin and receive some data from web server using SignalR. I've tried to use native Android port of SignalR client and JavaScript client and everything was fine.
But when I try to use SignalR Xamarin client app can connect to the server but receive empty response from the server. I've tried all kinds of fixes on client side but nothing helps me. I am sure that everything is fine on the server because everything works with another client.
Here is my server code:
public DataMessage GetData()
{
var DataList = db.data.ToList();
var DataIdList = new List<int>();
db.Dispose();
foreach (var a in DataList)
{
DataIdList.Add(a.id);
}
var result = new DataMessage(DataIdList);
return result;
}
And this is my app client code:
async public Task<DataList> GetDataList()
{
DataList dataList = new DataList();
Console.WriteLine(_hubConnection.State);
if (_hubConnection.State == ConnectionState.Connected)
{
try
{
dataList = await _hubProxy.Invoke<DataList>("GetData");
Console.WriteLine(dataList.data);
}
catch (Exception ex)
{
Console.WriteLine("SignalR Error GetDataList {0}", ex.Message);
}
}
if (dataList == null)
{
dataList = new DataList();
}
return dataList;
}
Can anybody help me with this issue?
Related
I’m relatively new to c# and working with API’s. I’ve created a simple windows form in VS and I’m trying to connect t a rest service to retrieve information based on a search condition (e.g ID number) and display everything in a data grid. I’ve been looking for examples of what I’m trying to achieve with very little success. The idea is to enable a user to enter an ID number inside a text box and click a “search” button which will then connect to the rest service and retrieve all the information related to that specific ID number and display it all in a data grid with column names. Is this possible? Can anyone advise me on how to establish my connection to the rest service?
Try this. Path1 is your connection:
The Class ApiResult is just a class with a List of ArticleApiModel.
public static List<ArticleApiModel> GetArticles (int id)
{
try
{
var task = Task<List<ArticleApiModel>>.Run(async () =>
{
using (HttpClient client = new HttpClient())
{
var response = await client.GetAsync(path1 + "/api/articles/",id);
if (response != null)
{
var jsonString = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<ApiResult>(jsonString);
return result.Result;
}
}
return null;
});
task.Wait();
return task.Result;
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
return null;
}
I am new at Microsoft Azure IoT Hub. I want to get a list of devices in my IoT Hub and check if there are any devices in the list.
Its works fine if I use a console application.
static async void QueryDevices()
{
registryManager = RegistryManager.CreateFromConnectionString(DeviceConnectionString);
var devices = await registryManager.GetDevicesAsync(100); // Time 1 sek
foreach (var item in devices)
{
Console.WriteLine("Divice id: " + item.Id + ", Connection state: " + item.ConnectionState);
}
Console.WriteLine("\nNumber of devices: " + devices.Count());
}
But if I use the "same" code in a WebAPI the GetDevicesAsync() keeps running and running without any result.
public bool CheckIoTHubConnection(string iotHubConnectionString)
{
registryManager = RegistryManager.CreateFromConnectionString(iotHubConnectionString);
return CreateConnection().Result;
}
private async Task<bool> CreateConnection()
{
bool connectionOk = false;
try
{
// Gets all devices from IoT Hub
var result = await registryManager.GetDevicesAsync(10); // This never gets further
if (result.Any())
connectionOk = true;
}
catch (Exception ex)
{
connectionOk = false;
throw ex;
}
return connectionOk;
}
What am I doing wrong?
You can try with this code format:
...
System.Threading.ThreadPool.QueueUserWorkItem(a => CheckIoTHubConnection(iotHubConnStr));
...
It works for me.
For more information you can reference the initial post "Send to IoT hub from MVC Web API?".
And for the reason of this issue, #Jason Malinowski's answer may explains at a certain extent.
I have a notification system for my Asp.net application that uses sql-server. Currently, when there is an update on certain tables email alert sent. I am wondering, if there is a way to use Lync instead of email so that when tables updated, users will get Lync messages?
You can use Lync client for .Net. Here is the link- https://code.msdn.microsoft.com/lync/Lync-2013-Use-the-Lync-47ded7b4
Below is a sample code.
using Microsoft.Lync.Model;
using Microsoft.Lync.Model.Conversation;
private static void SendMessage()
{
try
{
string[] arrRecepients = { "sip:receiver1#domain.com", "sip:receiver2#domain.com" }; //add your recepients here
LyncClient lyncClient = LyncClient.GetClient();
Conversation conversation = lyncClient.ConversationManager.AddConversation();
foreach (string recepient in arrRecepients)
{
conversation.AddParticipant(lyncClient.ContactManager.GetContactByUri(recepient));
}
InstantMessageModality imModality = conversation.Modalities[ModalityTypes.InstantMessage] as InstantMessageModality;
string message = GetNotification(); //use your existing notification logic here
imModality.BeginSendMessage(message, null, null);
}
catch (Exception ex)
{
}
}
I am a newbie when it comes to MVVM and Web related technologies. We are currently developing an MVVM client app using the latest MVVMLight framework in Visual Studios 2013. The application uses Microsoft's Webapi (latest version) to get data into our model via HTTP requests. Our code executes up to the point where the HTTP request is made, and we have confirmed that the server is getting the request, gathering up the requested data and returning it as JSON. However the client never sees the response, it just continues to wait for the response. Its almost as though we are seeing an issue that seems to do with threads. Where the request was made on one thread, but the response is being received on another. Here is our code (where the HTTP request is made):
public class DataService : IDataService
{
#region Fields
private HttpClient _client;
private LfActivityDataReturnObject _activityReturnObj;
private AdroServices _adroServices;
private bool _selectedProcssingOptionPosted = false;
private bool _activityDataSuccessfullyRetrieved = false;
private decimal _incomingLFEntryId;
#endregion
#region Constructor
public DataService()
{
try
{
//Get command line arguments
string[] arguments = Environment.GetCommandLineArgs();
for (int i = 1; i < arguments.Length; i++)
{
switch (i)
{
case 1:
{
if (!Decimal.TryParse(arguments[i], out _incomingLFEntryId))
{
_incomingLFEntryId = -1;
}
break;
}
}
}
if (_incomingLFEntryId <= 0)
{
throw new ArgumentException(String.Format("Invalid Activity Shortcut Entry ID: {0}", _incomingLFEntryId));
}
}
catch (Exception e)
{
throw e;
}
}
#endregion
#region Methods
public void GetGeneralInformationModel(Action<GeneralInformationModel, Exception> callback)
{
Exception locException = null;
GeneralInformationModel locGeneralInformationModel = null;
if (_adroServices == null)
{
try
{
//Start the HTTP request
GetActivityDataAsync().Wait();
}
catch (Exception e)
{
locException = e;
}
// change? should be for http success but adro failure
if (_activityDataSuccessfullyRetrieved)
{
_adroServices = new AdroServices(_activityReturnObj);
locGeneralInformationModel = new GeneralInformationModel(_adroServices);
}
else
{
Exception e2 = new Exception("Error retrieving activity data in DataService");
locException = e2;
}
}
else
{
locGeneralInformationModel = new GeneralInformationModel(_adroServices);
}
var item = locGeneralInformationModel;
callback(item, locException);
}
//Get data from the repository via the service layer.
private async Task GetActivityDataAsync()
{
try
{
using (this._client = new HttpClient())
{
_client.BaseAddress = new Uri("http://localhost:52512//");
_client.DefaultRequestHeaders.Accept.Clear();
_client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//Line below is where the app just runs getting no response
HttpResponseMessage caseDataResponse = await _client.GetAsync(string.Format("api/LfUrs/{0}", _incomingLFEntryId));
if (caseDataResponse.IsSuccessStatusCode)
{
_activityReturnObj = await caseDataResponse.Content.ReadAsAsync<LfActivityDataReturnObject>();
if (_activityReturnObj.ReturnCode == 0)
{
_activityDataSuccessfullyRetrieved = true;
}
else
{
_activityDataSuccessfullyRetrieved = false;
}
}
else
{
_activityDataSuccessfullyRetrieved = false;
}
}
}
catch (Exception ex)
{
_activityDataSuccessfullyRetrieved = false;
throw ex;
}
}
We have tried using Fiddler to get more information but Fiddler doesn't seem to be able to reveal any of the details. Also I should mention that we are simulating the server on the local host and as I stated above, we have confirmed the server gets the request and returns the data. My associates and I are starting to think this has something to do with the MVVM Light Framework and the IOC or possibly threading. When we use this same code in a MVVM solution that doesn't use the framework it works. Any help would be sincerely appreciated. Thanks...Mike
I have figured it out. Somehow, in my app.xaml, the Dispatcher.Helper had been moved to the event On_Startup rather than being contained in the class constructor. Additionally I had to move the HTTP stuff into the ADRO services class and make sure it was constructed in the App constructor in app.xaml right after Dispatcher.Helper. But thanks to everyone who participates here on StackOverFlow. This resource is an absolute life-saver. Thanks
Is there any possible that I can ensure that the application does not fall if app can not connect to the server using await socket.ConnectAsync(server) I get this exc:
But the biggest problem is I get this exception only occasionally and randomly. Try and catch completely unresponsive and applications fall. So I need something if I cannot connect firts time dont go to exception but try it again.
My code:
public async Task _connect(string token, string idInstalation, string lang)
{
try
{
if (token != null)
{
socket.SetRequestHeader("Token", token);
socket.SetRequestHeader("Lang", lang);
socket.SetRequestHeader("idInstallation", idInstalation);
}
await socket.ConnectAsync(server);
System.Diagnostics.Debug.WriteLine("Connected");
writer = new DataWriter(socket.OutputStream);
messageNumber = 1;
}
catch (Exception)
{
var dialog = new MessageDialog("Cannot connect to UNIAPPS server", "Error").ShowAsync();
}
}