コード例 #1
1
	    public SubscriptionClient(IServiceBus bus, SubscriptionRouter router, Uri subscriptionServiceUri,
		                          TimeSpan startTimeout)
		{
			_bus = bus;
			_router = router;
			_subscriptionServiceUri = subscriptionServiceUri;
			_startTimeout = startTimeout;
			_network = router.Network;

			if (_log.IsDebugEnabled)
				_log.DebugFormat("Starting SubscriptionClient using {0}", subscriptionServiceUri);

			VerifyClientAndServiceNotOnSameEndpoint(bus);

			_ready.Reset();

			var consumerInstance = new SubscriptionMessageConsumer(_router, _network);

			_unsubscribeAction = _bus.ControlBus.SubscribeInstance(consumerInstance);
		    _unsubscribeAction += _bus.ControlBus.SubscribeContextHandler<SubscriptionRefresh>(Consume);

		    _subscriptionEndpoint = _bus.GetEndpoint(subscriptionServiceUri);
		    _producer = new SubscriptionServiceMessageProducer(router, _subscriptionEndpoint);

			WaitForSubscriptionServiceResponse();
		}
コード例 #2
0
        public void SendMessage(WireSendingMessage message, IEndpoint endpoint)
        {
            TransportPipe pipe;
            var customEndpoint = (CustomTcpEndpoint) endpoint;
            if (!_endpointToPipe.TryGetValue(customEndpoint, out pipe))
            {
                pipe = new TcpTransportPipeMultiThread(3000000,
                                                           HighWaterMarkBehavior.Block,
                                                           customEndpoint.EndPoint,
                                                           _transport);
                _endpointToPipe.Add(customEndpoint, pipe);
            }
            var wait = default(SpinWait);
            var sent = false;
            bool first = true;
            var buffer = _serializer.Serialize(message.MessageData);
            do
            {
                sent = pipe.Send(new ArraySegment<byte>(buffer, 0, buffer.Length), true);
                if (!first)
                    wait.SpinOnce();
                else
                    first = false;
            } while (!sent && wait.Count < 1000);

            if (!sent) //peer is disconnected (or underwater from too many message), raise some event?
            {
                Console.WriteLine("AAAAG");
                _logger.Info(string.Format("disconnect of endpoint {0}", customEndpoint.EndPoint));
                EndpointDisconnected(endpoint);
                pipe.Dispose();
                _endpointToPipe.Remove(customEndpoint);
            }
        }
コード例 #3
0
ファイル: TcpSendEndpoint.cs プロジェクト: NiclasOlofsson/HIE
		public override void ProcessMessage(IEndpoint endpoint, byte[] data)
		{
			List<byte> package = new List<byte>();
			if (_client == null)
			{
				_client = new TcpClient();
				_client.Connect(_options.Endpoint);

				if (_options.SohDelimiters.Length > 0)
				{
					package.AddRange(_options.SohDelimiters);
				}
			}

			//TODO: If options mandate delimters, write STX and ETX here
			if (_options.StxDelimiters.Length > 0)
			{
				package.AddRange(_options.StxDelimiters);
			}

			package.AddRange(data);

			if (_options.EtxDelimiters.Length > 0)
			{
				package.AddRange(_options.EtxDelimiters);
			}

			Write(package.ToArray());

			if (!_options.KeepConnectionOpen)
			{
				CloseConnection();
			}
		}
コード例 #4
0
ファイル: RequestGraphTests.cs プロジェクト: UStack/UWeb
 public void SetUp()
 {
     endpoint = A.Fake<IEndpoint>();
     applicationEndpoints = new List<IEndpoint> { endpoint };
     findNextRequestChainPart = A.Fake<IFindNextRequestChainPart>();
     requestGraph = new RequestGraph(applicationEndpoints, findNextRequestChainPart);
 }
コード例 #5
0
        public IClient Create(IEndpoint endpoint, IClientPool ownerPool)
        {
            TSocket socket = null;
            TTransport transport = null;
            if (endpoint.Timeout == 0)
            {
                socket = new TSocket(endpoint.Address, endpoint.Port);
            }
            else
            {
                socket = new TSocket(endpoint.Address, endpoint.Port, endpoint.Timeout);
            }
            TcpClient tcpClient = socket.TcpClient;

            if (this.isBufferSizeSet)
            {
                transport = new TBufferedTransport(socket, this.bufferSize);
            }
            else
            {
                transport = new TBufferedTransport(socket);
            }

            TProtocol protocol = new TBinaryProtocol(transport);
            CassandraClient cassandraClient = new CassandraClient(protocol);
            IClient client = new DefaultClient() {
                CassandraClient = cassandraClient,
                Endpoint = endpoint,
                OwnerPool = ownerPool,
                TcpClient = tcpClient,
                Created = DateTime.Now
            };

            return client;
        }
コード例 #6
0
 public override void Bind(IEndpoint endpoint)
 {
     // TODO: ClearOldHeaders
     Open();
     safeChannel.Channel.QueueBind(endpoint.Name, name, endpoint.RoutingKey, endpoint.RoutingHeaders);
     Close();
 }
コード例 #7
0
        public IClient Create(IEndpoint endpoint, IClientPool ownerPool)
        {
            TSocket socket = null;
            if (endpoint.Timeout == 0)
            {
                socket = new TSocket(endpoint.Address, endpoint.Port);
            }
            else
            {
                socket = new TSocket(endpoint.Address, endpoint.Port, endpoint.Timeout);
            }
            TcpClient tcpClient = socket.TcpClient;
            TProtocol protocol = new TBinaryProtocol(socket);
            CassandraClient cassandraClient = new CassandraClient(protocol);
            IClient client = new DefaultClient()
            {
                CassandraClient = cassandraClient,
                Endpoint = endpoint,
                OwnerPool = ownerPool,
                TcpClient = tcpClient,
                Created = DateTime.Now
            };

            return client;
        }
コード例 #8
0
ファイル: Dispatcher.cs プロジェクト: EBojilova/CSharpHQC
 public string DispatchAction(IEndpoint endpoint)
 {
     switch (endpoint.ActionName)
     {
         case "RegisterUser":
             return this.ProcessRegisterUserCommand(endpoint.Parameters);
         case "LoginUser":
             return this.ProcessLoginUserCommand(endpoint.Parameters);
         case "LogoutUser":
             return this.ProcessLogoutUserCommand();
         case "CreateIssue":
             return this.ProcessCreateIssueCommand(endpoint.Parameters);
         case "RemoveIssue":
             return this.ProcessRemoveIssueCommand(endpoint.Parameters);
         case "AddComment":
             return this.ProcessAddCommentCommand(endpoint.Parameters);
         case "MyIssues":
             return this.ProcessMyIssuesCommand();
         case "MyComments":
             return this.ProcessMyCommentsCommand();
         case "Search":
             return this.ProcessSearchCommand(endpoint.Parameters);
         default:
             return string.Format(Messages.IvalidActionWithName, endpoint.ActionName);
     }
 }
コード例 #9
0
ファイル: SparkViewEngine.cs プロジェクト: UStack/UWeb
        public ViewEngineResult FindView(IEndpoint endpoint)
        {
            var templates = filterViewsCollection.FindTemplates(endpoint, FindAllTemplates()).ToList();

            if (templates.Count < 1) return null;

            if (templates.Count > 1)
                throw new UWebSparkException(
                    string.Format(
                        "More then one template was found for endpoint '{0}.{1}'.\nThe following templates were found: {2}",
                        endpoint.HandlerType.Name, endpoint.Method.Name,
                        string.Join(", ", templates.Select(x => x.Name))));

            var template = templates.Single();

            var descriptor = descriptorBuilder.BuildDescriptor(template, true, null, null);

            var sparkViewEntry = engine.CreateEntry(descriptor);

            var view = sparkViewEntry.CreateInstance() as UWebSparkView;

            if (view != null) view.ResolveDependencies = resolveDependencies;

            return new ViewEngineResult(view);
        }
コード例 #10
0
        private static object[] MapParameters(IEndpoint executionEndpoint, MethodInfo action)
        {
            var methodParams = action.GetParameters();

            var result = new object[methodParams.Length];

            int pos = 0;
            foreach (var param in methodParams)
            {
                object value = null;
                if (param.ParameterType == typeof(DateTime))
                {
                    value = DateTime.ParseExact(
                        executionEndpoint.Parameters[param.Name],
                        Constants.DateFormat,
                        CultureInfo.InvariantCulture);
                }
                else
                {
                    value = Convert.ChangeType(
                        executionEndpoint.Parameters[param.Name],
                        param.ParameterType);
                }

                result[pos++] = value;
            }

            return result;
        }
コード例 #11
0
 public ServiceHeartbeatMonitor(IEndpoint publisherEndpoint, IEndpoint subscriberEndpoint, MessageFormatType expectedMessageFormat)
     : this(publisherEndpoint, 
             subscriberEndpoint, 
             new SubscriptionsMsmqChannel(subscriberEndpoint, expectedMessageFormat), 
             new ServiceHeartbeatMsmqChannel(subscriberEndpoint, expectedMessageFormat))
 {
 }
コード例 #12
0
ファイル: Dispatcher.cs プロジェクト: ikolev94/Exercises
 public string DispatchAction(IEndpoint endpoint)
 {
     switch (endpoint.ActionName)
     {
         case "RegisterUser":
             return this.tracker.RegisterUser(
                 endpoint.Parameters["username"],
                 endpoint.Parameters["password"],
                 endpoint.Parameters["confirmPassword"]);
         case "LoginUser":
             return this.tracker.LoginUser(endpoint.Parameters["username"], endpoint.Parameters["password"]);
         case "CreateIssue":
             return this.tracker.CreateIssue(
                 endpoint.Parameters["title"],
                 endpoint.Parameters["description"],
                 (IssuePriority)Enum.Parse(typeof(IssuePriority), endpoint.Parameters["priority"], true),
                 endpoint.Parameters["tags"].Split('|'));
         case "RemoveIssue":
             return this.tracker.RemoveIssue(int.Parse(endpoint.Parameters["id"]));
         case "LogoutUser":
             return this.tracker.LogoutUser();
         case "AddComment":
             return this.tracker.AddComment(int.Parse(endpoint.Parameters["id"]), endpoint.Parameters["text"]);
         case "MyIssues":
             return this.tracker.GetMyIssues();
         case "MyComments":
             return this.tracker.GetMyComments();
         case "Search":
             return this.tracker.SearchForIssues(endpoint.Parameters["tags"].Split('|'));
         default:
             return string.Format("Invalid action: {0}", endpoint.ActionName);
     }
 }
コード例 #13
0
 /// <summary>
 /// Adds a named endpoint to the collection
 /// </summary>
 /// <param name="endpointName">The name of the endpoint</param>
 /// <param name="endpoint">The endpoint</param>
 /// <exception cref="ArgumentNullException">Thrown if <paramref name="endpointName"/>
 /// or <paramref name="endpoint"/> are <c>null</c></exception>
 /// <exception cref="EndpointAlreadyExistsException">Thrown if there is already an
 /// endpoint with the specified <paramref name="endpointName"/></exception>
 public void Add(EndpointName endpointName, IEndpoint endpoint)
 {
     if (endpointName == null) throw new ArgumentNullException("endpointName");
     if (endpoint == null) throw new ArgumentNullException("endpoint");
     if (_endpoints.ContainsKey(endpointName)) throw new EndpointAlreadyExistsException(endpointName);
     _endpoints[endpointName] = endpoint;
 }
コード例 #14
0
        private static object[] MapParameters(IEndpoint executionEndpoint, MethodInfo action)
        {
            var parameters = action
                             .GetParameters()
                             .Select<ParameterInfo, object>(p =>
            {
                if (p.ParameterType == typeof(int))
                {
                    return int.Parse(executionEndpoint.Parameters[p.Name]);
                }
                else if (p.ParameterType == typeof(DateTime))
                {
                    return DateTime.ParseExact(executionEndpoint.Parameters[p.Name], Constants.DateFormat, CultureInfo.InvariantCulture);
                } 
                else if (p.ParameterType == typeof(decimal))
                {
                    return decimal.Parse(executionEndpoint.Parameters[p.Name]);
                }
                else
                {
                    return executionEndpoint.Parameters[p.Name];
                }
            })
                             .ToArray();

            return parameters;
        }
コード例 #15
0
        public RedirectResult GetUrlToRedirectTo(object result, IEndpoint endpoint)
        {
            var redirectable = (IRedirectable) result;
            var redirectResult = redirectable.RedirectTo();

            return new RedirectResult(redirectResult.GetUrl(urlBuilder), redirectable.Permanent);
        }
コード例 #16
0
 public ShadowMessageCommand(MessageWireData message, PeerId primaryRecipient, bool primaryWasOnline, IEndpoint targetEndpoint)
 {
     Message = message;
     PrimaryRecipient = primaryRecipient;
     PrimaryWasOnline = primaryWasOnline;
     TargetEndpoint = targetEndpoint;
 }
コード例 #17
0
        public IMessageTopology Build(IEndpoint endpoint)
        {
            var topology = new MessageTopology();
            topology.PublishExchange = topology.DefineExchange(endpoint.Name, ExchangeType.Topic);

            return topology;
        }
コード例 #18
0
 public CompletionAcknowledgementMessage(Guid messageId, string messageType, bool processingSuccessful, IEndpoint endpoint)
 {
     MessageId = messageId;
     ProcessingSuccessful = processingSuccessful;
     Endpoint = endpoint;
     MessageType = messageType;
 }
コード例 #19
0
 public MessageSubscription(Type messageType, PeerId peer, IEndpoint endpoint, ISubscriptionFilter subscriptionFilter, ReliabilityLevel reliabilityLevel)
 {
     MessageType = messageType;
     Peer = peer;
     Endpoint = endpoint;
     SubscriptionFilter = (subscriptionFilter);
     ReliabilityLevel = reliabilityLevel;
 }
コード例 #20
0
        public void Render(object result, IEndpoint endpoint, IOutputWriter outputWriter, IRequest request)
        {
            var renderer = GetMatching(result, endpoint, request).FirstOrDefault();

            if(renderer == null) return;

            renderer.Render(result, endpoint, outputWriter);
        }
コード例 #21
0
 public void Save(IEndpoint endpoint)
 {
     var key = endpoint.Name.ToLower();
     if (Endpoints.ContainsKey(key))
         Endpoints[key] = endpoint;
     else
         Endpoints.Add(key, endpoint);
 }
コード例 #22
0
 public PipelineConsumerWork(IMessageProcessor processor, IEndpoint endpoint, ISerializer serializer, MessageThreshold messageThreshold, IEndpointCircuitBreaker circuitBreaker)
 {
     this.endpoint = endpoint;
     this.processor = processor;
     this.circuitBreaker = circuitBreaker;
     this.serializer = serializer;
     this.messageThreshold = messageThreshold ?? new MessageThreshold();
 }
コード例 #23
0
ファイル: AuthenticateEndpoint.cs プロジェクト: UStack/UWeb
 public AuthenticateEndpoint(IEndpoint endpoint, IAuthenticationRuleCollection authenticationRuleCollection, IAuthentication authentication, 
     IOutputWriter outputWriter)
 {
     this.endpoint = endpoint;
     this.authenticationRuleCollection = authenticationRuleCollection;
     this.authentication = authentication;
     this.outputWriter = outputWriter;
 }
コード例 #24
0
ファイル: RenderEndpointResult.cs プロジェクト: UStack/UWeb
 public RenderEndpointResult(IRenderEndpointResultCollection renderEndpointResultCollection, IEndpoint endpoint, IOutputWriter outputWriter, 
     IRequest currentRequest, IRequestBinder requestBinder)
 {
     this.renderEndpointResultCollection = renderEndpointResultCollection;
     this.endpoint = endpoint;
     this.outputWriter = outputWriter;
     this.currentRequest = currentRequest;
     this.requestBinder = requestBinder;
 }
コード例 #25
0
		public override void ProcessMessage(IEndpoint endpoint, byte[] data)
		{
			using (StreamWriter writer = new StreamWriter(_filePath, _append, _encoding))
			{
				writer.Write(Encoding.UTF8.GetString(data));
				writer.Close();
				MessageSent.Set();
			}
		}
コード例 #26
0
 public void Reinitialize(string messageType, PeerId peerId, Guid messageIdentity, IEndpoint endpoint, byte[] data, int? sequenceNumber)
 {
     PeerId = peerId;
     MessageIdentity = messageIdentity;
     MessageType = messageType;
     Data = data;
     SequenceNumber = sequenceNumber;
     Endpoint = endpoint;
 }
コード例 #27
0
        public ServiceNodePeer(IEndpoint controlEndpoint, IEndpoint serviceEndpoint, int pingTimeout)
        {
            ControlEndpoint = controlEndpoint;
            ServiceEndpoint = serviceEndpoint;
            _pingTimeout = pingTimeout;

            _cancel = new CancellationTokenSource();
            _composer = new TaskComposer<Peer>(_cancel.Token);
        }
コード例 #28
0
		public PostHandler(IEndpoint sagaRunner, [NotNull] IServiceBus bus)
		{
			if (sagaRunner == null) 
				throw new ArgumentNullException("sagaRunner");
			if (bus == null) throw new ArgumentNullException("bus");

			_sagaRunner = sagaRunner;
			_bus = bus;
		}
コード例 #29
0
ファイル: TopologyBuilder.cs プロジェクト: mzabolotko/Contour
        /// <summary>
        /// Создает временную конечную точку для получения сообщений.
        /// </summary>
        /// <param name="endpoint">Конечная точка шины сообщений для который создается подписка.</param>
        /// <param name="label">Метка сообщений, на которые ожидается получение ответа.</param>
        /// <returns>
        /// Конечная точка подписки для получения сообщений.
        /// </returns>
        public ISubscriptionEndpoint BuildTempReplyEndpoint(IEndpoint endpoint, MessageLabel label)
        {
            var queue = Queue.Named(string.Format("{0}.replies-{1}-{2}", endpoint.Address, label.IsAny ? "any" : label.Name, NameGenerator.GetRandomName(8)))
                .AutoDelete.Exclusive.Instance;

            this.rabbitChannel.Declare(queue);

            return new SubscriptionEndpoint(queue, new StaticRouteResolver(string.Empty, queue.Name));
        }
コード例 #30
0
 public ReceivedTransportMessage(string messageType, PeerId peerId, Guid messageIdentity, IEndpoint endpoint, byte[] data, int? sequenceNumber)
 {
     PeerId = peerId;
     MessageIdentity = messageIdentity;
     MessageType = messageType;
     Data = data;
     SequenceNumber = sequenceNumber;
     Endpoint = endpoint;
 }
コード例 #31
0
 public EndpointMessageSink(IEndpoint endpoint)
 {
     _endpoint = endpoint;
 }
コード例 #32
0
 public IOutboundRoutingConfiguration Add <TMessage>(IEndpoint endpoint, Type outboundConnectorType) =>
 Add(typeof(TMessage), endpoint, outboundConnectorType);
コード例 #33
0
 public TShapedNexus(IEndpoint connectToPoint1 = null, IEndpoint connectToPoint2 = null,
                     IEndpoint connectToPoint3 = null)
     : base(3, connectToPoint1, connectToPoint2, connectToPoint3)
 {
 }
コード例 #34
0
        private static string HandleRequest(IEndpoint <Links, string> endpoint, string requestUri, ILogger logger)
        {
            var result = endpoint.Invoke(requestUri);

            return(Serialize(result, logger));
        }
コード例 #35
0
 public EndpointMiddleware(IEndpoint <TResult> endpoint, IEnumerable <HttpMethod> allowedMethods = null, bool exactRequestPathMatching = true, ILogger logger = null)
     : this(allowedMethods, exactRequestPathMatching, logger)
 {
     _endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint));
 }
コード例 #36
0
        public void Send(IEndpoint endpoint, object message, Action <ISendContext> contextCallback)
        {
            var msg = message as TMessage;

            endpoint.Send(msg, context => contextCallback(context));
        }
コード例 #37
0
 public override bool OnWsConnecting(HttpRequest request, HttpResponse response)
 {
     _matchedEndpoint = _server._endpoints.Find(e => e.Matches(request));
     return(_matchedEndpoint != null);
 }
コード例 #38
0
 /// <summary>
 /// Pings the endpoint specified
 /// </summary>
 /// <param name="endpoint"></param>
 /// <param name="ct">Optional cancellation token to cancel pending request</param>
 /// <returns>HTTP error if there is a problem with the request, otherwise an
 /// empty <see cref="IPortalResponse"/> object if successful otherwise the Error property is populated</returns>
 public virtual Task <PortalResponse> Ping(IEndpoint endpoint, CancellationToken ct)
 {
     return(Get <PortalResponse>(endpoint, ct));
 }
コード例 #39
0
 public TestMiddleware2(IEndpoint <string, string> endpoint, IManagementOptions mgmtOptions, ILogger logger)
     : base(endpoint, mgmtOptions, logger: logger)
 {
 }
コード例 #40
0
 /// <summary>
 /// Pings the endpoint specified
 /// </summary>
 /// <param name="endpoint"></param>
 /// <param name="ct">Optional cancellation token to cancel pending request</param>
 /// <returns>HTTP error if there is a problem with the request, otherwise an
 /// empty <see cref="IPortalResponse"/> object if successful otherwise the Error property is populated</returns>
 public virtual Task <PortalResponse> Ping(IEndpoint endpoint, CancellationToken ct = default(CancellationToken))
 {
     return(Get <PortalResponse, ArcGISServerOperation>(new ArcGISServerOperation(endpoint), ct));
 }
コード例 #41
0
 public TestConsumer(IBroker broker, IEndpoint endpoint, IEnumerable <IConsumerBehavior> behaviors)
     : base(broker, endpoint, behaviors)
 {
 }
コード例 #42
0
 public void SetEndpoint(IEndpoint endpoint)
 {
     _context.SetEndpoint(endpoint);
 }
コード例 #43
0
 public GeocodeOperation(IEndpoint endpoint, Action beforeRequest = null, Action <string> afterRequest = null)
     : base(endpoint, beforeRequest, afterRequest)
 {
 }
コード例 #44
0
 public virtual Task <PortalResponse> Ping(IEndpoint endpoint)
 {
     return(Ping(endpoint, CancellationToken.None));
 }
コード例 #45
0
 public (string?Value1, string?Value2) GetAdditionalValues(
     IEndpoint endpoint,
     IReadOnlyCollection <MessageHeader>?headers,
     IBrokerMessageIdentifier?brokerMessageIdentifier) =>
 (null, null);
コード例 #46
0
 protected Task <T> Get <T>(IEndpoint endpoint, CancellationToken ct) where T : IPortalResponse
 {
     return(Get <T>(endpoint.BuildAbsoluteUrl(RootUrl), ct));
 }
コード例 #47
0
        public void Send(IEndpoint endpoint, object message)
        {
            var msg = message as TMessage;

            endpoint.Send(msg);
        }
コード例 #48
0
 public PartnerApiRequestBuilder WithEndpoint(IEndpoint value)
 {
     m_endpoint = value;
     return(this);
 }
コード例 #49
0
 /// <summary>
 /// Creates a new element collection endpoint.
 /// </summary>
 /// <param name="referrer">The endpoint used to navigate to this one.</param>
 /// <param name="relativeUri">The URI of this endpoint relative to the <paramref name="referrer"/>'s. Prefix <c>./</c> to append a trailing slash to the <paramref name="referrer"/> URI if missing.</param>
 public IndexerEndpoint(IEndpoint referrer, string relativeUri)
     : base(referrer, relativeUri)
 {
     SetupElementHandling();
 }
コード例 #50
0
 /// <summary>
 /// Create a new outgoing call to phones, SIP-enabled endpoints or Twilio Client connections
 /// </summary>
 ///
 /// <param name="to"> Phone number, SIP address or client identifier to call </param>
 /// <param name="from"> Twilio number from which to originate the call </param>
 /// <param name="pathAccountSid"> The account_sid </param>
 /// <param name="url"> Url from which to fetch TwiML </param>
 /// <param name="applicationSid"> ApplicationSid that configures from where to fetch TwiML </param>
 /// <param name="method"> HTTP method to use to fetch TwiML </param>
 /// <param name="fallbackUrl"> Fallback URL in case of error </param>
 /// <param name="fallbackMethod"> HTTP Method to use with FallbackUrl </param>
 /// <param name="statusCallback"> Status Callback URL </param>
 /// <param name="statusCallbackEvent"> The status_callback_event </param>
 /// <param name="statusCallbackMethod"> HTTP Method to use with StatusCallback </param>
 /// <param name="sendDigits"> Digits to send </param>
 /// <param name="ifMachine"> Action to take if a machine has answered the call </param>
 /// <param name="timeout"> Number of seconds to wait for an answer </param>
 /// <param name="record"> Whether or not to record the Call </param>
 /// <param name="recordingChannels"> The recording_channels </param>
 /// <param name="recordingStatusCallback"> The recording_status_callback </param>
 /// <param name="recordingStatusCallbackMethod"> The recording_status_callback_method </param>
 /// <param name="sipAuthUsername"> The sip_auth_username </param>
 /// <param name="sipAuthPassword"> The sip_auth_password </param>
 /// <param name="client"> Client to make requests to Twilio </param>
 /// <returns> Task that resolves to A single instance of Call </returns> 
 public static async System.Threading.Tasks.Task<CallResource> CreateAsync(IEndpoint to, Types.PhoneNumber from, string pathAccountSid = null, Uri url = null, string applicationSid = null, Twilio.Http.HttpMethod method = null, Uri fallbackUrl = null, Twilio.Http.HttpMethod fallbackMethod = null, Uri statusCallback = null, List<string> statusCallbackEvent = null, Twilio.Http.HttpMethod statusCallbackMethod = null, string sendDigits = null, string ifMachine = null, int? timeout = null, bool? record = null, string recordingChannels = null, string recordingStatusCallback = null, Twilio.Http.HttpMethod recordingStatusCallbackMethod = null, string sipAuthUsername = null, string sipAuthPassword = null, ITwilioRestClient client = null)
 {
     var options = new CreateCallOptions(to, from){PathAccountSid = pathAccountSid, Url = url, ApplicationSid = applicationSid, Method = method, FallbackUrl = fallbackUrl, FallbackMethod = fallbackMethod, StatusCallback = statusCallback, StatusCallbackEvent = statusCallbackEvent, StatusCallbackMethod = statusCallbackMethod, SendDigits = sendDigits, IfMachine = ifMachine, Timeout = timeout, Record = record, RecordingChannels = recordingChannels, RecordingStatusCallback = recordingStatusCallback, RecordingStatusCallbackMethod = recordingStatusCallbackMethod, SipAuthUsername = sipAuthUsername, SipAuthPassword = sipAuthPassword};
     return await CreateAsync(options, client);
 }
コード例 #51
0
 public OutboundRoute(Type messageType, IEndpoint destinationEndpoint, Type outboundConnectorType)
 {
     MessageType           = messageType;
     DestinationEndpoint   = destinationEndpoint;
     OutboundConnectorType = outboundConnectorType;
 }
コード例 #52
0
ファイル: Api.cs プロジェクト: segios/Poynt.NET
 public Api(PoyntSDK sdk, params string[] parents) : base(sdk, () => Constants.POYNT_API_HOST + EndpointConfig.Get <TModel>().Resolve(parents))
 {
     this.endPointRef = EndpointConfig.Get <TModel>();
 }
コード例 #53
0
        /// <summary>
        /// Sends a DELETE request to the given endpoint.
        /// </summary>
        internal async static Task <Response> Delete <T>(IEndpoint <T> endpoint)
        {
            if (endpoint == null)
            {
                throw new ArgumentNullException("Endpoint", "Endpoint should not be null.");
            }

            HttpResponseMessage httpResponse = null;
            Error  error      = null;
            string rawMessage = null;

            try
            {
                //application/x-www-form-urlencoded
                Requester.Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", endpoint.Arguments[0]);
                Requester.Client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*"));
                Requester.Client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("MojangSharp", "0.1"));

                httpResponse = await Requester.Client.DeleteAsync(endpoint.Address);

                rawMessage = await httpResponse.Content.ReadAsStringAsync();

                httpResponse.EnsureSuccessStatusCode();
            }
            catch (Exception ex)
            {
                if (httpResponse.StatusCode == HttpStatusCode.Unauthorized ||
                    httpResponse.StatusCode == HttpStatusCode.Forbidden)
                {
                    JObject err = JObject.Parse(rawMessage);
                    error = new Error()
                    {
                        ErrorMessage = err["errorMessage"].ToObject <string>(),
                        ErrorTag     = err["error"].ToObject <string>(),
                        Exception    = ex
                    };
                }
                else
                {
                    error = new Error()
                    {
                        ErrorMessage = ex.Message,
                        ErrorTag     = ex.GetBaseException().Message,
                        Exception    = ex
                    };
                }
            }

            return(new Response()
            {
                Code = httpResponse.StatusCode,
                RawMessage = rawMessage,
                IsSuccess = httpResponse.IsSuccessStatusCode && (
                    httpResponse.StatusCode == HttpStatusCode.Accepted ||
                    httpResponse.StatusCode == HttpStatusCode.Continue ||
                    httpResponse.StatusCode == HttpStatusCode.Created ||
                    httpResponse.StatusCode == HttpStatusCode.Found ||
                    httpResponse.StatusCode == HttpStatusCode.OK ||
                    httpResponse.StatusCode == HttpStatusCode.PartialContent) &&
                            error == null,
                Error = error
            });
        }
コード例 #54
0
ファイル: EndpointConfig.cs プロジェクト: segios/Poynt.NET
 public static void Register <T>(IEndpoint endpoint)
 {
     Endpoints[typeof(T)] = endpoint;
 }
コード例 #55
0
        protected async Task <T> Post <T>(IEndpoint endpoint, Dictionary <String, String> parameters, CancellationToken ct) where T : IPortalResponse
        {
            var url = endpoint.BuildAbsoluteUrl(RootUrl).Split('?').FirstOrDefault();

            var token = await CheckGenerateToken(ct);

            if (ct.IsCancellationRequested)
            {
                return(default(T));
            }

            // these should have already been added
            if (!parameters.ContainsKey("f"))
            {
                parameters.Add("f", "json");
            }
            if (!parameters.ContainsKey("token") && token != null && !String.IsNullOrWhiteSpace(token.Value))
            {
                parameters.Add("token", token.Value);
                _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(token.Value);
                if (token.AlwaysUseSsl)
                {
                    url = url.Replace("http:", "https:");
                }
            }

            HttpContent content = null;

            try
            {
                content = new FormUrlEncodedContent(parameters);
            }
            catch (FormatException)
            {
                var tempContent = new MultipartFormDataContent();
                foreach (var keyValuePair in parameters)
                {
                    tempContent.Add(new StringContent(keyValuePair.Value), keyValuePair.Key);
                }
                content = tempContent;
            }
            _httpClient.CancelPendingRequests();

            Uri  uri;
            bool validUrl = Uri.TryCreate(url, UriKind.Absolute, out uri);

            if (!validUrl)
            {
                throw new HttpRequestException(String.Format("Not a valid url: {0}", url));
            }

            System.Diagnostics.Debug.WriteLine(uri);
            String resultString = String.Empty;

            try
            {
                HttpResponseMessage response = await _httpClient.PostAsync(uri, content, ct);

                response.EnsureSuccessStatusCode();

                resultString = await response.Content.ReadAsStringAsync();
            }
            catch (TaskCanceledException cex)
            {
                System.Diagnostics.Debug.WriteLine(cex.ToString());
                return(default(T));
            }
            catch (HttpRequestException)
            {
                throw;
            }

            System.Diagnostics.Debug.WriteLine(resultString);
            var result = Serializer.AsPortalResponse <T>(resultString);

            if (result.Error != null)
            {
                throw new InvalidOperationException(result.Error.ToString());
            }

            return(result);
        }
コード例 #56
0
 public IOutboundRoutingConfiguration Add(Type messageType, IEndpoint endpoint, Type outboundConnectorType)
 {
     _routes.Add(new OutboundRoute(messageType, endpoint, outboundConnectorType));
     return(this);
 }
コード例 #57
0
 /// <summary>
 /// Connection details of API.
 /// </summary>
 /// <value>Details for connecting to an Endpoint.</value>
 public BaseClient(IEndpoint endpoint)
 {
     this.Endpoint = endpoint;
 }
コード例 #58
0
        /// <summary>
        /// Sends a PUT request to the given endpoint.
        /// </summary>
        internal async static Task <Response> Put <T>(IEndpoint <T> endpoint, Uri file)
        {
            if (endpoint == null)
            {
                throw new ArgumentNullException("Endpoint", "Endpoint should not be null.");
            }


            if (file == null || string.IsNullOrEmpty(file.ToString()))
            {
                throw new ArgumentNullException("Skin", "No file given.");
            }

            HttpResponseMessage httpResponse = null;
            Error  error      = null;
            string rawMessage = null;

            try
            {
                //application/x-www-form-urlencoded
                Requester.Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", endpoint.Arguments[0]);
                Requester.Client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*"));
                Requester.Client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("MojangSharp", "0.1"));

                using (var contents = new MultipartFormDataContent())
                {
                    contents.Add(new StringContent(bool.Parse(endpoint.Arguments[1]) == true ? "true" : "false"), "model");
                    using (WebClient wc = new WebClient()) {
                        contents.Add(new ByteArrayContent(wc.DownloadData(file)), "file", Path.GetFileName(file.ToString()));
                    }

                    httpResponse = await Requester.Client.PutAsync(endpoint.Address, contents);

                    rawMessage = await httpResponse.Content.ReadAsStringAsync();

                    httpResponse.EnsureSuccessStatusCode();
                }
            }
            catch (Exception ex)
            {
                if (httpResponse.StatusCode == HttpStatusCode.Unauthorized ||
                    httpResponse.StatusCode == HttpStatusCode.Forbidden)
                {
                    JObject err = JObject.Parse(rawMessage);
                    error = new Error()
                    {
                        ErrorMessage = err["errorMessage"].ToObject <string>(),
                        ErrorTag     = err["error"].ToObject <string>(),
                        Exception    = ex
                    };
                }
                else
                {
                    error = new Error()
                    {
                        ErrorMessage = ex.Message,
                        ErrorTag     = ex.GetBaseException().Message,
                        Exception    = ex
                    };
                }
            }

            return(new Response()
            {
                Code = httpResponse.StatusCode,
                RawMessage = rawMessage,
                IsSuccess = httpResponse.IsSuccessStatusCode && (
                    httpResponse.StatusCode == HttpStatusCode.Accepted ||
                    httpResponse.StatusCode == HttpStatusCode.Continue ||
                    httpResponse.StatusCode == HttpStatusCode.Created ||
                    httpResponse.StatusCode == HttpStatusCode.Found ||
                    httpResponse.StatusCode == HttpStatusCode.OK ||
                    httpResponse.StatusCode == HttpStatusCode.PartialContent) &&
                            error == null,
                Error = error
            });
        }
コード例 #59
0
        public override object ServiceMessage(IMessage message)
        {
            CommandMessage commandMessage = message as CommandMessage;

            if (commandMessage != null)
            {
                //Sub/unsub handled by base class
                return(base.ServiceMessage(commandMessage));
            }
            else
            {
                AsyncMessage responseMessage = null;
                DataMessage  dataMessage     = message as DataMessage;

                DataDestination dataDestination = this.GetDestination(dataMessage) as DataDestination;
                if (dataDestination.SubscriptionManager.GetSubscriber(dataMessage.clientId as string) == null)
                {
                    //Subscribe here as DS doesn't send a separate subscribe command
                    CommandMessage commandMessageSubscribe = new CommandMessage();
                    commandMessageSubscribe.destination = dataDestination.Id;
                    commandMessageSubscribe.operation   = CommandMessage.SubscribeOperation;
                    commandMessageSubscribe.clientId    = dataMessage.clientId as string;
                    string endpointId = dataMessage.GetHeader(MessageBase.EndpointHeader) as string;
                    commandMessageSubscribe.headers[MessageBase.EndpointHeader] = endpointId;
                    string flexClientIdHeader = dataMessage.GetHeader(MessageBase.FlexClientIdHeader) as string;
                    if (flexClientIdHeader != null)
                    {
                        commandMessageSubscribe.headers[MessageBase.FlexClientIdHeader] = flexClientIdHeader;
                    }
                    IEndpoint endpoint = GetMessageBroker().GetEndpoint(endpointId);
                    endpoint.ServiceMessage(commandMessageSubscribe);                    //route through the endpoint again
                    //base.ServiceMessage(commandMessageSubscribe);
                }

                switch (dataMessage.operation)
                {
                case DataMessage.FillOperation:
                    responseMessage = ExecuteFillOperation(message);
                    break;

                case DataMessage.GetOperation:
                    responseMessage = ExecuteGetOperation(message);
                    break;

                case DataMessage.BatchedOperation:
                case DataMessage.MultiBatchOperation:
                case DataMessage.TransactedOperation:
                    responseMessage = ExecuteMultiBatchOperation(message);
                    break;

                case DataMessage.PageItemsOperation:
                    responseMessage = ExecutePageItemsOperation(message);
                    break;

                case DataMessage.PageOperation:
                    responseMessage = ExecutePageOperation(message);
                    break;

                case DataMessage.ReleaseCollectionOperation:
                    responseMessage = ExecuteReleaseCollectionOperation(message);
                    break;

                case DataMessage.GetSequenceIdOperation:
                    responseMessage = ExecuteGetSequenceIdOperation(message);
                    break;

                case DataMessage.ReleaseItemOperation:
                    responseMessage = ExecuteReleaseItemOperation(message);
                    break;

                default:
                    if (log.IsErrorEnabled)
                    {
                        log.Error(__Res.GetString(__Res.DataService_Unknown, dataMessage.operation));
                    }

                    responseMessage = new AcknowledgeMessage();
                    break;
                }
                responseMessage.clientId      = message.clientId;
                responseMessage.correlationId = message.messageId;
                //Dump();
                return(responseMessage);
            }
        }
コード例 #60
0
ファイル: Form1.cs プロジェクト: anhnh14/Instagram
 public Form1(IEndpoint endPoint)
 {
     InitializeComponent();
     _endPoint = endPoint;
 }