public object Authorize(HttpRequest Request, string accountName)
        {
            try
            {
                var uri = Request.Url.ToString();
                var code = Request["code"];
                var error = Request["error"];

                if (!string.IsNullOrEmpty(error))
                    if (error == "access_denied")
                        return new UserRejectException();
                    else
                        return new UnknownException(error);

                BloggerService = null;

                if (code != null)
                {
                    string redirectUri = uri.Substring(0, uri.IndexOf("?"));
                    var token = CodeFlow.ExchangeCodeForTokenAsync(accountName, code, redirectUri, CancellationToken.None).Result;
                    string state = Request["state"];
                    var result = AuthWebUtility.ExtracRedirectFromState(CodeFlow.DataStore, accountName, state);
                    return result;
                }
                else
                {
                    string redirectUri = uri;
                    string state = "ostate_";// Guid.NewGuid().ToString("N");
                    var result = new AuthorizationCodeWebApp(CodeFlow, redirectUri, state).AuthorizeAsync(accountName, CancellationToken.None).Result;
                    if (result.RedirectUri != null)
                    {
                        return result;
                    }
                    else
                    {
                        BloggerService = new BloggerService(new BaseClientService.Initializer()
                        {
                            HttpClientInitializer = result.Credential,
                            ApplicationName = APPLICATION_NAME
                        });
                        // alright
                        return "OK";
                    }
                }
            }
            catch (Exception ex)
            {
                return ex;
            }
        }
        static void Main(string[] args)
        {
            Google.Apis.Blogger.v3.BloggerService bs = new BloggerService(new BaseClientService.Initializer()
            {
                ApiKey = "AIzaSyCkyf5p4x_2tW-Bwmqt7Bbj-HhFIC_kXvw",
            });
            Google.Apis.Blogger.v3.BlogsResource br = new BlogsResource(bs);
            var res = br.GetByUrl("http://blogzaserioznihora.blogspot.com/").Execute();
            
            Google.Apis.Blogger.v3.PostsResource pr = new PostsResource(bs);
            var list = pr.List("7485604791378022116");
            list.FetchBodies = false;
            var result = list.Execute();

            
        }
        /// <summary>
        /// Retrieve pageview stats for a Blog.
        /// Documentation https://developers.google.com/blogger/v3/reference/pageViews/get
        /// Generation Note: This does not always build corectly.  Google needs to standardise things I need to figuer out which ones are wrong.
        /// </summary>
        /// <param name="service">Authenticated Blogger service.</param>
        /// <param name="blogId">The ID of the blog to get.</param>
        /// <param name="optional">Optional paramaters.</param>
        /// <returns>PageviewsResponse</returns>
        public static Pageviews Get(BloggerService service, string blogId, PageViewsGetOptionalParms optional = null)
        {
            try
            {
                // Initial validation.
                if (service == null)
                {
                    throw new ArgumentNullException("service");
                }
                if (blogId == null)
                {
                    throw new ArgumentNullException(blogId);
                }

                // Building the initial request.
                var request = service.PageViews.Get(blogId);

                // Applying optional parameters to the request.
                request = (PageViewsResource.GetRequest)SampleHelpers.ApplyOptionalParms(request, optional);

                // Requesting data.
                return(request.Execute());
            }
            catch (Exception ex)
            {
                throw new Exception("Request PageViews.Get failed.", ex);
            }
        }
Exemple #4
0
        public static async Task <bool> LogIn()
        {
            using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
            {
                credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets, new[] { BloggerService.Scope.Blogger },
                    "*****@*****.**", CancellationToken.None);
            }

            using (var stream = new FileStream("client_secrets_links.json", FileMode.Open, FileAccess.Read))
            {
                linksCredential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets, new[] { BloggerService.Scope.Blogger },
                    "*****@*****.**", CancellationToken.None, new FileDataStore(@"Google.Apis.Auth\LinksBlog"));
            }

            if (credential == null || linksCredential == null)
            {
                return(false);
            }
            service = new BloggerService(new BaseClientService.Initializer
            {
                HttpClientInitializer = credential,
                ApplicationName       = "blogtestproject", // 這個名稱必須與申請憑證時所使用的專案名稱相同
            });
            linksService = new BloggerService(new BaseClientService.Initializer
            {
                HttpClientInitializer = linksCredential,
                ApplicationName       = "blogtestproject", // 這個名稱必須與申請憑證時所使用的專案名稱相同
            });
            return(service != null && linksCredential != null);
        }
        public static List<Post> getPostList(BloggerService bs, string blogId, PostsResource.ListRequest.StatusEnum status)
        {
            PostsResource.ListRequest req = bs.Posts.List(blogId);
            req.View = PostsResource.ListRequest.ViewEnum.ADMIN;
            req.FetchBodies = false;
            req.FetchImages = false;
            req.Status = status;

            List<Post> listOfPost = new List<Post>();
            string firstToken = "";

            while (true)
            {
                PostList posts = req.Execute();
                req.PageToken = posts.NextPageToken;
                if (firstToken == "")
                {
                    firstToken = posts.NextPageToken;
                }
                else if (firstToken != "" && posts.NextPageToken == firstToken)
                {
                    break;
                }
                if (posts.Items != null)
                {
                    posts.Items.ToList().ForEach(item => listOfPost.Add(item));
                }
            }

            return listOfPost;
        }
Exemple #6
0
        private async Task AuthenticateAsync()
        {
            if (_service != null)
            {
                return;
            }
            
            FileStream stream = new FileStream(SecretFileName, FileMode.Open, FileAccess.Read);

            CancellationTokenSource cts = new CancellationTokenSource();
            cts.CancelAfter(TimeSpan.FromSeconds(20));
            CancellationToken ct = cts.Token;

            _credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                GoogleClientSecrets.Load(stream).Secrets,
                new[] { BloggerService.Scope.Blogger },
                "user",
                ct
                );

            BaseClientService.Initializer initializer = new BaseClientService.Initializer()
            {
                HttpClientInitializer = _credential,
                ApplicationName = ApplicationName
            };

            _service = new BloggerService(initializer);
        }
Exemple #7
0
        /// <summary>
        /// Delete a post by ID.
        /// Documentation https://developers.google.com/blogger/v3/reference/posts/delete
        /// Generation Note: This does not always build corectly.  Google needs to standardise things I need to figuer out which ones are wrong.
        /// </summary>
        /// <param name="service">Authenticated Blogger service.</param>
        /// <param name="blogId">The ID of the Blog.</param>
        /// <param name="postId">The ID of the Post.</param>
        public static void Delete(BloggerService service, string blogId, string postId)
        {
            try
            {
                // Initial validation.
                if (service == null)
                {
                    throw new ArgumentNullException("service");
                }
                if (blogId == null)
                {
                    throw new ArgumentNullException(blogId);
                }
                if (postId == null)
                {
                    throw new ArgumentNullException(postId);
                }

                // Make the request.
                service.Posts.Delete(blogId, postId).Execute();
            }
            catch (Exception ex)
            {
                throw new Exception("Request Posts.Delete failed.", ex);
            }
        }
        /// <summary>
        /// Authenticate to Google Using Oauth2
        /// Documentation https://developers.google.com/accounts/docs/OAuth2
        /// </summary>
        /// <param name="clientId">From Google Developer console https://console.developers.google.com</param>
        /// <param name="clientSecret">From Google Developer console https://console.developers.google.com</param>
        /// <param name="userName">A string used to identify a user.</param>
        /// <returns></returns>
        public static BloggerService AuthenticateOauth(string clientId, string clientSecret, string userName)
        {
            string[] scopes = new string[] { BloggerService.Scope.Blogger,           // view and manage your analytics data
                                             BloggerService.Scope.BloggerReadonly }; // View your Blogs

            try
            {
                // here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData%
                UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets {
                    ClientId = clientId, ClientSecret = clientSecret
                }
                                                                                        , scopes
                                                                                        , userName
                                                                                        , CancellationToken.None
                                                                                        , new FileDataStore("Daimto.Blogger.Auth.Store")).Result;

                BloggerService service = new BloggerService(new BloggerService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName       = "Blogger API Sample",
                });
                return(service);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.InnerException);
                return(null);
            }
        }
Exemple #9
0
        private void AddEntry_Click(object sender, System.EventArgs e)
        {
            addentry dlg = new addentry();

            if (dlg.ShowDialog() == DialogResult.OK &&
                dlg.Entry.Length > 0)
            {
                // now add this to the feed.

                BloggerEntry entry = new BloggerEntry();

                entry.Content.Content = dlg.Entry;
                entry.Content.Type    = "html";
                entry.Title.Text      = dlg.EntryTitle;


                string userName = this.UserName.Text;
                string passWord = this.Password.Text;

                BloggerService service = new BloggerService("BloggerSampleApp.NET");

                if (userName != null && userName.Length > 0)
                {
                    service.Credentials = new GDataCredentials(userName, passWord);
                }

                service.Insert(new Uri(this.feedUri), entry);

                RefreshFeed(this.feedUri);
            }
        }
Exemple #10
0
        /// <summary>
        /// Search for a post.
        /// Documentation https://developers.google.com/blogger/v3/reference/posts/search
        /// Generation Note: This does not always build corectly.  Google needs to standardise things I need to figuer out which ones are wrong.
        /// </summary>
        /// <param name="service">Authenticated Blogger service.</param>
        /// <param name="blogId">ID of the blog to fetch the post from.</param>
        /// <param name="q">Query terms to search this blog for matching posts.</param>
        /// <param name="optional">Optional paramaters.</param>
        /// <returns>PostListResponse</returns>
        public static PostList Search(BloggerService service, string blogId, string q, PostsSearchOptionalParms optional = null)
        {
            try
            {
                // Initial validation.
                if (service == null)
                {
                    throw new ArgumentNullException("service");
                }
                if (blogId == null)
                {
                    throw new ArgumentNullException(blogId);
                }
                if (q == null)
                {
                    throw new ArgumentNullException(q);
                }

                // Building the initial request.
                var request = service.Posts.Search(blogId, q);

                // Applying optional parameters to the request.
                request = (PostsResource.SearchRequest)SampleHelpers.ApplyOptionalParms(request, optional);

                // Requesting data.
                return(request.Execute());
            }
            catch (Exception ex)
            {
                throw new Exception("Request Posts.Search failed.", ex);
            }
        }
Exemple #11
0
        /// <summary>
        /// Retrieves the comments for a blog, possibly filtered.
        /// Documentation https://developers.google.com/blogger/v2/reference/comments/list
        /// Generation Note: This does not always build corectly.  Google needs to standardise things I need to figuer out which ones are wrong.
        /// </summary>
        /// <param name="service">Authenticated Blogger service.</param>
        /// <param name="blogId">ID of the blog to fetch comments from.</param>
        /// <param name="postId">ID of the post to fetch posts from.</param>
        /// <param name="optional">Optional paramaters.</param>
        /// <returns>CommentListResponse</returns>
        public static CommentList List(BloggerService service, string blogId, string postId, CommentsListOptionalParms optional = null)
        {
            try
            {
                // Initial validation.
                if (service == null)
                {
                    throw new ArgumentNullException("service");
                }
                if (blogId == null)
                {
                    throw new ArgumentNullException(blogId);
                }
                if (postId == null)
                {
                    throw new ArgumentNullException(postId);
                }

                // Building the initial request.
                var request = service.Comments.List(blogId, postId);

                // Applying optional parameters to the request.
                request = (CommentsResource.ListRequest)SampleHelpers.ApplyOptionalParms(request, optional);

                // Requesting data.
                return(request.Execute());
            }
            catch (Exception ex)
            {
                throw new Exception("Request Comments.List failed.", ex);
            }
        }
Exemple #12
0
        public void BloggerPublicFeedTest()
        {
            Tracing.TraceMsg("Entering BloggerPublicFeedTest");

            FeedQuery      query   = new FeedQuery();
            BloggerService service = new BloggerService(this.ApplicationName);

            String publicURI = (String)this.externalHosts[0];

            if (publicURI != null)
            {
                service.RequestFactory = this.factory;

                query.Uri = new Uri(publicURI);
                AtomFeed feed = service.Query(query);

                if (feed != null)
                {
                    // look for the one with dinner time...
                    foreach (AtomEntry entry in feed.Entries)
                    {
                        Assert.IsTrue(entry.ReadOnly, "The entry should be readonly");
                    }
                }
            }
        }
Exemple #13
0
        //
        // GET: /E3/

        public ActionResult Index()
        {
            string apiKey  = System.Configuration.ConfigurationManager.AppSettings["BloggerApiKey"];
            string appName = System.Configuration.ConfigurationManager.AppSettings["GoogleAppName"];

            BloggerService service = new BloggerService(new Google.Apis.Services.BaseClientService.Initializer()
            {
                ApiKey          = apiKey,
                ApplicationName = appName
            });

            ArticlesHelper helper = new ArticlesHelper(apiKey, appName, service);

            List <Article> nintendoArticles = helper.GetArticlesFromBlog(NintendoBlogId, "Nintendo", 100, 1, "E3 2016", "/Artigos/Ler/");
            List <Article> generalArticles  = helper.GetArticlesFromBlog(MainBlogId, "Multi", 100, 1, "E3 2016", "/Artigos/Ler/");

            List <Article> articles = new List <Article>();

            articles.AddRange(nintendoArticles);
            articles.AddRange(generalArticles);

            ViewData["articles"] = articles.OrderByDescending(t => t.DatePublished).ToList();

            return(View());
        }
        /// <summary>
        /// Authenticate to Google Using Oauth2
        /// Documentation https://developers.google.com/accounts/docs/OAuth2
        /// </summary>
        /// <param name="clientId">From Google Developer console https://console.developers.google.com</param>
        /// <param name="clientSecret">From Google Developer console https://console.developers.google.com</param>
        /// <param name="userName">A string used to identify a user.</param>
        /// <returns></returns>
        public static BloggerService AuthenticateOauth(string clientId, string clientSecret, string userName)
        {
            
            string[] scopes = new string[] { BloggerService.Scope.Blogger,  // view and manage your analytics data                                            
                                             BloggerService.Scope.BloggerReadonly};     // View your Blogs

            try
            {
                // here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData%
                UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = clientId, ClientSecret = clientSecret }
                                                                                             , scopes
                                                                                             , userName
                                                                                             , CancellationToken.None
                                                                                             , new FileDataStore("Daimto.Blogger.Auth.Store")).Result;

                BloggerService service = new BloggerService(new BloggerService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "Blogger API Sample",
                });
                return service;
            }
            catch (Exception ex)
            {

                Console.WriteLine(ex.InnerException);
                return null;

            }

        }
Exemple #15
0
        /// <summary>
        /// Gets one comment by id.
        /// Documentation https://developers.google.com/blogger/v2/reference/comments/get
        /// Generation Note: This does not always build corectly.  Google needs to standardise things I need to figuer out which ones are wrong.
        /// </summary>
        /// <param name="service">Authenticated Blogger service.</param>
        /// <param name="blogId">ID of the blog to containing the comment.</param>
        /// <param name="postId">ID of the post to fetch posts from.</param>
        /// <param name="commentId">The ID of the comment to get.</param>
        /// <returns>CommentResponse</returns>
        public static Comment Get(BloggerService service, string blogId, string postId, string commentId)
        {
            try
            {
                // Initial validation.
                if (service == null)
                {
                    throw new ArgumentNullException("service");
                }
                if (blogId == null)
                {
                    throw new ArgumentNullException(blogId);
                }
                if (postId == null)
                {
                    throw new ArgumentNullException(postId);
                }
                if (commentId == null)
                {
                    throw new ArgumentNullException(commentId);
                }

                // Make the request.
                return(service.Comments.Get(blogId, postId, commentId).Execute());
            }
            catch (Exception ex)
            {
                throw new Exception("Request Comments.Get failed.", ex);
            }
        }
        /// <summary>
        /// Retrieves a list of blogs, possibly filtered.
        /// Documentation https://developers.google.com/blogger/v3/reference/blogs/listByUser
        /// Generation Note: This does not always build corectly.  Google needs to standardise things I need to figuer out which ones are wrong.
        /// </summary>
        /// <param name="service">Authenticated Blogger service.</param>
        /// <param name="userId">ID of the user whose blogs are to be fetched. Either the word 'self' (sans quote marks) or the user's profile identifier.</param>
        /// <param name="optional">Optional paramaters.</param>
        /// <returns>BlogListResponse</returns>
        public static BlogList ListByUser(BloggerService service, string userId, BlogsListByUserOptionalParms optional = null)
        {
            try
            {
                // Initial validation.
                if (service == null)
                {
                    throw new ArgumentNullException("service");
                }
                if (userId == null)
                {
                    throw new ArgumentNullException(userId);
                }

                // Building the initial request.
                var request = service.Blogs.ListByUser(userId);

                // Applying optional parameters to the request.
                request = (BlogsResource.ListByUserRequest)SampleHelpers.ApplyOptionalParms(request, optional);

                // Requesting data.
                return(request.Execute());
            }
            catch (Exception ex)
            {
                throw new Exception("Request Blogs.ListByUser failed.", ex);
            }
        }
Exemple #17
0
        /// <summary>
        /// Revert a published or scheduled page to draft state.
        /// Documentation https://developers.google.com/blogger/v3/reference/pages/revert
        /// Generation Note: This does not always build corectly.  Google needs to standardise things I need to figuer out which ones are wrong.
        /// </summary>
        /// <param name="service">Authenticated Blogger service.</param>
        /// <param name="blogId">The ID of the blog.</param>
        /// <param name="pageId">The ID of the page.</param>
        /// <returns>PageResponse</returns>
        public static Page Revert(BloggerService service, string blogId, string pageId)
        {
            try
            {
                // Initial validation.
                if (service == null)
                {
                    throw new ArgumentNullException("service");
                }
                if (blogId == null)
                {
                    throw new ArgumentNullException(blogId);
                }
                if (pageId == null)
                {
                    throw new ArgumentNullException(pageId);
                }

                // Make the request.
                return(service.Pages.Revert(blogId, pageId).Execute());
            }
            catch (Exception ex)
            {
                throw new Exception("Request Pages.Revert failed.", ex);
            }
        }
Exemple #18
0
        public void BloggerVersion2Test()
        {
            Tracing.TraceMsg("Entering BloggerVersion2Test");

            BloggerQuery   query   = new BloggerQuery();
            BloggerService service = new BloggerService(this.ApplicationName);

            string title = "V1" + Guid.NewGuid().ToString();

            service.ProtocolMajor = 1;

            service.RequestFactory = this.factory;
            query.Uri = new Uri(this.bloggerURI);

            // insert a new entry in version 1

            AtomEntry entry = ObjectModelHelper.CreateAtomEntry(1);

            entry.Categories.Clear();
            entry.Title.Text    = title;
            entry.IsDraft       = true;
            entry.ProtocolMajor = 12;



            AtomEntry returnedEntry = service.Insert(new Uri(this.bloggerURI), entry);

            Assert.IsTrue(returnedEntry.ProtocolMajor == service.ProtocolMajor);
            Assert.IsTrue(entry.IsDraft);
            Assert.IsTrue(returnedEntry.IsDraft);

            BloggerFeed feed = service.Query(query);

            Assert.IsTrue(feed.ProtocolMajor == service.ProtocolMajor);
            if (feed != null)
            {
                Assert.IsTrue(feed.TotalResults >= feed.Entries.Count, "totalresults should be >= number of entries");
                Assert.IsTrue(feed.Entries.Count > 0, "We should have some entries");
            }

            service.ProtocolMajor = 2;
            feed = service.Query(query);
            Assert.IsTrue(feed.ProtocolMajor == service.ProtocolMajor);

            if (feed != null)
            {
                Assert.IsTrue(feed.Entries.Count > 0, "We should have some entries");
                Assert.IsTrue(feed.TotalResults >= feed.Entries.Count, "totalresults should be >= number of entries");

                foreach (BloggerEntry e in feed.Entries)
                {
                    if (e.Title.Text == title)
                    {
                        Assert.IsTrue(e.ProtocolMajor == 2);
                        Assert.IsTrue(e.IsDraft);
                    }
                }
            }
        }
Exemple #19
0
 public void ServiceOpen()
 {
     service = new BloggerService(new BaseClientService.Initializer()
     {
         HttpClientInitializer = credential,
         ApplicationName       = "Buddhika Blogger",
     });
 }
 public void ServiceOpen()
 {
     service = new BloggerService(new BaseClientService.Initializer()
     {
         HttpClientInitializer = credential,
         ApplicationName = "Buddhika Blogger",
     });
 }
        public static Post getPost(BloggerService bs, string blogId, string postId)
        {
            PostsResource.GetRequest req = bs.Posts.Get(blogId, postId);
            req.View = PostsResource.GetRequest.ViewEnum.ADMIN;

            Post p = req.Execute();
            return p;
        }
Exemple #22
0
        public static BlogList getBlogs(BloggerService service, String userId)
        {
            BlogsResource.ListByUserRequest blogListByUserAction = service.Blogs.ListByUser("self");

            BlogList list = blogListByUserAction.Fetch();

            return(list);
        }
 public static BloggerService createService(UserCredential uc, string appName)
 {
     BloggerService bs = new BloggerService(new BaseClientService.Initializer
         {
             HttpClientInitializer = uc,
             ApplicationName = appName
         });
     return bs;
 }
Exemple #24
0
        private static BloggerService BloggerService(UserCredential credential)
        {
            var service = new BloggerService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = "Blogger Console App"
            });

            return(service);
        }
        public static BlogPerUserInfo getBlogUserInfo(BloggerService bs, string blogId)
        {
            if (bs == null)
            {
                return null;
            }

            BlogUserInfosResource.GetRequest req = bs.BlogUserInfos.Get("self", blogId);
            BlogUserInfo bui = req.Execute();

            return bui.BlogUserInfoValue;
        }
 /// <summary>
 /// Retrieves a list of blogs
 ///
 /// Documentation: https://developers.google.com/blogger/docs/3.0/reference/blogs/listByUser
 /// </summary>
 /// <param name="service">a Valid authenticated BloggerService</param>
 /// <param name="user">The ID of the user whose blogs are to be fetched. Either the word self or the user's profile ID.</param>
 /// <returns></returns>
 public static BlogList listByUser(BloggerService service, string user)
 {
     try
     {
         BlogsResource.ListByUserRequest list = service.Blogs.ListByUser(user);
         return(list.Execute());
     }
     catch (Exception ex) {
         // In the event there is an error with the request.
         Console.WriteLine(ex.Message);
     }
     return(null);
 }
        public static List<Pageviews.CountsData> getPageViews(BloggerService bs, string blogId, PageViewsResource.GetRequest.RangeEnum range)
        {
            if (bs == null || getBlogUserInfo(bs, blogId).HasAdminAccess != true)
            {
                return null;
            }

            PageViewsResource.GetRequest req = bs.PageViews.Get(blogId);
            req.Range = range;

            Pageviews pv = req.Execute();
            return pv.Counts.ToList();
        }
 /// <summary>
 /// Retrieves a list of blogs  
 /// 
 /// Documentation: https://developers.google.com/blogger/docs/3.0/reference/blogs/listByUser
 /// </summary>
 /// <param name="service">a Valid authenticated BloggerService</param>        
 /// <param name="user">The ID of the user whose blogs are to be fetched. Either the word self or the user's profile ID.</param>        
 /// <returns></returns>
 public static BlogList listByUser(BloggerService service, string user)
 {
     try
     {                
         BlogsResource.ListByUserRequest list = service.Blogs.ListByUser(user);               
         return list.Execute();              
     }
     catch (Exception ex) {
         // In the event there is an error with the request.
         Console.WriteLine(ex.Message);                            
     }
     return null;
 }
 /// <summary>
   /// Retrieves a blog by its ID.  
   /// 
   /// Documentation: https://developers.google.com/blogger/docs/3.0/reference/blogs/get
   /// </summary>
   /// <param name="service">a Valid authenticated BloggerService</param>        
   /// <param name="id">The ID of the blog to get.</param>  
   /// <param name="maxPosts">Maximum number of posts to retrieve along with the blog. When this parameter is not specified, no posts will be returned as part of the blog resource.</param> 
   /// <returns></returns>
   public static Blog GetFiles(BloggerService service, string id, long maxPosts)
   {
       try
       {
            BlogsResource.GetRequest  list = service.Blogs.Get(id);
           list.MaxPosts = maxPosts;               
           return list.Execute();               
       }
       catch (Exception ex) {
           // In the event there is an error with the request.
           Console.WriteLine(ex.Message);                            
       }
       return null;
   }
Exemple #30
0
        public static CommentList getComments(BloggerService service, BlogLink blogLink, String postId)
        {
            CommentsResource.ListRequest commentsListRequest = null;
            try
            {
                commentsListRequest = new CommentsResource.ListRequest(service, blogLink.blogId, postId);
            }
            catch (Exception ex)
            {
                DAL.InsertAccessLog(blogLink.blogName, blogLink.userId, ex.ToString());
            }

            return(commentsListRequest.Fetch());
        }
Exemple #31
0
        public static async Task AuthenticateAsync()
        {
            var credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                Application.GetResourceStream(new Uri("pack://application:,,,/client_id.json")).Stream,
                new[] { BloggerService.Scope.BloggerReadonly },
                "user",
                CancellationToken.None);

            Service = new BloggerService(new BaseClientService.Initializer
            {
                HttpClientInitializer = credential,
                ApplicationName       = "BloggerQuickViewer",
            });
        }
Exemple #32
0
 BloggerService GetService()
 {
     // Bloggerのインスタンスを取得
     if (service == null)
     {
         var credential = GetCredential();
         service = new BloggerService(new BaseClientService.Initializer()
         {
             HttpClientInitializer = credential,
             ApplicationName       = "Blogger Post"
         });
     }
     return(service);
 }
 /// <summary>
 /// Retrieves a blog by its ID.
 ///
 /// Documentation: https://developers.google.com/blogger/docs/3.0/reference/blogs/get
 /// </summary>
 /// <param name="service">a Valid authenticated BloggerService</param>
 /// <param name="id">The ID of the blog to get.</param>
 /// <param name="maxPosts">Maximum number of posts to retrieve along with the blog. When this parameter is not specified, no posts will be returned as part of the blog resource.</param>
 /// <returns></returns>
 public static Blog GetFiles(BloggerService service, string id, long maxPosts)
 {
     try
     {
         BlogsResource.GetRequest list = service.Blogs.Get(id);
         list.MaxPosts = maxPosts;
         return(list.Execute());
     }
     catch (Exception ex) {
         // In the event there is an error with the request.
         Console.WriteLine(ex.Message);
     }
     return(null);
 }
Exemple #34
0
        public void BloggerHTMLTest()
        {
            Tracing.TraceMsg("Entering BloggerHTMLTest");

            FeedQuery      query   = new FeedQuery();
            BloggerService service = new BloggerService(this.ApplicationName);

            if (this.bloggerURI != null)
            {
                if (this.userName != null)
                {
                    service.Credentials = new GDataCredentials(this.userName, this.passWord);
                }

                service.RequestFactory = this.factory;

                query.Uri = new Uri(this.bloggerURI);
                AtomFeed feed = service.Query(query);

                String strTitle = "Dinner time" + Guid.NewGuid().ToString();

                if (feed != null)
                {
                    // get the first entry
                    String    htmlContent = "<div>&lt;b&gt;this is an html test text&lt;/b&gt;</div>";
                    AtomEntry entry       = ObjectModelHelper.CreateAtomEntry(1);
                    entry.Categories.Clear();
                    entry.Title.Text      = strTitle;
                    entry.Content.Type    = "html";
                    entry.Content.Content = htmlContent;

                    AtomEntry newEntry = feed.Insert(entry);
                    Tracing.TraceMsg("Created blogger entry");

                    // try to get just that guy.....
                    FeedQuery singleQuery = new FeedQuery();
                    singleQuery.Uri = new Uri(newEntry.SelfUri.ToString());
                    AtomFeed  newFeed = service.Query(singleQuery);
                    AtomEntry sameGuy = newFeed.Entries[0];

                    Assert.IsTrue(sameGuy.Title.Text.Equals(newEntry.Title.Text), "both titles should be identical");
                    Assert.IsTrue(sameGuy.Content.Type.Equals("html"));
                    String input  = HttpUtility.HtmlDecode(htmlContent);
                    String output = HttpUtility.HtmlDecode(sameGuy.Content.Content);
                    Assert.IsTrue(input.Equals(output), "The input string should be equal the output string");
                }

                service.Credentials = null;
            }
        }
Exemple #35
0
        public static Post insertPost(BloggerService service, BlogLink blogLink, String content)
        {
            Post postContent = new Post();

            postContent.Title   = "#throughglass";
            postContent.Content = content;
            postContent.Labels  = new List <String>()
            {
                "throughglass"
            };

            PostsResource prInsertAction = service.Posts;

            return(prInsertAction.Insert(postContent, blogLink.blogId).Fetch());
        }
Exemple #36
0
        private void InitializeClientService()
        {
            if (service == null)
            {
                ClientSecrets clientSecrets = Newtonsoft.Json.JsonConvert.DeserializeObject <ClientSecrets>(
                    File.ReadAllText("Assets/client_secrets.json"));

                var initializer = new BaseClientService.Initializer()
                {
                    ApplicationName = "TheFinePrint",
                    ApiKey          = clientSecrets.ApiKey
                };
                service = new BloggerService(initializer);
            }
        }
Exemple #37
0
        public Article GetSingleArticleFromBlogByPath(string blogId, string blogDomain, string path)
        {
            Article article = null;

            try
            {
                BloggerService service = new BloggerService(new Google.Apis.Services.BaseClientService.Initializer()
                {
                    ApiKey          = this.apiKey,
                    ApplicationName = this.applicationName
                });

                PostsResource.GetByPathRequest resource = service.Posts.GetByPath(blogId, path);

                Post post = resource.Execute();

                article       = new Article();
                article.Id    = post.Id;
                article.Title = post.Title;

                if (post.Author != null)
                {
                    article.AuthorData = GetAuthorFromJson(post.Author);
                    article.AuthorName = post.Author.DisplayName;
                }

                article.Content       = post.Content;
                article.CoverImage    = post.Images != null && post.Images.Count > 0 ? post.Images[0].Url : null;
                article.DatePublished = post.Published.HasValue ? post.Published.Value : DateTime.MinValue;

                article.Domain = blogDomain;
                article.GenerateNPartyArticleLink(blogDomain, "/Artigos/Ler/");

                if (post.Labels != null && post.Labels.Count > 0)
                {
                    article.Labels = new string[post.Labels.Count];
                    for (int i = 0; i < post.Labels.Count; i++)
                    {
                        article.Labels[i] = post.Labels[i];
                    }
                }
            }
            catch (Exception e)
            {
            }

            return(article);
        }
        public void Authenticate()
        {
            // here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData%
            credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets
            {
                ClientId = clientId,
                ClientSecret = clientSecret
            }, scopes, userName, CancellationToken.None).Result;
            var initializer = new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = "BloggerApp",
            };

            service = new BloggerService(initializer);
        }
Exemple #39
0
        //
        // GET: /ESports/EVO/

        public ActionResult Index(int?page)
        {
            string apiKey  = System.Configuration.ConfigurationManager.AppSettings["ESportsBloggerApiKey"];
            string appName = System.Configuration.ConfigurationManager.AppSettings["ESportsGoogleAppName"];

            BloggerService service = new BloggerService(new Google.Apis.Services.BaseClientService.Initializer()
            {
                ApiKey          = apiKey,
                ApplicationName = appName
            });

            ArticlesHelper helper = new ArticlesHelper(apiKey, appName, service);

            List <Article> generalArticles = helper.GetArticlesFromBlog(ESportsBlogId, "ESports", 100, 1, "EVO 2016", "/Artigos/Ler/");

            ViewData["articles"] = generalArticles;

            return(View());
        }
Exemple #40
0
        public static Post updatePostTitle(BloggerService service, BlogLink blogLink, PostManager postManager, String content)
        {
            Post patchContent = new Post();

            patchContent.Title = content;

            patchContent.Content = postManager.postContent;

            patchContent.Id = postManager.postId;

            patchContent.Labels = new List <String>()
            {
                "throughglass"
            };

            PostsResource.PatchRequest prPatchRequest = service.Posts.Patch(patchContent, blogLink.blogId, postManager.postId);

            return(prPatchRequest.Fetch());
        }
        private async Task AuthenticateAsync()
        {
            if (service != null)
                return;

            credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                new Uri("ms-appx:///Assets/client_secrets.json"),
                new[] { BloggerService.Scope.BloggerReadonly },
                "user",
                CancellationToken.None);

            var initializer = new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = "BloggerApp",
            };

            service = new BloggerService(initializer);
        }
Exemple #42
0
        private async Task AuthenticateAsync()
        {
            if (service != null)
            {
                return;
            }

            credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                new Uri("ms-appx:///Assets/client_secrets.json"),
                new[] { BloggerService.Scope.BloggerReadonly },
                "user",
                CancellationToken.None);

            var initializer = new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = "BloggerApp",
            };

            service = new BloggerService(initializer);
        }
Exemple #43
0
        private static void InsertPost(BloggerService service, string title, string blogId, List <string> labels, string content)
        {
            //WebClient wc = new WebClient();
            //byte[] bytes = wc.DownloadData(@"C:\Users\v-santt\Desktop\1.jpg");
            //Post.ImagesData image = new Post.ImagesData();

            //var url = System.Web.HttpUtility.UrlEncode("https://1.bp.blogspot.com/-kqFVZAmU6nE/XseAVmNjpZI/AAAAAAABUyA/wEnCVeLOfJ8hT_KUPPrghoDy3JV5u3swwCK4BGAsYHg/MV5BYjljZGFjNzktZjJlZC00ODkxLWExZGUtYjhmOWMxNGU1YTljXkEyXkFqcGdeQXVyNDc2NzU1MTA%2540._V1_QL50_SY1000_CR0%252C0%252C756%252C1000_AL_.jpg");
            //image.Url = url;
            //List<Post.ImagesData> images = new List<Post.ImagesData>();
            //// images.Add(url);
            ////images.Add((Post.ImagesData)image.Url);
            //images.Add(image);
            var insertRequest = service.Posts.Insert(new Post()
            {
                Title   = title,
                Content = content,
                Labels  = labels,
            }, blogId: blogId);;

            insertRequest.Execute();
        }
 public void Login()
 {
     _ucUser = BloggerHelper.createCredential(_csAppSec, _fdsStore);
     _bsBlogger = BloggerHelper.createService(_ucUser, _strAppName);
 }
        public async Task GetDataBlogZaSeriozniHora(string pageToken, Action<PageModel, Exception> callback)
        {
            string uri = "http://blogzaserioznihora.blogspot.com/";

            Exception err = null;
            var result = new PageModel();
            try
            {
                BloggerService _service = new BloggerService(new BaseClientService.Initializer()
                {
                    ApiKey = "AIzaSyCkyf5p4x_2tW-Bwmqt7Bbj-HhFIC_kXvw",
                });

                SiteModel site = Sites.FirstOrDefault(x => x.Title == "Блог за сериозни хора");
                if (site == null)
                {
                    var blog = await _service.Blogs.GetByUrl(uri).ExecuteAsync();
                    site = new SiteModel()
                    {
                        Title = "Блог за сериозни хора",
                        Id = blog.Id
                    };
                    
                    //group.ImagePath = blog.
                    Sites.Add(site);
                }

                PageModel page = site.Pages.FirstOrDefault(x => x.CurrentPageToken == pageToken);
                if (page != null)
                {
                    result = page;
                }
                else
                {
                    var getPosts = _service.Posts.List(site.Id);
                    getPosts.MaxResults = 8;
                    if (!string.IsNullOrEmpty(pageToken))
                    {
                        getPosts.PageToken = pageToken;
                        result.CurrentPageToken = pageToken;
                    }

                    var response = await getPosts.ExecuteAsync();
                    result.NextPageToken = response.NextPageToken;
                    result.PrevPageToken = response.PrevPageToken;
                    result.PageIndex = site.Pages.Count;

                    foreach (var item in response.Items)
                    {
                        var itemModel = new ItemModel()
                        {
                            Id = item.Id,
                            Title = item.Title,
                            OriginalItem = item,
                            //Parent = result,
                            OriginalUrl = item.Url,
                            CommentUrl = "http://www.blogger.com/comment.g?blogID=" + site.Id + "&postID="+ item.Id +"&isPopup=true"
                        };

                        var document = new HtmlDocument();
                        document.LoadHtml(WebContentHelper.WrapHtml(item.Content, 0, 0));

                        itemModel.Content = RefactorContent(document);

                        var img = document.DocumentNode.Descendants().FirstOrDefault(doc => doc.Name == "img" &&
                            (doc.Attributes["src"].Value.EndsWith(".jpg") || doc.Attributes["src"].Value.EndsWith(".gif") || doc.Attributes["src"].Value.EndsWith(".png")));
                        if (img != null)
                        {
                            itemModel.ImagePath = img.Attributes["src"].Value;
                        }

                        AddItemToTiles(itemModel);

                        result.Items.Add(itemModel);
                        if (string.IsNullOrEmpty(pageToken))
                        {
                            site.Items.Add(itemModel);
                        }
                    }
                    site.Pages.Add(result);
                }
            }
            catch (Exception ex)
            {
                err = ex;
            }

            callback(result, err);
        }
Exemple #46
0
        public void Login()
        {
            //Timeout
            new Thread(delegate()
            {
                Thread.Sleep(30000);
                if (_ucUser == null)
                {
                    throw new Exception("Authorization timeout 30s");
                }
            }) { IsBackground = true }.Start();

            _ucUser = GoogleWebAuthorizationBroker.AuthorizeAsync(
                _csAppSec,
                new[] { BloggerService.Scope.Blogger },
                "user",
                CancellationToken.None,
                _fdsToken
                ).Result;

            _bsBlog = new BloggerService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = _ucUser,
                    ApplicationName = "Blogger Manager"
                });
        }
        public static List<Blog> listAllBlogs(BloggerService bs)
        {
            if (bs == null)
            {
                return null;
            }

            BlogsResource.ListByUserRequest req = bs.Blogs.ListByUser("self");
            BlogList bl = req.Execute();

            return bl.Items.ToList();
        }
Exemple #48
0
 public void Logout()
 {
     _ucUser = null;
     _bsBlog = null;
     _blBlogs = null;
     _fdsToken.ClearAsync();
 }
 public void Logout()
 {
     _ucUser = null;
     _bsBlogger = null;
     _fdsStore.ClearAsync();
 }