C# HttpClient Uri value - c#

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.

Related

FirebaseAdmin FirebaseApp Check if Firebase Instance exists

I have a C# project that subscribes multiple Registrations to a Topic. Because of the nature of the project and the fact that you cant check to see how many people have already subscribed to a Topic I need to make the following Async Calls to the server:
Subscribe Registrations
TopicManagementResponse response = await FirebaseMessaging.DefaultInstance.SubscribeToTopicAsync(registrationTokens, topic);
Send message to Topic
string response = await FirebaseMessaging.DefaultInstance.SendAsync(message);
Unsubscribe Registrations
TopicManagementResponse response = await FirebaseMessaging.DefaultInstance.UnsubscribeFromTopicAsync(registrationTokens, topic);
Because there are three calls I need to Create an Instance of the FirebaseApp using Credentials:
FirebaseApp.Create(new AppOptions()
{
Credential = GoogleCredential.FromFile(path),
});
BUT because the async posts return a "WaitingForActivation" response (yet it does correctly do what it is supposed to do) I cant Delete the Instance to move on to the next function as it throws an error as it cant re-create another FirebaseApp Instance - It fails if I give it a name so I cant use GetInstance(string name).
Am I missing something or is there another way to do this.
Here is an example of a subscribe function:
internal static async Task SubscribeToTopic(string path, string topic, string regID5, string regID)
{
FirebaseApp app = FirebaseApp.Create(new AppOptions()
{
Credential = GoogleCredential.FromFile(path),
});
var registrationTokens = new List<string>()
{
regID5, regID
};
// Subscribe the devices corresponding to the registration tokens to the
// topic
try
{
TopicManagementResponse response = await FirebaseMessaging.DefaultInstance.SubscribeToTopicAsync(registrationTokens, topic);
using (StreamWriter sw = System.IO.File.AppendText(HttpContext.Current.Server.MapPath("/tokens.txt")))
{
sw.WriteLine($"{response.SuccessCount} tokens were subscribed successfully");
}
}
catch (Exception ex)
{
string myerror = ex.Message;
}
}
Any ideas?
you are creating firebase instance every time. so you need to create firebase instance in application start in global.asax file.

C# Connecting to Rest Service to retrieve information

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;
}

Firestore real-time-updates in c#

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));
};

UWP AppServiceConnection not getting value

I'm trying to communicate between my host app and service via AppServiceConnection. I'm using the following code in my host app:
using (var connection = new AppServiceConnection())
{
connection.AppServiceName = extension.AppServiceName;
connection.PackageFamilyName = extension.PackageFamilyName;
var connectionStatus = await connection.OpenAsync();
if (connectionStatus == AppServiceConnectionStatus.Success)
{
var response = await connection.SendMessageAsync(requestMessage);
if (response.Status == AppServiceResponseStatus.Success)
returnValue = response.Message as ValueSet;
}
}
And my service code:
private async void OnRequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args)
{
var messageDeferral = args.GetDeferral();
var message = args.Request.Message;
var returnData = new ValueSet();
var command = message["Command"] as string;
switch (command)
{
case "ACTION":
var value = await AsyncAction();
returnData = new ValueSet { { "Value", JsonConvert.SerializeObject(value) } };
break;
default:
break;
}
await args.Request.SendResponseAsync(returnData);
messageDeferral.Complete();
}
This works some of the time, but other times the ValueSet (returnValue) is randomly empty when the host receives it. It has Value in it when returned in the service, but when I get the response in the host, nothing.
I've verified that the service is indeed setting the value, adding it to the ValueSet and returning it correctly.
Note that my service is receiving the request, the host is receiving the response and the response status is Success; a failed connection isn't the issue.
Sometimes this happens only once before requests start working again, other times it will happen ten times in a row.
The first working response after a failure always takes significantly longer than normal.
Also, I have no issues in the request from host to service. It's always service to host where the problem shows up.
Has anyone else run into this issue and figured it out?
In the process of creating a sample app I realized what the problem was. I was performing an asynchronous action (albeit a very short one) before my line var messageDeferral = args.GetDeferral();. It appears that this was allowing the background task to be closed before it had responded to the host. Simply moving that line to the beginning of the OnRequestReceived function fixed the problem for me.
So for anyone who runs into a similar issue, get your deferral before you do anything else! Spare yourself the pain I went through.

windows phone slow connection GPRS httpClient request

i'm testing my app wp7 and i don't understand this error.
When I use the wifi everything works fine.
While when I turn off the wifi, use the data connection with a maximum speed equal to 2G, the string that I get from the server SOMETIMES is equal to NULL.
public void sentInfo()
{
myuri= new Uri(myuri);
//create connection to web
ReadDataFromWeb(myuri, myuseragent);
}
async private void ReadDataFromWeb(Uri site, string userAgent)
{
is_connected_to_internet();
client.MaxResponseContentBufferSize = 256000;
client.DefaultRequestHeaders.Add("user-agent", userAgent);
var response = await client.GetAsync(site);
var result = await response.Content.ReadAsStringAsync();
client.Dispose();
bool isJson = false;
if (result != null)
isJson = IsJson(result);
if (!isJson)
{
MessageBox.Show("ERROR");
}
....
}
I thought it was a server problem, I went to edit the php.ini file but nothing has changed.
Then I try to insert a different link instead of my default links, and I realized that it behaves the same way: sometimes reads the html content, sometimes it returns null.
I have tried several methods to make requests to the server (HttpClient and WebClient) but all with this result if the connection is slow.
The problem is that only this application, windows phone, it behaves in this way, while the iOS and Android app even if the connection is slow sooner or later return something other than null.

Categories