در این مقاله نشان می دهیم که چگونه با استفاده از ASPSnippets.GoogleAPI تصویر پروفایل و آدرس ایمیل مخاطبین خود در Gmail را وارد ASP.Net کنیم.
مخاطبین Gmail باید از طریق پروتکل OAUTH2 فراخوانی شوند.
دریافت Google Client ID و Client Secret:
برای استفاده از Google Account API برای واکشی مخاطبین Gmail، باید یک اپلیکیشن در Google Console ایجاد کرده و Client ID و Client Secret دریافت نماییم.
بخش HTML:
در این بخش، یک Button داریم که امکان احراز هویت کاربر از طریق Google Account API را به ما می دهد، یک پنل شامل یک Grid View برای نمایش مخاطبین بازیابی شده به همراه عکس پروفایل و آدرس ایمیل آن ها داریم.
<asp:Button ID="btnLogin" Text="ورود" runat="server" OnClick="Login" /> <asp:Panel ID="pnlProfile" runat="server" Visible="false"> <hr /> <asp:GridView ID="gvContacts" runat="server" AutoGenerateColumns="false"> <Columns> <asp:TemplateField HeaderText="عکس پروفایل" HeaderStyle-Width="60"> <ItemTemplate> <asp:Image ID="Image1" ImageUrl='<%# Eval("PhotoUrl") %>' runat="server" onerror="this.src='default.png';" /> </ItemTemplate> </asp:TemplateField> <asp:BoundField DataField="Name" HeaderText="نام" HeaderStyle-Width="100" /> <asp:BoundField DataField="Email" HeaderText="آدرس ایمیل" HeaderStyle-Width="100" /> </Columns> </asp:GridView> </asp:Panel>
فضاهای نام:
فضاهای نام زیر باید به پروژه اضافه شوند.
در C#:
using System.Data; using ASPSnippets.GoogleAPI; using System.Web.Script.Serialization;
در VB.Net:
using System.Data; Imports ASPSnippets.GoogleAPI Imports System.Web.Script.Serialization
توجه داشته باشید که باید فایل dll مربوط به ASPSnippets.GoogleAPI را باید به فولدر bin اضافه کرده و refrence آن را نیز به پروژه اضافه کنیم.
کلاس های داده:
برای نگه داری جزئیات مخاطبینی که بعد از احراز هویت از طریق Google API برگردانده می شود، باید کلاس زیر را ایجاد کنیم.
ساختار این کلاس دقیقا شبیه به رشته Json ای است که از Google API برگردانده می شود، بنابراین رشته json به سادگی به اشیای متناظر خود تبدیل (deserialize) می شود.
کد C#:
public class GoogleContacts { public Feed Feed { get; set; } } public class Feed { public GoogleTitle Title { get; set; } public List<Contact> Entry { get; set; } } public class GoogleTitle { public string T { get; set; } } public class Contact { public GoogleTitle Title { get; set; } public List<Email> GdEmail { get; set; } public List<Link> Link { get; set; } } public class Email { public string Address { get; set; } public bool Primary { get; set; } } public class Link { public string Rel { get; set; } public string Type { get; set; } public string Href { get; set; } }
کد VB.Net:
Public Class GoogleContacts Public Property Feed() As Feed Get Return m_Feed End Get Set(value As Feed) m_Feed = Value End Set End Property Private m_Feed As Feed End Class Public Class Feed Public Property Title() As GoogleTitle Get Return m_Title End Get Set(value As GoogleTitle) m_Title = Value End Set End Property Private m_Title As GoogleTitle Public Property Entry() As List(Of Contact) Get Return m_Entry End Get Set(value As List(Of Contact)) m_Entry = Value End Set End Property Private m_Entry As List(Of Contact) End Class Public Class GoogleTitle Public Property T() As String Get Return m_T End Get Set(value As String) m_T = Value End Set End Property Private m_T As String End Class Public Class Contact Public Property Title() As GoogleTitle Get Return m_Title End Get Set(value As GoogleTitle) m_Title = Value End Set End Property Private m_Title As GoogleTitle Public Property GdEmail() As List(Of Email) Get Return m_GdEmail End Get Set(value As List(Of Email)) m_GdEmail = Value End Set End Property Private m_GdEmail As List(Of Email) Public Property Link() As List(Of Link) Get Return m_Link End Get Set(value As List(Of Link)) m_Link = Value End Set End Property Private m_Link As List(Of Link) End Class Public Class Email Public Property Address() As String Get Return m_Address End Get Set(value As String) m_Address = Value End Set End Property Private m_Address As String Public Property Primary() As Boolean Get Return m_Primary End Get Set(value As Boolean) m_Primary = Value End Set End Property Private m_Primary As Boolean End Class Public Class Link Public Property Rel() As String Get Return m_Rel End Get Set(value As String) m_Rel = Value End Set End Property Private m_Rel As String Public Property Type() As String Get Return m_Type End Get Set(value As String) m_Type = Value End Set End Property Private m_Type As String Public Property Href() As String Get Return m_Href End Get Set(value As String) m_Href = Value End Set End Property Private m_Href As String End Class
احراز هویت کاربر از طریق اکانت گوگل:
با کلیک روی دکمه “ورود”، کاربر به صفحه مجوزهای دسترسی گوگل (Google Authorization) هدایت می شود که کاربر امکان دسترسی اپلیکیشن به جزئیات مخاطبین Gmail خود را می دهد
در این مثال، ما درخواست دسترسی به جزییات مخاطبین Gmail را با ارسال http://www.google.com/m8/feeds داریم. کاربر می تواند اجازه دسترسی بدهد و یا آن را رد کند که در هر دو مورد، کاربر به صفحه ای برگردانده می شود که در زمان ساخت اپلیکیشن در Google Developer Console به عنوان RedirectUri تنظیم شده است.
کد C#:
protected void Login(object sender, EventArgs e) { GoogleConnect.Authorize(Server.UrlEncode("https://www.google.com/m8/feeds/")); }
کد VB.Net:
Protected Sub Login(sender As Object, e As EventArgs) GoogleConnect.Authorize(Server.UrlEncode("https://www.google.com/m8/feeds/")) End Sub
فراخوانی مخاطبین حساب Gmail کاربر و نمایش آن در صفحه:
اولین کاری که باید انجام دهیم این است که Client ID و Client Secret را برای کلاس GoogleConnect تنظیم کنیم و همچنین API را نیز روی Contacts تنظیم کنیم چرا که ما می خواهیم مخاطبین را واکشی نماییم.
کد زیر در Query string به دنبال کد دسترسی (توکن دسترسی) می گردد و سپس این کد دسترسی به همراه پارامتر maxRecords که حداکثر تعداد مخاطبینی را که قرار است از Google API واکشی شود مشخص می کند، به تابع Fetch در کلاس GoogleConnect ارسال می شود.
تابع Fetch مخاطبین حساب Gamil را به صورت رشته JSON برمی گرداند که سپس به اشیای کلاس GoogleContacts تبدیل (deserialize) می شود.
سپس حلقه ای اجرا می شود که نام، آدرس ایمیل و آدرس محل ذخیره عکس پروفایل را در DataTable کپی می کند که درنهایت به Grid View متصل (Bind) می شود.
اگر مخاطبی عکس پروفایل نداشت، تصویر پیش فرضی به جای آن نمایش داده می شود.
کد C#:
protected void Page_Load(object sender, EventArgs e) { GoogleConnect.ClientId = " <Google Client ID>"; GoogleConnect.ClientSecret = " <Google Client Secret>"; GoogleConnect.RedirectUri = Request.Url.AbsoluteUri.Split('?')[0]; GoogleConnect.API = EnumAPI.Contacts; if (!string.IsNullOrEmpty(Request.QueryString["code"])) { string code = Request.QueryString["code"]; string json = GoogleConnect.Fetch("me", code, 10); GoogleContacts profile = new JavaScriptSerializer().Deserialize<GoogleContacts>(json); DataTable dt = new DataTable(); dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Name", typeof(string)), new DataColumn("Email", typeof(string)), new DataColumn("PhotoUrl",typeof(string)) }); foreach (Contact contact in profile.Feed.Entry) { string name = contact.Title.T; string email = contact.GdEmail.Find(p => p.Primary).Address; Link photo = contact.Link.Find(p => p.Rel.EndsWith("#photo")); string photoUrl = GoogleConnect.GetPhotoUrl(photo != null ? photo.Href : "~/default.png"); dt.Rows.Add(name, email, photoUrl); gvContacts.DataSource = dt; gvContacts.DataBind(); } pnlProfile.Visible = true; btnLogin.Enabled = false; } if (Request.QueryString["error"] == "access_denied") { ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", "alert('Access denied.')", true); } }
کد VB.Net:
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load GoogleConnect.ClientId = " <Google Client ID>" GoogleConnect.ClientSecret = " <Google Client Secret>" GoogleConnect.RedirectUri = Request.Url.AbsoluteUri.Split("?"c)(0) GoogleConnect.API = EnumAPI.Contacts If Not String.IsNullOrEmpty(Request.QueryString("code")) Then Dim code As String = Request.QueryString("code") Dim json As String = GoogleConnect.Fetch("me", code, 10) Dim profile As GoogleContacts = New JavaScriptSerializer().Deserialize(Of GoogleContacts)(json) Dim dt As New DataTable() dt.Columns.AddRange(New DataColumn(2) {New DataColumn("Name", GetType(String)), New DataColumn("Email",GetType(String)), New DataColumn("PhotoUrl", GetType(String))}) For Each contact As Contact In profile.Feed.Entry Dim name As String = contact.Title.T Dim email As String = contact.GdEmail.Find(Function(p) p.Primary).Address Dim photo As Link = contact.Link.Find(Function(p) p.Rel.EndsWith("#photo")) Dim photoUrl As String = GoogleConnect.GetPhotoUrl(If(photo IsNot Nothing, photo.Href, "~/default.png")) dt.Rows.Add(name, email, photoUrl) gvContacts.DataSource = dt gvContacts.DataBind() Next pnlProfile.Visible = True btnLogin.Enabled = False End If If Request.QueryString("error") = "access_denied" Then ClientScript.RegisterClientScriptBlock(Me.[GetType](), "alert", "alert('Access denied.')", True) End If End Sub
خطاهای احتمالی:
اگر زمان استفاده از ASPSnippets.GoogleAPI در پروژه خود با خطاهایی از جانب Google API برخورد کردید، لطفا به لینک زیر مراجعه نمایید:
ممنووووووووون
۴