Return a User and Message in Parse Query - parse-platform

Updated:
I am able to get to here, but I still can't return the username.
public async void getMessagesFromGroup1(string sGroupObjectId) {
try{
var innerQuery = ParseObject.GetQuery("Message").WhereEqualTo("Group", ParseObject.CreateWithoutData("Group", sGroupObjectId)).Include("User"); //.Include("Category");
IEnumerable<ParseObject> MyFirstResults = await innerQuery.FindAsync();
Console.WriteLine("made it past the query");
foreach (var result in MyFirstResults)
{
Console.WriteLine("made it into forloop");
var category = result.Get<string>("Content");
Console.WriteLine ("The message is......... " + category);
var userObject = result.Get<ParseObject>("User");
var user = result.Get<string>("username");
Console.WriteLine ("The from user......... " + user);
// return category;
}
}
catch(Exception exception){
Console.WriteLine ("- " + exception.Message.ToString());
}
}
I am building a message board application using Parse and Xamarin.
I need to query a table of Messages and return the Content of each message and the Username of the person who posted the message.
This should return a list.
I am able to retrieve the Message.Content, but not the User information.
How can I return the username from user table?
I appreciate your advice and thoughts.
Current Code:
public async void getMessagesFromGroup(string sGroupObjectId) {
// OBJECT ID: ejphwBr3UX
var query = from message in ParseObject.GetQuery("Message")
where message["Group"] == ParseObject.CreateWithoutData("Group", sGroupObjectId)
select message;
IEnumerable<ParseObject> results1 = await query.FindAsync ();
// List<ParseObject> list = results.ToList;
List<ParseObject> list = results1.ToList();
Console.WriteLine ("testing");
try
{
Console.WriteLine ("test" + list[0].Get<string>("Content") + " ");
}
catch (Exception exception){
Console.WriteLine ("- " + exception.Message.ToString());
}
// Get our button from the layout resource,
// and attach an event to it
}

Solved.
this is how I did it... I had to convert the Parse Object into a parseuser
public async void getMessagesFromGroup1(string sGroupObjectId) {
try{
var innerQuery = ParseObject.GetQuery("Message").WhereEqualTo("Group", ParseObject.CreateWithoutData("Group", sGroupObjectId)).Include("User"); //.Include("Category");
IEnumerable<ParseObject> MyFirstResults = await innerQuery.FindAsync();
Console.WriteLine("made it past the query");
foreach (var result in MyFirstResults)
{
Console.WriteLine("made it into forloop");
var Content = result.Get<string>("Content");
Console.WriteLine ("The message is......... " + Content);
var userObject = result.Get<ParseUser>("User");
var user = userObject.Username;
Console.WriteLine ("The message is from user......... " + user);
// return category;
}
}
catch(Exception exception){
Console.WriteLine ("- " + exception.Message.ToString());
}
}

Related

Poper way to make a HTTPClient PostAsync and GetAsync?

I want to make a proper HTTPClient request. I have a code but I am always getting so may exceptions like:
Java.IO.IOException: Socket closed
System.OperationCanceledException: The operation was canceled.
Java.Net.SocketException: Connection reset
Java.Net.SocketException: Software caused connection abort
Java.Net.UnknownHostException: android_getaddrinfo failed: EAI_NODATA (No address associated with hostname)
Java.Net.UnknownHostException: Unable to resolve host "tbs.scratchit.ph": No address associated with hostname
Java.IO.IOException: isConnected failed: ETIMEDOUT (Connection timed out)
Java.Net.SocketException: recvfrom failed: ECONNRESET (Connection reset by peer)
I am always getting these kinds of exceptions, errors.
I am starting to wonder how can I create a Post Async and GetAsync properly to avoid these errors in the future?
Here is how I create a HTTP Client:
1. I have a class call Constants, in there I will declare a new HTTP Client so that I only have 1 HTTPClient across my project
public class Constants
{
public static HttpClient client = new HttpClient();
}
2. I have a function(s) that gets data from my server through a PHP API by sending the parameters through JSON.
public async void FirstTimeSyncUser(string host, string database, string contact, string ipaddress)
{
try
{
syncStatus.Text = "Checking internet connection";
string apifile = "first-time-sync-user-api.php";
if (CrossConnectivity.Current.IsConnected)
{
syncStatus.Text = "Initializing first-time user sync";
var db = DependencyService.Get<ISQLiteDB>();
var conn = db.GetConnection();
var getData = conn.QueryAsync<UserTable>("SELECT * FROM tblUser WHERE ContactID = ? AND Deleted != '1'", contact);
var resultCount = getData.Result.Count;
var current_datetime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
int count = 1;
var settings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
MissingMemberHandling = MissingMemberHandling.Ignore
};
if (resultCount == 0)
{
syncStatus.Text = "Getting user data from the server";
var link = "http://" + ipaddress + "/" + Constants.apifolder + "/api/" + apifile;
string contentType = "application/json";
JObject json = new JObject
{
{ "Host", host },
{ "Database", database },
{ "ContactID", contact }
};
Constants.client.DefaultRequestHeaders.ConnectionClose = true;
var response = await Constants.client.PostAsync(link, new StringContent(json.ToString(), Encoding.UTF8, contentType));
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
if (!string.IsNullOrEmpty(content))
{
try
{
var dataresult = JsonConvert.DeserializeObject<List<UserData>>(content, settings);
var datacount = dataresult.Count;
for (int i = 0; i < datacount; i++)
{
syncStatus.Text = "Syncing user " + count + " out of " + datacount;
var item = dataresult[i];
var userid = item.UserID;
var usrpassword = item.UsrPassword;
var usertypeid = item.UserTypeID;
var userstatus = item.UserStatus;
var lastsync = DateTime.Parse(current_datetime);
var lastupdated = item.LastUpdated;
var deleted = item.Deleted;
var insertdata = new UserTable
{
UserID = userid,
UsrPassword = usrpassword,
ContactID = contact,
UserTypeID = usertypeid,
UserStatus = userstatus,
LastSync = lastsync,
LastUpdated = lastupdated,
Deleted = deleted
};
await conn.InsertOrReplaceAsync(insertdata);
count++;
}
synccount += "Total synced user: " + count + "\n";
var logType = "App Log";
var log = "Initialized first-time sync (<b>User</b>) <br/>" + "App Version: <b>" + Constants.appversion + "</b><br/> Device ID: <b>" + Constants.deviceID + "</b>";
int logdeleted = 0;
Save_Logs(contact, logType, log, database, logdeleted);
Preferences.Set("userchangeslastcheck", current_datetime, "private_prefs");
FirstTimeSyncSystemSerial(host, database, contact, ipaddress);
}
catch
{
var retry = await DisplayAlert("Application Error", "Syncing failed. Failed to send the data.\n\n Error:\n\n" + content + "\n\n Do you want to retry?", "Yes", "No");
if (retry.Equals(true))
{
FirstTimeSyncUser(host, database, contact, ipaddress);
}
else
{
First_Time_OnSyncFailed();
}
}
}
else
{
Preferences.Set("userchangeslastcheck", current_datetime, "private_prefs");
FirstTimeSyncSystemSerial(host, database, contact, ipaddress);
}
}
else
{
var retry = await DisplayAlert("Application Error", "Syncing failed. Server is unreachable.\n\n Error:\n\n"+ response.StatusCode +" Do you want to retry?", "Yes", "No");
if (retry.Equals(true))
{
FirstTimeSyncUser(host, database, contact, ipaddress);
}
else
{
First_Time_OnSyncFailed();
}
}
}
else
{
SyncUserClientUpdate(host, database, contact, ipaddress);
}
}
else
{
var retry = await DisplayAlert("Application Error", "Syncing failed. Please connect to the internet to sync your data. Do you want to retry?", "Yes", "No");
if (retry.Equals(true))
{
FirstTimeSyncUser(host, database, contact, ipaddress);
}
else
{
First_Time_OnSyncFailed();
}
}
}
catch (Exception ex)
{
Crashes.TrackError(ex);
var retry = await DisplayAlert("Application Error", "Syncing failed. Failed to send the data.\n\n Error:\n\n" + ex.Message.ToString() + "\n\n Do you want to retry?", "Yes", "No");
if (retry.Equals(true))
{
FirstTimeSyncUser(host, database, contact, ipaddress);
}
else
{
First_Time_OnSyncFailed();
}
}
}
3. After getting the data I needed it will execute another function with another POSTASYNC Call. In my code above when I got the user data from my server it will execute the next function which is FirstTimeSyncSystemSerial(host, database, contact, ipaddress);
What am I doing wrong? and How can I improve this so that I can avoid these exceptions?
Debug your code to find out where the exception is thrown.
Put a try catch blocked around that block of code. Then catch all the expected exceptions and try loopback again for a number of time.
You can Make a Generic Custom Service call That Can be Called Anywhere When You Need
public class RestClient : IRestClient
{
private const string TokenHeaderKey = "Any Token Header";
private HttpClient _httpclient = new HttpClient();
public async Task<T> GetAsync<T>(string url, string token) where T : new()
{
var responseContent = await ExecuteRequest(
async () =>
{
try
{
AddTokenToDefaultRequestsHeader(token);
return await _httpclient.GetAsync(url);
}
finally
{
ClearAuthenticationHeader();
}
});
return await Deserialize<T>(responseContent);
}
private void AddTokenToDefaultRequestsHeader(string token)
{
_httpclient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(TokenHeaderKey, token);
}
private void ClearAuthenticationHeader()
{
_httpclient.DefaultRequestHeaders.Authorization = null;
}
private static async Task<HttpContent> ExecuteRequest(Func<Task<HttpResponseMessage>> requestFunc)
{
HttpResponseMessage response = null;
try
{
response = await requestFunc();
if (!response.IsSuccessStatusCode)
{
var message = $"Executed HTTP request returned status code {response.StatusCode} and reason phrase {response.ReasonPhrase}";
if (response.StatusCode == HttpStatusCode.Unauthorized)
{
throw new Exception(message);
}
throw new Exception(message);
}
return response.Content;
}
catch (Exception exception)
{
if (exception is HttpRequestException || exception is WebException || exception is TaskCanceledException)
{
throw new Exception(
"Could not connect to service.");
}
throw;
}
}
private static async Task<T> Deserialize<T>(HttpContent responseContent) where T : new()
{
try
{
var responseContentString = await responseContent.ReadAsStringAsync();
return JsonConvert.DeserializeObject<T>(responseContentString);
}
catch (Exception exception)
{
if (exception is TaskCanceledException || exception is JsonException)
{
throw new Exception("Could not deserialize response content.", exception);
}
throw;
}
}
And Add an App settings class
public class AppSettings : IAppSettings
{
public string Server => "server url";
public string ServerEndPoint => "End point";
public string Token => "Token If you Have any";
}
Then Call Like this
public class Servicecall
{
private readonly IRestClient _restClient;
private readonly IAppSettings _appSettings;
public PatientService(IRestClient restClient, IAppSettings appSettings)
{
_restClient = restClient;
_appSettings = appSettings;
}
public async Task<IList<PatientViewModel>> GetPatients()
{
var url = _appSettings.Server + _appSettings.EndPoint ;
var token = _appSettings.Token;
return GetPatientList(await _restClient.GetAsync<List<ListModelClass>>(url, token));
}
public IList<Model> GetPatientList(IList<ListModelClass> List)
{
return List.Select(p => new Model(p)).ToList();
}
}
This way You can Call deferent services without typing a lot of boilercodes
This way You can Call Services with real ease

.NET MVC Web API Upload file to local storage and data model to database

I want to upload a file and pass the model with it. But when I try it from postman, it Always bring error.
Here is my code
public async Task<IHttpActionResult> PostArPumPd([FromBody] tx_arPumPd pum)
{
try
{
if (pum == null)
{
return Content(HttpStatusCode.BadRequest, "Enter the data correctly");
}
else
{
tx_arPumPd arpumpds = new tx_arPumPd()
{
doc_no = doc,
doc_date = DateTime.Now,
descs = pum.descs,
currency_code = pum.currency_code,
amount = pum.amount,
employee_code = pum.employee_code,
head_code = pum.head_code,
company_code = pum.company_code,
created_by = pum.emp_code,
created_date = DateTime.Now
};
db.tx_arPumPd.Add(arpumpds);
var multiFormDataStreamProvider = new MultiFileUploadProvider(Constants.MEDIA_PATH);
var mod = "PP";
var newFileName = mod + "_" + doc;
await Request.Content.ReadAsMultipartAsync(multiFormDataStreamProvider);
try
{
await FileHelper.Upload(multiFormDataStreamProvider, mod, newFileName);
db.SaveChanges();
return Content(HttpStatusCode.Created, "Data was save");
}
catch (Exception ex)
{
return Content(HttpStatusCode.BadRequest, ex);
}
}
}
catch (Exception ex)
{
return Content(HttpStatusCode.BadRequest, ex);
}
}
I get an Error while i get to this part
await Request.Content.ReadAsMultipartAsync(multiFormDataStreamProvider);
This is the error
ioexception: unexpected end of mime multipart stream. mime multipart
message is not complete test with postman
Is there anyone who know why? And Help me to upload file and the data model?
Thank you very much for your help
Okay I found the answer. To save a file and the Form data, i'm not parse the model. I'm just send the data from postmant using form data and the value is Json data. So I read the request from ReadAsMultipartAsync and get the Json data, and then deserilize the json. After that we can save the data.
This how I send the data from postmant
Postmant
and this is the code
public async Task<IHttpActionResult> PostArPumPd()
{
try
{
var multiFormDataStreamProvider = new MultiFileUploadProvider(Constants.MEDIA_PATH);
var readToProvider = await Request.Content.ReadAsMultipartAsync(multiFormDataStreamProvider);
// Get Json Data and Deserialize it
var json = await readToProvider.Contents[0].ReadAsStringAsync();
tx_arPumPd a = JsonConvert.DeserializeObject<tx_arPumPd>(json);
// Set mod and file name for FileHelper classl
var mod = "PP";
var newFileName = mod + "_" + doc ;
tx_arPumPd arpumpds = new tx_arPumPd()
{
doc_no = doc,
doc_date = DateTime.Now,
descs = a.descs,
currency_code = a.currency_code,
amount = a.amount,
employee_code = a.employee_code,
head_code = a.head_code,
company_code = a.company_code,
created_by = a.emp_code,
created_date = DateTime.Now
};
db.tx_arPumPd.Add(arpumpds);
var dtl = a.tx_arPumPdDtl;
foreach (var item in dtl)
{
item.doc_no = doc;
item.bg_is_ok = true;
item.bg_approved = true;
item.bg_app_date = DateTime.Now;
item.created_by = a.emp_Code;
item.created_date = DateTime.Now;
db.tx_arPumPdDtl.Add(item);
}
try
{
await FileHelper.Upload(multiFormDataStreamProvider, mod, newFileName);
db.SaveChanges();
return Content(HttpStatusCode.Created, "Data was save");
}
catch (Exception ex)
{
return Content(HttpStatusCode.BadRequest, ex);
}
}
catch (Exception ex)
{
return Content(HttpStatusCode.BadRequest, ex);
}
}
if anyone has a better way to do this, i'm still very happy getting to know about it.
Thank you.

Bot Framework with LUIS - Issue with opening Form one after another

My bot is supposed to help delete appointment.
A prompt for user's nric will be done (in RetrieveAppt.cs)
Subsequently, if there is such user in my database, it should go on to prompt user to enter the apptId which he/she wants to delete (as there may be multiple appointments made by same person) (in DeleteAppt.cs)
Issue Description
Exception thrown: 'Microsoft.Bot.Builder.Internals.Fibers.InvalidNeedException' in Microsoft.Bot.Builder.dll
Code Example
RetrieveAppt.cs
using Microsoft.Bot.Builder.FormFlow;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
namespace Bot.Models
{
[Serializable]
public class RetrieveAppt
{
[Prompt("Please provide your NRIC:")]
public string Nric { get; set; }
public override string ToString()
{
var builder = new StringBuilder();
builder.AppendFormat(Nric);
return builder.ToString();
}
}
}
DeleteAppt.cs
using Microsoft.Bot.Builder.FormFlow;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
namespace Bot.Models
{
[Serializable]
public class DeleteAppt
{
[Prompt("Please enter the appointment id that you wish to delete/cancel :")]
public string apptId { get; set; }
public override string ToString()
{
var builder = new StringBuilder();
builder.AppendFormat(apptId);
return builder.ToString();
}
}
}
ApptLuisDialog.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Builder.Luis;
using Microsoft.Bot.Builder.Luis.Models;
using System.Threading.Tasks;
using Microsoft.Bot.Builder.FormFlow;
using Microsoft.Bot.Connector;
using Bot.Models;
using System.Data.SqlClient;
using System.Globalization;
namespace Bot.Dialogs
{
[LuisModel("I have my own key", "I have my own key")]
[Serializable]
class ApptLuisDialog : LuisDialog<ApptLuisDialog>
{
String sql = #"Data Source=(localdb)\MSSQLLocalDB; Initial Catalog=Temp.DB; User Id = (insert your username here); Password = (insert your password here); Integrated Security=true;MultipleActiveResultSets = true";
private static IForm<RetrieveAppt> BuildRetrieveForm()
{
var builder = new FormBuilder<RetrieveAppt>();
return builder.AddRemainingFields().Build();
}
private static IForm<DeleteAppt> BuildDeleteForm()
{
var builder = new FormBuilder<DeleteAppt>();
return builder.AddRemainingFields().Build();
}
[LuisIntent("")]
[LuisIntent("None")]
public async Task None(IDialogContext context, LuisResult result)
{
System.Diagnostics.Debug.WriteLine("Entered here: B");
await context.PostAsync("I'm sorry I don't understand you. However, I can help you to: \n\n" + "1) Retrieve Appointment \n\n" + "2) Create Appointment \n\n" + "3) Delete Appointment \n\n" + "4) Edit Appointment");
context.Wait(MessageReceived);
}
[LuisIntent("RetrieveAppointment")]
public async Task RetrieveAppointment(IDialogContext context, LuisResult result)
{
System.Diagnostics.Debug.WriteLine("Entered here: C");
var form = new RetrieveAppt();
var entities = new List<EntityRecommendation>(result.Entities);
var retrieveAppt = new FormDialog<RetrieveAppt>(form, BuildRetrieveForm, FormOptions.PromptInStart);
context.Call(retrieveAppt, RetrieveComplete);
}
private async Task RetrieveComplete(IDialogContext context, IAwaitable<RetrieveAppt> result)
{
RetrieveAppt appt = null;
try
{
appt = await result;
}
catch (OperationCanceledException)
{
await context.PostAsync("You cancelled the form!");
return;
}
if (appt != null)
{
//getting user's input value
String nric = appt.Nric.ToString();
List<string> apptInfo = new List<string>();
//Create connection
SqlConnection con = new SqlConnection(sql);
//SQL Command
SqlCommand cmd = new SqlCommand("SELECT * FROM Appointment a WHERE a.Nric ='" + nric + "'", con);
//Open sql connection
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
String date = dr["AptDate"].ToString();
String[] temp = date.Split(null);
apptInfo.Add("Appointment ID: " + dr["ApptId"].ToString() + "\n\n"
+ "Nric: " + dr["Nric"].ToString() + "\n\n"
+ "Date: " + temp[0] + "\n\n"
+ "Time: " + dr["AptStartTime"].ToString() + "\n\n"
+ "Location: " + dr["Location"].ToString() + "\n\n"
+ "Purpose: " + dr["Purpose"].ToString());
}
//Close sql connection
dr.Close();
con.Close();
if (apptInfo.Count == 0)
{
await context.PostAsync("You do not have an appointment/no such NRIC");
}
else
{
for (int i = 0; i < apptInfo.Count(); i++)
{
await context.PostAsync("Your Appointment Info is: " + "\n\n" + apptInfo[i]);
}
}
}
else
{
await context.PostAsync("Form returned empty response!");
}
context.Wait(MessageReceived);
}
[LuisIntent("DeleteAppointment")]
public async Task DeleteAppointment(IDialogContext context, LuisResult result)
{
System.Diagnostics.Debug.WriteLine("Entered here: A");
var form = new RetrieveAppt();
var retrieveAppt = new FormDialog<RetrieveAppt>(form, BuildRetrieveForm, FormOptions.PromptInStart);
context.Call(retrieveAppt, Delete);
}
private async Task Delete(IDialogContext context, IAwaitable<RetrieveAppt> result)
{
RetrieveAppt appt = null;
try
{
appt = await result;
}
catch (OperationCanceledException)
{
await context.PostAsync("You cancelled the form!");
return;
}
if (appt != null)
{
//getting user's input value
String nric = appt.Nric.ToString().ToUpper();
List<string> apptInfo = new List<string>();
//SqlAdapter for inserting new records
SqlDataAdapter sda = new SqlDataAdapter();
//Create connection
SqlConnection con = new SqlConnection(sql);
//SQL Command to check existing patient
SqlCommand cmd = new SqlCommand("SELECT * FROM Appointment a WHERE a.Nric ='" + nric + "'", con);
//Open sql connection
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
String date = dr["AptDate"].ToString();
String[] temp = date.Split(null);
apptInfo.Add("Appointment ID: " + dr["ApptId"].ToString() + "\n\n"
+ "Nric: " + dr["Nric"].ToString() + "\n\n"
+ "Date: " + temp[0] + "\n\n"
+ "Time: " + dr["AptStartTime"].ToString() + "\n\n"
+ "Location: " + dr["Location"].ToString() + "\n\n"
+ "Purpose: " + dr["Purpose"].ToString());
}
if (apptInfo.Count != 0)
{
**//this is the part that has error, i can't prompt for the appointment id that user wants to delete**
System.Diagnostics.Debug.WriteLine("Entered here: AA");
var form = new DeleteAppt();
var deleteAppt = new FormDialog<DeleteAppt>(form, BuildDeleteForm, FormOptions.PromptInStart);
context.Call(deleteAppt, DeleteComplete);
}
else
{
//Close sql connection
dr.Close();
con.Close();
await context.PostAsync("Invalid NRIC/No current appointment");
}
}
else
{
await context.PostAsync("Form returned empty response!");
}
context.Wait(MessageReceived);
}
private async Task DeleteComplete(IDialogContext context, IAwaitable<DeleteAppt> result)
{
DeleteAppt appt = null;
try
{
appt = await result;
}
catch (OperationCanceledException)
{
await context.PostAsync("You canceled the form!");
return;
}
if (appt != null)
{
//getting user's input value
String apptId = appt.apptId.ToString();
List<string> newApptInfo = new List<string>();
//SqlAdapter for inserting new records
SqlDataAdapter sda = new SqlDataAdapter();
//Create connection
SqlConnection con = new SqlConnection(sql);
//SQL Command to check existing patient
String cmd = "DELETE FROM Appointment a WHERE a.ApptId ='" + apptId + "'";
//Open sql connection
con.Open();
try
{
sda.InsertCommand = new SqlCommand(cmd, con);
sda.InsertCommand.ExecuteNonQuery();
//Close sql connection
con.Close();
await context.PostAsync("Appointment " + apptId + " cancelled successfully.");
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("Exception caught: " + ex);
}
}
else
{
await context.PostAsync("Form returned empty response!");
}
context.Wait(MessageReceived);
}
}
}
Expected Behavior
For example, after bot prompts user to input NRIC, user inputs "123456". So let's say, there are 3 appointments linked to NRIC "123456". So it will show all 3 appointments (with the following details: apptId, apptDate, apptTime, locatoin) first.
Next, I want the bot to prompt the user for the appointment that he/she wants to delete base on the apptId. (But this prompt is not showing)
Actual Results
Exception thrown: 'Microsoft.Bot.Builder.Internals.Fibers.InvalidNeedException' in Microsoft.Bot.Builder.dll
Help needed here definitely
adding a "return" statement would solve it.
When making the call to context.Call(deleteAppt, DeleteComplete); there should not follow a call to context.Wait(MessageReceived). So add a return statement after context.Call(deleteAppt, DeleteComplete);
if (apptInfo.Count != 0)
{
//this is the part that has error, i can't prompt for the appointment id that user wants to delete
System.Diagnostics.Debug.WriteLine("Entered here: AA");
var form = new DeleteAppt();
var deleteAppt = new FormDialog<DeleteAppt>(form, BuildDeleteForm, FormOptions.PromptInStart);
context.Call(deleteAppt, DeleteComplete);
return;
}

How to get current location coordinates in the Map feature in Xamarin Application?

I am working on location coordinates marking feature in the App.
I am using following dll's and google map.
Xamarin.Forms.Maps
Xam.Plugin.Geolocator
Xam.Plugin.ExternalMaps
In my iphone simulator, If the Location is NONE.It pulls default location some where in Rome, Italy
Following is the code written to pull the Map ..
public async Task<Xamarin.Forms.Maps.Position> GetPosition()
{
IsBusy = true;
Xamarin.Forms.Maps.Position p;
try
{
if (!locator.IsGeolocationAvailable)
{
p = new Xamarin.Forms.Maps.Position();
}
if (!locator.IsGeolocationEnabled)
{
p = new Xamarin.Forms.Maps.Position();
}
var position = await locator.GetPositionAsync(timeoutMilliseconds: 10000);
p = new Xamarin.Forms.Maps.Position(position.Latitude,position.Longitude);
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
p = new Xamarin.Forms.Maps.Position();
}
IsBusy = false;
return p;
}
public async Task<object> GetCityName(double latitude, double longitude) {
HttpClient client;
client = new HttpClient();
client.MaxResponseContentBufferSize = 256000;
try
{
var response = await client.GetAsync("https://maps.googleapis.com/maps/api/geocode/json?latlng=" + latitude + "," + longitude);
if (response.IsSuccessStatusCode)
{
var result = await response.Content.ReadAsStringAsync();
var json = Newtonsoft.Json.Linq.JObject.Parse(result);
var reValue = "" + json["results"][0]["formatted_address"];
var strArr = reValue.Split(',');
if (strArr.Length > 2)
return strArr[strArr.Length - 2] + ", " +strArr[strArr.Length - 1];
else
return "";
}
else {
Debug.WriteLine(#"Failed.");
return "Failed";
}
}
catch (Exception ex)
{
Debug.WriteLine(#"ERROR {0}", ex.Message);
return ex.Message;
}
}
Image :
elaborate your problem please, and change your conditions as follows:
if (CrossGeolocator.Current.IsGeolocationAvailable)
{
if (CrossGeolocator.Current.IsGeolocationEnabled)
{
var position = await locator.GetPositionAsync(timeoutMilliseconds: 10000);
p = new Xamarin.Forms.Maps.Position(position.Latitude,position.Longitude);
}
else
{
throw new Exception("Geolocation is turned off");
// Geolocation is turned off for the device.
}
}
else
{
throw new Exception("Geolocation is turned off");
// Geolocation not available for device
}
Here now Handle the catches from GetPosition() Method to make sure you don't get the default location.

"The request has already been submitted.” while working with Skydrive API in WP8

I am trying to use the SkyDrive API to upload a file. I tried using the below code.GEtAccountInformaiton and GetQuotaInformaiton methods are successfully executed But it always sets this error "The request has already been submitted.” at the end (in UploadISOFileToSkyDriveAsync() method for the field lblMessageBar.Text ).
private async void GetAccountInformations()
{
try
{
LiveOperationResult operationResult = await App.liveConnectClient.GetAsync("me");
var jsonResult = operationResult.Result as dynamic;
string firstName = jsonResult.first_name ?? string.Empty;
string lastName = jsonResult.last_name ?? string.Empty;
lblMessageBar.Text = "Welcome " + firstName + " " + lastName;
GetQuotaInformations();
}
catch (Exception e)
{
lblMessageBar.Text = e.ToString();
}
}
private async void GetQuotaInformations()
{
try
{
LiveOperationResult operationResult = await App.liveConnectClient.GetAsync("me/skydrive/quota");
var jsonResult = operationResult.Result as dynamic;
quota = jsonResult.quota ?? string.Empty;
available = jsonResult.available ?? string.Empty;
lblMessageBar.Text = "Available space in bytes: " + ConvertBytesToGigabytes(available).ToString("#.####") + "GB " + "out of bytes " + ConvertBytesToGigabytes(quota).ToString("#.####") + "GB";
UploadISOFileToSkyDriveAsync();
}
catch (Exception e)
{
lblMessageBar.Text = e.ToString();
}
}
public async void UploadISOFileToSkyDriveAsync()
{
try
{
//http://developer.nokia.com/Community/Wiki/SkyDrive_-_How_to_upload_content_on_Windows_Phone
IsolatedStorageFile fileStorage = IsolatedStorageFile.GetUserStoreForApplication();
StreamWriter Writer = new StreamWriter(new IsolatedStorageFileStream("/shared/transfers/" + Constants.SkyDriveSavedLocationsFileName, FileMode.Append, fileStorage));
//get the data from local database and write to the isolated file and then use the path of this file to saved it to skydrive..
ObservableCollection<SavedLocationsTableEntity> SavedLocations = SavedLocationsTableEntity.GetSavedLocations();
foreach (SavedLocationsTableEntity item in SavedLocations)
{
Writer.WriteLine(UtilityLib.GetGoogleURL(new System.Device.Location.GeoCoordinate(item.SavedLocationLatitude, item.SavedLocationLongitude, item.SavedLocationAltitude)));
}
Writer.Close();
using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
{
fileStream = store.OpenFile("/shared/transfers/" + Constants.SkyDriveSavedLocationsFileName, FileMode.OpenOrCreate, FileAccess.Read);
//strEncryptedFileStream = Encoding.Unicode.GetBytes(fileStream.ToString()).ToString();
if (fileStream.Length == 0)
{
lblMessageBar.Text = "No data to upload to SkyDrive..";
return;
}
fileStream.Close();
}
//remove previous calls
var reqList = BackgroundTransferService.Requests.ToList();
foreach (var req in reqList)
{
if (req.UploadLocation.Equals(new Uri(MyFilePathInIsoStore, UriKind.Relative)))
BackgroundTransferService.Remove(BackgroundTransferService.Find(req.RequestId));
}
//Make a new call to upload
LiveOperationResult res = await App.liveConnectClient.BackgroundUploadAsync("me/skydrive", new Uri("/shared/transfers/" + Constants.SkyDriveSavedLocationsFileName, UriKind.Relative), OverwriteOption.Overwrite);
lblMessageBar.Text = "File " + Constants.SkyDriveSavedLocationsFileName + " uploaded.";
return;
}
catch (Exception ex)
{
lblMessageBar.Text = "Cannot upload to SkyDrive.. " + ex.Message;
return;
}
}
It looks like MyFilePathInIsoStore here:
if (req.UploadLocation.Equals(new Uri(MyFilePathInIsoStore
is not equals "/shared/transfers/" + Constants.SkyDriveSavedLocationsFileName here:
new Uri("/shared/transfers/" + Constants.SkyDriveSavedLocationsFileName, UriKind.Relative)

Resources