public static void Main(string[] args)
        {
            ConsoleOutput.PrintMessage("BoxKite.Twitter Live Fire Tests (Initiate User Auth)");
            ConsoleOutput.PrintMessage("(control-c ends at anytime)");

            var twitterConnection = new TwitterConnection("3izxqWiej34yTlofisw", "uncicYQtDx5SoWth1I9xcn5vrpczUct1Oz9ydwTY4");

            var authString = twitterConnection.BeginUserAuthentication().Result;
 
            // if the response is null, something is wrong with the initial request to OAuth
            if (!string.IsNullOrWhiteSpace(authString))
            {
                ConsoleOutput.PrintMessage("Pin: ");
                var pin = System.Console.ReadLine();
                twitterCredentials = twitterConnection.CompleteUserAuthentication(pin, authString).Result;
            }

            if (twitterCredentials.Valid)
            {
                ConsoleOutput.PrintMessage(twitterCredentials.ScreenName + " is authorised to use BoxKite.Twitter.");
            }
            else
            {
                ConsoleOutput.PrintMessage("Something Went Wrong during User Authentication Dance.");              
            }
            ConsoleOutput.PrintMessage("Press Return to close window");
            System.Console.ReadLine();
        }
Example #2
0
        public static void Main(string[] args)
        {
            ConsoleOutput.PrintMessage("BoxKite.Twitter Live Fire Tests (Initiate User Auth)");
            ConsoleOutput.PrintMessage("(control-c ends at anytime)");

            var twitterConnection = new TwitterConnection("3izxqWiej34yTlofisw", "uncicYQtDx5SoWth1I9xcn5vrpczUct1Oz9ydwTY4");

            var authString = twitterConnection.BeginUserAuthentication().Result;

            // if the response is null, something is wrong with the initial request to OAuth
            if (!string.IsNullOrWhiteSpace(authString))
            {
                ConsoleOutput.PrintMessage("Pin: ");
                var pin = System.Console.ReadLine();
                twitterCredentials = twitterConnection.CompleteUserAuthentication(pin, authString).Result;
            }

            if (twitterCredentials.Valid)
            {
                ConsoleOutput.PrintMessage(twitterCredentials.ScreenName + " is authorised to use BoxKite.Twitter.");
            }
            else
            {
                ConsoleOutput.PrintMessage("Something Went Wrong during User Authentication Dance.");
            }
            ConsoleOutput.PrintMessage("Press Return to close window");
            System.Console.ReadLine();
        }
Example #3
0
        private void MainForm_Load(object sender, EventArgs e)
        {
            DisableStandardToolbar();

            try
            {
                Dac dac = new Dac();
                dac.LoadDatabaseFileLocationFromReqistry();
                DatabaseFileLocationToolStripStatusLabel.Text = "Database : " + Dac.Current.DatabaseFileLocation;
            }
            catch
            {
                DatabaseFileLocationToolStripStatusLabel.Text = "Database Connection Error !!!";
            }

            try
            {
                TwitterConnection twitterConnection = new TwitterConnection();
                twitterConnection.LoadCredentialsFromReqistry();
                twitterConnection.Connect();
                TwitterUserToolStripStatusLabel.Text = "Twitter User : "******"Twitter Connection Error !!!";
            }
        }
        private void OkButton_Click(object sender, EventArgs e)
        {
            TwitterConnection twitterConnection = new TwitterConnection();

            twitterConnection.ConsumerKey      = consumerKeyTextBox.Text;
            twitterConnection.ConsumerSecret   = consumerSecretTextBox.Text;
            twitterConnection.UserAccessToken  = userAccessTokenTextBox.Text;
            twitterConnection.UserAccessSecret = userAccessSecretTextBox.Text;

            try
            {
                twitterConnection.Connect();

                if (RememberCheckBox.Checked)
                {
                    twitterConnection.SaveCredentialsToReqistry();
                }
                else
                {
                    twitterConnection.ResetCredentialsToReqistry();
                }

                this.DialogResult = DialogResult.OK;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Wrong Credentials Or Connection Error :-(" + Environment.NewLine + ex.ToString());
            }
        }
        /// <summary>
        /// Gets the information of a new single promotion and send it to the database.
        /// </summary>
        /// <returns></returns>
        public ActionResult NewSinglePromotion()
        {
            AdminModel AdminModel = (AdminModel)TempData["admin"];

            // get the type of material
            string materialType = Request["materialType"].ToString();

            // get the amount of kg of the material
            int amountKg = int.Parse(Request["inputAmountKg"].ToString());

            // get the value of tcs of the promotion
            float valueTCS = float.Parse(Request["inputValueTCS"].ToString());

            // get the datetime of the promotion
            string finishDate = Request["inputFinishDate"].ToString();

            // value of the active state of the promotion: 1=active, 0=notactive; by default is 0
            int activeValue = 0;

            // if the user wants the promotion to be active and publish now, else not
            if (Request["publish"] != null && Request["save"] == null)
            {
                activeValue = 1;
            }

            // if the user let one option blank is shown a message
            if (Request["publish"] == null && Request["save"] == null)
            {
                ViewBag.Msj = "Se debe seleccionar si desea Activar o Almacenar.";
            }

            // if the user wants the promotion to be save and ketp for later
            if (Request["publicar"] == null && Request["almacenar"] != null)
            {
                activeValue = 0;
            }

            // send the information to the database
            DBConnection.InsertNewPromotion(AdminModel.Id, valueTCS, finishDate, activeValue, 1);
            DBConnection.GetNewestIdPromotion(AdminModel.PromotionModel);
            int IdPromotion = AdminModel.PromotionModel.LatestIdPromotion;

            DBConnection.InsertPromosMaterial(IdPromotion, materialType, amountKg);

            // if the promotion is active, make it a tweet
            if (activeValue == 1)
            {
                TwitterConnection.SetCredentials();
                TwitterConnection.Publish(
                    "Hay una nueva promocion de: " + valueTCS + " TEColones. Consiste en entregar: " +
                    amountKg + " kg de " + materialType + ". La promocion es valida hasta: " + finishDate
                    );
            }
            return(View("~/Views/Administrator/Promotion/CreateSinglePromotion.cshtml", AdminModel));
        }
        public ActionResult GetNewTwitterCredentials()
        {
            AdminModel AdminModel = (AdminModel)TempData["admin"];

            string NewCONSUMER_KEY        = Request["inputConsumerKey"].ToString();
            string NewCONSUMER_SECRET     = Request["inputConsumerSecret"].ToString();
            string NewACCESS_TOKEN        = Request["inputAccessToken"].ToString();
            string NewACCESS_TOKEN_SECRET = Request["inputAccessTokenSecret"].ToString();

            DBConnection.InsertNewTwitterData(NewCONSUMER_KEY, NewCONSUMER_SECRET, NewACCESS_TOKEN, NewACCESS_TOKEN_SECRET);

            TwitterConnection.SetCredentials(NewCONSUMER_KEY, NewCONSUMER_SECRET, NewACCESS_TOKEN, NewACCESS_TOKEN_SECRET);

            return(View("~/Views/Administrator/Configuration/TwitterConfig.cshtml", AdminModel));
        }
Example #7
0
        public static void Main(string[] args)
        {
            ConsoleOutput.PrintMessage("BoxKite.Twitter Live Fire Tests (Application Auth)");
            ConsoleOutput.PrintMessage("(control-c ends at anytime)");

            System.Console.CancelKeyPress += cancelStreamHandler;

            twitterConnection = new TwitterConnection("3izxqWiej34yTlofisw", "uncicYQtDx5SoWth1I9xcn5vrpczUct1Oz9ydwTY4");

            // put the test series number you wish to run into the init of the array
            // then in each test group, put the numbers of the tests you would like to run
            // NOTE: some tests require a previous test to work successfully
            // NOTE: some tests post/delete items. This *is* a live fire test!

            var testSeriesToRun = new List <int> {
                12
            };

            // Calls tested by Test Series
            // series 12=> 5 (Application Only Auth tests)
            // =============
            // TOTAL       5

            // Test Series 12 Application Only Auth tests

            if (testSeriesToRun.Contains(12))
            {
                var cmbs         = new ApplicationOnlyAuthFireTests();
                var testResult12 = cmbs.DoApplicationOnlyAuthFireTests(twitterConnection, new List <int> {
                    2
                }).Result;

                if (testResult12)
                {
                    ConsoleOutput.PrintMessage(
                        String.Format("12.0 Application Auth Tests Status: {0}", testResult12),
                        ConsoleColor.White);
                }
                else
                {
                    ConsoleOutput.PrintMessage(
                        String.Format("12.0 Application Auth Tests Status: {0}", testResult12),
                        ConsoleColor.Red);
                }
            }
            ConsoleOutput.PrintMessage("Press Return to close window");
            System.Console.ReadLine();
        }
Example #8
0
        private static void Main(string[] args)
        {
            ConsoleOutput.PrintMessage("Welcome to BoxKite.Twitter Console (App Auth Tests)");
            ConsoleOutput.PrintMessage("(control-c ends)");
            System.Console.CancelKeyPress += cancelStreamHandler;

            twitterConnection = new TwitterConnection("3izxqWiej34yTlofisw", "uncicYQtDx5SoWth1I9xcn5vrpczUct1Oz9ydwTY4");

            twitterConnection.StartSearchStreaming("v8sc");
            twitterConnection.SearchTimeLine.Subscribe(t => ConsoleOutput.PrintTweet(t));

            while (true)
            {
                Thread.Sleep(TimeSpan.FromSeconds(0.5));
            }
        }
        private void ConnectForm_Load(object sender, EventArgs e)
        {
            try
            {
                TwitterConnection twitterConnection = new TwitterConnection();
                twitterConnection.LoadCredentialsFromReqistry();

                consumerKeyTextBox.Text      = twitterConnection.ConsumerKey;
                consumerSecretTextBox.Text   = twitterConnection.ConsumerSecret;
                userAccessTokenTextBox.Text  = twitterConnection.UserAccessToken;
                userAccessSecretTextBox.Text = twitterConnection.UserAccessSecret;
            }
            catch (Exception ex)
            {
            }
        }
        private static void Main(string[] args)
        {
            ConsoleOutput.PrintMessage("Welcome to BoxKite.Twitter Console (App Auth Tests)");
            ConsoleOutput.PrintMessage("(control-c ends)");
            System.Console.CancelKeyPress += cancelStreamHandler;

            twitterConnection = new TwitterConnection("3izxqWiej34yTlofisw", "uncicYQtDx5SoWth1I9xcn5vrpczUct1Oz9ydwTY4");

            twitterConnection.StartSearchStreaming("v8sc");
            twitterConnection.SearchTimeLine.Subscribe(t => ConsoleOutput.PrintTweet(t));

            while (true)
            {
                Thread.Sleep(TimeSpan.FromSeconds(0.5));
            }

        }
        public static void Main(string[] args)
        {
            ConsoleOutput.PrintMessage("BoxKite.Twitter Live Fire Tests (Application Auth)");
            ConsoleOutput.PrintMessage("(control-c ends at anytime)");

            System.Console.CancelKeyPress += cancelStreamHandler;

            twitterConnection = new TwitterConnection("3izxqWiej34yTlofisw", "uncicYQtDx5SoWth1I9xcn5vrpczUct1Oz9ydwTY4");

            // put the test series number you wish to run into the init of the array
            // then in each test group, put the numbers of the tests you would like to run
            // NOTE: some tests require a previous test to work successfully
            // NOTE: some tests post/delete items. This *is* a live fire test!

            var testSeriesToRun = new List<int> {12};

            // Calls tested by Test Series
            // series 12=> 5 (Application Only Auth tests)
            // =============
            // TOTAL       5

            // Test Series 12 Application Only Auth tests

            if (testSeriesToRun.Contains(12))
            {
                var cmbs = new ApplicationOnlyAuthFireTests();
                var testResult12 = cmbs.DoApplicationOnlyAuthFireTests(twitterConnection, new List<int> { 2 }).Result;

                if (testResult12)
                {
                    ConsoleOutput.PrintMessage(
                        String.Format("12.0 Application Auth Tests Status: {0}", testResult12),
                        ConsoleColor.White);
                }
                else
                {
                    ConsoleOutput.PrintMessage(
                        String.Format("12.0 Application Auth Tests Status: {0}", testResult12),
                        ConsoleColor.Red);
                }
            }
            ConsoleOutput.PrintMessage("Press Return to close window");
            System.Console.ReadLine();
        }
        private void TestButton_Click(object sender, EventArgs e)
        {
            TwitterConnection twitterConnection = new TwitterConnection();

            twitterConnection.ConsumerKey      = consumerKeyTextBox.Text;
            twitterConnection.ConsumerSecret   = consumerSecretTextBox.Text;
            twitterConnection.UserAccessToken  = userAccessTokenTextBox.Text;
            twitterConnection.UserAccessSecret = userAccessSecretTextBox.Text;

            try
            {
                twitterConnection.Connect();
                MessageBox.Show("Connection Ok :-)" + Environment.NewLine + "User : "******"Connection Error :-(" + Environment.NewLine + ex.ToString());
            }
        }
        public ActionResult GetNewMaterialTCSValues()
        {
            AdminModel AdminModel = (AdminModel)TempData["admin"];

            TwitterConnection.SetCredentials();
            foreach (KeyValuePair <string, float> item in AdminModel.ConfigurationModel.Materials)
            {
                string newValue = Request[item.Key];
                if (!string.IsNullOrWhiteSpace(newValue))
                {
                    string name = item.Key;
                    DBConnection.InsertNewMaterialTCSValue(name, float.Parse(newValue));
                    string message = String.Format("La tasa de cambio del material {0} por kg es: {1} TEColones", name, newValue);
                    TwitterConnection.Publish(message);
                }
            }
            DBConnection.GetMaterialTCSValue(AdminModel.ConfigurationModel);
            return(View("~/Views/Administrator/Configuration/MaterialConfig.cshtml", AdminModel));
        }
        public ActionResult Register() //(SCMModel emple)
        {
            SCM scm = (SCM)TempData["scm"];

            IDictionary <string, string> dict = new Dictionary <string, string>();

            foreach (string material in scm.Materials)
            {
                dict.Add(material, Request[material].ToString());
            }
            string carnet = Request["InputCarnet"].ToString();

            if (DBConnection.ExistUser(carnet).Equals(1))
            {
                string email         = DBConnection.GetEmailUser(carnet);
                string messageToSend = String.Format("El estudiante {0} ha ingresado ", carnet);

                foreach (KeyValuePair <string, string> item in dict)
                {
                    if (!string.IsNullOrWhiteSpace(item.Value))
                    {
                        //if (DBConnection.VerifyPromotion()){} --> APLICAR PROMOCION

                        DBConnection.InsertRegister(carnet, scm.Id, item.Key, item.Value);
                        messageToSend += String.Format("{0} kg del material {1}. ", item.Value, item.Key);
                    }
                }

                TwitterConnection.SetCredentials();
                TwitterConnection.Publish(messageToSend);

                SendEmail(email, messageToSend);

                ViewBag.Message = String.Format("Se registro el material con exito, para el estudiante {0}", carnet);
                return(PartialView("~/Views/StorageCenterManager/SCMHome/SCMHome.cshtml", scm));
            }
            else
            {
                ViewBag.Message = String.Format("Numero {0} no existe como Usuario Estudiante", carnet);
                return(PartialView("~/Views/StorageCenterManager/SCMHome/SCMHome.cshtml", scm));
            }
        }
        public ActionResult GetNewBenefitsValues()
        {
            AdminModel AdminModel         = (AdminModel)TempData["admin"];
            string     NewStudyExchange   = Request["inputTCSStudy"];
            string     NewDinningExchange = Request["inputTCSDinning"];

            TwitterConnection.SetCredentials();
            if (!string.IsNullOrWhiteSpace(NewStudyExchange))
            {
                DBConnection.InsertNewBenefitsValue(float.Parse(NewStudyExchange), "Matricula");
                TwitterConnection.Publish("La tasa de cambio de TEColones en los Derechos de Estudio (Matricula) es: " + NewStudyExchange + " colones");
            }
            if (!string.IsNullOrWhiteSpace(NewDinningExchange))
            {
                DBConnection.InsertNewBenefitsValue(float.Parse(NewDinningExchange), "Comedor");
                TwitterConnection.Publish("La tasa de cambio de TEColones en el Comedor Intitucional es: " + NewDinningExchange + " colones");
            }

            DBConnection.GetBenefitsValue(AdminModel.ConfigurationModel);
            return(View("~/Views/Administrator/Configuration/TEColonesConfig.cshtml", AdminModel));
        }
        /// <summary>
        /// Gets the information of a new combo promotion and send it to the database.
        /// </summary>
        /// <returns></returns>
        public ActionResult NewComboPromotion()
        {
            AdminModel AdminModel = (AdminModel)TempData["admin"];

            Dictionary <string, int> dict = new Dictionary <string, int>();

            // checks the value of the inputs: name, amount of kg, the checkbox
            foreach (var item in AdminModel.PromotionModel.ListMaterials)
            {
                string materialType = item;                        // which type of material is, the name of the material
                string amountKg     = Request[item];               // the amount, float, of kg of the material
                string checkBox     = Request["checkbox " + item]; // the value of the checkbox

                if (amountKg != " " && checkBox != null)
                {
                    int amountKgInt = int.Parse(amountKg); // converts the string type of amount to float for the sending it to the database
                    dict.Add(materialType, amountKgInt);
                }
                else
                {
                    continue;
                }
            }

            // to be a combo at least must be two materials, else proceed to choose again.
            if (dict.Count < 2)
            {
                ViewBag.Msj = "Para crear una PromocionCombo minimo son dos materiales. Si desea solo un material, proceda a la seccion de Promo Individual.";
            }

            // checks and gets the value of the tcs and the datetime of it
            float  valueTCS   = float.Parse(Request["inputValueTCS"]);
            string finishDate = Request["inputFinishDate"].ToString();

            // value of the active state of the promotion: 1=active, 0=notactive; by default is 0
            int activeValue = 0;

            // if the user wants the promotion to be active and publish now, else not
            if (Request["publish"] != null && Request["save"] == null)
            {
                activeValue = 1;
            }

            // if the user let one option blank is shown a message
            if (Request["publish"] == null && Request["save"] == null)
            {
                ViewBag.Msj = "Se debe seleccionar si desea Activar o Almacenar.";
            }

            // if the user wants the promotion to be save and ketp for later
            if (Request["publicar"] == null && Request["almacenar"] != null)
            {
                activeValue = 0;
            }

            // send the information to the database
            DBConnection.InsertNewPromotion(AdminModel.Id, valueTCS, finishDate, activeValue, 0);
            DBConnection.GetNewestIdPromotion(AdminModel.PromotionModel);
            int IdPromotion = AdminModel.PromotionModel.LatestIdPromotion;

            foreach (var item in dict)
            {
                DBConnection.InsertPromosMaterial(IdPromotion, item.Key, item.Value);
            }

            // if the promotion is active, make it a tweet
            if (activeValue == 1)
            {
                TwitterConnection.SetCredentials();
                TwitterConnection.Publish("Hay una nueva Promocion en Combo de: " + valueTCS + " TEColones. Consiste en entregar: ");
                foreach (var item in dict)
                {
                    TwitterConnection.Publish("Entregar " + item.Value + " kg " + " de " + item.Key);
                }
                TwitterConnection.Publish("La promocion es valida hasta: " + finishDate);
            }

            return(View("~/Views/Administrator/Promotion/CreateComboPromotion.cshtml", AdminModel));
        }
        private static void Main(string[] args)
        {
            ConsoleOutput.PrintMessage("Welcome to BoxKite.Twitter Console");
            ConsoleOutput.PrintMessage("(control-c ends)");
            System.Console.CancelKeyPress += cancelStreamHandler;

            var twittercredentials = ManageTwitterCredentials.GetTwitterCredentialsFromFile();

            if (twittercredentials == null)
            {
                // there are no Credentials on file, so create a new set
                // first, get the Twitter Client (also known as Consumer) Key and Secret from my service
                var twitterClientKeys = ClientKeyManager.GetTwitterClientKeys().Result;

                // make a new connection
                twitterConnection = new TwitterConnection(twitterClientKeys.Item1, twitterClientKeys.Item2);

                // PIN based authentication
                var oauth = twitterConnection.BeginUserAuthentication().Result;

                // if the response is null, something is wrong with the initial request to OAuth
                if (!string.IsNullOrWhiteSpace(oauth))
                {
                    ConsoleOutput.PrintMessage("Pin: ");
                    var pin = System.Console.ReadLine();
                    twittercredentials = twitterConnection.CompleteUserAuthentication(pin, oauth).Result;

                    ManageTwitterCredentials.SaveTwitterCredentialsToFile(twittercredentials);
                }
                else
                {
                    ConsoleOutput.PrintError("Cannot OAuth with Twitter");
                }
            }


            if (twittercredentials != null)
            {
                twitterConnection = new TwitterConnection(twittercredentials);

                twitterConnection.StartUserStreaming();

                ConsoleOutput.PrintMessage(twitterConnection.TwitterCredentials.ScreenName +
                                           " is authorised to use BoxKite.Twitter.");

                var usersession = twitterConnection.UserSession;
                var userstream = twitterConnection.UserStream;
                var applicationsession = twitterConnection.ApplicationSession;
                var searchstream = twitterConnection.SearchStream;
 
                // userstream.Tweets.Subscribe( t => ConsoleOutput.PrintTweet(t));

                //userstream.Events.Subscribe(e => ConsoleOutput.PrintEvent(e, ConsoleColor.Yellow));
                //userstream.DirectMessages.Subscribe(C:\Users\nhodge\Documents\GitHub\BoxKite.Twitter\src\BoxKite.Twitter\SearchStream.cs
                //    d => ConsoleOutput.PrintDirect(d, ConsoleColor.Magenta, ConsoleColor.Black));
                //userstream.Start();

                //while (userstream.IsActive)
                //{
                //    Thread.Sleep(TimeSpan.FromSeconds(0.5));
                //}





                /*var x = session.SendTweet("d realnickhodge testing & ampersands");

                        if (x.IsFaulted)
                        {
                            ConsoleOutput.PrintMessage("bugger");
                        }

                        */



                //var locations = new List<string> { "150.700493", "-34.081953", "151.284828", "-33.593316" };
               // var locations = new List<string> { "-180", "-90", "180", "90" };
                // var track = new List<string> { "mh370" };

                
                twitterConnection.TimeLine.Subscribe(t =>
                                                {
                                                    ConsoleOutput.PrintTweet(t, ConsoleColor.Green);
                                                });
                twitterConnection.Mentions.Subscribe(
                    t => ConsoleOutput.PrintTweet(t, ConsoleColor.White, ConsoleColor.DarkGray));

                //twitterConnection.SearchTimeLine.Subscribe(t => { ConsoleOutput.PrintTweet(t, ConsoleColor.Cyan); });
                
                //twitterConnection.StartSearchStreaming("angeles");

                        while (true)
                        {
                            Thread.Sleep(TimeSpan.FromSeconds(0.5));
                        }
                
                  /*
                 twitterConnection.StartSearch("mh370");
                 var xx = session.GetUserProfile(screen_name:"nickhodgemsft").Result;

                 if (xx.twitterFaulted)
                 {
                     PrintTwitterErrors(xx.twitterControlMessage);
                 }
                 else
                 {
                     ConsoleOutput.PrintMessage(xx.ToString());
                 }

                

                 var fileName = "sampleimage\\boxkite1500x500.png";

                 if (File.Exists(fileName))
                 {
                     // var newImage = File.ReadAllBytes(fileName);

                     var sr = FilesHelper.FromFile(fileName);

                     // var x = session.SendTweetWithImage("Testing Image Upload. You can Ignore", Path.GetFileName(fileName),newImage).Result;

                     using (var fs = new FileStream(sr, FileMode.Open, FileAccess.Read))
                     {

                         var x = session.ChangeProfileBanner("sampleimage\\boxkite1500x500.png", fs).Result;

                         // var x = session.SendTweetWithImage("Maggies Rules", "maggie.jpg", fs).Result;

                         if (x.twitterFaulted)
                         {
                             PrintTwitterErrors(x.twitterControlMessage);
                         }
                         else
                         {
                             ConsoleOutput.PrintMessage("OK");
                         }

                     }

                 }
                 */
                /*
                mainTwitterAccount.TimeLine.Subscribe(t => ConsoleOutput.PrintTweet(t));
                mainTwitterAccount.Mentions.Subscribe(
                    t => ConsoleOutput.PrintTweet(t, ConsoleColor.White, ConsoleColor.DarkGray));

                while (true)
                {
                    Thread.Sleep(TimeSpan.FromSeconds(0.5));
                }

                Console.ConsoleOutput.PrintMessage("Event stream has stoppped.");

                         var locations = new List<string> { "-34.081953", "150.700493", "-33.593316", "151.284828" };
                            searchstream = session.StartSearchStream(locations: locations);
                            searchstream = session.StartSearchStream(track: "hazel");
                            searchstream.FoundTweets.Subscribe(t => ConsoleOutput.PrintTweet(t, ConsoleColor.Green));
                            searchstream.Start();

                            while (searchstream.IsActive)
                            {
                                Thread.Sleep(TimeSpan.FromMinutes(1));
                                var sr = new StreamSearchRequest();
                                sr.tracks.Add("xbox");
                                searchstream.SearchRequests.Publish(sr);
                            }
                         * 
                         */


                /*
                        var x = session.GetMentions(count:100).Result;

                        foreach (var tweet in x)
                        {
                            ConsoleOutputPrintTweet(tweet);
                        }
                        
                    
                         session.GetFavourites(count: 10)
                            .Subscribe(t => ConsoleOutputPrintTweet(t, ConsoleColor.White, ConsoleColor.Black));
                        */

            }

            ConsoleOutput.PrintMessage("All Finished");
            System.Console.ReadLine();

        }
Example #18
0
        public void Send(string meleeUser, string opponent)
        {
            try
            {
                var    resultsText = "and the winner is.....click <a href='{0}' >here</a> to find out";
                string winnerId;

                Clients.Caller.broadcastMessage("The battle has begun!");

                _repository      = new MeleeUserRepository();
                _meleeRepository = new MeleeRepository();

                //if the opponent is not a registered user then only battle twitter
                var currentUser  = _repository.Get(meleeUser);
                var opponentUser = _repository.Get(opponent);

                var userScore     = 0.00;
                var opponentScore = 0.00;

                if (opponentUser != null)
                {
                    //battle twitter
                    Clients.Caller.broadcastMessage("Battling for Twitter supremecy.");
                    var currentUserTwitter = currentUser.Connections.SingleOrDefault(c => c.ConnectionName == "Twitter");
                    if (currentUserTwitter != null)
                    {
                        userScore = currentUserTwitter.ConnectionProvider.GetScore(currentUser);
                    }
                    var currentOpponentTwitter = currentUser.Connections.SingleOrDefault(c => c.ConnectionName == "Twitter");
                    if (currentOpponentTwitter != null)
                    {
                        opponentScore = currentOpponentTwitter.ConnectionProvider.GetScore(currentUser);
                    }
                    Clients.Caller.broadcastMessage("you: " + userScore + " " + " them: " + opponentScore);

                    //battle facebook
                    Clients.Caller.broadcastMessage("Battling for Facebook supremecy.");
                    var currentUserFacebook = currentUser.Connections.SingleOrDefault(c => c.ConnectionName == "Facebook");
                    if (currentUserFacebook != null)
                    {
                        userScore = currentUserFacebook.ConnectionProvider.GetScore(currentUser);
                    }

                    var currentOpponentFacebook = currentUser.Connections.SingleOrDefault(c => c.ConnectionName == "Facebook");
                    if (currentOpponentFacebook != null)
                    {
                        opponentScore = currentOpponentFacebook.ConnectionProvider.GetScore(opponentUser);
                    }
                    Clients.Caller.broadcastMessage("you: " + userScore + " " + " them: " + opponentScore);

                    //battle google+
                    Clients.Caller.broadcastMessage("Battling for Google+ supremecy.");
                    var currentUserGoogle = currentUser.Connections.SingleOrDefault(c => c.ConnectionName == "Google+");
                    if (currentUserGoogle != null)
                    {
                        userScore = currentUserGoogle.ConnectionProvider.GetScore(currentUser);
                    }
                    var currentOpponentGoogle = currentUser.Connections.SingleOrDefault(c => c.ConnectionName == "Google+");

                    if (currentOpponentGoogle != null)
                    {
                        opponentScore = currentOpponentGoogle.ConnectionProvider.GetScore(opponentUser);
                    }
                    Clients.Caller.broadcastMessage("you: " + userScore + " " + " them: " + opponentScore);
                }
                else
                {
                    Clients.Caller.broadcastMessage("Battling for Twitter supremecy.");

                    var twitterConnection = currentUser.Connections.SingleOrDefault(c => c.ConnectionName == "Twitter");
                    if (twitterConnection != null)
                    {
                        userScore = twitterConnection.ConnectionProvider.GetScore(currentUser);
                    }
                    Clients.Caller.broadcastUserScore("Points:" + userScore);

                    opponentScore = new TwitterConnection().GetScore(opponent);
                    Clients.Caller.broadcastCompetitorScore("Points:" + opponentScore);
                }

                if (userScore > opponentScore)
                {
                    _meleeRepository.Add(meleeUser, opponent, meleeUser, opponent);
                    winnerId = meleeUser;
                }
                else
                {
                    _meleeRepository.Add(meleeUser, opponent, opponent, meleeUser);
                    winnerId = opponent;
                }

                Clients.Caller.broadcastMessage(string.Format(resultsText, "/Melee/MeleeMe/" + winnerId));
            }
            catch (Exception ex)
            {
                Clients.Caller.catchException(ex.ToString());
            }
        }
        public async Task<bool> DoApplicationOnlyAuthFireTests(TwitterConnection twitterConnection, List<int> testSeq)
        {
            var successStatus = true;

            try
            {
                // 1
                if (testSeq.Contains(1))
                {
                    ConsoleOutput.PrintMessage("12.1 User Time Line//Application Auth Only", ConsoleColor.Gray);

                    var combo1 = await twitterConnection.TwitterSession.GetUserTimeline("KatyPerry");

                    if (combo1.OK)
                    {
                        foreach (var trnd in combo1)
                        {
                            ConsoleOutput.PrintMessage(
                                String.Format("App Auth Timeline Test: {0}", trnd.Text));
                        }
                    }
                    else
                    {
                        successStatus = false;
                        throw new Exception("cannot user time line (app only auth)");
                    }
                } // end test 1

                // 2
                if (testSeq.Contains(2))
                {
                    ConsoleOutput.PrintMessage("12.2 API Management//Rate limits", ConsoleColor.Gray);

                    var combo2 = await twitterConnection.TwitterSession.GetCurrentApiStatus();

                    if (combo2.OK)
                    {
                        foreach (var apir in combo2.APIRateStatuses)
                        {
                            ConsoleOutput.PrintMessage(
                                String.Format("API: {0} Limit: {1} Remaining: {2}", apir.Value.APIPath, apir.Value.Limit, apir.Value.Remaining));
                        }
                    }
                    else
                    {
                        successStatus = false;
                        throw new Exception("cannot api management (app only auth)");
                    }
                } // end test 2

                // 3 
                if (testSeq.Contains(3))
                {
                    ConsoleOutput.PrintMessage("12.3 Get a Tweet//", ConsoleColor.Gray);

                    var combo3 = await twitterConnection.TwitterSession.GetTweet(464717579861258242);

                    if (combo3.OK)
                    {
                            ConsoleOutput.PrintMessage(combo3.Text);
                    }
                    else
                    {
                        successStatus = false;
                        throw new Exception("cannot get tweet (app only auth)");
                    }
                } // end test 3


                // 4 
                if (testSeq.Contains(4))
                {
                    ConsoleOutput.PrintMessage("12.4 Get a Retweet//", ConsoleColor.Gray);

                    var oldtweet = new Tweet() {Id = 453310114796412928};

                    var combo4 = await twitterConnection.TwitterSession.GetRetweets(oldtweet);

                    if (combo4.OK)
                    {
                        ConsoleOutput.PrintMessage(String.Format("Retweeted {0} times",combo4.Count));
                    }
                    else
                    {
                        successStatus = false;
                        throw new Exception("cannot get retweet (app only auth)");
                    }
                } // end test 4


                // 5 
                if (testSeq.Contains(5))
                {
                    ConsoleOutput.PrintMessage("12.5 Get friendships//", ConsoleColor.Gray);

                    var combo5 = await twitterConnection.TwitterSession.GetFriendship(sourceScreenName:"shiftkey",targetScreenName:"nickhodgemsft");

                    if (combo5.OK)
                    {
                        
                    }
                    else
                    {
                        successStatus = false;
                        throw new Exception("cannot get friendships (app only auth)");
                    }
                } // end test 5

            }
            catch (Exception e)
            {
                ConsoleOutput.PrintError(e.ToString());
                return false;
            }
            return successStatus;
        }
Example #20
0
 // Gets the HTTPClientFactory through dependency injection and passes this to the TwitterConnection class
 public HomeController(IHttpClientFactory clientFactory)
 {
     twitterConnection = new TwitterConnection(clientFactory);
 }
Example #21
0
        private static void Main(string[] args)
        {
            ConsoleOutput.PrintMessage("Welcome to BoxKite.Twitter Console");
            ConsoleOutput.PrintMessage("(control-c ends)");
            System.Console.CancelKeyPress += cancelStreamHandler;

            var twittercredentials = ManageTwitterCredentials.GetTwitterCredentialsFromFile();

            if (twittercredentials == null)
            {
                // there are no Credentials on file, so create a new set
                // first, get the Twitter Client (also known as Consumer) Key and Secret from my service
                var twitterClientKeys = ClientKeyManager.GetTwitterClientKeys().Result;

                // make a new connection
                twitterConnection = new TwitterConnection(twitterClientKeys.Item1, twitterClientKeys.Item2);

                // PIN based authentication
                var oauth = twitterConnection.BeginUserAuthentication().Result;

                // if the response is null, something is wrong with the initial request to OAuth
                if (!string.IsNullOrWhiteSpace(oauth))
                {
                    ConsoleOutput.PrintMessage("Pin: ");
                    var pin = System.Console.ReadLine();
                    twittercredentials = twitterConnection.CompleteUserAuthentication(pin, oauth).Result;

                    ManageTwitterCredentials.SaveTwitterCredentialsToFile(twittercredentials);
                }
                else
                {
                    ConsoleOutput.PrintError("Cannot OAuth with Twitter");
                }
            }


            if (twittercredentials != null)
            {
                twitterConnection = new TwitterConnection(twittercredentials);

                twitterConnection.StartUserStreaming();

                ConsoleOutput.PrintMessage(twitterConnection.TwitterCredentials.ScreenName +
                                           " is authorised to use BoxKite.Twitter.");

                var usersession        = twitterConnection.UserSession;
                var userstream         = twitterConnection.UserStream;
                var applicationsession = twitterConnection.ApplicationSession;
                var searchstream       = twitterConnection.SearchStream;

                // userstream.Tweets.Subscribe( t => ConsoleOutput.PrintTweet(t));

                //userstream.Events.Subscribe(e => ConsoleOutput.PrintEvent(e, ConsoleColor.Yellow));
                //userstream.DirectMessages.Subscribe(C:\Users\nhodge\Documents\GitHub\BoxKite.Twitter\src\BoxKite.Twitter\SearchStream.cs
                //    d => ConsoleOutput.PrintDirect(d, ConsoleColor.Magenta, ConsoleColor.Black));
                //userstream.Start();

                //while (userstream.IsActive)
                //{
                //    Thread.Sleep(TimeSpan.FromSeconds(0.5));
                //}



                /*var x = session.SendTweet("d realnickhodge testing & ampersands");
                 *
                 *      if (x.IsFaulted)
                 *      {
                 *          ConsoleOutput.PrintMessage("bugger");
                 *      }
                 *
                 */



                //var locations = new List<string> { "150.700493", "-34.081953", "151.284828", "-33.593316" };
                // var locations = new List<string> { "-180", "-90", "180", "90" };
                // var track = new List<string> { "mh370" };


                twitterConnection.TimeLine.Subscribe(t =>
                {
                    ConsoleOutput.PrintTweet(t, ConsoleColor.Green);
                });
                twitterConnection.Mentions.Subscribe(
                    t => ConsoleOutput.PrintTweet(t, ConsoleColor.White, ConsoleColor.DarkGray));

                //twitterConnection.SearchTimeLine.Subscribe(t => { ConsoleOutput.PrintTweet(t, ConsoleColor.Cyan); });

                //twitterConnection.StartSearchStreaming("angeles");

                while (true)
                {
                    Thread.Sleep(TimeSpan.FromSeconds(0.5));
                }

                /*
                 * twitterConnection.StartSearch("mh370");
                 * var xx = session.GetUserProfile(screen_name:"nickhodgemsft").Result;
                 *
                 * if (xx.twitterFaulted)
                 * {
                 * PrintTwitterErrors(xx.twitterControlMessage);
                 * }
                 * else
                 * {
                 * ConsoleOutput.PrintMessage(xx.ToString());
                 * }
                 *
                 *
                 *
                 * var fileName = "sampleimage\\boxkite1500x500.png";
                 *
                 * if (File.Exists(fileName))
                 * {
                 * // var newImage = File.ReadAllBytes(fileName);
                 *
                 * var sr = FilesHelper.FromFile(fileName);
                 *
                 * // var x = session.SendTweetWithImage("Testing Image Upload. You can Ignore", Path.GetFileName(fileName),newImage).Result;
                 *
                 * using (var fs = new FileStream(sr, FileMode.Open, FileAccess.Read))
                 * {
                 *
                 *     var x = session.ChangeProfileBanner("sampleimage\\boxkite1500x500.png", fs).Result;
                 *
                 *     // var x = session.SendTweetWithImage("Maggies Rules", "maggie.jpg", fs).Result;
                 *
                 *     if (x.twitterFaulted)
                 *     {
                 *         PrintTwitterErrors(x.twitterControlMessage);
                 *     }
                 *     else
                 *     {
                 *         ConsoleOutput.PrintMessage("OK");
                 *     }
                 *
                 * }
                 *
                 * }
                 */
                /*
                 * mainTwitterAccount.TimeLine.Subscribe(t => ConsoleOutput.PrintTweet(t));
                 * mainTwitterAccount.Mentions.Subscribe(
                 *  t => ConsoleOutput.PrintTweet(t, ConsoleColor.White, ConsoleColor.DarkGray));
                 *
                 * while (true)
                 * {
                 *  Thread.Sleep(TimeSpan.FromSeconds(0.5));
                 * }
                 *
                 * Console.ConsoleOutput.PrintMessage("Event stream has stoppped.");
                 *
                 *       var locations = new List<string> { "-34.081953", "150.700493", "-33.593316", "151.284828" };
                 *          searchstream = session.StartSearchStream(locations: locations);
                 *          searchstream = session.StartSearchStream(track: "hazel");
                 *          searchstream.FoundTweets.Subscribe(t => ConsoleOutput.PrintTweet(t, ConsoleColor.Green));
                 *          searchstream.Start();
                 *
                 *          while (searchstream.IsActive)
                 *          {
                 *              Thread.Sleep(TimeSpan.FromMinutes(1));
                 *              var sr = new StreamSearchRequest();
                 *              sr.tracks.Add("xbox");
                 *              searchstream.SearchRequests.Publish(sr);
                 *          }
                 *
                 */


                /*
                 *      var x = session.GetMentions(count:100).Result;
                 *
                 *      foreach (var tweet in x)
                 *      {
                 *          ConsoleOutputPrintTweet(tweet);
                 *      }
                 *
                 *
                 *       session.GetFavourites(count: 10)
                 *          .Subscribe(t => ConsoleOutputPrintTweet(t, ConsoleColor.White, ConsoleColor.Black));
                 */
            }

            ConsoleOutput.PrintMessage("All Finished");
            System.Console.ReadLine();
        }
        public async Task <bool> DoApplicationOnlyAuthFireTests(TwitterConnection twitterConnection, List <int> testSeq)
        {
            var successStatus = true;

            try
            {
                // 1
                if (testSeq.Contains(1))
                {
                    ConsoleOutput.PrintMessage("12.1 User Time Line//Application Auth Only", ConsoleColor.Gray);

                    var combo1 = await twitterConnection.TwitterSession.GetUserTimeline("KatyPerry");

                    if (combo1.OK)
                    {
                        foreach (var trnd in combo1)
                        {
                            ConsoleOutput.PrintMessage(
                                String.Format("App Auth Timeline Test: {0}", trnd.Text));
                        }
                    }
                    else
                    {
                        successStatus = false;
                        throw new Exception("cannot user time line (app only auth)");
                    }
                } // end test 1

                // 2
                if (testSeq.Contains(2))
                {
                    ConsoleOutput.PrintMessage("12.2 API Management//Rate limits", ConsoleColor.Gray);

                    var combo2 = await twitterConnection.TwitterSession.GetCurrentApiStatus();

                    if (combo2.OK)
                    {
                        foreach (var apir in combo2.APIRateStatuses)
                        {
                            ConsoleOutput.PrintMessage(
                                String.Format("API: {0} Limit: {1} Remaining: {2}", apir.Value.APIPath, apir.Value.Limit, apir.Value.Remaining));
                        }
                    }
                    else
                    {
                        successStatus = false;
                        throw new Exception("cannot api management (app only auth)");
                    }
                } // end test 2

                // 3
                if (testSeq.Contains(3))
                {
                    ConsoleOutput.PrintMessage("12.3 Get a Tweet//", ConsoleColor.Gray);

                    var combo3 = await twitterConnection.TwitterSession.GetTweet(464717579861258242);

                    if (combo3.OK)
                    {
                        ConsoleOutput.PrintMessage(combo3.Text);
                    }
                    else
                    {
                        successStatus = false;
                        throw new Exception("cannot get tweet (app only auth)");
                    }
                } // end test 3


                // 4
                if (testSeq.Contains(4))
                {
                    ConsoleOutput.PrintMessage("12.4 Get a Retweet//", ConsoleColor.Gray);

                    var oldtweet = new Tweet()
                    {
                        Id = 453310114796412928
                    };

                    var combo4 = await twitterConnection.TwitterSession.GetRetweets(oldtweet);

                    if (combo4.OK)
                    {
                        ConsoleOutput.PrintMessage(String.Format("Retweeted {0} times", combo4.Count));
                    }
                    else
                    {
                        successStatus = false;
                        throw new Exception("cannot get retweet (app only auth)");
                    }
                } // end test 4


                // 5
                if (testSeq.Contains(5))
                {
                    ConsoleOutput.PrintMessage("12.5 Get friendships//", ConsoleColor.Gray);

                    var combo5 = await twitterConnection.TwitterSession.GetFriendship(sourceScreenName : "shiftkey", targetScreenName : "nickhodgemsft");

                    if (combo5.OK)
                    {
                    }
                    else
                    {
                        successStatus = false;
                        throw new Exception("cannot get friendships (app only auth)");
                    }
                } // end test 5
            }
            catch (Exception e)
            {
                ConsoleOutput.PrintError(e.ToString());
                return(false);
            }
            return(successStatus);
        }