/// <summary>
        /// Processes a command throwing a <see cref="LimeException"/> in case of <see cref="CommandStatus.Failure"/> status.
        /// </summary>
        public static Task <Command> ProcessCommandOrThrowAsync <TRequestResource>(
            this ICommandProcessor channel,
            CommandMethod method,
            LimeUri uri,
            TRequestResource resource,
            CancellationToken cancellationToken,
            Node from = null,
            Node to   = null,
            Node pp   = null,
            IDictionary <string, string> metadata = null)
            where TRequestResource : Document
        {
            if (uri == null)
            {
                throw new ArgumentNullException(nameof(uri));
            }
            if (resource == null)
            {
                throw new ArgumentNullException(nameof(resource));
            }

            return(ProcessCommandOrThrowAsync(
                       channel,
                       new Command()
            {
                From = from,
                To = to,
                Pp = pp,
                Method = method,
                Uri = uri,
                Resource = resource,
                Metadata = metadata
            },
                       cancellationToken));
        }
        /// <summary>
        /// Gets a resource from the specified URI.
        /// </summary>
        public static Task <TResource> GetResourceAsync <TResource>(
            this ICommandProcessor channel,
            LimeUri uri,
            CancellationToken cancellationToken,
            Node from = null,
            Node to   = null,
            Node pp   = null,
            IDictionary <string, string> metadata = null)
            where TResource : Document
        {
            if (channel == null)
            {
                throw new ArgumentNullException(nameof(channel));
            }
            if (uri == null)
            {
                throw new ArgumentNullException(nameof(uri));
            }

            return(ProcessCommandWithResponseResourceAsync <TResource>(
                       channel,
                       CommandMethod.Get,
                       uri,
                       cancellationToken,
                       from,
                       to,
                       pp,
                       metadata));
        }
        /// <summary>
        /// Observes a the resource value in the specified URI.
        /// </summary>
        public static Task ObserveResourceAsync <TRequestResource>(
            this ICommandProcessor channel,
            LimeUri uri,
            TRequestResource resource,
            CancellationToken cancellationToken,
            Node from = null,
            Node to   = null,
            Node pp   = null,
            IDictionary <string, string> metadata = null)
            where TRequestResource : Document
        {
            if (channel == null)
            {
                throw new ArgumentNullException(nameof(channel));
            }
            if (uri == null)
            {
                throw new ArgumentNullException(nameof(uri));
            }
            if (resource == null)
            {
                throw new ArgumentNullException(nameof(resource));
            }

            return(ProcessCommandOrThrowAsync(
                       channel,
                       CommandMethod.Observe,
                       uri,
                       resource,
                       cancellationToken,
                       from,
                       to,
                       pp,
                       metadata));
        }
 /// <summary>
 /// Processes a command throwing a <see cref="LimeException"/> in case of <see cref="CommandStatus.Failure"/> status and returns the response resource.
 /// </summary>
 public static Task <TResponseResource> ProcessCommandWithResponseResourceAsync <TRequestResource, TResponseResource>(
     this ICommandProcessor channel,
     CommandMethod method,
     LimeUri uri,
     TRequestResource resource,
     CancellationToken cancellationToken,
     Node from = null,
     Node to   = null,
     Node pp   = null,
     IDictionary <string, string> metadata = null)
     where TRequestResource : Document
     where TResponseResource : Document
 {
     return(ProcessCommandWithResponseResourceAsync <TResponseResource>(
                channel,
                new Command()
     {
         From = from,
         To = to,
         Pp = pp,
         Method = method,
         Uri = uri,
         Resource = resource,
         Metadata = metadata
     },
                cancellationToken));
 }
Beispiel #5
0
        /// <summary>
        /// Composes a command envelope with a
        /// delete method for the specified resource.
        /// </summary>
        /// <param name="channel">The channel.</param>
        /// <param name="uri">The resource uri.</param>
        /// <param name="from">The originator to be used in the command.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentNullException">channel</exception>
        /// <exception cref="LimeException">Returns an exception with the failure reason</exception>
        public static async Task DeleteResourceAsync(this ICommandChannel channel, LimeUri uri, Node from, CancellationToken cancellationToken)
        {
            if (channel == null)
            {
                throw new ArgumentNullException(nameof(channel));
            }
            if (uri == null)
            {
                throw new ArgumentNullException(nameof(uri));
            }

            var requestCommand = new Command
            {
                From   = from,
                Method = CommandMethod.Delete,
                Uri    = uri
            };

            var responseCommand = await channel.ProcessCommandAsync(requestCommand, cancellationToken).ConfigureAwait(false);

            if (responseCommand.Status != CommandStatus.Success)
            {
                if (responseCommand.Reason != null)
                {
                    throw new LimeException(responseCommand.Reason.Code, responseCommand.Reason.Description);
                }
                throw new InvalidOperationException("An invalid command response was received");
            }
        }
        public async Task ReceiveCommandAsync_PingCommandReceivedAndAutoReplyPingsFalse_DoNotSendsPingCommandToTransport()
        {
            var ping    = Dummy.CreatePing();
            var command = Dummy.CreateCommand(ping);

            command.Uri = LimeUri.Parse(UriTemplates.PING);
            var cancellationToken = Dummy.CreateCancellationToken();

            var tcs = new TaskCompletionSource <Envelope>();

            _transport
            .SetupSequence(t => t.ReceiveAsync(It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult <Envelope>(command))
            .Returns(tcs.Task);

            var target = GetTarget(state: SessionState.Established, autoReplyPings: false);
            var actual = await target.ReceiveCommandAsync(cancellationToken);

            actual.ShouldBe(command);

            _transport.Verify(
                t => t.SendAsync(It.Is <Command>(
                                     c => c.Id == command.Id &&
                                     c.To.Equals(command.From) &&
                                     c.Resource is Ping &&
                                     c.Status == CommandStatus.Success),
                                 It.IsAny <CancellationToken>()),
                Times.Never());
        }
Beispiel #7
0
        public void Parse_NullString_ThrowsArgumentNullException()
        {
            string path   = null;
            Action action = () => LimeUri.Parse(path);

            action.ShouldThrow <ArgumentNullException>();
        }
Beispiel #8
0
        public void Parse_InvalidSchemeAbsoluteString_ThrowsArgumentException()
        {
            var    absolutePath = "http://[email protected]/presence";
            Action action       = () => LimeUri.Parse(absolutePath);

            action.ShouldThrow <ArgumentException>();
        }
Beispiel #9
0
 private Task SetPresenceAsync()
 {
     return(_clientChannel.SetResourceAsync(
                LimeUri.Parse(UriTemplates.PRESENCE),
                Presence,
                _receiveTimeout.ToCancellationToken()));
 }
        public async Task ReceiveCommandAsync_PingCommandAbsoluteUriReceivedAndAutoReplyPingsTrue_SendsPingCommandToTransport()
        {
            var ping    = Dummy.CreatePing();
            var command = Dummy.CreateCommand(ping);

            command.Uri = LimeUri.Parse(LimeUri.Parse(UriTemplates.PING).ToUri(command.From).ToString());
            var cancellationToken = Dummy.CreateCancellationToken();

            var tcs = new TaskCompletionSource <Envelope>();

            _transport
            .SetupSequence(t => t.ReceiveAsync(It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult <Envelope>(command))
            .Returns(tcs.Task);

            var target = GetTarget(state: SessionState.Established, autoReplyPings: true);

            await Task.Delay(250);

            _transport.Verify(
                t => t.SendAsync(It.Is <Command>(
                                     c => c.Id == command.Id &&
                                     c.To.Equals(command.From) &&
                                     c.Resource.GetMediaType().ToString().Equals(Ping.MIME_TYPE, StringComparison.OrdinalIgnoreCase) &&
                                     c.Status == CommandStatus.Success),
                                 It.IsAny <CancellationToken>()),
                Times.Once());
        }
Beispiel #11
0
        public void Parse_InvalidRelativeString_ThrowsArgumentException()
        {
            var    resourceName = Dummy.CreateRandomString(10);
            var    invalidPath  = string.Format("\\{0}", resourceName);
            Action action       = () => LimeUri.Parse(invalidPath);

            action.ShouldThrow <ArgumentException>();
        }
Beispiel #12
0
        public void ToUri_RelativeInstance_ThrowsInvalidOperationException()
        {
            var resourceName = DataUtil.CreateRandomString(10);
            var relativePath = string.Format("/{0}", resourceName);
            var limeUri      = LimeUri.Parse(relativePath);

            // Act
            var uri = limeUri.ToUri();
        }
Beispiel #13
0
        public void Parse_ValidRelativeString_ReturnsInstance()
        {
            var resourceName = Dummy.CreateRandomString(10);
            var relativePath = string.Format("/{0}", resourceName);
            var actual       = LimeUri.Parse(relativePath);

            actual.Path.ShouldNotBe(null);
            actual.Path.ShouldBe(relativePath);
            actual.IsRelative.ShouldBe(true);
        }
Beispiel #14
0
        public Task <Command> GetContactsAsync(CancellationToken cancellationToken)
        {
            var rosterCommand = new Command
            {
                Method = CommandMethod.Get,
                Uri    = LimeUri.Parse(UriTemplates.CONTACTS)
            };

            return(Channel.ProcessCommandAsync(rosterCommand, cancellationToken));
        }
Beispiel #15
0
        public void ToUriIdentity_AbsoluteInstance_ThrowsInvalidOperationException()
        {
            var identity     = DataUtil.CreateIdentity();
            var resourceName = DataUtil.CreateRandomString(10);
            var absolutePath = string.Format("{0}://{1}/{2}", LimeUri.LIME_URI_SCHEME, identity, resourceName);
            var limeUri      = LimeUri.Parse(absolutePath);

            // Act
            var uri = limeUri.ToUri(identity);
        }
Beispiel #16
0
        private async void Contacts_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (!ModernUIHelper.IsInDesignMode)
            {
                if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
                {
                    var addedContacts = e.NewItems.Cast <ContactViewModel>();

                    var cancellationToken = _receiveTimeout.ToCancellationToken();

                    foreach (var contactViewModel in addedContacts)
                    {
                        try
                        {
                            await base.ExecuteAsync(async() =>
                            {
                                var identityPresence = await _clientChannel.GetResourceAsync <Presence>(
                                    LimeUri.Parse(UriTemplates.PRESENCE),
                                    new Node()
                                {
                                    Name   = contactViewModel.Contact.Identity.Name,
                                    Domain = contactViewModel.Contact.Identity.Domain
                                },
                                    cancellationToken);

                                if (identityPresence.Instances != null &&
                                    identityPresence.Instances.Any())
                                {
                                    var presence = await _clientChannel.GetResourceAsync <Presence>(
                                        LimeUri.Parse(UriTemplates.PRESENCE),
                                        new Node()
                                    {
                                        Name     = contactViewModel.Contact.Identity.Name,
                                        Domain   = contactViewModel.Contact.Identity.Domain,
                                        Instance = identityPresence.Instances[0]
                                    },
                                        cancellationToken);

                                    contactViewModel.Presence = presence;
                                }
                            });
                        }
                        catch (LimeException ex)
                        {
                            ErrorMessage = ex.Message;
                        }
                        catch (Exception ex)
                        {
                            ErrorMessage = ex.Message;
                            break;
                        }
                    }
                }
            }
        }
Beispiel #17
0
        public Task <Command> SetContactsAsync(Contact contact, CancellationToken cancellationToken)
        {
            var contactCommand = new Command
            {
                Method   = CommandMethod.Set,
                Uri      = LimeUri.Parse(UriTemplates.CONTACTS),
                Resource = contact
            };

            return(Channel.ProcessCommandAsync(contactCommand, cancellationToken));
        }
Beispiel #18
0
        public void ToUri_RelativeInstance_ThrowsInvalidOperationException()
        {
            var resourceName = Dummy.CreateRandomString(10);
            var relativePath = string.Format("/{0}", resourceName);
            var limeUri      = LimeUri.Parse(relativePath);

            // Act
            Action action = () => limeUri.ToUri();

            action.ShouldThrow <InvalidOperationException>();
        }
Beispiel #19
0
        public void Parse_ValidAbsoluteString_ReturnsInstance()
        {
            var identity     = Dummy.CreateIdentity();
            var resourceName = Dummy.CreateRandomString(10);
            var absolutePath = string.Format("{0}://{1}/{2}", LimeUri.LIME_URI_SCHEME, identity, resourceName);
            var actual       = LimeUri.Parse(absolutePath);

            actual.Path.ShouldNotBe(null);
            actual.Path.ShouldBe(absolutePath);
            actual.IsRelative.ShouldBe(false);
        }
 private async Task SetPresenceAsync(IClientChannel clientChannel, CancellationToken cancellationToken = default(CancellationToken))
 {
     if (!IsGuest(clientChannel.LocalNode.Name))
     {
         await clientChannel.SetResourceAsync(
             LimeUri.Parse(UriTemplates.PRESENCE),
             new Presence { Status = PresenceStatus.Available, RoutingRule = RoutingRule, RoundRobin = true },
             cancellationToken)
         .ConfigureAwait(false);
     }
 }
Beispiel #21
0
        public void Parse_ValidAbsoluteSpecialCharactersStringContainingSpace_ReturnsInstance()
        {
            var identity = Dummy.CreateIdentity();
            var resourceNameWithSpace = $"{Dummy.CreateRandomStringSpecial(5)} {Dummy.CreateRandomStringSpecial(5)}";
            var absolutePath          = string.Format("{0}://{1}/{2}", LimeUri.LIME_URI_SCHEME, identity, Uri.EscapeDataString(resourceNameWithSpace));
            var actual = LimeUri.Parse(absolutePath);

            actual.Path.ShouldNotBe(null);
            actual.Path.ShouldBe(absolutePath);
            actual.IsRelative.ShouldBe(false);
        }
Beispiel #22
0
 public override void WriteJson(global::Newtonsoft.Json.JsonWriter writer, object value, global::Newtonsoft.Json.JsonSerializer serializer)
 {
     if (value != null)
     {
         LimeUri identity = (LimeUri)value;
         writer.WriteValue(identity.ToString());
     }
     else
     {
         writer.WriteNull();
     }
 }
Beispiel #23
0
            public override object ReadJson(JsonReader reader, Type objectType, object existingValue, global::Newtonsoft.Json.JsonSerializer serializer)
            {
                if (reader.TokenType == JsonToken.String)
                {
                    var tokenValue = reader.Value.ToString();

                    return(LimeUri.Parse(tokenValue));
                }
                else
                {
                    return(null);
                }
            }
Beispiel #24
0
        private async Task GetContactsAsync()
        {
            var contactCollection = await _clientChannel.GetResourceAsync <DocumentCollection>(
                LimeUri.Parse(UriTemplates.CONTACTS),
                _receiveTimeout.ToCancellationToken());

            Contacts.Clear();

            foreach (Contact contact in contactCollection.Items)
            {
                Contacts.Add(new ContactViewModel(contact, _clientChannel));
            }
        }
        private async Task SetReceiptAsync(IClientChannel clientChannel, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (IsGuest(clientChannel.LocalNode.Name) ||
                ReceiptEvents.Length == 0)
            {
                return;
            }

            await clientChannel.SetResourceAsync(
                LimeUri.Parse(UriTemplates.RECEIPT),
                new Receipt { Events = ReceiptEvents },
                cancellationToken)
            .ConfigureAwait(false);
        }
Beispiel #26
0
        public void ToUri_AbsoluteInstance_ReturnsUri()
        {
            var identity     = Dummy.CreateIdentity();
            var resourceName = Dummy.CreateRandomString(10);
            var absolutePath = string.Format("{0}://{1}/{2}", LimeUri.LIME_URI_SCHEME, identity, resourceName);
            var limeUri      = LimeUri.Parse(absolutePath);

            // Act
            var uri = limeUri.ToUri();

            // Assert
            uri.Scheme.ShouldBe(LimeUri.LIME_URI_SCHEME);
            uri.UserInfo.ShouldBe(identity.Name);
            uri.Authority.ShouldBe(identity.Domain);
            uri.PathAndQuery.ShouldBe("/" + resourceName);
        }
Beispiel #27
0
        public Task RejectPendingContactAsync()
        {
            return(ExecuteAsync(async() =>
            {
                var selectedContact = SelectedContact;
                if (selectedContact != null &&
                    selectedContact.Contact != null)
                {
                    await _clientChannel.DeleteResourceAsync(
                        LimeUri.Parse(UriTemplates.CONTACT.NamedFormat(new { contactIdentity = selectedContact.Contact.Identity })),
                        _receiveTimeout.ToCancellationToken());

                    await GetContactsAsync();
                }
            }));
        }
Beispiel #28
0
        private Task RemoveContactAsync()
        {
            return(ExecuteAsync(async() =>
            {
                var selectedContact = SelectedContact;

                if (selectedContact != null &&
                    selectedContact.Contact != null)
                {
                    await _clientChannel.DeleteResourceAsync(
                        LimeUri.Parse(Smart.Format(UriTemplates.CONTACT, new { contactIdentity = SelectedContact.Contact })),
                        _receiveTimeout.ToCancellationToken());

                    await GetContactsAsync();
                }
            }));
        }
Beispiel #29
0
        /// <summary>
        /// Sets the resource value asynchronous.
        /// </summary>
        /// <typeparam name="TResource">The type of the resource.</typeparam>
        /// <param name="channel">The channel.</param>
        /// <param name="uri">The resource uri.</param>
        /// <param name="resource">The resource.</param>
        /// <param name="from">From.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentNullException">channel</exception>
        /// <exception cref="LimeException"></exception>
        public static async Task SetResourceAsync <TResource>(this IChannel channel, LimeUri uri, TResource resource, Node from, CancellationToken cancellationToken) where TResource : Document
        {
            if (channel == null)
            {
                throw new ArgumentNullException("channel");
            }

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

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

            var requestCommand = new Command()
            {
                From     = from,
                Method   = CommandMethod.Set,
                Uri      = uri,
                Resource = resource
            };

            var responseCommand = await ProcessCommandAsync(channel, requestCommand, cancellationToken).ConfigureAwait(false);

            if (responseCommand.Status != CommandStatus.Success)
            {
                if (responseCommand.Reason != null)
                {
                    throw new LimeException(responseCommand.Reason.Code, responseCommand.Reason.Description);
                }
                else
                {
#if DEBUG
                    if (requestCommand == responseCommand)
                    {
                        throw new InvalidOperationException("The request and the response are the same instance");
                    }
#endif

                    throw new InvalidOperationException("An invalid command response was received");
                }
            }
        }
        static ServiceStackSerializer()
        {
            JsConfig.ExcludeTypeInfo                 = true;
            JsConfig.EmitCamelCaseNames              = true;
            JsConfig <Message> .IncludeTypeInfo      = false;
            JsConfig <Notification> .IncludeTypeInfo = false;
            JsConfig <Command> .IncludeTypeInfo      = false;
            JsConfig <Session> .IncludeTypeInfo      = false;


            JsConfig <MediaType> .SerializeFn   = m => m.ToString();
            JsConfig <MediaType> .DeSerializeFn = s => MediaType.Parse(s);
            JsConfig <Node> .SerializeFn        = n => n.ToString();
            JsConfig <Node> .DeSerializeFn      = s => Node.Parse(s);
            JsConfig <Identity> .SerializeFn    = i => i.ToString();
            JsConfig <Identity> .DeSerializeFn  = s => Identity.Parse(s);
            JsConfig <Guid> .SerializeFn        = g => g.ToString();
            JsConfig <Guid> .DeSerializeFn      = s => Guid.Parse(s);
            JsConfig <LimeUri> .SerializeFn     = u => u.ToString();
            JsConfig <LimeUri> .DeSerializeFn   = u => LimeUri.Parse(u);

            JsConfig <Document> .RawSerializeFn = d =>
            {
                var mediaType = d.GetMediaType();
                if (mediaType.IsJson)
                {
                    return(global::ServiceStack.Text.JsonSerializer.SerializeToString(d));
                }
                else
                {
                    return(string.Format("\"{0}\"", d.ToString()));
                }
            };

            foreach (var enumType in TypeUtil.GetEnumTypes())
            {
                var jsonConfigEnumType    = typeof(JsConfig <>).MakeGenericType(enumType);
                var serializeProperty     = jsonConfigEnumType.GetProperty("SerializeFn");
                var serializeFuncType     = typeof(Func <,>).MakeGenericType(enumType, typeof(string));
                var methodInfo            = typeof(ServiceStackSerializer).GetMethod("ToCamelCase", BindingFlags.Static | BindingFlags.NonPublic);
                var enumToCamelCaseMethod = methodInfo.MakeGenericMethod(enumType);
                var serializeFunc         = Delegate.CreateDelegate(serializeFuncType, enumToCamelCaseMethod);
                serializeProperty.SetValue(null, serializeFunc, BindingFlags.Static, null, null, CultureInfo.InvariantCulture);
            }
        }
        public void Deserialize_CapabilityRequestCommand_ReturnsValidInstance()
        {
            var target = GetTarget();

            var contentType1 = DataUtil.CreateJsonMediaType();
            var contentType2 = DataUtil.CreateJsonMediaType();
            var contentType3 = DataUtil.CreateJsonMediaType();

            var resourceType1 = DataUtil.CreateJsonMediaType();
            var resourceType2 = DataUtil.CreateJsonMediaType();
            var resourceType3 = DataUtil.CreateJsonMediaType();

            var method = CommandMethod.Get;

            var id = Guid.NewGuid();

            var from = DataUtil.CreateNode();
            var pp = DataUtil.CreateNode();
            var to = DataUtil.CreateNode();

            string randomKey1 = "randomString1";
            string randomKey2 = "randomString2";
            string randomString1 = DataUtil.CreateRandomString(50);
            string randomString2 = DataUtil.CreateRandomString(50);

            var resourceUri = new LimeUri("/capability");

            string json = string.Format(
                "{{\"uri\":\"{0}\",\"type\":\"application/vnd.lime.capability+json\",\"resource\":{{\"contentTypes\":[\"{1}\",\"{2}\",\"{3}\"],\"resourceTypes\":[\"{4}\",\"{5}\",\"{6}\"]}},\"method\":\"{7}\",\"id\":\"{8}\",\"from\":\"{9}\",\"pp\":\"{10}\",\"to\":\"{11}\",\"metadata\":{{\"{12}\":\"{13}\",\"{14}\":\"{15}\"}}}}",
                resourceUri,
                contentType1,
                contentType2,
                contentType3,
                resourceType1,
                resourceType2,
                resourceType3,
                method.ToString().ToCamelCase(),
                id,
                from,
                pp,
                to,
                randomKey1,
                randomString1,
                randomKey2,
                randomString2);

            var envelope = target.Deserialize(json);

            Assert.IsTrue(envelope is Command);
            var command = (Command)envelope;
            Assert.AreEqual(id, command.Id);
            Assert.AreEqual(from, command.From);
            Assert.AreEqual(pp, command.Pp);
            Assert.AreEqual(to, command.To);

            Assert.AreEqual(method, command.Method);
            Assert.IsNotNull(command.Metadata);
            Assert.IsTrue(command.Metadata.ContainsKey(randomKey1));
            Assert.AreEqual(command.Metadata[randomKey1], randomString1);
            Assert.IsTrue(command.Metadata.ContainsKey(randomKey2));
            Assert.AreEqual(command.Metadata[randomKey2], randomString2);

            Assert.IsTrue(command.Resource is Capability);

            var capability = (Capability)command.Resource;

            Assert.IsTrue(capability.ContentTypes.Any(c => c.Equals(contentType1)));
            Assert.IsTrue(capability.ContentTypes.Any(c => c.Equals(contentType2)));
            Assert.IsTrue(capability.ContentTypes.Any(c => c.Equals(contentType3)));

            Assert.IsTrue(capability.ResourceTypes.Any(c => c.Equals(resourceType1)));
            Assert.IsTrue(capability.ResourceTypes.Any(c => c.Equals(resourceType2)));
            Assert.IsTrue(capability.ResourceTypes.Any(c => c.Equals(resourceType3)));

            Assert.IsNotNull(command.Uri);
            Assert.AreEqual(command.Uri, resourceUri);
        }