/// <summary>
    /// Form OnAfterSave event.
    /// </summary>
    private void Form_OnAfterSave(object sender, EventArgs e)
    {
        if (TweetInfo == null || !HasUserModifyPermission)
        {
            return;
        }

        if (Document != null)
        {
            if (!TweetInfo.TwitterPostDocumentGUID.HasValue)
            {
                TweetInfo.TwitterPostDocumentGUID = Document.DocumentGUID;
            }

            if (TweetInfo.TwitterPostPostAfterDocumentPublish && !IsUnderWorkflow && !TweetInfo.IsPublished)
            {
                // Tweet will be scheduled on time when document gets published
                TweetInfo.TwitterPostScheduledPublishDateTime = Document.DocumentPublishFrom;
            }

            if (TweetInfo.HasChanged)
            {
                TwitterPostInfoProvider.SetTwitterPostInfo(TweetInfo);
            }
        }

        // Check whether the tweet should be published or scheduled now (tweet WON'T be published/scheduled if it should be published with the document which is under workflow)
        if (!TweetInfo.IsPublished && !(TweetInfo.TwitterPostPostAfterDocumentPublish && IsUnderWorkflow))
        {
            PublishPost(TweetInfo.TwitterPostID);
        }
        LoadPostDataIntoControl(TweetInfo);
    }
    /// <summary>
    /// Creates a new tweet. Requires Create Twitter app and Create Twitter channel to be run first.
    /// </summary>
    private bool CreateTwitterPost()
    {
        // Get the channel the tweet is tied to
        TwitterAccountInfo channel = TwitterAccountInfoProvider.GetTwitterAccountInfo("MyNewTwitterChannel", SiteContext.CurrentSiteID);

        if (channel == null)
        {
            throw new Exception("[ApiExamples.CreateTwitterPost]: Account 'MyNewTwitterChannel' has not been found.");
        }

        // Create new post object
        TwitterPostInfo tweet = new TwitterPostInfo();

        // Set the roperties
        tweet.TwitterPostTwitterAccountID = channel.TwitterAccountID;
        tweet.TwitterPostSiteID           = SiteContext.CurrentSiteID;
        tweet.TwitterPostText             = "Sample tweet text.";

        // Should the tweet be scheduled instead of directly posted?
        tweet.TwitterPostScheduledPublishDateTime = DateTime.Now + TimeSpan.FromMinutes(5);

        // Save the tweet into DB
        TwitterPostInfoProvider.SetTwitterPostInfo(tweet);

        return(true);
    }
    /// <summary>
    /// Gets and updates a tweet
    /// </summary>
    private bool GetAndUpdateTwitterPost()
    {
        // Get the channel the tweet is tied to
        TwitterAccountInfo channel = TwitterAccountInfoProvider.GetTwitterAccountInfo("MyNewTwitterChannel", SiteContext.CurrentSiteID);

        if (channel == null)
        {
            throw new Exception("[ApiExamples.GetAndUpdateTwitterPost]: Account 'MyNewTwitterChannel' has not been found.");
        }

        // Get a post tied to the channel
        TwitterPostInfo tweet = TwitterPostInfoProvider.GetTwitterPostInfoByAccountId(channel.TwitterAccountID).FirstOrDefault();

        if (tweet == null)
        {
            throw new Exception("[ApiExamples.GetAndUpdateTwitterPost]: No post has been created via these api-examples. (There is no post tied to 'MyNewTwitterChannel'.)");
        }

        // Update the properties
        tweet.TwitterPostText = tweet.TwitterPostText + " Edited.";

        // Save the changes into DB
        TwitterPostInfoProvider.SetTwitterPostInfo(tweet);

        return(true);
    }
    /// <summary>
    /// OnAfterDataLoad event
    /// </summary>
    private void ControlOnAfterDataLoad(object sender, EventArgs eventArgs)
    {
        TwitterPostInfo twitterPost = Control.EditedObject as TwitterPostInfo;

        if (twitterPost == null)
        {
            return;
        }

        if (twitterPost.TwitterPostID > 0)
        {
            string message = TwitterPostInfoProvider.GetPostPublishStateMessage(twitterPost, MembershipContext.AuthenticatedUser, SiteContext.CurrentSite);
            if (twitterPost.IsFaulty)
            {
                Control.ShowError(message);
            }
            else
            {
                Control.ShowInformation(message);
            }

            // Disable control if post has already been published or is faulty
            Control.Enabled = !(twitterPost.IsPublished || twitterPost.IsFaulty);
        }
    }
    /// <summary>
    /// OnAfterSave event.
    /// </summary>
    private void ControlOnAfterSave(object sender, EventArgs eventArgs)
    {
        TwitterPostInfo twitterPost = Control.EditedObject as TwitterPostInfo;

        if (twitterPost == null)
        {
            return;
        }

        if (!twitterPost.TwitterPostPostAfterDocumentPublish)
        {
            try
            {
                TwitterPostInfoProvider.PublishTwitterPost(twitterPost.TwitterPostID);
            }
            catch (Exception ex)
            {
                EventLogProvider.LogWarning("Social marketing - Twitter post", "PUBLISHPOST", ex, SiteContext.CurrentSiteID,
                                            String.Format("An error occurred while publishing the Twitter post with ID {0}.", twitterPost.TwitterPostID));
                Control.ShowError(Control.GetString("sm.twitter.posts.msg.unknownerror"));
            }
        }

        // Invoke event to set the form's state properly
        ControlOnAfterDataLoad(sender, eventArgs);
    }
 /// <summary>
 /// Publishes Twitter post with given identifier.
 /// </summary>
 /// <param name="postId">Twitter post identifier.</param>
 private void PublishPost(int postId)
 {
     try
     {
         TwitterPostInfoProvider.TryCancelScheduledPublishTwitterPost(postId);
         TwitterPostInfoProvider.PublishTwitterPost(postId);
     }
     catch (Exception ex)
     {
         EventLogProvider.LogWarning("Social marketing - Twitter post", "PUBLISHPOST", ex, SiteContext.CurrentSiteID,
                                     String.Format("An error occurred while publishing the Twitter post with ID {0}.", postId));
     }
 }
    /// <summary>
    /// Gets localized message describing post state.
    /// </summary>
    /// <param name="postId">Post id.</param>
    private object GetPostState(int postId)
    {
        switch (Control.ObjectType)
        {
        // Facebook post
        case FacebookPostInfo.OBJECT_TYPE:
            FacebookPostInfo facebookPost = FacebookPostInfoProvider.GetFacebookPostInfo(postId);
            return(FacebookPostInfoProvider.GetPostPublishStateMessage(facebookPost, MembershipContext.AuthenticatedUser, SiteContext.CurrentSite, true));

        // Twitter post
        case TwitterPostInfo.OBJECT_TYPE:
            TwitterPostInfo twitterPost = TwitterPostInfoProvider.GetTwitterPostInfo(postId);
            return(TwitterPostInfoProvider.GetPostPublishStateMessage(twitterPost, MembershipContext.AuthenticatedUser, SiteContext.CurrentSite, true));
        }

        return(String.Empty);
    }
 /// <summary>
 /// OnAction for Twitter post object type.
 /// </summary>
 /// <param name="actionName"></param>
 /// <param name="actionArgument">Integer ID as a string.</param>
 private void OnAction_Twitter(string actionName, object actionArgument)
 {
     switch (actionName)
     {
     case "delete":
         try
         {
             TwitterPostInfoProvider.DeleteTwitterPostInfo(ValidationHelper.GetInteger(actionArgument, 0));
         }
         catch (Exception ex)
         {
             EventLogProvider.LogWarning("Social marketing - Twitter post", "DELETEPOST", ex, SiteContext.CurrentSiteID, "Twitter post could not be deleted.");
             Control.ShowError(Control.GetString("sm.twitter.posts.msg.deleteerror"));
         }
         break;
     }
 }
    /// <summary>
    /// Form OnBeforeDataRetrieval.
    /// </summary>
    private void Form_OnBeforeDataRetrieval(object sender, EventArgs eventArgs)
    {
        if (!HasUserModifyPermission)
        {
            return;
        }

        if (chkPostToTwitter.Checked)
        {
            if ((TweetInfo == null) || TweetInfo.IsEditable)
            {
                // Post does not exist or can be modified
                TweetInfo = SetControlDataIntoPost(TweetInfo);
                TwitterPostInfoProvider.SetTwitterPostInfo(TweetInfo);
            }
            else if (!FormDataEqualsPostInfo(TweetInfo))
            {
                mPublishedWhileEditing = true;
            }
        }
        else
        {
            // Checkbox post to Twitter is not checked
            if (TweetInfo != null)
            {
                if (TweetInfo.IsEditable)
                {
                    // Existing post has to be deleted
                    TwitterPostInfoProvider.DeleteTwitterPostInfo(TweetInfo);
                    TweetInfo = null;
                    InitializeControls();
                }
                else
                {
                    mPublishedWhileEditing = true;
                }
            }
            else if (mBackCompatibilityValue.HasValue)
            {
                // Form has to be cleaned up from old value
                mBackCompatibilityValue = null;
                InitializeControls();
            }
        }
    }
    /// <summary>
    /// Deletes all tweets tied to channel 'MyNewTwitterChannel'.
    /// </summary>
    private bool DeleteTwitterPosts()
    {
        // Get the channel the tweet is tied to
        TwitterAccountInfo channel = TwitterAccountInfoProvider.GetTwitterAccountInfo("MyNewTwitterChannel", SiteContext.CurrentSiteID);

        if (channel == null)
        {
            throw new Exception("[ApiExamples.DeleteTwitterPosts]: Account 'MyNewTwitterChannel' has not been found.");
        }

        // Get all posts tied to the account
        ObjectQuery <TwitterPostInfo> tweets = TwitterPostInfoProvider.GetTwitterPostInfoByAccountId(channel.TwitterAccountID);

        // Delete these posts from CMS and from Twitter
        foreach (TwitterPostInfo tweet in tweets)
        {
            TwitterPostInfoProvider.DeleteTwitterPostInfo(tweet);
        }

        return(tweets.Count != 0);
    }
    /// <summary>
    /// OnBeforeSave event.
    /// </summary>
    private void Control_OnBeforeSave(object sender, EventArgs eventArgs)
    {
        TwitterPostInfo twitterPost = Control.EditedObject as TwitterPostInfo;

        if (twitterPost == null)
        {
            return;
        }

        if (twitterPost.TwitterPostID <= 0)
        {
            // The post is being created, not edited
            return;
        }

        if (!TwitterPostInfoProvider.TryCancelScheduledPublishTwitterPost(twitterPost))
        {
            // The post has been published during user edit. Prevent the changes to take effect
            CancelPendingSave(Control.GetString("sm.twitter.posts.msg.editforbidden"));
        }
    }
    /// <summary>
    /// Shows given Twitter post's publish state.
    /// </summary>
    /// <param name="post">Twitter post.</param>
    private void ShowPostPublishState(TwitterPostInfo post)
    {
        string message = TwitterPostInfoProvider.GetPostPublishStateMessage(post, MembershipContext.AuthenticatedUser, CurrentSite);

        if (String.IsNullOrEmpty(message))
        {
            return;
        }

        if (post.IsFaulty)
        {
            var errorMessage = FormatErrorMessage(message);
            ShowError(errorMessage);
        }
        else if (post.IsPublished)
        {
            ShowConfirmation(message);
        }
        else
        {
            ShowInformation(message);
        }
    }
    /// <summary>
    /// Shows given Twitter post's publish state.
    /// </summary>
    /// <param name="post">Twitter post.</param>
    private void ShowPostPublishState(TwitterPostInfo post)
    {
        string message = TwitterPostInfoProvider.GetPostPublishStateMessage(post, MembershipContext.AuthenticatedUser, CurrentSite);

        if (String.IsNullOrEmpty(message))
        {
            return;
        }

        if (post.IsFaulty)
        {
            ShowPostStateError(message);
            ShowError(String.Format("<strong>{0}</strong>: {1}", GetString("sm.twitter.autopost"), message));
        }
        else if (post.IsPublished)
        {
            ShowPostStateSuccess(message);
        }
        else
        {
            ShowPostStateInformation(message, MessageTypeEnum.Information);
        }
    }
    /// <summary>
    /// Publishes a tweet.
    /// </summary>
    private bool PublishTweetToTwitter()
    {
        // Get the channel the tweet is tied to
        TwitterAccountInfo channel = TwitterAccountInfoProvider.GetTwitterAccountInfo("MyNewTwitterChannel", SiteContext.CurrentSiteID);

        if (channel == null)
        {
            throw new Exception("[ApiExamples.PublishTweetToTwitter]: Account 'MyNewTwitterChannel' has not been found.");
        }

        // Get a post tied to the channel
        TwitterPostInfo tweet = TwitterPostInfoProvider.GetTwitterPostInfoByAccountId(channel.TwitterAccountID).FirstOrDefault();

        if (tweet == null)
        {
            throw new Exception("[ApiExamples.PublishTweetToTwitter]: No post has been created via these api-examples. (There is no post tied to 'MyNewTwitterChannel'.)");
        }

        // Publish the post. The Tweet is scheduled for publishing if its FacebookPostScheduledPublishDateTime is set in the future.
        TwitterPostInfoProvider.PublishTwitterPost(tweet.TwitterPostID);

        return(true);
    }