· 6 years ago · Nov 29, 2019, 08:28 PM
1/// contact.cs - models mvc ///
2namespace contacto.Models
3{
4 using System.ComponentModel.DataAnnotations;
5
6 public enum TypeContact
7 {
8 telephone,
9 email,
10 facebook
11 }
12
13 public class Contact
14 {
15 [Key]
16 public int ContactID { get; set; }
17 [Required]
18 public string Name { get; set; }
19 [Required]
20 public TypeContact Type { get; set; }
21 [Required]
22 [Display(Description ="Contact")]
23 public string ContactValue { get; set; }
24 }
25}
26/// DataContext.cs ///
27namespace contacto.Models
28{
29 using System.Data.Entity;
30
31 public class DataContext:DbContext
32 {
33 public DataContext():base("DefaultConnection")
34 {
35
36 }
37
38 public System.Data.Entity.DbSet<contacto.Models.Contact> Contacts { get; set; }
39 }
40}
41
42
43/// Web Config ///
44
45<?xml version="1.0" encoding="utf-8"?>
46<!--
47 Para obtener más información sobre cómo configurar la aplicación ASP.NET, visite
48 https://go.microsoft.com/fwlink/?LinkId=301880
49 -->
50<configuration>
51 <configSections>
52 <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
53 <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
54 </configSections>
55 <appSettings>
56 <add key="webpages:Version" value="3.0.0.0" />
57 <add key="webpages:Enabled" value="false" />
58 <add key="ClientValidationEnabled" value="true" />
59 <add key="UnobtrusiveJavaScriptEnabled" value="true" />
60 </appSettings>
61 <connectionStrings>
62 <add name="DefaultConnection" connectionString="Server=tcp:srvsabado.database.windows.net,1433;Initial Catalog=BDsabado;Persist Security Info=False;User ID=sufrimiento;Password=Passw0rd;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;" providerName="System.Data.SqlClient" />
63 </connectionStrings>
64 <system.web>
65 <compilation debug="true" targetFramework="4.6.1" />
66 <httpRuntime targetFramework="4.6.1" />
67 </system.web>
68 <runtime>
69 <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
70 <dependentAssembly>
71 <assemblyIdentity name="Antlr3.Runtime" publicKeyToken="eb42632606e9261f" />
72 <bindingRedirect oldVersion="0.0.0.0-3.5.0.2" newVersion="3.5.0.2" />
73 </dependentAssembly>
74 <dependentAssembly>
75 <assemblyIdentity name="System.Diagnostics.DiagnosticSource" publicKeyToken="cc7b13ffcd2ddd51" />
76 <bindingRedirect oldVersion="0.0.0.0-4.0.2.1" newVersion="4.0.2.1" />
77 </dependentAssembly>
78 <dependentAssembly>
79 <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" />
80 <bindingRedirect oldVersion="0.0.0.0-11.0.0.0" newVersion="11.0.0.0" />
81 </dependentAssembly>
82 <dependentAssembly>
83 <assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
84 <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
85 </dependentAssembly>
86 <dependentAssembly>
87 <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
88 <bindingRedirect oldVersion="0.0.0.0-1.6.5135.21930" newVersion="1.6.5135.21930" />
89 </dependentAssembly>
90 <dependentAssembly>
91 <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
92 <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
93 </dependentAssembly>
94 <dependentAssembly>
95 <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
96 <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
97 </dependentAssembly>
98 <dependentAssembly>
99 <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
100 <bindingRedirect oldVersion="1.0.0.0-5.2.4.0" newVersion="5.2.4.0" />
101 </dependentAssembly>
102 </assemblyBinding>
103 </runtime>
104 <system.webServer>
105 <modules>
106 <remove name="TelemetryCorrelationHttpModule" />
107 <add name="TelemetryCorrelationHttpModule" type="Microsoft.AspNet.TelemetryCorrelation.TelemetryCorrelationHttpModule, Microsoft.AspNet.TelemetryCorrelation" preCondition="integratedMode,managedHandler" />
108 </modules>
109 </system.webServer>
110 <entityFramework>
111 <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
112 <providers>
113 <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
114 </providers>
115 </entityFramework>
116 <system.codedom>
117 <compilers>
118 <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701" />
119 <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
120 </compilers>
121 </system.codedom>
122</configuration>
123
124/// ContactViewModel - appContacto ///
125namespace appContacto.ViewModels
126{
127 using Models;
128 using Services;
129 using System;
130 using System.Collections.Generic;
131 using System.Collections.ObjectModel;
132 using Xamarin.Forms;
133
134 public class ContactViewModel:BaseViewModel
135 {
136 #region Attributes
137 private ApiService apiService;
138 private ObservableCollection<Contact> contacts;
139 #endregion
140
141 #region Properties
142 public ObservableCollection<Contact> Contacts
143 {
144 get { return this.contacts; }
145 set { SetValue(ref this.contacts, value); }
146 }
147 #endregion
148
149 #region Constructor
150 public ContactViewModel()
151 {
152 this.apiService = new ApiService();
153 this.LoadContacts();
154
155 }
156 #endregion
157
158 #region Methods
159 private async void LoadContacts()
160 {
161 var connection = await this.apiService.CheckConnection();
162 if (!connection.IsSuccess)
163 {
164 await Application.Current.MainPage.DisplayAlert(
165 "Connection Error",
166 connection.Message,
167 "Accept"
168 );
169 return;
170 }
171
172 var response = await this.apiService.GetList<Contact>(
173 "https://apicontactsi220.azurewebsites.net/",
174 "api/",
175 "Contacts");
176 if (!response.IsSuccess)
177 {
178 await Application.Current.MainPage.DisplayAlert(
179 "GET Contact Error",
180 response.Message,
181 "Accept"
182 );
183 return;
184 }
185
186 MainViewModel mainViewModel = MainViewModel.GetInstance();
187 mainViewModel.ContactList = (List<Contact>)response.Result;
188
189 this.Contacts = new ObservableCollection<Contact>(this.ToContactView());
190
191
192 }
193
194 private IEnumerable<Contact> ToContactView()
195 {
196 ObservableCollection<Contact> collection = new ObservableCollection<Contact>();
197 MainViewModel main = MainViewModel.GetInstance();
198 foreach (var lista in main.ContactList)
199 {
200 Contact contacto = new Contact();
201 contacto.ContactID = lista.ContactID;
202 contacto.Name = lista.Name;
203 contacto.Type = lista.Type;
204 contacto.ContactValue=lista.ContactValue;
205 collection.Add(contacto);
206 }
207 return collection;
208 }
209 #endregion
210
211
212 }
213}
214/// BaseViewModel ///
215namespace appContacto.ViewModels
216{
217
218 using System.Collections.Generic;
219 using System.ComponentModel;
220 using System.Runtime.CompilerServices;
221
222 public class BaseViewModel : INotifyPropertyChanged
223 {
224 public event PropertyChangedEventHandler PropertyChanged;
225 protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
226 {
227 PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
228 }
229
230 protected void SetValue<T>(ref T backingField,
231 T value,
232 [CallerMemberName] string propertyName = null)
233 {
234 if (EqualityComparer<T>.Default.Equals(backingField, value))
235 {
236 return;
237 }
238 backingField = value;
239 OnPropertyChanged(propertyName);
240 }
241 }
242
243}
244/// MainViewModel ///
245namespace appContacto.ViewModels
246{
247 using appContacto.Models;
248 using System.Collections.Generic;
249
250 public class MainViewModel
251 {
252 #region Properties
253 public List<Contact> ContactList { get; set; }
254 #endregion
255
256 #region ViewModel
257 public ContactViewModel contactViewModel { get; set; }
258 #endregion
259
260 #region Constructor
261 public MainViewModel()
262 {
263 instance = this;
264 this.contactViewModel = new ContactViewModel();
265 }
266 #endregion
267
268 #region singleton
269 private static MainViewModel instance;
270
271 public static MainViewModel GetInstance()
272 {
273 if (instance==null)
274 {
275 instance = new MainViewModel();
276 }
277 return (instance);
278 }
279 #endregion
280
281
282
283 }
284}
285
286/// ApiService ///
287namespace appContacto.Services
288{
289
290 using System;
291 using System.Collections.Generic;
292 using System.Net.Http;
293 using System.Net.Http.Headers;
294 using System.Text;
295 using System.Threading.Tasks;
296 using Newtonsoft.Json;
297 using Plugin.Connectivity;
298 using Models;
299
300 public class ApiService
301 {
302 public async Task<Response> CheckConnection()
303 {
304 if (!CrossConnectivity.Current.IsConnected)
305 {
306 return new Response
307 {
308 IsSuccess = false,
309 Message = "Please turn on your internet settings.",
310 };
311 }
312
313
314 bool isReachable = VerifyConnectionURL("https://apicontactsi220.azurewebsites.net/");
315 if (!isReachable)
316 {
317 return new Response
318 {
319 IsSuccess = false,
320 Message = "Check you internet connection.",
321 };
322 }
323
324 return new Response
325 {
326 IsSuccess = true,
327 Message = "Ok",
328 };
329 }
330
331
332 public bool VerifyConnectionURL(string mURL)
333 {
334 try
335 {
336 System.Net.WebRequest Peticion = System.Net.WebRequest.Create(mURL);
337 System.Net.WebResponse Respuesta = Peticion.GetResponse();
338 return true;
339 }
340 catch (System.Net.WebException ex)
341 {
342 if (ex.Status == System.Net.WebExceptionStatus.NameResolutionFailure)
343 {
344 return false;
345 }
346 return false;
347 }
348 }
349
350 public async Task<TokenResponse> GetToken(
351 string urlBase,
352 string username,
353 string password)
354 {
355 try
356 {
357 var client = new HttpClient();
358 client.BaseAddress = new Uri(urlBase);
359 StringContent head = new StringContent(string.Format(
360 "grant_type=password&username={0}&password={1}",
361 username, password),
362 Encoding.UTF8, "application/x-www-form-urlencoded");
363 HttpResponseMessage response = await client.PostAsync("Token", head);
364 var resultJSON = await response.Content.ReadAsStringAsync();
365 var result = JsonConvert.DeserializeObject<TokenResponse>(
366 resultJSON);
367 return result;
368 }
369 catch
370 {
371 return null;
372 }
373 }
374
375 public async Task<Response> Get<T>(
376 string urlBase,
377 string servicePrefix,
378 string controller,
379 string tokenType,
380 string accessToken,
381 string parameter,
382 string query)
383 {
384 try
385 {
386 var client = new HttpClient();
387 client.DefaultRequestHeaders.Authorization =
388 new AuthenticationHeaderValue(tokenType, accessToken);
389 client.BaseAddress = new Uri(urlBase);
390 var url = string.Format(
391 "{0}{1}?{2}={3}",
392 servicePrefix,
393 controller,
394 parameter,
395 query);
396 HttpResponseMessage response = await client.GetAsync(url);
397
398 if (!response.IsSuccessStatusCode)
399 {
400 return new Response
401 {
402 IsSuccess = false,
403 Message = response.StatusCode.ToString(),
404 };
405 }
406
407 var result = await response.Content.ReadAsStringAsync();
408 var model = JsonConvert.DeserializeObject<T>(result);
409 return new Response
410 {
411 IsSuccess = true,
412 Message = "Ok",
413 Result = model,
414 };
415 }
416 catch (Exception ex)
417 {
418 return new Response
419 {
420 IsSuccess = false,
421 Message = ex.Message,
422 };
423 }
424 }
425
426 public async Task<Response> Get<T>(
427 string urlBase,
428 string servicePrefix,
429 string controller,
430 string tokenType,
431 string accessToken,
432 int id)
433 {
434 try
435 {
436 var client = new HttpClient();
437 client.DefaultRequestHeaders.Authorization =
438 new AuthenticationHeaderValue(tokenType, accessToken);
439 client.BaseAddress = new Uri(urlBase);
440 var url = string.Format(
441 "{0}{1}/{2}",
442 servicePrefix,
443 controller,
444 id);
445 var response = await client.GetAsync(url);
446
447 if (!response.IsSuccessStatusCode)
448 {
449 return new Response
450 {
451 IsSuccess = false,
452 Message = response.StatusCode.ToString(),
453 };
454 }
455
456 var result = await response.Content.ReadAsStringAsync();
457 var model = JsonConvert.DeserializeObject<T>(result);
458 return new Response
459 {
460 IsSuccess = true,
461 Message = "Ok",
462 Result = model,
463 };
464 }
465 catch (Exception ex)
466 {
467 return new Response
468 {
469 IsSuccess = false,
470 Message = ex.Message,
471 };
472 }
473 }
474
475 public async Task<Response> GetList<T>(
476 string urlBase,
477 string servicePrefix,
478 string controller)
479 {
480 try
481 {
482 var client = new HttpClient();
483 client.BaseAddress = new Uri(urlBase);
484 var url = string.Format("{0}{1}", servicePrefix, controller);
485 var response = await client.GetAsync(url);
486 var result = await response.Content.ReadAsStringAsync();
487
488 if (!response.IsSuccessStatusCode)
489 {
490 return new Response
491 {
492 IsSuccess = false,
493 Message = result,
494 };
495 }
496
497 var list = JsonConvert.DeserializeObject<List<T>>(result);
498 return new Response
499 {
500 IsSuccess = true,
501 Message = "Ok",
502 Result = list,
503 };
504 }
505 catch (Exception ex)
506 {
507 return new Response
508 {
509 IsSuccess = false,
510 Message = ex.Message,
511 };
512 }
513 }
514
515 public async Task<Response> GetList<T>(
516 string urlBase,
517 string servicePrefix,
518 string controller,
519 string tokenType,
520 string accessToken)
521 {
522 try
523 {
524 var client = new HttpClient();
525 client.DefaultRequestHeaders.Authorization =
526 new AuthenticationHeaderValue(tokenType, accessToken);
527 client.BaseAddress = new Uri(urlBase);
528 var url = string.Format("{0}{1}", servicePrefix, controller);
529 var response = await client.GetAsync(url);
530 var result = await response.Content.ReadAsStringAsync();
531
532 if (!response.IsSuccessStatusCode)
533 {
534 return new Response
535 {
536 IsSuccess = false,
537 Message = result,
538 };
539 }
540
541 var list = JsonConvert.DeserializeObject<List<T>>(result);
542 return new Response
543 {
544 IsSuccess = true,
545 Message = "Ok",
546 Result = list,
547 };
548 }
549 catch (Exception ex)
550 {
551 return new Response
552 {
553 IsSuccess = false,
554 Message = ex.Message,
555 };
556 }
557 }
558
559 public async Task<Response> GetList<T>(
560 string urlBase,
561 string servicePrefix,
562 string controller,
563 string tokenType,
564 string accessToken,
565 int id)
566 {
567 try
568 {
569 var client = new HttpClient();
570 client.DefaultRequestHeaders.Authorization =
571 new AuthenticationHeaderValue(tokenType, accessToken);
572 client.BaseAddress = new Uri(urlBase);
573 var url = string.Format(
574 "{0}{1}/{2}",
575 servicePrefix,
576 controller,
577 id);
578 HttpResponseMessage response = await client.GetAsync(url);
579
580 if (!response.IsSuccessStatusCode)
581 {
582 return new Response
583 {
584 IsSuccess = false,
585 Message = response.StatusCode.ToString(),
586 };
587 }
588
589 var result = await response.Content.ReadAsStringAsync();
590 var list = JsonConvert.DeserializeObject<List<T>>(result);
591 return new Response
592 {
593 IsSuccess = true,
594 Message = "Ok",
595 Result = list,
596 };
597 }
598 catch (Exception ex)
599 {
600 return new Response
601 {
602 IsSuccess = false,
603 Message = ex.Message,
604 };
605 }
606 }
607
608 public async Task<Response> Post<T>(
609 string urlBase,
610 string servicePrefix,
611 string controller,
612 string tokenType,
613 string accessToken,
614 T model)
615 {
616 try
617 {
618 var request = JsonConvert.SerializeObject(model);
619 var content = new StringContent(
620 request, Encoding.UTF8,
621 "application/json");
622 var client = new HttpClient();
623 client.DefaultRequestHeaders.Authorization =
624 new AuthenticationHeaderValue(tokenType, accessToken);
625 client.BaseAddress = new Uri(urlBase);
626 var url = string.Format("{0}{1}", servicePrefix, controller);
627 var response = await client.PostAsync(url, content);
628 var result = await response.Content.ReadAsStringAsync();
629
630 if (!response.IsSuccessStatusCode)
631 {
632 var error = JsonConvert.DeserializeObject<Response>(result);
633 error.IsSuccess = false;
634 return error;
635 }
636
637 var newRecord = JsonConvert.DeserializeObject<T>(result);
638
639 return new Response
640 {
641 IsSuccess = true,
642 Message = "Record added OK",
643 Result = newRecord,
644 };
645 }
646 catch (Exception ex)
647 {
648 return new Response
649 {
650 IsSuccess = false,
651 Message = ex.Message,
652 };
653 }
654 }
655
656 public async Task<Response> Post<T>(
657 string urlBase,
658 string servicePrefix,
659 string controller,
660 T model)
661 {
662 try
663 {
664 var request = JsonConvert.SerializeObject(model);
665 var content = new StringContent(
666 request,
667 Encoding.UTF8,
668 "application/json");
669 var client = new HttpClient();
670 client.BaseAddress = new Uri(urlBase);
671 var url = string.Format("{0}{1}", servicePrefix, controller);
672 var response = await client.PostAsync(url, content);
673
674 if (!response.IsSuccessStatusCode)
675 {
676 return new Response
677 {
678 IsSuccess = false,
679 Message = response.StatusCode.ToString(),
680 };
681 }
682
683 var result = await response.Content.ReadAsStringAsync();
684 var newRecord = JsonConvert.DeserializeObject<T>(result);
685
686 return new Response
687 {
688 IsSuccess = true,
689 Message = "Record added OK",
690 Result = newRecord,
691 };
692 }
693 catch (Exception ex)
694 {
695 return new Response
696 {
697 IsSuccess = false,
698 Message = ex.Message,
699 };
700 }
701 }
702
703 public async Task<Response> Put<T>(
704 string urlBase,
705 string servicePrefix,
706 string controller,
707 string tokenType,
708 string accessToken,
709 T model)
710 {
711 try
712 {
713 var request = JsonConvert.SerializeObject(model);
714 var content = new StringContent(
715 request,
716 Encoding.UTF8, "application/json");
717 var client = new HttpClient();
718 client.DefaultRequestHeaders.Authorization =
719 new AuthenticationHeaderValue(tokenType, accessToken);
720 client.BaseAddress = new Uri(urlBase);
721 var url = string.Format(
722 "{0}{1}/{2}",
723 servicePrefix,
724 controller,
725 model.GetHashCode());
726 var response = await client.PutAsync(url, content);
727 var result = await response.Content.ReadAsStringAsync();
728
729 if (!response.IsSuccessStatusCode)
730 {
731 var error = JsonConvert.DeserializeObject<Response>(result);
732 error.IsSuccess = false;
733 return error;
734 }
735
736 var newRecord = JsonConvert.DeserializeObject<T>(result);
737
738 return new Response
739 {
740 IsSuccess = true,
741 Result = newRecord,
742 };
743 }
744 catch (Exception ex)
745 {
746 return new Response
747 {
748 IsSuccess = false,
749 Message = ex.Message,
750 };
751 }
752 }
753
754 public async Task<Response> Delete<T>(
755 string urlBase,
756 string servicePrefix,
757 string controller,
758 string tokenType,
759 string accessToken,
760 T model)
761 {
762 try
763 {
764 var client = new HttpClient();
765 client.BaseAddress = new Uri(urlBase);
766 client.DefaultRequestHeaders.Authorization =
767 new AuthenticationHeaderValue(tokenType, accessToken);
768 var url = string.Format(
769 "{0}{1}/{2}",
770 servicePrefix,
771 controller,
772 model.GetHashCode());
773 var response = await client.DeleteAsync(url);
774 var result = await response.Content.ReadAsStringAsync();
775
776 if (!response.IsSuccessStatusCode)
777 {
778 var error = JsonConvert.DeserializeObject<Response>(result);
779 error.IsSuccess = false;
780 return error;
781 }
782
783 return new Response
784 {
785 IsSuccess = true,
786 };
787 }
788 catch (Exception ex)
789 {
790 return new Response
791 {
792 IsSuccess = false,
793 Message = ex.Message,
794 };
795 }
796 }
797 }
798
799
800
801}
802/// Response.cs en appcontacto models ///
803namespace appContacto.Models
804{
805 public class Response
806 {
807 public bool IsSuccess { get; set; }
808 public string Message { get; set; }
809 public object Result { get; set; }
810 }
811}
812
813/// Contact.cs en models appcontacto ///
814using Newtonsoft.Json;
815
816namespace appContacto.Models
817{
818 public enum TypeContact
819 {
820 telephone,
821 email,
822 facebook
823 }
824
825 public class Contact
826 {
827 [JsonProperty(PropertyName = "ContactID")]
828 public int ContactID { get; set; }
829 [JsonProperty(PropertyName = "Name")]
830 public string Name { get; set; }
831 [JsonProperty(PropertyName = "Type")]
832 public TypeContact Type { get; set; }
833 [JsonProperty(PropertyName = "ContactValue")]
834 public string ContactValue { get; set; }
835 }
836
837}
838
839///TokenResponse ///
840
841namespace appContacto.Models
842{
843 using System;
844 using Newtonsoft.Json;
845
846 public class TokenResponse
847 {
848 #region Properties
849 [JsonProperty(PropertyName = "access_token")]
850 public string AccessToken { get; set; }
851
852 [JsonProperty(PropertyName = "token_type")]
853 public string TokenType { get; set; }
854
855 [JsonProperty(PropertyName = "expires_in")]
856 public int ExpiresIn { get; set; }
857
858 [JsonProperty(PropertyName = "userName")]
859 public string UserName { get; set; }
860
861 [JsonProperty(PropertyName = ".issued")]
862 public DateTime Issued { get; set; }
863
864 [JsonProperty(PropertyName = ".expires")]
865 public DateTime Expires { get; set; }
866
867 [JsonProperty(PropertyName = "error_description")]
868 public string ErrorDescription { get; set; }
869 #endregion
870 }
871
872}
873
874/// InstanceLocator.cs en interfaces appcontacto ///
875
876namespace appContacto.Interfaces
877{
878 using ViewModels;
879 public class InstanceLocator
880 {
881 #region Properties
882 public MainViewModel Main { get; set; }
883 #endregion
884
885 #region Constructors
886 public InstanceLocator()
887 {
888 this.Main = new MainViewModel();
889 }
890 #endregion
891 }
892}
893/// ListViewContact.xaml en appcontacto-Views ///
894<?xml version="1.0" encoding="utf-8" ?>
895<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
896 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
897 BindingContext="{Binding Main, Source={StaticResource Locator}}"
898 x:Class="appContacto.Views.ListViewContact">
899 <StackLayout Margin="2">
900 <Label Text="Hola" FontAttributes="Bold" />
901 <ListView x:Name="MyListView"
902 ItemsSource="{Binding Contacts}"
903 CachingStrategy="RecycleElement">
904
905 <ListView.ItemTemplate>
906 <DataTemplate>
907 <!--TextCell Text="{Binding Name}" /-->
908 <StackLayout Margin="8">
909
910 <Label Text="{Binding Name}"
911 FontAttributes="Bold" />
912 <Label Text="{Binding ContactValue}" />
913 </StackLayout>
914
915 </DataTemplate>
916 </ListView.ItemTemplate>
917 </ListView>
918 </StackLayout>
919</ContentPage>
920
921
922/// ListViewContact.xaml.cs en appcontacto-Views ///
923using Xamarin.Forms;
924using Xamarin.Forms.Xaml;
925
926namespace appContacto.Views
927{
928 [XamlCompilation(XamlCompilationOptions.Compile)]
929 public partial class ListViewContact : ContentPage
930 {
931 public ListViewContact()
932 {
933 InitializeComponent();
934 }
935 }
936}
937
938/// IdentityModels en apicontactsecurity- Models ///
939using System.Security.Claims;
940using System.Threading.Tasks;
941using Microsoft.AspNet.Identity;
942using Microsoft.AspNet.Identity.EntityFramework;
943using Microsoft.AspNet.Identity.Owin;
944
945namespace apiContactSecurity.Models
946{
947 // Para agregar datos de perfil del usuario, agregue más propiedades a su clase ApplicationUser. Visite https://go.microsoft.com/fwlink/?LinkID=317594 para obtener más información.
948 public class ApplicationUser : IdentityUser
949 {
950 public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager, string authenticationType)
951 {
952 // Tenga en cuenta que el valor de authenticationType debe coincidir con el definido en CookieAuthenticationOptions.AuthenticationType
953 var userIdentity = await manager.CreateIdentityAsync(this, authenticationType);
954 // Agregar aquí notificaciones personalizadas de usuario
955 return userIdentity;
956 }
957 }
958
959 public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
960 {
961 public ApplicationDbContext()
962 : base("DefaultConnection", throwIfV1Schema: false)
963 {
964 }
965
966 public static ApplicationDbContext Create()
967 {
968 return new ApplicationDbContext();
969 }
970 }
971}
972
973/// En apicontactsecurity añadir contact.cs y datacontext//
974
975/// AccountViewModels.cs en apicontactsecurity-models
976
977using System;
978using System.Collections.Generic;
979
980namespace apiContactSecurity.Models
981{
982 // Modelos devueltos por las acciones de AccountController.
983
984 public class ExternalLoginViewModel
985 {
986 public string Name { get; set; }
987
988 public string Url { get; set; }
989
990 public string State { get; set; }
991 }
992
993 public class ManageInfoViewModel
994 {
995 public string LocalLoginProvider { get; set; }
996
997 public string Email { get; set; }
998
999 public IEnumerable<UserLoginInfoViewModel> Logins { get; set; }
1000
1001 public IEnumerable<ExternalLoginViewModel> ExternalLoginProviders { get; set; }
1002 }
1003
1004 public class UserInfoViewModel
1005 {
1006 public string Email { get; set; }
1007
1008 public bool HasRegistered { get; set; }
1009
1010 public string LoginProvider { get; set; }
1011 }
1012
1013 public class UserLoginInfoViewModel
1014 {
1015 public string LoginProvider { get; set; }
1016
1017 public string ProviderKey { get; set; }
1018 }
1019}
1020
1021/// AccountBindingModels.cs en apicontactsecurity-models ///
1022using System;
1023using System.ComponentModel.DataAnnotations;
1024using Newtonsoft.Json;
1025
1026namespace apiContactSecurity.Models
1027{
1028 // Modelos usados como parámetros para las acciones de AccountController.
1029
1030 public class AddExternalLoginBindingModel
1031 {
1032 [Required]
1033 [Display(Name = "Token de acceso externo")]
1034 public string ExternalAccessToken { get; set; }
1035 }
1036
1037 public class ChangePasswordBindingModel
1038 {
1039 [Required]
1040 [DataType(DataType.Password)]
1041 [Display(Name = "Contraseña actual")]
1042 public string OldPassword { get; set; }
1043
1044 [Required]
1045 [StringLength(100, ErrorMessage = "El número de caracteres de {0} debe ser al menos {2}.", MinimumLength = 6)]
1046 [DataType(DataType.Password)]
1047 [Display(Name = "Nueva contraseña")]
1048 public string NewPassword { get; set; }
1049
1050 [DataType(DataType.Password)]
1051 [Display(Name = "Confirmar la nueva contraseña")]
1052 [Compare("NewPassword", ErrorMessage = "La nueva contraseña y la contraseña de confirmación no coinciden.")]
1053 public string ConfirmPassword { get; set; }
1054 }
1055
1056 public class RegisterBindingModel
1057 {
1058 [Required]
1059 [Display(Name = "Correo electrónico")]
1060 public string Email { get; set; }
1061
1062 [Required]
1063 [StringLength(100, ErrorMessage = "El número de caracteres de {0} debe ser al menos {2}.", MinimumLength = 6)]
1064 [DataType(DataType.Password)]
1065 [Display(Name = "Contraseña")]
1066 public string Password { get; set; }
1067
1068 [DataType(DataType.Password)]
1069 [Display(Name = "Confirmar contraseña")]
1070 [Compare("Password", ErrorMessage = "La contraseña y la contraseña de confirmación no coinciden.")]
1071 public string ConfirmPassword { get; set; }
1072 }
1073
1074 public class RegisterExternalBindingModel
1075 {
1076 [Required]
1077 [Display(Name = "Correo electrónico")]
1078 public string Email { get; set; }
1079 }
1080
1081 public class RemoveLoginBindingModel
1082 {
1083 [Required]
1084 [Display(Name = "Proveedor de inicio de sesión")]
1085 public string LoginProvider { get; set; }
1086
1087 [Required]
1088 [Display(Name = "Clave de proveedor")]
1089 public string ProviderKey { get; set; }
1090 }
1091
1092 public class SetPasswordBindingModel
1093 {
1094 [Required]
1095 [StringLength(100, ErrorMessage = "El número de caracteres de {0} debe ser al menos {2}.", MinimumLength = 6)]
1096 [DataType(DataType.Password)]
1097 [Display(Name = "Nueva contraseña")]
1098 public string NewPassword { get; set; }
1099
1100 [DataType(DataType.Password)]
1101 [Display(Name = "Confirmar la nueva contraseña")]
1102 [Compare("NewPassword", ErrorMessage = "La nueva contraseña y la contraseña de confirmación no coinciden.")]
1103 public string ConfirmPassword { get; set; }
1104 }
1105}
1106///ApiContact