Esempio n. 1
0
        public virtual Task SendGroupsAsync(IReadOnlyList <string> groupNames, IPushMessage message, CancellationToken cancellationToken = default)
        {
            // Each task represents the list of tasks for each of the writes within a group
            List <Task> tasks = null;

            string serMessage = null;

            foreach (var groupName in groupNames)
            {
                if (string.IsNullOrEmpty(groupName))
                {
                    throw new InvalidOperationException("Cannot send to an empty group name.");
                }

                var group = _groups[groupName];
                if (group != null)
                {
                    SendToGroupConnections(message, group, null, ref tasks, ref serMessage);
                }
            }

            if (tasks != null)
            {
                return(Task.WhenAll(tasks));
            }

            return(Task.CompletedTask);
        }
Esempio n. 2
0
        public void CreateProject(string name, string gitUrl, IPushMessage output,
                                  IReceiveStreamWriter input)
        {
            if (Exists(name))
            {
                output.PushMessage($"Project {name} already exists.");

                return;
            }


            string configPath = GetConfigPath(name);
            string projPath   = GetProjectPath(name);

            var proj = new Project()
            {
                GitUrl = gitUrl,
            };

            SaveProject(name, proj);

            Directory.CreateDirectory(projPath);


            // Clone git repo
            Shell.WorkingDirectory = projPath;
            var process = Shell.Execute("git", $"clone \"{gitUrl}\" .",
                                        output.PushMessage);

            input.SetStreamWriter(process.StandardInput);

            process.WaitForExit();
            process.Close();
        }
Esempio n. 3
0
        public void RunProject(string name, string args, IPushMessage output,
                               IReceiveStreamWriter input)
        {
            if (Exists(name))
            {
                var proj = LoadProject(name);


                SyncProject(name, output);


                // Run script
                if (string.IsNullOrWhiteSpace(proj.RunScript) == false)
                {
                    Shell.WorkingDirectory = GetProjectPath(name);
                    var process = Shell.Execute("cmd", "/C " + proj.RunScript + " " + args,
                                                output.PushMessage);

                    input.SetStreamWriter(process.StandardInput);

                    process.WaitForExit();
                    process.Close();
                }
            }
            else
            {
                output.PushMessage($"Project {name} does not exists.");
            }
        }
Esempio n. 4
0
        public virtual Task SendGroupAsync(string groupName, IPushMessage message, CancellationToken cancellationToken = default)
        {
            if (groupName == null)
            {
                throw new ArgumentNullException(nameof(groupName));
            }

            var group = _groups[groupName];

            if (group != null)
            {
                // Can't optimize for sending to a single connection in a group because
                // group might be modified inbetween checking and sending
                List <Task> tasks = null;

                string serMessage = null;

                SendToGroupConnections(message, group, null, ref tasks, ref serMessage);

                if (tasks != null)
                {
                    return(Task.WhenAll(tasks));
                }
            }

            return(Task.CompletedTask);
        }
Esempio n. 5
0
        public void BuildProject(string name, string args, IPushMessage output)
        {
            if (Exists(name))
            {
                var proj = LoadProject(name);


                SyncProject(name, output);


                // Run build script
                if (string.IsNullOrWhiteSpace(proj.BuildScript) == false)
                {
                    var process = Shell.Execute("cmd", "/C " + proj.BuildScript + " " + args,
                                                output.PushMessage);

                    process.WaitForExit();
                    process.Close();
                }
            }
            else
            {
                output.PushMessage($"Project {name} does not exists.");
            }
        }
Esempio n. 6
0
        private Task SendToAllConnections(IPushMessage message, Func <IConnectionContext, bool> include)
        {
            List <Task> tasks = null;

            var serializedMessage = message.GetMessage();

            // foreach over HubConnectionStore avoids allocating an enumerator
            foreach (var connection in _connections)
            {
                if (include != null && !include(connection))
                {
                    continue;
                }

                var task = connection.WriteAsync(serializedMessage, CancellationToken.None);

                if (!task.IsCompleted)
                {
                    tasks.Add(task);
                }
            }

            if (tasks == null)
            {
                return(Task.CompletedTask);
            }

            // Some connections are slow
            return(Task.WhenAll(tasks));
        }
Esempio n. 7
0
        public byte[] WriteInvocation(IPushMessage message, IReadOnlyList <string> excludedConnectionIds)
        {
            // Written as a MessagePack 'arr' containing at least these items:
            // * A MessagePack 'arr' of 'str's representing the excluded ids
            // * [The output of WriteSerializedHubMessage, which is an 'arr']
            // Any additional items are discarded.

            var writer = MemoryBufferWriter.Get();

            try
            {
                MessagePackBinary.WriteArrayHeader(writer, 2);
                if (excludedConnectionIds != null && excludedConnectionIds.Count > 0)
                {
                    MessagePackBinary.WriteArrayHeader(writer, excludedConnectionIds.Count);
                    foreach (var id in excludedConnectionIds)
                    {
                        MessagePackBinary.WriteString(writer, id);
                    }
                }
                else
                {
                    MessagePackBinary.WriteArrayHeader(writer, 0);
                }

                WriteSerializedHubMessage(writer, message);
                return(writer.ToArray());
            }
            finally
            {
                MemoryBufferWriter.Return(writer);
            }
        }
Esempio n. 8
0
        private void SendToGroupConnections(IPushMessage message, ConcurrentDictionary <string, IConnectionContext> connections, Func <IConnectionContext, bool> include, ref List <Task> tasks, ref string serializedMessage)
        {
            if (serializedMessage == null)
            {
                serializedMessage = message.GetMessage();
            }
            // foreach over ConcurrentDictionary avoids allocating an enumerator
            foreach (var connection in connections)
            {
                if (include != null && !include(connection.Value))
                {
                    continue;
                }

                var task = connection.Value.WriteAsync(serializedMessage, CancellationToken.None);

                if (!task.IsCompleted)
                {
                    if (tasks == null)
                    {
                        tasks = new List <Task>();
                    }

                    tasks.Add(task);
                }
            }
        }
        public WcfService(string url)
        {
            Url = url;
            InitCBHandler();

            channelFactory = new DuplexChannelFactory <IPushMessage>(callback, new NetTcpBinding(SecurityMode.None), Url);
            proxy          = channelFactory.CreateChannel();
        }
Esempio n. 10
0
        public void Notification(IPushMessage message)
        {
            if (!Logger.IsInfoEnabled)
            {
                return;
            }

            Logger.Info(JsonConvert.SerializeObject(message));
        }
Esempio n. 11
0
        private void WriteSerializedHubMessage(Stream stream, IPushMessage message)
        {
            // Written as a MessagePack 'map' where the keys are the name of the protocol (as a MessagePack 'str')
            // and the values are the serialized blob (as a MessagePack 'bin').

            var serialized = message.GetMessage();

            MessagePackBinary.WriteString(stream, serialized);
        }
Esempio n. 12
0
        public override void Start()
        {
            using (IPushMessage client = WCFHelper.CreateService <IPushMessage>("BasicHttpBinding_IPushMessage"))
            {
                client.Push(input);
            }

            WCFHelper.ExecuteMethod <IPushMessage>("BasicHttpBinding_IPushMessage", "Push", new object[] { input });
        }
Esempio n. 13
0
        public Task SendGroupExceptAsync(string groupName, IPushMessage message, IReadOnlyList <string> excludedConnectionIds, CancellationToken cancellationToken = default)
        {
            if (groupName == null)
            {
                throw new ArgumentNullException(nameof(groupName));
            }

            var payload = _protocol.WriteInvocation(message, excludedConnectionIds);

            return(PublishAsync(_channels.Group(groupName), payload));
        }
Esempio n. 14
0
        public void ListAllProject(IPushMessage output)
        {
            var buffer = new StringBuilder();

            foreach (string file in Directory.GetFiles(ConfigDir, "*.json"))
            {
                buffer.AppendLine(Path.GetFileNameWithoutExtension(file));
            }

            output.PushMessage(buffer.ToString());
        }
Esempio n. 15
0
 private static async void SendPush(ApiServices service, IPushMessage message)
 {
     try
     {
         PushClient cliente = new PushClient(service);
         await cliente.SendAsync(message);
     }
     catch (System.Exception ex)
     {
     }
 }
        /// <summary>
        /// Sends a notification to the Notification Hub.
        /// </summary>
        /// <param name="message">The notification payload is one of <see cref="WindowsPushMessage"/>,
        /// <see cref="ApplePushMessage"/>, or <see cref="TemplatePushMessage"/>.</param>
        /// <returns>A <see cref="Task{T}"/> representing the notification send operation.</returns>
        public virtual Task <NotificationOutcome> SendAsync(IPushMessage message)
        {
            if (message == null)
            {
                throw new ArgumentNullException("message");
            }

            Notification notification = this.CreateNotification(message);

            return(this.SendNotificationAsync(notification, string.Empty));
        }
        private static string GetUnknownPayloadError(IPushMessage message)
        {
            string knownFormats = string.Join(", ",
                                              typeof(WindowsPushMessage).Name,
                                              typeof(MpnsPushMessage).Name,
                                              typeof(ApplePushMessage).Name,
                                              typeof(GooglePushMessage).Name,
                                              typeof(TemplatePushMessage).Name);

            return(RResources.NotificationHub_UnknownPayload.FormatForUser(message.GetType(), knownFormats));
        }
Esempio n. 18
0
 private bool GetWcfServiceBool(Func <bool> func)
 {
     try
     {
         return(func());
     }
     catch (Exception ex)
     {
         proxy = channelFactory.CreateChannel();
         return(func());
     }
 }
Esempio n. 19
0
 private void GetWcfServiceVoid(string name, Action func)
 {
     try
     {
         func();
     }
     catch (Exception ex)
     {
         proxy = channelFactory.CreateChannel();
         func();
     }
 }
Esempio n. 20
0
 private void GetWcfMsgVoid(SendInfo sendInfo, Action func)
 {
     try
     {
         func();
     }
     catch (Exception ex)
     {
         proxy = channelFactory.CreateChannel();
         func();
     }
 }
Esempio n. 21
0
 private string GetWcfServiceString(string TransactionId, string SendName, string RecvName, Func <string> func)
 {
     try
     {
         return(func());
     }
     catch (Exception ex)
     {
         proxy = channelFactory.CreateChannel();
         return(func());
     }
 }
Esempio n. 22
0
        public void InfoProject(string name, IPushMessage output)
        {
            if (Exists(name))
            {
                var proj = LoadProject(name);

                output.PushMessage(proj.ToJson());
            }
            else
            {
                output.PushMessage($"Project {name} does not exists.");
            }
        }
Esempio n. 23
0
        public void SyncProject(string name, IPushMessage output)
        {
            if (Exists(name))
            {
                // Sync repo
                Shell.WorkingDirectory = GetProjectPath(name);
                string pullResult = Shell.Execute("git", "pull");

                output.PushMessage(pullResult);
            }
            else
            {
                output.PushMessage($"Project {name} does not exists.");
            }
        }
Esempio n. 24
0
        public void ConfigProject(string name, string prop, string data, IPushMessage output)
        {
            if (Exists(name))
            {
                var proj = LoadProject(name);

                proj.SetProperty(prop, data);

                SaveProject(name, proj);
            }
            else
            {
                output.PushMessage($"Project {name} does not exists.");
            }
        }
Esempio n. 25
0
        public void DeleteProject(string name, IPushMessage output)
        {
            if (Exists(name))
            {
                string projPath   = GetProjectPath(name);
                string configPath = GetConfigPath(name);

                NoException(() => DeleteDirectory(projPath));
                NoException(() => File.Delete(configPath));
            }
            else
            {
                output.PushMessage($"Project {name} does not exists.");
            }
        }
        public virtual Task <NotificationOutcome> SendAsync(IPushMessage message, IEnumerable <string> tags)
        {
            if (message == null)
            {
                throw new ArgumentNullException("message");
            }

            if (tags == null)
            {
                throw new ArgumentNullException("tags");
            }

            Notification notification = this.CreateNotification(message);

            return(this.SendNotificationAsync(notification, tags));
        }
Esempio n. 27
0
        public Task SendConnectionsAsync(IReadOnlyList <string> connectionIds, IPushMessage message, CancellationToken cancellationToken = default)
        {
            if (connectionIds == null)
            {
                throw new ArgumentNullException(nameof(connectionIds));
            }

            var publishTasks = new List <Task>(connectionIds.Count);
            var payload      = _protocol.WriteInvocation(message);

            foreach (var connectionId in connectionIds)
            {
                publishTasks.Add(PublishAsync(_channels.Connection(connectionId), payload));
            }

            return(Task.WhenAll(publishTasks));
        }
Esempio n. 28
0
        public void SendAsync_SendsValidNotification(IPushMessage message, Type expected)
        {
            // Arrange
            this.clientMock.Protected()
            .Setup("SendNotificationAsync", ItExpr.IsAny <Notification>(), string.Empty)
            .Callback((Notification notification, string tagExpression) =>
            {
                Assert.IsType(expected, notification);
            })
            .Verifiable();

            // Act
            this.client.SendAsync(message);

            // Assert
            this.clientMock.Verify();
        }
        /// <summary>
        /// Creates a <see cref="Notification"/> from a <see cref="IPushMessage"/>.
        /// </summary>
        /// <param name="message">The <see cref="IPushMessage"/> to create the <see cref="Notification"/> from.</param>
        /// <returns>The resulting <see cref="Notification"/>.</returns>
        protected virtual Notification CreateNotification(IPushMessage message)
        {
            if (message == null)
            {
                throw new ArgumentNullException("message");
            }

            Notification        notification = null;
            ApplePushMessage    apnsPush;
            WindowsPushMessage  wnsPush;
            MpnsPushMessage     mpnsPush;
            TemplatePushMessage templatePush;

            if ((wnsPush = message as WindowsPushMessage) != null)
            {
                notification = new WindowsNotification(wnsPush.ToString(), wnsPush.Headers);
            }
            else if ((mpnsPush = message as MpnsPushMessage) != null)
            {
                notification = new MpnsNotification(mpnsPush.ToString(), mpnsPush.Headers);
            }
            else if ((apnsPush = message as ApplePushMessage) != null)
            {
                DateTime?expiration = null;
                if (apnsPush.Expiration.HasValue)
                {
                    expiration = apnsPush.Expiration.Value.DateTime;
                }
                notification = new AppleNotification(message.ToString(), expiration);
            }
            else if (message is GooglePushMessage)
            {
                notification = new GcmNotification(message.ToString());
            }
            else if ((templatePush = message as TemplatePushMessage) != null)
            {
                notification = new TemplateNotification(templatePush);
            }
            else
            {
                throw new InvalidOperationException(GetUnknownPayloadError(message));
            }

            return(notification);
        }
Esempio n. 30
0
        public void CmdProject(string name, string command, IPushMessage output,
                               IReceiveStreamWriter input)
        {
            if (Exists(name))
            {
                Shell.WorkingDirectory = GetProjectPath(name);
                var process = Shell.Execute("cmd", "/C " + command,
                                            output.PushMessage);

                input.SetStreamWriter(process.StandardInput);

                process.WaitForExit();
                process.Close();
            }
            else
            {
                output.PushMessage($"Project {name} does not exists.");
            }
        }
        public void SendAsync_WithTag_SendsValidNotification(IPushMessage message, Type expected)
        {
            // Arrange
            List<string> tags = new List<string>();
            this.clientMock.Protected()
                .Setup("SendNotificationAsync", ItExpr.IsAny<Notification>(), tags)
                .Callback((Notification notification, IEnumerable<string> t) =>
                {
                    Assert.IsType(expected, notification);
                })
                .Verifiable();

            // Act
            this.client.SendAsync(message, tags);

            // Assert
            this.clientMock.Verify();
        }
        public void SendAsync_WithTagExpression_SendsValidNotification(IPushMessage message, Type expected)
        {
            // Arrange
            string tagExpression = "Hello";
            this.clientMock.Protected()
                .Setup("SendNotificationAsync", ItExpr.IsAny<Notification>(), tagExpression)
                .Callback((Notification notification, string tagExpr) =>
                {
                    Assert.IsType(expected, notification);
                })
                .Verifiable();

            // Act
            this.client.SendAsync(message, tagExpression);

            // Assert
            this.clientMock.Verify();
        }
 private static string GetUnknownPayloadError(IPushMessage message)
 {
     string knownFormats = string.Join(", ",
         typeof(WindowsPushMessage).Name,
         typeof(MpnsPushMessage).Name,
         typeof(ApplePushMessage).Name,
         typeof(GooglePushMessage).Name,
         typeof(TemplatePushMessage).Name);
     return RResources.NotificationHub_UnknownPayload.FormatForUser(message.GetType(), knownFormats);
 }
        /// <summary>
        /// Creates a <see cref="Notification"/> from a <see cref="IPushMessage"/>.
        /// </summary>
        /// <param name="message">The <see cref="IPushMessage"/> to create the <see cref="Notification"/> from.</param>
        /// <returns>The resulting <see cref="Notification"/>.</returns>
        protected virtual Notification CreateNotification(IPushMessage message)
        {
            if (message == null)
            {
                throw new ArgumentNullException("message");
            }

            Notification notification = null;
            ApplePushMessage apnsPush;
            WindowsPushMessage wnsPush;
            MpnsPushMessage mpnsPush;
            TemplatePushMessage templatePush;
            if ((wnsPush = message as WindowsPushMessage) != null)
            {
                notification = new WindowsNotification(wnsPush.ToString(), wnsPush.Headers);
            }
            else if ((mpnsPush = message as MpnsPushMessage) != null)
            {
                notification = new MpnsNotification(mpnsPush.ToString(), mpnsPush.Headers);
            }
            else if ((apnsPush = message as ApplePushMessage) != null)
            {
                DateTime? expiration = null;
                if (apnsPush.Expiration.HasValue)
                {
                    expiration = apnsPush.Expiration.Value.DateTime;
                }
                notification = new AppleNotification(message.ToString(), expiration);
            }
            else if (message is GooglePushMessage)
            {
                notification = new GcmNotification(message.ToString());
            }
            else if ((templatePush = message as TemplatePushMessage) != null)
            {
                notification = new TemplateNotification(templatePush);
            }
            else
            {
                throw new InvalidOperationException(GetUnknownPayloadError(message));
            }

            return notification;
        }
        /// <summary>
        /// Sends a notification to the Notification Hub with a given tag expression.
        /// </summary>
        /// <param name="message">The notification payload is one of <see cref="WindowsPushMessage"/>,
        /// <see cref="ApplePushMessage"/>, or <see cref="TemplatePushMessage"/>.</param>
        /// <param name="tags">The set of tags to use for this notification.</param>
        /// <returns>A <see cref="Task{T}"/> representing the notification send operation.</returns>
        public virtual Task<NotificationOutcome> SendAsync(IPushMessage message, IEnumerable<string> tags)
        {
            if (message == null)
            {
                throw new ArgumentNullException("message");
            }

            if (tags == null)
            {
                throw new ArgumentNullException("tags");
            }

            Notification notification = this.CreateNotification(message);
            return this.SendNotificationAsync(notification, tags);
        }
        /// <summary>
        /// Sends a notification to the Notification Hub with a given tag expression.
        /// </summary>
        /// <param name="message">The notification payload is one of <see cref="WindowsPushMessage"/>,
        /// <see cref="ApplePushMessage"/>, or <see cref="TemplatePushMessage"/>.</param>
        /// <param name="tagExpression">A tag expression representing the combination of tags to use for this notification.</param>
        /// <returns>A <see cref="Task{T}"/> representing the notification send operation.</returns>
        public virtual Task<NotificationOutcome> SendAsync(IPushMessage message, string tagExpression)
        {
            if (message == null)
            {
                throw new ArgumentNullException("message");
            }

            if (tagExpression == null)
            {
                throw new ArgumentNullException("tagExpression");
            }

            Notification notification = this.CreateNotification(message);
            return this.SendNotificationAsync(notification, tagExpression);
        }