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;
}
Related
I'm trying to subscribe to real-time updates with Cloud Firestore in c# using Google.Cloud.Firestore.V1Beta1. I'm using the following code, which receives updates for a short time, until the stream is closed. Has anyone got FirestoreClient.Listen to work?
// Create client
FirestoreClient firestoreClient = FirestoreClient.Create();
// Initialize streaming call, retrieving the stream object
FirestoreClient.ListenStream duplexStream = firestoreClient.Listen();
// Create task to do something with responses from server
Task responseHandlerTask = Task.Run(async () =>
{
IAsyncEnumerator<ListenResponse> responseStream = duplexStream.ResponseStream;
while (await responseStream.MoveNext())
{
ListenResponse response = responseStream.Current;
Console.WriteLine(response);
}
});
// Send requests to the server
var citiesPath = string.Format("projects/{0}/databases/{1}/documents/cities/CJThcwCipOtIEAm2tEMY", projectId, databaseId);
// Initialize a request
var dt = new DocumentsTarget { };
dt.Documents.Add(citiesPath);
ListenRequest request = new ListenRequest
{
Database = new DatabaseRootName(projectId, databaseId).ToString(),
AddTarget = new Target
{
Documents = dt
}
};
// Stream a request to the server
await duplexStream.WriteAsync(request);
// Await the response handler.
// This will complete once all server responses have been processed.
Console.WriteLine("Awaiting responseHandlerTask");
await responseHandlerTask;
Edit 1:
I've tried setting the expiration explicitly to never expire, but still no luck, I get 5 minutes in then receive a RST_STREAM.
//Setup no expiration for the listen
CallSettings listenSettings = CallSettings.FromCallTiming(CallTiming.FromExpiration(Expiration.None));
// Initialize streaming call, retrieving the stream object
FirestoreClient.ListenStream duplexStream = firestoreClient.Listen(listenSettings);
Edit 2:
It seems like a bit of a kludge, but I found it works to keep track of the last resetToken, catch the exception, then restart the request with the request token. I've updated the code that makes the original request to take an optional resumeToken.
ListenRequest request = new ListenRequest
{
Database = new DatabaseRootName(projectId, databaseId).ToString(),
AddTarget = new Target
{
Documents = dt
}
};
if (resumeToken != null)
{
Console.WriteLine(string.Format("Resuming a listen with token {0}", resumeToken.ToBase64()));
request.AddTarget.ResumeToken = resumeToken;
}
// Stream a request to the server
await duplexStream.WriteAsync(request);
It's not perfect, but I think it's the way Google implemented it in Node.js. It does result in an API call every 5 minutes, so there is some expense to it. Maybe that's the why it works this way?
Thanks
Until Jon finishes the official support, you can use something I put together if you need it right away. https://github.com/cleversolutions/FirebaseDotNetRamblings/blob/master/FirebaseDocumentListener.cs Its an extension method you can drop into your project and use like this:
//Create our database connection
FirestoreDb db = FirestoreDb.Create(projectId);
//Create a query
CollectionReference collection = db.Collection("cities");
Query qref = collection.Where("Capital", QueryOperator.Equal, true);
//Listen to realtime updates
FirebaseDocumentListener listener = qref.AddSnapshotListener();
//Listen to document changes
listener.DocumentChanged += (obj, e) =>
{
var city = e.DocumentSnapshot.Deserialize<City>();
Console.WriteLine(string.Format("City {0} Changed/Added with pop {1}", city.Name, city.Population));
};
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?
I'm working on creating a WindowsPhone 8.1 app, and I'm having trouble getting the client to access the database. I created a server-side project that works fine using web api. I'm able to run debugger and add "/api/entityName" to return a list of all the rows in that table or just a single row if I specify an id value. After doing a lot of testing on the client side, I think I've pinpointed my error: the uri value. Can someone tell me what value I should be passing into the uri constructor? Here's the method that I'm using in the client:
public async void GetBars()
{
var uri = new Uri("http://localhost:20672/tables/bars"); //seems like this value is the problem
var httpClient = new HttpClient();
barsListBox.Items.Add("right before try starts");
// Always catch network exceptions for async methods
try
{
barsListBox.Items.Add("try started");
var result = await httpClient.GetStringAsync(uri); //never gets past this line. goes straight to finally
barsListBox.Items.Add("right before linq");
var queryAllBars =
from bar in result
select bar;
barsListBox.Items.Add("linq finished");
foreach (var bar in queryAllBars)
{
barsListBox.Items.Add(bar);
}
}
catch
{
// Details in ex.Message and ex.HResult.
}
finally
{
barsListBox.Items.Add("finally executed");
httpClient.Dispose();
}
}
The database is a SQL Server database being hosted on Azure. I've tried using the URL listed for the database in Azure, my current IP address, just about every combination of using/excluding the port number, etc but nothing seems to work. I don't get any errors, but I also don't get anything displayed in the UI (except for the testing statements I've entered). Try started gets printed, but right before linq doesn't, which is why I believe my problem is coming from the uri value being passed int GetStringAsync. Thanks for the help.
You can Try like this
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://Ipaddress/mammo/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync("api/controllername");
if (response.IsSuccessStatusCode)
{
IList<something> data = await response.Content.ReadAsAsync<IList<something>>();
}
}
Thanks to #Midhun's answer and other answers I received, I was able to get the bars to print correctly. I used Midhun's code above with the uri of my hosted database (the azurewebsites.net url) instead of my localhost database. I also changed the IList to a String and wrote a method that picks out the values using IndexOf and Substring as follows:
start = bar.IndexOf("BarID", start) + 7;
int end = bar.IndexOf(",", start);
int id = Convert.ToInt32(bar.Substring(start, (end - start)));
Bars newBar = new Bars(id, name, street, city, state, phone, zip);
Bars.barsList.Add(newBar);
I then created a static list in my Bars model to add the newly created Bars items to.
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();
}
}
I have a page which is fetching data from a webservice using async call.
If i get the response from webservice control goes to catch where a message box is pooped.
The code is given below:
string uri = "http://free.worldweatheronline.com/feed/weather.ashx?key=b7d3b5ed25080109113008&q=Mumbai&num_of_days=5";
UriBuilder fullUri = new UriBuilder("http://free.worldweatheronline.com/feed/weather.ashx");
fullUri.Query = "key=b7d3b5ed25080109113008&q=Mumbai&num_of_days=5";
HttpWebRequest forecastRequest = (HttpWebRequest)WebRequest.Create(fullUri.Uri);
// set up the state object for the async request
ForecastUpdateState forecastState = new ForecastUpdateState();
forecastState.AsyncRequest = forecastRequest;
// start the asynchronous request
forecastRequest.BeginGetResponse(new AsyncCallback(HandleForecastResponse), forecastState);
This part is response
private void HandleForecastResponse(IAsyncResult asyncResult)
{
try
{
// get the state information
ForecastUpdateState forecastState = (ForecastUpdateState)asyncResult.AsyncState;
HttpWebRequest forecastRequest = (HttpWebRequest)forecastState.AsyncRequest;
// end the async request
forecastState.AsyncResponse = (HttpWebResponse)forecastRequest.EndGetResponse(asyncResult);
Stream streamResult;
string newCityName = "";
//int newHeight = 0;
// get the stream containing the response from the async call
streamResult = forecastState.AsyncResponse.GetResponseStream();
// load the XML
XElement xmlWeather = XElement.Load(streamResult);
}
catch (Exception ex)
{
MessageBox.Show("Connection Error");
}
}
Problem :
when the page is loaded it starts fetching data from webservice(consider the case when the web service is not responding and control goes to catch part).
In the mean time if we press the back button or navigate the page the message box popps on the new page.
How could i stop that.
Thanks and Regards
Haven't tested it, but it may work:
1/ Store the value of the NavigationService.CurrentSource property somewhere it can be retrieved (the best would be in the asyncState parameter, but a property may work as well
2/ In the HandleForecastResponse, compare the old and new value of the NavigationService.CurrentSource. This way, you should be able to deduce if the active page has changed or not.
ifixed that problem by add
System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() =>
{
});
try this
private void HandleForecastResponse(IAsyncResult asyncResult)
{
try
{
// get the state information
ForecastUpdateState forecastState = (ForecastUpdateState)asyncResult.AsyncState;
HttpWebRequest forecastRequest = (HttpWebRequest)forecastState.AsyncRequest;
// end the async request
forecastState.AsyncResponse = (HttpWebResponse)forecastRequest.EndGetResponse(asyncResult);
Stream streamResult;
string newCityName = "";
//int newHeight = 0;
// get the stream containing the response from the async call
streamResult = forecastState.AsyncResponse.GetResponseStream();
// load the XML
XElement xmlWeather = XElement.Load(streamResult);
}
catch (Exception ex)
{
System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() =>
{
MessageBox.Show("Connection Error");
});
}
}
Finally solved it.
catch (Exception x)
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
var currentPage = ((App)Application.Current).RootFrame.Content as PhoneApplicationPage;
if ((currentPage.ToString()).Equals("MumbaiMarathon.Info.News"))
{
MessageBox.Show("Connection Error");
}
});
}
I just checked at the time of popping the message box the name of the Current UI application page. If its same as the page from which message box is initiated than it pops otherwise not.