In this article I will explain how to import contacts along with their profile image and email address from Google Gmail account in ASP.Net using C#, VB.Net and the ASPSnippets.GoogleAPI.
The Google Gmail contacts will be fetched using OAUTH2 protocol.
Getting Google Client ID and Client Secret
In order to use Google Account API to fetch Google Gmail contacts, you will need to create an Application in Google Console and get Client ID and Client Secret. For details please refer the following article.
HTML Markup
HTML Markup consists of a Button to allow authenticate the user with Google Account API, and a Panel containing a GridView to display retrieved contacts, their profile picture and email address.
<asp:Button ID="btnLogin" Text="Login" 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="Photo" 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="Name" HeaderStyle-Width="100" />
<asp:BoundField DataField="Email" HeaderText="Email Address" HeaderStyle-Width="100" />
</Columns>
</asp:GridView>
</asp:Panel>
Namespaces
You will need to import the following namespaces.
Note: You will need place the ASPSnippets.GoogleAPI DLL inside the BIN folder of your project and add its reference.
C#
using System.Data;
using ASPSnippets.GoogleAPI;
using System.Web.Script.Serialization;
VB.Net
Imports System.Data
Imports ASPSnippets.GoogleAPI
Imports System.Web.Script.Serialization
Data Class
You will need to create the following class which will be used to hold the Google Gmail Contact details returned from Google API after authentication.
The structure of this class is same as that of the JSON string returned from the Google API so that the JSON string can be easily deserialized to its object.
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
Authenticate user using Google account
On the click of the Login button, User is redirected to the Google Authorization page where user has to provide permission to the Application to access his Google Gmail contact details.
For this article I am requesting access to the Google Gmail contact details of the user by passing the https://www.google.com/m8/feeds/ scope. User can allow and deny and in both cases he is sent back to the URL set as the RedirectUri while creating the application in Google Developer Console.
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
Fetching the User’s Google Gmail Contacts and displaying on Page
The very first thing is that you need to set the Client ID and the Client Secret for the GoogleConnect class and you need to set the API as Contacts as we need fetch Contacts.
The below code looks for access code (access token) in Query string and then this access code is passed to the Fetch function of the GoogleConnect class along with the maxRecords parameter which determines the number of contacts that will be fetched from Google API.
The Fetch function returns the Google Gmail contacts as JSON string which is then deserialized to the GoogleContacts class object.
Then a loop is executed and the name, email address and the profile picture URL are copied to a DataTable and which is finally bound to the GridView control.
If the person does not have a Profile Picture then a default image is displayed.
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", code);
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"),
code)
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
Errors
If you encounter errors from Google API when using the ASPSnippets.GoogleAPI in your projects, please refer the following link.
Demo
Downloads