Ejemplo n.º 1
0
        //
        // GET: /RabbitMQ/
        public ActionResult Index()
        {
            RabbitMqQueueModel model = new RabbitMqQueueModel();
            // Connect to Rabbit MQ and grab basic queue counts.
            HttpWebRequest request = HttpWebRequest.CreateHttp("http://localhost:15672/api/queues");

            request.Credentials = new NetworkCredential(MtaParameters.RabbitMQ.Username, MtaParameters.RabbitMQ.Password);
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                string json         = new StreamReader(response.GetResponseStream()).ReadToEnd();
                JArray rabbitQueues = JArray.Parse(json);
                foreach (JToken q in rabbitQueues.Children())
                {
                    JEnumerable <JProperty> qProperties = q.Children <JProperty>();
                    string queueName = (string)qProperties.First(x => x.Name.Equals("name")).Value;
                    if (queueName.StartsWith("manta_mta_"))
                    {
                        model.Add(new RabbitMqQueue {
                            Name     = queueName,
                            Messages = (long)qProperties.First(x => x.Name.Equals("messages")).Value,
                            State    = (string)qProperties.First(x => x.Name.Equals("state")).Value
                        });
                    }
                }
            }
            return(View(model));
        }
Ejemplo n.º 2
0
        //
        // GET: /Dashboard/
        public ActionResult Index()
        {
            DashboardModel model = new DashboardModel
            {
                SendTransactionSummaryCollection = TransactionDB.GetLastHourTransactionSummary(),
                Waiting       = SendDB.GetQueueCount(new SendStatus[] { SendStatus.Active, SendStatus.Discard }),
                Paused        = SendDB.GetQueueCount(new SendStatus[] { SendStatus.Paused }),
                BounceInfo    = TransactionDB.GetLastHourBounceInfo(3),
                SendSpeedInfo = TransactionDB.GetLastHourSendSpeedInfo()
            };

            try
            {
                // Connect to Rabbit MQ and grab basic queue counts.
                HttpWebRequest request = HttpWebRequest.CreateHttp("http://localhost:15672/api/queues");
                request.Credentials = new NetworkCredential(MtaParameters.RabbitMQ.Username, MtaParameters.RabbitMQ.Password);
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    string json         = new StreamReader(response.GetResponseStream()).ReadToEnd();
                    JArray rabbitQueues = JArray.Parse(json);
                    foreach (JToken q in rabbitQueues.Children())
                    {
                        JEnumerable <JProperty> qProperties = q.Children <JProperty>();
                        string queueName = (string)qProperties.First(x => x.Name.Equals("name")).Value;
                        if (queueName.StartsWith("manta_mta_"))
                        {
                            long messages = (long)qProperties.First(x => x.Name.Equals("messages", System.StringComparison.OrdinalIgnoreCase)).Value;
                            if (queueName.IndexOf("_inbound") > 0)
                            {
                                model.RabbitMqInbound += messages;
                            }
                            else if (queueName.IndexOf("_outbound_") > 0)
                            {
                                model.RabbitMqTotalOutbound += messages;
                            }
                        }
                    }
                }
            }
            catch (Exception)
            {
                model.RabbitMqInbound       = int.MinValue;
                model.RabbitMqTotalOutbound = int.MinValue;
            }


            return(View(model));
        }
Ejemplo n.º 3
0
        public AppDetails getUWPAppDetails(JObject payload)
        {
            if (payload == null)
            {
                return(new AppDetails("Not found", new DateTime()));
            }
            var      title = payload.Value <string>("Title");
            DateTime releaseDate;
            DateTime lastUpdatedDate;

            try {
                releaseDate = payload.Value <DateTime>("ReleaseDateUtc");
            } catch {
                releaseDate = DateTime.Parse(payload.Value <string>("ReleaseDateUtc"));
            }
            var details = new AppDetails(title, releaseDate);
            JEnumerable <JObject> images = payload.GetValue("Images").Children <JObject>();
            var logo = images.FirstOrDefault(img => (img["ImageType"].ToString() == "tile" || img["ImageType"].ToString() == "logo") && int.Parse(img["Width"].ToString()) >= 150);

            // if a bigger image is not found, use whatever is available
            if (logo == null)
            {
                logo = images.First(img => (img["ImageType"].ToString() == "tile" || img["ImageType"].ToString() == "logo"));
            }

            details.image           = logo["Url"].ToString();
            details.backgroundColor = logo["BackgroundColor"].ToString();
            try {
                lastUpdatedDate = payload.Value <DateTime>("LastUpdateDateUtc");
            } catch {
                lastUpdatedDate = DateTime.Parse(payload.Value <string>("LastUpdateDateUtc"));
            }
            details.lastUpdatedDate = lastUpdatedDate;
            return(details);
        }
Ejemplo n.º 4
0
        /// <summary>
        ///   Updates the behavioural values. Triggers on a specific species
        /// </summary>
        /// <param name="property">Should be a specific species</param>
        /// <param name="children">The children of the given property</param>
        /// <remarks>
        ///   <para>
        ///     Changes a json like
        ///     "1": {
        ///       ...
        ///       "Aggression": 126.188889,
        ///       "Opportunism": 34.3588943,
        ///       "Fear": 52.6969757,
        ///       "Activity": 74.67135,
        ///       "Focus": 111.778221,
        ///       ...
        ///     }
        ///     to
        ///     "1": {
        ///       ...
        ///       "Behaviour": {
        ///         "Aggression": 126.188889,
        ///         "Opportunism": 34.3588943,
        ///         "Fear": 52.6969757,
        ///         "Activity": 74.67135,
        ///         "Focus": 111.778221
        ///       },
        ///       ...
        ///     }
        ///   </para>
        /// </remarks>
        private void UpgradeBehaviouralValues(JProperty property, JEnumerable <JProperty> children)
        {
            var aggression  = children.First(p => p.Name == "Aggression");
            var opportunism = children.First(p => p.Name == "Opportunism");
            var fear        = children.First(p => p.Name == "Fear");
            var activity    = children.First(p => p.Name == "Activity");
            var focus       = children.First(p => p.Name == "Focus");

            aggression.Remove();
            opportunism.Remove();
            fear.Remove();
            activity.Remove();
            focus.Remove();

            ((JObject)property.Value).Add("Behaviour",
                                          new JObject(aggression, opportunism, fear, activity, focus));
        }
Ejemplo n.º 5
0
        public void GetOrderBook(PoloniexTicker ticker, int depth)
        {
            string address = string.Format("https://poloniex.com/public?command=returnOrderBook&currencyPair={0}&depth={1}",
                                           Uri.EscapeDataString(ticker.CurrencyPair), depth);
            string text;

            using (WebClient client = new WebClient()) {
                text = client.DownloadString(address);
            }
            ticker.OrderBook.Bids.Clear();
            ticker.OrderBook.Asks.Clear();

            JObject res = (JObject)JsonConvert.DeserializeObject(text);

            foreach (JProperty prop in res.Children())
            {
                if (prop.Name == "asks" || prop.Name == "bids")
                {
                    OrderBookEntryType type  = prop.Name == "asks" ? OrderBookEntryType.Ask : OrderBookEntryType.Bid;
                    JArray             items = prop.Value.ToObject <JArray>();
                    foreach (JArray item in items.Children())
                    {
                        OrderBookUpdateInfo info = new OrderBookUpdateInfo();
                        info.Type   = prop.Name == "asks" ? OrderBookEntryType.Ask : OrderBookEntryType.Bid;
                        info.Entry  = new OrderBookEntry();
                        info.Action = OrderBookUpdateType.Modify;
                        JEnumerable <JToken> values = (JEnumerable <JToken>)item.Children();
                        JValue rateValue            = (JValue)values.First();
                        info.Entry.Value  = rateValue.ToObject <double>();
                        info.Entry.Amount = rateValue.Next.ToObject <double>();
                        if (type == OrderBookEntryType.Ask)
                        {
                            ticker.OrderBook.ForceAddAsk(info);
                        }
                        else
                        {
                            ticker.OrderBook.ForceAddBid(info);
                        }
                    }
                }
                else if (prop.Name == "seq")
                {
                    ticker.OrderBook.SeqNumber = prop.Value.ToObject <int>();
                    Console.WriteLine("Snapshot seq no = " + ticker.OrderBook.SeqNumber);
                }
                else if (prop.Name == "isFrozen")
                {
                    ticker.IsFrozen = prop.Value.ToObject <int>() == 0;
                }
            }
            ticker.OrderBook.ApplyQueueUpdates();
        }
Ejemplo n.º 6
0
        private static List <object> toObjectData(JToken token, JEnumerable <JObject> included)
        {
            var list       = new List <object>();
            var ignoreCase = BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance;

            // TODO: add deCamelCase
            var types = GetTypesWith <Type>(true);

            foreach (var data in token["data"].Children <JObject>())
            {
                var itemType = (string)data["type"];
                var type     = types.First(x => ((Type)x.GetCustomAttribute(typeof(Type))).Value == itemType);

                var item = Activator.CreateInstance(type);
                list.Add(item);

                // set id
                type.GetProperty("id", ignoreCase).SetValue(item, Convert.ChangeType(data["id"], type.GetProperty("id", ignoreCase).PropertyType), null);

                var ndata = data;
                // there is probably a better way todo this
                if (included.Any(x => (string)x["type"] == (string)data["type"] && (string)x["id"] == (string)data["id"]))
                {
                    // get data from included
                    ndata = included.First(x => (string)x["type"] == (string)data["type"] && (string)x["id"] == (string)data["id"]);
                }

                // set attributes
                if (ndata["attributes"] as JObject != null)
                {
                    foreach (var attr in ((JObject)ndata["attributes"]).Properties())
                    {
                        type.GetProperty(attr.Name, ignoreCase).SetValue(item, Convert.ChangeType(attr.Value, type.GetProperty(attr.Name, ignoreCase).PropertyType), null);
                    }
                }

                // set relationships
                if (ndata["relationships"] as JObject != null)
                {
                    foreach (var rela in ((JObject)ndata["relationships"]).Properties())
                    {
                        // will this work ?
                        // just hopes it's a ?????<T> container
                        type.GetProperty(rela.Name, ignoreCase).SetValue(item, ConvertList(toObjectData(rela.Value, included), type.GetProperty(rela.Name, ignoreCase).PropertyType), null);
                    }
                }
            }

            return(list);
        }
Ejemplo n.º 7
0
        public JObject ProcessMessage(JObject message)
        {
            string action         = "";
            JToken parametersJSON = null;

            foreach (JProperty property in message.Properties())
            {
                if (property.Name == "task_action")
                {
                    action = property.Value.ToString();
                }
                else if (property.Name == "parameters")
                {
                    parametersJSON = property.Value;
                }
            }
            JArray parameters = parametersJSON.Value <JArray>();

            if (action == "create_task")
            {
                string  fileName = parameters.Children().First().Value <string>();
                JObject result   = CreateTask(fileName);
                return(result);
            }
            else if (action == "run_task")
            {
                JEnumerable <JToken> parameterList = parameters.Children();
                string     taskID     = parameterList.First().Value <string>();
                Activation activation = parseActivationFromRunTaskParameters(parameters);

                return(RunTask(taskID, activation));
            }
            else if (action == "remove_task")
            {
                string taskID = parameters.Children().First().Value <string>();
                return(RemoveTask(taskID));
            }
            else
            {
                return(GenerateReply(FAILURE, "Unknown action " + action));
            }
        }
Ejemplo n.º 8
0
        public ActionResult Index(LoadRankingsModel loadRankingsModel)
        {
            using (tennisDBEntities db = new tennisDBEntities())
            {
                if (Request.RequestType == "POST")
                {
                    if (loadRankingsModel.RankingsToUpdate == "ATP")
                    {
                        using (WebClient wc = new WebClient())
                        {
                            string Gender = "M";
                            var    sJson  = wc.DownloadString("https://vbarbaresi.opendatasoft.com/explore/dataset/atp-rankings/download/?format=json&timezone=Europe/London");
                            JArray json   = JsonConvert.DeserializeObject <JArray>(sJson);
                            JEnumerable <JToken> records = json.Children();
                            JToken Timestamp             = records.First().SelectToken("record_timestamp");
                            int    year  = Timestamp.ToObject <DateTime>().Year;
                            int    count = 0;
                            db.rankings.RemoveRange(db.rankings.Select(r => r).Where(r => r.player.gender == Gender && r.year == year));
                            foreach (var record in records)
                            {
                                JToken Fields      = record.SelectToken("fields");
                                string PlayerName  = Fields.Value <string>("player_name");
                                string CountryName = Fields.Value <string>("player_country");
                                int    Points      = Fields.Value <int>("player_points");
                                if (CountryName == "United Kingdom")
                                {
                                    CountryName = "Great Britain";
                                }
                                else if (CountryName.Equals("usa", StringComparison.InvariantCultureIgnoreCase) || CountryName == "United States")
                                {
                                    CountryName = "USA";
                                }
                                else if (CountryName == "Bosnia")
                                {
                                    CountryName = "Bosnia And Herzegovina";
                                }
                                else if (CountryName == "Slovak Republic")
                                {
                                    CountryName = "Slovakia";
                                }
                                else if (CountryName == "Chinese Taipei")
                                {
                                    CountryName = "Taiwan";
                                }
                                PlayerName = PlayerName.Trim();
                                PlayerName = Regex.Replace(PlayerName, " +", " ");

                                ranking Ranking = new ranking();
                                Ranking.points = Points;
                                Ranking.year   = year;
                                if (db.players.Select(p => p).Where(p => p.name == PlayerName && p.country.name == CountryName).SingleOrDefault() == null)
                                {
                                    player Player = new player();
                                    Player.name   = PlayerName;
                                    Player.gender = Gender;
                                    if (db.countries.Select(c => c).Where(c => c.name == CountryName).SingleOrDefault() == null)
                                    {
                                        country Country = new country();
                                        Country.name = CountryName;
                                        db.countries.Add(Country);
                                        db.SaveChanges();
                                    }
                                    Player.country_id = db.countries.Select(c => c).Where(c => c.name == CountryName).Single().id;
                                    db.players.Add(Player);
                                    db.SaveChanges();
                                }
                                Ranking.player_id = db.players.Select(p => p).Where(p => p.name == PlayerName && p.country.name == CountryName).Single().id;
                                db.rankings.Add(Ranking);
                                db.SaveChanges();
                                count++;
                            }
                            RankingsUpdate.ResetRank(year, Gender, db);
                            db.SaveChanges();
                            loadRankingsModel.Message = "Loaded " + count + " rankings.";
                        }
                    }
                    if (loadRankingsModel.RankingsToUpdate == "WTA")
                    {
                        using (WebClient wc = new WebClient())
                        {
                            string Gender = "F";
                            var    sJson  = wc.DownloadString("https://data.opendatasoft.com/explore/dataset/wta-rankings@vbarbaresi/download/?format=json&timezone=Europe/London");
                            JArray json   = JsonConvert.DeserializeObject <JArray>(sJson);
                            JEnumerable <JToken> records = json.Children();
                            JToken Timestamp             = records.First().SelectToken("record_timestamp");
                            int    year  = Timestamp.ToObject <DateTime>().Year;
                            int    count = 0;
                            db.rankings.RemoveRange(db.rankings.Select(r => r).Where(r => r.player.gender == Gender && r.year == year));
                            foreach (var record in records)
                            {
                                JToken Fields      = record.SelectToken("fields");
                                string PlayerName  = Fields.Value <string>("player_name");
                                string CountryName = Fields.Value <string>("player_country");
                                int    Points      = Fields.Value <int>("player_points");
                                if (CountryName == "United Kingdom")
                                {
                                    CountryName = "Great Britain";
                                }
                                else if (CountryName.Equals("usa", StringComparison.InvariantCultureIgnoreCase) || CountryName == "United States")
                                {
                                    CountryName = "USA";
                                }
                                else if (CountryName == "Bosnia")
                                {
                                    CountryName = "Bosnia And Herzegovina";
                                }
                                else if (CountryName == "Slovak Republic")
                                {
                                    CountryName = "Slovakia";
                                }
                                else if (CountryName == "Chinese Taipei")
                                {
                                    CountryName = "Taiwan";
                                }
                                PlayerName = PlayerName.Trim();
                                PlayerName = Regex.Replace(PlayerName, " +", " ");

                                ranking Ranking = new ranking();
                                Ranking.points = Points;
                                Ranking.year   = year;
                                if (db.players.Select(p => p).Where(p => p.name == PlayerName && p.country.name == CountryName).SingleOrDefault() == null)
                                {
                                    player Player = new player();
                                    Player.name   = PlayerName;
                                    Player.gender = Gender;
                                    if (db.countries.Select(c => c).Where(c => c.name == CountryName).SingleOrDefault() == null)
                                    {
                                        country Country = new country();
                                        Country.name = CountryName;
                                        db.countries.Add(Country);
                                        db.SaveChanges();
                                    }
                                    Player.country_id = db.countries.Select(c => c).Where(c => c.name == CountryName).Single().id;
                                    db.players.Add(Player);
                                    db.SaveChanges();
                                }
                                Ranking.player_id = db.players.Select(p => p).Where(p => p.name == PlayerName && p.country.name == CountryName).Single().id;
                                db.rankings.Add(Ranking);
                                db.SaveChanges();
                                count++;
                            }
                            RankingsUpdate.ResetRank(year, Gender, db);
                            db.SaveChanges();
                            loadRankingsModel.Message = "Loaded " + count + " rankings.";
                        }
                    }
                }
            }
            return(View(loadRankingsModel));
        }
Ejemplo n.º 9
0
        private Activation parseActivationFromRunTaskParameters(JArray parameters)
        {
            JEnumerable <JToken> parameterList = parameters.Children();
            string  taskID      = parameterList.First().Value <string>();
            JObject invokerJSON = parameterList.Skip(1).First().Value <JObject>();

            List <int>         hotkeys            = new List <int>();
            List <int>         keySequence        = new List <int>();
            ActivationVariable activationVariable = null;
            string             activationPhrase   = null;
            string             mouseGesture       = null;

            foreach (JProperty property in invokerJSON.Properties())
            {
                JToken token = property.Value;
                if (property.Name == "hotkey")
                {
                    // Get the first hotkey, or leave as empty list.
                    JArray hotkeyListJSON = token.Value <JArray>();
                    foreach (JArray hotkey in hotkeyListJSON.Children <JArray>())
                    {
                        foreach (JObject keyObject in hotkey.Children())
                        {
                            foreach (JProperty keyProperty in keyObject.Properties())
                            {
                                JToken keyToken = keyProperty.Value;
                                if (keyProperty.Name == "key")
                                {
                                    hotkeys.Add(keyToken.Value <int>());
                                }
                            }
                        }
                        break;
                    }
                }
                else if (property.Name == "key_sequence")
                {
                    // Get the first key sequence, or leave as empty list.
                    JArray hotkeyListJSON = token.Value <JArray>();
                    foreach (JArray hotkey in hotkeyListJSON.Children <JArray>())
                    {
                        foreach (JObject keyObject in hotkey.Children())
                        {
                            foreach (JProperty keyProperty in keyObject.Properties())
                            {
                                JToken keyToken = keyProperty.Value;
                                if (keyProperty.Name == "key")
                                {
                                    hotkeys.Add(keyToken.Value <int>());
                                }
                            }
                        }
                        break;
                    }
                }
                else if (property.Name == "variables")
                {
                    // Get the first variable, or leave as empty.
                    string varNamespace = "";
                    string name         = "";
                    JArray variableList = token.Value <JArray>();
                    foreach (JObject variable in variableList.Children <JObject>())
                    {
                        foreach (JProperty innerVariable in variable.Properties())
                        {
                            if (innerVariable.Name != "variable")
                            {
                                continue;
                            }
                            JToken  innerVariableToken  = innerVariable.Value;
                            JObject innerVariableObject = innerVariableToken.Value <JObject>();
                            foreach (JProperty prop in innerVariableObject.Properties())
                            {
                                JToken keyToken = prop.Value;
                                if (prop.Name == "namespace")
                                {
                                    varNamespace = prop.Value.ToString();
                                }
                                else if (prop.Name == "name")
                                {
                                    name = prop.Value.ToString();
                                }
                            }
                        }

                        activationVariable = new ActivationVariable {
                            varNamespace = varNamespace,
                            name         = name
                        };
                        break;
                    }
                }
                else if (property.Name == "phrases")
                {
                    // Get the first phrase, or leave as empty.
                    JArray phrasesList = token.Value <JArray>();
                    foreach (JObject phrase in phrasesList.Children <JObject>())
                    {
                        foreach (JProperty prop in phrase.Properties())
                        {
                            JToken keyToken = prop.Value;
                            if (prop.Name == "value")
                            {
                                activationPhrase = prop.Value.ToString();
                            }
                        }
                        break;
                    }
                }
                else if (property.Name == "mouse_gesture")
                {
                    // Get the first mouse gesture, or leave as null.
                    JArray mouseGestureListJSON = token.Value <JArray>();
                    foreach (JObject gesture in mouseGestureListJSON.Children <JObject>())
                    {
                        foreach (JProperty prop in gesture.Properties())
                        {
                            if (prop.Name == "name")
                            {
                                mouseGesture = prop.Value.ToString();
                            }
                        }
                        break;
                    }
                }
            }

            Activation activation = new Activation();

            activation.hotkeys            = hotkeys;
            activation.keySequence        = keySequence;
            activation.activationVariable = activationVariable;
            activation.phrase             = activationPhrase;
            activation.mouseGesture       = mouseGesture;
            return(activation);
        }