public async void GetContactPermission() { GooglePlusAccessToken objToken = new GooglePlusAccessToken(); List <TextValue> objNameEmailCollection = new List <TextValue>(); session = new SessionHelper(); try { if (Request.QueryString["code"] != null) { objNameEmailCollection = objClientsManager.getClientContactForSync(session.UserSession.UserId, Convert.ToInt64(session.UserSession.PIN)); objToken = await GetAccessToken(Request.QueryString["code"].ToString()); await AddContacts(objToken, objNameEmailCollection); } else { string clientId = "995459998390-h5ea19firkf4q99mp44uic5qk8djtrnb.apps.googleusercontent.com"; string redirectUrl = "http://testerp.easysavemerchants.com/UserSetings/GetContactPermission"; Response.Redirect("https://accounts.google.com/o/oauth2/auth?redirect_uri=" + redirectUrl + "&response_type=code&client_id=" + clientId + "&scope=https://www.google.com/m8/feeds/&approval_prompt=force&access_type=offline"); } } catch (Exception ex) { BAL.Common.LogManager.LogError("GetContactPermission Post Method", 1, Convert.ToString(ex.Source), Convert.ToString(ex.Message), Convert.ToString(ex.StackTrace)); // return Json("", JsonRequestBehavior.AllowGet); } }
public void GetAccessToken() { string code = Request.QueryString["code"]; //"4/0AfDhmrhkTNFgMEWC5kDhKko63t8KlhYSXhNE6Jo-5AdOGxQawkYnwG0rqRtKoodQFGWW4A"; string google_client_id = "295167635687-bhugb57e9u7tg46ieolrbs636silvljj.apps.googleusercontent.com"; string google_client_sceret = "CwUAg3ydCCE1dnA6OshbOJfX"; string google_redirect_url = "https://localhost:44339/Webform1"; /*Get Access Token and Refresh Token*/ HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token"); webRequest.Method = "POST"; string parameters = "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; Stream postStream = webRequest.GetRequestStream(); // Add the post data to the web request postStream.Write(byteArray, 0, byteArray.Length); postStream.Close(); WebResponse response = webRequest.GetResponse(); postStream = response.GetResponseStream(); StreamReader reader = new StreamReader(postStream); string responseFromServer = reader.ReadToEnd(); GooglePlusAccessToken serStatus = JsonConvert.DeserializeObject <GooglePlusAccessToken>(responseFromServer); /*End*/ Run(serStatus); //CreateEvent(serStatus); }
public ActionResult ContactPermissionCallback() { GooglePlusAccessToken objToken = new GooglePlusAccessToken(); objResponse Response = new objResponse(); // DataSyncManager objData = new DataSyncManager(); session = new SessionHelper(); try { if (Request.QueryString["code"] != null) { // objToken = GetAccessToken(Request.QueryString["code"].ToString()); } else { return(RedirectToRoute("UserSetings")); } } catch (Exception ex) { BAL.Common.LogManager.LogError("ContactPermissionCallback Post Method", 1, Convert.ToString(ex.Source), Convert.ToString(ex.Message), Convert.ToString(ex.StackTrace)); return(RedirectToRoute("UserSetings")); } return(RedirectToRoute("ClientHome")); }
public ActionResult ContactPermissionCallback() { GooglePlusAccessToken objToken = new GooglePlusAccessToken(); objResponse Response = new objResponse(); DataSyncManager objData = new DataSyncManager(); session = new SessionHelper(); try { if (Request.QueryString["code"] != null) { objToken = GetAccessToken(Request.QueryString["code"].ToString()); Response = objData.SetGContactSeting(objToken.access_token, objToken.token_type, objToken.expires_in, objToken.refresh_token, "contact", Convert.ToInt64(session.UserSession.PIN), session.UserSession.UserId); if (Response.ErrorCode == 0) { return(RedirectToRoute("UserSetings")); } else { return(RedirectToRoute("UserSetings")); } } else { return(RedirectToRoute("UserSetings")); } } catch (Exception ex) { BAL.Common.LogManager.LogError("ContactPermissionCallback Post Method", 1, Convert.ToString(ex.Source), Convert.ToString(ex.Message), Convert.ToString(ex.StackTrace)); return(RedirectToRoute("UserSetings")); } }
public async Task <GooglePlusAccessToken> GetAccessToken(string code) { // string code = Request.QueryString["code"]; string google_client_id = "995459998390-h5ea19firkf4q99mp44uic5qk8djtrnb.apps.googleusercontent.com"; string google_client_sceret = "yCrtm5O-K_aWSmE3hzqq3pWD"; string google_redirect_url = "http://testerp.easysavemerchants.com/UserSetings/ContactPermissionCallback"; /*Get Access Token and Refresh Token*/ HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token"); webRequest.Method = "POST"; string parameters = "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; Stream postStream = webRequest.GetRequestStream(); // Add the post data to the web request await postStream.WriteAsync(byteArray, 0, byteArray.Length); postStream.Close(); WebResponse response = await webRequest.GetResponseAsync(); postStream = response.GetResponseStream(); StreamReader reader = new StreamReader(postStream); string responseFromServer = await reader.ReadToEndAsync(); GooglePlusAccessToken serStatus = JsonConvert.DeserializeObject <GooglePlusAccessToken>(responseFromServer); /*End*/ return(serStatus); // GetContacts(serStatus); }
public List <GmailContacts> GetAccessToken() { string code = Request.QueryString["code"]; string google_client_id = "936649599657-s9akus1uv18lo7b103ji7t3cu1ljlfjb.apps.googleusercontent.com"; string google_client_sceret = "w5nmQnac-A2gBLR8dh2YWGqk"; string google_redirect_url = "http://" + Global.MainLink + "/MyContact/AddGoogleContacts"; HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token"); webRequest.Method = "POST"; string parameters = "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; Stream postStream = webRequest.GetRequestStream(); // Add the post data to the web request postStream.Write(byteArray, 0, byteArray.Length); postStream.Close(); WebResponse response = webRequest.GetResponse(); postStream = response.GetResponseStream(); StreamReader reader = new StreamReader(postStream); string responseFromServer = reader.ReadToEnd(); GooglePlusAccessToken serStatus = JsonConvert.DeserializeObject <GooglePlusAccessToken>(responseFromServer); /*End*/ return(GetContacts(serStatus)); }
public GooglePlusAccessToken getAccessToken(string code, string google_client_id, string google_client_sceret, string google_redirect_url) { /*Get Access Token and Refresh Token*/ HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token"); webRequest.Method = "POST"; string parameters = "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; Stream postStream = webRequest.GetRequestStream(); // Add the post data to the web request postStream.Write(byteArray, 0, byteArray.Length); postStream.Close(); WebResponse response = webRequest.GetResponse(); postStream = response.GetResponseStream(); StreamReader reader = new StreamReader(postStream); string responseFromServer = reader.ReadToEnd(); GooglePlusAccessToken serStatus = JsonConvert.DeserializeObject <GooglePlusAccessToken>(responseFromServer); HttpContext.Current.Session["serStatus"] = serStatus; return(serStatus); }
public void GetAccessToken() { string code = Request.QueryString["code"]; string google_client_id = "yourclientId"; string google_client_sceret = "yourclientSecret"; string google_redirect_url = "http://www.yogihosting.com/TutorialCode/GoogleContactAPI/google-contact-api.aspx"; /*Get Access Token and Refresh Token*/ HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token"); webRequest.Method = "POST"; string parameters = "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; Stream postStream = webRequest.GetRequestStream(); // Add the post data to the web request postStream.Write(byteArray, 0, byteArray.Length); postStream.Close(); WebResponse response = webRequest.GetResponse(); postStream = response.GetResponseStream(); StreamReader reader = new StreamReader(postStream); string responseFromServer = reader.ReadToEnd(); GooglePlusAccessToken serStatus = JsonConvert.DeserializeObject <GooglePlusAccessToken>(responseFromServer); /*End*/ GetContacts(serStatus); }
protected void GetGoogleInfo() { try { if ((Session.Contents.Count > 0) && (Session["loginWith"] != null) && (Session["loginWith"].ToString() == "google")) { var url = Request.Url.Query; if (url != "") { string queryString = url.ToString(); char[] delimiterChars = { '=' }; string[] words = queryString.Split(delimiterChars); string code = words[1]; if (code != null) { //get the access token HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token"); webRequest.Method = "POST"; Parameters = "code=" + code + "&client_id=" + googleplus_client_id + "&client_secret=" + googleplus_client_secret + "&redirect_uri=" + googleplus_redirect_url + "&grant_type=authorization_code"; byte[] byteArray = Encoding.UTF8.GetBytes(Parameters); webRequest.ContentType = "application/x-www-form-urlencoded"; webRequest.ContentLength = byteArray.Length; Stream postStream = webRequest.GetRequestStream(); // Add the post data to the web request postStream.Write(byteArray, 0, byteArray.Length); postStream.Close(); WebResponse response = webRequest.GetResponse(); postStream = response.GetResponseStream(); StreamReader reader = new StreamReader(postStream); string responseFromServer = reader.ReadToEnd(); GooglePlusAccessToken serStatus = JsonConvert.DeserializeObject <GooglePlusAccessToken>(responseFromServer); if (serStatus != null) { string accessToken = string.Empty; accessToken = serStatus.access_token; if (!string.IsNullOrEmpty(accessToken)) { // This is where you want to add the code if login is successful. getgoogleplususerdataSer(accessToken); } } } } } } catch (Exception ex) { throw ex; //throw new Exception(ex.Message, ex); //Response.Redirect("index.aspx"); } }
public void ListAllContacts() { string code = Request.QueryString["code"]; string google_client_id = ConfigurationManager.AppSettings["google_client_id"].ToString(); string google_client_sceret = ConfigurationManager.AppSettings["google_client_sceret"].ToString(); string google_redirect_url = ConfigurationManager.AppSettings["google_redirect_url"].ToString(); /*Get Access Token and Refresh Token*/ GoogleContactService objService = new GoogleContactService(); GooglePlusAccessToken serStatus = objService.getAccessToken(code, google_client_id, google_client_sceret, google_redirect_url); /*End*/ List <ContactDetail> contactDetails = objService.GetContacts(serStatus); BindDataToDrid(contactDetails); }
public void Run(GooglePlusAccessToken model) { //string refreshToken = string.Empty; //string credentialError; //var credential = GetUserCredential(out credentialError); //if (credential != null && string.IsNullOrWhiteSpace(credentialError)) //{ // //Save RefreshToken into Database // refreshToken = credential.Token.RefreshToken; //} string addEventError; string calendarEventId = string.Empty; calendarEventId = AddCalenderEvents(model.refresh_token, "*****@*****.**", "My Calendar Event", DateTime.Now, DateTime.Now.AddHours(1), out addEventError); }
public List <ContactDetail> GetContacts(GooglePlusAccessToken serStatus) { string refreshToken = serStatus.refresh_token; string accessToken = serStatus.access_token; string scopes = "https://www.google.com/m8/feeds/contacts/default/full/"; OAuth2Parameters oAuthparameters = new OAuth2Parameters() { RedirectUri = ConfigurationManager.AppSettings["google_redirect_url"].ToString(), Scope = scopes, AccessToken = accessToken, RefreshToken = refreshToken }; RequestSettings settings = new RequestSettings("<var>" + ConfigurationManager.AppSettings["google_app_name"].ToString() + "</var>", oAuthparameters); ContactsRequest cr = new ContactsRequest(settings); ContactsQuery query = new ContactsQuery(ContactsQuery.CreateContactsUri("default")); query.NumberToRetrieve = 5000; Feed <Contact> feed = cr.Get <Contact>(query); StringBuilder sb = new StringBuilder(); int i = 1; List <ContactDetail> contactDetails = new List <ContactDetail>(); foreach (Contact entry in feed.Entries) { ContactDetail contact = new ContactDetail { Name = entry.Title.ToString(), EmailAddress1 = entry.Emails.Count >= 1 ? entry.Emails[0].Address : "", EmailAddress2 = entry.Emails.Count >= 2 ? entry.Emails[1].Address : "", Phone = entry.Phonenumbers.Count >= 1 ? entry.Phonenumbers[0].Value : "", Address = entry.PostalAddresses.Count >= 1 ? entry.PostalAddresses[0].FormattedAddress : "" //Details = entry.Content.Content }; contactDetails.Add(contact); } /*End*/ return(contactDetails); }
public async Task <User> GetAccessToken(string code) { string clientId = "654449040707-68osetc7oe7jgbrhi9gqs81abg1q6l72.apps.googleusercontent.com"; string clientSecret = "PnMvDLoP4qQg_Rnti0TmfpH8"; string redirect_uri = "https://localhost:5001/api/Authentication/getGoogleToken"; var content = new StringContent ( "code=" + code + "&client_id=" + clientId + "&client_secret=" + clientSecret + "&redirect_uri=" + redirect_uri + "&grant_type=" + "authorization_code" ); content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded"); string accessToken = string.Empty; using (var client = new HttpClient()) { HttpResponseMessage response = null; response = await client.PostAsync("https://www.googleapis.com/oauth2/v3/token", content); if (response.StatusCode == HttpStatusCode.OK) { var result = await response.Content.ReadAsStringAsync(); GooglePlusAccessToken serStatus = JsonConvert.DeserializeObject <GooglePlusAccessToken>(result); if (serStatus != null) { accessToken = serStatus.access_token; } } } if (!String.IsNullOrWhiteSpace(accessToken)) { User user = await GetGooglePlusUserData(accessToken); return(user); } return(null); }
public List <GmailContacts> GetContacts(GooglePlusAccessToken serStatus) { string google_client_id = "936649599657-s9akus1uv18lo7b103ji7t3cu1ljlfjb.apps.googleusercontent.com"; string google_client_sceret = "w5nmQnac-A2gBLR8dh2YWGqk"; /*Get Google Contacts From Access Token and Refresh Token*/ // string refreshToken = serStatus.refresh_token; string accessToken = serStatus.access_token; string scopes = "https://www.google.com/m8/feeds/contacts/default/full/"; OAuth2Parameters oAuthparameters = new OAuth2Parameters() { ClientId = google_client_id, ClientSecret = google_client_sceret, RedirectUri = "http://" + Global.MainLink + "/MyContact/AddGoogleContacts", Scope = scopes, AccessToken = accessToken, // RefreshToken = refreshToken }; RequestSettings settings = new RequestSettings("Group Gifts ", oAuthparameters); ContactsRequest cr = new ContactsRequest(settings); ContactsQuery query = new ContactsQuery(ContactsQuery.CreateContactsUri("default")); query.NumberToRetrieve = 5000; Feed <Contact> ContactList = cr.GetContacts(); List <GmailContacts> olist = new List <GmailContacts>(); foreach (Contact contact in ContactList.Entries) { foreach (EMail email in contact.Emails) { GmailContacts gc = new GmailContacts(); gc.EmailID = email.Address; var a = contact.Name.FullName; olist.Add(gc); } } return(olist); }
public void GetContacts(GooglePlusAccessToken serStatus) { string google_client_id = "yourclientId"; string google_client_sceret = "yourclientSecret"; /*Get Google Contacts From Access Token and Refresh Token*/ string refreshToken = serStatus.refresh_token; string accessToken = serStatus.access_token; string scopes = "https://www.google.com/m8/feeds/contacts/default/full/"; OAuth2Parameters oAuthparameters = new OAuth2Parameters() { ClientId = google_client_id, ClientSecret = google_client_sceret, RedirectUri = "http://www.yogihosting.com/TutorialCode/GoogleContactAPI/google-contact-api.aspx", Scope = scopes, AccessToken = accessToken, RefreshToken = refreshToken }; RequestSettings settings = new RequestSettings("<var>YOUR_APPLICATION_NAME</var>", oAuthparameters); ContactsRequest cr = new ContactsRequest(settings); ContactsQuery query = new ContactsQuery(ContactsQuery.CreateContactsUri("default")); query.NumberToRetrieve = 5000; Feed <Contact> feed = cr.Get <Contact>(query); StringBuilder sb = new StringBuilder(); int i = 1; foreach (Contact entry in feed.Entries) { foreach (EMail email in entry.Emails) { sb.Append(i + " ").Append(email.Address).Append("<br/>"); i++; } } /*End*/ dataDiv.InnerHtml = sb.ToString(); }
public async Task <bool> AddContacts(GooglePlusAccessToken serStatus, List <TextValue> objContacts) { /*Get Google Contacts From Access Token and Refresh Token*/ string refreshToken = serStatus.refresh_token; string accessToken = serStatus.access_token; string scopes = "https://www.google.com/m8/feeds/contacts/default/full/"; OAuth2Parameters oAuthparameters = new OAuth2Parameters() { Scope = scopes, AccessToken = accessToken, RefreshToken = refreshToken }; RequestSettings settings = new RequestSettings("<var>YOUR_APPLICATION_NAME</var>", oAuthparameters); ContactsRequest cr = new ContactsRequest(settings); foreach (var contact in objContacts) { await SynchContact(cr, contact.Text, contact.Value); } return(true); }
public Feed <Contact> GetContacts(GooglePlusAccessToken serStatus) { string refreshToken = serStatus.refresh_token; string accessToken = serStatus.access_token; string scopes = "https://www.google.com/m8/feeds/contacts/default/full/"; OAuth2Parameters oAuthparameters = new OAuth2Parameters() { RedirectUri = "http://localhost:2216/index.aspx", Scope = scopes, AccessToken = accessToken, RefreshToken = refreshToken }; RequestSettings settings = new RequestSettings("<var>YOUR_APPLICATION_NAME</var>", oAuthparameters); ContactsRequest cr = new ContactsRequest(settings); ContactsQuery query = new ContactsQuery(ContactsQuery.CreateContactsUri("default")); query.NumberToRetrieve = 5000; Feed <Contact> feed = cr.Get <Contact>(query); return(feed); }
public void GetContacts(GooglePlusAccessToken serStatus) { string google_client_id = "yourclientId"; string google_client_sceret = "yourclientSecret"; /*Get Google Contacts From Access Token and Refresh Token*/ string refreshToken = serStatus.refresh_token; string accessToken = serStatus.access_token; string scopes = "https://www.google.com/m8/feeds/contacts/default/full/"; OAuth2Parameters oAuthparameters = new OAuth2Parameters() { ClientId = google_client_id, ClientSecret = google_client_sceret, RedirectUri = "http://www.yogihosting.com/TutorialCode/GoogleContactAPI/google-contact-api.aspx", Scope = scopes, AccessToken = accessToken, RefreshToken = refreshToken }; RequestSettings settings = new RequestSettings("<var>YOUR_APPLICATION_NAME</var>", oAuthparameters); ContactsRequest cr = new ContactsRequest(settings); ContactsQuery query = new ContactsQuery(ContactsQuery.CreateContactsUri("default")); query.NumberToRetrieve = 5000; Feed<Contact> feed = cr.Get<Contact>(query); StringBuilder sb = new StringBuilder(); int i = 1; foreach (Contact entry in feed.Entries) { foreach (EMail email in entry.Emails) { sb.Append(i + " ").Append(email.Address).Append("<br/>"); i++; } } /*End*/ dataDiv.InnerHtml = sb.ToString(); }
public void GetContacts(GooglePlusAccessToken serStatus) { /*Get Google Contacts From Access Token and Refresh Token*/ string refreshToken = serStatus.refresh_token; string accessToken = serStatus.access_token; string scopes = "https://www.google.com/m8/feeds/contacts/default/full/"; OAuth2Parameters oAuthparameters = new OAuth2Parameters() { Scope = scopes, AccessToken = accessToken, RefreshToken = refreshToken }; RequestSettings settings = new RequestSettings("<var>YOUR_APPLICATION_NAME</var>", oAuthparameters); ContactsRequest cr = new ContactsRequest(settings); ContactsQuery query = new ContactsQuery(ContactsQuery.CreateContactsUri("default")); query.NumberToRetrieve = 5000; Feed <Contact> feed = cr.Get <Contact>(query); StringBuilder sb = new StringBuilder(); int i = 1; foreach (Contact entry in feed.Entries) { foreach (EMail email in entry.Emails) { sb.Append("<span>" + i + ". </span>").Append(email.Address) .Append("<br/>"); i++; } } /*End*/ //dataDiv.InnerHtml = sb.ToString(); }
protected void Page_Load(object sender, EventArgs e) { if (Session.Contents.Count > 0) { if (Session["loginWith"] != null) { if (Session["loginWith"].ToString() == "google") { try { var url = Request.Url.Query; if (url != "") { string queryString = url.ToString(); char[] delimiterChars = { '=' }; string[] words = queryString.Split(delimiterChars); string code = words[1]; if (code != null) { //Gán Token đuợc yêu cầu HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token"); webRequest.Method = "POST"; Parameters = "code=" + code + "&client_id=" + googleplus_client_id + "&client_secret=" + googleplus_client_sceret + "&redirect_uri=" + googleplus_redirect_url + "&grant_type=authorization_code"; byte[] byteArray = Encoding.UTF8.GetBytes(Parameters); webRequest.ContentType = "application/x-www-form-urlencoded"; webRequest.ContentLength = byteArray.Length; Stream postStream = webRequest.GetRequestStream(); // Thêm dữ liệu tới trang web yêu cầu postStream.Write(byteArray, 0, byteArray.Length); postStream.Close(); //Đọc dữ liệu WebResponse response = webRequest.GetResponse(); postStream = response.GetResponseStream(); StreamReader reader = new StreamReader(postStream); string responseFromServer = reader.ReadToEnd(); GooglePlusAccessToken serStatus = JsonConvert.DeserializeObject <GooglePlusAccessToken>(responseFromServer); if (serStatus != null) { string accessToken = string.Empty; accessToken = serStatus.access_token; if (!string.IsNullOrEmpty(accessToken)) { // Gán dữ liệu nếu đăng nhập thành công getgoogleplususerdataSer(accessToken); } else { } } else { } } else { } } } catch (Exception ex) { //throw new Exception(ex.Message, ex); Response.Redirect("/"); } } } } }
private void getRt() { try { var url = Request.Url.Query; if (url != "") { string queryString = url.ToString(); char[] delimiterChars = { '=' }; string[] words = queryString.Split(delimiterChars); string code = words[1]; if (code != null) { //get the access token HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token"); webRequest.Method = "POST"; //string Parameters = "code=" + code + "&client_id=590319039890-ch2k0tvs7749rgf8vjp3eeep24n5hj5s.apps.googleusercontent.com&client_secret=qOHQHR2ch1CgFsCNhttul8yZ&redirect_uri=http://localhost:1049/site1/googleReturn.aspx&grant_type=authorization_code"; string Parameters = "code=" + code + "&client_id=645346265016-09bade801ee8s618m5ng54cn9b0pi8qt.apps.googleusercontent.com&client_secret=Ozhmx_tUT9-xnraibBctCF8B&redirect_uri=http://localhost:17017/LoginSuccess.aspx&grant_type=authorization_code"; byte[] byteArray = Encoding.UTF8.GetBytes(Parameters); webRequest.ContentType = "application/x-www-form-urlencoded"; webRequest.ContentLength = byteArray.Length; Stream postStream = webRequest.GetRequestStream(); // Add the post data to the web request postStream.Write(byteArray, 0, byteArray.Length); postStream.Close(); WebResponse response = webRequest.GetResponse(); postStream = response.GetResponseStream(); StreamReader reader = new StreamReader(postStream); string responseFromServer = reader.ReadToEnd(); GooglePlusAccessToken serStatus = JsonConvert.DeserializeObject <GooglePlusAccessToken>(responseFromServer); if (serStatus != null) { string accessToken = string.Empty; accessToken = serStatus.access_token; if (!string.IsNullOrEmpty(accessToken)) { // This is where you want to add the code if login is successful. getgoogleplususerdataSer(accessToken); } else { } } else { } } else { } } } catch (Exception ex) { //throw new Exception(ex.Message, ex); // Response.Redirect("index.aspx"); } }
protected void Page_Load(object sender, EventArgs e) { string scopes = "https://www.googleapis.com/auth/calendar"; //if (string.IsNullOrEmpty(redirectUri)) //{ // redirectUri = "urn:ietf:wg:oauth:2.0:oob"; //} string oauth = string.Format("https://accounts.google.com/o/oauth2/auth?client_id={0}&redirect_uri={1}&scope={2}&response_type=code", googleplus_client_id, googleplus_redirect_url, scopes); try { var url = oauth; if (url != "") { string queryString = url.ToString(); char[] delimiterChars = { '=' }; string[] words = queryString.Split(delimiterChars); string code = words[1]; if (code != null) { //get the access token HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token"); webRequest.Method = "POST"; Parameters = "code=" + code + "&client_id=" + googleplus_client_id + "&client_secret=" + googleplus_client_secret + "&redirect_uri=" + googleplus_redirect_url + "&grant_type=authorization_code"; byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(Parameters); webRequest.ContentType = "application/x-www-form-urlencoded"; webRequest.ContentLength = byteArray.Length; Stream postStream = webRequest.GetRequestStream(); // Add the post data to the web request postStream.Write(byteArray, 0, byteArray.Length); postStream.Close(); WebResponse response = webRequest.GetResponse(); postStream = response.GetResponseStream(); StreamReader reader = new StreamReader(postStream); string responseFromServer = reader.ReadToEnd(); GooglePlusAccessToken serStatus = JsonConvert.DeserializeObject <GooglePlusAccessToken>(responseFromServer); if (serStatus != null) { string accessToken = string.Empty; accessToken = serStatus.access_token; if (!string.IsNullOrEmpty(accessToken)) { // This is where you want to add the code if login is successful. // getgoogleplususerdataSer(accessToken); } } } } } catch (Exception ex) { //throw new Exception(ex.Message, ex); Response.Redirect("index.aspx"); } }
public void CreateEvent(GooglePlusAccessToken serStatus) { UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync( new ClientSecrets { ClientId = "295167635687-bhugb57e9u7tg46ieolrbs636silvljj.apps.googleusercontent.com", ClientSecret = "CwUAg3ydCCE1dnA6OshbOJfX", }, new[] { CalendarService.Scope.Calendar }, "user", CancellationToken.None).Result; credential.Token = new Google.Apis.Auth.OAuth2.Responses.TokenResponse(); credential.Token.AccessToken = serStatus.access_token; credential.Token.ExpiresInSeconds = serStatus.expires_in; credential.Token.RefreshToken = serStatus.refresh_token; credential.Token.TokenType = serStatus.token_type; var service = new CalendarService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "ProjectMeet", }); DateTime start = DateTime.Now; Google.Apis.Calendar.v3.Data.Event calenderEvent = new Google.Apis.Calendar.v3.Data.Event(); calenderEvent.Summary = "prueba"; //calenderEvent.Description = summary; //calenderEvent.Location = summary; calenderEvent.Start = new Google.Apis.Calendar.v3.Data.EventDateTime { //DateTime = new DateTime(2018, 1, 20, 19, 00, 0) DateTime = start, TimeZone = "America/Mexico_City" }; calenderEvent.End = new Google.Apis.Calendar.v3.Data.EventDateTime { //DateTime = new DateTime(2018, 4, 30, 23, 59, 0) DateTime = start.AddHours(1), TimeZone = "America/Mexico_City" }; //calenderEvent.Creator = new Google.Apis.Calendar.v3.Data.Event.CreatorData(); //calenderEvent.Creator.DisplayName = "Jesús Torres"; //calenderEvent.Creator.Email = "*****@*****.**"; calenderEvent.Status = "confirmed"; calenderEvent.Visibility = "public"; calenderEvent.Description = "EjemploDescripcion"; var Recurrence = new String[] { "RRULE:FREQ=DAILY;COUNT=2" }; calenderEvent.Recurrence = Recurrence; calenderEvent.ConferenceData = new Google.Apis.Calendar.v3.Data.ConferenceData(); calenderEvent.ConferenceData.CreateRequest = new Google.Apis.Calendar.v3.Data.CreateConferenceRequest(); calenderEvent.ConferenceData.CreateRequest.ConferenceSolutionKey = new Google.Apis.Calendar.v3.Data.ConferenceSolutionKey(); calenderEvent.ConferenceData.CreateRequest.ConferenceSolutionKey.Type = "hangoutsMeet"; calenderEvent.ConferenceData.CreateRequest.Status = new Google.Apis.Calendar.v3.Data.ConferenceRequestStatus(); calenderEvent.ConferenceData.CreateRequest.Status.StatusCode = "success"; calenderEvent.ConferenceData.CreateRequest.RequestId = "123456789100"; var pm = new Dictionary <string, string> { { "conferenceDataVersion", "1" } }; List <ConferenceParametersAddOnParameters> listParameters = new List <ConferenceParametersAddOnParameters>(); //listParameters.Add(new ConferenceParametersAddOnParameters { Parameters = { }, ETag = "1" }); ConferenceParameters objParam = new ConferenceParameters(); objParam.AddOnParameters = new ConferenceParametersAddOnParameters(); objParam.AddOnParameters.Parameters = pm; objParam.ETag = "1"; calenderEvent.ConferenceData.Parameters = new ConferenceParameters(); calenderEvent.ConferenceData.Parameters.AddOnParameters = new ConferenceParametersAddOnParameters(); calenderEvent.ConferenceData.Parameters.AddOnParameters.Parameters = pm; calenderEvent.ConferenceData.Parameters.AddOnParameters.ETag = "1"; calenderEvent.ConferenceData.ConferenceSolution = new Google.Apis.Calendar.v3.Data.ConferenceSolution(); calenderEvent.ConferenceData.ConferenceSolution.Key = new Google.Apis.Calendar.v3.Data.ConferenceSolutionKey(); calenderEvent.ConferenceData.ConferenceSolution.Key.Type = "hangoutsMeet"; List <EntryPoint> list = new System.Collections.Generic.List <Google.Apis.Calendar.v3.Data.EntryPoint>(); EntryPoint entry = new Google.Apis.Calendar.v3.Data.EntryPoint(); entry.EntryPointType = "video"; entry.AccessCode = "123456"; //list.Add(new Google.Apis.Calendar.v3.Data.EntryPoint { EntryPointType = "video" }); list.Add(entry); //EntryPoint entry = new Google.Apis.Calendar.v3.Data.EntryPoint(); //entry.EntryPointType = "video"; calenderEvent.ConferenceData.EntryPoints = list; try { String calendarId = "primary"; EventsResource.InsertRequest request = service.Events.Insert(calenderEvent, calendarId); Event createdEvent = request.Execute(); Console.WriteLine("Event created: {0}", createdEvent.HtmlLink); } catch (Exception ex) { } }
public async Task <ActionResult> CallBack(string state, string code) { ViewBag.EmailError = false; string path = ""; bool writeLog = false; if (System.Configuration.ConfigurationManager.AppSettings["DebugLogFile"] != null) { if (string.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["DebugLogFile"].ToString()) == false) { path = System.Configuration.ConfigurationManager.AppSettings["DebugLogFile"].ToString(); writeLog = true; } } KaribouAlpha.DAL.KaribouAlphaContext db = new DAL.KaribouAlphaContext(); GoogleAuthClient googleClient = db.GoogleAuthClients.SingleOrDefault(_google => _google.Active); if (googleClient == null || (!string.IsNullOrEmpty(code) && code.ToLower() == "error")) { if (writeLog && googleClient == null) { System.IO.File.AppendAllText(path, Environment.NewLine + System.DateTime.Now.ToString() + " google client is not setup.."); } else if (writeLog) { System.IO.File.AppendAllText(path, Environment.NewLine + System.DateTime.Now.ToString() + "user may be declined code is error..."); } ViewBag.EmailError = true; return(View()); } try { if (writeLog) { System.IO.File.AppendAllText(path, Environment.NewLine + System.DateTime.Now.ToString() + "- google - start getting token from code...."); } System.Net.HttpWebRequest webRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create("https://accounts.google.com/o/oauth2/token"); webRequest.Method = "POST"; string parameters = "code=" + code + "&client_id=" + googleClient.ClientId + "&client_secret=" + googleClient.ClientSecret + "&redirect_uri=" + googleClient.RedirectUrl + "&grant_type=authorization_code"; byte[] byteArray = Encoding.UTF8.GetBytes(parameters); webRequest.ContentType = "application/x-www-form-urlencoded"; webRequest.ContentLength = byteArray.Length; Stream postStream = webRequest.GetRequestStream(); postStream.Write(byteArray, 0, byteArray.Length); postStream.Close(); WebResponse response = webRequest.GetResponse(); postStream = response.GetResponseStream(); StreamReader reader = new StreamReader(postStream); string responseFromServer = reader.ReadToEnd(); GooglePlusAccessToken responseToken = JsonConvert.DeserializeObject <GooglePlusAccessToken>(responseFromServer); if (responseToken != null) { string accessToken = string.Empty; accessToken = responseToken.access_token; if (!string.IsNullOrEmpty(accessToken)) { Task <GoogleUserOutputData> data = GetGoogleUserInfo(accessToken); if (data != null && data.Result != null) { User user = await this._authenticationRepository.FindAsync(new Microsoft.AspNet.Identity.UserLoginInfo("Google", data.Result.id)); bool hasRegistered = user != null; bool hasCervitUser = false; long existingCervitUserId = this._authenticationRepository.FindUserExists(data.Result.email); hasCervitUser = (existingCervitUserId > 0); if (hasRegistered) { hasCervitUser = false; } ViewBag.hascervituser = hasCervitUser.ToString(); ViewBag.haslocalaccount = hasRegistered.ToString(); ViewBag.provider = "Google"; ViewBag.external_user_name = data.Result.id; ViewBag.external_access_token = accessToken; ViewBag.email = data.Result.email; } } } } catch (Exception ex) { if (writeLog) { System.IO.File.AppendAllText(path, Environment.NewLine + System.DateTime.Now.ToString() + "- google - error during getting token from code...." + ex.ToString()); } ViewBag.EmailError = true; } return(View()); }
public ActionResult GoogleLogin() { string googleplus_client_id = "936649599657-s9akus1uv18lo7b103ji7t3cu1ljlfjb.apps.googleusercontent.com"; string googleplus_client_sceret = "w5nmQnac-A2gBLR8dh2YWGqk"; string googleplus_redirect_url = "http://" + Global.MainLink + "/Account/GoogleLogin"; string Parameters; var url = Request.Url.Query; if (url != "") { string queryString = url.ToString(); char[] delimiterChars = { '=' }; string[] words = queryString.Split(delimiterChars); string code = words[1]; if (code != null) { //get the access token HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token"); webRequest.Method = "POST"; Parameters = "code=" + code + "&client_id=" + googleplus_client_id + "&client_secret=" + googleplus_client_sceret + "&redirect_uri=" + googleplus_redirect_url + "&grant_type=authorization_code"; byte[] byteArray = Encoding.UTF8.GetBytes(Parameters); webRequest.ContentType = "application/x-www-form-urlencoded"; webRequest.ContentLength = byteArray.Length; Stream postStream = webRequest.GetRequestStream(); // Add the post data to the web request postStream.Write(byteArray, 0, byteArray.Length); postStream.Close(); WebResponse response = webRequest.GetResponse(); postStream = response.GetResponseStream(); StreamReader reader = new StreamReader(postStream); string responseFromServer = reader.ReadToEnd(); GooglePlusAccessToken serStatus = JsonConvert.DeserializeObject <GooglePlusAccessToken>(responseFromServer); if (serStatus != null) { string accessToken = string.Empty; accessToken = serStatus.access_token; if (!string.IsNullOrEmpty(accessToken)) { string JSONDATA = ""; HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(@"https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=" + accessToken); httpWebRequest.Method = "GET"; httpWebRequest.ContentType = @"application/json; charset=utf-8"; var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse(); using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) { JSONDATA = streamReader.ReadToEnd(); } var json_serializer = new JavaScriptSerializer(); GooglePlusLogin Profile = JsonConvert.DeserializeObject <GooglePlusLogin>(JSONDATA); SocialRegistration obj = new SocialRegistration(); obj.Id = Profile.id; obj.Email_Id = string.IsNullOrEmpty(Profile.email)?Profile.id + "@BAG.com": Profile.email; obj.First_Name = Profile.name; obj.Phone_No = string.Empty; obj.Profile_Pic = Profile.picture; AccountsBLL obll = new AccountsBLL(); Login status = obll.Registration_ThirdParty(obj); if (status != null) { if (!string.IsNullOrEmpty(status.Id)) { Session["UserId"] = status.Id; Session["UserName"] = status.First_Name; UpdateEventInvites(); return(RedirectToAction("Index", "Dashboard")); } } else { return(RedirectToAction("Index", "Account")); } } else { } } else { } } else { } } return(View("Index")); }