deleting data from webservice not showing anything? XAMARIN - c#

I have been trying to delete a data using "DeleteAsync" and it doesn't show anything neither an error, when i hit delete buttom nothing happens.
although things seems fine to me, but you guys help where i missed?
this is the code
private async void Delete(object sender, EventArgs e)
{
private const string weburl = "http://localhost:59850/api/Donate_Table";
var uri = new Uri(string.Format(weburl, txtID.Text));
HttpClient client = new HttpClient();
var result = await client.DeleteAsync(uri);
if (result.IsSuccessStatusCode)
{
await DisplayAlert("Successfully", "your data have been Deleted", "OK");
}
}

Your web API url appears to be wrong as the weburl is set using
private const string weburl = "http://localhost:59850/api/Donate_Table";
var uri = new Uri(string.Format(weburl, txtID.Text));
Note the missing placeholder in the weburl yet it is being used in a string.Format(weburl, txtID.Text
From that it would appear that the weburl was probably meant to be
private const string weburl = "http://localhost:59850/api/Donate_Table/{0}";
so that the id of the resource to be deleted will be part of the URL being called.
Also it is usually suggested that one avoid repeatedly creating instances of HttpClient
private static HttpClient client = new HttpClient();
private const string webUrlTempplate = "http://localhost:59850/api/Donate_Table/{0}";
private async void Delete(object sender, EventArgs e) {
var uri = new Uri(string.Format(webUrlTempplate, txtID.Text));
var result = await client.DeleteAsync(uri);
if (result.IsSuccessStatusCode) {
await DisplayAlert("Successfully", "your data have been Deleted", "OK");
} else {
//should have some action for failed requests.
}
}

Related

ASP.NET Post request called on page load with Webclient not working

I'm integrating OAuth into a ASP.NET Webforms application, and I'm trying to make a post request using WebClient synchronously to get an access_token. It doesn't give an errors, but the Response.Redirect at the bottom isn't firing, and there doesn't seem to be any record of the post request or response. I'm calling the method in page load as the Authorisation Code is returned to to this page as query string. Am I doing something silly? Any help would be appreciated!
protected void Page_Load(object sender, EventArgs e)
{
String authorisationcode = Request.QueryString["code"];
if (authorisationcode != null)
{
MicrosoftAuthorisation(authorisationcode);
}
}
protected void MicrosoftAuthorisation(String AuthCode)
{
String MicrosoftClientId = HttpContext.Current.Application["MicrosoftClientId"].ToString();
String MicrosoftRedirectUri = HttpContext.Current.Application["MicrosoftRedirectUri"].ToString();
using (var client = new WebClient())
{
var values = new NameValueCollection();
values["client_id"] = MicrosoftClientId;
values["scope"] = "openid";
values["code"] = AuthCode;
values["redirect_uri"] = MicrosoftRedirectUri;
values["grant_type"] = "authorization_code";
var response = client.UploadValues("https://login.microsoftonline.com/consumers/oauth2/v2.0/token", values);
var responseString = Encoding.Default.GetString(response);
Response.Redirect("loginauthorisation.aspx");
}
}

Passing data from web api on the main page to the details page in xamarin forms

Here is how my code looks like for the page that has data:
private async Task GetLeaveBalance() {
try
{
Uri = "http://192.168.42.35/API/api/leave/getbalance/"+ empId + "/"+ companyId;
client = new HttpClient();
var authHeaderValue = basic;
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authHeaderValue);
HttpResponseMessage response = await client.GetAsync(Uri);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
{
var emp = JsonConvert.DeserializeObject<List<Leave>>(responseBody);
dataGrid.ItemsSource = emp;
UserDialogs.Instance.HideLoading();
}
}
catch (HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ", e.Message);
UserDialogs.Instance.ShowError(e.Message);
}
}
private void Button_Clicked(object sender, EventArgs e)
{
Navigation.PushAsync(new Details());
}
My Second page(Details Page) has a picker which needs to be populated by data that I get from the emp variable so how can I pass data from the first page to the second page(Details Page)?
Considering your approach and code you can directly pass data to the constructor of your second page
List<Leave> leaves = new List<Leave>();
private async Task GetLeaveBalance() {
...
leaves = JsonConvert.DeserializeObject<List<Leave>>(responseBody);
...
}
private void Button_Clicked(object sender, EventArgs e)
{
Navigation.PushAsync(new Details(leaves));
}
You can pass through MessagingCenter aswell, here is some steps.
First in your SecondPage you register an messagingcenter task.
MessagingCenter.Subscribe<SecondPage(you can create a empty interface if you want to use as type),string>(this, "PopulateSecondPage", (sender,DataFromMainPage) =>
{
//your code to handle DataFromMainPage
});
then pass the data using
var page = new SecondPage();
Navigation.PushAsync(page);
MessagingCenter.Send<MainPage>(page, "PopulateSecondPage","Data you want to pass");

TLSharp Telegram API. Check phone registrered

I've got a problem with TLSharp method IsPhoneRegisteredAsync(...).
It always returns true, no matter the number I'm trying to check. Even for an input like "asdhbqaihbqwieuashdq23934327940scj0" it returns true.
Thanks for your help.
My code:
private void button1_Click(object sender, EventArgs e)
{
connectClient(SETS.API_ID, SETS.API_HASH);
}
private async void connectClient(int api_id, string api_hash)
{
client = new TelegramClient(api_id, api_hash);
api_ID_tb.Text = api_id.ToString();
api_hash_tb.Text = api_hash;
await client.ConnectAsync();
if (client.IsConnected)
{
MessageBox.Show("Connect Succefull");
}
}
async void CheckNumber(string number)
{
bool q = await client.IsPhoneRegisteredAsync(number);
MessageBox.Show(q.ToString());
}
private void numberCheckBtn_Click(object sender, EventArgs e)
{
CheckNumber(number_tb.Text);
}
Got same problem.
That`s how i solved it:
var req = new Auth.TLRequestSendCode
{
PhoneNumber = myPhone,
ApiId = ApiID,
ApiHash = ApiHash
};
var resp = await client.SendRequestAsync<Auth.TLSentCode>(req);
var phoneCodeHash = resp.PhoneCodeHash;
var isRegistered = resp.PhoneRegistered;
This is the same code as SendCodeRequestAsync (witch return only hash) but now we have access to Auth.TLSentCode.PhoneRegistered

WebClient.DownloadStringAsync URL not working

I've got an issue about webclient on windowsphone 8.
I've hit an API use webclient on my code.
public void LoadData(bool refresh)
{
IsLoading = true;
WebClient webclient = new WebClient();
webclient.DownloadStringCompleted += webclient_DownloadStringCompleted;
webclient.DownloadStringAsync(new Uri("http://api.xxxx.com/getQuestion"));
}
public void webclient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
RootObject deserCustomers = JsonConvert.DeserializeObject<RootObject>(e.Result);
foreach (var cust in deserCustomers.data)
{
Debug.WriteLine(cust.title);
int length = cust.question.Length;
string subquestion;
if (length > 100) { subquestion = cust.question.Substring(0, 100); }
else { subquestion = cust.question; }
_questiondata.Add(new QuestionItem() { Title = cust.title, Question_Str = subquestion, Slug = cust.slug });
}
IsLoading = false;
}
It's work for the first time and the data is exactly same as web. But when the web update with new question, and I try to call method LoadData for the second time, the data not same as web. the new update question on web does not appear in my apps (windows phone).
What should I do, Is there any cache that make my result not updated like on web?
Thanks a lot.
I've got a help and it Solved. try this:
public void LoadData(bool refresh)
{
IsLoading = true;
WebClient webclient = new WebClient();
webclient.DownloadStringCompleted += webclient_DownloadStringCompleted;
Random random = new Random();
webclient.DownloadStringAsync(new Uri("http://api.xxxx.com/getQuestion?random="+ random.Next().ToString()));
}

WP8 - Facebook Login Issue

I am trying to authenticate a user on Facebook using the Facebook C# SDK on Windows Phone 8. To do so I am following the code here: FacebookLoginPage.xaml.cs
But the problem I am facing is that, whenever I input my username and password into the dialog that opens to authenticate the user, I just get the following page:
After this, my program does not redirect to the Landing page which is a separate view. The other solutions I have seen that suggest hiding the WebView are not applicable since the authentication is abstracted into a single LoginAsync function call.
Any suggestions on what to do?
It would seem that FB has made some changes to its redirection script, when it detects a Windows Phone webbrowser control.
What the C# SDK does, is generate the login page as "http://www.facebook.com....". When you open this URL on the webbrowser control, it gets redirected to "http://m.facebook.com..." which displays the mobile version of the FB login page.
This previously has no issue, but recently, when FB does the redirection, it also strips the parameter "display=page" from the URL. What happens then is that when a successful FB login is made, the "login_success.html" page is opened without this parameter. Without the "display=page" parameter passed in, it defaults to "display=touch". This URL unfortunately, does not append the token string in the URL, hence the page shown in the very first thread is displayed.
The solution to this is, instead of using the below code to generate the login URL, ammend it to
original:
Browser.Navigate(_fb.GetLoginUrl(parameters));
ammended:
var URI = _fb.GetLoginUrl(parameters).toString().replace("www.facebook.com","m.facebook.com");
Browser.Navigate(new Uri(URI));
In my project I just listened for the WebView's navigated event. If it happens, it means that user did something on the login page (i.e. pressed login button).
Then I parsed the uri of the page you mentioned which should contain OAuth callback url, if it is correct and the result is success I redirect manually to the correct page:
//somewhere in the app
private readonly FacebookClient _fb = new FacebookClient();
private void webBrowser1_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
FacebookOAuthResult oauthResult;
if (!_fb.TryParseOAuthCallbackUrl(e.Uri, out oauthResult))
{
return;
}
if (oauthResult.IsSuccess)
{
var accessToken = oauthResult.AccessToken;
//you have an access token, you can proceed further
FBLoginSucceded(accessToken);
}
else
{
// errors when logging in
MessageBox.Show(oauthResult.ErrorDescription);
}
}
If you abstract logging in an async function, you expect it to behave asynchronously, so events are ok.
Sorry for my English.
The code for the full page:
public partial class LoginPageFacebook : PhoneApplicationPage
{
private readonly string AppId = Constants.FacebookAppId;
private const string ExtendedPermissions = "user_birthday,email,user_photos";
private readonly FacebookClient _fb = new FacebookClient();
private Dictionary<string, object> facebookData = new Dictionary<string, object>();
UserIdentity userIdentity = App.Current.Resources["userIdentity"] as UserIdentity;
public LoginPageFacebook()
{
InitializeComponent();
}
private void webBrowser1_Loaded(object sender, RoutedEventArgs e)
{
var loginUrl = GetFacebookLoginUrl(AppId, ExtendedPermissions);
webBrowser1.Navigate(loginUrl);
}
private Uri GetFacebookLoginUrl(string appId, string extendedPermissions)
{
var parameters = new Dictionary<string, object>();
parameters["client_id"] = appId;
parameters["redirect_uri"] = "https://www.facebook.com/connect/login_success.html";
parameters["response_type"] = "token";
parameters["display"] = "touch";
// add the 'scope' only if we have extendedPermissions.
if (!string.IsNullOrEmpty(extendedPermissions))
{
// A comma-delimited list of permissions
parameters["scope"] = extendedPermissions;
}
return _fb.GetLoginUrl(parameters);
}
private void webBrowser1_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
if (waitPanel.Visibility == Visibility.Visible)
{
waitPanel.Visibility = Visibility.Collapsed;
webBrowser1.Visibility = Visibility.Visible;
}
FacebookOAuthResult oauthResult;
if (!_fb.TryParseOAuthCallbackUrl(e.Uri, out oauthResult))
{
return;
}
if (oauthResult.IsSuccess)
{
var accessToken = oauthResult.AccessToken;
FBLoginSucceded(accessToken);
}
else
{
// user cancelled
MessageBox.Show(oauthResult.ErrorDescription);
}
}
private void FBLoginSucceded(string accessToken)
{
var fb = new FacebookClient(accessToken);
fb.GetCompleted += (o, e) =>
{
if (e.Error != null)
{
Dispatcher.BeginInvoke(() => MessageBox.Show(e.Error.Message));
return;
}
var result = (IDictionary<string, object>)e.GetResultData();
var id = (string)result["id"];
userIdentity.FBAccessToken = accessToken;
userIdentity.FBID = id;
facebookData["Name"] = result["first_name"];
facebookData["Surname"] = result["last_name"];
facebookData["Email"] = result["email"];
facebookData["Birthday"] = DateTime.Parse((string)result["birthday"]);
facebookData["Country"] = result["locale"];
Dispatcher.BeginInvoke(() =>
{
BitmapImage profilePicture = new BitmapImage(new Uri(string.Format("https://graph.facebook.com/{0}/picture?type={1}&access_token={2}", id, "square", accessToken)));
facebookData["ProfilePicture"] = profilePicture;
userIdentity.FBData = facebookData;
userIdentity.ProfilePicture = profilePicture;
ARLoginOrRegister();
});
};
fb.GetAsync("me");
}
private void ARLoginOrRegister()
{
WebService.ARServiceClient client = new WebService.ARServiceClient();
client.GetUserCompleted += client_GetUserCompleted;
client.GetUserAsync((string)facebookData["Email"]);
client.CloseAsync();
}
void client_GetUserCompleted(object sender, WebService.GetUserCompletedEventArgs e)
{
if (e.Result == null)
NavigationService.Navigate(new Uri("/RegisterPageFacebook.xaml", UriKind.RelativeOrAbsolute));
else if (e.Result.AccountType != (int)AccountType.Facebook)
{
MessageBox.Show("This account is not registered with facebook!");
NavigationService.Navigate(new Uri("/LoginPage.xaml", UriKind.RelativeOrAbsolute));
}
else
{
userIdentity.Authenticated += userIdentity_Authenticated;
userIdentity.FetchARSocialData((string)facebookData["Email"]);
}
}
void userIdentity_Authenticated(bool success)
{
NavigationService.Navigate(new Uri("/MenuPage.xaml", UriKind.RelativeOrAbsolute));
}
}
Before trying to do all the proposed changes,
please check that your Facebook App is not on Sandbox mode. This will eventually resolve your issue.
If your facebook app is in sandbox mode, only the developer can login, using his email address. Any other fb user will get the white page.

Categories