Beispiel #1
0
	public void BuyTransport(Transport t) {
		if (mTransports.Contains(t) || Money < t.Price)
			return;

		Money -= t.Price;
		mTransports.Add (t);
	}
 public Dictionary<string, string> executeOperation(Transport transport)
 {
     //Defines a new Dictonary which is capable of storing indexed string values with a string index.
     Dictionary<string, string> result;
     //Writes the request header
     HeaderParams param = writeHeader(transport, STATS_REQUEST);
     transport.flush();
     readHeaderAndValidate(transport, param);
     //reads the number of statistic details sent from server
     int numberOfStats = transport.readVInt();
     if (logger.IsTraceEnabled)
         logger.Trace("Number of Stats : " + numberOfStats);
     result = new Dictionary<string, string>();
     //reads all statistics and add them to the 'result' dictionary
     for (int i = 0; i < numberOfStats; i++)
     {
         String statName = transport.readString();
         if (logger.IsTraceEnabled)
             logger.Trace("Stat Name Recieved : " + statName);
         String statValue = transport.readString();
         if (logger.IsTraceEnabled)
             logger.Trace("Stat ValueRecieved : " + statName);
         result.Add(statName, statValue);
     }
     return result;
 }
Beispiel #3
0
        public ServerHost(Transport tsp, string endpoint, string subscription, TarballStreamWriter tarball, string basePath, int chunkSize, int hwm, int pgmRate, bool testMode)
        {
            if (String.IsNullOrEmpty(endpoint)) throw new ArgumentNullException("endpoint");
            if (String.IsNullOrEmpty(subscription)) throw new ArgumentNullException("subscription");
            if (tarball == null) throw new ArgumentNullException("tarball");
            if (String.IsNullOrEmpty(basePath)) throw new ArgumentNullException("basePath");

            this.tsp = tsp;
            this.endpoint = endpoint;
            this.subscription = subscription;
            this.tarball = tarball;
            this.basePath = basePath;
            this.chunkSize = chunkSize;
            this.pgmRate = pgmRate;
            this.testMode = testMode;

            this.lastChunkSize = (int)(tarball.Length % chunkSize);
            this.numChunks = (int)(tarball.Length / chunkSize) + ((lastChunkSize > 0) ? 1 : 0);
            this.numBitArrayBytes = ((numChunks + 7) & ~7) >> 3;
            //this.currentNAKs = new BitArray(numBitArrayBytes * 8, false);

            if (this.numChunks == 0) throw new System.Exception();

            this.port = 12198;
            this.device = endpoint;
            int idx = endpoint.LastIndexOf(':');
            if (idx >= 0)
            {
                device = endpoint.Substring(0, idx);
                UInt32.TryParse(endpoint.Substring(idx + 1), out port);
            }

            this.hwm = hwm;
        }
Beispiel #4
0
        public ClientHost(Transport tsp, string endpointData, string endpointCtl, string subscription, DirectoryInfo downloadDirectory, bool testMode, GetClientNAKStateDelegate getClientState, int networkHWM, int diskHWM, int pgmRate)
        {
            this.tsp = tsp;
            this.subscription = subscription;
            this.downloadDirectory = downloadDirectory;
            this.testMode = testMode;
            this.getClientState = getClientState;
            this.pgmRate = pgmRate;

            this.Completed = false;
            this.doLogging = new BooleanSwitch("doLogging", "Log client events", "0");

            this.portData = 12198;
            this.deviceData = endpointData;
            int idx = endpointData.LastIndexOf(':');
            if (idx >= 0)
            {
                this.deviceData = endpointData.Substring(0, idx);
                UInt32.TryParse(endpointData.Substring(idx + 1), out portData);
            }

            this.portCtl = portData + 1;
            this.deviceCtl = endpointCtl;
            idx = endpointCtl.LastIndexOf(':');
            if (idx >= 0)
            {
                this.deviceCtl = endpointCtl.Substring(0, idx);
                UInt32.TryParse(endpointCtl.Substring(idx + 1), out portCtl);
                if (portCtl == portData) portCtl = portData + 1;
            }

            this.networkHWM = networkHWM;
            this.diskHWM = diskHWM;
        }
 public TransferController(Transport transport, string tempFolder = null, int maxConnections = 4, int maxThreads = 4)
 {
     tempPath = tempFolder == null ? Path.GetTempPath() : tempFolder;
     this.transport = transport;
     this.maxConnections = maxConnections;
     this.maxThreads = maxThreads;
 }
		/**== Transports
		*
		* The `ITransport` interface can be seen as the motor block of the client. It's interface is deceitfully simple and
		* it's ultimately responsible from translating a client call to a response.
		*
		* If for some reason you do not agree with the way we wrote the internals of the client,
		* by implementing a custom `ITransport`, you can circumvent all of it and introduce your own.
		*/
		public async Task InterfaceExplained()
		{
			/**
			* Transport is generically typed to a type that implements `IConnectionConfigurationValues`
			* This is the minimum `ITransport` needs to report back for the client to function.
			*
			* In the low level client, `ElasticLowLevelClient`, a `Transport` is instantiated like this:
			*/
			var lowLevelTransport = new Transport<ConnectionConfiguration>(new ConnectionConfiguration());

			/** and in the high level client, `ElasticClient`, like this: */
			var highlevelTransport = new Transport<ConnectionSettings>(new ConnectionSettings());

			var connectionPool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));
			var inMemoryTransport = new Transport<ConnectionSettings>(new ConnectionSettings(connectionPool, new InMemoryConnection()));

			/**
			* The only two methods on `ITransport` are `Request()` and `RequestAsync()`; the default `ITransport` implementation is responsible for introducing
			* many of the building blocks in the client. If you feel that the defaults do not work for you then you can swap them out for your own
			* custom `ITransport` implementation and if you do, {github}/issues[please let us know] as we'd love to learn why you've go down this route!
			*/
			var response = inMemoryTransport.Request<SearchResponse<Project>>(
				HttpMethod.GET,
				"/_search",
				new { query = new { match_all = new { } } });

			response = await inMemoryTransport.RequestAsync<SearchResponse<Project>>(
				HttpMethod.GET,
				"/_search",
				default(CancellationToken),
				new { query = new { match_all = new { } } });
		}
		/** == Transports
		*
		* The ITransport interface can be seen as the motor block of the client. It's interface is deceitfully simple. 
		* Its ultimately responsible from translating a client call to a response. If for some reasons you do not agree with the way we wrote
		* the internals of the client by implementing a custom ITransport you can circumvent all of it and introduce your own.
		*/

		public async Task InterfaceExplained()
		{
			/** 
			* Transport is generically typed to a type that implements IConnectionConfigurationValues 
			* This is the minimum ITransport needs to report back for the client to function.
			*
			* e.g in the low level client transport is instantiated like this:
			*/
			var lowLevelTransport = new Transport<ConnectionConfiguration>(new ConnectionConfiguration());

			/** In the high level client like this. */
			var highlevelTransport = new Transport<ConnectionSettings>(new ConnectionSettings());

			var connectionPool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));
			var inMemoryTransport = new Transport<ConnectionSettings>(new ConnectionSettings(connectionPool, new InMemoryConnection()));

			/**
			* The only two methods on ITransport are Request and DoRequestAsync, the default ITransport implementation is responsible for introducing
			* many of the building blocks in the client, if these do not work for you can swap them out for your own custom ITransport implementation. 
			* If you feel this need report back to us we would love to learn why you'd go down this route!
			*/

			var response = inMemoryTransport.Request<SearchResponse<Project>>(HttpMethod.GET, "/_search", new { query = new { match_all = new { } } });
			response = await inMemoryTransport.RequestAsync<SearchResponse<Project>>(HttpMethod.GET, "/_search", new { query = new { match_all = new { } } });
		}
		public IDuplexTransport BuildLoopback(ITransportSettings settings)
		{
			RabbitMqEndpointAddress address = RabbitMqEndpointAddress.Parse(settings.Address.Uri);

			var transport = new Transport(address, () => BuildInbound(settings), () => BuildOutbound(settings));

			return transport;
		}
 public void executeOperation(Transport transport)
 {
     HeaderParams param = writeHeader(transport, CLEAR_REQUEST);
     if (logger.IsTraceEnabled)
         logger.Trace("Clear Request Sent");
     transport.flush();
     readHeaderAndValidate(transport, param);
 }
 public SocketInitiatorThread(Transport.SocketInitiator initiator, Session session, IPEndPoint socketEndPoint)
 {
     initiator_ = initiator;
     session_ = session;
     socketEndPoint_ = socketEndPoint;
     parser_ = new Parser();
     socket_ = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
     session_ = session;
 }
 public ActionResult Edit(int idRoute, int id, Transport transport)
 {
     if (transportDAO.editTransport(idRoute, transport))
         return RedirectToAction("Index");
     else
     {
         ViewDataSelectList(-1);
         return View("Edit", transportDAO.getTransport(id));
     }
 }
 public SocketInitiatorThread(Transport.SocketInitiator initiator, Session session, IPEndPoint socketEndPoint, SocketSettings socketSettings)
 {
     isDisconnectRequested_ = false;
     initiator_ = initiator;
     session_ = session;
     socketEndPoint_ = socketEndPoint;
     parser_ = new Parser();
     session_ = session;
     socketSettings_ = socketSettings;
 }
 public void testTransport()
 {
     //create instance of factory
     TransportFactory f = new TransportFactory();
     //create instance from factory
     Transport p = f.create("Transport");
     //check that it is right type
     Type t = new Transport().GetType();
     Assert.IsInstanceOfType(t, p);
 }
Beispiel #14
0
    public void Awake()
    {
        i = this;
        t = Object.FindObjectOfType<Transport>();

        Developer = new Developer(t);
        Game = new Game(t);
        Player = new Player(t);
        Tip = new Tip(t);
        Bitcoin = new Bitcoin(t);
    }
 public SocketInitiatorThread(Transport.SocketInitiator initiator, Session session, IPEndPoint socketEndPoint, SocketSettings socketSettings)
 {
     isDisconnectRequested_ = false;
     initiator_ = initiator;
     session_ = session;
     socketEndPoint_ = socketEndPoint;
     parser_ = new Parser();
     socket_ = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
     socket_.NoDelay = socketSettings.SocketNodelay;
     session_ = session;
 }
Beispiel #16
0
        public EndpointActor(Address localAddress, Address remoteAddress, Transport.Transport transport,
            RemoteSettings settings)
        {
            this.localAddress = localAddress;
            this.remoteAddress = remoteAddress;
            this.transport = transport;
            this.settings = settings;

            client = new TcpClient();
            client.Connect(remoteAddress.Host, remoteAddress.Port.Value);
            stream = client.GetStream();
        }
Beispiel #17
0
        public virtual void Bind(Transport transport, string address, uint port)
        {
            if (socket == null)
            {
                socket = new Socket(Type);
                socket.SetSockOpt(SocketOpt.LINGER, 0);

                socketManager.Registry(socket);
            }

            socket.Bind(Socket.BuildUri(transport, address, port));
        }
 protected HeaderParams writeHeader(Transport transport, byte operationCode)
 {
     HeaderParams param = new HeaderParams().opCode(operationCode).cacheName(cacheName).flags(flags).clientIntel(HotRodConstants.CLIENT_INTELLIGENCE_BASIC).topologyId(topologyId).txMarker(NO_TX);
     if (logger.IsTraceEnabled)
     {
         if (logger.IsTraceEnabled)
         {
             string msg = ("headerparams created " + operationCode + " " + cacheName + " " + flags + " " + HotRodConstants.CLIENT_INTELLIGENCE_BASIC + " " + topologyId + " " + NO_TX);
             logger.Trace(msg);
         }
     }
     return codec.writeHeader(transport, param, HotRodConstants.VERSION_11);
 }
        public static long readUnsignedLong(Transport trans)
        {
            byte b = trans.getBinaryReader().ReadByte();
            long i = b & 0x7F;
            for (int shift = 7; (b & 0x80) != 0; shift += 7)
            {
                b = trans.getBinaryReader().ReadByte();
                i |= (b & 0x7FL) << shift;
            }

            logger.Trace(String.Format("Unsigned long read : " + i));
            return i;
        }
Beispiel #20
0
        public SendMessageForm(Transport transport, Email email = null, bool forward = false) {
            InitializeComponent();
            this.transport = transport;
            if (email != null) {
                if (forward) {
                    this.themeTextBox.Text = "Fwd: " + email.Theme;
                } else {
                    this.themeTextBox.Text = "Re: " + email.Theme;

                }
                this.messageRichTextBox.Lines = email.Content.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
            }
        }
Beispiel #21
0
        public Manager(Transport transport)
        {
            Transport = transport;

            this.Connection = transport == Transport.Socket ? new Connection(this) as IConnection : new BoSH(this) as IConnection;
            this.Parser = new Parser(this);
            this.State = new ClosedState(this);

			this.Events.OnNewTag += OnNewTag;
            this.Events.OnError += OnError;
            this.Events.OnConnect += OnConnect;
            this.Events.OnDisconnect += OnDisconnect;
        }
 public Dictionary<byte[], byte[]> executeOperation(Transport transport)
 {
     HeaderParams param = writeHeader(transport, BULK_GET_REQUEST);
     transport.writeVInt(entryCount);
     transport.flush();
     readHeaderAndValidate(transport, param);
     Dictionary<byte[], byte[]> result = new Dictionary<byte[], byte[]>();
     while (transport.readByte() == 1)
     {
         result.Add(transport.readArray(), transport.readArray());
     }
     return result;
 }
        public static void writeUnsignedInt(Transport trans, int i)
        {
            while ((i & ~0x7F) != 0)
            {
                trans.getBinaryWriter().Write((byte)((i & 0x7f) | 0x80));

                i = (int)((uint)i >> 7);

            }

            trans.getBinaryWriter().Write((byte)i);

            logger.Trace(String.Format("Unsigned byte written : " + i));
        }
Beispiel #24
0
        public byte readHeader(Transport trans, HeaderParams param)
        {
            byte magic = trans.readByte(); //Reads magic byte: indicates whether the header is a request or a response

            if (magic != HotRodConstants.RESPONSE_MAGIC)
            {
                String message = "Invalid magic number! Expected "+HotRodConstants.RESPONSE_MAGIC+ "received " + magic;
                InvalidResponseException e = new InvalidResponseException(message);
                logger.Warn(e);
                throw e;
            }

            long receivedMessageId = trans.readVLong(); //Reads the message ID. Should be similar to the msg ID of the request

            if (receivedMessageId != param.Messageid && receivedMessageId != 0)
            {
                String message = "Invalid Message ID! Expected " + param.Messageid + "received " + receivedMessageId;
                InvalidResponseException e = new InvalidResponseException(message);
                logger.Warn(e);
                throw new InvalidResponseException(message);
            }

            byte receivedOpCode = trans.readByte(); //Reads the OP Code

            logger.Trace(String.Format("response code recieved = " + receivedOpCode));
            if (receivedOpCode != param.OpRespCode) //Checks whether the recieved OP code is the corrsponding OPCode for the request sent
            {
                if (receivedOpCode == HotRodConstants.ERROR_RESPONSE) //In case of any error indication by the server
                {

                    logger.Warn(String.Format("Error Response Recieved : "+receivedOpCode));
                    throw new NotImplementedException("Error Response Recieved");
                }

                logger.Warn(String.Format("Invalid Response Recieved : Expected " + param.OpRespCode+" Recieved " +receivedOpCode));
                throw new InvalidResponseException("Invalid Response Operation.");

            }

            byte status = trans.readByte(); //Reads the status

            byte topchange = trans.readByte(); //Reads the Topology change byte. Equals 0 for No Change in topology

            logger.Trace(String.Format("Topology change indicator value : "+topchange));

            return status;
        }
 public SocketInitiatorThread(Transport.SocketInitiator initiator, Session session, IPEndPoint socketEndPoint, SocketSettings socketSettings)
 {
     isDisconnectRequested_ = false;
     initiator_ = initiator;
     session_ = session;
     socketEndPoint_ = socketEndPoint;
     parser_ = new Parser();
     if (socketEndPoint.AddressFamily == AddressFamily.InterNetwork)
         socket_ = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
     else
     {
         socket_ = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
         socket_.SetSocketOption(SocketOptionLevel.IPv6, (SocketOptionName)23, 10);
     }
     socket_.NoDelay = socketSettings.SocketNodelay;
     session_ = session;
 }
Beispiel #26
0
 private void joinNetworkButton_Click(object sender, EventArgs e) {
     if (!this.isConnect) {
         if (settings.IsValid()) {
             transport = new Transport(this);
             transport.Connect(settings.IncomingPortName, settings.OutgoingPortName);
             transport.InitGettingListClients();
             this.isConnect = true;
             ((Button)sender).Text = "Отключиться";
         } else {
             MessageBox.Show("Настройки неверны");
         }
     } else {
         connectionStatusNetwork.Text = "Не в сети";
         messageFormButton.Enabled = false;
         this.isConnect = false;
         ((Button)sender).Text = "Подключиться";
         transport.Disconnect();
     }
 }
		public void RequestPipeline()
		{
			var settings = TestClient.CreateSettings();

			/** When calling Request(Async) on Transport the whole coordination of the request is deferred to a new instance in a `using` block. */
			var pipeline = new RequestPipeline(settings, DateTimeProvider.Default, new MemoryStreamFactory(), new SearchRequestParameters());
			pipeline.GetType().Should().Implement<IDisposable>();

			/** However the transport does not instantiate RequestPipeline directly, it uses a pluggable `IRequestPipelineFactory`*/
			var requestPipelineFactory = new RequestPipelineFactory();
			var requestPipeline = requestPipelineFactory.Create(settings, DateTimeProvider.Default, new MemoryStreamFactory(), new SearchRequestParameters());
			requestPipeline.Should().BeOfType<RequestPipeline>();
			requestPipeline.GetType().Should().Implement<IDisposable>();

			/** which can be passed to the transport when instantiating a client */
			var transport = new Transport<ConnectionSettings>(settings, requestPipelineFactory, DateTimeProvider.Default, new MemoryStreamFactory());

			/** this allows you to have requests executed on your own custom request pipeline */
		}
        public void ImportData(TravelAgencyDbContext ctx)
        {
            var db = this.GetDatabase(DatabaseName, DatabaseHost);
            var transportsDocuments = db.GetCollection<BsonDocument>("Transports");
            var transportsMongo = transportsDocuments
                .FindAll()
                .Select(x => new
                {
                    CompanyName = x["CompanyName"].AsString,
                    Type = x["Type"].AsInt32
                })
                .ToList();

            var uniqueTransportNames = new HashSet<string>();

            var transportsInDB = ctx
                .Transports
                .Select(x => x.CompanyName)
                .ToList();

            foreach (var transport in transportsInDB)
            {
                uniqueTransportNames.Add(transport);
            }

            foreach (var currentTransport in transportsMongo)
            {
                if (!uniqueTransportNames.Contains(currentTransport.CompanyName))
                {
                    uniqueTransportNames.Add(currentTransport.CompanyName);

                    var transportToAdd = new Transport()
                    {
                        CompanyName = currentTransport.CompanyName,
                        Type = (TransportType)currentTransport.Type
                    };

                    ctx.Transports.Add(transportToAdd);
                }
            }

            ctx.SaveChanges();
        }
 public Activity(string name, DateTime openingHour, DateTime closingHour, DaysOpen daysOpen,
                 int minParticipants, int maxParticipants, Price studentPrice, Price adultPrice,
                 string address, EnergyNeeded energyNeeded, string materialNeeded, Transport transport,
                 Duration duration, Temperature temperature, Category category)
 {
     Name = name;
     OpeningHour = openingHour;
     ClosingHour = closingHour;
     DaysOpen = daysOpen;
     MinimumParticipants = minParticipants;
     MaximumParticipants = maxParticipants;
     StudentPrice = studentPrice;
     AdultPrice = adultPrice;
     Address = address;
     EnergyNeeded = energyNeeded;
     MaterialNeeded = materialNeeded;
     Transport = transport;
     Duration = duration;
     Temperature = temperature;
     Category = category;
 }
        public DataTable GetHourlyStatisticsForOccupancy(Transport.CashDeskOperatorEntity.HourlyDetails objHourlyDetails)
        {
            DataTable dtHourlyData = new DataTable();
            SqlParameter[] Param = new SqlParameter[7];
            try
            {
                Param[0] = DataBaseServiceHandler.AddParameter<string>("@DataType", DbType.String, objHourlyDetails.Datatype);
                Param[1] = DataBaseServiceHandler.AddParameter<int>("@rows", DbType.Int32, objHourlyDetails.Rows);
                Param[2] = DataBaseServiceHandler.AddParameter<int>("@starthour", DbType.Int32, objHourlyDetails.StartHour);
                Param[3] = objHourlyDetails.Category == 0 ? DataBaseServiceHandler.AddParameter<object>("@category", DbType.Int32, DBNull.Value) : DataBaseServiceHandler.AddParameter<int>("@category", DbType.Int32, objHourlyDetails.Category);
                Param[4] = objHourlyDetails.Zone == 0 ? DataBaseServiceHandler.AddParameter<object>("@zone", DbType.Int32, DBNull.Value) : DataBaseServiceHandler.AddParameter<int>("@zone", DbType.Int32, objHourlyDetails.Zone);
                Param[5] = objHourlyDetails.Position == 0 ? DataBaseServiceHandler.AddParameter<object>("@position", DbType.Int32, DBNull.Value) : DataBaseServiceHandler.AddParameter<int>("@position", DbType.Int32, objHourlyDetails.Position);
                Param[6] = objHourlyDetails.Date == DateTime.MinValue ? DataBaseServiceHandler.AddParameter<object>("@date", DbType.DateTime, DBNull.Value) : DataBaseServiceHandler.AddParameter<DateTime>("@date", DbType.DateTime, objHourlyDetails.Date);

                dtHourlyData = DataBaseServiceHandler.Fill(CommonDataAccess.ExchangeConnectionString, CommandType.StoredProcedure, Get24HourStatisticsByOccupancy, dtHourlyData, Param);
            }
            catch (Exception ex)
            {
                LogManager.WriteLog(ex.Message, LogManager.enumLogLevel.Error);
            }
            return dtHourlyData;
        }
Beispiel #31
0
        protected override void Seed(TransportContext context)
        {
            base.Seed(context);

            Transport transport1 = new Transport()
            {
                Name = "AutoBus"
            };
            Transport transport2 = new Transport()
            {
                Name = "TrolleyBus"
            };
            Transport transport3 = new Transport()
            {
                Name = "Tram"
            };
            Transport transport4 = new Transport()
            {
                Name = "AutoBus"
            };
            Transport transport5 = new Transport()
            {
                Name = "TrolleyBus"
            };
            Transport transport6 = new Transport()
            {
                Name = "Tram"
            };

            StopInfo stop1 = new StopInfo()
            {
                Name = "ДС Веснянка"
            };
            StopInfo stop2 = new StopInfo()
            {
                Name = "Кавальская слобода"
            };
            StopInfo stop3 = new StopInfo()
            {
                Name = "Гостиница Юбилейная"
            };
            StopInfo stop4 = new StopInfo()
            {
                Name = "Магазин Спутник"
            };
            StopInfo stop5 = new StopInfo()
            {
                Name = "Вокзал"
            };
            StopInfo stop6 = new StopInfo()
            {
                Name = "ДС Дружная"
            };
            StopInfo stop7 = new StopInfo()
            {
                Name = "Брилевичи"
            };



            RouteInfo route1 = new RouteInfo()
            {
                Name = "ДС Веснянка - Вокзал", Number = "Маршрут 1"
            };

            route1.Transports = new List <Transport> {
                transport1, transport2, transport3
            };


            RouteInfo route2 = new RouteInfo()
            {
                Name = "ДС Дружная - Брилевичи", Number = "Маршрут 2"
            };

            route2.Transports = new List <Transport> {
                transport4, transport5, transport6
            };


            RoadtoStop roadtostop1 = new RoadtoStop()
            {
                Routes = route1, Stops = stop1, VisitTime = new DateTime(2008, 5, 1, 8, 30, 52)
            };

            context.Routes.AddRange(new[] { route1, route2 });
            context.SaveChanges();
        }
        private async Task ProcessMessageHandlerAsync(Message message)
        {
            switch (message)
            {
            case Ping _:
            case FindNeighbors _:
                break;

            case GetChainStatus getChainStatus:
            {
                _logger.Debug(
                    "Received a {MessageType} message.",
                    nameof(Messages.GetChainStatus));

                // This is based on the assumption that genesis block always exists.
                Block <T> tip         = BlockChain.Tip;
                var       chainStatus = new ChainStatus(
                    tip.ProtocolVersion,
                    BlockChain.Genesis.Hash,
                    tip.Index,
                    tip.Hash,
                    tip.TotalDifficulty
                    )
                {
                    Identity = getChainStatus.Identity,
                };

                await Transport.ReplyMessageAsync(chainStatus, default);

                break;
            }

            case GetBlockHashes getBlockHashes:
            {
                _logger.Debug(
                    "Received a {MessageType} message (stop: {Stop}).",
                    nameof(Messages.GetBlockHashes),
                    getBlockHashes.Stop);
                BlockChain.FindNextHashes(
                    getBlockHashes.Locator,
                    getBlockHashes.Stop,
                    FindNextHashesChunkSize
                    ).Deconstruct(
                    out long?offset,
                    out IReadOnlyList <BlockHash> hashes
                    );
                _logger.Debug(
                    "Found {HashCount} hashes after the branchpoint (offset: {Offset}) " +
                    "with locator [{LocatorHead}, ...] (stop: {Stop}).",
                    hashes.Count,
                    offset,
                    getBlockHashes.Locator.FirstOrDefault(),
                    getBlockHashes.Stop);
                var reply = new BlockHashes(offset, hashes)
                {
                    Identity = getBlockHashes.Identity,
                };

                await Transport.ReplyMessageAsync(reply, default);

                break;
            }

            case GetBlocks getBlocks:
                await TransferBlocksAsync(getBlocks);

                break;

            case GetTxs getTxs:
                await TransferTxsAsync(getTxs);

                break;

            case TxIds txIds:
                ProcessTxIds(txIds);
                break;

            case BlockHashes _:
                _logger.Error(
                    "{MessageType} messages are only for IBD.",
                    nameof(Messages.BlockHashes));
                break;

            case BlockHeaderMessage blockHeader:
                ProcessBlockHeader(blockHeader);
                break;

            default:
                throw new InvalidMessageException(
                          $"Failed to handle message: {message}",
                          message
                          );
            }
        }
        public void should_start_inner_transport()
        {
            Transport.Start();

            InnerTransport.IsStarted.ShouldBeTrue();
        }
        /**
         * Registers a UDDI binding template that represents the subscription
         * callback endpoint
         *
         * @param client
         * @param cfg_node_name
         * @param bt - Binding Template
         * @param behavior
         * @return
         * @throws ServiceAlreadyStartedException
         * @throws SecurityException
         * @throws ConfigurationException
         * @throws TransportException
         * @throws DispositionReportFaultMessage
         * @throws RemoteException
         * @throws UnexpectedException
         * @throws RegistrationAbortedException
         * @throws UnableToSignException
         */
        public static bindingTemplate registerBinding(UDDIClient client, String cfg_node_name, bindingTemplate bt, SignatureBehavior behavior)
        {
            log.info("Attempting to register binding " + bt.bindingKey);
            UDDIClerk clerk = client.getClerk(cfg_node_name);
            Transport tp    = client.getTransport(cfg_node_name);
            UDDI_Inquiry_SoapBinding     uddiInquiryService = tp.getUDDIInquiryService();
            UDDI_Publication_SoapBinding uddiPublishService = tp.getUDDIPublishService();


            String token = clerk.getAuthToken(clerk.getUDDINode().getSecurityUrl());

            switch (behavior)
            {
            case SignatureBehavior.AbortIfSigned:
                if (CheckExistingBindingForSignature(bt.bindingKey, uddiInquiryService, token, behavior))
                {
                    throw new RegistrationAbortedException("Aborting, Either the item exists and is signed");
                }
                if (CheckServiceAndParentForSignature(bt.serviceKey, uddiInquiryService, token))
                {
                    throw new RegistrationAbortedException("Aborting, Either the service or busness is signed");
                }
                break;

            case SignatureBehavior.DoNothing:
                break;

            case SignatureBehavior.SignAlways:
                try
                {
                    DigSigUtil ds = new DigSigUtil(client.getClientConfig().getDigitalSignatureConfiguration());
                    bt = (bindingTemplate)ds.signUddiEntity(bt);
                }
                catch (Exception ex)
                {
                    log.error("Unable to sign", ex);
                    throw new UnableToSignException("Unable to sign", ex);
                }

                break;

            case SignatureBehavior.SignOnlyIfParentIsntSigned:
                if (!CheckServiceAndParentForSignature(bt.serviceKey, uddiInquiryService, token))
                {
                    try
                    {
                        DigSigUtil ds = new DigSigUtil(client.getClientConfig().getDigitalSignatureConfiguration());
                        bt = (bindingTemplate)ds.signUddiEntity(bt);
                    }
                    catch (Exception ex)
                    {
                        log.error("Unable to sign", ex);
                        throw new UnableToSignException("Unable to sign", ex);
                    }
                }
                break;
            }
            save_binding sb = new save_binding();

            sb.authInfo        = (token);
            sb.bindingTemplate = new bindingTemplate[] { bt };

            bindingDetail saveBinding = uddiPublishService.save_binding(sb);

            log.info("Binding registered successfully");
            if (saveBinding.bindingTemplate == null || saveBinding.bindingTemplate.Length > 1)
            {
                throw new UnexpectedResponseException("The number of binding templates returned was unexpected, count=" + (saveBinding.bindingTemplate == null ? "none" : saveBinding.bindingTemplate.Length.ToString()));
            }
            return(saveBinding.bindingTemplate[0]);
        }
Beispiel #35
0
        /// <summary>
        /// Opens a UDP multicast socket.
        /// </summary>
        /// <param name="adapter">The network adapter to bind this socket.</param>
        /// <param name="cloudEP">Specifies the multicast group and port.</param>
        /// <remarks>
        /// <para>
        /// Pass <b>adapter=IPAddress.Any</b> to bind the socket to all available network
        /// adapters.
        /// </para>
        /// <note>
        /// A valid port and address must be specified in <b>cloudEP</b>.
        /// </note>
        /// </remarks>
        public void OpenMulticast(IPAddress adapter, IPEndPoint cloudEP)
        {
            if (cloudEP.Address.Equals(IPAddress.Any))
            {
                throw new MsgException("Invalid multicast address.");
            }

            if (cloudEP.Port == 0)
            {
                throw new MsgException("Invalid multicast port.");
            }

            using (TimedLock.Lock(router.SyncRoot))
            {
                this.sock = new EnhancedSocket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                this.sock.ReuseAddress             = true;
                this.sock.EnableBroadcast          = true;
                this.sock.MulticastTTL             = MulticastTTL;
                this.sock.MulticastLoopback        = true;
                this.sock.IgnoreUdpConnectionReset = true;

                this.sock.Bind(new IPEndPoint(adapter, cloudEP.Port));

                // The framework throws an exception if there is no connected network connection
                // when we attempt to add the socket to the multicast group.  I'm going to catch
                // this exception and track that this didn't work and then periodically retry
                // the operation.

                try
                {
                    this.sock.MulticastGroup = cloudEP.Address;
                    this.multicastInit       = true;
                }
                catch
                {
                    this.multicastInit = false;
                }

                this.transport = Transport.Multicast;
                this.localEP   = router.NormalizeEP(new ChannelEP(Transport.Udp, router.UdpEP));
                this.port      = cloudEP.Port;
                this.sendQueue = new PriorityQueue <Msg>();
                this.onSend    = new AsyncCallback(OnSend);
                this.sendMsg   = null;
                this.cbSend    = 0;
                this.sendBuf   = null;
                this.msgBuf    = new byte[TcpConst.MTU];
                this.cloudEP   = cloudEP;

                this.onSocketReceive = new AsyncCallback(OnSocketReceive);
                this.recvBuf         = new byte[TcpConst.MTU];

                sendQueue.CountLimit = router.UdpMsgQueueCountMax;
                sendQueue.SizeLimit  = router.UdpMsgQueueSizeMax;

                router.Trace(1, "UDP: OpenMulticast",
                             string.Format("cloudEP={0} localEP={1} adaptor={2} NIC={3}",
                                           cloudEP, localEP.NetEP, adapter, NetHelper.GetNetworkAdapterIndex(adapter)), null);

                sock.SendBufferSize    = router.UdpMulticastSockConfig.SendBufferSize;
                sock.ReceiveBufferSize = router.UdpMulticastSockConfig.ReceiveBufferSize;

                // Initiate the first async receive operation on this socket

                sock.BeginReceiveFrom(recvBuf, 0, recvBuf.Length, SocketFlags.None, ref recvEP, onSocketReceive, null);

                // Mark the channel as open.

                this.isOpen = true;
            }
        }
Beispiel #36
0
 public void should_not_crash_when_stopping_if_it_was_not_started()
 {
     Assert.That(() => Transport.Stop(), Throws.Nothing);
 }
Beispiel #37
0
        public async Task <EmailResponse> SendEmailAsync()
        {
            ValidateEmail();

            return(await Transport.SendEmailAsync(this));
        }
Beispiel #38
0
        private Task ProcessResponse(StateChangeTracker tracker, object result, HubRequest request, Exception error)
        {
            var hubResult = new HubResponse
            {
                State  = tracker.GetChanges(),
                Result = result,
                Id     = request.Id,
            };

            if (error != null)
            {
                _counters.ErrorsHubInvocationTotal.Increment();
                _counters.ErrorsHubInvocationPerSec.Increment();
                _counters.ErrorsAllTotal.Increment();
                _counters.ErrorsAllPerSec.Increment();

                var hubError = error.InnerException as HubException;

                if (_enableDetailedErrors || hubError != null)
                {
                    var exception = error.InnerException ?? error;
                    hubResult.StackTrace = _isDebuggingEnabled ? exception.StackTrace : null;
                    hubResult.Error      = exception.Message;

                    if (hubError != null)
                    {
                        hubResult.IsHubException = true;
                        hubResult.ErrorData      = hubError.ErrorData;
                    }
                }
                else
                {
                    hubResult.Error = String.Format(CultureInfo.CurrentCulture, Resources.Error_HubInvocationFailed, request.Hub, request.Method);
                }
            }

            Trace.TraceVerbose("Sending hub invocation result to connection {0} using transport {1}", Transport.ConnectionId, Transport.GetType().Name);

            return(Transport.Send(hubResult));
        }
Beispiel #39
0
        private static ModelNode LoadModelNode(Resource resource, IEnumerable <CMSDDocumentDataSectionJob> CMSDjobs)
        {
            var modelnode = new ModelNode();

            if (resource.ResourceType.Contains("Machine"))
            {
                modelnode = new Machine();
            }
            else if (resource.ResourceType.Contains("Facility"))
            {
                modelnode = new Facility();
            }
            else if (resource.ResourceType.Contains("Buffer"))
            {
                modelnode = new UserControles.Buffer();
            }
            else if (resource.ResourceType.Contains("Transport"))
            {
                modelnode = new Transport();
            }

            double left = 0, top = 0;

            foreach (ResourceProperty resourceProperty in resource.Property)
            {
                switch (resourceProperty.Name)
                {
                case "XGrid":
                    left = double.Parse(resourceProperty.Value);
                    break;

                case "YGrid":
                    top = double.Parse(resourceProperty.Value);
                    break;

                case "MTTR":
                    var distsource = resourceProperty.Distribution.First();
                    modelnode.ResourceModel.MTTR.Distribution = DataLayer.IDistribution.GetFromCmsd(distsource);
                    modelnode.ResourceModel.MTTR.Distribution.GeneralConverter = GeneralConverter.GetInstance(resourceProperty.Unit);
                    break;

                case "MTBF":
                    distsource = resourceProperty.Distribution.First();
                    modelnode.ResourceModel.MTBF.Distribution = DataLayer.IDistribution.GetFromCmsd(distsource);
                    modelnode.ResourceModel.MTBF.Distribution.GeneralConverter = GeneralConverter.GetInstance(resourceProperty.Unit);
                    break;

                case "Capacity":
                    try
                    {
                        modelnode.ResourceModel.Capacity = int.Parse(resourceProperty.Value);
                    }
                    catch {}
                    break;

                case "Speed":
                    try
                    {
                        modelnode.ResourceModel.Speed = int.Parse(resourceProperty.Value, CultureInfo.InvariantCulture);
                    }
                    catch
                    {}
                    break;

                case "DistanceToNode":
                    try
                    {
                        modelnode.ResourceModel.DistansToNode = int.Parse(resourceProperty.Value, CultureInfo.InvariantCulture);
                    }
                    catch
                    { }
                    break;
                }
            }

            modelnode.Margin = new Thickness(left, top, 0, 0);
            modelnode.XGrid  = left;
            modelnode.YGrid  = top;
            modelnode.ResourceModel.ProcessName = resource.Name;

            AddConsumption(resource.Property.Where(t => t.Name.StartsWith("Idle")), modelnode.ResourceModel.Idle);
            AddConsumption(resource.Property.Where(t => t.Name.StartsWith("Off")), modelnode.ResourceModel.Off);
            AddConsumption(resource.Property.Where(t => t.Name.StartsWith("Down")), modelnode.ResourceModel.Down);

            modelnode.ResourceModel.Job.Clear();
            var cmsdDocumentDataSectionJobs = CMSDjobs as IList <CMSDDocumentDataSectionJob> ?? CMSDjobs.ToList();

            foreach (var sectionJob in cmsdDocumentDataSectionJobs.Where(t => t.Identifier.StartsWith("BaseJob")))
            {
                var job = new Job()
                {
                    Name = sectionJob.Identifier.Remove(0, 7).Replace(modelnode.ResourceModel.ProcessName, "")
                };

                AddConsumption(resource.Property.Where(t => t.Name.StartsWith(job.Name)), job.State);
                job.Subjobs.Clear();
                foreach (var pointSubJob in sectionJob.SubJob)
                {
                    var cmsdSubJob = cmsdDocumentDataSectionJobs.FirstOrDefault(t => t.Identifier == pointSubJob.JobIdentifier);
                    if (cmsdSubJob != null)
                    {
                        var sub = new SubJob()
                        {
                            Description  = cmsdSubJob.Description,
                            Distribution = IDistribution.GetFromCmsd(cmsdSubJob.PlannedEffort.ProcessingTime.Distribution)
                        };
                        sub.Distribution.GeneralConverter = GeneralConverter.TimeConverters.FirstOrDefault(
                            t => t.UnitType.ToString() == cmsdSubJob.PlannedEffort.ProcessingTime.TimeUnit);
                        job.Subjobs.Add(sub);
                    }
                }

                modelnode.ResourceModel.Job.Add(job);
            }
            return(modelnode);
        }
        static private float RunTest(Test test)
        {
            Stopwatch sw = new Stopwatch();

            sw.Start();
            DayTime dt = new DayTime();

            Console.WriteLine("Updating Configuration for {0}", test.Name);
            Configuration.Initialize(test);

            //Console.WriteLine("{0}: Creating Customer and Enterprise", test.Name);
            Customer   customer = new Customer();
            Enterprise ent      = new Enterprise(customer);
            BigData    bigData  = new BigData();

            //Console.WriteLine("{0}: Generating Plants", test.Name);
            List <Plant> plants = SimulationSetup.GeneratePlants();

            foreach (Plant plant in plants)
            {
                ent.Add(plant);
                foreach (var wc in plant.Workcenters)
                {
                    if (wc.Name == "Shipping Dock" || wc.Name == "Stage")
                    {
                        continue;
                    }
                    bigData.AddWorkcenter(wc.Name);
                    ((Core.Workcenters.Workcenter)wc).AddBigData(bigData);
                }
            }
            ent.Add(bigData);

            //Console.WriteLine("{0}: Generating Transport Routes", test.Name);
            var       routes    = SimulationSetup.GenerateRoutes(plants);
            Transport transport = new Transport(ent, routes);

            ent.Add(transport);

            //Console.WriteLine("{0}: Generating Simulation Node", test.Name);
            SimulationNode sn = new SimulationNode(dt, ent);

            //Console.WriteLine("{0}: Loading Workorders", test.Name);
            int woCounter = 0;

            while (woCounter < Configuration.InitialNumberOfWorkorders)
            {
                Workorder.PoType type = SimulationSetup.SelectWoPoType(woCounter);
                DayTime          due  = SimulationSetup.SelectWoDueDate(dt, woCounter);
                int initialOp         = SimulationSetup.SelectWoInitialOp(woCounter, Workorder.GetMaxOps(type) - 1);
                customer.CreateOrder(type, due, initialOp);
                woCounter++;
            }
            customer.Work(dt); // Load Workorders into Enterprise

            //SaveToFile(Configuration.Instance.TestFilename, 0, sn);

            Console.WriteLine("{0}: Starting Simulation", test.Name);
            for (int i = 1; i < Configuration.MinutesForProgramToTest; i++)
            {
                dt.Next();
                ent.Work(dt);
                customer.Work(dt);

                var next = bigData.GetNextOrder(i);
                if (next.HasValue)
                {
                    customer.CreateOrder(next.Value.Item1, new DayTime((int)next.Value.Item2, 800));
                }

                if (i % 500 == 0)
                {
                    Console.Write(".");
                }

                //SaveToFile(Configuration.Instance.TestFilename, i, sn);
            }
            Console.WriteLine(".");
            //Console.WriteLine("Finished with Test {0}", test.Name);
            sw.Stop();
            Console.WriteLine("Time to Complete: {0}", sw.Elapsed);
            sw.Reset();

            var result = customer.Result();

            Console.WriteLine("Result: {0}", result.ToString());
            return(result);
        }
Beispiel #41
0
 public MyServerFactory(Transport <ServerFactory> listener, MyCuaeServerFactory implFactory)
     : base(listener, implFactory)
 {
     _listener    = listener;
     _implFactory = implFactory;
 }
Beispiel #42
0
        internal async Task OnAuthUpdated(TokenDetails tokenDetails, bool wait)
        {
            if (Connection.State != ConnectionState.Connected)
            {
                ExecuteCommand(Connect());
                return;
            }

            try
            {
                var msg = new ProtocolMessage(ProtocolMessage.MessageAction.Auth)
                {
                    Auth = new AuthDetails
                    {
                        AccessToken = tokenDetails.Token,
                    },
                };

                Send(msg);
            }
            catch (AblyException e)
            {
                Logger.Warning("OnAuthUpdated: closing transport after send failure");
                Logger.Debug(e.Message);
                Transport?.Close();
            }

            if (wait)
            {
                var waiter = new ConnectionChangeAwaiter(Connection);

                try
                {
                    while (true)
                    {
                        var(success, newState) = await waiter.Wait(Defaults.DefaultRealtimeTimeout);

                        if (success == false)
                        {
                            throw new AblyException(
                                      new ErrorInfo(
                                          $"Connection state didn't change after Auth updated within {Defaults.DefaultRealtimeTimeout}",
                                          40140));
                        }

                        switch (newState)
                        {
                        case ConnectionState.Connected:
                            Logger.Debug("onAuthUpdated: Successfully connected");
                            return;

                        case ConnectionState.Connecting:
                        case ConnectionState.Disconnected:
                            continue;

                        default:     // if it's one of the failed states
                            Logger.Debug("onAuthUpdated: Failed to reconnect");
                            throw new AblyException(Connection.ErrorReason);
                        }
                    }
                }
                catch (AblyException)
                {
                    throw;
                }
                catch (Exception e)
                {
                    Logger.Error("Error in AuthUpdated handler", e);
                    throw new AblyException(
                              new ErrorInfo("Error while waiting for connection to update after updating Auth"), e);
                }
            }
        }
Beispiel #43
0
 /// <summary>
 /// Receives an envelope from the transport.
 /// </summary>
 /// <param name="cancellationToken">The cancellation token.</param>
 /// <returns></returns>
 private Task <Envelope> ReceiveFromTransportAsync(CancellationToken cancellationToken)
 => Transport.ReceiveAsync(cancellationToken);
Beispiel #44
0
 public bool Initialize(string apiKey)
 {
     _transport = new Transport(ServiceBaseUri, apiKey);
     return(true);
 }
Beispiel #45
0
 public static void InheritanceExample()
 {
     Transport transport = new Transport(mileage: 3000);
     Transport car       = new Car(consumption: 10, fuel: 50, mileage: 35000);
 }
Beispiel #46
0
 public override void OnRealTimeMessage(TransportMessage transportMessage)
 {
     Transport.TriggerMessageReceived(transportMessage);
 }
Beispiel #47
0
        public EmailResponse Send()
        {
            ValidateEmail();

            return(Transport.SendEmail(this));
        }
 // Use this for initialization
 void Start()
 {
     t = GetComponent <Transport> ();
     a = GetComponent <Animator> ();
 }
Beispiel #49
0
 override public void Add(Transport transport)
 {
     Add <TransportEarth>(transport);
 }
Beispiel #50
0
 public void Dispose() => Transport.Dispose();
Beispiel #51
0
        void HandleMovementOpcode(ClientOpcodes opcode, MovementInfo movementInfo)
        {
            Unit   mover    = GetPlayer().GetUnitBeingMoved();
            Player plrMover = mover.ToPlayer();

            if (plrMover && plrMover.IsBeingTeleported())
            {
                return;
            }

            GetPlayer().ValidateMovementInfo(movementInfo);

            if (movementInfo.Guid != mover.GetGUID())
            {
                Log.outError(LogFilter.Network, "HandleMovementOpcodes: guid error");
                return;
            }
            if (!movementInfo.Pos.IsPositionValid())
            {
                Log.outError(LogFilter.Network, "HandleMovementOpcodes: Invalid Position");
                return;
            }

            if (!mover.MoveSpline.Finalized())
            {
                return;
            }

            // stop some emotes at player move
            if (plrMover && (plrMover.GetEmoteState() != 0))
            {
                plrMover.SetEmoteState(Emote.OneshotNone);
            }

            //handle special cases
            if (!movementInfo.transport.guid.IsEmpty())
            {
                // We were teleported, skip packets that were broadcast before teleport
                if (movementInfo.Pos.GetExactDist2d(mover) > MapConst.SizeofGrids)
                {
                    return;
                }

                if (Math.Abs(movementInfo.transport.pos.GetPositionX()) > 75f || Math.Abs(movementInfo.transport.pos.GetPositionY()) > 75f || Math.Abs(movementInfo.transport.pos.GetPositionZ()) > 75f)
                {
                    return;
                }

                if (!GridDefines.IsValidMapCoord(movementInfo.Pos.posX + movementInfo.transport.pos.posX, movementInfo.Pos.posY + movementInfo.transport.pos.posY,
                                                 movementInfo.Pos.posZ + movementInfo.transport.pos.posZ, movementInfo.Pos.Orientation + movementInfo.transport.pos.Orientation))
                {
                    return;
                }

                if (plrMover)
                {
                    if (!plrMover.GetTransport())
                    {
                        Transport transport = plrMover.GetMap().GetTransport(movementInfo.transport.guid);
                        if (transport)
                        {
                            transport.AddPassenger(plrMover);
                        }
                    }
                    else if (plrMover.GetTransport().GetGUID() != movementInfo.transport.guid)
                    {
                        plrMover.GetTransport().RemovePassenger(plrMover);
                        Transport transport = plrMover.GetMap().GetTransport(movementInfo.transport.guid);
                        if (transport)
                        {
                            transport.AddPassenger(plrMover);
                        }
                        else
                        {
                            movementInfo.ResetTransport();
                        }
                    }
                }

                if (!mover.GetTransport() && !mover.GetVehicle())
                {
                    GameObject go = mover.GetMap().GetGameObject(movementInfo.transport.guid);
                    if (!go || go.GetGoType() != GameObjectTypes.Transport)
                    {
                        movementInfo.transport.Reset();
                    }
                }
            }
            else if (plrMover && plrMover.GetTransport())                // if we were on a transport, leave
            {
                plrMover.GetTransport().RemovePassenger(plrMover);
            }

            // fall damage generation (ignore in flight case that can be triggered also at lags in moment teleportation to another map).
            if (opcode == ClientOpcodes.MoveFallLand && plrMover && !plrMover.IsInFlight())
            {
                plrMover.HandleFall(movementInfo);
            }

            // interrupt parachutes upon falling or landing in water
            if (opcode == ClientOpcodes.MoveFallLand || opcode == ClientOpcodes.MoveStartSwim || opcode == ClientOpcodes.MoveSetFly)
            {
                mover.RemoveAurasWithInterruptFlags(SpellAuraInterruptFlags.LandingOrFlight); // Parachutes
            }
            movementInfo.Guid    = mover.GetGUID();
            movementInfo.Time    = AdjustClientMovementTime(movementInfo.Time);
            mover.m_movementInfo = movementInfo;

            // Some vehicles allow the passenger to turn by himself
            Vehicle vehicle = mover.GetVehicle();

            if (vehicle)
            {
                VehicleSeatRecord seat = vehicle.GetSeatForPassenger(mover);
                if (seat != null)
                {
                    if (seat.HasFlag(VehicleSeatFlags.AllowTurning))
                    {
                        if (movementInfo.Pos.GetOrientation() != mover.GetOrientation())
                        {
                            mover.SetOrientation(movementInfo.Pos.GetOrientation());
                            mover.RemoveAurasWithInterruptFlags(SpellAuraInterruptFlags.Turning);
                        }
                    }
                }
                return;
            }

            mover.UpdatePosition(movementInfo.Pos);

            MoveUpdate moveUpdate = new();

            moveUpdate.Status = mover.m_movementInfo;
            mover.SendMessageToSet(moveUpdate, GetPlayer());

            if (plrMover)                                            // nothing is charmed, or player charmed
            {
                if (plrMover.IsSitState() && movementInfo.HasMovementFlag(MovementFlag.MaskMoving | MovementFlag.MaskTurning))
                {
                    plrMover.SetStandState(UnitStandStateType.Stand);
                }

                plrMover.UpdateFallInformationIfNeed(movementInfo, opcode);

                if (movementInfo.Pos.posZ < plrMover.GetMap().GetMinHeight(plrMover.GetPhaseShift(), movementInfo.Pos.GetPositionX(), movementInfo.Pos.GetPositionY()))
                {
                    if (!(plrMover.GetBattleground() && plrMover.GetBattleground().HandlePlayerUnderMap(GetPlayer())))
                    {
                        // NOTE: this is actually called many times while falling
                        // even after the player has been teleported away
                        // @todo discard movement packets after the player is rooted
                        if (plrMover.IsAlive())
                        {
                            plrMover.AddPlayerFlag(PlayerFlags.IsOutOfBounds);
                            plrMover.EnvironmentalDamage(EnviromentalDamage.FallToVoid, (uint)GetPlayer().GetMaxHealth());
                            // player can be alive if GM/etc
                            // change the death state to CORPSE to prevent the death timer from
                            // starting in the next player update
                            if (plrMover.IsAlive())
                            {
                                plrMover.KillPlayer();
                            }
                        }
                    }
                }
                else
                {
                    plrMover.RemovePlayerFlag(PlayerFlags.IsOutOfBounds);
                }

                if (opcode == ClientOpcodes.MoveJump)
                {
                    plrMover.RemoveAurasWithInterruptFlags(SpellAuraInterruptFlags2.Jump); // Mind Control
                    Unit.ProcSkillsAndAuras(plrMover, null, ProcFlags.Jump, ProcFlags.None, ProcFlagsSpellType.MaskAll, ProcFlagsSpellPhase.None, ProcFlagsHit.None, null, null, null);
                }
            }
        }
        public void TestConstructor()
        {
            Transport t = new Transport();

            Assert.AreEqual("Railway Station:\tOwned by: Banker", t.ToString());
        }
Beispiel #53
0
 void OnConnected(Transport Transport, string msg)
 {
     DebugEx.TraceLog("OnConnected transport=" + Transport.ToString() + " msg=" + msg);
 }
Beispiel #54
0
        private void LayoutRoot_ManipulationCompleted(object sender, ManipulationCompletedRoutedEventArgs e)
        {
            var width  = (float)ActualWidth;
            var height = (float)ActualHeight;

            var offset = _layout.Offset;

            if (Math.Abs(e.Cumulative.Translation.X) > Math.Abs(e.Cumulative.Translation.Y))
            {
                var current = -width;
                var delta   = -(offset.X - current) / width;

                Scroll(delta, e.Velocities.Linear.X, true);
            }
            else
            {
                var current = 0;
                var delta   = -(offset.Y - current) / height;

                var maximum = current - height;
                var minimum = current + height;

                var direction = 0;

                var animation = _layout.Compositor.CreateScalarKeyFrameAnimation();
                animation.InsertKeyFrame(0, offset.Y);

                if (delta < 0 && e.Velocities.Linear.Y > 1.5)
                {
                    // previous
                    direction--;
                    animation.InsertKeyFrame(1, minimum);
                }
                else if (delta > 0 && e.Velocities.Linear.Y < -1.5)
                {
                    // next
                    direction++;
                    animation.InsertKeyFrame(1, maximum);
                }
                else
                {
                    // back
                    animation.InsertKeyFrame(1, current);
                }

                if (direction != 0)
                {
                    Layer.Visibility = Visibility.Collapsed;

                    if (Transport.IsVisible)
                    {
                        Transport.Hide();
                    }

                    Unload();

                    Dispose();
                    Hide();
                }
                else
                {
                    var opacity = _layout.Compositor.CreateScalarKeyFrameAnimation();
                    opacity.InsertKeyFrame(0, _layer.Opacity);
                    opacity.InsertKeyFrame(1, 1);

                    _layer.StartAnimation("Opacity", opacity);
                }

                _layout.StartAnimation("Offset.Y", animation);
            }

            e.Handled = true;
        }
        private async Task TransferBlocksAsync(GetBlocks getData)
        {
            string identityHex = ByteUtil.Hex(getData.Identity);

            _logger.Verbose(
                "Preparing a {MessageType} message to reply to {Identity}...",
                nameof(Messages.Blocks),
                identityHex
                );

            var blocks = new List <byte[]>();

            List <BlockHash> hashes = getData.BlockHashes.ToList();
            int          i          = 1;
            int          total      = hashes.Count;
            const string logMsg     =
                "Fetching block {Index}/{Total} {Hash} to include in " +
                "a reply to {Identity}...";

            foreach (BlockHash hash in hashes)
            {
                _logger.Verbose(logMsg, i, total, hash, identityHex);
                if (_store.GetBlock <T>(BlockChain.Policy.GetHashAlgorithm, hash) is { } block)
                {
                    byte[] payload = Codec.Encode(block.MarshalBlock());
                    blocks.Add(payload);
                }

                if (blocks.Count == getData.ChunkSize)
                {
                    var response = new Messages.Blocks(blocks)
                    {
                        Identity = getData.Identity,
                    };
                    _logger.Verbose(
                        "Enqueuing a blocks reply (...{Index}/{Total})...",
                        i,
                        total
                        );
                    await Transport.ReplyMessageAsync(response, default);

                    blocks.Clear();
                }

                i++;
            }

            if (blocks.Any())
            {
                var response = new Messages.Blocks(blocks)
                {
                    Identity = getData.Identity,
                };
                _logger.Verbose(
                    "Enqueuing a blocks reply (...{Index}/{Total}) to {Identity}...",
                    total,
                    total,
                    identityHex
                    );
                await Transport.ReplyMessageAsync(response, default);
            }

            _logger.Debug("Blocks were transferred to {Identity}.", identityHex);
        }
Beispiel #56
0
    ////////////////////////
    /// Auxiliar Methods ///
    ////////////////////////

    int GetTravelTime(int distance, Transport t) => (int)Math.Ceiling(distance / t.Speed);
Beispiel #57
0
    void OnMouseDown()
    {
        var s = this.name.TakeWhile(c => !Char.IsDigit(c))
                .ToArray();

        nameofGameObj = new string(s);
        var showGoodsObjects = GetComponents <ShowGoods> ();

        foreach (var item in showGoodsObjects)
        {
            item.info = null;
        }

        if (nameofGameObj == "House")
        {
            isShowHouse      = true;
            coolDownShowGood = cooldownMessageOfGoods;
        }


        switch (nameofGameObj)
        {
        case "Train":
        {
            var digits = this.name.SkipWhile(c => !Char.IsDigit(c))
                         .TakeWhile(Char.IsDigit)
                         .ToArray();
            var str = new string (digits);
            id = int.Parse(str);
            foreach (var item in GetMQTrain.trainListNotGameObj)
            {
                if (id == item.Id)
                {
                    curTransport     = item as Transport;
                    showGoods        = true;
                    coolDownShowGood = cooldownMessageOfGoods;
                }
            }
            break;
        }

        case "Plane":
        {
            var digits = this.name.SkipWhile(c => !Char.IsDigit(c))
                         .TakeWhile(Char.IsDigit)
                         .ToArray();
            var str = new string(digits);
            id = int.Parse(str);
            foreach (var item in GetMQPlane.planeListNotGameObj)
            {
                if (id == item.Id)
                {
                    curTransport     = item as Transport;
                    showGoods        = true;
                    coolDownShowGood = cooldownMessageOfGoods;
                }
            }
            break;
        }

        case "Car":
        {
            var digits = this.name.SkipWhile(c => !Char.IsDigit(c))
                         .TakeWhile(Char.IsDigit)
                         .ToArray();
            var str = new string (digits);
            id = int.Parse(str);
            foreach (var item in GetMQCar.carListNotGameObj)
            {
                if (id == item.Id)
                {
                    curTransport     = item as Transport;
                    showGoods        = true;
                    coolDownShowGood = cooldownMessageOfGoods;
                }
            }
            break;
        }
        }
    }
 public OmniServerConfiguration(Transport tMode = Transport.HTTP, string logDirectory = "logs") : this(tMode, "localhost", 8080, logDirectory)
 {
 }
Beispiel #59
0
 public Network(Transport transport = null, Codecs cs = null)
 {
     _transport = transport == null ? new TCPTransport() : transport;
 }
Beispiel #60
0
        public Setting()
        {
            Id          = Guid.NewGuid();
            RootPath    = AppDomain.CurrentDomain.BaseDirectory;//SetupInformation.ApplicationBase
            ModuleLevel = ModuleLevel.All;

            MessageSettings = (MessageSettings)ConfigurationManager.GetSection(MessageSettings.SectionName);
            if (MessageSettings == null)
            {
                MessageSettings = new MessageSettings();
            }

            Branch = ConfigurationManager.AppSettings["Branch"];

            if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["AccountingMode"]))
            {
                AccountingMode = Convert.ToInt32(ConfigurationManager.AppSettings["AccountingMode"]);
            }
            //启用读取数据库中的缓存配置
            if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["UseDbCacheConfiguration"]))
            {
                UseDbCacheConfiguration = Convert.ToBoolean(ConfigurationManager.AppSettings["UseDbCacheConfiguration"]);
            }
            //启用Ignite校验
            if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["UseIgniteCompute"]))
            {
                UseIgniteCompute = Convert.ToBoolean(ConfigurationManager.AppSettings["UseIgniteCompute"]);
            }


            ServiceType = ConfigurationManager.AppSettings["ServiceType"];
            ServiceName = ConfigurationManager.AppSettings["ServiceName"];
            AuthUrl     = ConfigurationManager.AppSettings["AuthUrl"];
            //取消掉OracleSchema
            //OracleSchema = ConfigurationManager.AppSettings["OracleSchema"];
            OracleSchema = "";

            Transport          = ConfigurationManager.AppSettings["NServiceBus/Transport"];
            BusinessRuleConfig = ConfigurationManager.AppSettings["BusinessRuleConfig"];

            if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["UseLogInterceptor"]))
            {
                UseLogInterceptor = bool.Parse(ConfigurationManager.AppSettings["UseLogInterceptor"]);
            }
            if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["UseMeasureInterceptor"]))
            {
                UseMeasureInterceptor = bool.Parse(ConfigurationManager.AppSettings["UseMeasureInterceptor"]);
            }
            if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["UseExceptionHandlingInterceptor"]))
            {
                UseExceptionHandlingInterceptor = bool.Parse(ConfigurationManager.AppSettings["UseExceptionHandlingInterceptor"]);
            }
            if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["UseCachingInterceptor"]))
            {
                UseCachingInterceptor = bool.Parse(ConfigurationManager.AppSettings["UseCachingInterceptor"]);
            }
            if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["UseLookupQueryInterceptor"]))
            {
                UseLookupQueryInterceptor = bool.Parse(ConfigurationManager.AppSettings["UseLookupQueryInterceptor"]);
            }
            //RegisterServerHost = ConfigurationManager.AppSettings["RegisterServerHost"];
            //InternetRegisterServerHost = ConfigurationManager.AppSettings["InternetRegisterServerHost"];
            LogKeeperUrl = ConfigurationManager.AppSettings["LogKeeperUrl"];

            if (!string.IsNullOrEmpty(Transport))
            {
                var ar = Transport.Split(';');

                TransportIp       = ar[0].Split('=')[1];
                TransportUserName = ar[1].Split('=')[1];
                TransportPassword = ar[2].Split('=')[1];

                if (ar.Length > 3 && !string.IsNullOrEmpty(ar[3]))
                {
                    TransportVirtualHost = ar[3].Split('=')[1];
                }
            }

            if (ConfigurationManager.ConnectionStrings[CONST_CONN_NAME] != null)
            {
                ConnString = ConfigurationManager.ConnectionStrings[CONST_CONN_NAME].ConnectionString;
            }
            ConnPoolNum = new Random().Next(1, 10);
            //if (!string.IsNullOrEmpty(RegisterServerHost))
            //{
            //    RegisterServerHost = RegisterServerHost.EndsWith("/")
            //        ? RegisterServerHost
            //        : string.Format("{0}/", RegisterServerHost);
            //}

            //if (!string.IsNullOrEmpty(InternetRegisterServerHost))
            //{
            //    InternetRegisterServerHost = InternetRegisterServerHost.EndsWith("/")
            //        ? InternetRegisterServerHost
            //        : string.Format("{0}/", InternetRegisterServerHost);
            //}
        }