Chapter161:ImportGoogleContacts

No Comments

Section161.1:Requirements

ToImportGoogle(Gmail)contactsinASP.NETMVCapplication,firstdownload”GoogleAPIsetup”Thiswillgrantthe following references:

usingGoogle.Contacts;

usingGoogle.GData.Client;

usingGoogle.GData.Contacts;

usingGoogle.GData.Extensions;

Add these to therelevant application.

Section161.2:Sourcecodeinthecontroller

usingGoogle.Contacts;

usingGoogle.GData.Client;

usingGoogle.GData.Contacts;

usingGoogle.GData.Extensions;

usingNewtonsoft.Json;

usingSystem;

usingSystem.Collections.Generic;

usingSystem.IO;

usingSystem.Linq;

usingSystem.Net;

usingSystem.Text;

usingSystem.Web;

usingSystem.Web.Mvc;

namespaceGoogleContactImport.Controllers

{

publicclassHomeController:Controller

{

publicActionResultIndex()

{

returnView();

}

publicActionResultImport()

{

stringclientId=””;                   //hereyouneedtoaddyourgoogleclientid

stringredirectUrl=”http://localhost:1713/Home/AddGoogleContacts”;//hereyour redirectactionmethodNOTE:youneedtoconfiguresameurlingoogleconsole

Response.Redirect(“https://accounts.google.com/o/oauth2/auth?redirect_uri=”+redirectUrl+”&amp&response_type=code&amp&client_id=”+clientId+ “&amp&scope=https://www.google.com/m8/feeds/&approval_prompt=force&access_type=offline”);

returnView();

}

publicActionResultAddGoogleContacts()

{

stringcode=Request.QueryString[“code”];

if(!string.IsNullOrEmpty(code))

{

varcontacts=GetAccessToken().ToArray();

if(contacts.Length>0)

{

//Youwillgetallcontactshere

returnView(“Index”,contacts);

}

else

{

returnRedirectToAction(“Index”,”Home”);

}

}

else

{

returnRedirectToAction(“Index”,”Home”);

}

}

publicList<GmailContacts>GetAccessToken()

{

stringcode=Request.QueryString[“code”];

stringgoogle_client_id=””;//yourgoogleclientId

stringgoogle_client_sceret=””;//yourgooglesecretkey

stringgoogle_redirect_url=”http://localhost:1713/MyContact/AddGoogleContacts”;

HttpWebRequest webRequest= (HttpWebRequest)WebRequest.Create(“https://accounts.google.com/o/oauth2/token”);

webRequest.Method=”POST”;

stringparameters=”code=”+code+”&client_id=”+google_client_id+ “&client_secret=”+google_client_sceret+”&redirect_uri=”+google_redirect_url+ “&grant_type=authorization_code”;

byte[]byteArray=Encoding.UTF8.GetBytes(parameters);

webRequest.ContentType=”application/x-www-form-urlencoded”; webRequest.ContentLength=byteArray.Length;

StreampostStream=webRequest.GetRequestStream();

//Addthepostdatatothewebrequest

postStream.Write(byteArray,0,byteArray.Length);

postStream.Close();

WebResponseresponse=webRequest.GetResponse();

postStream=response.GetResponseStream();

StreamReaderreader=newStreamReader(postStream);

stringresponseFromServer=reader.ReadToEnd();GooglePlusAccess

TokenserStatus=

JsonConvert.DeserializeObject<GooglePlusAccessToken>(responseFromServer);

/*End*/

returnGetContacts(serStatus);

}

publicList<GmailContacts>GetContacts(GooglePlusAccessTokenserStatus)

{

stringgoogle_client_id=””;                    //clientid

stringgoogle_client_sceret=””;//secretkey

/*GetGoogleContactsFromAccessTokenandRefreshToken*/

//stringrefreshToken=serStatus.refresh_token;

stringaccessToken=serStatus.access_token;

stringscopes=”https://www.google.com/m8/feeds/contacts/default/full/”;OAuth2ParametersoAuthparameters=newOAuth2Parameters()

{

ClientId=google_client_id,

ClientSecret=google_client_sceret,

RedirectUri=”http://localhost:1713/Home/AddGoogleContacts”, Scope=scopes,

AccessToken=accessToken,

//       RefreshToken=refreshToken

};

RequestSettingssettings=newRequestSettings(“AppName”,oAuthparameters); ContactsRequestcr=newContactsRequest(settings);

ContactsQueryquery=newContactsQuery(ContactsQuery.CreateContactsUri(“default”)); query.NumberToRetrieve=5000;

Feed<Contact>ContactList=cr.GetContacts();

List<GmailContacts>olist=newList<GmailContacts>();

foreach(ContactcontactinContactList.Entries)

{

foreach(EMailemailincontact.Emails)

{

GmailContactsgc=newGmailContacts();

gc.EmailID=email.Address;

vara=contact.Name.FullName; olist.Add(gc);

}

}

returnolist;

}

publicclassGmailContacts

{

publicstringEmailID

{

get{return_EmailID;}

set{_EmailID=value;}

}

privatestring_EmailID;

}

publicclassGooglePlusAccessToken

{

publicGooglePlusAccessToken()

{}

publicstringaccess_token

{

get{return_access_token;}

set{_access_token=value;}

}

privatestring_access_token;

publicstringtoken_type

{

get{return_token_type;}

set{_token_type=value;}

}

privatestring_token_type;

publicstringexpires_in

{

get{return_expires_in;}

set{_expires_in=value;}

}

privatestring_expires_in;

}

}

}

Section161.3:Sourcecodeintheview

Theonlyactionmethodyouneedtoaddistoaddanactionlinkpresentbelow

<ahref=’@Url.Action(“Import”,”Home”)’>ImportGoogleContacts</a>

About us and this blog

We are a digital marketing company with a focus on helping our customers achieve great results across several key areas.

Request a free quote

We offer professional SEO services that help websites increase their organic search score drastically in order to compete for the highest rankings even when it comes to highly competitive keywords.

Subscribe to our newsletter!

More from our blog

See all posts

Leave a Comment