WebAPI:How to read message from HttpResponseMessage class at client side - asp.net-web-api

below is a sample action which is returning HttpResponseMessage and if any error occur then this way web api action returning error message and status code to client side return Request.CreateErrorResponse(HttpStatusCode.NotFound, message);.
[HttpGet, Route("GetAll")]
public HttpResponseMessage GetAllCustomers()
{
IEnumerable<Customer> customers = repository.GetAll();
if (customers == null)
{
var message = string.Format("No customers found");
return Request.CreateErrorResponse(HttpStatusCode.NotFound, message);
}
else
{
return Request.CreateResponse(HttpStatusCode.OK, customers);
}
}
when i am invoking action by http client then i am not getting message in ReasonPhrase property. just tell me what is the right way to read message at client side which is passing like this way return Request.CreateResponse(HttpStatusCode.OK, customers);
here is my client side code
private async void btnFind_Click(object sender, EventArgs e)
{
var fullAddress = baseAddress + "api/customer/GetByID/"+txtFind.Text;
Customer _Customer = null;
using (var client = new HttpClient())
{
using (var response = client.GetAsync(fullAddress).Result)
{
if (response.IsSuccessStatusCode)
{
var customerJsonString = await response.Content.ReadAsStringAsync();
_Customer = JsonConvert.DeserializeObject<Customer>(customerJsonString);
}
else
{
Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
}
}
}
if (_Customer != null)
{
var _CustList = new List<Customer> { _Customer };
dgCustomers.DataSource = _CustList;
}
}
response.ReasonPhrase not holding the message which i am passing from action. so may be i am not doing things to read message. please tell me what to change in my code to read the message. thanks

i have the job this way.
private async void btnFind_Click(object sender, EventArgs e)
{
var fullAddress = baseAddress + "api/customer/GetByID/"+txtFind.Text;
Customer _Customer = null;
try
{
using (var client = new HttpClient())
{
using (var response = client.GetAsync(fullAddress).Result)
{
if (response.IsSuccessStatusCode)
{
var customerJsonString = await response.Content.ReadAsStringAsync();
_Customer = JsonConvert.DeserializeObject<Customer>(customerJsonString);
}
else
{
//Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
var ErrMsg = JsonConvert.DeserializeObject<dynamic>(response.Content.ReadAsStringAsync().Result);
MessageBox.Show(ErrMsg.Message);
}
}
}
if (_Customer != null)
{
var _CustList = new List<Customer> { _Customer };
dgCustomers.DataSource = _CustList;
}
}
catch (HttpRequestException ex)
{
// catch any exception here
}
}
read error message this way.
var ErrMsg = JsonConvert.DeserializeObject<dynamic>(response.Content.ReadAsStringAsync().Result);

Related

Xamarin forms monkey chat

I am using monkey chat in my mobile application(Xamrin forms based). While sending a message on IOS, on a real device, I have to click the send button 2 times. First time when I click, it minimizes the keyboard and 2nd time, it sends the message. Please suggest.
How do I send a message on one click?
Here is my send message function
namespace Budocode.ViewModels
{
public class MainChatViewModel : BaseViewModel
{
public ObservableRangeCollection Messages { get; }
ITwilioMessenger twilioMessenger;
string outgoingText = string.Empty;
public string OutGoingText
{
get { return outgoingText; }
set { SetProperty(ref outgoingText, value); }
}
public ICommand SendCommand { get; set; }
public ICommand LocationCommand { get; set; }
public MainChatViewModel()
{
// Initialize with default values
twilioMessenger = DependencyService.Get<ITwilioMessenger>();
Messages = new ObservableRangeCollection<ChatMessage>();
SendCommand = new Command(() =>
{
var message = new ChatMessage
{
Text = OutGoingText,
IsIncoming = false,
ProfileId = "profile" + GlobalSettingsDataSource.Current.SelectedProfileImageId + ".png",
MessageDateTime = DateTime.Now,
FromUser = GlobalSettingsDataSource.Current.SelectedProfile
};
if (string.IsNullOrWhiteSpace(OutGoingText))
return;
Messages.Add(message);
twilioMessenger?.SendMessage(message.Text, message.ProfileId, GlobalSettingsDataSource.Current.SelectedProfile);
OutGoingText = string.Empty;
});
LocationCommand = new Command(async () =>
{
try
{
var local = await CrossGeolocator.Current.GetPositionAsync(TimeSpan.FromSeconds(15));
var map = $"https://maps.googleapis.com/maps/api/staticmap?center={local.Latitude.ToString(CultureInfo.InvariantCulture)},{local.Longitude.ToString(CultureInfo.InvariantCulture)}&zoom=17&size=400x400&maptype=street&markers=color:red%7Clabel:%7C{local.Latitude.ToString(CultureInfo.InvariantCulture)},{local.Longitude.ToString(CultureInfo.InvariantCulture)}&key=";
var message = new ChatMessage
{
Text = "I am here",
AttachementUrl = map,
ProfileId = "profile" + GlobalSettingsDataSource.Current.SelectedProfileImageId + ".png",
IsIncoming = false,
MessageDateTime = DateTime.Now
};
Messages.Add(message);
twilioMessenger?.SendMessage("attach:" + message.AttachementUrl, message.ProfileId, GlobalSettingsDataSource.Current.SelectedProfile);
}
catch (Exception ex)
{
}
});
if (twilioMessenger == null)
return;
twilioMessenger.MessageAdded = (message) =>
{
//if (message.ProfileId == "Icon.png")
Device.BeginInvokeOnMainThread(() =>
{
if (message.FromUser != GlobalSettingsDataSource.Current.SelectedProfile)
{
message.IsIncoming = true;
}
else
{
message.IsIncoming = false;
}
Messages.Add(message);
});
};
}
public async void InitializeMock(string channelName)
{
try
{
var id = CrossDeviceInfo.Current.Id;
var userId = PersistantData.Current.UserAccount.Properties["user_id"];
HttpResponseMessage appResponse = CommonUtility.GetApiContent(
String.Format(ClientConfiguration.TwilioServiceChatHistory, id, GlobalSettingsDataSource.Current.SelectedProfile, channelName));
if (appResponse.IsSuccessStatusCode)
{
var chatContent = await appResponse.Content.ReadAsStringAsync();
List<ChatMessage> chatMsgs = JsonConvert.DeserializeObject<List<ChatMessage>>(chatContent);
Messages.ReplaceRange(chatMsgs);
}
}
catch
{
// ignore if there are any issues with twilio
}
}
}
}

Xamarin Forms not Debugging and ZXing freezing all the application

I made an application to read some QR Codes using Zxing on Xamarin. Days before yesterday, it was working good, but since yesterday I have this problem:
I put a breakpoint in OnAppearing() method, but it's ignored, Ok... When I click in the Zxing button, to open the scanner, the application stops, but don't show nothing, only freeze, no errors, no messages, no debug, nothing. My code is the same as when it was working, nothing changed. If anybody could help me, I'll be grateful.
public MainPage()
{
InitializeComponent();
this.InitializeComponent();
this.BindingContext = this;
this.IsBusy = false;
}
protected override async void OnAppearing()
{
base.OnAppearing();
var dados = new AcessoDB();
if (dados.GetAlunos().Count() > 0)
{
var infopage = new Wallet();
Navigation.InsertPageBefore(infopage, Navigation.NavigationStack[0]);
await Navigation.PopToRootAsync();
codeqr.IsEnabled = false;
}
}
private async void Scan_Clicked(object sender, EventArgs e)
{
semaphoreSlim.Release();
string img;
this.IsBusy = true;
if (CrossConnectivity.Current.IsConnected)
{
var scan = new ZXingScannerPage();
await Navigation.PushAsync(scan);
scan.OnScanResult += async (result) =>
{
bool liberado = await semaphoreSlim.WaitAsync(-1);
if (!liberado)
{
return;
}
scan.IsScanning = false;
Device.BeginInvokeOnMainThread(async () =>
{
if (CrossConnectivity.Current.IsConnected)
{
var parseResult = ResultParser.parseResult(result);
if (parseResult != null)
{
var hash = sha256_hash(result.ToString());
Aluno items = new Aluno();
try
{
scan.IsAnalyzing = false;
scan.IsScanning = false;
items = JsonConvert.DeserializeObject<Aluno>(result.ToString());
img = GetImage(items.Foto);
}
catch (Exception)
{
scan.IsScanning = false;
scan.IsAnalyzing = false;
await Navigation.PopAsync();
await DisplayAlert("Ops...", "Ocorreu algum erro com a leitura do seu código, tente de novo.", "Ok!");
return;
}
var info = new Aluno
{
Matricula = items.Matricula,
Nome = items.Nome,
RG = items.RG,
Nascimento = items.Nascimento,
Curso = items.Curso,
Campus = items.Campus,
Periodos = items.Periodos,
Modalidade = items.Modalidade,
Validade = items.Validade,
Hash = hash,
Foto = img
};
var infopage = new Wallet();
var dados = new AcessoDB();
if (!await dados.InserirAlunoAsync(info))
{
scan.IsAnalyzing = false;
scan.IsScanning = false;
await Navigation.PopAsync();
await DisplayAlert("Ops...", "Esse código não consta no nosso banco de dados, tem certeza que estuda no UGB?", "Repetir");
return;
}
try
{
scan.IsScanning = false;
scan.IsAnalyzing = false;
infopage.BindingContext = info;
Navigation.InsertPageBefore(infopage, Navigation.NavigationStack[0]);
await Navigation.PopToRootAsync();
}
catch (Exception)
{
scan.IsScanning = false;
scan.IsAnalyzing = false;
await DisplayAlert("Erro", "Não foi possível carregar a sua carteirinha.", "Ok...");
}
}
}
});
};
}
else
{
await DisplayAlert("Ops...", "Você não está conectado à internet.", "Ok!");
}
this.IsBusy = false;
}
public string GetImage(string foto)
{
if (String.IsNullOrEmpty(foto))
{
return "";
}
using (var WebClient = new WebClient())
{
var imageBytes = WebClient.DownloadData("http://portal.ugb.edu.br/upload/ImagemAluno/" + foto);
var sxtyfr = Convert.ToBase64String(imageBytes);
//var img = "data:image/jpg;base64," + sxtyfr;
return sxtyfr;
}
}
public static string sha256_hash(string value)
{
StringBuilder Sb = new StringBuilder(); using (SHA256 hash = SHA256Managed.Create())
{
Encoding enc = Encoding.UTF8;
Byte[] result = hash.ComputeHash(enc.GetBytes(value)); foreach (Byte b in result)
Sb.Append(b.ToString("x2"));
}
return Sb.ToString();
}
}
}
I solve my problem... I just clean, build and rebuild the solution, then magic happens. Thank you all to help me.

WebAPI: PostAsync with query string does not work

see my sample web api action which take one string type parameter.
[RoutePrefix("api/customer")]
public class CustomerController : ApiController
{
[HttpPost, Route("DeleteCustomer")]
public HttpResponseMessage DeleteProduct(string customerID)
{
HttpResponseMessage response = null;
Customer customer = repository.Get(customerID);
if (customer == null)
{
var message = string.Format("No customer found by the ID {0}", customerID);
HttpError err = new HttpError(message);
response = Request.CreateErrorResponse(HttpStatusCode.ExpectationFailed, err);
response.ReasonPhrase = message;
}
else
{
if(repository.Remove(customerID))
{
response = Request.CreateResponse<Customer>(HttpStatusCode.Created, customer);
response.ReasonPhrase = "Customer successfully deleted";
}
else
{
var message = string.Format("Due to some error customer not removed");
HttpError err = new HttpError(message);
response = Request.CreateErrorResponse(HttpStatusCode.ExpectationFailed, err);
response.ReasonPhrase = message;
}
}
return response;
}
}
and calling like this below way with http client but not working and giving error Not found
private void btnDelete_Click(object sender, EventArgs e)
{
var uri = new Uri(ConfigurationManager.AppSettings["baseAddress"] + "/api/customer/DeleteCustomer");
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("customerID", "CUS01")
});
try
{
using (var client = new HttpClient())
{
using (var response = client.PostAsync(uri, content).Result)
{
if (response.IsSuccessStatusCode)
{
MessageBox.Show(response.ReasonPhrase);
}
else
{
Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
var dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(response.Content.ReadAsStringAsync().Result);
MessageBox.Show(dict["Message"]);
}
}
}
}
catch (HttpRequestException ex)
{
// catch any exception here
}
}
some one please see my code and tell me where i made the mistake in calling code ? thanks
[RoutePrefix("api/customer")]
public class CustomerController : ApiController
{
[HttpPost, Route("DeleteCustomer")]
public HttpResponseMessage DeleteProduct([FromBody]string customerID)
{
HttpResponseMessage response = null;
Customer customer = repository.Get(customerID);
if (customer == null)
{
var message = string.Format("No customer found by the ID {0}", customerID);
HttpError err = new HttpError(message);
response = Request.CreateErrorResponse(HttpStatusCode.ExpectationFailed, err);
response.ReasonPhrase = message;
}
else
{
if(repository.Remove(customerID))
{
response = Request.CreateResponse<Customer>(HttpStatusCode.Created, customer);
response.ReasonPhrase = "Customer successfully deleted";
}
else
{
var message = string.Format("Due to some error customer not removed");
HttpError err = new HttpError(message);
response = Request.CreateErrorResponse(HttpStatusCode.ExpectationFailed, err);
response.ReasonPhrase = message;
}
}
return response;
}
}
Could you add [FromBody] keyword in method parameter ?

Creating a new entry in Azure mobile table

Good day
I am currently facing a weird problem with my insert command on my client side I think. I can create new entries in my other models(Tables) easily but in my person model I keep getting a bad request message each time I click create account.
Backend Model:
public class Person : EntityData
{
[StringLength(20)]
public string Name { get; set; }
[StringLength(20)]
public string Surname { get; set; }
[StringLength(150)]
public string Email { get; set; }
[StringLength(15)]
public string Mobile { get; set; }
[StringLength(15)]
public string Work { get; set; }
[StringLength(14)]
public string Password { get; set; }
[StringLength(80)]
public string Company { get; set; }
public virtual City City { get; set; }
}
Client Side Controller:
namespace azuremobile
{
public partial class PersonManager
{
static PersonManager defaultInstance = new PersonManager();
MobileServiceClient client;//Initialize Mobile SDK
IMobileServiceTable<Person> accountTable;
private PersonManager()
{
var handler = new AuthHandler();
//Create our client and pass in Authentication handler
this.client = new MobileServiceClient(
Constants.ApplicationURL, handler);
this.accountTable = client.GetTable<Person>();
}
public static PersonManager DefaultManager
{
get
{
return defaultInstance;
}
private set
{
defaultInstance = value;
}
}
public MobileServiceClient CurrentClient//Provides basic access to azure mobile services
{
get { return client; }
}
public bool IsOfflineEnabled
{
get { return accountTable is Microsoft.WindowsAzure.MobileServices.Sync.IMobileServiceSyncTable<Person>; }
}
public async Task<Person> GetTodoItemsAsync(Expression<Func<Person, bool>> linq)
//public async Task<List<Person>> GetTodoItemsAsync(bool syncItems = false)
{
try
{
// return new List<Person>(await accountTable.ReadAsync());
//List<Person> newUser = await accountTable.Where(linq).Take(1).ToListAsync();
IEnumerable<Person> items = await accountTable
.Where(c => c.Name != null)
.Take(1)
.ToListAsync();
//return newUser.First();
// return await accountTable;
// .Where(c => c.Name != null)
// .Take(1)
// .ToListAsync();
}
catch (MobileServiceInvalidOperationException msioe)
{
Debug.WriteLine(#"Invalid sync operation: {0}", msioe.Message);
}
catch (Exception e)
{
Debug.WriteLine(#"Sync error: {0}", e.Message);
}
return null;
}
public async Task SaveTaskAsync(Person item)
{
// if (item.Id != null)
// await accountTable.InsertAsync(item);
// else
await accountTable.UpdateAsync(item);
}
public async Task CreateTaskAsync(Person item)
{
try
{
await accountTable.InsertAsync(item);
}
catch (MobileServiceInvalidOperationException msioe)
{
Debug.WriteLine(#"INVALID {0}", msioe.Message);
}
catch (Exception e)
{
Debug.WriteLine(#"ERROR {0}", e.Message);
}
}
}
}
Client Side Signup Screen:
public partial class SignupScreen : ContentPage
{
PersonManager manager;
public SignupScreen()
{
InitializeComponent();
NavigationPage.SetHasNavigationBar(this, false);
manager = PersonManager.DefaultManager;
LoginClicked.Clicked += async (object sender, EventArgs e) =>
{
var main = new LoginScreen();
Application.Current.MainPage = main;
Navigation.RemovePage(this);
};
}
async Task CreatedNewUser(Person items)
{
try
{
await manager.CreateTaskAsync(items);
}
catch (MobileServiceInvalidOperationException e)
{
await DisplayAlert("Info", e.Message, "Ok");
}
}
public async void OnSignUp(object sender, EventArgs e)
{
string name = this.nameEntry.Text.Trim();
string surname = this.surnameEntry.Text.Trim();
string email = this.emailEntry.Text.Trim();
string company = this.companyEntry.Text.Trim();
string work = this.workEntry.Text.Trim();
string mobile = this.mobileEntry.Text.Trim();
string password = this.passwordEntry.Text.Trim();
if (string.IsNullOrEmpty(name))
{
await DisplayAlert("Info", "Please fill in your name.", "Ok");
this.nameEntry.PlaceholderColor = this.nameEntry.TextColor = Color.FromHex("#00FF00");
nameEntry.Focus();
signUpButton.IsEnabled = true;
return;
}
if (string.IsNullOrEmpty(surname))
{
await DisplayAlert("Info", "Please fill in your surname.", "Ok");
this.surnameEntry.PlaceholderColor = this.surnameEntry.TextColor = Color.FromHex("#00FF00");
surnameEntry.Focus();
signUpButton.IsEnabled = true;
return;
}
if (string.IsNullOrEmpty(email))
{
await DisplayAlert("Info", "Please fill in your email.", "Ok");
this.emailEntry.PlaceholderColor = this.emailEntry.TextColor = Color.FromHex("#00FF00");
emailEntry.Focus();
signUpButton.IsEnabled = true;
return;
}
if (string.IsNullOrEmpty(company))
{
await DisplayAlert("Info", "Please fill in your company name.", "Ok");
this.companyEntry.PlaceholderColor = this.companyEntry.TextColor = Color.FromHex("#00FF00");
companyEntry.Focus();
signUpButton.IsEnabled = true;
return;
}
if (string.IsNullOrEmpty(mobile))
{
await DisplayAlert("Info", "Please fill in your cellphone number.", "Ok");
this.mobileEntry.PlaceholderColor = this.mobileEntry.TextColor = Color.FromHex("#00FF00");
mobileEntry.Focus();
signUpButton.IsEnabled = true;
return;
}
if (string.IsNullOrEmpty(work))
{
await DisplayAlert("Info", "Please fill in your office number.", "Ok");
this.workEntry.PlaceholderColor = this.workEntry.TextColor = Color.FromHex("#00FF00");
workEntry.Focus();
signUpButton.IsEnabled = true;
return;
}
if (string.IsNullOrEmpty(password))
{
await DisplayAlert("Info", "Please fill in your password.", "Ok");
this.passwordEntry.PlaceholderColor = this.passwordEntry.TextColor = Color.FromHex("#00FF00");
passwordEntry.Focus();
signUpButton.IsEnabled = true;
return;
}
try
{
activityIndicator.IsRunning = true;
validationLabel.IsVisible = true;
signUpButton.IsEnabled = false;
if (!string.IsNullOrEmpty(email) && !string.IsNullOrEmpty(password))
{
var OnAdd = new Person
{
Name = name,
Surname = surname,
Email = email,
Mobile = mobile,
Work = work,
Company = company,
Password = password
};
await CreatedNewUser(OnAdd);
await Navigation.PushAsync(new LoginScreen());
}
else
{
await DisplayAlert("Warning", "Could not create user account.", "Ok");
}
}
catch (Exception)
{
await DisplayAlert("Warning", "Could not create user account, problem with internet connection or server.", "Ok");
activityIndicator.IsRunning = false;
validationLabel.IsVisible = false;
signUpButton.IsEnabled = true;
}
}
}
}

Executeasync in the same method

i'm trying to call a restclient in the method including the parsing of data, her's my code which i want to make all of it in the method,any ideas please :
public void Convert(object value, Type targetType, object parameter, CultureInfo culture){RestClient client = new RestClient();
client.BaseUrl = "http://";
RestRequest request = new RestRequest();
request.Method = Method.GET;
request.AddParameter("action", "REE");
request.AddParameter("atm_longitude", location.Longitude);
client.ExecuteAsync(request, ParseFeedCallBack_ListDistance);}
public void ParseFeedCallBack_ListDistance(IRestResponse response){
if (response.StatusCode == HttpStatusCode.OK)
{
ParseXMLFeedDistance(response.Content);
}
private string ParseXMLFeedDistance(string feed)
{
.... return myvalueToBind;
}
i did somthing like this,but it don't call ParseXMLFeedDistance for every item :
foreach (var resp in xmlItems2.Descendants("result"))
{
RestClient client = new RestClient();
client.BaseUrl = "http://";
RestRequest request = new RestRequest();
request.Method = Method.GET;
request.AddParameter("action", "atms_distances");
request.AddParameter("lang", "ar");
request.AddParameter("mode", "xml");
request.AddParameter("appli", "WP");
request.AddParameter("mobile_latitude", "35.843283");
request.AddParameter("mobile_longitude", "10.61617");
request.AddParameter("atm_latitude", resp.Element("Lattitude"));
request.AddParameter("atm_longitude",resp.Element("longitude"));
// client.ExecuteAsync(request, ParseFeedCallBack_ListDistance);
client.ExecuteAsync(request, response =>
{
ParseXMLFeedDistance(response.Content);
});
}
private void ParseXMLFeedDistance(string feed)
{
if (feed == null)
return;
try
{
XElement xmlItems = XElement.Parse(feed);
XDocument xmlItems2 = XDocument.Parse(feed);
var list = new List<State>();
foreach (XElement val in xmlItems2.Descendants("result").Last().Elements())
{
// distance = val.Value;
list.Add(new State
{
TotalDistance = val.Value,
});
}
ResultSearch_ListDistance.ItemsSource = list;
}
catch
{
}
}

Resources