Example #1
0
        public async Task <IActionResult> OnPostTWIAsync()
        {
            TwitterAccountInfo TAI = new TwitterAccountInfo();

            TAI.TwitterAccountInfoID   = int.Parse(Request.Form["AccountInfoID"]);
            TAI.Hashtags               = Request.Form["Hashtags"];
            TAI.LastHashtagSearched    = Request.Form["LastHashtagSearched"];
            TAI.FollowsToday           = int.Parse(Request.Form["FollowsToday"]);
            TAI.MaxRunsPerDay          = int.Parse(Request.Form["MaxRunsPerDay"]);
            TAI.UnfollowDaysThreshold  = int.Parse(Request.Form["UnfollowDaysThreshold"]);
            TAI.LastMutualFollowCheck  = DateTime.Parse(Request.Form["LastMutualFollowCheck"]);
            TAI.LastTimeManagedFollows = DateTime.Parse(Request.Form["LastTimeManagedFollows"]);
            TAI.LastTimeSearched       = DateTime.Parse(Request.Form["LastTimeSearched"]);
            TAI.NextTimeManagedFollows = DateTime.Parse(Request.Form["NextTimeManagedFollows"]);
            TAI.NextTimeSearched       = DateTime.Parse(Request.Form["NextTimeSearched"]);


            string en = Request.Form["Enabled"];

            if (en == "on" || en == "true")
            {
                TAI.AutoExpandThisAccount = true;
            }
            else
            {
                TAI.AutoExpandThisAccount = false;
            }

            string response = await DS.PutAsyncString(TAI, "Twitter/UpdateTwitterAccountInfo");


            await GetData();

            return(Page());
        }
Example #2
0
    /// <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);
    }
Example #3
0
    /// <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);
    }
Example #4
0
    /// <summary>
    /// Creates a Twitter channel.
    /// </summary>
    private bool CreateTwitterChannel()
    {
        if (string.IsNullOrEmpty(txtAccessToken.Text) || string.IsNullOrEmpty(txtAccessTokenSecret.Text))
        {
            throw new Exception("[ApiExamples.CreateTwitterChannel]: Empty values for 'Channel access token' and 'Channel access token secret' are not allowed. Please provide your channel's credentials.");
        }

        // Get the app the channel is tied to.
        TwitterApplicationInfo app = TwitterApplicationInfoProvider.GetTwitterApplicationInfo("MyNewTwitterApp", SiteContext.CurrentSiteName);

        if (app == null)
        {
            throw new Exception("[ApiExamples.CreateTwitterChannel]: Application 'MyNewTwitterApp' was not found.");
        }

        // Create new channel object
        TwitterAccountInfo channel = new TwitterAccountInfo();

        // Set the properties
        channel.TwitterAccountDisplayName = "My new Twitter channel";
        channel.TwitterAccountName        = "MyNewTwitterChannel";

        channel.TwitterAccountAccessToken          = txtAccessToken.Text;
        channel.TwitterAccountAccessTokenSecret    = txtAccessTokenSecret.Text;
        channel.TwitterAccountSiteID               = SiteContext.CurrentSiteID;
        channel.TwitterAccountTwitterApplicationID = app.TwitterApplicationID;

        // Save the channel into DB
        TwitterAccountInfoProvider.SetTwitterAccountInfo(channel);

        return(true);
    }
Example #5
0
 private void Initialize()
 {
     _twitterAccountInformation = _twitterPersistenceService.Load();
     _twitterService            = new TwitterService(Constants.ConsumerKey,
                                                     Constants.ConsumerSecret);
     _twitterService.AuthenticateWith(_twitterAccountInformation.AccessToken,
                                      _twitterAccountInformation.AccessTokenSecret);
     _twitterAccount = _twitterService.GetAccountSettings();
 }
    /// <summary>
    /// Initializes inner controls. Post data are loaded when editing post.
    /// </summary>
    private void InitializeControls()
    {
        chkPostAfterDocumentPublish.Checked = false;

        string content = String.Empty;

        if (mBackCompatibilityValue.HasValue)
        {
            // Pre fill form with old data
            chkPostAfterDocumentPublish.Checked = mBackCompatibilityValue.Value.AutoPostAfterPublishing;
            content = mBackCompatibilityValue.Value.Template;
        }
        else if (!String.IsNullOrWhiteSpace(mDefaultValue))
        {
            // Default content given as control's string Value
            content = mDefaultValue;
        }
        else if ((FieldInfo != null) && !String.IsNullOrWhiteSpace(FieldInfo.DefaultValue))
        {
            // Default content from field info
            content = FieldInfo.DefaultValue;
        }
        tweetContent.Text = content;

        if (!chkPostAfterDocumentPublish.Checked)
        {
            publishDateTime.Value = DateTime.Now;
        }

        channelSelector.ObjectSiteName = SiteIdentifier;
        TwitterAccountInfo defaultAccountInfo = TwitterAccountInfoProvider.GetDefaultTwitterAccount(SiteIdentifier);

        if (defaultAccountInfo != null)
        {
            channelSelector.Value = defaultAccountInfo.TwitterAccountID;
        }

        ClearPostState();
        urlShortenerSelector.SiteID         = SiteIdentifier;
        urlShortenerSelector.Value          = URLShortenerHelper.GetDefaultURLShortenerForSocialNetwork(SocialNetworkTypeEnum.Twitter, SiteIdentifier);
        chkPostAfterDocumentPublish.Visible = (Document != null);
        campaingSelector.Value          = null;
        campaingSelector.ObjectSiteName = SiteIdentifier;

        if ((FieldInfo != null) && !FieldInfo.AllowEmpty)
        {
            // Post must be created because field doesn't allow an empty value
            chkPostToTwitter.Enabled = false;
            DisplayForm = true;
        }
        else
        {
            // Form is displayed if it is pre filled with old data
            DisplayForm = mBackCompatibilityValue.HasValue;
        }
    }
Example #7
0
    /// <summary>
    /// Gets twitter User ID and caches it to avoid exceeding limits
    /// </summary>
    /// <param name="twittAppInfo">Application to use to interact with Twitter</param>
    /// <param name="twittAccountInfo">Channel to be used to interact with Twitter</param>
    /// <returns>null on failure, correct Twitter UserId otherwise</returns>
    private static string GetTwitterUserId(TwitterApplicationInfo twittAppInfo, TwitterAccountInfo twittAccountInfo)
    {
        string key    = String.Join(":", twittAppInfo.TwitterApplicationConsumerKey, twittAppInfo.TwitterApplicationConsumerSecret, twittAccountInfo.TwitterAccountAccessToken, twittAccountInfo.TwitterAccountAccessTokenSecret);
        string userId = null;

        if (!mTwitterIDs.TryGetValue(key, out userId))
        {
            userId = TwitterHelper.GetTwitterUserId(twittAppInfo.TwitterApplicationConsumerKey, twittAppInfo.TwitterApplicationConsumerSecret, twittAccountInfo.TwitterAccountAccessToken, twittAccountInfo.TwitterAccountAccessTokenSecret);
            mTwitterIDs.Add(key, userId);
        }

        return(userId);
    }
Example #8
0
    /// <summary>
    /// Deletes a channel from DB
    /// </summary>
    private bool DeleteTwitterChannel()
    {
        // Get the channel from DB
        TwitterAccountInfo channel = TwitterAccountInfoProvider.GetTwitterAccountInfo("MyNewTwitterChannel", SiteContext.CurrentSiteID);

        if (channel == null)
        {
            return(false);
        }

        // Delete channel from DB
        TwitterAccountInfoProvider.DeleteTwitterAccountInfo(channel);

        return(true);
    }
Example #9
0
    /// <summary>
    /// Gets a Twitter channel from the database and modifies it.
    /// </summary>
    private bool GetAndUpdateTwitterChannel()
    {
        // Get the channel from DB
        TwitterAccountInfo channel = TwitterAccountInfoProvider.GetTwitterAccountInfo("MyNewTwitterChannel", SiteContext.CurrentSiteID);

        if (channel == null)
        {
            return(false);
        }

        // Update the properties
        channel.TwitterAccountDisplayName = channel.TwitterAccountDisplayName.ToLowerCSafe();

        // Save the changes into DB
        TwitterAccountInfoProvider.SetTwitterAccountInfo(channel);

        return(true);
    }
        public override string RenderToString(Guid contactId)
        {
            Contact model = GetContact(contactId);

            var twitter = new StringBuilder();

            TwitterAccountInfo t = null;

            if (model.Facets.ContainsKey("TwitterAccountInfo"))
            {
                t = (TwitterAccountInfo)model.Facets["TwitterAccountInfo"];
            }

            twitter.Append("<div id=\"SocialRow\" class=\"row\">");
            twitter.Append("<div id=\"LeftContactColumn\" class=\"col-md-4\">");
            twitter.Append(
                "<span style=\"padding-bottom:15px;color:#121212;font-weight:bold;font-size:1.167em;\" id=\"SocialTitle\">Twitter</span>");

            if (t == null)
            {
                twitter.Append("<div id=\"TwitterHandleBorder\">");
                twitter.Append("<span id=\"TwitterHandleLabel\"><em>No Twitter account info available.</em></span></div>");
            }
            else
            {
                twitter.Append("<div id=\"TwitterHandleBorder\">");
                twitter.Append("<span id=\"TwitterHandleLabel\">Twitter Handle: &nbsp;</span>");
                twitter.Append($"<span id=\"TwitterHandleValue\">{t.TwitterHandle}</span></div>");
                twitter.Append("<div id=\"NumFollowersBorder\">");
                twitter.Append("<span id=\"NumFollowersLabel\">Number of Followers: &nbsp;</span>");
                twitter.Append($"<span id=\"NumFollowersValue\">{t.NumberOfFollowers}</span></div>");
                twitter.Append("<div id=\"AcctAgeBorder\">");
                twitter.Append("<span id=\"AcctAgeLabel\">Account Age: &nbsp;</span>");
                twitter.Append($"<span id=\"AcctAgeValue\">{t.TwitterStartDate.ToShortDateString()}</span></div>");
                twitter.Append("<div id=\"VerifiedBorder\">");
                twitter.Append("<span id=\"VerifiedLabel\">Verified: &nbsp;</span>");
                twitter.Append($"<span id=\"VerifiedValue\">{t.VerifiedTwitterHandle}</span></div>");
            }
            twitter.Append("</div><div id=\"MiddleContactColumn\" class=\"col-md-4\"></div>");
            twitter.Append("<div id=\"RightContactColumn\" class=\"col-md-4\"></div>");
            twitter.Append("</div>");

            return(twitter.ToString());
        }
    /// <summary>
    /// OnBeforeDataLoad event - Ensures default account is pre-selected.
    /// </summary>
    private void Control_OnBeforeDataLoad(object sender, EventArgs e)
    {
        var twitterPost = Control.EditedObject as TwitterPostInfo;

        if (twitterPost == null)
        {
            return;
        }

        // if the post is newly created fill in default page
        if (twitterPost.TwitterPostID == 0)
        {
            TwitterAccountInfo defaultTwitterAccountInfo = TwitterAccountInfoProvider.GetDefaultTwitterAccount(Control.ObjectSiteID);
            if (defaultTwitterAccountInfo != null)
            {
                twitterPost.TwitterPostTwitterAccountID = defaultTwitterAccountInfo.TwitterAccountID;
            }
        }
    }
    /// <summary>
    /// Creates an object that represents information required by this page to display Twitter insights, and returns it.
    /// </summary>
    /// <param name="accountId">The Twitter account identifier.</param>
    /// <returns>An object that represents information required by this page to display Twitter insights.</returns>
    private PageContext GetPageContextForTwitter(int accountId)
    {
        TwitterAccountInfo account = TwitterAccountInfoProvider.GetTwitterAccountInfo(accountId);

        if (account == null || account.TwitterAccountSiteID != SiteContext.CurrentSiteID)
        {
            throw new Exception("[CMSModules_SocialMarketing_Pages_InsightsMenu.GetPageContextForTwitter]: Twitter account with the specified identifier does not exist.");
        }
        if (!account.CheckPermissions(PermissionsEnum.Read, SiteContext.CurrentSiteName, MembershipContext.AuthenticatedUser))
        {
            RedirectToAccessDenied(ModuleName.SOCIALMARKETING, PermissionsEnum.Read.ToString());
        }

        return(new PageContext
        {
            ExternalId = account.TwitterAccountUserID,
            ReportNamePrefix = "Twitter.channel_",
            ReportNameFormat = "Twitter.{0}.{1}.{2}report",
            DisplayNameResourceNameFormat = "sm.ins.twitter.{0}"
        });
    }
Example #13
0
    /// <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);
    }
Example #14
0
    /// <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);
    }
Example #15
0
    private void Control_OnBeforeSave(object sender, EventArgs e)
    {
        TwitterAccountInfo account = Control.EditedObject as TwitterAccountInfo;

        if (account != null)
        {
            TwitterApplicationInfo application = TwitterApplicationInfoProvider.GetTwitterApplicationInfo(account.TwitterAccountTwitterApplicationID);
            try
            {
                account.TwitterAccountUserID = TwitterHelper.GetTwitterUserId(application.TwitterApplicationConsumerKey, application.TwitterApplicationConsumerSecret, account.TwitterAccountAccessToken, account.TwitterAccountAccessTokenSecret);
                string errorMessage = null;
                Validate <TwitterAccountInfo>("TwitterAccountUserID", account.TwitterAccountUserID, "sm.twitter.account.msg.useridexists", ref errorMessage);
                if (!String.IsNullOrEmpty(errorMessage))
                {
                    CancelPendingSave(errorMessage);
                }
            }
            catch
            {
                string errorMessage = ResHelper.GetString("sm.twitter.account.msg.getuseridfail");
                CancelPendingSave(errorMessage);
            }
        }
    }
        private async Task Register(PipelineArgs arg)
        {
            CertificateHttpClientHandlerModifierOptions options =
                CertificateHttpClientHandlerModifierOptions.Parse("StoreName=My;StoreLocation=LocalMachine;FindType=FindByThumbprint;FindValue=" + Constants.XConnectThumbprint);

            var certificateModifier = new CertificateHttpClientHandlerModifier(options);

            List <IHttpClientModifier> clientModifiers = new List <IHttpClientModifier>();
            var timeoutClientModifier = new TimeoutHttpClientModifier(new TimeSpan(0, 0, 20));

            clientModifiers.Add(timeoutClientModifier);

            var collectionClient    = new CollectionWebApiClient(new Uri(Constants.XConnectInstance + "/odata"), clientModifiers, new[] { certificateModifier });
            var searchClient        = new SearchWebApiClient(new Uri(Constants.XConnectInstance + "/odata"), clientModifiers, new[] { certificateModifier });
            var configurationClient = new ConfigurationWebApiClient(new Uri(Constants.XConnectInstance + "/configuration"), clientModifiers, new[] { certificateModifier });

            var cfg = new XConnectClientConfiguration(
                new XdbRuntimeModel(ProductTrackingModel.Model), collectionClient, searchClient, configurationClient);


            foreach (var interactionEvent in arg.ProcessingResult.Interaction.Interaction.Events)
            {
                if (interactionEvent.CustomValues != null && interactionEvent.CustomValues.Count > 0)
                {
                    var name      = interactionEvent.CustomValues["name"].Split(' ');
                    var firstName = name[0] != null ? name[0] : "Not Available";
                    var lastName  = name.Length > 1 ? name[1] : "Not Available";

                    var twitterHandle        = interactionEvent.CustomValues["twitterhandle"];
                    var twitterHandleCreated = Convert.ToDateTime(interactionEvent.CustomValues["twitterhandlecreated"]);
                    var numberOfFollowers    = Convert.ToInt32(interactionEvent.CustomValues["followerscount"]);
                    var tweetfulltext        = interactionEvent.CustomValues["tweetfulltext"];
                    var hashtag = interactionEvent.CustomValues["hashtags"];

                    await cfg.InitializeAsync();

                    using (var client = new XConnectClient(cfg))
                    {
                        try
                        {
                            ContactIdentifier contactIdentifier = new ContactIdentifier("twitter", twitterHandle, ContactIdentifierType.Known);

                            // Let's just save this for later
                            //TODO: If time check for existing user.
                            Identifier = contactIdentifier.Identifier;
                            Contact contact = new Contact(contactIdentifier);

                            //TODO Get from args custom values "Name". If space save first and last
                            PersonalInformation personalInfo = new PersonalInformation()
                            {
                                FirstName = firstName,
                                LastName  = lastName
                            };


                            // TODO get from args
                            TwitterAccountInfo visitorInfo = new TwitterAccountInfo()
                            {
                                TwitterHandle         = twitterHandle,
                                TwitterStartDate      = twitterHandleCreated,
                                NumberOfFollowers     = numberOfFollowers,
                                VerifiedTwitterHandle = false
                            };

                            client.AddContact(contact);
                            client.SetFacet(contact, TwitterAccountInfo.DefaultFacetKey, visitorInfo);
                            client.SetFacet(contact, PersonalInformation.DefaultFacetKey, personalInfo);

                            var interaction = new Interaction(contact, InteractionInitiator.Contact, arg.ProcessingResult.Interaction.Interaction.ChannelId, ""); // GUID should be from a channel item in Sitecore

                            //TODO Get from args

                            var productTweet = new ProductTweet();
                            productTweet.Tweet          = tweetfulltext;
                            productTweet.ProductHashtag = hashtag;
                            productTweet.TwitterHandle  = twitterHandle;

                            ITextAnalyticsClient cogClient = new TextAnalyticsClient(new ApiKeyServiceClientCredentials())
                            {
                                Endpoint = "https://westus.api.cognitive.microsoft.com"
                            };

                            SentimentBatchResult result = cogClient.SentimentAsync(
                                new MultiLanguageBatchInput(
                                    new List <MultiLanguageInput>()
                            {
                                new MultiLanguageInput("en", new Guid().ToString(), productTweet.Tweet)
                            })).Result;

                            if (result != null && result.Documents.Any())
                            {
                                var firstDocument = result.Documents.First();
                                if (firstDocument != null)
                                {
                                    productTweet.Sentiment = firstDocument.Score;
                                }
                            }

                            interaction.Events.Add(new ProductReviewOutcome(productTweet, DateTime.UtcNow));
                            client.AddInteraction(interaction);
                            await client.SubmitAsync();
                        }
                        catch (XdbExecutionException ex)
                        {
                            // Deal with exception
                            Logger.LogInformation("Tres Divas Twitter Interactions EnrichmentPipelineProcessor: ", ex);
                        }
                    }
                }
            }
        }
Example #17
0
 public LeaderboardShareService(LeaderboardApi leaderboardApi, TwitterPersistenceService twitterPersistenceService)
 {
     _leaderboardApi     = leaderboardApi;
     _twitterAccountInfo = twitterPersistenceService.Load();
 }
Example #18
0
    /// <summary>
    /// Attempts to upgrade settings from the old way to he new-one.
    /// </summary>
    /// <param name="site">site we are importing for</param>
    /// <returns>true on success, false on failure</returns>
    private static void ImportTwitterSettings(SiteInfo site)
    {
        TwitterApplicationInfo twittAppInfo = new TwitterApplicationInfo()
        {
            TwitterApplicationDisplayName    = site.DisplayName + "Twitter App",
            TwitterApplicationName           = site.SiteName + "TwitterApp",
            TwitterApplicationConsumerKey    = SettingsKeyInfoProvider.GetStringValue(site.SiteName + ".CMSTwitterConsumerKey"),
            TwitterApplicationConsumerSecret = SettingsKeyInfoProvider.GetStringValue(site.SiteName + ".CMSTwitterConsumerSecret"),
            TwitterApplicationSiteID         = site.SiteID
        };

        if (String.IsNullOrWhiteSpace(twittAppInfo.TwitterApplicationConsumerKey) || String.IsNullOrWhiteSpace(twittAppInfo.TwitterApplicationConsumerSecret))
        {
            return;
        }

        try
        {
            TwitterApplicationInfoProvider.SetTwitterApplicationInfo(twittAppInfo);
            twittAppInfo = TwitterApplicationInfoProvider.GetTwitterApplicationInfo(site.SiteName + "TwitterApp", site.SiteName);
        }
        catch (Exception ex)
        {
            EventLogProvider.LogException("Upgrade to 8.0", "Upgrade of SocialMarketing", ex, additionalMessage: "Error during Twitter application storage to DB for site " + site.SiteName, siteId: site.SiteID);

            return;
        }

        TwitterAccountInfo twittAccountInfo = new TwitterAccountInfo()
        {
            TwitterAccountName                 = site.SiteName + "TwitterChannel",
            TwitterAccountDisplayName          = site.DisplayName + " Twitter Channel",
            TwitterAccountTwitterApplicationID = twittAppInfo.TwitterApplicationID,
            TwitterAccountSiteID               = site.SiteID,
            TwitterAccountAccessToken          = SettingsKeyInfoProvider.GetStringValue(site.SiteName + ".CMSTwitterAccessToken"),
            TwitterAccountAccessTokenSecret    = SettingsKeyInfoProvider.GetStringValue(site.SiteName + ".CMSTwitterAccessTokenSecret"),
            TwitterAccountIsDefault            = true,
        };

        twittAccountInfo.TwitterAccountUserID = GetTwitterUserId(twittAppInfo, twittAccountInfo);

        if (String.IsNullOrWhiteSpace(twittAccountInfo.TwitterAccountAccessToken) || String.IsNullOrWhiteSpace(twittAccountInfo.TwitterAccountAccessTokenSecret))
        {
            return;
        }

        try
        {
            TwitterAccountInfoProvider.SetTwitterAccountInfo(twittAccountInfo);
        }
        catch (Exception ex)
        {
            EventLogProvider.LogException("Upgrade to 8.0", "Upgrade of SocialMarketing", ex, additionalMessage: "Error during Twitter channel storage to DB for site " + site.SiteName, siteId: site.SiteID);

            return;
        }

        // URL shortener
        if (!SettingsKeyInfoProvider.IsValueInherited(site.SiteName + ".CMSTwitterURLShortenerType"))
        {
            string shortener = SettingsKeyInfoProvider.GetStringValue(site.SiteName + ".CMSTwitterURLShortenerType");
            SettingsKeyInfoProvider.SetValue(site.SiteName + ".CMSSocialMarketingURLShorteningTwitter", shortener);
        }

        return;
    }
    /// <summary>
    /// Creates a Twitter channel.
    /// </summary>
    private bool CreateTwitterChannel()
    {
        if (string.IsNullOrEmpty(txtAccessToken.Text) || string.IsNullOrEmpty(txtAccessTokenSecret.Text))
        {
            throw new Exception("[ApiExamples.CreateTwitterChannel]: Empty values for 'Channel access token' and 'Channel access token secret' are not allowed. Please provide your channel's credentials.");
        }

        // Get the app the channel is tied to.
        TwitterApplicationInfo app = TwitterApplicationInfoProvider.GetTwitterApplicationInfo("MyNewTwitterApp", SiteContext.CurrentSiteName);

        if (app == null)
        {
            throw new Exception("[ApiExamples.CreateTwitterChannel]: Application 'MyNewTwitterApp' was not found.");
        }

        // Create new channel object
        TwitterAccountInfo channel = new TwitterAccountInfo();

        // Set the properties
        channel.TwitterAccountDisplayName = "My new Twitter channel";
        channel.TwitterAccountName = "MyNewTwitterChannel";

        channel.TwitterAccountAccessToken = txtAccessToken.Text;
        channel.TwitterAccountAccessTokenSecret = txtAccessTokenSecret.Text;
        channel.TwitterAccountSiteID = SiteContext.CurrentSiteID;
        channel.TwitterAccountTwitterApplicationID = app.TwitterApplicationID;

        // Save the channel into DB
        TwitterAccountInfoProvider.SetTwitterAccountInfo(channel);

        return true;
    }
Example #20
0
 public LeaderboardApi(TwitterPersistenceService twitterPersistence)
 {
     _numberOfRetries    = 0;
     _twitterAccountInfo = twitterPersistence.Load();
     _logger             = LogManager.GetLogger("log");
 }
Example #21
0
 public LeaderboardApi(TwitterPersistenceService twitterPersistence)
 {
     _numberOfRetries    = 0;
     _twitterAccountInfo = twitterPersistence.Load();
 }