void spawnPipes()
 {
     lastPipes = (Pipe)Instantiate(pipes);
     lastPipes.p = p;
     lastPipes.speed = pipeSpeed;
     lastPipes.transform.position = new Vector3(12,Random.Range(minHeight,maxHeight),0);
 }
Exemple #2
0
        private Pipe displayIndex(Pipe notFound)
        {
            var specialFolders = new[] { ".", ".." };

              return (ctx, next) =>
              {
            // validate path
            var curPath = Path.Combine(_basePath, ctx.Request.Path.Substring(1));
            var fullPath = Path.GetFullPath(curPath);

            if (!Directory.Exists(curPath) || !fullPath.StartsWith(_basePath)) {
              notFound(ctx, next);
              return;
            }

            // generate list of files and folders to display in the index
            var entries = Directory
              .GetFiles(curPath)
              .Concat(Directory.GetDirectories(curPath))
              .Select(path => path.Substring(_basePath.Length));

            if (curPath != _basePath)
              entries = entries.Concat(specialFolders);

            // render the index page
            var html = _template.RenderIndex(curPath, entries.ToArray());
            Static.String(Mime.Text.Html, html)(ctx, next);
              };
        }
		internal BlockingPipe(Pipe pipe)
			: base(pipe.Loop)
		{
			Handle = pipe;
			Stream = pipe;
			Pipe = pipe;
		}
		public ThreadPoolConsumerPool(IServiceBus bus, IObjectBuilder objectBuilder, Pipe eventAggregator, TimeSpan receiveTimeout)
		{
			_objectBuilder = objectBuilder;
			_receiveTimeout = receiveTimeout;
			_eventAggregator = eventAggregator;
			_bus = bus;
		}
Exemple #5
0
        // TODO: Eliminate these AsPipe/AsConitnuable switches... framework-wide
        private void mapCore(string urlPrefix, Func<Pipe, Pipe, Pipe> mapFunc, Pipe cont)
        {
            var err = HttpErrors.MethodNotAllowed();
              var notMethod = _mappings.FindMapping(urlPrefix, ifNotFound: err);

              _mappings[urlPrefix] = mapFunc(cont, notMethod);
        }
 public BasicApiProvider_1_4(IMapper mapper, Pipe eventAggregator)
 {
     Helper.GuardNotNull(mapper);
     Helper.GuardNotNull(eventAggregator);
     _mapper = mapper;
     _eventAggregator = eventAggregator;
 }
        protected virtual Pipe Visit(Pipe pipe)
        {
            if (pipe == null)
                return pipe;

            switch (pipe.SegmentType)
            {
                case PipeSegmentType.End:
                    return VisitEnd((EndSegment)pipe);

                case PipeSegmentType.Filter:
                    return VisitFilter((FilterSegment)pipe);

                case PipeSegmentType.Input:
                    return VisitInput((InputSegment)pipe);

                case PipeSegmentType.MessageConsumer:
                    return VisitMessageConsumer((MessageConsumerSegment)pipe);

                case PipeSegmentType.RecipientList:
                    return VisitRecipientList((RecipientListSegment)pipe);

                case PipeSegmentType.Interceptor:
                    return VisitInterceptor((InterceptorSegment)pipe);

                default:
                    throw new ArgumentException("The pipe node is not a known type: " + pipe.SegmentType,
                                                "pipeline");
            }
        }
 public GdbProtocol(Pipe pipe)
 {
     mPipe = pipe;
     mPipe.PipeReceiveEvent += RecvFired;
     mTimer.Elapsed += ResendTimer;
     mTimer.Start();
 }
Exemple #9
0
        public static void PumpingRound()
        {
            Pump<TextMessage> pump = new Pump<TextMessage>();
            pump.Initialize();
            pump.Interval = 1;
            
            Pipe<TextMessage> p1 = new Pipe<TextMessage>();
            Pipe<TextMessage> p2 = new Pipe<TextMessage>();
            Pipe<TextMessage> p3 = new Pipe<TextMessage>();
            Pipe<TextMessage> p4 = new Pipe<TextMessage>();

            p1.Initialize();
            p2.Initialize();
            p3.Initialize();
            p4.Initialize();

            pump.AddFlow(p1, p2);
            pump.AddFlow(p2, p3);
            pump.AddFlow(p3, p4);
            pump.AddFlow(p4, p1);

            p1.AddInputNotify(new Notify(NotifyOutput));
            p2.AddInputNotify(new Notify(NotifyOutput2));
            p3.AddInputNotify(new Notify(NotifyOutput));
            p4.AddInputNotify(new Notify(NotifyOutput2));
            
            p1.Push(new TextMessage("bla bla"));

            pump.Start();            

            Console.ReadLine();
        }
Exemple #10
0
    public override void GenerateItems(Pipe pipe)
    {
        float start = pipe.pipeSegmentCount + 0.5f;
        //float direction = Random.value < 0.5f ? 1f : -1f;

        //float angleStep = pipe.CurveAngle / pipe.CurveSegmentCount;

        float direction = 0.30f;

        float angleStep = 2.4f;
        for (int i = 0; i < 1; i++)
        {
            if(i>1)
            {

                PipeItem item = Instantiate<PipeItem>(
                itemPrefabs[Random.Range(0, itemPrefabs.Length)].GetComponent<PipeItem>());
                float pipeRotation =
                    (start + i * direction) * 360f / pipe.pipeSegmentCount;
                item.Position(pipe, angleStep, pipeRotation);

            }
            else
            {

                PipeItem item = Instantiate<PipeItem>(
                itemPrefabs[Random.Range(0, itemPrefabs.Length)].GetComponent<PipeItem>());
                float pipeRotation =
                    ((start * 7.5f) + i * direction) * 360f / pipe.pipeSegmentCount;
                item.Position(pipe, angleStep, pipeRotation);

            }

        }
    }
        public void Merge(
            FileInfo           source,
            Pipe<CilDocumentSyntax> compile,
            FileInfo           destination)
        {
            CilSyntax context = CilBackend.CreateCompiler(null);
            context
            .BeginDocument()
                .AssemblyRewrite(source.FullName)
                    .CustomAttribute(
                        context.Types.Import(
                            typeof(DerivedAssemblyMarker)))
                .EndAssembly()
                .Do(compile)
            .EndDocument();

            ((IAssemblyResolverParameters)context).AddSearchDirectory(destination.DirectoryName);

            var writer = context as IAssemblyWriter;
            if (writer == null)
            {
                throw new InvalidOperationException("Backend does not support assembly writing");
            }

            writer.Write(destination.FullName);
        }
        public Graph CreateGraph(Pipe pipe)
        {
            var visitor = new GraphPipelineVisitor();
            visitor.Visit(pipe);

            return CreateGraph(visitor.Vertices, visitor.Edges);
        }
Exemple #13
0
 public void Position(Pipe pipe, float curveRotation, float ringRotation)
 {
     transform.SetParent(pipe.transform, false);
     transform.localRotation = Quaternion.Euler(0f, 0f, -curveRotation);
     rotater.localPosition = new Vector3(0f, pipe.CurveRadius);
     rotater.localRotation = Quaternion.Euler(ringRotation, 0f, 0f);
 }
		public StraightThroughPipelineRunner()
		{
			Pipe consumer = PipeSegment.Consumer<ClaimModified>(m => Interlocked.Increment(ref _count));

			_input = PipeSegment.Input(consumer);

			_message = new ClaimModified();
		}
Exemple #15
0
 // Use this for initialization
 void Start()
 {
     world = pipeSystem.transform.parent;
     rotater = transform.GetChild(0);
     currentPipe = pipeSystem.SetupFirstPipe();
     deltaToRotation = 360f / (2f * Mathf.PI * currentPipe.CurveRadius);
     SetupCurrentPipe();
 }
Exemple #16
0
        public static IServer Connect(this IContainer container,
            string host, int port, Pipe pipes, params IService[] services)
        {
            var broker = container.BuildServicesBroker(services);
              var handler = container.BuildRequestHandler(pipes, broker);

              return container.BuildServer(host, port, handler);
        }
Exemple #17
0
        public void Setup()
        {
            Input = PipeSegment.Input(PipeSegment.End<object>());
            BeforeCalled = new ManualResetEvent(false);
            AfterCalled = new ManualResetEvent(false);

            EstablishContext();
        }
Exemple #18
0
        public void TimeoutTest()
        {
            var pipe = new Pipe {OutputStream = {ReadTimeout = 0}};
            Assert.Throws<TimeoutException>(() => pipe.OutputStream.ReadByte());

            pipe.WriteText(new string('a', 2048));
            Assert.AreEqual(new string('a', 2048), pipe.ReadTextAsync(2048).Result);
        }
Exemple #19
0
        public void Bind(Pipe pipe)
        {
            base.Visit(pipe);

            if (!_bound)
                throw new PipelineException("Could not bind pipe: " + _segment.SegmentType + "(" + _segment.MessageType + ")");

            pipe.Send(new SubscriberAdded {MessageType = _messageType});
        }
Exemple #20
0
        public void Second_example()
        {
            _eventAggregator = PipeSegment.Input(PipeSegment.End());

            _scope = _eventAggregator.NewSubscriptionScope();
            _scope.Subscribe<CustomerChanged>(message => Trace.WriteLine("Customer changed: " + message.CustomerName));

            new TracePipeVisitor().Trace(_eventAggregator);
        }
Exemple #21
0
        public virtual RequestHandler BuildRequestHandler(Pipe pipes,
            IServicesBroker servicesBroker)
        {
            Assert.ArgumentsNotNull(() => pipes, () => servicesBroker);

              return (request, response) => pipes(
            BuildContext(request, response, BuildStore(), servicesBroker),
            Pipes.End);
        }
Exemple #22
0
 public void Disconnect(Pipe pipe)
 {
     if(Pipe != pipe)
     {
         Debug.LogWarning("Tried to disconnect unconnected pipe");
         return;
     }
     Pipe = null;
 }
 public void ConnectToNotListeningFile()
 {
     Pipe pipe = new Pipe();
     pipe.Connect("NOT_EXISTING", (e) => {
         Assert.IsNotNull(e);
         Assert.AreEqual(e.GetType(), typeof(System.IO.FileNotFoundException));
     });
     Loop.Default.Run();
 }
Exemple #24
0
		public void ConnectToNotListeningFile()
		{
			Pipe pipe = new Pipe();
			pipe.Connect("NOT_EXISTING", (e) => {
				Assert.NotNull(e);
				Assert.IsType<System.IO.FileNotFoundException>(e);
			});
			Loop.Default.Run();
		}
Exemple #25
0
 private Pipe indexCheck(Pipe onFolder, Pipe onFile)
 {
     return (ctx, next) =>
       {
     var path = mapPath(ctx.Request.Path);
     (string.IsNullOrEmpty(path) || Directory.Exists(path) ? onFolder : onFile)
       (ctx, next);
       };
 }
Exemple #26
0
 public void Connect(Pipe pipe)
 {
     if(Pipe != null)
     {
         Debug.LogWarning("Tried to connect pipe to already connected port");
         return;
     }
     Pipe = pipe;
 }
Exemple #27
0
 public void TestWriteTimeout()
 {
     var pipe = new Pipe {InputStream = {WriteTimeout = 0}};
     pipe.SetFixedLength();
     pipe.WriteText(new string('a', 2*Pipe.ByteBufferSize));
     var asyncWrite = pipe.InputStream.WriteAsync(new byte[1], 0, 1);
     Assert.AreEqual(true, asyncWrite.ContinueWith(_ => { }).Wait(TimeSpan.FromSeconds(.01)));
     Assert.AreEqual(true, asyncWrite.IsFaulted);
     Assert.IsInstanceOf<TimeoutException>(asyncWrite.Exception.InnerException);
 }
        public Signal(Vector3 source, Vector3 target)
        {
            this.source = source;
            this.target = target;

            pipe = new Pipe(source, source, 0.5f, 0.1f, 1);
            pipe.Color = Color.Khaki;

            shift();
        }
        public void Setup()
        {
            _pipe = PipeSegment.Input(PipeSegment.End<object>());
            _subscriptionScope = _pipe.NewSubscriptionScope();

            _called = new ManualResetEvent(false);
            _subscriptionScope.Subscribe<ClaimModified>(x => _called.Set());

            EstablishContext();
        }
        public void verify_unary_functor_behavior()
        {
            var func = new Pipe<int, string>(a => a.ToString());

            var output = func.fmap(new[] {1, 2}).ToList();

            Assert.That(output.Count(), Is.EqualTo(2));
            Assert.That(output[0], Is.EqualTo("1"));
            Assert.That(output[1], Is.EqualTo("2"));
        }
Exemple #31
0
        async Task ISendTransport.Send <T>(T message, IPipe <SendContext <T> > pipe, CancellationToken cancellationToken)
        {
            if (IsStopped)
            {
                throw new TransportUnavailableException($"The send transport is stopped: {_entityName}");
            }

            IPipe <ClientContext> modelPipe = Pipe.New <ClientContext>(p =>
            {
                p.UseFilter(_filter);

                p.UseExecuteAsync(async clientContext =>
                {
                    var sendContext = new TransportAmazonSqsSendContext <T>(message, cancellationToken);
                    try
                    {
                        await pipe.Send(sendContext).ConfigureAwait(false);

                        var transportMessage = clientContext.CreateSendRequest(_entityName, sendContext.Body);

                        transportMessage.MessageAttributes.Set(sendContext.Headers);

                        if (!string.IsNullOrEmpty(sendContext.DeduplicationId))
                        {
                            transportMessage.MessageDeduplicationId = sendContext.DeduplicationId;
                        }

                        if (!string.IsNullOrEmpty(sendContext.GroupId))
                        {
                            transportMessage.MessageGroupId = sendContext.GroupId;
                        }

                        if (sendContext.DelaySeconds.HasValue)
                        {
                            transportMessage.DelaySeconds = sendContext.DelaySeconds.Value;
                        }

                        transportMessage.MessageAttributes.Set("Content-Type", sendContext.ContentType.MediaType);
                        transportMessage.MessageAttributes.Set(nameof(sendContext.MessageId), sendContext.MessageId);
                        transportMessage.MessageAttributes.Set(nameof(sendContext.CorrelationId), sendContext.CorrelationId);
                        transportMessage.MessageAttributes.Set(nameof(sendContext.TimeToLive), sendContext.TimeToLive);

                        await _observers.PreSend(sendContext).ConfigureAwait(false);

                        await clientContext.SendMessage(transportMessage, sendContext.CancellationToken).ConfigureAwait(false);

                        sendContext.LogSent();

                        await _observers.PostSend(sendContext).ConfigureAwait(false);
                    }
                    catch (Exception ex)
                    {
                        sendContext.LogFaulted(ex);

                        await _observers.SendFault(sendContext, ex).ConfigureAwait(false);

                        throw;
                    }
                });
            });

            await _clientSource.Send(modelPipe, cancellationToken).ConfigureAwait(false);
        }
Exemple #32
0
        public void RotateTest()
        {
            Part p = new Pipe(Connector.None, Connector.Single, Connector.Double, Connector.Universal);

            //the ctor connectors are top, right, bottom, left in that order
            //the default rotation is towards top
            Assert.Equal(Connector.None, p.GetConnector(Direction.Top));
            Assert.Equal(Connector.Single, p.GetConnector(Direction.Right));
            Assert.Equal(Connector.Double, p.GetConnector(Direction.Bottom));
            Assert.Equal(Connector.Universal, p.GetConnector(Direction.Left));

            Assert.Equal(Direction.Top, p.Rotation);

            //the supplied int to rotate with is either +1 for +90° or -1 for -90°
            for (int i = -5; i <= 5; ++i)
            {
                if (i != -1 && i != 1)
                {
                    Assert.Throws <ArgumentOutOfRangeException>(() => p.Rotate(i));
                }
            }

            //rotate 90° to the left
            p.Rotate(1);
            Assert.Equal(Connector.Universal, p.GetConnector(Direction.Top));
            Assert.Equal(Connector.None, p.GetConnector(Direction.Right));
            Assert.Equal(Connector.Single, p.GetConnector(Direction.Bottom));
            Assert.Equal(Connector.Double, p.GetConnector(Direction.Left));

            Assert.Equal(Direction.Right, p.Rotation);

            //rotate another 90° to the left
            p.Rotate(1);
            Assert.Equal(Connector.Double, p.GetConnector(Direction.Top));
            Assert.Equal(Connector.Universal, p.GetConnector(Direction.Right));
            Assert.Equal(Connector.None, p.GetConnector(Direction.Bottom));
            Assert.Equal(Connector.Single, p.GetConnector(Direction.Left));

            Assert.Equal(Direction.Bottom, p.Rotation);

            //rotate 2 * 90° to the left to get the original layout
            p.Rotate(1);
            Assert.Equal(Connector.Single, p.GetConnector(Direction.Top));
            Assert.Equal(Connector.Double, p.GetConnector(Direction.Right));
            Assert.Equal(Connector.Universal, p.GetConnector(Direction.Bottom));
            Assert.Equal(Connector.None, p.GetConnector(Direction.Left));

            Assert.Equal(Direction.Left, p.Rotation);

            p.Rotate(1);
            Assert.Equal(Connector.None, p.GetConnector(Direction.Top));
            Assert.Equal(Connector.Single, p.GetConnector(Direction.Right));
            Assert.Equal(Connector.Double, p.GetConnector(Direction.Bottom));
            Assert.Equal(Connector.Universal, p.GetConnector(Direction.Left));

            Assert.Equal(Direction.Top, p.Rotation);

            //rotate 4 * 90° to the right
            p.Rotate(-1);
            Assert.Equal(Connector.Single, p.GetConnector(Direction.Top));
            Assert.Equal(Connector.Double, p.GetConnector(Direction.Right));
            Assert.Equal(Connector.Universal, p.GetConnector(Direction.Bottom));
            Assert.Equal(Connector.None, p.GetConnector(Direction.Left));

            Assert.Equal(Direction.Left, p.Rotation);

            p.Rotate(-1);
            Assert.Equal(Connector.Double, p.GetConnector(Direction.Top));
            Assert.Equal(Connector.Universal, p.GetConnector(Direction.Right));
            Assert.Equal(Connector.None, p.GetConnector(Direction.Bottom));
            Assert.Equal(Connector.Single, p.GetConnector(Direction.Left));

            Assert.Equal(Direction.Bottom, p.Rotation);

            p.Rotate(-1);
            Assert.Equal(Connector.Universal, p.GetConnector(Direction.Top));
            Assert.Equal(Connector.None, p.GetConnector(Direction.Right));
            Assert.Equal(Connector.Single, p.GetConnector(Direction.Bottom));
            Assert.Equal(Connector.Double, p.GetConnector(Direction.Left));

            Assert.Equal(Direction.Right, p.Rotation);

            p.Rotate(-1);
            Assert.Equal(Connector.None, p.GetConnector(Direction.Top));
            Assert.Equal(Connector.Single, p.GetConnector(Direction.Right));
            Assert.Equal(Connector.Double, p.GetConnector(Direction.Bottom));
            Assert.Equal(Connector.Universal, p.GetConnector(Direction.Left));

            Assert.Equal(Direction.Top, p.Rotation);
        }
Exemple #33
0
        /***************************************************/

        public static Pipe Clone(this Pipe surface)
        {
            return(new Pipe {
                Centreline = surface.Centreline.IClone(), Radius = surface.Radius, Capped = surface.Capped
            });
        }
Exemple #34
0
 public Outpipe([NotNull] Pipe pipe, bool active)
 {
     Pipe   = pipe;
     Active = active;
 }
    private Http2FrameWriter CreateFrameWriter(Pipe pipe)
    {
        var serviceContext = TestContextFactory.CreateServiceContext(new KestrelServerOptions());

        return(new Http2FrameWriter(pipe.Writer, null, null, 1, null, null, null, _dirtyMemoryPool, serviceContext));
    }
        protected virtual void SetPipeReaderOptions(MemoryPool <byte>?pool = null, int bufferSize = -1)
        {
            PipeOptions options = new PipeOptions(pool, readerScheduler: PipeScheduler.Inline, useSynchronizationContext: false, minimumSegmentSize: bufferSize);

            Pipe = new Pipe(options);
        }
Exemple #37
0
 public async Task CopyToAsyncThrowsTaskCanceledExceptionForAlreadyCancelledToken()
 {
     var pipe = new Pipe(s_testOptions);
     await Assert.ThrowsAsync <TaskCanceledException>(() => pipe.Reader.CopyToAsync(new MemoryStream(), new CancellationToken(true)));
 }
 public PipelineReaderWriterFacts()
 {
     _pool = new TestMemoryPool();
     _pipe = new Pipe(new PipeOptions(_pool));
 }
Exemple #39
0
        List <double> PopulateData(Pipe pipe, int position)
        {
            int           qi  = 1;
            var           su  = SimObject.GetFlowsheet().FlowsheetOptions.SelectedUnitSystem;
            List <double> vec = new List <double>();

            switch (position)
            {
            case 0:     //distance

                double comp_ant = 0.0f;
                foreach (var sec in pipe.Profile.Sections.Values)
                {
                    for (qi = 1; qi == 1; qi++)
                    {
                        foreach (var res in sec.Resultados)
                        {
                            vec.Add(cv.ConvertFromSI(su.distance, comp_ant));
                            comp_ant += sec.Comprimento / sec.Incrementos;
                        }
                    }
                }
                break;

            case 1:     //elevation

                foreach (var sec in pipe.Profile.Sections.Values)
                {
                    for (qi = 1; qi == 1; qi++)
                    {
                        foreach (var res in sec.Resultados)
                        {
                            vec.Add(Math.Atan(sec.Elevacao / Math.Pow(Math.Pow(sec.Comprimento, 2) - Math.Pow(sec.Elevacao, 2), 0.5) * 180 / Math.PI));
                        }
                    }
                }
                break;

            case 2:     //pressure

                foreach (var sec in pipe.Profile.Sections.Values)
                {
                    for (qi = 1; qi == 1; qi++)
                    {
                        foreach (var res in sec.Resultados)
                        {
                            vec.Add(cv.ConvertFromSI(su.pressure, res.PressaoInicial.GetValueOrDefault()));
                        }
                    }
                }
                break;

            case 3:     //temperaturee

                foreach (var sec in pipe.Profile.Sections.Values)
                {
                    for (qi = 1; qi == 1; qi++)
                    {
                        foreach (var res in sec.Resultados)
                        {
                            vec.Add(cv.ConvertFromSI(su.temperature, res.TemperaturaInicial.GetValueOrDefault()));
                        }
                    }
                }
                break;

            case 4:     //vel liqe

                foreach (var sec in pipe.Profile.Sections.Values)
                {
                    for (qi = 1; qi == 1; qi++)
                    {
                        foreach (var res in sec.Resultados)
                        {
                            vec.Add(cv.ConvertFromSI(su.velocity, res.LiqVel.GetValueOrDefault()));
                        }
                    }
                }
                break;

            case 5:     //vel vape

                foreach (var sec in pipe.Profile.Sections.Values)
                {
                    for (qi = 1; qi == 1; qi++)
                    {
                        foreach (var res in sec.Resultados)
                        {
                            vec.Add(cv.ConvertFromSI(su.velocity, res.VapVel.GetValueOrDefault()));
                        }
                    }
                }
                break;

            case 6:     //heatflowe

                foreach (var sec in pipe.Profile.Sections.Values)
                {
                    for (qi = 1; qi == 1; qi++)
                    {
                        foreach (var res in sec.Resultados)
                        {
                            vec.Add(cv.ConvertFromSI(su.heatflow, res.CalorTransferido.GetValueOrDefault()));
                        }
                    }
                }
                break;

            case 7:     //liqholde

                foreach (var sec in pipe.Profile.Sections.Values)
                {
                    for (qi = 1; qi == 1; qi++)
                    {
                        foreach (var res in sec.Resultados)
                        {
                            vec.Add(res.HoldupDeLiquido.GetValueOrDefault());
                        }
                    }
                }
                break;

            case 8:     //OHTCe

                foreach (var sec in pipe.Profile.Sections.Values)
                {
                    for (qi = 1; qi == 1; qi++)
                    {
                        foreach (var res in sec.Resultados)
                        {
                            vec.Add(cv.ConvertFromSI(su.heat_transf_coeff, res.HTC.GetValueOrDefault()));
                        }
                    }
                }
                break;

            case 9:     //IHTCC

                foreach (var sec in pipe.Profile.Sections.Values)
                {
                    for (qi = 1; qi == 1; qi++)
                    {
                        foreach (var res in sec.Resultados)
                        {
                            vec.Add(cv.ConvertFromSI(su.heat_transf_coeff, res.HTC_internal));
                        }
                    }
                }
                break;

            case 10:     //IHTC

                foreach (var sec in pipe.Profile.Sections.Values)
                {
                    for (qi = 1; qi == 1; qi++)
                    {
                        foreach (var res in sec.Resultados)
                        {
                            vec.Add(cv.ConvertFromSI(su.heat_transf_coeff, res.HTC_pipewall));
                        }
                    }
                }
                break;

            case 11:     //IHTC

                foreach (var sec in pipe.Profile.Sections.Values)
                {
                    for (qi = 1; qi == 1; qi++)
                    {
                        foreach (var res in sec.Resultados)
                        {
                            vec.Add(cv.ConvertFromSI(su.heat_transf_coeff, res.HTC_insulation));
                        }
                    }
                }
                break;

            case 12:     //EHTC

                foreach (var sec in pipe.Profile.Sections.Values)
                {
                    for (qi = 1; qi == 1; qi++)
                    {
                        foreach (var res in sec.Resultados)
                        {
                            vec.Add(cv.ConvertFromSI(su.heat_transf_coeff, res.HTC_external));
                        }
                    }
                }
                break;
            }
            return(vec);
        }
 public async Task CopyToAsyncThrowsTaskCanceledExceptionForAlreadyCancelledToken()
 {
     var pipe = new Pipe();
     await Assert.ThrowsAsync <TaskCanceledException>(() => new MemoryStream().CopyToAsync(pipe.Writer, new CancellationToken(true)));
 }
Exemple #41
0
 protected override void XWriteActivated(Pipe pipe)
 {
     m_distribution.Activated(pipe);
 }
Exemple #42
0
        private bool IdentifyPeer([NotNull] Pipe pipe)
        {
            byte[] identity;

            if (this.m_options.RawSocket)
            {
                // Always assign identity for raw-socket
                identity = new byte[5];
                byte[] result = BitConverter.GetBytes(this.m_nextPeerId++);
                Buffer.BlockCopy(result, 0, identity, 1, 4);
            }
            else
            {
                // Pick up handshake cases and also case where next identity is set

                Msg msg = new Msg();
                msg.InitEmpty();

                bool ok = pipe.Read(ref msg);

                if (!ok)
                {
                    return(false);
                }

                if (msg.Size == 0)
                {
                    // Fall back on the auto-generation
                    identity = new byte[5];

                    byte[] result = BitConverter.GetBytes(this.m_nextPeerId++);

                    Buffer.BlockCopy(result, 0, identity, 1, 4);

                    msg.Close();
                }
                else
                {
                    identity = msg.CloneData();
                    msg.Close();

                    Outpipe existPipe;

                    if (this.m_outpipes.TryGetValue(identity, out existPipe))
                    {
                        if (!this.m_handover)
                        {
                            // Ignore peers with duplicate ID.
                            return(false);
                        }

                        //  We will allow the new connection to take over this
                        //  identity. Temporarily assign a new identity to the
                        //  existing pipe so we can terminate it asynchronously.
                        byte[] newIdentity = new byte[5];
                        byte[] result      = BitConverter.GetBytes(this.m_nextPeerId++);
                        Buffer.BlockCopy(result, 0, newIdentity, 1, 4);
                        existPipe.Pipe.Identity = newIdentity;
                        this.m_outpipes.Add(newIdentity, existPipe);

                        //  Remove the existing identity entry to allow the new
                        //  connection to take the identity.
                        this.m_outpipes.Remove(identity);

                        if (existPipe.Pipe == this.m_currentIn)
                        {
                            this.m_closingCurrentIn = true;
                        }
                        else
                        {
                            existPipe.Pipe.Terminate(true);
                        }
                    }
                }
            }

            pipe.Identity = identity;
            // Add the record into output pipes lookup table
            Outpipe outpipe = new Outpipe(pipe, true);

            this.m_outpipes.Add(identity, outpipe);

            return(true);
        }
            public async Task Should_not_invoke_post_sent_on_exception()
            {
                var observer = new SendObserver();

                using (InputQueueSendEndpoint.ConnectSendObserver(observer))
                {
                    Assert.That(
                        async() => await InputQueueSendEndpoint.Send(new PingMessage(), Pipe.Execute <SendContext>(x => x.Serializer = null)),
                        Throws.TypeOf <SerializationException>());

                    await observer.SendFaulted;

                    observer.PostSent.Status.ShouldBe(TaskStatus.WaitingForActivation);
                }
            }
Exemple #44
0
 public Outpipe([NotNull] Pipe pipe, bool active)
 {
     this.Pipe   = pipe;
     this.Active = active;
 }
Exemple #45
0
 internal static void Deconstruct(this Pipe pipe, out PipeReader reader, out PipeWriter writer)
 {
     reader = pipe.Reader;
     writer = pipe.Writer;
 }
Exemple #46
0
        /// <summary>
        ///     Set the specified option on this socket.
        /// </summary>
        /// <param name="option">which option to set</param>
        /// <param name="optionValue">the value to set the option to</param>
        /// <returns><c>true</c> if successful</returns>
        /// <exception cref="InvalidException">optionValue must be a byte-array.</exception>
        protected override bool XSetSocketOption(ZmqSocketOption option, object optionValue)
        {
            switch (option)
            {
            case ZmqSocketOption.XpubVerbose:
            {
                this.m_verbose = (bool)optionValue;
                return(true);
            }

            case ZmqSocketOption.XPublisherManual:
            {
                this.m_manual = (bool)optionValue;
                return(true);
            }

            case ZmqSocketOption.XPublisherBroadcast:
            {
                this.m_broadcastEnabled = (bool)optionValue;
                return(true);
            }

            case ZmqSocketOption.Identity:
            {
                if (this.m_manual && this.m_lastPipe != null)
                {
                    byte[] val;

                    if (optionValue is string)
                    {
                        val = Encoding.ASCII.GetBytes((string)optionValue);
                    }
                    else if (optionValue is byte[])
                    {
                        val = (byte[])optionValue;
                    }
                    else
                    {
                        throw new InvalidException($"In XPub.XSetSocketOption(Identity, {optionValue?.ToString() ?? "null"}) optionValue must be a string or byte-array.");
                    }

                    if (val.Length == 0 || val.Length > 255)
                    {
                        throw new InvalidException($"In XPub.XSetSocketOption(Identity,) optionValue yielded a byte-array of length {val.Length}, should be 1..255.");
                    }

                    this.m_lastPipe.Identity = val;
                    this.m_options.Identity  = val;
                }

                return(true);
            }

            case ZmqSocketOption.Subscribe:
            {
                if (this.m_manual && this.m_lastPipe != null)
                {
                    byte[] subscription = optionValue as byte[] ?? Encoding.ASCII.GetBytes((string)optionValue);
                    this.m_subscriptions.Add(subscription, 0, subscription.Length, this.m_lastPipe);
                    this.m_lastPipe = null;
                    return(true);
                }

                break;
            }

            case ZmqSocketOption.Unsubscribe:
            {
                if (this.m_manual && this.m_lastPipe != null)
                {
                    byte[] subscription = optionValue as byte[] ?? Encoding.ASCII.GetBytes((string)optionValue);
                    this.m_subscriptions.Remove(subscription, 0, subscription.Length, this.m_lastPipe);
                    this.m_lastPipe = null;
                    return(true);
                }

                break;
            }

            case ZmqSocketOption.XPublisherWelcomeMessage:
            {
                this.m_welcomeMessage.Close();

                if (optionValue != null)
                {
                    byte[] bytes = optionValue as byte[];
                    if (bytes == null)
                    {
                        throw new InvalidException($"In XPub.XSetSocketOption({option},{optionValue}), optionValue must be a byte-array.");
                    }

                    byte[] welcomeBytes = new byte[bytes.Length];
                    bytes.CopyTo(welcomeBytes, 0);
                    this.m_welcomeMessage.InitGC(welcomeBytes, welcomeBytes.Length);
                }
                else
                {
                    this.m_welcomeMessage.InitEmpty();
                }

                return(true);
            }
            }

            return(false);
        }
            public async Task Should_invoke_the_exception_after_send_failure()
            {
                var observer = new SendObserver();

                using (InputQueueSendEndpoint.ConnectSendObserver(observer))
                {
                    Assert.That(
                        async() => await InputQueueSendEndpoint.Send(new PingMessage(), Pipe.Execute <SendContext>(x => x.Serializer = null)),
                        Throws.TypeOf <SerializationException>());

                    await observer.SendFaulted;
                }
            }
        /// <summary>
        /// Called once before ProcessRecord(). Internally it calls
        /// BeginProcessing() of the InternalCommand.
        /// </summary>
        /// <exception cref="PipelineStoppedException">
        /// a terminating error occurred, or the pipeline was otherwise stopped
        /// </exception>
        internal virtual void DoBegin()
        {
            // Note that DoPrepare() and DoBegin() should NOT be combined.
            // Reason: Encoding of commandline parameters happen as part
            // of DoPrepare(). If they are combined, the first command's
            // DoBegin() will be called before the next command's
            // DoPrepare(). Since BeginProcessing() can write objects
            // to the downstream commandlet, it will end up calling
            // DoExecute() (from Pipe.Add()) before DoPrepare.
            if (!RanBeginAlready)
            {
                RanBeginAlready = true;
                Pipe oldErrorOutputPipe = _context.ShellFunctionErrorOutputPipe;
                CommandProcessorBase oldCurrentCommandProcessor = _context.CurrentCommandProcessor;
                try
                {
                    //
                    // On V1 the output pipe was redirected to the command's output pipe only when it
                    // was already redirected. This is the original comment explaining this behaviour:
                    //
                    //      NTRAID#Windows Out of Band Releases-926183-2005-12-15
                    //      MonadTestHarness has a bad dependency on an artifact of the current implementation
                    //      The following code only redirects the output pipe if it's already redirected
                    //      to preserve the artifact. The test suites need to be fixed and then this
                    //      the check can be removed and the assignment always done.
                    //
                    // However, this makes the hosting APIs behave differently than commands executed
                    // from the command-line host (for example, see bugs Win7:415915 and Win7:108670).
                    // The RedirectShellErrorOutputPipe flag is used by the V2 hosting API to force the
                    // redirection.
                    //
                    if (RedirectShellErrorOutputPipe || _context.ShellFunctionErrorOutputPipe is not null)
                    {
                        _context.ShellFunctionErrorOutputPipe = commandRuntime.ErrorOutputPipe;
                    }

                    _context.CurrentCommandProcessor = this;
                    SetCurrentScopeToExecutionScope();

                    using (commandRuntime.AllowThisCommandToWrite(true))
                        using (ParameterBinderBase.bindingTracer.TraceScope("CALLING BeginProcessing"))
                        {
                            if (Context._debuggingMode > 0 && Command is not PSScriptCmdlet)
                            {
                                Context.Debugger.CheckCommand(Command.MyInvocation);
                            }

                            Command.DoBeginProcessing();
                        }
                }
                catch (Exception e)
                {
                    // This cmdlet threw an exception, so
                    // wrap it and bubble it up.
                    throw ManageInvocationException(e);
                }
                finally
                {
                    _context.ShellFunctionErrorOutputPipe = oldErrorOutputPipe;
                    _context.CurrentCommandProcessor      = oldCurrentCommandProcessor;
                    RestorePreviousScope();
                }
            }
        }
 public ReadAtLeastAsyncTests()
 {
     Pipe = new Pipe(s_testOptions);
 }
Exemple #50
0
        /// <summary>
        /// Transmit the given message. The <c>Send</c> method calls this to do the actual sending.
        /// </summary>
        /// <param name="msg">the message to transmit</param>
        /// <returns><c>true</c> if the message was sent successfully</returns>
        /// <exception cref="HostUnreachableException">The receiving host must be identifiable.</exception>
        protected override bool XSend(ref Msg msg)
        {
            // If this is the first part of the message it's the ID of the
            // peer to send the message to.
            if (m_sendingState == State.RoutingId)
            {
                Debug.Assert(m_currentOut == null);

                // If we have malformed message (prefix with no subsequent message)
                // then just silently ignore it.
                if (msg.HasMore)
                {
                    // Find the pipe associated with the routingId stored in the prefix.
                    var routingId = BitConverter.ToUInt32(msg.UnsafeToArray(), 0);

                    if (m_outpipes.TryGetValue(routingId, out Outpipe op))
                    {
                        m_currentOut = op.Pipe;
                        if (!m_currentOut.CheckWrite())
                        {
                            op.Active    = false;
                            m_currentOut = null;

                            if (!op.Pipe.Active)
                            {
                                throw new HostUnreachableException("In Peer.XSend");
                            }

                            return(false);
                        }
                    }
                    else
                    {
                        throw new HostUnreachableException("In Peer.XSend");
                    }

                    m_sendingState = State.Data;
                }

                // Detach the message from the data buffer.
                msg.Close();
                msg.InitEmpty();

                return(true);
            }

            m_sendingState = State.RoutingId;

            //  Peer sockets do not allow multipart data (ZMQ_SNDMORE)
            if (msg.HasMore)
            {
                throw new InvalidException();
            }

            // Push the message into the pipe. If there's no out pipe, just drop it.
            if (m_currentOut != null)
            {
                bool ok = m_currentOut.Write(ref msg);

                if (ok)
                {
                    m_currentOut.Flush();
                }

                m_currentOut = null;
            }
            else
            {
                msg.Close();
            }

            // Detach the message from the data buffer.
            msg.InitEmpty();

            return(true);
        }
Exemple #51
0
 public PipelineReaderWriterFacts()
 {
     _pool = new TestMemoryPool();
     _pipe = new Pipe(new PipeOptions(_pool, readerScheduler: PipeScheduler.Inline, writerScheduler: PipeScheduler.Inline, useSynchronizationContext: false));
 }
Exemple #52
0
 public AnyExistingSagaPolicy(IPipe <ConsumeContext <TMessage> > missingPipe = null)
 {
     _missingPipe = missingPipe ?? Pipe.Empty <ConsumeContext <TMessage> >();
 }
Exemple #53
0
 public Pipe Clone(Pipe pipe)
 {
     return(base.Visit(pipe));
 }
Exemple #54
0
        protected void InitializeContext()
        {
            // create a memory barrier between initialize and disconnect to prevent a possible
            // NullRef with disconnect being called before these fields have been written
            // disconnect aquires this lock as well
            lock (_abortLock)
            {
                _thisHandle = GCHandle.Alloc(this);

                Method = GetVerb();

                RawTarget = GetRawUrl();
                // TODO version is slow.
                HttpVersion = GetVersion();
                Scheme      = SslStatus != SslStatus.Insecure ? Constants.HttpsScheme : Constants.HttpScheme;
                KnownMethod = VerbId;
                StatusCode  = 200;

                var originalPath = GetOriginalPath();

                if (KnownMethod == HttpApiTypes.HTTP_VERB.HttpVerbOPTIONS && string.Equals(RawTarget, "*", StringComparison.Ordinal))
                {
                    PathBase = string.Empty;
                    Path     = string.Empty;
                }
                else
                {
                    // Path and pathbase are unescaped by RequestUriBuilder
                    // The UsePathBase middleware will modify the pathbase and path correctly
                    PathBase = string.Empty;
                    Path     = originalPath;
                }

                var cookedUrl = GetCookedUrl();
                QueryString = cookedUrl.GetQueryString() ?? string.Empty;

                RequestHeaders      = new RequestHeaders(this);
                HttpResponseHeaders = new HeaderCollection();
                ResponseHeaders     = HttpResponseHeaders;

                if (_options.ForwardWindowsAuthentication)
                {
                    WindowsUser = GetWindowsPrincipal();
                    if (_options.AutomaticAuthentication)
                    {
                        User = WindowsUser;
                    }
                }

                MaxRequestBodySize = _options.MaxRequestBodySize;

                ResetFeatureCollection();

                if (!_server.IsWebSocketAvailable(_requestNativeHandle))
                {
                    _currentIHttpUpgradeFeature = null;
                }

                _streams = new Streams(this);

                (RequestBody, ResponseBody) = _streams.Start();

                var pipe = new Pipe(
                    new PipeOptions(
                        _memoryPool,
                        readerScheduler: PipeScheduler.ThreadPool,
                        pauseWriterThreshold: PauseWriterThreshold,
                        resumeWriterThreshold: ResumeWriterTheshold,
                        minimumSegmentSize: MinAllocBufferSize));
                _bodyOutput = new OutputProducer(pipe);
            }

            NativeMethods.HttpSetManagedContext(_requestNativeHandle, (IntPtr)_thisHandle);
        }
Exemple #55
0
 public void Setup()
 {
     _memoryPool = SlabMemoryPoolFactory.Create();
     _pipe       = new Pipe(new PipeOptions(_memoryPool));
 }
Exemple #56
0
 public RackItemInput(string visibleName, Pipe pipeIn)
 {
     VisibleName = visibleName;
     Key         = (long)(new Random().NextDouble() * long.MaxValue);
     Pipe        = pipeIn;
 }
Exemple #57
0
        /// <summary>
        ///     Receive a message. The <c>Recv</c> method calls this lower-level method to do the actual receiving.
        /// </summary>
        /// <param name="msg">the <c>Msg</c> to receive the message into</param>
        /// <returns><c>true</c> if the message was received successfully, <c>false</c> if there were no messages to receive</returns>
        protected override bool XRecv(ref Msg msg)
        {
            if (this.m_prefetched)
            {
                if (!this.m_identitySent)
                {
                    msg.Move(ref this.m_prefetchedId);
                    this.m_identitySent = true;
                }
                else
                {
                    msg.Move(ref this.m_prefetchedMsg);
                    this.m_prefetched = false;
                }

                this.m_moreIn = msg.HasMore;

                if (!this.m_moreIn)
                {
                    if (this.m_closingCurrentIn)
                    {
                        this.m_currentIn.Terminate(true);
                        this.m_closingCurrentIn = false;
                    }

                    this.m_currentIn = null;
                }

                return(true);
            }

            Pipe[] pipe = new Pipe[1];

            bool isMessageAvailable = this.m_fairQueueing.RecvPipe(pipe, ref msg);

            // It's possible that we receive peer's identity. That happens
            // after reconnection. The current implementation assumes that
            // the peer always uses the same identity.
            while (isMessageAvailable && msg.IsIdentity)
            {
                isMessageAvailable = this.m_fairQueueing.RecvPipe(pipe, ref msg);
            }

            if (!isMessageAvailable)
            {
                return(false);
            }

            Debug.Assert(pipe[0] != null);

            // If we are in the middle of reading a message, just return the next part.
            if (this.m_moreIn)
            {
                this.m_moreIn = msg.HasMore;

                if (!this.m_moreIn)
                {
                    if (this.m_closingCurrentIn)
                    {
                        this.m_currentIn.Terminate(true);
                        this.m_closingCurrentIn = false;
                    }

                    this.m_currentIn = null;
                }
            }
            else
            {
                // We are at the beginning of a message.
                // Keep the message part we have in the prefetch buffer
                // and return the ID of the peer instead.
                this.m_prefetchedMsg.Move(ref msg);

                this.m_prefetched = true;
                this.m_currentIn  = pipe[0];

                byte[] identity = pipe[0].Identity;
                msg.InitPool(identity.Length);
                msg.Put(identity, 0, identity.Length);
                msg.SetFlags(MsgFlags.More);

                this.m_identitySent = true;
            }

            return(true);
        }
Exemple #58
0
        /// <summary>
        ///     Transmit the given message. The <c>Send</c> method calls this to do the actual sending.
        /// </summary>
        /// <param name="msg">the message to transmit</param>
        /// <returns><c>true</c> if the message was sent successfully</returns>
        /// <exception cref="HostUnreachableException">The receiving host must be identifiable.</exception>
        protected override bool XSend(ref Msg msg)
        {
            // If this is the first part of the message it's the ID of the
            // peer to send the message to.
            if (!this.m_moreOut)
            {
                Debug.Assert(this.m_currentOut == null);

                // If we have malformed message (prefix with no subsequent message)
                // then just silently ignore it.
                // TODO: The connections should be killed instead.
                if (msg.HasMore)
                {
                    this.m_moreOut = true;

                    // Find the pipe associated with the identity stored in the prefix.
                    // If there's no such pipe just silently ignore the message, unless
                    // mandatory is set.

                    byte[] identity = msg.Size == msg.Data.Length
                        ? msg.Data
                        : msg.CloneData();

                    Outpipe op;

                    if (this.m_outpipes.TryGetValue(identity, out op))
                    {
                        this.m_currentOut = op.Pipe;
                        if (!this.m_currentOut.CheckWrite())
                        {
                            op.Active         = false;
                            this.m_currentOut = null;
                            if (this.m_mandatory)
                            {
                                this.m_moreOut = false;

                                if (op.Pipe.Active)
                                {
                                    return(false);
                                }

                                throw new HostUnreachableException("In Router.XSend");
                            }
                        }
                    }
                    else if (this.m_mandatory)
                    {
                        this.m_moreOut = false;
                        throw new HostUnreachableException("In Router.XSend");
                    }
                }

                // Detach the message from the data buffer.
                msg.Close();
                msg.InitEmpty();

                return(true);
            }

            if (this.m_options.RawSocket)
            {
                msg.ResetFlags(MsgFlags.More);
            }

            // Check whether this is the last part of the message.
            this.m_moreOut = msg.HasMore;

            // Push the message into the pipe. If there's no out pipe, just drop it.
            if (this.m_currentOut != null)
            {
                // Close the remote connection if user has asked to do so
                // by sending zero length message.
                // Pending messages in the pipe will be dropped (on receiving term-ack)
                if (this.m_rawSocket && msg.Size == 0)
                {
                    this.m_currentOut.Terminate(false);
                    msg.Close();
                    msg.InitEmpty();
                    this.m_currentOut = null;
                    return(true);
                }

                bool ok = this.m_currentOut.Write(ref msg);
                if (!ok)
                {
                    this.m_currentOut = null;
                }
                else if (!this.m_moreOut)
                {
                    this.m_currentOut.Flush();
                    this.m_currentOut = null;
                }
            }
            else
            {
                msg.Close();
            }

            // Detach the message from the data buffer.
            msg.InitEmpty();

            return(true);
        }
Exemple #59
0
 public void addConnection(Pipe p)
 {
     connections.Add(p);
 }
Exemple #60
0
 /// <summary>
 /// Indicate the given pipe as being ready for reading by this socket.
 /// </summary>
 /// <param name="pipe">the <c>Pipe</c> that is now becoming available for reading</param>
 protected override void XReadActivated(Pipe pipe)
 {
     m_fairQueueing.Activated(pipe);
 }