public string Get_VideoCategories(string accesstoken, string part) { oAuthTokenYoutube objoAuthTokenYoutube = new oAuthTokenYoutube(_clientId, _clientSecret, _redirectUrl); //https://www.googleapis.com/youtube/v3/videoCategories?part=snippet&hl=en_US®ionCode=IN&key={YOUR_API_KEY} string RequestUrl = "https://www.googleapis.com/youtube/v3/videoCategories?part=" + part + "&hl=en_US®ionCode=IN&key=" + accesstoken; Uri path = new Uri(RequestUrl); string[] header = { "Authorization", "X-JavaScript-User-Agent" }; string[] val = { "Bearer " + accesstoken, "Google APIs Explorer" }; string response = string.Empty; try { response = objoAuthTokenYoutube.WebRequestHeader(path, header, val, Socioboard.GoogleLib.Authentication.oAuthToken.Method.GET.ToString()); //if (!response.StartsWith("[")) // response = "[" + response + "]"; } catch (Exception Err) { Console.Write(Err.StackTrace); } return(response); }
public string replyToComment(string refreshtoken, string parentid, string commentText) { oAuthTokenYoutube objoAuthTokenYoutube = new oAuthTokenYoutube(_clientId, _clientSecret, _redirectUrl); oAuthToken objoauth = new oAuthToken(_clientId, _clientSecret, _redirectUrl); string accesstoken_jdata = objoauth.GetAccessToken(refreshtoken); JObject JData = JObject.Parse(accesstoken_jdata); string accesstoken = JData["access_token"].ToString(); commentText = commentText.Replace("\\n", "######2525").Replace("\\", "\\\\").Replace("\"", "\\\"").Replace("######2525", "\\n");; string RequestUrl = "https://www.googleapis.com/youtube/v3/comments?part=snippet&key=" + accesstoken + "&alt=json"; string postdata = "{\"snippet\":{\"parentId\":\"" + parentid + "\",\"textOriginal\":\"" + commentText + "\"}}"; Uri path = new Uri(RequestUrl); string[] header = { "Authorization", "X-JavaScript-User-Agent" }; string[] val = { "Bearer " + accesstoken, "Google APIs Explorer" }; string response = string.Empty; try { response = objoAuthTokenYoutube.Post_WebRequest(Socioboard.GoogleLib.Authentication.oAuthToken.Method.POST, RequestUrl, postdata, header, val); } catch (Exception Err) { Console.Write(Err.StackTrace); } return(response); }
public string Get_PlaylistItems_List(string accesstoken, string part, string UploadId) { oAuthTokenYoutube objoAuthTokenYoutube = new oAuthTokenYoutube(_clientId, _clientSecret, _redirectUrl); //string RequestUrl = "https://www.googleapis.com/youtube/v3/playlistItems?part=" + part + "&maxResults=50&playlistId=" + UploadId + "&key=" + accesstoken; string RequestUrl = "https://www.googleapis.com/youtube/v3/playlistItems?part=" + part + "&maxResults=50&playlistId=" + UploadId + "&key=" + accesstoken; Uri path = new Uri(RequestUrl); string[] header = { "Authorization", "X-JavaScript-User-Agent" }; string[] val = { "Bearer " + accesstoken, "Google APIs Explorer" }; string response = string.Empty; try { response = objoAuthTokenYoutube.WebRequestHeader(path, header, val, Authentication.oAuthToken.Method.GET.ToString()); //if (!response.StartsWith("[")) // response = "[" + response + "]"; } catch (Exception Err) { Console.Write(Err.StackTrace); } return(response); }
public string Get_Channel_List_serarch(string accesstoken, string search) { oAuthTokenYoutube objoAuthTokenYoutube = new oAuthTokenYoutube(_clientId, _clientSecret, _redirectUrl); // string RequestUrl = "https://www.googleapis.com/youtube/v3/channels?part=" + part + "&id=" + Id + "&key=" + accesstoken; string RequestUrl = "https://www.googleapis.com/plus/v1/activities?query=salman&key=" + accesstoken; Uri path = new Uri(RequestUrl); string[] header = { "Authorization", "X-JavaScript-User-Agent" }; string[] val = { "Bearer " + accesstoken, "Google APIs Explorer" }; string response = string.Empty; try { response = objoAuthTokenYoutube.WebRequestHeader(path, header, val, Socioboard.GoogleLib.Authentication.oAuthToken.Method.GET.ToString()); //if (!response.StartsWith("[")) // response = "[" + response + "]"; } catch (Exception Err) { Console.Write(Err.StackTrace); } return(response); }
public string Get_Activities(string accesstoken, string part, string channelId, int maxResults) { //https://www.googleapis.com/youtube/v3/activities?part=snippet&channelId=UCBR8-60-B28hp2BmDPdntcQ&maxResults=50&key={YOUR_API_KEY} oAuthTokenYoutube objoAuthTokenYoutube = new oAuthTokenYoutube(_clientId, _clientSecret, _redirectUrl); string RequestUrl = "https://www.googleapis.com/youtube/v3/activities?part=" + part + "&channelId=" + channelId + "&maxResults=" + maxResults + "&key=" + accesstoken; Uri path = new Uri(RequestUrl); string[] header = { "Authorization", "X-JavaScript-User-Agent" }; string[] val = { "Bearer " + accesstoken, "Google APIs Explorer" }; string response = string.Empty; try { response = objoAuthTokenYoutube.WebRequestHeader(path, header, val, Authentication.oAuthToken.Method.GET.ToString()); //if (!response.StartsWith("[")) // response = "[" + response + "]"; } catch (Exception Err) { Console.Write(Err.StackTrace); } return(response); }
public string RejectAComment(string refreshtoken, string commmentId) { oAuthTokenYoutube objoAuthTokenYoutube = new oAuthTokenYoutube(_clientId, _clientSecret, _redirectUrl); oAuthToken objoauth = new oAuthToken(_clientId, _clientSecret, _redirectUrl); string accesstoken_jdata = objoauth.GetAccessToken(refreshtoken); JObject JData = JObject.Parse(accesstoken_jdata); string accesstoken = JData["access_token"].ToString(); string RequestUrl = "https://www.googleapis.com/youtube/v3/comments/setModerationStatus?id=" + commmentId + "&moderationStatus=rejected&key=" + accesstoken + "&alt=json"; string postdata = ""; Uri path = new Uri(RequestUrl); string[] header = { "Authorization", "X-JavaScript-User-Agent" }; string[] val = { "Bearer " + accesstoken, "Google APIs Explorer" }; string response = string.Empty; try { response = objoAuthTokenYoutube.Post_WebRequest(Socioboard.GoogleLib.Authentication.oAuthToken.Method.POST, RequestUrl, postdata, header, val); } catch (Exception Err) { Console.Write(Err.StackTrace); } return(response); }
public string Get_YAnalytics_ChannelId(string channelId, string acctoken, string fromDate, string toDate) { oAuthTokenYoutube objoAuthTokenYoutube = new oAuthTokenYoutube(_clientId, _clientSecret, _redirectUrl); string accesstoken = objoAuthTokenYoutube.GetAccessToken(acctoken); JObject JData = JObject.Parse(accesstoken); accesstoken = JData["access_token"].ToString(); string RequestUrl = "https://www.googleapis.com/youtube/analytics/v1/reports?ids=channel%3D%3D" + channelId + "&start-date=" + fromDate + "&end-date=" + toDate + "&metrics=subscribersGained%2Cviews%2Clikes%2Ccomments%2Cshares%2Cdislikes%2CsubscribersLost%2CaverageViewDuration%2CestimatedMinutesWatched%2CannotationClickThroughRate%2CannotationCloseRate&dimensions=day%2Cchannel&key=" + accesstoken; Uri path = new Uri(RequestUrl); string[] header = { "Authorization", "X-JavaScript-User-Agent" }; string[] val = { "Bearer " + accesstoken, "Google APIs Explorer" }; string response = string.Empty; try { response = objoAuthTokenYoutube.WebRequestHeader(path, header, val, Socioboard.GoogleLib.Authentication.oAuthToken.Method.GET.ToString()); } catch (Exception Err) { Console.Write(Err.StackTrace); } return(response); }
private void UpdateYoutubeFeeds(YoutubeChannel youtubeChannel) { if (youtubeChannel.LastUpdate.AddHours(1) <= DateTime.UtcNow) { if (youtubeChannel.IsActive) { var objoAuthTokenYtubes = new oAuthTokenYoutube(AppSettings.googleClientId, AppSettings.googleClientSecret, AppSettings.googleRedirectionUrl); var objToken = new oAuthToken(AppSettings.googleClientId, AppSettings.googleClientSecret, AppSettings.googleRedirectionUrl); var objVideo = new Video(AppSettings.googleClientId, AppSettings.googleClientSecret, AppSettings.googleRedirectionUrl); var databaseRepository = new DatabaseRepository(); ParseAndUpdateAccountDetails(youtubeChannel, databaseRepository, objVideo); YoutubeFeedsfetch.ParseAndUpdateFeeds(youtubeChannel.YtubeChannelId); } } }
public string GetYoutubeChannelVideos(string userid, string profileid) { string ret = string.Empty; string strfinaltoken = string.Empty; string channelDetails = string.Empty; Domain.Socioboard.Domain.YoutubeAccount objYoutubeAccount = objYoutubeAccountRepository.getYoutubeAccountDetailsById(profileid, Guid.Parse(userid)); Domain.Socioboard.Domain.YoutubeChannel objYoutubeChannel = objYoutubeChannelRepository.getYoutubeChannelDetailsById(profileid, Guid.Parse(userid)); oAuthTokenYoutube objoAuthTokenYoutube = new oAuthTokenYoutube(); string finaltoken = objoAuthTokenYoutube.GetAccessToken(objYoutubeAccount.Refreshtoken); JObject objArray = JObject.Parse(finaltoken); //foreach (var item in objArray) //{ try { strfinaltoken = objArray["access_token"].ToString(); // break; } catch (Exception ex) { Console.WriteLine(ex.StackTrace); } //} PlaylistItems objPlaylistItems = new PlaylistItems(); try { channelDetails = objPlaylistItems.Get_PlaylistItems_List(strfinaltoken, GlobusGooglePlusLib.Authentication.oAuthTokenYoutube.Parts.snippet.ToString(), objYoutubeChannel.Uploadsid); } catch (Exception ex) { } return(channelDetails); }
/// <Get_Subscriptions_List> /// /// </summary> /// <param name="accesstoken">true</param> /// <param name="part">snippet</param> /// <returns></returns> public string Get_Subscriptions_List(string accesstoken, string part) { oAuthTokenYoutube objoAuthTokenYoutube = new oAuthTokenYoutube(_clientId, _clientSecret, _redirectUrl); string RequestUrl = "https://www.googleapis.com/youtube/v3/subscriptions?part=" + part + "&mine=true&maxResults=50&key=" + accesstoken; Uri path = new Uri(RequestUrl); string[] header = { "Authorization", "X-JavaScript-User-Agent" }; string[] val = { "Bearer " + accesstoken, "Google APIs Explorer" }; string response = string.Empty; try { response = objoAuthTokenYoutube.WebRequestHeader(path, header, val, Socioboard.GoogleLib.Authentication.oAuthToken.Method.GET.ToString()); } catch (Exception Err) { Console.Write(Err.StackTrace); } return(response); }
public string Get_All_Activities(string accesstoken, oAuthTokenYoutube.Parts part, bool mine, int maxResults) { oAuthTokenYoutube objoAuthTokenYoutube = new oAuthTokenYoutube(_clientId, _clientSecret, _redirectUrl); string RequestUrl = "https://www.googleapis.com/youtube/v3/activities?part=" + part.ToString() + "&mine=" + mine.ToString() + "&maxResults=50&key=" + accesstoken; Uri path = new Uri(RequestUrl); string[] header = { "Authorization", "X-JavaScript-User-Agent" }; string[] val = { "Bearer " + accesstoken, "Google APIs Explorer" }; string response = string.Empty; try { response = objoAuthTokenYoutube.WebRequestHeader(path, header, val, Authentication.oAuthToken.Method.GET.ToString()); } catch (Exception Err) { Console.Write(Err.StackTrace); } return(response); }
public string Get_VideoRating(string accesstoken, string videoId) { oAuthTokenYoutube objoAuthTokenYoutube = new oAuthTokenYoutube(_clientId, _clientSecret, _redirectUrl); string RequestUrl = "https://www.googleapis.com/youtube/v3/videos?id=" + videoId + "&key=" + accesstoken + "&part=snippet,statistics&fields=items(id,snippet,statistics)"; Uri path = new Uri(RequestUrl); string[] header = { "Authorization", "X-JavaScript-User-Agent" }; string[] val = { "Bearer " + accesstoken, "Google APIs Explorer" }; string response = string.Empty; try { response = objoAuthTokenYoutube.WebRequestHeader(path, header, val, Socioboard.GoogleLib.Authentication.oAuthToken.Method.GET.ToString()); } catch (Exception Err) { Console.Write(Err.StackTrace); } return(response); }
// include in the parameter value are snippet and status. public void Insert_Playlist(string accesstoken, string part, string playlistId, string videoId, string kind, string title, string description) { oAuthTokenYoutube _oAuthTokenYoutube = new oAuthTokenYoutube(_clientId, _clientSecret, _redirectUrl); string _RequestUrl = "https://www.googleapis.com/youtube/v3/activities?part=" + part + "&key=" + accesstoken; Uri path = new Uri(_RequestUrl); string[] _header = { "Authorization", "X-JavaScript-User-Agent" }; string[] _val = { "Bearer " + accesstoken, "Google APIs Explorer" }; string response = string.Empty; String _PostData = "{\"snippet\": {\"title\": \"" + title + "\",\"description\": \"" + description + "\"},\"status\": {\"privacyStatus\": \"public\"}}"; try { response = _oAuthTokenYoutube.Post_WebRequest(oAuthToken.Method.POST, _RequestUrl, _PostData, _header, _val); } catch (Exception Err) { Console.Write(Err.StackTrace); } }
public string GetYTVideoDetailList(string apiKey, string VideoId) { oAuthTokenYoutube objoAuthTokenYoutube = new oAuthTokenYoutube(_clientId, _clientSecret, _redirectUrl); string RequestUrl = "https://www.googleapis.com/youtube/v3/videos?part=snippet%2Cstatistics%2CcontentDetails%2Cstatus&id=" + VideoId + "&key=" + apiKey; Uri path = new Uri(RequestUrl); string[] header = { "token_type", "expires_in" }; string[] val = { "Bearer", "3600" }; string response = string.Empty; try { response = objoAuthTokenYoutube.WebRequestHeader(path, header, val); } catch (Exception Err) { Console.Write(Err.StackTrace); } return(response); }
public void AuthenticateYoutube(object sender, EventArgs e) { try { int profilecount = (int)Session["ProfileCount"]; int totalaccount = (int)Session["TotalAccount"]; if (profilecount < totalaccount) { oAuthTokenYoutube objoAuthTokenYoutube = new oAuthTokenYoutube(); Response.Redirect("https://accounts.google.com/o/oauth2/auth?client_id=" + ConfigurationManager.AppSettings["YtconsumerKey"] + "&redirect_uri=" + ConfigurationManager.AppSettings["Ytredirect_uri"] + "&scope=https://www.googleapis.com/auth/youtube+https://www.googleapis.com/auth/youtube.readonly+https://www.googleapis.com/auth/youtubepartner+https://www.googleapis.com/auth/youtubepartner-channel-audit+https://www.googleapis.com/auth/userinfo.email+https://www.googleapis.com/auth/userinfo.profile+https://www.googleapis.com/auth/plus.me&response_type=code&access_type=offline"); } else { //Response.Write("<script>SimpleMessageAlert('Change the Plan to Add More Accounts');</script>"); ScriptManager.RegisterStartupScript(this, GetType(), "showalert", "alert('Change the Plan to Add More Accounts');", true); } } catch (Exception ex) { logger.Error(ex.Message); } }
public string Get_Search_List_Page(string apiKey, string query, string page) { oAuthTokenYoutube objoAuthTokenYoutube = new oAuthTokenYoutube(_clientId, _clientSecret, _redirectUrl); string RequestUrl = "https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=50&pageToken=" + page + "&q=" + query + "&key=" + apiKey; Uri path = new Uri(RequestUrl); string[] header = { "token_type", "expires_in" }; string[] val = { "Bearer", "3600" }; string response = string.Empty; try { response = objoAuthTokenYoutube.WebRequestHeader(path, header, val); } catch (Exception Err) { Console.Write(Err.StackTrace); } return(response); }
public string Post_Comments_toVideo(string refreshtoken, string VideoId, string commentText) { oAuthTokenYoutube objoAuthTokenYoutube = new oAuthTokenYoutube(_clientId, _clientSecret, _redirectUrl); oAuthToken objoauth = new oAuthToken(_clientId, _clientSecret, _redirectUrl); string accesstoken_jdata = objoauth.GetAccessToken(refreshtoken); JObject JData = JObject.Parse(accesstoken_jdata); string accesstoken = JData["access_token"].ToString(); string RequestUrl = "https://content.googleapis.com/youtube/v3/commentThreads?part=snippet&key=" + accesstoken + "&alt=json"; string postdata = "{\"snippet\": {\"videoId\": \"" + VideoId + "\",\"topLevelComment\": {\"snippet\": {\"textOriginal\": \"" + commentText + "\"}}}}"; Uri path = new Uri(RequestUrl); string[] header = { "Authorization", "X-JavaScript-User-Agent", "Origin", "X-Origin" }; string[] val = { "Bearer " + accesstoken, "Google APIs Explorer", "https://content.googleapis.com", "https://developers.google.com" }; string response = string.Empty; try { response = objoAuthTokenYoutube.Post_WebRequest(Socioboard.GoogleLib.Authentication.oAuthToken.Method.POST, RequestUrl, postdata, header, val); } catch (Exception Err) { Console.Write(Err.StackTrace); } return(response); }
public string Get_CommentsRepliesBy_CmParentId(string cmParentId, string key) { oAuthTokenYoutube objoAuthTokenYoutube = new oAuthTokenYoutube(_clientId, _clientSecret, _redirectUrl); string RequestUrl = "https://www.googleapis.com/youtube/v3/comments?part=snippet&maxResults=100&parentId=" + cmParentId + "&key=" + key; Uri path = new Uri(RequestUrl); string[] header = { "token_type", "expires_in" }; string[] val = { "Bearer", "3600" }; string response = string.Empty; try { response = objoAuthTokenYoutube.WebRequestHeader(path, header, val); } catch (Exception Err) { Console.Write(Err.StackTrace); } return(response); }
public string GetChannelCmntCount(string accesstoken, string ChannelId) { oAuthTokenYoutube objoAuthTokenYoutube = new oAuthTokenYoutube(_clientId, _clientSecret, _redirectUrl); string RequestUrl = "https://www.googleapis.com/youtube/v3/commentThreads?part=snippet&channelId=" + ChannelId + "&maxResults=100&key=" + accesstoken; Uri path = new Uri(RequestUrl); string[] header = { "token_type", "expires_in" }; string[] val = { "Bearer", "3600" }; string response = string.Empty; try { response = objoAuthTokenYoutube.WebRequestHeader(path, header, val); } catch (Exception Err) { Console.Write(Err.StackTrace); } return(response); }
//Get All Activities // public string GetYtVideos(string ChannelId, string ApiKey) { oAuthTokenYoutube objoAuthTokenYoutube = new oAuthTokenYoutube(_clientId, _clientSecret, _redirectUrl); string RequestUrl = "https://www.googleapis.com/youtube/v3/activities?part=snippet%2CcontentDetails&channelId=" + ChannelId + "&maxResults=50&key=" + ApiKey; Uri path = new Uri(RequestUrl); string[] header = { "token_type", "expires_in" }; string[] val = { "Bearer", "3600" }; string response = string.Empty; try { response = objoAuthTokenYoutube.WebRequestHeader(path, header, val); } catch (Exception Err) { Console.Write(Err.StackTrace); } return(response); }
public string Get_Channel_info(string accesstoken) { oAuthTokenYoutube objoAuthTokenYoutube = new oAuthTokenYoutube(_clientId, _clientSecret, _redirectUrl); string RequestUrl = "https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + accesstoken; Uri path = new Uri(RequestUrl); string[] header = { "token_type", "expires_in" }; string[] val = { "Bearer", "3600" }; string response = string.Empty; try { response = objoAuthTokenYoutube.WebRequestHeader(path, header, val); } catch (Exception Err) { Console.Write(Err.StackTrace); } return(response); }
public string AddYoutubeAccountwithLogin(string client_id, string client_secret, string redirect_uri, string UserId, string GroupId, string access_token) { #region Local variables Inisitalisation string ret = string.Empty; string objRefresh = string.Empty; string refreshToken = string.Empty; oAuthTokenYoutube ObjoAuthTokenYoutube = new oAuthTokenYoutube(); oAuthToken objToken = new oAuthToken(); Domain.Socioboard.Domain.YoutubeAccount objYoutubeAccount = new Domain.Socioboard.Domain.YoutubeAccount(); Domain.Socioboard.Domain.YoutubeChannel objYoutubeChannel; YoutubeChannelRepository objYoutubeChannelRepository = new YoutubeChannelRepository(); YoutubeAccountRepository objYoutubeAccountRepository = new YoutubeAccountRepository(); #endregion #region Get user Profile and Add Youtube Account JArray userinfo = new JArray(); try { userinfo = objToken.GetUserInfo("me", access_token.ToString()); } catch (Exception ex) { } foreach (var itemEmail in userinfo) { try { objYoutubeAccount.Id = Guid.NewGuid(); objYoutubeAccount.Ytuserid = itemEmail["id"].ToString(); objYoutubeAccount.Emailid = itemEmail["email"].ToString(); try { objYoutubeAccount.Ytusername = itemEmail["given_name"].ToString(); } catch (Exception ex) { objYoutubeAccount.Ytusername = itemEmail["name"].ToString(); } objYoutubeAccount.Ytprofileimage = itemEmail["picture"].ToString(); objYoutubeAccount.Accesstoken = access_token; objYoutubeAccount.Refreshtoken = refreshToken; objYoutubeAccount.Isactive = 1; objYoutubeAccount.Entrydate = DateTime.Now; objYoutubeAccount.UserId = Guid.Parse(UserId); if (!objYoutubeAccountRepository.checkYoutubeUserExists(objYoutubeAccount)) { YoutubeAccountRepository.Add(objYoutubeAccount); ret = "Account Added Successfully"; } else { ret = "Account already Exist !"; } } catch (Exception ex) { Console.WriteLine(ex.StackTrace); } } #endregion #region Add Youtube Channels GlobusGooglePlusLib.Youtube.Core.Channels ObjChannel = new GlobusGooglePlusLib.Youtube.Core.Channels(); JArray objarray = new JArray(); try { string part = (oAuthTokenYoutube.Parts.contentDetails.ToString() + "," + oAuthTokenYoutube.Parts.statistics.ToString()); string Value = ObjChannel.Get_Channel_List(access_token, part, 50, true); JObject UserChannels = JObject.Parse(@Value); objarray = (JArray)UserChannels["items"]; } catch (Exception ex) { } foreach (var item in objarray) { objYoutubeChannel = new Domain.Socioboard.Domain.YoutubeChannel(); try { objYoutubeChannel.Id = Guid.NewGuid(); objYoutubeChannel.Channelid = item["id"].ToString(); objYoutubeChannel.Likesid = item["contentDetails"]["relatedPlaylists"]["likes"].ToString(); objYoutubeChannel.Favoritesid = item["contentDetails"]["relatedPlaylists"]["favorites"].ToString(); objYoutubeChannel.Uploadsid = item["contentDetails"]["relatedPlaylists"]["uploads"].ToString(); objYoutubeChannel.Watchhistoryid = item["contentDetails"]["relatedPlaylists"]["watchHistory"].ToString(); objYoutubeChannel.Watchlaterid = item["contentDetails"]["relatedPlaylists"]["watchLater"].ToString(); objYoutubeChannel.Googleplususerid = objYoutubeAccount.Ytuserid; objYoutubeChannel.UserId = Guid.Parse(UserId); try { string viewcnt = item["statistics"]["viewCount"].ToString(); objYoutubeChannel.ViewCount = Convert.ToInt32(viewcnt); string videocnt = item["statistics"]["videoCount"].ToString(); objYoutubeChannel.VideoCount = Convert.ToInt32(videocnt); string commentcnt = item["statistics"]["commentCount"].ToString(); objYoutubeChannel.CommentCount = Convert.ToInt32(commentcnt); string Subscribercnt = item["statistics"]["subscriberCount"].ToString(); objYoutubeChannel.SubscriberCount = Convert.ToInt32(Subscribercnt); try { string str = item["statistics"]["hiddenSubscriberCount"].ToString(); if (str == "false") { objYoutubeChannel.HiddenSubscriberCount = 0; } else { objYoutubeChannel.HiddenSubscriberCount = 1; } } catch (Exception ex) { Console.WriteLine(ex.StackTrace); } } catch (Exception ex) { Console.WriteLine(ex.StackTrace); } } catch (Exception ex) { Console.WriteLine(ex.StackTrace); } if (!objYoutubeChannelRepository.checkYoutubeChannelExists(objYoutubeChannel.Channelid, Guid.Parse(UserId))) { YoutubeChannelRepository.Add(objYoutubeChannel); } } #endregion #region Add TeamMemberProfile Domain.Socioboard.Domain.Team objTeam = objTeamRepository.GetTeamByGroupId(Guid.Parse(GroupId)); Domain.Socioboard.Domain.TeamMemberProfile objTeamMemberProfile = new Domain.Socioboard.Domain.TeamMemberProfile(); objTeamMemberProfile.Id = Guid.NewGuid(); objTeamMemberProfile.TeamId = objTeam.Id; objTeamMemberProfile.Status = 1; objTeamMemberProfile.ProfileType = "youtube"; objTeamMemberProfile.StatusUpdateDate = DateTime.Now; objTeamMemberProfile.ProfileId = objYoutubeAccount.Ytuserid; objTeamMemberProfile.ProfileName = objYoutubeAccount.Ytusername; objTeamMemberProfile.ProfilePicUrl = objYoutubeAccount.Ytprofileimage; if (!objTeamMemberProfileRepository.checkTeamMemberProfile(objTeam.Id, objYoutubeAccount.Ytuserid)) { objTeamMemberProfileRepository.addNewTeamMember(objTeamMemberProfile); } #endregion #region SocialProfile Domain.Socioboard.Domain.SocialProfile objSocialProfile = new Domain.Socioboard.Domain.SocialProfile(); objSocialProfile.Id = Guid.NewGuid(); objSocialProfile.ProfileType = "youtube"; objSocialProfile.ProfileId = objYoutubeAccount.Ytuserid; objSocialProfile.UserId = Guid.Parse(UserId); objSocialProfile.ProfileDate = DateTime.Now; objSocialProfile.ProfileStatus = 1; if (!objSocialProfilesRepository.checkUserProfileExist(objSocialProfile)) { objSocialProfilesRepository.addNewProfileForUser(objSocialProfile); } #endregion return(ret); }
private void AccessToken() { SocioBoard.Domain.User user = (User)Session["LoggedUser"]; oAuthTokenYoutube ObjoAuthTokenYoutube = new oAuthTokenYoutube(); oAuthToken objToken = new oAuthToken(); //GlobusGooglePlusLib.App.Core.PeopleController obj = new GlobusGooglePlusLib.App.Core.PeopleController(); logger.Error("Error1:oAuthToken"); string refreshToken = string.Empty; string access_token = string.Empty; try { string objRefresh = string.Empty; objRefresh = ObjoAuthTokenYoutube.GetRefreshToken(Request.QueryString["code"]); if (!objRefresh.StartsWith("[")) { objRefresh = "[" + objRefresh + "]"; } JArray objArray = JArray.Parse(objRefresh); logger.Error("Error1:GetRefreshToken"); if (!objRefresh.Contains("refresh_token")) { logger.Error("Error0:refresh_token"); access_token = objArray[0]["access_token"].ToString(); string abc = ObjoAuthTokenYoutube.RevokeToken(access_token); Response.Redirect("https://accounts.google.com/o/oauth2/auth?client_id=" + System.Configuration.ConfigurationManager.AppSettings["YtconsumerKey"] + "&redirect_uri=" + System.Configuration.ConfigurationManager.AppSettings["Ytredirect_uri"] + "&scope=https://www.googleapis.com/auth/youtube+https://www.googleapis.com/auth/youtube.readonly+https://www.googleapis.com/auth/youtubepartner+https://www.googleapis.com/auth/youtubepartner-channel-audit+https://www.googleapis.com/auth/userinfo.email+https://www.googleapis.com/auth/userinfo.profile+https://www.googleapis.com/auth/plus.me&response_type=code&access_type=offline"); logger.Error("Error1:refresh_token"); } foreach (var item in objArray) { logger.Error("Abhay Item :" + item); try { try { refreshToken = item["refresh_token"].ToString(); } catch (Exception ex) { logger.Error(ex.StackTrace); logger.Error(ex.Message); Console.WriteLine(ex.StackTrace); } access_token = item["access_token"].ToString(); break; } catch (Exception ex) { logger.Error(ex.StackTrace); Console.WriteLine(ex.StackTrace); } } //Get user Profile #region <<Get user Profile>> JArray objEmail = new JArray(); try { objEmail = objToken.GetUserInfo("me", access_token.ToString()); } catch (Exception ex) { logger.Error("Email : " + objEmail); logger.Error(ex.Message); } #endregion GlobusGooglePlusLib.Youtube.Core.Channels ObjChannel = new GlobusGooglePlusLib.Youtube.Core.Channels(); //Get the Channels of user JArray objarray = new JArray(); try { string part = (oAuthTokenYoutube.Parts.contentDetails.ToString() + "," + oAuthTokenYoutube.Parts.statistics.ToString()); string Value = ObjChannel.Get_Channel_List(access_token, part, 50, true); logger.Error("Successfully GetValus"); logger.Error("Value :" + Value); JObject UserChannels = JObject.Parse(@Value); logger.Error("Successfully Convert Jobj"); logger.Error("Successfully Convert Jobj"); objarray = (JArray)UserChannels["items"]; logger.Error("Successfully Convert JArr"); } catch (Exception ex) { logger.Error("UserChannels :" + ex.Message); } YoutubeAccount objYoutubeAccount = new YoutubeAccount(); YoutubeChannel objYoutubeChannel = new YoutubeChannel(); YoutubeChannelRepository objYoutubeChannelRepository = new YoutubeChannelRepository(); YoutubeAccountRepository objYoutubeAccountRepository = new YoutubeAccountRepository(); //put condition here to check is user already exise if exist then update else insert string ytuerid = ""; foreach (var itemEmail in objEmail) { logger.Error("itemEmail :" + itemEmail); try { objYoutubeAccount.Id = Guid.NewGuid(); ytuerid = itemEmail["id"].ToString(); objYoutubeAccount.Ytuserid = itemEmail["id"].ToString(); objYoutubeAccount.Emailid = itemEmail["email"].ToString(); objYoutubeAccount.Ytusername = itemEmail["given_name"].ToString(); objYoutubeAccount.Ytprofileimage = itemEmail["picture"].ToString(); objYoutubeAccount.Accesstoken = access_token; objYoutubeAccount.Refreshtoken = refreshToken; objYoutubeAccount.Isactive = 1; objYoutubeAccount.Entrydate = DateTime.Now; objYoutubeAccount.UserId = user.Id; } catch (Exception ex) { logger.Error("itemEmail1 :" + ex.Message); logger.Error("itemEmail1 :" + ex.StackTrace); Console.WriteLine(ex.StackTrace); } } foreach (var item in objarray) { try { objYoutubeChannel.Id = Guid.NewGuid(); objYoutubeChannel.Channelid = item["id"].ToString(); objYoutubeChannel.Likesid = item["contentDetails"]["relatedPlaylists"]["likes"].ToString(); objYoutubeChannel.Favoritesid = item["contentDetails"]["relatedPlaylists"]["favorites"].ToString(); objYoutubeChannel.Uploadsid = item["contentDetails"]["relatedPlaylists"]["uploads"].ToString(); objYoutubeChannel.Watchhistoryid = item["contentDetails"]["relatedPlaylists"]["watchHistory"].ToString(); objYoutubeChannel.Watchlaterid = item["contentDetails"]["relatedPlaylists"]["watchLater"].ToString(); objYoutubeChannel.Googleplususerid = ytuerid; try { string viewcnt = item["statistics"]["viewCount"].ToString(); objYoutubeChannel.ViewCount = Convert.ToInt32(viewcnt); string videocnt = item["statistics"]["videoCount"].ToString(); objYoutubeChannel.VideoCount = Convert.ToInt32(videocnt); string commentcnt = item["statistics"]["commentCount"].ToString(); objYoutubeChannel.CommentCount = Convert.ToInt32(commentcnt); string Subscribercnt = item["statistics"]["subscriberCount"].ToString(); objYoutubeChannel.SubscriberCount = Convert.ToInt32(Subscribercnt); try { string str = item["statistics"]["hiddenSubscriberCount"].ToString(); if (str == "false") { objYoutubeChannel.HiddenSubscriberCount = 0; } else { objYoutubeChannel.HiddenSubscriberCount = 1; } } catch (Exception ex) { logger.Error("aagaya1: " + ex); Console.WriteLine(ex.StackTrace); } } catch (Exception ex) { logger.Error("aagaya2: " + ex); Console.WriteLine(ex.StackTrace); } } catch (Exception ex) { logger.Error("aagaya3: " + ex); Console.WriteLine(ex.StackTrace); logger.Error(ex.StackTrace); logger.Error(ex.Message); } } //YoutubeChannelRepository.Add(objYoutubeChannel); SocialProfile objSocialProfile = new SocialProfile(); SocialProfilesRepository objSocialProfilesRepository = new SocialProfilesRepository(); objSocialProfile.Id = Guid.NewGuid(); objSocialProfile.UserId = user.Id; objSocialProfile.ProfileId = ytuerid; objSocialProfile.ProfileType = "youtube"; objSocialProfile.ProfileDate = DateTime.Now; objSocialProfile.ProfileStatus = 1; logger.Error("aagaya"); if (!objSocialProfilesRepository.checkUserProfileExist(objSocialProfile)) { objSocialProfilesRepository.addNewProfileForUser(objSocialProfile); if (!objYoutubeAccountRepository.checkYoutubeUserExists(objYoutubeAccount)) { logger.Error("Abhay"); YoutubeAccountRepository.Add(objYoutubeAccount); logger.Error("Abhay account add ho gaya"); YoutubeChannelRepository.Add(objYoutubeChannel); logger.Error("Channel account add ho gaya"); GroupRepository objGroupRepository = new GroupRepository(); SocioBoard.Domain.Team team = (SocioBoard.Domain.Team)HttpContext.Current.Session["GroupName"]; Groups lstDetails = objGroupRepository.getGroupName(team.GroupId); if (lstDetails.GroupName == "Socioboard") { TeamMemberProfileRepository objTeamMemberProfileRepository = new TeamMemberProfileRepository(); TeamMemberProfile teammemberprofile = new TeamMemberProfile(); teammemberprofile.Id = Guid.NewGuid(); teammemberprofile.TeamId = team.Id; teammemberprofile.ProfileId = objYoutubeAccount.Ytuserid; teammemberprofile.ProfileType = "youtube"; teammemberprofile.StatusUpdateDate = DateTime.Now; objTeamMemberProfileRepository.addNewTeamMember(teammemberprofile); } } } else { logger.Error("Suraj"); if (!objYoutubeAccountRepository.checkYoutubeUserExists(objYoutubeAccount)) { YoutubeAccountRepository.Add(objYoutubeAccount); YoutubeChannelRepository.Add(objYoutubeChannel); } else { Response.Redirect("Home.aspx"); } } Response.Redirect("Home.aspx"); } catch (Exception Err) { Console.Write(Err.Message.ToString()); logger.Error(Err.StackTrace); logger.Error(Err.Message); } }
public string GoogleLogin(string code) { string ret = string.Empty; string objRefresh = string.Empty; string refreshToken = string.Empty; string access_token = string.Empty; oAuthTokenYoutube ObjoAuthTokenYoutube = new oAuthTokenYoutube(); oAuthToken objToken = new oAuthToken(); Domain.Socioboard.Domain.User objuser = new Domain.Socioboard.Domain.User(); try { logger.Error("Abhay before ObjoAuthTokenYoutube.GetRefreshToken: " + new System.Diagnostics.StackFrame(0, true).GetFileLineNumber()); objRefresh = ObjoAuthTokenYoutube.GetRefreshToken(code, ConfigurationManager.AppSettings["YtconsumerKey"], ConfigurationManager.AppSettings["YtconsumerSecret"], ConfigurationManager.AppSettings["Ytredirect_uri"]); logger.Error("Abhay: " + new System.Diagnostics.StackFrame(0, true).GetFileLineNumber()); logger.Error("1 " + code + " " + ConfigurationManager.AppSettings["YtconsumerKey"] + " " + ConfigurationManager.AppSettings["YtconsumerSecret"] + " " + ConfigurationManager.AppSettings["Ytredirect_uri"]); } catch (Exception ex) { logger.Error("2 " + code + " " + ConfigurationManager.AppSettings["YtconsumerKey"] + " " + ConfigurationManager.AppSettings["YtconsumerSecret"] + " " + ConfigurationManager.AppSettings["Ytredirect_uri"]); logger.Error(ex.Message); logger.Error(ex.StackTrace); } JObject objaccesstoken = JObject.Parse(objRefresh); try { refreshToken = objaccesstoken["refresh_token"].ToString(); } catch (Exception ex) { Console.WriteLine(ex.Message); } try { access_token = objaccesstoken["access_token"].ToString(); } catch (Exception ex) { Console.WriteLine(ex.StackTrace); } JArray userinfo = new JArray(); try { userinfo = objToken.GetUserInfo("me", access_token.ToString()); } catch (Exception ex) { } foreach (var itemEmail in userinfo) { try { objuser.EmailId = itemEmail["email"].ToString(); objuser.UserName = itemEmail["name"].ToString(); objuser.ProfileUrl = itemEmail["picture"].ToString(); } catch (Exception ex) { Console.WriteLine(ex.StackTrace); } } return((new JavaScriptSerializer().Serialize(objuser)) + "_#_" + access_token); }
public void GetYoutubeChannelVideos(string userid, string profileid) { string ret = string.Empty; string strfinaltoken = string.Empty; string channelDetails = string.Empty; Domain.Socioboard.Domain.YoutubeAccount objYoutubeAccount = objYoutubeAccountRepository.getYoutubeAccountDetailsById(profileid, Guid.Parse(userid)); List <Domain.Socioboard.Domain.YoutubeChannel> lstYoutubeChannel = objYoutubeChannelRepository.getYoutubeChannelDetailsById(profileid, Guid.Parse(userid)); foreach (Domain.Socioboard.Domain.YoutubeChannel objYoutubeChannel in lstYoutubeChannel) { oAuthTokenYoutube objoAuthTokenYoutube = new oAuthTokenYoutube(); string finaltoken = objoAuthTokenYoutube.GetAccessToken(objYoutubeAccount.Refreshtoken); JObject objArray = JObject.Parse(finaltoken); //foreach (var item in objArray) //{ try { strfinaltoken = objArray["access_token"].ToString(); // break; } catch (Exception ex) { Console.WriteLine(ex.StackTrace); } //} PlaylistItems objPlaylistItems = new PlaylistItems(); Video objVideo = new Video(); try { Domain.Socioboard.MongoDomain.YouTubeFeed _YouTubeFeed; channelDetails = objPlaylistItems.Get_PlaylistItems_List(strfinaltoken, GlobusGooglePlusLib.Authentication.oAuthTokenYoutube.Parts.snippet.ToString(), objYoutubeChannel.Uploadsid); JObject obj = JObject.Parse(channelDetails); JArray array = (JArray)obj["items"]; foreach (var item in array) { try { _YouTubeFeed = new Domain.Socioboard.MongoDomain.YouTubeFeed(); _YouTubeFeed.Id = ObjectId.GenerateNewId(); _YouTubeFeed.ChannelName = item["snippet"]["channelTitle"].ToString(); _YouTubeFeed.PublishTime = DateTime.Parse(item["snippet"]["publishedAt"].ToString()).ToString("yyyy/MM/dd HH:mm:ss"); _YouTubeFeed.Thumbnail = item["snippet"]["thumbnails"]["maxres"]["url"].ToString(); _YouTubeFeed.Title = item["snippet"]["title"].ToString(); _YouTubeFeed.ChannelId = item["snippet"]["channelId"].ToString(); _YouTubeFeed.Description = item["snippet"]["description"].ToString(); _YouTubeFeed.VideoId = item["snippet"]["resourceId"]["videoId"].ToString(); _YouTubeFeed.YoutubeId = profileid; string videodetail = objVideo.Get_VideoDetails_byId(_YouTubeFeed.VideoId, strfinaltoken, "contentDetails,statistics"); JObject objv = JObject.Parse(videodetail); var videodata = objv["items"][0]; _YouTubeFeed.commentCount = videodata["statistics"]["commentCount"].ToString(); _YouTubeFeed.dislikeCount = videodata["statistics"]["dislikeCount"].ToString(); _YouTubeFeed.duration = videodata["contentDetails"]["duration"].ToString(); _YouTubeFeed.favoriteCount = videodata["statistics"]["favoriteCount"].ToString(); _YouTubeFeed.likeCount = videodata["statistics"]["likeCount"].ToString(); _YouTubeFeed.viewCount = videodata["statistics"]["viewCount"].ToString(); var rt = youtubefeedrepo.Find <Domain.Socioboard.MongoDomain.YouTubeFeed>(t => t.VideoId.Equals(_YouTubeFeed.VideoId)); var task = Task.Run(async() => { return(await rt); }); int count = task.Result.Count; if (count < 1) { youtubefeedrepo.Add(_YouTubeFeed); } else { FilterDefinition <BsonDocument> filter = new BsonDocument("VideoId", _YouTubeFeed.VideoId); var update = Builders <BsonDocument> .Update.Set("commentCount", _YouTubeFeed.commentCount).Set("dislikeCount", _YouTubeFeed.dislikeCount).Set("duration", _YouTubeFeed.duration).Set("favoriteCount", _YouTubeFeed.favoriteCount) .Set("likeCount", _YouTubeFeed.likeCount).Set("viewCount", _YouTubeFeed.viewCount); youtubefeedrepo.Update <Domain.Socioboard.MongoDomain.YouTubeFeed>(update, filter); } } catch (Exception ex) { } } } catch (Exception ex) { } } }
public static List <Domain.Socioboard.ViewModels.YoutubeProfiles> GetYoutubeAccount(string code, Helper.AppSettings _appSettings, Model.DatabaseRepository dbr) { Domain.Socioboard.ViewModels.YoutubeProfiles _YoutubeChannels; List <Domain.Socioboard.ViewModels.YoutubeProfiles> lstYoutubeProfiles = new List <Domain.Socioboard.ViewModels.YoutubeProfiles>(); string access_token = string.Empty; string refresh_token = string.Empty; Channels _Channels = new Channels(_appSettings.GoogleConsumerKey, _appSettings.GoogleConsumerSecret, _appSettings.GoogleRedirectUri); try { oAuthTokenYoutube objToken = new oAuthTokenYoutube(_appSettings.GoogleConsumerKey, _appSettings.GoogleConsumerSecret, _appSettings.GoogleRedirectUri); string accessToken = objToken.GetRefreshToken(code); JObject JData = JObject.Parse(accessToken); try { refresh_token = JData["refresh_token"].ToString(); } catch (Exception ex) { access_token = JData["access_token"].ToString(); objToken.RevokeToken(access_token); return(null); } access_token = JData["access_token"].ToString(); string channelsdata = _Channels.Get_Channel_List(access_token, "snippet,contentDetails,statistics", 50, true); JObject JChanneldata = JObject.Parse(channelsdata); foreach (var item in JChanneldata["items"]) { try { string channelid = item["id"].ToString(); string channelname = item["snippet"]["title"].ToString(); string channelimage = item["snippet"]["thumbnails"]["default"]["url"].ToString(); channelimage = channelimage.Replace(".jpg", ""); string publishdate = item["snippet"]["publishedAt"].ToString(); string viewscount = item["statistics"]["viewCount"].ToString(); string commentscount = item["statistics"]["commentCount"].ToString(); string subscriberscount = item["statistics"]["subscriberCount"].ToString(); string videoscount = item["statistics"]["videoCount"].ToString(); string channeldescrip = item["snippet"]["description"].ToString(); #region Update Access and refresh token after authentication for every time //try //{ // List<Domain.Socioboard.Models.YoutubeChannel> lstYTChannel = dbr.Find<Domain.Socioboard.Models.YoutubeChannel>(t => t.YtubeChannelId.Equals(channelid)).ToList(); // if (lstYTChannel != null && lstYTChannel.Count() > 0) // { // lstYTChannel.First().AccessToken = access_token; // lstYTChannel.First().RefreshToken = refresh_token; // dbr.Update<Domain.Socioboard.Models.YoutubeChannel>(lstYTChannel.First()); // } //} //catch(Exception ex) //{ //} #endregion try { _YoutubeChannels = new Domain.Socioboard.ViewModels.YoutubeProfiles(); _YoutubeChannels.Accesstoken = access_token; _YoutubeChannels.Refreshtoken = refresh_token; _YoutubeChannels.YtChannelId = channelid; _YoutubeChannels.YtChannelName = channelname; _YoutubeChannels.YtChannelImage = channelimage; _YoutubeChannels.PublishDate = publishdate; _YoutubeChannels.viewscount = viewscount; _YoutubeChannels.commentscount = commentscount; _YoutubeChannels.subscriberscount = subscriberscount; _YoutubeChannels.videoscount = videoscount; _YoutubeChannels.YtChannelDescrip = channeldescrip; lstYoutubeProfiles.Add(_YoutubeChannels); } catch (Exception ex) { } } catch (Exception e) { } } } catch { } return(lstYoutubeProfiles); }
public void UpdateYtAccount() { { while (true) { try { Helper.DatabaseRepository dbr = new Helper.DatabaseRepository(); string apiKey = AppSettings.googleApiKey; oAuthTokenYoutube ObjoAuthTokenYtubes = new oAuthTokenYoutube(AppSettings.googleClientId, AppSettings.googleClientSecret, AppSettings.googleRedirectionUrl); oAuthToken objToken = new oAuthToken(AppSettings.googleClientId, AppSettings.googleClientSecret, AppSettings.googleRedirectionUrl); Video ObjVideo = new Video(AppSettings.googleClientId, AppSettings.googleClientSecret, AppSettings.googleRedirectionUrl); JObject userinfo = new JObject(); List <Domain.Socioboard.Models.YoutubeChannel> lstYtChannels = dbr.Find <Domain.Socioboard.Models.YoutubeChannel>(t => t.IsActive).ToList(); long count = 0; Console.WriteLine("---------------- Youtube Dataservices Started ----------------"); foreach (var item in lstYtChannels) { List <Domain.Socioboard.Models.Groupprofiles> _grpProfile = dbr.Find <Domain.Socioboard.Models.Groupprofiles>(t => t.profileId.Contains(item.YtubeChannelId)).ToList(); try { if (item.LastUpdate.AddHours(1) <= DateTime.UtcNow) { if (item.IsActive) { try { //string objRefresh = ObjoAuthTokenYtubes.GetAccessToken(item.RefreshToken); //JObject objaccesstoken = JObject.Parse(objRefresh); //string access_token = objaccesstoken["access_token"].ToString(); string ChannelInfo = ObjVideo.GetChannelInfo(apiKey, item.YtubeChannelId); JObject JChannelInfo = JObject.Parse(ChannelInfo); try { string cmntsCount = ObjVideo.GetChannelCmntCount(apiKey, item.YtubeChannelId); JObject JcmntsCount = JObject.Parse(cmntsCount); try { item.CommentsCount = Convert.ToDouble(JcmntsCount["pageInfo"]["totalResults"]); } catch { } } catch { } foreach (var ittem in JChannelInfo["items"]) { try { item.YtubeChannelName = ittem["snippet"]["title"].ToString(); _grpProfile.Select(s => { s.profileName = ittem["snippet"]["title"].ToString(); return(s); }).ToList(); } catch { } try { item.ChannelpicUrl = Convert.ToString(ittem["snippet"]["thumbnails"]["default"]["url"]).Replace(".jpg", ""); _grpProfile.Select(s => { s.profilePic = Convert.ToString(ittem["snippet"]["thumbnails"]["default"]["url"]).Replace(".jpg", ""); return(s); }).ToList(); } catch { } try { item.YtubeChannelDescription = Convert.ToString(ittem["snippet"]["description"]); if (item.YtubeChannelDescription == "") { item.YtubeChannelDescription = "No Description"; } } catch { } //try //{ // item.CommentsCount = Convert.ToDouble(ittem["statistics"]["commentCount"]); //} //catch //{ //} try { item.SubscribersCount = Convert.ToDouble(ittem["statistics"]["subscriberCount"]); } catch { } try { item.VideosCount = Convert.ToDouble(ittem["statistics"]["videoCount"]); } catch { } try { item.ViewsCount = Convert.ToDouble(ittem["statistics"]["viewCount"]); } catch { } dbr.Update <Domain.Socioboard.Models.YoutubeChannel>(item); foreach (var item_grpProfile in _grpProfile) { dbr.Update <Domain.Socioboard.Models.Groupprofiles>(item_grpProfile); } Youtube.YtFeeds.GetYtFeeds(item.YtubeChannelId, ""); item.LastUpdate = DateTime.UtcNow; dbr.Update <Domain.Socioboard.Models.YoutubeChannel>(item); } } catch (Exception) { Thread.Sleep(600000); } } } } catch (Exception ex) { Thread.Sleep(600000); } long oldcount = count; count++; long newcount = count; long totalcount = lstYtChannels.Count(); long percentagenew = (newcount * 100) / totalcount; long percentageold = (oldcount * 100) / totalcount; if (percentagenew != percentageold) { Console.WriteLine("---------------- {0}% Completed ----------------", percentagenew); } } Thread.Sleep(600000); } catch (Exception ex) { Console.WriteLine("issue in web api calling" + ex.StackTrace); Thread.Sleep(600000); } } } }
public static List <Domain.Socioboard.ViewModels.YoutubeProfiles> GetYoutubeAccount(string code, Helper.AppSettings _appSettings) { Domain.Socioboard.ViewModels.YoutubeProfiles _YoutubeChannels; List <Domain.Socioboard.ViewModels.YoutubeProfiles> lstYoutubeProfiles = new List <Domain.Socioboard.ViewModels.YoutubeProfiles>(); string access_token = string.Empty; string refresh_token = string.Empty; Channels _Channels = new Channels("575089347457-74q0u81gj88ve5bfdmbklcf2dnc0353q.apps.googleusercontent.com", "JRtS_TaeYpKOJWBCqt9h8-iG", "http://localhost:9821/GoogleManager/Google"); try { oAuthTokenYoutube objToken = new oAuthTokenYoutube("575089347457-74q0u81gj88ve5bfdmbklcf2dnc0353q.apps.googleusercontent.com", "JRtS_TaeYpKOJWBCqt9h8-iG", "http://localhost:9821/GoogleManager/Google"); string accessToken = objToken.GetRefreshToken(code); JObject JData = JObject.Parse(accessToken); try { refresh_token = JData["refresh_token"].ToString(); } catch (Exception ex) { access_token = JData["access_token"].ToString(); objToken.RevokeToken(access_token); return(null); } access_token = JData["access_token"].ToString(); string channelsdata = _Channels.Get_Channel_List(access_token, "snippet,contentDetails,statistics", 50, true); JObject JChanneldata = JObject.Parse(channelsdata); foreach (var item in JChanneldata["items"]) { try { string channelid = item["id"].ToString(); string channelname = item["snippet"]["title"].ToString(); string channelimage = item["snippet"]["thumbnails"]["default"]["url"].ToString(); string publishdate = item["snippet"]["publishedAt"].ToString(); string viewscount = item["statistics"]["viewCount"].ToString(); string commentscount = item["statistics"]["commentCount"].ToString(); string subscriberscount = item["statistics"]["subscriberCount"].ToString(); string videoscount = item["statistics"]["videoCount"].ToString(); string channeldescrip = item["snippet"]["description"].ToString(); try { _YoutubeChannels = new Domain.Socioboard.ViewModels.YoutubeProfiles(); _YoutubeChannels.Accesstoken = access_token; _YoutubeChannels.Refreshtoken = refresh_token; _YoutubeChannels.YtChannelId = channelid; _YoutubeChannels.YtChannelName = channelname; _YoutubeChannels.YtChannelImage = channelimage; _YoutubeChannels.PublishDate = publishdate; _YoutubeChannels.viewscount = viewscount; _YoutubeChannels.commentscount = commentscount; _YoutubeChannels.subscriberscount = subscriberscount; _YoutubeChannels.videoscount = videoscount; _YoutubeChannels.YtChannelDescrip = channeldescrip; lstYoutubeProfiles.Add(_YoutubeChannels); } catch (Exception ex) { } } catch (Exception e) { } } } catch { } return(lstYoutubeProfiles); }
public void UpdateYAnalyticsReports() { while (true) { try { var databaseRepository = new DatabaseRepository(); var objOauthTokenYoutube = new oAuthTokenYoutube(AppSettings.googleClientId, AppSettings.googleClientSecret, AppSettings.googleRedirectionUrl); var objToken = new oAuthToken(AppSettings.googleClientId, AppSettings.googleClientSecret, AppSettings.googleRedirectionUrl); var ObjYAnalytics = new YAnalytics(AppSettings.googleClientId, AppSettings.googleClientSecret, AppSettings.googleRedirectionUrl); var lstYtChannels = databaseRepository.Find <YoutubeChannel>(t => t.IsActive).ToList(); var count = 0; Console.WriteLine("---------------- Youtube Analytics Dataservices Started ----------------"); foreach (var youtubeChannelItem in lstYtChannels) { #region count for mongo data var mongoreposs = new MongoRepository("YoutubeReportsData"); var result = mongoreposs.Find <YoutubeReports>(t => t.channelId.Equals(youtubeChannelItem.YtubeChannelId)); var task = Task.Run(async() => { return(await result); }); var lstYanalytics = task.Result; var count90AnalyticsUpdated = lstYanalytics.Count(); #endregion try { if (!youtubeChannelItem.Days90Update || count90AnalyticsUpdated < 90) { if (youtubeChannelItem.IsActive) { try { ////////code of reports here/////////////////////// var to_Date = DateTime.UtcNow; var to_dd = ("0" + Convert.ToString(to_Date.Day)); to_dd = to_dd.Substring(to_dd.Length - 2); var to_mm = "0" + Convert.ToString(to_Date.Month); to_mm = to_mm.Substring(to_mm.Length - 2); var to_yyyy = Convert.ToString(to_Date.Year); var from_Date = DateTime.UtcNow.AddDays(-90); var from_dd = "0" + Convert.ToString(from_Date.Day); from_dd = from_dd.Substring(from_dd.Length - 2); var from_mm = "0" + Convert.ToString(from_Date.Month); from_mm = from_mm.Substring(from_mm.Length - 2); var from_yyyy = Convert.ToString(from_Date.Year); var YaFrom_Date = from_yyyy + "-" + from_mm + "-" + from_dd; var YaTo_Date = to_yyyy + "-" + to_mm + "-" + to_dd; var mongorepo = new MongoRepository("YoutubeReportsData"); var AnalyticData = ObjYAnalytics.Get_YAnalytics_ChannelId(youtubeChannelItem.YtubeChannelId, youtubeChannelItem.RefreshToken, YaFrom_Date, YaTo_Date); var JAnalyticData = JObject.Parse(AnalyticData); var dataArray = (JArray)JAnalyticData["rows"]; var datesJdata = new List <string>(); if (dataArray != null) { foreach (var rows in dataArray) { datesJdata.Add(rows[0].ToString()); } foreach (var items in dataArray) { var objYtReports = new YoutubeReports(); objYtReports.Id = ObjectId.GenerateNewId(); objYtReports.date = items[0].ToString(); objYtReports.channelId = items[1].ToString(); objYtReports.SubscribersGained = Convert.ToInt32(items[2]); objYtReports.views = Convert.ToInt32(items[3]); objYtReports.likes = Convert.ToInt32(items[4]); objYtReports.comments = Convert.ToInt32(items[5]); objYtReports.dislikes = Convert.ToInt32(items[7]); objYtReports.subscribersLost = Convert.ToInt32(items[8]); objYtReports.averageViewDuration = Convert.ToInt64(items[9]); objYtReports.estimatedMinutesWatched = Convert.ToInt64(items[10]); objYtReports.annotationClickThroughRate = Convert.ToInt64(items[11]); objYtReports.annotationCloseRate = Convert.ToInt64(items[12]); objYtReports.uniqueIdentifier = youtubeChannelItem.YtubeChannelId + "_" + objYtReports.date; objYtReports.datetime_unix = Convert.ToDouble(UnixTimeNows(Convert.ToDateTime(objYtReports.date))); mongorepo.Add(objYtReports); } } else { datesJdata.Add("Null"); } for (var i = 1; i <= 90; i++) { YoutubeReports objYreports = new YoutubeReports(); DateTime dateTimeTemp = DateTime.UtcNow.AddDays(-i); var now_dd = "0" + Convert.ToString(dateTimeTemp.Day); now_dd = now_dd.Substring(now_dd.Length - 2); var now_mm = "0" + Convert.ToString(dateTimeTemp.Month); now_mm = now_mm.Substring(now_mm.Length - 2); var now_yyyy = Convert.ToString(dateTimeTemp.Year); var Ynow_Date = now_yyyy + "-" + now_mm + "-" + now_dd; if (!(datesJdata.Contains(Ynow_Date))) { objYreports.Id = ObjectId.GenerateNewId(); objYreports.date = Ynow_Date; objYreports.channelId = youtubeChannelItem.YtubeChannelId; objYreports.SubscribersGained = 0; objYreports.views = 0; objYreports.likes = 0; objYreports.comments = 0; objYreports.dislikes = 0; objYreports.subscribersLost = 0; objYreports.averageViewDuration = 0; objYreports.estimatedMinutesWatched = 0; objYreports.annotationClickThroughRate = 0; objYreports.annotationCloseRate = 0; objYreports.uniqueIdentifier = youtubeChannelItem.YtubeChannelId + "_" + Ynow_Date; objYreports.datetime_unix = Convert.ToDouble(UnixTimeNows(Convert.ToDateTime(Ynow_Date))); mongorepo.Add(objYreports); } } youtubeChannelItem.Days90Update = true; youtubeChannelItem.LastReport_Update = DateTime.UtcNow; databaseRepository.Update(youtubeChannelItem); } catch (Exception) { Thread.Sleep(600000); } } } else { if (youtubeChannelItem.LastReport_Update.AddHours(24) < DateTime.UtcNow) { //dailyReport Code here// if (youtubeChannelItem.IsActive) { try { //code of reports here// var to_Date = DateTime.UtcNow; var to_dd = "0" + Convert.ToString(to_Date.Day); to_dd = to_dd.Substring(to_dd.Length - 2); var to_mm = "0" + Convert.ToString(to_Date.Month); to_mm = to_mm.Substring(to_mm.Length - 2); var to_yyyy = Convert.ToString(to_Date.Year); var from_Date = DateTime.UtcNow.AddDays(-4); var from_dd = "0" + Convert.ToString(from_Date.Day); from_dd = from_dd.Substring(from_dd.Length - 2); var from_mm = "0" + Convert.ToString(from_Date.Month); from_mm = from_mm.Substring(from_mm.Length - 2); var from_yyyy = Convert.ToString(from_Date.Year); var YaFrom_Date = from_yyyy + "-" + from_mm + "-" + from_dd; var YaTo_Date = to_yyyy + "-" + to_mm + "-" + to_dd; var AnalyticData = ObjYAnalytics.Get_YAnalytics_ChannelId(youtubeChannelItem.YtubeChannelId, youtubeChannelItem.RefreshToken, YaFrom_Date, YaTo_Date); var JAnalyticData = JObject.Parse(AnalyticData); var dataArray = (JArray)JAnalyticData["rows"]; var datesJdata = new List <string>(); if (dataArray != null) { foreach (var rows in dataArray) { datesJdata.Add(rows[0].ToString()); } foreach (var items in dataArray) { var objYReports = new YoutubeReports(); objYReports.Id = ObjectId.GenerateNewId(); objYReports.date = items[0].ToString(); objYReports.channelId = items[1].ToString(); objYReports.SubscribersGained = Convert.ToInt32(items[2]); objYReports.views = Convert.ToInt32(items[3]); objYReports.likes = Convert.ToInt32(items[4]); objYReports.comments = Convert.ToInt32(items[5]); objYReports.shares = Convert.ToInt32(items[6]); objYReports.dislikes = Convert.ToInt32(items[7]); objYReports.subscribersLost = Convert.ToInt32(items[8]); objYReports.averageViewDuration = Convert.ToInt64(items[9]); objYReports.estimatedMinutesWatched = Convert.ToInt64(items[10]); objYReports.annotationClickThroughRate = Convert.ToInt64(items[11]); objYReports.annotationCloseRate = Convert.ToInt64(items[12]); objYReports.uniqueIdentifier = youtubeChannelItem.YtubeChannelId + "_" + objYReports.date; objYReports.datetime_unix = Convert.ToDouble(UnixTimeNows(Convert.ToDateTime(objYReports.date))); try { var mongoRepotsRepo = new MongoRepository("YoutubeReportsData"); var ret = mongoRepotsRepo.Find <YoutubeReports>(t => t.uniqueIdentifier.Equals(objYReports.uniqueIdentifier)); var task_Reports = Task.Run(async() => { return(await ret); }); var count_Reports = task_Reports.Result.Count; if (count_Reports < 1) { try { mongoRepotsRepo.Add(objYReports); } catch { } } else { try { var filter = new BsonDocument("uniqueIdentifier", objYReports.uniqueIdentifier); var update = Builders <BsonDocument> .Update.Set("SubscribersGained", objYReports.SubscribersGained).Set("views", objYReports.views).Set("likes", objYReports.likes).Set("comments", objYReports.comments).Set("dislikes", objYReports.dislikes).Set("subscribersLost", objYReports.subscribersLost).Set("averageViewDuration", objYReports.averageViewDuration).Set("estimatedMinutesWatched", objYReports.estimatedMinutesWatched).Set("annotationClickThroughRate", objYReports.annotationClickThroughRate).Set("annotationCloseRate", objYReports.annotationCloseRate); mongoRepotsRepo.Update <YoutubeReports>(update, filter); } catch { } } } catch { } } } else { datesJdata.Add("Null"); } for (var i = 1; i <= 4; i++) { var _YReports = new YoutubeReports(); var dateTimeTemp = DateTime.UtcNow.AddDays(-i); var now_dd = "0" + Convert.ToString(dateTimeTemp.Day); now_dd = now_dd.Substring(now_dd.Length - 2); var now_mm = "0" + Convert.ToString(dateTimeTemp.Month); now_mm = now_mm.Substring(now_mm.Length - 2); var now_yyyy = Convert.ToString(dateTimeTemp.Year); var Ynow_Date = now_yyyy + "-" + now_mm + "-" + now_dd; if (!(datesJdata.Contains(Ynow_Date))) { _YReports.Id = ObjectId.GenerateNewId(); _YReports.date = Ynow_Date; _YReports.channelId = youtubeChannelItem.YtubeChannelId; _YReports.SubscribersGained = 0; _YReports.views = 0; _YReports.likes = 0; _YReports.comments = 0; _YReports.dislikes = 0; _YReports.subscribersLost = 0; _YReports.averageViewDuration = 0; _YReports.estimatedMinutesWatched = 0; _YReports.annotationClickThroughRate = 0; _YReports.annotationCloseRate = 0; _YReports.uniqueIdentifier = youtubeChannelItem.YtubeChannelId + "_" + Ynow_Date; _YReports.datetime_unix = Convert.ToDouble(UnixTimeNows(Convert.ToDateTime(Ynow_Date))); var mongoRepotsRepo = new MongoRepository("YoutubeReportsData"); mongoRepotsRepo.Add(_YReports); } } youtubeChannelItem.LastReport_Update = DateTime.UtcNow; databaseRepository.Update(youtubeChannelItem); } catch (Exception) { Thread.Sleep(600000); } } } } } catch (Exception ex) { Thread.Sleep(600000); } var oldcount = count; count++; var newcount = count; var totalcount = lstYtChannels.Count(); var percentagenew = (newcount * 100) / totalcount; var percentageold = (oldcount * 100) / totalcount; if (percentagenew != percentageold) { Console.WriteLine("---------------- {0}% Completed ----------------", percentagenew); } } Thread.Sleep(600000); } catch (Exception ex) { Console.WriteLine("issue in web api calling" + ex.StackTrace); Thread.Sleep(600000); } } }
public void UpdateVideoDetailsList() { while (true) { try { Helper.DatabaseRepository dbr = new Helper.DatabaseRepository(); string apiKey = AppSettings.googleApiKey; oAuthTokenYoutube ObjoAuthTokenYtubes = new oAuthTokenYoutube(AppSettings.googleClientId, AppSettings.googleClientSecret, AppSettings.googleRedirectionUrl); oAuthToken objToken = new oAuthToken(AppSettings.googleClientId, AppSettings.googleClientSecret, AppSettings.googleRedirectionUrl); Video objVideo = new Video(AppSettings.googleClientId, AppSettings.googleClientSecret, AppSettings.googleRedirectionUrl); List <Domain.Socioboard.Models.YoutubeChannel> lstYtChannels = dbr.Find <Domain.Socioboard.Models.YoutubeChannel>(t => t.IsActive).ToList(); long count = 0; Console.WriteLine("---------------- Youtube Videos List Dataservices Started ----------------"); foreach (var item in lstYtChannels) { try { if (item.LastVideoListDetails_Update.AddMinutes(60) < DateTime.UtcNow) { MongoRepository mongoreposs = new MongoRepository("YoutubeVideos"); var result = mongoreposs.Find <Domain.Socioboard.Models.Mongo.MongoYoutubeFeeds>(t => t.YtChannelId.Equals(item.YtubeChannelId)); var task = Task.Run(async() => { return(await result); }); IList <Domain.Socioboard.Models.Mongo.MongoYoutubeFeeds> lstChannelVideos = task.Result; List <string> videoIds = new List <string>(); foreach (var items in lstChannelVideos) { videoIds.Add(items.YtVideoId); } foreach (string videoId in videoIds) { try { string VideoList = objVideo.GetYTVideoDetailList(apiKey, videoId); JObject JVideoList = JObject.Parse(VideoList); foreach (var itemVideo in JVideoList["items"]) { YoutubeVideoDetailsList _YVideoDetails = new YoutubeVideoDetailsList(); _YVideoDetails.Id = ObjectId.GenerateNewId(); try { _YVideoDetails.YtvideoId = itemVideo["id"].ToString(); _YVideoDetails.watchUrl = "https://www.youtube.com/watch?v=" + _YVideoDetails.YtvideoId; _YVideoDetails.embedVideo = "https://www.youtube.com/embed/" + _YVideoDetails.YtvideoId; } catch { _YVideoDetails.YtvideoId = ""; _YVideoDetails.watchUrl = "N/A"; _YVideoDetails.embedVideo = "N/A"; } try { _YVideoDetails.publishedAt = itemVideo["snippet"]["publishedAt"].ToString(); } catch { _YVideoDetails.publishedAt = "0001-01-01"; } try { _YVideoDetails.publishDateUnix = UnixTimeNows(Convert.ToDateTime(_YVideoDetails.publishedAt)); } catch { _YVideoDetails.publishDateUnix = UnixTimeNows(Convert.ToDateTime("0001-01-01")); } try { _YVideoDetails.channelId = itemVideo["snippet"]["channelId"].ToString(); } catch { _YVideoDetails.channelId = "N/A"; } try { _YVideoDetails.title = itemVideo["snippet"]["title"].ToString(); } catch { _YVideoDetails.title = "N/A"; } try { _YVideoDetails.description = itemVideo["snippet"]["description"].ToString(); if (_YVideoDetails.description == "") { _YVideoDetails.description = "No Description"; } } catch { _YVideoDetails.description = "N/A"; } try { _YVideoDetails.vdoImageUrl = itemVideo["snippet"]["thumbnails"]["default"]["url"].ToString(); } catch { _YVideoDetails.vdoImageUrl = "N/A"; } try { _YVideoDetails.channelTitle = itemVideo["snippet"]["channelTitle"].ToString(); } catch { _YVideoDetails.channelTitle = "N/A"; } try { _YVideoDetails.categoryId = itemVideo["snippet"]["categoryId"].ToString(); } catch { _YVideoDetails.categoryId = "N/A"; } try { _YVideoDetails.liveBroadcastContent = itemVideo["snippet"]["liveBroadcastContent"].ToString(); } catch { _YVideoDetails.liveBroadcastContent = "N/A"; } try { _YVideoDetails.duration = itemVideo["contentDetails"]["duration"].ToString(); _YVideoDetails.videoLength = _YVideoDetails.duration.Replace("PT", "").Replace("H", "h:").Replace("M", "m:").Replace("S", "s"); } catch { _YVideoDetails.duration = "N/A"; _YVideoDetails.videoLength = "N/A"; } try { _YVideoDetails.dimension = itemVideo["contentDetails"]["dimension"].ToString(); } catch { _YVideoDetails.dimension = "N/A"; } try { _YVideoDetails.definition = itemVideo["contentDetails"]["definition"].ToString(); } catch { _YVideoDetails.definition = "N/A"; } try { _YVideoDetails.caption = itemVideo["contentDetails"]["caption"].ToString(); } catch { _YVideoDetails.caption = "N/A"; } try { _YVideoDetails.licensedContent = itemVideo["contentDetails"]["licensedContent"].ToString(); } catch { _YVideoDetails.licensedContent = "N/A"; } try { _YVideoDetails.projection = itemVideo["contentDetails"]["projection"].ToString(); } catch { _YVideoDetails.projection = "N/A"; } try { _YVideoDetails.uploadStatus = itemVideo["status"]["uploadStatus"].ToString(); } catch { _YVideoDetails.uploadStatus = "N/A"; } try { _YVideoDetails.privacyStatus = itemVideo["status"]["privacyStatus"].ToString(); } catch { _YVideoDetails.privacyStatus = "N/A"; } try { _YVideoDetails.license = itemVideo["status"]["license"].ToString(); } catch { _YVideoDetails.license = "N/A"; } try { _YVideoDetails.embeddable = itemVideo["status"]["embeddable"].ToString(); } catch { _YVideoDetails.embeddable = "N/A"; } try { _YVideoDetails.publicStatsViewable = itemVideo["status"]["publicStatsViewable"].ToString(); } catch { _YVideoDetails.publicStatsViewable = "N/A"; } try { _YVideoDetails.viewCount = Convert.ToInt32(itemVideo["statistics"]["viewCount"]); } catch { _YVideoDetails.viewCount = 0; } try { _YVideoDetails.likeCount = Convert.ToInt32(itemVideo["statistics"]["likeCount"].ToString()); } catch { _YVideoDetails.likeCount = 0; } try { _YVideoDetails.dislikeCount = Convert.ToInt32(itemVideo["statistics"]["dislikeCount"].ToString()); } catch { _YVideoDetails.dislikeCount = 0; } try { _YVideoDetails.favoriteCount = Convert.ToInt32(itemVideo["statistics"]["favoriteCount"].ToString()); } catch { _YVideoDetails.favoriteCount = 0; } try { _YVideoDetails.commentCount = Convert.ToInt32(itemVideo["statistics"]["commentCount"].ToString()); } catch { _YVideoDetails.commentCount = 0; } try { _YVideoDetails.channelProfilePic = item.ChannelpicUrl; } catch { _YVideoDetails.channelProfilePic = "N/A"; } try { _YVideoDetails.channelEmailId = item.Channel_EmailId; } catch { _YVideoDetails.channelEmailId = "N/A"; } try { _YVideoDetails.channelUrl = item.WebsiteUrl; } catch { _YVideoDetails.channelUrl = "N/A"; } try { MongoRepository mongoRepotsRepo = new MongoRepository("YoutubeVideosDetailedList"); var ret = mongoRepotsRepo.Find <YoutubeVideoDetailsList>(t => t.YtvideoId.Equals(_YVideoDetails.YtvideoId)); var task_Reports = Task.Run(async() => { return(await ret); }); int count_Reports = task_Reports.Result.Count; if (count_Reports < 1) { try { mongoRepotsRepo.Add(_YVideoDetails); } catch { } } else { try { FilterDefinition <BsonDocument> filter = new BsonDocument("YtvideoId", _YVideoDetails.YtvideoId); var update = Builders <BsonDocument> .Update.Set("title", _YVideoDetails.title).Set("description", _YVideoDetails.description).Set("vdoImageUrl", _YVideoDetails.vdoImageUrl).Set("channelTitle", _YVideoDetails.channelTitle).Set("uploadStatus", _YVideoDetails.uploadStatus).Set("categoryId", _YVideoDetails.categoryId).Set("privacyStatus", _YVideoDetails.privacyStatus).Set("viewCount", _YVideoDetails.viewCount).Set("likeCount", _YVideoDetails.likeCount).Set("dislikeCount", _YVideoDetails.dislikeCount).Set("favoriteCount", _YVideoDetails.favoriteCount).Set("commentCount", _YVideoDetails.commentCount).Set("publishDateUnix", _YVideoDetails.publishDateUnix).Set("videoLength", _YVideoDetails.videoLength).Set("channelProfilePic", _YVideoDetails.channelProfilePic).Set("channelEmailId", _YVideoDetails.channelEmailId).Set("channelUrl", _YVideoDetails.channelUrl); mongoRepotsRepo.Update <YoutubeReports>(update, filter); } catch { } } } catch { } Console.Write("."); } } catch { } } item.LastVideoListDetails_Update = DateTime.UtcNow; dbr.Update <Domain.Socioboard.Models.YoutubeChannel>(item); } } catch { } long oldcount = count; count++; long newcount = count; long totalcount = lstYtChannels.Count(); long percentagenew = (newcount * 100) / totalcount; long percentageold = (oldcount * 100) / totalcount; if (percentagenew != percentageold) { Console.WriteLine("---------------- {0}% Completed ----------------", percentagenew); } } Thread.Sleep(600000); } catch (Exception ex) { Console.WriteLine("issue in web api calling" + ex.StackTrace); Thread.Sleep(600000); } } }