Example #1
0
 private Token(Token oldToken, ILink link)
     : this(oldToken.Document, oldToken.FullName, oldToken.Value, oldToken.Type, oldToken.LineNumber, oldToken.IsDeclaration, oldToken.IsSearchable)
 {
     Link = link;
     LeadingTrivia = oldToken.LeadingTrivia;
     TrailingTrivia = oldToken.TrailingTrivia;
 }
        public LinkViewModel(ILink link)
        {
            if (link == null)
                throw new ArgumentNullException("link");

            this.link = link;
        }
		/// <summary>
		/// Adds a link
		/// </summary>
		/// <param name="NewLink">The link</param>
		public virtual void AddLink (ILink NewLink) 
		{
			if (NewLink.SourceComponent==this)
			{
				for (int iNewDO = 0; iNewDO < NewLink.DataOperationsCount; iNewDO++)
				{
					IDataOperation newDataOperation = NewLink.GetDataOperation(iNewDO);
					foreach (ILink link in _providingLinks)
					{
						for (int iExistingDO = 0; iExistingDO < link.DataOperationsCount; iExistingDO++)
						{
							IDataOperation existingDataOperation = link.GetDataOperation(iExistingDO);
							if (newDataOperation == existingDataOperation)
							{
								Event warning = new Event(EventType.Warning);
								warning.Description = "DataOperation " + newDataOperation.ID + " has already been used. " +
									"It's argument values will overrule the values set previously for this operation.";
								warning.Sender = this;
								SendEvent(warning);
							}
						}
					}
				}
				_providingLinks.Add(NewLink);
			}
			if (NewLink.TargetComponent==this)
			{
				_acceptingLinks.Add(NewLink);
			}
		}
Example #4
0
 public void LinkFrontendSetup()
 {
     var decrypter = new DecryptStm();
     var encrypter = new EncryptStm();
     _fakePhysical = Substitute.For<IPhysical>();
     _uut = new Link(decrypter, encrypter, _fakePhysical, 1000);
 }
Example #5
0
 public void AddInput(ILink link, IFuzzyNumber weight)
 {
     _inputs.Add(link);
     _weights.Add(new Link(weight));
     _weightsDeltas.Add(new Link());
     _weightsLambdas.Add(_defaultWeightLambda);
 }
 /// <summary>
 /// Builds a new RelationshipObject with links and linkage
 /// </summary>
 public RelationshipObject(IResourceLinkage linkage, ILink selfLink, ILink relatedResourceLink, IMetadata metadata = null)
 {
     Linkage = linkage;
     SelfLink = selfLink;
     RelatedResourceLink = relatedResourceLink;
     Metadata = metadata;
 }
Example #7
0
 public void AddInput(ILink link)
 {
     _inputs.Add(link);
     _weights.Add(new Link(_generateLittleFuzzyNumber()));
     _weightsDeltas.Add(new Link());
     _weightsLambdas.Add(_defaultWeightLambda);
 }
Example #8
0
 public void Disconnect()
 {
     _sender = null;
     _receiver = null;
     _link.Close();
     _link = null;
     _connected = false;
 }
 public SandboxControlLink(ILink link, INode from, INode to, SandboxControl control, IKeyTableFactory tableFactory, IPrimFactory primFactory, IPermissions permissions)
     : base(link, from, to, control, permissions)
 {
     _control = control;
     _bufferedChanges = tableFactory.MakeKeyTable<double>();
     _dialog = new Dialog(control.HostPrim, primFactory, LINK_BUTTONS);
     _dialog.ResponseReceived += DialogPressed;
 }
Example #10
0
        public void setLink(ILink link)
        {
            if (_link == link) return;

            _link = link;

            dependEntity = calculateDependEntity();
        }
Example #11
0
 public void Connect(string portName, int baud, int databits)
 {
     var port = new SerialPort(portName, baud, Parity.None, databits, StopBits.One);
     _link = Factory.GetLink(port, LinkBufferSize, LinkTimeoutModifier);
     _sender = new SenderStmContext(_link, _checksum, new SequenceGenerator(), MaxMessageDataSize, MessageTimeoutModifier);
     _receiver = new ReceiverStmContext(_link, _checksum, new SequenceGenerator(), MaxMessageDataSize);
     _connected = true;
 }
Example #12
0
		/// <summary>
		/// Checks whether the specified link is a participant in the path.
		/// </summary>
		public bool Contains(ILink link)
		{
			foreach (ILink l in _links)
				if (l.Equals(link))
					return true;

			return false;
		}
 protected override HttpRequestMessage ApplyChanges(ILink link, HttpRequestMessage request)
 {
     request.Headers.Accept.Clear();
     foreach (var headerValue in _AcceptHeader)
     {
         request.Headers.Accept.Add(headerValue);
     }
     return request;
 }
        public TorshifySongPlayerTest()
        {
            _session = Substitute.For<ISession>();
            _link = Substitute.For<ILink<ITrackAndOffset>>();

            var linkFactory = Substitute.For<ILinkFactory>();
            linkFactory.GetLink(Arg.Any<string>()).Returns(_link);

            _songPlayer = new TorshifySongPlayer(_session, linkFactory);
        }
		public void AddLink(ILink link)
		{
			var myLink = link as Link;
			if (myLink != null)
			{
				if (myLink.Source != null)
					myLink.Source.ChildrenCount++;
				this.mindmapLinks.Add(myLink);
			}
		}
Example #16
0
        public void RemoveLink(ILink link)
        {
            if (link == null)
                throw new ArgumentNullException("link");

            if (!links.Contains(link))
                return;

            links.Remove(link);
        }
Example #17
0
 public ReceiverStmContext(ILink link, IChecksum cheksum, ISequenceGenerator sequenceGenerator,
     int maxMessageDataSize)
 {
     _message = new Message(maxMessageDataSize);
     _reply = new Message(0);
     _link = link;
     _sequence = sequenceGenerator;
     _checksum = cheksum;
     SetState(new MissingSync());
 }
Example #18
0
 /// <summary>
 /// Creates a ResourceObject
 /// </summary>
 public ResourceObject(string type, string id, IDictionary<string, JToken> attributes = null,
     IDictionary<string, IRelationshipObject> relationships = null, ILink selfLink = null, IMetadata metadata = null)
 {
     Type = type;
     Id = id;
     Attributes = attributes ?? new Dictionary<string, JToken>();
     Relationships = relationships ?? new Dictionary<string, IRelationshipObject>();
     SelfLink = selfLink;
     Metadata = metadata;
 }
Example #19
0
        public void AddLink(ILink link)
        {
            if (link == null)
                throw new ArgumentNullException("link");

            if (links.Contains(link))
                return;

            links.Add(link);
        }
		public void SerializeLink(ILink link, SerializationInfo info)
		{
			var myLink = link as Link;
			if (myLink.Source != null)
				info["SourceEmployeeId"] = myLink.Source.GetId();
			if (myLink.Target != null)
				info["TargetEmployeeId"] = myLink.Target.GetId();
			info["IsVisible"] = myLink.IsVisible;
			info["Text"] = myLink.Text;
			info["MainColor"] = myLink.MainColor;
		}
        public HttpRequestMessage Build(ILink link, HttpRequestMessage request)
        {
            request = ApplyChanges(link, request);

            if (NextBuilder != null)
            { 
                request = NextBuilder.Build(link,request);
            }
            return request;
            
        }
Example #22
0
 private LinkDto ConvertToLinkDto(ILink link)
 {
     return new LinkDto
     {
         LinkID = link.LinkId,
         Enabled = link.Enabled,
         LinkUri = link.LinkUri,
         LinkName = link.LinkName,
         LinkTitle = link.LinkTitle
     };
 }
		public bool RemoveLink(ILink link)
		{
			var myLink = link as Link;
			bool result = false;
			if (myLink != null)
			{
				if (myLink.Source != null)
					myLink.Source.ChildrenCount--;
				result = this.mindmapLinks.Remove(myLink);
			}
			return result;
		}
 protected override void InitLink( String input, ILink link )
 {
     try {
         var match = Regex.Match( input, RegExp );
         var address = match.Groups[0].Value;
         var db_name = match.Groups[1].Value;
         var dc_name = match.Groups[2].Value;
         link.Init( address, db_name, dc_name, null );
     } catch ( Exception ex ) {
         Errors.Messages.DisplayError( "DC link parsing: "+ex.Message );
     }
 }
        /// <summary>
        /// Creates a new instance of <see cref="Trigger">Trigger</see> class.
        /// </summary>
        public Trigger()
        {
            _link = null;
            _inputExchangeItem = new TriggerExchangeItem();

            Oatc.OpenMI.Sdk.Backbone.TimeStamp
                start = new TimeStamp( CalendarConverter.Gregorian2ModifiedJulian(new DateTime(1800,1,1)) ),
                end = new TimeStamp( CalendarConverter.Gregorian2ModifiedJulian(new DateTime(2200,1,1)) );
            _timeHorizon = new Oatc.OpenMI.Sdk.Backbone.TimeSpan(start, end);

            _earliestInputTime = end;
        }
Example #26
0
		/// <summary>
		/// Copy constructor
		/// </summary>
		/// <param name="source">The link to copy</param>
		public Link(ILink source)
		{
			SourceComponent = source.SourceComponent;
			SourceElementSet = source.SourceElementSet;
			SourceQuantity = source.SourceQuantity;
			TargetComponent = source.TargetComponent;
			TargetElementSet = source.TargetElementSet;
			TargetQuantity = source.TargetQuantity;
			Description = source.Description;
			ID = source.ID;
			for (int i=0;i<source.DataOperationsCount;i++)
				AddDataOperation(source.GetDataOperation(i));
		}
Example #27
0
 public Task Serialize(ILink link, JsonWriter writer)
 {
     if (link.Metadata == null)
     {
         writer.WriteValue(link.Href);
     }
     else
     {
         writer.WriteStartObject();
         writer.WritePropertyName(HrefKeyName);
         writer.WriteValue(link.Href);
         writer.WritePropertyName(MetaKeyName);
         _metadataFormatter.Serialize(link.Metadata, writer);
         writer.WriteEndObject();
     }
     return Task.FromResult(0);
 }
 public static void WriteToLogFile(Operation op, ILink data, string msg = "")
 {
     now = DateTime.Now;
     if (data != null)
     {
         using (StreamWriter sw = File.AppendText(LogSaveLoc))
         {
             sw.WriteLine("{0} {1} {2} from {3} {4}", now, op, data.VideoTitle, data.VideoUrl, VidSavedLoc);
         }
     }
     else
     {
         using (StreamWriter sw = File.AppendText(LogSaveLoc))
         {
             sw.WriteLine("{0}  {1}  {2}", now, op, msg);
         }
     }
 }
Example #29
0
 protected override void InitLink( String input, ILink link )
 {
     try {
         var match = Regex.Match( input, RegExp );
         var address = match.Groups[0].Value;
         var db_name = match.Groups[1].Value;
         var dc_name = match.Groups[2].Value;
         var rec_hash = match.Groups[3].Value;
         ((RecordLink)link).Init(
             address,
             db_name,
             dc_name,
             rec_hash
         );
     } catch ( Exception ex ) {
         Errors.Messages.DisplayError( "Record link parsing: "+ex.Message );
     }
 }
Example #30
0
        public SenderStmContext(ILink link, IChecksum checksum, ISequenceGenerator sequenceGenerator, int maxMessageDataSize, int timeoutModifier)
        {
            _checksum = checksum;

            _timeout = link.Timeout * timeoutModifier;

            _timer = new Timer(MessageTimeout);

            _link = link;

            _maxMessageDataSize = maxMessageDataSize;
            _message = new Message(_maxMessageDataSize);
            _reply = new Message(0);

            _sequence = sequenceGenerator;

            SetState(new Sending());
        }
Example #31
0
 public IObservable <IEnumerable <T> > RoutesBetween(T source, T target)
 {
     return(Observable.Create <IEnumerable <T> >(observer =>
     {
         List <T> lettersAlreadyUsed = new List <T>();
         foreach (var item in _links.Where(x => x.Source.Equals(source)))
         {
             var list = new List <T>();
             T tempSource = item.Source;
             while (!target.Equals(tempSource))
             {
                 ILink <T> next = _links.Where(x => x.Source.Equals(tempSource) && !lettersAlreadyUsed.Contains(x.Target)).FirstOrDefault();
                 list.Add(tempSource);
                 lettersAlreadyUsed.Add(tempSource);
                 tempSource = next.Target;
             }
             list.Add(tempSource);
             observer.OnNext(list);
         }
         observer.OnCompleted();
         return Disposable.Empty;
     }));
 }
Example #32
0
        /// <inheritdoc/>
        public override void AddLink(ILink link)
        {
            if (!this.Options.HasFlag(SpanOptions.RecordEvents))
            {
                return;
            }

            lock (this.@lock)
            {
                if (this.hasBeenEnded)
                {
                    // logger.log(Level.FINE, "Calling addLink() on an ended Span.");
                    return;
                }

                if (link == null)
                {
                    throw new ArgumentNullException(nameof(link));
                }

                this.InitializedLinks.AddEvent(link);
            }
        }
Example #33
0
        public override void AddLink(ILink link)
        {
            if (!Options.HasFlag(SpanOptions.RECORD_EVENTS))
            {
                return;
            }

            lock (_lock)
            {
                if (hasBeenEnded)
                {
                    // logger.log(Level.FINE, "Calling addLink() on an ended Span.");
                    return;
                }

                if (link == null)
                {
                    throw new ArgumentNullException(nameof(link));
                }

                InitializedLinks.AddEvent(link);
            }
        }
Example #34
0
        static void OnOutcome(ILink link, Message message, Outcome outcome, object state)
        {
            SendTask thisPtr = (SendTask)state;

            thisPtr.timer.Dispose();

            if (outcome.Descriptor.Code == Codec.Accepted.Code)
            {
                thisPtr.TrySetResult(true);
            }
            else if (outcome.Descriptor.Code == Codec.Rejected.Code)
            {
                thisPtr.TrySetException(new AmqpException(((Rejected)outcome).Error));
            }
            else if (outcome.Descriptor.Code == Codec.Released.Code)
            {
                thisPtr.TrySetException(new AmqpException(ErrorCode.MessageReleased, null));
            }
            else
            {
                thisPtr.TrySetException(new AmqpException(ErrorCode.InternalError, outcome.ToString()));
            }
        }
Example #35
0
        bool P_Contains(TComponent component, out ILink <TOwner, TComponent> link)
        {
            component.EnsureNotNull(nameof(component));
            //
            var itemParentLink = component.ParentLink;
            ILink <TOwner, TComponent> itemParentLinkStricted;

            if (itemParentLink == null || (itemParentLinkStricted = itemParentLink as ILink <TOwner, TComponent>) == null)
            {
                link = null;
                return(false);
            }
            else if (P_Contains(itemParentLinkStricted))
            {
                link = itemParentLinkStricted;
                return(true);
            }
            else
            {
                link = null;
                return(false);
            }
        }
Example #36
0
        public void CanFollowAuthorLinkFromBlog()
        {
            // Arrange
            Request blogRequest = Session.Bind(BlogRootPath);

            // Act ...

            // - GET blog
            Resources.Blog blog = blogRequest.Get <Resources.Blog>().Body;

            // - Fetch author link
            ILink authorLink = blog.Links.Select("author");

            // - Follow author link and get author data
            Resources.Author author = authorLink.Follow(Session).Get <Resources.Author>().Body;

            // Assert ...
            Assert.IsNotNull(author);

            // - Check e-mail of author
            Assert.AreEqual("Pete Peterson", author.Name);
            Assert.AreEqual("*****@*****.**", author.EMail);
        }
Example #37
0
        virtual protected GraphLink CreateLink(ILink l, ArrayList nodes)
        {
            GraphNode origin = null, destination = null;

            foreach (GraphNode g in nodes)
            {
                if (g.Node.Equals(l.Origin))
                {
                    origin = g;
                    break;
                }
            }
            foreach (GraphNode g in nodes)
            {
                if (g.Node.Equals(l.Destination))
                {
                    destination = g;
                    break;
                }
            }

            return(new GraphLink(l, origin, destination));
        }
Example #38
0
        private static Comment Deserialize(MetaType type, Comment entity, IDbValueSet source)
        {
            MetaMember member;

            member = type.Members["topic"];
            ILink <Topic> attachment_link = (ILink <Topic>)member.Accessor.GetValue(entity);

            if (attachment_link == null)
            {
                attachment_link = new Link <Topic>();
            }

            attachment_link.Source = Materializer.Single((MetaAssociation)member, source).Load;

            /*if (source.ContainsAny("topic"))
             * {
             *      IValueSet topicValue = source.GetValue<IValueSet>("topic");
             *      attachment_link.Value =
             * }*/
            member.Accessor.SetValue(entity, attachment_link);

            return(entity);
        }
Example #39
0
        public static ILink <TNode> SetElements0D <TNode>(this ILink <TNode> link, List <IElement0D> newElements0D)
            where TNode : INode
        {
            if (newElements0D.Count != 2)
            {
                Reflection.Compute.RecordError("An ILink is defined by 2 nodes.");
                return(null);
            }

            ILink <TNode> clone = link.DeepClone();

            // Default the ILink end if the input is an Point
            if (newElements0D[0] is Point)
            {
                //clone.StartNode = new TNode() { Position = newElements0D[0] as Point };
                clone.StartNode          = Activator.CreateInstance <TNode>();
                clone.StartNode.Position = newElements0D[0] as Point;
            }
            else
            {
                clone.StartNode = (TNode)newElements0D[0];
            }

            // Default the ILink end if the input is an Point
            if (newElements0D[1] is Point)
            {
                //clone.EndNode = new TNode() { Position = newElements0D[1] as Point };
                clone.EndNode          = Activator.CreateInstance <TNode>();
                clone.EndNode.Position = newElements0D[1] as Point;
            }
            else
            {
                clone.EndNode = (TNode)newElements0D[1];
            }

            return(clone);
        }
Example #40
0
        /// <summary>
        /// Получить документ.
        /// </summary>
        /// <param name="comment">HTML.</param>
        /// <param name="baseLink">Базовая ссылка.</param>
        /// <returns>Документ.</returns>
        public IPostDocument ParseHtml(string comment, ILink baseLink)
        {
            var html = _htmlDocumentFactory.Load(comment);
            IList <IPostNode> result = new List <IPostNode>();

            result = html.DocumentNode.ChildNodes.TreeWalk(new ParseContext()
            {
                Nodes = result, BaseLink = baseLink
            })
                     .GetChildren(node => node.ChildNodes)
                     .If(node => node.NodeType == typeof(IHtmlTextNode), (node, res) => AddToResult(res, new TextPostNode()
            {
                Text = WebUtility.HtmlDecode(node.InnerText)
            }), node => null)
                     .If(IsPostLink, AddPostLink, node => null)
                     .If(node => node.Name.EqualsNc("br"), (node, res) => AddToResult(res, new LineBreakPostNode()))
                     .If(node => node.Name.EqualsNc("p"), (node, res) => CreateAttribute(res, PostBasicAttributes.Paragraph))
                     .If(node => node.Name.EqualsNc("em"), (node, res) => CreateAttribute(res, PostBasicAttributes.Italic))
                     .If(node => node.Name.EqualsNc("strong"), (node, res) => CreateAttribute(res, PostBasicAttributes.Bold))
                     .If(node => GetPreformatNode(node) != null, (node, res) => CreateAttribute(res, PostBasicAttributes.Monospace), node => GetPreformatNode(node).ChildNodes)
                     .If(node => CheckSpan(node, "u"), (node, res) => CreateAttribute(res, PostBasicAttributes.Underscore))
                     .If(node => CheckSpan(node, "o"), (node, res) => CreateAttribute(res, PostBasicAttributes.Overscore))
                     .If(node => CheckSpan(node, "spoiler"), (node, res) => CreateAttribute(res, PostBasicAttributes.Spoiler))
                     .If(node => CheckSpan(node, "s"), (node, res) => CreateAttribute(res, PostBasicAttributes.Strikeout))
                     .If(node => node.Name.EqualsNc("sub"), (node, res) => CreateAttribute(res, PostBasicAttributes.Sub))
                     .If(node => node.Name.EqualsNc("sup"), (node, res) => CreateAttribute(res, PostBasicAttributes.Sup))
                     .If(node => CheckSpan(node, "unkfunc"), (node, res) => CreateAttribute(res, PostBasicAttributes.Quote))
                     .If(node => node.Name.EqualsNc("a") && !string.IsNullOrWhiteSpace(node.GetAttributeValue("href", null)), CreateLinkAttrNode)
                     .Else((node, res) => res)
                     .Run()
                     .Nodes;

            return(new PostDocument()
            {
                Nodes = result, UniqueId = Guid.NewGuid()
            });
        }
        public void CanFollowAllAuthorsAndGetAllEMails()
        {
            // Arrange
            HashSet <string> foundEMails = new HashSet <string>();
            Request          blogRequest = Session.Bind(BlogRootPath);

            // Act ...

            // - GET blog
            Response <HtmlDocument> blog = blogRequest.Get <HtmlDocument>();

            // - Extract "post" nodes
            HtmlNodeCollection posts = blog.Body.DocumentNode.SelectNodes(@"//*[@class=""post""]");

            foreach (HtmlNode listPost in posts)
            {
                // - Extract post link, follow and GET the post
                ILink        postLink = listPost.SelectNodes(@".//a[@rel=""self""]").First().Anchor(blog);
                HtmlDocument postItem = postLink.Follow(Session).Get <HtmlDocument>().Body;

                // - Extract author link from post
                ILink authorLink = postItem.DocumentNode.SelectNodes(@".//a[@rel=""author""]").First().Anchor(blog);

                // - Follow author link and get HTML document representing the author
                HtmlDocument author = authorLink.Follow(Session).Get <HtmlDocument>().Body;

                // - Get e-mail of author
                HtmlNode email = author.DocumentNode.SelectNodes(@"//a[@rel=""email""]").First();

                foundEMails.Add(email.Attributes["href"].Value);
            }

            // Assert ...
            Assert.AreEqual(2, foundEMails.Count);
            Assert.IsTrue(foundEMails.Contains("*****@*****.**"));
            Assert.IsTrue(foundEMails.Contains("*****@*****.**"));
        }
        public void CanAddNewBlogItemIncludingImage()
        {
            // Arrange
            Request blogRequest = Session.Bind(BlogRootPath);

            // Act ...

            // - GET blog
            Response <HtmlDocument> blog = blogRequest.Get <HtmlDocument>();

            // - Extract "edit" anchor
            ILink editLink = blog.Body.DocumentNode.SelectNodes(@"//a[@rel=""edit""]").First().Anchor(blog);

            // - GET form describing how to input
            Response <HtmlDocument> createDescriptor = editLink.Follow(Session).Get <HtmlDocument>();

            // - Extract "create" form
            IKeyValueForm form = createDescriptor.Body.DocumentNode.SelectNodes(@"//form[@id=""create""]").First().Form(createDescriptor);

            // - Populate form inputs
            IFile file = new File("..\\..\\data1.gif", "image/gif");

            form.Value("Title", "New item");
            form.Value("Text", "Yaj!");
            form.Value("Image", file);

            // - Submit the form
            HtmlDocument createdBlogItem = form.Bind().Submit <HtmlDocument>().Created();

            // Assert ...
            Assert.IsNotNull(createdBlogItem);
            HtmlNode postTitle   = createdBlogItem.DocumentNode.SelectNodes(@"//*[@class=""post-title""]").First();
            HtmlNode postContent = createdBlogItem.DocumentNode.SelectNodes(@"//*[@class=""post-content""]").First();

            Assert.AreEqual("New item", postTitle.InnerText);
            Assert.AreEqual("Yaj!", postContent.InnerText);
        }
        public static ILinkViewModel Convert(this ILink link)
        {
            if (link == null)
            {
                return(null);
            }

            if (link is LinearPosition linPos)
            {
                return(UpdateViewModel(new LinearPositionViewModel(), linPos));
            }
            else if (link is LinearPneumatic pnmPos)
            {
                return(UpdateViewModel(new LinearPneumaticViewModel(), pnmPos));
            }
            else if (link is RotaryPneumatic pnmRot)
            {
                return(UpdateViewModel(new RotaryPneumaticViewModel(), pnmRot));
            }
            else
            {
                throw new NotImplementedException();
            }
        }
Example #44
0
        private static void TestConsumer(ILink link, CancellationToken cancellation)
        {
            var tcs = new TaskCompletionSource <LinkConsumerAckStrategy>();

            tcs.TrySetResult(LinkConsumerAckStrategy.Ack);

            Console.WriteLine("--- Creating consumer ---");
            using (link.Consumer
                   .Queue(async cfg =>
            {
                var exchange = await cfg.ExchangeDeclarePassive("link.consume");
                var queue = await cfg.QueueDeclare("link.consume");

                await cfg.Bind(queue, exchange);

                return(queue);
            })
                   .AutoAck(false)
                   .PrefetchCount(5)
                   .Serializer(new LinkJsonSerializer())
                   .TypeNameMap(map => map.Set <Msg>("msg").Set <MsgInt>("msg_int").Set <MsgGuid>("msg_guid"))
                   .Handler(msg =>
            {
                Console.WriteLine(
                    "---[ Message ({1}) ]---\n{0}\n---------",
                    JsonConvert.SerializeObject(msg.Body, Formatting.Indented),
                    msg.Body?.GetType()?.Name ?? "None"
                    );

                return(tcs.Task);
            })
                   .Build())
            {
                cancellation.WaitHandle.WaitOne();
            }
        }
Example #45
0
        private static void OnOutcome(ILink sender, global::Amqp.Message message, Outcome outcome, object state)
        {
            var tcs = (TaskCompletionSource <bool>)state;

            if (outcome.Descriptor.Code == MessageSupport.ACCEPTED_INSTANCE.Descriptor.Code)
            {
                tcs.TrySetResult(true);
            }
            else if (outcome.Descriptor.Code == MessageSupport.REJECTED_INSTANCE.Descriptor.Code)
            {
                Rejected rejected = (Rejected)outcome;
                tcs.TrySetException(ExceptionSupport.GetException(rejected.Error, $"Message {message.Properties.GetMessageId()} rejected"));
            }
            else if (outcome.Descriptor.Code == MessageSupport.RELEASED_INSTANCE.Descriptor.Code)
            {
                Error error = new Error(ErrorCode.MessageReleased);
                tcs.TrySetException(ExceptionSupport.GetException(error, $"Message {message.Properties.GetMessageId()} released"));
            }
            else
            {
                Error error = new Error(ErrorCode.InternalError);
                tcs.TrySetException(ExceptionSupport.GetException(error, outcome.ToString()));
            }
        }
        public void WhenBothNormalAndIntlTitleExistsItSelectsInternational()
        {
            // Arrange
            string header1 = @"<http://example.com/TheBook/chapter6>; rel=""previous""; title=""abc""; title*=""UTF-8'de'N%c3%a4chstes%20Kapitel""";
            string header2 = @"<http://example.com/TheBook/chapter6>; rel=""previous""; title*=""UTF-8'de'N%c3%a4chstes%20Kapitel""; title=""abc""";

            // Act
            IList <WebLink> links1 = WebLinkParser.ParseLinks(new Uri("http://example.com"), header1);
            IList <WebLink> links2 = WebLinkParser.ParseLinks(new Uri("http://example.com"), header2);

            // Assert
            Assert.IsNotNull(links1);
            Assert.IsNotNull(links2);
            Assert.AreEqual(1, links1.Count);
            Assert.AreEqual(1, links2.Count);

            ILink l1 = links1[0];

            Assert.AreEqual("Nächstes Kapitel", l1.Title);

            ILink l2 = links2[0];

            Assert.AreEqual("Nächstes Kapitel", l2.Title);
        }
Example #47
0
 public void AddLink(ILink link)
 {
     if (link == null)
     {
         throw new ArgumentNullException("link");
     }
     if (link.From == null)
     {
         throw new ArgumentNullException("link.From");
     }
     if (link.To == null)
     {
         throw new ArgumentNullException("link.To");
     }
     if (!_actions.Contains(link.From))
     {
         AddAction(link.From);
     }
     if (!_actions.Contains(link.To))
     {
         AddAction(link.To);
     }
     _links.Add(link);
 }
Example #48
0
        public void WhenBaseUrlIsNullItHandlesAbsoluteHeadLinks()
        {
            // Arrange
            string       html = @"
<html>
  <head>
    <link rel=""search""
          type=""application/opensearchdescription+xml"" 
          href=""http://example.com""
          title=""Content search"" />
  </head>
</html>";
            HtmlDocument doc  = new HtmlDocument();

            doc.LoadHtml(html);

            // Act
            ILink l1 = doc.Links((Uri)null).Select("search");
            ILink l2 = doc.Links((Response)null).Select("search");
            ILink l3 = doc.DocumentNode.Links((Uri)null).Select("search");
            ILink l4 = doc.DocumentNode.Links((Response)null).Select("search");
            ILink l5 = doc.DocumentNode.SelectNodes("//*").Links((Uri)null).Select("search");
            ILink l6 = doc.DocumentNode.SelectNodes("//*").Links((Response)null).Select("search");
            ILink l7 = doc.DocumentNode.SelectNodes("//link").First().Link((Uri)null);
            ILink l8 = doc.DocumentNode.SelectNodes("//link").First().Link((Response)null);

            // Assert
            Assert.AreEqual("http://example.com/", l1.HRef.AbsoluteUri);
            Assert.AreEqual("http://example.com/", l2.HRef.AbsoluteUri);
            Assert.AreEqual("http://example.com/", l3.HRef.AbsoluteUri);
            Assert.AreEqual("http://example.com/", l4.HRef.AbsoluteUri);
            Assert.AreEqual("http://example.com/", l5.HRef.AbsoluteUri);
            Assert.AreEqual("http://example.com/", l6.HRef.AbsoluteUri);
            Assert.AreEqual("http://example.com/", l7.HRef.AbsoluteUri);
            Assert.AreEqual("http://example.com/", l8.HRef.AbsoluteUri);
        }
        public static Google.Cloud.Trace.V2.Span.Types.Link ToLink(this ILink link)
        {
            var ret = new Google.Cloud.Trace.V2.Span.Types.Link();

            ret.SpanId  = link.Context.SpanId.ToHexString();
            ret.TraceId = link.Context.TraceId.ToHexString();

            if (link.Attributes != null)
            {
                ret.Attributes = new Google.Cloud.Trace.V2.Span.Types.Attributes
                {
                    DroppedAttributesCount = OpenTelemetry.Trace.Config.TraceParams.Default.MaxNumberOfAttributes - link.Attributes.Count,

                    AttributeMap =
                    {
                        link.Attributes.ToDictionary(
                            att => att.Key,
                            att => att.Value.ToAttributeValue()),
                    },
                };
            }

            return(ret);
        }
Example #50
0
        public KeyJoinAppender(ILink <Tuple <List <T1>, List <T2> > > previousLink, string primaryKeyName, string foreignKeyName, string targetCollectionName, JoinOptions joinOptions) : base(previousLink)
        {
            if (previousLink == null)
            {
                throw new ArgumentNullException(nameof(previousLink), $"{nameof(previousLink)} is null.");
            }

            if (string.IsNullOrEmpty(primaryKeyName))
            {
                throw new ArgumentException($"{nameof(primaryKeyName)} is null or empty.", nameof(primaryKeyName));
            }

            if (string.IsNullOrEmpty(foreignKeyName))
            {
                throw new ArgumentException($"{nameof(foreignKeyName)} is null or empty.", nameof(foreignKeyName));
            }

            if (string.IsNullOrEmpty(targetCollectionName))
            {
                throw new ArgumentException($"{nameof(targetCollectionName)} is null or empty.", nameof(targetCollectionName));
            }

            var primaryKeyStub = MetadataCache.GetMetadata(typeof(T1)).Properties[primaryKeyName]; //don't inline this variable.

            m_PrimaryKeyExpression = (p) => (TKey)primaryKeyStub.InvokeGet(p);

            var foreignKeyStub = MetadataCache.GetMetadata(typeof(T1)).Properties[foreignKeyName]; //don't inline this variable.

            m_ForeignKeyExpression = (p) => (TKey)foreignKeyStub.InvokeGet(p);

            var targetPropertyStub = MetadataCache.GetMetadata(typeof(T1)).Properties[targetCollectionName]; //don't inline this variable.

            m_TargetCollectionExpression = (p) => (ICollection <T2>)targetPropertyStub.InvokeGet(p);

            m_JoinOptions = joinOptions;
        }
        protected override HttpRequestMessage ApplyChanges(ILink stdlink, HttpRequestMessage request)
        {
            var link = stdlink as Link;

            if (link != null)
            {
                // if there is a template, then get parameters and try and find property values
                if (link.Template != null)
                {
                    var matchingProps = GetBindingProperties(link)
                                        .Where(p => link.Template.GetParameterNames()
                                               .Any(n => String.Compare(n, p.Key, StringComparison.OrdinalIgnoreCase) == 0))
                                        .ToList();

                    foreach (var prop in matchingProps)
                    {
                        object value        = prop.Value.PropertyInfo.GetValue(link, null);
                        object defaultValue = GetDefault(prop.Value);
                        if (!value.Equals(defaultValue))
                        {
                            link.Template.AddParameter(prop.Key, value);
                        }
                    }
                    link.Target = new Uri(link.Template.Resolve(), UriKind.RelativeOrAbsolute);
                }

                request.Method = link.Method;

                request.Content = link.Content;

                request = ApplyHints(request, link.GetHints());
            }

            request.RequestUri = stdlink.Target;
            return(request);
        }
Example #52
0
        public Tfs.Link FindEquivalentLink(Tfs.WorkItem item, ILink link)
        {
            if (link.BaseType == BaseLinkType.RelatedLink)
            {
                var relatedLink = (IRelatedLink)link;
                return
                    (item.Links.Cast <Tfs.Link>()
                     .OfType <Tfs.RelatedLink>()
                     .SingleOrDefault(
                         rl =>
                         rl.LinkTypeEnd.ImmutableName.Equals(relatedLink.LinkTypeEnd.ImmutableName, StringComparison.OrdinalIgnoreCase) &&
                         rl.RelatedWorkItemId == relatedLink.RelatedWorkItemId));
            }
            if (link.BaseType == BaseLinkType.Hyperlink)
            {
                var hyperlink = (IHyperlink)link;
                return
                    (item.Links.Cast <Tfs.Link>()
                     .OfType <Tfs.Hyperlink>()
                     .SingleOrDefault(hl => hl.Location == hyperlink.Location));
            }

            throw new ArgumentException("Unknown link type", nameof(link));
        }
Example #53
0
        public void Add(int linkId, string name, string title, string uri, bool enabled)
        {
            ILink link = null;

            switch (this.TypeIndent)
            {
            case "1":
                link = new LinkOfArchive(linkId, name, title, uri, enabled);
                break;
            }

            if (link != null)
            {
                foreach (ILink _link in this._links)
                {
                    if (_link.Equal(link))
                    {
                        throw new Exception("已存在重名的链接!");
                    }
                }

                this._links.Add(link);
            }
        }
Example #54
0
        public void CanSelectLinkFromLinkList()
        {
            // Act
            ILink l1a = Links.Select(Link1.RelationType);
            ILink l2a = Links.Select(Link2.RelationType);
            ILink l1b = Links.Select(Link1.RelationType, "text/html");
            ILink l2b = Links.Select(Link2.RelationType, "text/html");
            ILink l3  = Links.Select(Link3.RelationType, "application/atom+xml");
            ILink l4  = Links.Select(Link4.RelationType, "application/atom+xml");

            // Assert
            Assert.IsNotNull(l1a);
            Assert.IsNotNull(l2a);
            Assert.IsNotNull(l1b);
            Assert.IsNotNull(l2b);
            Assert.IsNotNull(l3);
            Assert.IsNotNull(l4);
            Assert.AreEqual(Link1.HRef, l1a.HRef);
            Assert.AreEqual(Link2.HRef, l2a.HRef);
            Assert.AreEqual(Link1.HRef, l1b.HRef);
            Assert.AreEqual(Link2.HRef, l2b.HRef);
            Assert.AreEqual(Link3.HRef, l3.HRef);
            Assert.AreEqual(Link4.HRef, l4.HRef);
        }
Example #55
0
        public ICollection <ILink> GetProects()
        {
            ICollection <ILink> nodes = new Collection <ILink>();

            ILink n1  = factory.Make("Link", "AssemblyNode", "СМТШ.123456.001");
            ILink n2  = factory.Make("Link", "AssemblyNode", "СМТШ.321000.002");
            ILink n3  = factory.Make("Link", "AssemblyNode", "СМТШ.123456.003");
            ILink n4  = factory.Make("Link", "AssemblyNode", "СМТШ.123456.004");
            ILink n5  = factory.Make("Link", "AssemblyNode", "СМТШ.123456.005");
            ILink n6  = factory.Make("Link", "AssemblyNode", "СМТШ.321000.002", -1);
            ILink n7  = factory.Make("Link", "AssemblyNode", "СМТШ.321000.002", 2);
            ILink n8  = factory.Make("Link", "AssemblyNode", "СМТШ.321000.002", -1);
            ILink n9  = factory.Make("Link", "AssemblyNode", "СМТШ.321000.002", -1);
            ILink n10 = factory.Make("Link", "AssemblyNode", "СМТШ.321000.002", -1);
            ILink n11 = factory.Make("Link", "DetailNode", "СМТШ.123456.001");

            n1.AddNode(n7);
            n1.AddNode(n3);
            n7.AddNode(n4);
            n7.AddNode(n11);
            n4.AddNode(n5);
            nodes.Add(n1);
            return(nodes);
        }
Example #56
0
        public KeyJoinAppender(ILink <Tuple <List <T1>, List <T2> > > previousLink, Func <T1, TKey> primaryKeyExpression, Func <T2, TKey> foreignKeyExpression, Func <T1, ICollection <T2> > targetCollectionExpression, JoinOptions joinOptions) : base(previousLink)
        {
            if (previousLink == null)
            {
                throw new ArgumentNullException(nameof(previousLink), $"{nameof(previousLink)} is null.");
            }
            if (primaryKeyExpression == null)
            {
                throw new ArgumentNullException(nameof(primaryKeyExpression), $"{nameof(primaryKeyExpression)} is null.");
            }
            if (foreignKeyExpression == null)
            {
                throw new ArgumentNullException(nameof(foreignKeyExpression), $"{nameof(foreignKeyExpression)} is null.");
            }
            if (targetCollectionExpression == null)
            {
                throw new ArgumentNullException(nameof(targetCollectionExpression), $"{nameof(targetCollectionExpression)} is null.");
            }

            m_ForeignKeyExpression       = foreignKeyExpression;
            m_PrimaryKeyExpression       = primaryKeyExpression;
            m_TargetCollectionExpression = targetCollectionExpression;
            m_JoinOptions = joinOptions;
        }
Example #57
0
 protected virtual void OnSettingParent(ILink <IMetadataTreeStructureComponent, IMetadataTreeNodeInclusion> link)
 {
     link.EnsureNotNull(nameof(link));
     //
 }
Example #58
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Appender{TResult}" /> class.
 /// </summary>
 /// <param name="previousLink">The previous link.</param>
 /// <exception cref="ArgumentNullException">previousLink;previousLink is null.</exception>
 protected Appender(ILink <TIn> previousLink)
 {
     PreviousLink = previousLink ?? throw new ArgumentNullException(nameof(previousLink), $"{nameof(previousLink)} is null.");
     PreviousLink.ExecutionTokenPrepared  += PreviousLink_ExecutionTokenPrepared;
     PreviousLink.ExecutionTokenPreparing += PreviousLink_ExecutionTokenPreparing;
 }
Example #59
0
        /// <summary>
        /// AMQP Link has attached. Signal that protocol stack is ready to send.
        /// </summary>
        /// <param name="_">Which link (ignored).</param>
        /// <param name="__">Peer AMQP Attach (ignored).</param>
        void onAttached(ILink _, Attach __)
        {
            Trace.WriteLine(TraceLevel.Verbose, "Event: OnAttached");

            sendable.Set();
        }
Example #60
0
 public A(ILink destination)
 {
     Destination = destination;
 }