Advertisement
Guest User

Untitled

a guest
Aug 12th, 2016
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.76 KB | None | 0 0
  1. using System;
  2.  
  3. using Android.App;
  4. using Android.Content.PM;
  5. using Android.Runtime;
  6. using Android.Views;
  7. using Android.Widget;
  8. using Android.OS;
  9. using Android.Content;
  10. using System.Json;
  11. using System.Net;
  12. using System.IO;
  13. using System.Threading.Tasks;
  14.  
  15. using static Android.Support.V7.Widget.Toolbar;
  16. using Android.Support.V7.App;
  17. using Android.Support.V4.Widget;
  18. using Java.Util;
  19.  
  20. namespace Upgrid.Droid
  21. {
  22. [Activity(Label = "", Icon = "@drawable/upgrid", Theme = "@style/MainTheme", MainLauncher = false, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
  23. public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
  24. {
  25. private string pt = "Utilizador desconhecido";
  26. private string en = "Unknown user";
  27. private string loggedUserID;
  28. private string retrievedCred;
  29. private string[] credentials = new string[2];
  30. private SharedPreferences sp = new SharedPreferences();
  31.  
  32. protected override void OnCreate(Bundle bundle)
  33. {
  34. base.OnCreate(bundle);
  35.  
  36. //elimina o utilizador
  37. //removeUserLogin("Username", "Password");
  38.  
  39. //recebe as credenciais do utilizador
  40. retrievedCred = sp.retrieveCredencials();
  41.  
  42. //verifica se o utilizador já tem o login feito ou não
  43. checkLogin(retrievedCred);
  44.  
  45. global::Xamarin.Forms.Forms.Init(this, bundle);
  46. LoadApplication(new App());
  47. }
  48.  
  49.  
  50. //verifica se o utilizador já tem o login feito ou não
  51. private async void checkLogin(string retrievedCred)
  52. {
  53. //se o campo das credenciais tiver dados de um utilizador, faz login com esse utilizador
  54. if (!retrievedCred.Equals("-"))
  55. {
  56. string loggedUsername = "";
  57. string loggedPassword = "";
  58.  
  59. string[] words = retrievedCred.Split('-');
  60.  
  61. for (int i = 0; i < words.Length; i++)
  62. {
  63. credentials[i] = words[i];
  64. }
  65.  
  66. //username + password
  67. int j = 0;
  68. loggedUsername = credentials[j];
  69. loggedPassword = credentials[j + 1];
  70.  
  71. string url = "http://intra.withus.pt:8080/upgrid/api/v1/fakelogin/" + loggedUsername + "/" + loggedPassword;
  72.  
  73. //Ler valores do utilizador
  74. JsonValue json = await FetchUrlAsync(url);
  75.  
  76. //Passa diretamente para a páginal inicial da aplicação com os dados do utilizador
  77. var dashboard = new Intent(this, typeof(Dashboard));
  78. dashboard.PutExtra("loggedUserID", loggedUserID); //passa o id do utilizador para acesso a dados
  79. StartActivity(dashboard);
  80. }
  81. else
  82. {
  83. //se o campo das credenciais estiver sem dados, pede login ao utilizador
  84.  
  85. TabLayoutResource = Resource.Layout.Tabbar;
  86. ToolbarResource = Resource.Layout.toolbar;
  87.  
  88. SetContentView(Resource.Layout.login_layout);
  89.  
  90. var userName = FindViewById<EditText>(Resource.Id.usertext);
  91. var password = FindViewById<EditText>(Resource.Id.passwordtext);
  92. var loginButton = FindViewById<Button>(Resource.Id.loginButton);
  93.  
  94. //Botão para login
  95. loginButton.Click += async delegate {
  96. userName.TextChanged += (object sender, Android.Text.TextChangedEventArgs e) =>
  97. {
  98. userName.Text = e.Text.ToString();
  99. };
  100.  
  101. password.TextChanged += (object sender, Android.Text.TextChangedEventArgs e) =>
  102. {
  103. password.Text = e.Text.ToString();
  104. };
  105.  
  106. //Pedido ao servidor
  107. string url = "http://intra.withus.pt:8080/upgrid/api/v1/fakelogin/" + userName.Text + "/" + password.Text;
  108.  
  109. //Ler valores do utilizador
  110. JsonValue json = await FetchUrlAsync(url);
  111.  
  112. //Verificar se o utilizador existe
  113. checkUser(loggedUserID, userName, password);
  114.  
  115. };
  116. }
  117. }
  118.  
  119. //verifica se o utilizador existe (no caso de não haver credenciais guardadas)
  120. private void checkUser(string loggedUserID, EditText userName, EditText password)
  121. {
  122. //Utilizador desconhecido
  123. if (loggedUserID.Equals("-1"))
  124. {
  125. string language = Locale.Default.Language;
  126. if (language.Equals("pt"))
  127. {
  128. Toast.MakeText(this, pt, ToastLength.Long).Show();
  129. }
  130. else if (language.Equals("en"))
  131. {
  132. Toast.MakeText(this, en, ToastLength.Long).Show();
  133. }
  134. }
  135. else
  136. {
  137. sp.saveCredentials(userName.Text, password.Text); //guardar credenciais de acesso à app
  138. var dashboard = new Intent(this, typeof(Dashboard));
  139. dashboard.PutExtra("loggedUserID", loggedUserID); //passa o id do utilizador para acesso a dados
  140. StartActivity(dashboard);
  141. }
  142. }
  143.  
  144. // Gets data from the passed URL.
  145. private async Task<JsonValue> FetchUrlAsync(string url)
  146. {
  147. // Create an HTTP web request using the URL:
  148. HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(url));
  149. request.ContentType = "application/json";
  150. request.Method = "GET";
  151.  
  152. // Send the request to the server and wait for the response:
  153. using (WebResponse response = await request.GetResponseAsync())
  154. {
  155. // Get a stream representation of the HTTP web response:
  156. using (Stream stream = response.GetResponseStream())
  157. {
  158. // Use this stream to build a JSON document object:
  159. JsonValue jsonDoc = await Task.Run(() => JsonObject.Load(stream));
  160. //Console.Out.WriteLine("Response: {0}", jsonDoc.ToString());
  161.  
  162. //Get user ID (-1 if not exists)
  163. loggedUserID = jsonDoc.ToString();
  164.  
  165. // Return the JSON document:
  166. //Console.Out.WriteLine(" - " + jsonDoc.ToString());
  167. return jsonDoc;
  168. }
  169. }
  170. }
  171.  
  172. public override void OnBackPressed()
  173. {
  174. base.OnBackPressed();
  175. }
  176. }
  177. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement