Beispiel #1
0
        /// <summary>
        /// Chats the specified identifier.
        /// </summary>
        /// <param name="id">The identifier.</param>
        /// <returns>ActionResult.</returns>
        public async Task <ActionResult> Chat(string id)
        {
            var user = await _userManager.FindByIdAsync(User.Identity.GetUserId());

            var hipChat = new HipChatClient(new ApiConnection(new Credentials(user.HipChatPersonalV2Token)));

            // create default message and notification hooks if they do not exist
            var hooks = await hipChat.Rooms.GetWebhooks(id);

            if (!hooks.Model.Items.Any(h => h.Name == "HipChatDotNet_Default" && h.Event == "room_notification"))
            {
                await hipChat.Rooms.CreateWebhookAsync(id, new CreateWebhook { Event = WebhookEvent.RoomNotification, Url = ConfigurationManager.AppSettings["BaseUri"] + "api/notification/" + id });
            }
            if (!hooks.Model.Items.Any(h => h.Name == "HipChatDotNet_Default" && h.Event == "room_message"))
            {
                await hipChat.Rooms.CreateWebhookAsync(id, new CreateWebhook { Event = WebhookEvent.RoomMessage, Url = ConfigurationManager.AppSettings["BaseUri"] + "api/message/" + id });
            }

            // get the latest message history
            var history = await hipChat.Rooms.GetHistoryAsync(id);

            var contextList = history.Model.Items.Select(h => new MessageContext
            {
                Id      = h.Id,
                Message = h.MessageText,
                Color   = h.Color,
                From    = h.From is string?h.From: h.From.name,
                FileUrl = h.File != null ? h.File.Url : null
            }).ToList();

            ViewBag.roomId = id;

            return(View(contextList));
        }
        public HipChatService(string hipChatIntegrationUrl, string projectName)
        {
            var hipChat = new HipChatClient(new ApiConnection(new Credentials(GetAuthToken(hipChatIntegrationUrl))));

            hipChat.Rooms.SendNotificationAsync(
                GetRoomName(hipChatIntegrationUrl),
                $"{projectName} was just published!");
        }
Beispiel #3
0
        public void TestAuthenticationException()
        {
            var client = new HipChatClient()
            {
                Token = "XYZ", RoomId = 123
            };

            client.ListRooms();
        }
Beispiel #4
0
        public static void TestWindsorInstaller(TestContext context)
        {
            IWindsorContainer container = new WindsorContainer();

            container.Install(new HipChatClientInstaller());
            defaultClient       = container.Resolve <HipChatClient>("ChatClient");
            defaultClient.From += defaultClient.GetHashCode().ToString();
//            defaultClient.SendMessage("TestWindsorInstaller");
        }
Beispiel #5
0
        public async Task <JsonResult> SendNotification(string id, string message, string color = "gray")
        {
            var user = await _userManager.FindByIdAsync(User.Identity.GetUserId());

            var hipChat = new HipChatClient(new ApiConnection(new Credentials(user.HipChatPersonalV2Token)));
            await hipChat.Rooms.SendNotificationAsync(id, HttpUtility.HtmlDecode(message));

            return(Json(true));
        }
        public static void SendMessage(this ICakeContext context, string authToken, string roomId, string senderName, string message)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var client = new HipChatClient(authToken, roomId, senderName);

            client.SendMessage(message);
        }
        public void Run(IIntegrationResult result)
        {
            var displayDuration = false;
            var duration        = TimeSpan.Zero;

            if (result.EndTime != DateTime.MinValue)
            {
                duration        = result.EndTime - result.StartTime;
                displayDuration = true;
            }
            var link = String.Format(@"<a href=""{0}"">{1}</a>", result.ProjectUrl, result.Status);

            var message = new StringBuilder();

            message.Append(result.ProjectName);
            message.Append(" ");

            if (String.IsNullOrEmpty(Message))
            {
                message.Append("build complete");
            }
            else
            {
                message.Append(Message);
            }

            message.Append(" ");

            if (displayDuration)
            {
                message.AppendFormat("(duration {0})", duration);
            }

            message.Append(". ");

            if (!HideResult)
            {
                message.AppendFormat("Result: {0}.", link);
            }

            var notify = result.Succeeded;
            var color  = result.Succeeded ? HipChatClient.BackgroundColor.green : HipChatClient.BackgroundColor.red;

            if (HideResult)
            {
                color = HipChatClient.BackgroundColor.yellow;
            }

            var client = new HipChatClient(AuthToken, RoomId, From);

            client.SendMessage(message.ToString(), color, notify);
        }
        public MyApplicationContext()
        {
            client    = new HipChatClient(new ApiConnection(new Credentials("")));
            _trayIcon = new NotifyIcon
            {
                Icon        = Resources.AppIcon,
                ContextMenu = new ContextMenu(new[] { new MenuItem("Exit", Exit) }),
                Visible     = true
            };

            // Ping(null, null);

            StartTimer();
        }
        public SendHipChatMessageResponse Invoke(SendHipChatMessageRequest request)
        {
            if (request.HipChatAuthToken.IsNotNullOrEmpty() && request.HipChatRoomId > 0)
            {
                if (request.Colour.HasValue)
                {
                    HipChatClient.SendMessage(request.HipChatAuthToken, request.HipChatRoomId, "Errordite", request.Message, request.Colour.Value);
                }
                else
                {
                    HipChatClient.SendMessage(request.HipChatAuthToken, request.HipChatRoomId, "Errordite", request.Message);
                }
            }

            return(new SendHipChatMessageResponse());
        }
Beispiel #10
0
        /// <summary>
        /// Indexes this instance.
        /// </summary>
        /// <returns>Task&lt;ActionResult&gt;.</returns>
        public async Task <ActionResult> Index()
        {
            var user = await _userManager.FindByIdAsync(User.Identity.GetUserId());

            var hipChat = new HipChatClient(new ApiConnection(new Credentials(user.HipChatPersonalV2Token)));
            var rooms   = await hipChat.Rooms.GetAllAsync();

            var contextList = new List <RoomContext>();

            foreach (var r in rooms.Model.Items)
            {
                var context = new RoomContext
                {
                    Name        = r.Name,
                    Id          = r.Id,
                    MemberCount = r.Links.Members != null ? (await hipChat.Rooms.GetMembersAsync(r.Id)).Model.Items.Count() : 0
                };
                contextList.Add(context);
            }

            return(View(contextList));
        }
Beispiel #11
0
        public static void Main()
        {
            var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            var pulseBotConfigurationSection = (PulseConfigurationSection)config.GetSection("pulseBot");

            var alertingMetrics = pulseBotConfigurationSection.Alerts
                                  .Select(x => new AlertingMetric
            {
                IPAddress              = x.Host.IPAddress,
                PingInterval           = x.Host.PingInterval,
                PingTimeout            = x.Host.PingTimeout,
                PingHipChatFailCount   = x.Host.PingHipChatFailCount,
                PingPagerDutyFailCount = x.Host.PingPagerDutyFailCount,
                HipChatApiKey          = x.HipChat.HipChatApiKey,
                HipChatRoomName        = x.HipChat.HipChatRoomName,
                LastPagerDutyAlert     = null,
                PagerDutyServiceAPIKey = x.PagerDuty.GenericServiceApiKey,
                PagerDutyMessage       = x.PagerDuty.MessageOnAlert
            })
                                  .ToList();

            foreach (var hipChatSink in alertingMetrics.Select(x => new { x.HipChatApiKey, x.HipChatRoomName }).Distinct())
            {
                HipChatClient.SendMessage(hipChatSink.HipChatApiKey, hipChatSink.HipChatRoomName, "PulseBot", "PulseBot has started", true, HipChatClient.BackgroundColor.purple);
            }

            Parallel.ForEach(alertingMetrics, alertingMetric =>
            {
                var consecutiveFailCount = 0;

                while (true)
                {
                    try
                    {
                        if (alertingMetric.PingInterval.HasValue)
                        {
                            using (var pingSender = new Ping())
                            {
                                var options = new PingOptions
                                {
                                    DontFragment = true
                                };

                                // Create a buffer of 32 bytes of data to be transmitted.
                                var buffer = Encoding.ASCII.GetBytes(PingData);
                                try
                                {
                                    var reply = pingSender.Send(IPAddress.Parse(alertingMetric.IPAddress), alertingMetric.PingTimeout ?? 10000, buffer, options);
                                    if (reply != null && reply.Status != IPStatus.Success)
                                    {
                                        Console.WriteLine("\r\n{0:yyyy-MM-dd-HH:mm:ss} - {1}: PING FAILURE", DateTime.Now, alertingMetric.PagerDutyMessage);
                                        consecutiveFailCount++;

                                        if (alertingMetric.PingHipChatFailCount.HasValue &&
                                            consecutiveFailCount == alertingMetric.PingHipChatFailCount.Value)
                                        {
                                            HipChatClient.SendMessage(alertingMetric.HipChatApiKey, alertingMetric.HipChatRoomName, "PulseBot", alertingMetric.PagerDutyMessage, true, HipChatClient.BackgroundColor.red);
                                        }

                                        if (alertingMetric.PingPagerDutyFailCount.HasValue &&
                                            (consecutiveFailCount == alertingMetric.PingPagerDutyFailCount.Value || (alertingMetric.LastPagerDutyAlert.HasValue && (DateTime.Now - alertingMetric.LastPagerDutyAlert.Value).TotalMinutes > 60)))
                                        {
                                            Console.WriteLine("\r\nAlerting PagerDuty for {0} after {1} failures!", alertingMetric.PagerDutyMessage,
                                                              consecutiveFailCount);
                                            //PostPagerDutyAlert(alertingMetric.PagerDutyServiceAPIKey, alertingMetric.PagerDutyMessage, consecutiveFailCount);
                                            alertingMetric.LastPagerDutyAlert = DateTime.Now;
                                        }
                                    }
                                    else if (reply != null && reply.Status == IPStatus.Success)
                                    {
                                        consecutiveFailCount = 0;
                                        Console.Write(".");
                                    }
                                }
                                catch (PingException)
                                {
                                    Console.WriteLine("\r\n{0:yyyy-MM-dd-HH:mm:ss} - {1}: PING FAILURE", DateTime.Now, alertingMetric.PagerDutyMessage);
                                    consecutiveFailCount++;
                                }
                            }
                        }

                        System.Threading.Thread.Sleep(alertingMetric.PingInterval.Value * 1000);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("\r\n{0}", ex.ToString());
                    }
                }
            });
        }
        private void SendMessageToHipchat(string message)
        {
            var client = new HipChatClient(this.AuthToken, this.RoomId, this.SenderName);

            client.SendMessage(message, this.BackgroundColor);
        }
Beispiel #13
0
        public static void Main()
        {
            var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            var canaryRelicConfigurationSection = (CanaryConfigurationSection)config.GetSection("canaryRelic");

            var alertingMetrics = canaryRelicConfigurationSection.Alerts.Select(x => new AlertingMetric
            {
                Name                   = x.Name,
                AccountID              = x.NewRelic.NewRelicAccountId,
                ApplicationID          = x.NewRelic.NewRelicApplicationId,
                FieldName              = x.NewRelic.NewRelicMetricFieldName,
                HipChatApiKey          = x.HipChat.HipChatApiKey,
                HipChatRoomName        = x.HipChat.HipChatRoomName,
                LastPagerDutyAlert     = null,
                MinAverage             = x.MinimumMetricAverage,
                MaxAverage             = x.MaximumMetricAverage,
                MetricName             = x.NewRelic.NewRelicMetricName,
                NewRelicAPIKey         = x.NewRelic.NewRelicApiKey,
                PagerDutyServiceAPIKey = x.PagerDuty == null ? null : x.PagerDuty.GenericServiceApiKey,
                PagerDutyMessage       = x.PagerDuty == null ? null : x.PagerDuty.MessageOnAlert
            })
                                  .ToList();

            foreach (var hipChatSink in alertingMetrics.Select(x => new { x.HipChatApiKey, x.HipChatRoomName }).Distinct())
            {
                HipChatClient.SendMessage(hipChatSink.HipChatApiKey, hipChatSink.HipChatRoomName, "CanaryBot", "CanaryBot has started", true, HipChatClient.BackgroundColor.purple);
            }

            while (true)
            {
                try
                {
                    foreach (var alertingMetric in alertingMetrics)
                    {
                        var startDate = DateTime.UtcNow.AddMinutes(-5).ToString("yyyy-MM-ddTHH:mm:ss") + "Z";
                        var endDate   = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ss") + "Z";

                        var url = string.Format(
                            @"https://api.newrelic.com/api/v1/accounts/{0}/applications/{1}/data.xml?metrics[]={2}&field={3}&begin={4}&end={5}",
                            alertingMetric.AccountID,
                            alertingMetric.ApplicationID,
                            alertingMetric.MetricName,
                            alertingMetric.FieldName,
                            startDate,
                            endDate);

                        string data;
                        using (var request = new WebClient())
                        {
                            request.Headers.Add("x-api-key", alertingMetric.NewRelicAPIKey);
                            data = request.DownloadString(url);
                        }

                        var urlCount = string.Format(
                            @"https://api.newrelic.com/api/v1/accounts/{0}/applications/{1}/data.xml?metrics[]={2}&field={3}&begin={4}&end={5}",
                            alertingMetric.AccountID,
                            alertingMetric.ApplicationID,
                            alertingMetric.MetricName,
                            "call_count",
                            startDate,
                            endDate);

                        string dataCount;
                        using (var requestCount = new WebClient())
                        {
                            requestCount.Headers.Add("x-api-key", alertingMetric.NewRelicAPIKey);
                            dataCount = requestCount.DownloadString(urlCount);
                        }

                        var xml = new XmlDocument();
                        xml.LoadXml(data);
                        var nodes = xml.SelectNodes("metrics/metric/field");

                        var xmlCount = new XmlDocument();
                        xmlCount.LoadXml(dataCount);
                        var nodesCount = xmlCount.SelectNodes("metrics/metric/field");

                        if (nodes != null && nodesCount != null && nodes.Count == nodesCount.Count)
                        {
                            var sumMetric   = 0F;
                            var countMetric = 0F;

                            for (var i = 0; i < nodes.Count; i++)
                            {
                                var node      = nodes[i];
                                var nodeCount = nodesCount[i];

                                if ((float.Parse(nodeCount.InnerText) > 1 && alertingMetric.FieldName == "average_value") ||
                                    alertingMetric.FieldName != "average_value")
                                {
                                    sumMetric += float.Parse(node.InnerText);
                                    countMetric++;
                                }
                            }

                            //if (countMetric < 3)
                            //	continue;

                            var avgMetric = sumMetric / countMetric;
                            if (float.IsNaN(avgMetric))
                            {
                                avgMetric = 0;
                            }

                            Console.WriteLine("{0:yyyy-MM-dd-HH:mm:ss} - {1}: {2:N3} average over {3} minutes", DateTime.Now, alertingMetric.Name, avgMetric, countMetric);

                            if (avgMetric > alertingMetric.MaxAverage || avgMetric < alertingMetric.MinAverage)
                            {
                                Console.WriteLine("Alerting HipChat for {0}!", alertingMetric.Name);
                                HipChatClient.SendMessage(alertingMetric.HipChatApiKey, alertingMetric.HipChatRoomName, "CanaryBot", alertingMetric.Name, true, HipChatClient.BackgroundColor.red);
                            }

                            if ((avgMetric > alertingMetric.MaxAverage || avgMetric < alertingMetric.MinAverage) &&
                                (alertingMetric.LastPagerDutyAlert == null || (DateTime.Now - alertingMetric.LastPagerDutyAlert.Value).TotalMinutes > 60) &&
                                !string.IsNullOrWhiteSpace(alertingMetric.PagerDutyServiceAPIKey))
                            {
                                Console.WriteLine("Alerting PagerDuty for {0}!", alertingMetric.Name);
                                PostPagerDutyAlert(alertingMetric.PagerDutyServiceAPIKey, alertingMetric.PagerDutyMessage, avgMetric);
                                alertingMetric.LastPagerDutyAlert = DateTime.Now;
                            }
                        }
                    }
                    System.Threading.Thread.Sleep(29000);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                    System.Threading.Thread.Sleep(15000);
                }
            }
        }