public static void ReplyOverHttp(CommandResponse response)
        {
            var url = Configuration.ServantIoHost + "/client/response?installationGuid=" + Configuration.InstallationGuid + "&organizationId=" + Configuration.ServantIoKey;
            var wc = new WebClient();

            var result = wc.UploadValues(url, new NameValueCollection()
            {
                {"Message", response.Message},
                {"Guid", response.Guid.ToString()},
                {"Success", response.Success.ToString()},
                {"Type", response.Type.ToString()}
            });
        }
        public void GivenValidRequest_ExecuteRequest_Returns_ExpectedCommandResponse(string jsonResponse, CommandResponse expectedDeserializedResponse)
        {
            //Arrange
            IRestResponse restResponse = new RestResponse();

            restResponse.Content        = jsonResponse;
            restResponse.ResponseStatus = ResponseStatus.Completed;
            restResponse.StatusCode     = HttpStatusCode.OK;
            CommandSender commandSender = InitCommandSender(jsonResponse, restResponse);

            //Act
            var response = commandSender.ExecuteRequest <CommandResponse>("", new RestRequest());

            //Assert
            Assert.Equal(expectedDeserializedResponse.ErrorMessage, response.ErrorMessage);
            Assert.Equal(expectedDeserializedResponse.ErrorNumber, response.ErrorNumber);
            Assert.Equal(expectedDeserializedResponse.ClientTransactionID, response.ClientTransactionID);
            Assert.Equal(expectedDeserializedResponse.ServerTransactionID, response.ServerTransactionID);
        }
Beispiel #3
0
 public ICamera Command(CommandRequest <ICamera> command, out CommandResponse commandResponse,
                        bool checkStatus = true)
 {
     commandResponse = Command(command, checkStatus);
     return(this);
 }
Beispiel #4
0
 public CommandResultViewModel(CommandResponse response)
 {
     Status        = response.StatusCode;
     ScalarResults = response.ScalarResults;
     Links.Add(new LinkViewModel($"/api", "tables", string.Empty, string.Empty, string.Empty));
 }
 void IHandle <CommandResponse> .Handle(CommandResponse response)
 {
     Interlocked.Increment(ref _gotResponse);
 }
Beispiel #6
0
        internal override void Parse()
        {
            /*
             * <Images xmlns="http://schemas.microsoft.com/windowsazure" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
             *    <OSImage>
             *      <AffinityGroup>name-of-the-affinity-group</AffinityGroup>
             *      <Category>category-of-the-image</Category>
             *      <Label>image-description</Label>
             *      <Location>geo-location-of-the-stored-image</Location>
             *      <LogicalSizeInGB>size-of-the-image</LogicalSizeInGB>
             *      <MediaLink>url-of-the-containing-blob</MediaLink>
             *      <Name>image-name</Name>
             *      <OS>operating-system-of-the-image</OS>
             *      <Eula>image-eula</Eula>
             *      <Description>image-description</Description>
             *      <ImageFamily>image-family</ImageFamily>
             *      <ShowInGui>true|false</ShowInGui>
             *      <PublishedDate>published-date</PublishedDate>
             *      <IsPremium>true|false</IsPremium>
             *      <PrivacyUri>uri-of-privacy-policy</PrivacyUri>
             *      <RecommendedVMSize>size-of-the-virtual-machine</RecommendedVMSize>
             *      <PublisherName>publisher-identifier</PublisherName>
             *      <PricingDetailLink>pricing-details</PricingDetailLink>
             *      <SmallIconUri>uri-of-icon</SmallIconUri>
             *      <Language>language-of-image</Language>
             *    </OSImage>
             *    …
             *  </Images>*/
            IEnumerable <XElement> rootElements = Document.Element(GetSchema() + "Images")
                                                  .Elements(GetSchema() + "OSImage");

            foreach (XElement osDetail in rootElements)
            {
                //if (osDetail.Element(GetSchema() + "MediaLink") == null)
                //{
                //    continue;
                //}

                //if (osDetail.Element(GetSchema() + "MediaLink").Value == String.Empty)
                //{
                //    continue;
                //}

                if (osDetail.Element(GetSchema() + "ImageFamily") != null)
                {
                    if (osDetail.Element(GetSchema() + "ImageFamily").Value.Contains("RightScale"))
                    {
                        continue;
                    }
                }
                var imageProperties = new ImageProperties();
                // get the affinity group if it exists
                if (osDetail.Element(GetSchema() + "Description") != null)
                {
                    imageProperties.Description = osDetail.Element(GetSchema() + "Description").Value;
                }
                if (osDetail.Element(GetSchema() + "Name") != null)
                {
                    imageProperties.Name = osDetail.Element(GetSchema() + "Name").Value;
                }
                if (osDetail.Element(GetSchema() + "Label") != null)
                {
                    imageProperties.Label = osDetail.Element(GetSchema() + "Label").Value;
                }
                if (osDetail.Element(GetSchema() + "Eula") != null)
                {
                    imageProperties.Eula = osDetail.Element(GetSchema() + "Eula").Value;
                }
                if (osDetail.Element(GetSchema() + "ImageFamily") != null)
                {
                    imageProperties.ImageFamily = osDetail.Element(GetSchema() + "ImageFamily").Value;
                }
                if (osDetail.Element(GetSchema() + "IsPremium") != null)
                {
                    imageProperties.IsPremium = bool.Parse(osDetail.Element(GetSchema() + "IsPremium").Value);
                }
                if (osDetail.Element(GetSchema() + "ShowInGui") != null)
                {
                    imageProperties.ShowInGui = bool.Parse(osDetail.Element(GetSchema() + "ShowInGui").Value);
                }
                if (osDetail.Element(GetSchema() + "MediaLink") != null)
                {
                    imageProperties.MediaLink = osDetail.Element(GetSchema() + "MediaLink").Value;
                }
                if (osDetail.Element(GetSchema() + "OS") != null)
                {
                    imageProperties.OperatingSystem = (PlatformType)Enum.Parse(typeof(PlatformType), osDetail.Element(GetSchema() + "OS").Value);
                }
                if (osDetail.Element(GetSchema() + "PublishedDate") != null)
                {
                    imageProperties.PublishedDate = DateTime.Parse(osDetail.Element(GetSchema() + "PublishedDate").Value);
                }

                CommandResponse.Add(imageProperties);
            }
        }
Beispiel #7
0
        public static CommandResponse PostCommandRequest(CommandRequest request, string url = "http://localhost:8033/command")
        {
            bool isRetry = false;

            //Ok!
retry:
            try
            {
                {
                    HttpClient client = new HttpClient();
                    client.Timeout = TimeSpan.FromSeconds(15);
                    StringWriter wr = new StringWriter();
                    JsonSerializer.Create().Serialize(wr, request);
                    HttpContent content = new StringContent(wr.ToString());
                    content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");

                    var    task       = client.PostAsync(url, content).GetAwaiter().GetResult();
                    string jsonResult = task.Content.ReadAsStringAsync().GetAwaiter().GetResult();

                    return(JsonConvert.DeserializeObject <CommandResponse>(jsonResult, new JsonSerializerSettings()
                    {
                        StringEscapeHandling = StringEscapeHandling.EscapeNonAscii,
                        Formatting = Formatting.None
                    }));
                }
                isRetry = false;
            }
            catch (HttpRequestException httpRequestException)
            {
                if (httpRequestException.Message.Contains("target machine actively refused"))
                {
                }
                else if (httpRequestException.Message.Contains("An error occurred while sending the request"))
                {
                    Console.WriteLine("Failed to send request to " + url);
                    //Damn it.
                    if (!isRetry)
                    {
                        isRetry = true;
                        goto retry;
                    }
                    else
                    {
                        isRetry = false;
                    }
                }
                else if (httpRequestException.Message.Contains("established connection was aborted by the software in your host machine"))
                {
                    //Damn it.
                    if (!isRetry)
                    {
                        isRetry = true;
                        goto retry;
                    }
                    else
                    {
                        isRetry = false;
                    }
                }
                else
                {
                    Console.WriteLine(httpRequestException);
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception);
            }
            return(CommandResponse.Failed());
        }
Beispiel #8
0
        public void CommandComplete(Command c, CommandResponse cr)
        {
            c.Response = cr.Status;
            c.Result = cr.Result;
            c.TimestampResponse = DateTime.UtcNow;

            TulipContext.SaveChanges();

            switch (cr.Result)
            {
                case CommandResult.RESPONSE_OK:

                    break;

                case CommandResult.NO_COMMS:
                    // set point state

                    break;

                case CommandResult.TIMEOUT:
                    // set point state
                    break;
            }

            // TODO: set point state for different results
        }
Beispiel #9
0
        public async Task <CommandResponse <Order> > ExecuteAsync(CreateOrderCommand command, CommandResponse <Order> previousResult)
        {
            _logger.LogInformation("Creating order for user {0} from basket", command.AuthenticatedUserId);
            try
            {
                ShoppingCart.Model.ShoppingCart cart = (await _dispatcher.DispatchAsync(new GetCartQuery {
                    AuthenticatedUserId = command.AuthenticatedUserId
                })).Result;
                if (cart.Items.Count == 0)
                {
                    return(new CommandResponse <Order> {
                        ErrorMessage = "Shopping cart must not be empty to checkout", IsSuccess = false
                    });
                }
                Order order = new Order
                {
                    Id           = Guid.NewGuid(),
                    CreatedAtUtc = DateTime.UtcNow,
                    OrderItems   = cart.Items.Select(x => new OrderItem
                    {
                        Name      = x.Product.Name,
                        Price     = x.Product.Price,
                        ProductId = x.Product.Id,
                        Quantity  = x.Quantity
                    }).ToArray(),
                    PaymentMade = false,
                    PercentageDiscountApplied = 10.0,
                    UserId = command.AuthenticatedUserId
                };
                order.Total = order.OrderItems.Sum(i => i.Price * i.Quantity) * (100 - order.PercentageDiscountApplied) / 100.0;
                await _repository.CreateAsync(order);

                _logger.LogInformation("Created order for user {0} from basket", command.AuthenticatedUserId);
                return(CommandResponse <Order> .Ok(order));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Unable to create order for user {0}", command.AuthenticatedUserId);
                throw new CheckoutException($"Unable to create order for user {command.AuthenticatedUserId}");
            }
        }
 public void Send(CommandResponse response, Update update, bool edit = false)
 {
     Send(response, update.Message, edit);
 }
Beispiel #11
0
 public async Task <CommandResponse <StoreProduct> > ExecuteAsync(GetStoreProductQuery command, CommandResponse <StoreProduct> previousResult)
 {
     return(CommandResponse <StoreProduct> .Ok(await _repository.GetAsync(command.ProductId)));
 }
 public CommandResponseEventArgs(CommandResponse response)
 {
     Response = response;
 }
        public string processCommands(JObject json)
        {
            string response = "";
            List<CommandResult> results = new List<CommandResult>();

            if (json["commands"].GetType() == typeof(Newtonsoft.Json.Linq.JArray))
            {
                JArray commands = (JArray)json["commands"];
                foreach (JObject command in commands)
                {
                    var type = Type.GetType("SteelCityAutomatonCommands." + (string)command["command"]);
                    if (type != null)
                    {
                        AutomatonCommand cmd = (AutomatonCommand)Activator.CreateInstance(type);
                        cmd.Setup(command);
                        if (Client != null) cmd.Excecute(this, Client, false);
                        else cmd.result.message = "Client Not Yet initialized";
                        results.Add(cmd.result);
                    }
                    else
                    {
                        CommandResult result = new CommandResult((string)command["command"]);
                        result.success = false;
                        result.data = "unrecognized command";
                        results.Add(result);
            /*
            #if DEBUG
                        Console.WriteLine("CMD NOT RECOGNIZED - {0} : {1}", command["command"], "null");
            #endif
            */
                    }
                }
                CommandResponse resp = new CommandResponse((string)json["label"], results);
                response = resp.serialise();
            }
            return response;
        }
Beispiel #14
0
        /// <summary>
        /// The on access denied.
        /// </summary>
        /// <returns>
        /// The <see cref="IEnumerable{CommandResponse}"/>.
        /// </returns>
        protected virtual IEnumerable<CommandResponse> OnAccessDenied()
        {
            var response = new CommandResponse
                               {
                                   Destination = CommandResponseDestination.PrivateMessage,
                                   Message = this.MessageService.RetrieveMessage(Messages.OnAccessDenied, this.CommandSource, null)
                               };

            return response.ToEnumerable();
        }
        public async Task <CommandResponse <Model.ShoppingCart> > ExecuteAsync(GetCartQuery command, CommandResponse <Model.ShoppingCart> previousResult)
        {
            _logger.LogInformation("Getting basket for user {0}", command.AuthenticatedUserId);
            try
            {
                Model.ShoppingCart cart = await _repository.GetActualOrDefaultAsync(command.AuthenticatedUserId);

                _logger.LogInformation("Retrieved cart for user {0} with {1} items", command.AuthenticatedUserId, cart.Items.Count);
                return(CommandResponse <Model.ShoppingCart> .Ok(cart));
            }
            catch (Exception e)
            {
                _logger.LogError(e, "Unable to get basket for user {0}", command.AuthenticatedUserId);
                return(CommandResponse <Model.ShoppingCart> .WithError("Unable to get basket"));
            }
        }
Beispiel #16
0
        public async Task <CommandResponse <Model.ShoppingCart> > ExecuteAsync(GetCartQuery command, CommandResponse <Model.ShoppingCart> previousResult)
        {
            Model.ShoppingCart cart = await _repository.GetActualOrDefaultAsync(command.AuthenticatedUserId);

            return(CommandResponse <Model.ShoppingCart> .Ok(cart));
        }
Beispiel #17
0
        public Task <Result <CommandResponse> > ExecuteAsync(OperationContext context, CommandRequest request)
        {
            return(context.PerformOperationAsync(Tracer, async() =>
            {
                var requestAsBytes = _serializationPool.Serialize(request, (value, writer) => value.Serialize(writer));
                var requestAsProto = new Grpc.Request()
                {
                    Request_ = Google.Protobuf.ByteString.CopyFrom((byte[])requestAsBytes),
                };

                var callOptions = new CallOptions()
                                  .WithCancellationToken(context.Token)
                                  .WithHeaders(new Metadata()
                {
                    { "X-Cache-Client-Version", "0.0" },
                    { "X-Cache-Operation-Id", context.TracingContext.TraceId },
                });

                Contract.AssertNotNull(_client);
                var asyncUnaryCall = _client.ExecuteAsync(requestAsProto, callOptions);

                Grpc.Reply responseAsProto = await asyncUnaryCall;
                var responseAsBytes = responseAsProto.Reply_.ToByteArray();
                var response = _serializationPool.Deserialize(responseAsBytes, reader => CommandResponse.Deserialize(reader));
                Contract.AssertNotNull(response);

                return new Result <CommandResponse>(response);
            }, traceErrorsOnly: true));
        }
        public void SetUp()
        {
            _createSomething          = new CreateSomething();
            _createSomethingConcrete  = new CreateSomething();
            _somethingCreated         = new SomethingCreated();
            _somethingCreatedConcrete = new SomethingCreated();
            _events = new List <IEvent> {
                _somethingCreated
            };

            _createAggregate          = new CreateAggregate();
            _createAggregateConcrete  = new CreateAggregate();
            _aggregateCreatedConcrete = new AggregateCreated();
            _aggregate        = new Aggregate();
            _aggregateCreated = (AggregateCreated)_aggregate.Events[0];

            _sampleCommandSequence     = new SampleCommandSequence();
            _commandInSequenceConcrete = new CommandInSequence();

            _commandResponse = new CommandResponse {
                Events = _events, Result = "Result"
            };
            _domainCommandResponse = new CommandResponse {
                Events = _aggregate.Events, Result = "Result"
            };

            _eventPublisher = new Mock <IEventPublisher>();
            _eventPublisher
            .Setup(x => x.PublishAsync(_aggregateCreatedConcrete))
            .Returns(Task.CompletedTask);

            _storeProvider = new Mock <IStoreProvider>();
            _storeProvider
            .Setup(x => x.SaveAsync(It.IsAny <SaveStoreData>()))
            .Callback <SaveStoreData>(x => _storeDataSaved = x)
            .Returns(Task.CompletedTask);

            _objectFactory = new Mock <IObjectFactory>();
            _objectFactory
            .Setup(x => x.CreateConcreteObject(_somethingCreated))
            .Returns(_somethingCreatedConcrete);
            _objectFactory
            .Setup(x => x.CreateConcreteObject(_aggregateCreated))
            .Returns(_aggregateCreatedConcrete);
            _objectFactory
            .Setup(x => x.CreateConcreteObject(_createSomething))
            .Returns(_createSomethingConcrete);
            _objectFactory
            .Setup(x => x.CreateConcreteObject(_createAggregate))
            .Returns(_createAggregateConcrete);
            _objectFactory
            .Setup(x => x.CreateConcreteObject(It.IsAny <CommandInSequence>()))
            .Returns(_commandInSequenceConcrete);

            _validationService = new Mock <IValidationService>();
            _validationService
            .Setup(x => x.ValidateAsync(It.IsAny <CreateSomething>()))
            .Returns(Task.CompletedTask);

            _commandHandlerAsync = new Mock <ICommandHandlerAsync <CreateSomething> >();
            _commandHandlerAsync
            .Setup(x => x.HandleAsync(_createSomethingConcrete))
            .ReturnsAsync(_commandResponse);

            _domainCommandHandlerAsync = new Mock <ICommandHandlerAsync <CreateAggregate> >();
            _domainCommandHandlerAsync
            .Setup(x => x.HandleAsync(_createAggregate))
            .ReturnsAsync(_domainCommandResponse);
            _domainCommandHandlerAsync
            .Setup(x => x.HandleAsync(_createAggregateConcrete))
            .ReturnsAsync(_domainCommandResponse);

            _sequenceCommandHandlerAsync = new Mock <ISequenceCommandHandlerAsync <CommandInSequence> >();
            _sequenceCommandHandlerAsync
            .Setup(x => x.HandleAsync(It.IsAny <CommandInSequence>(), It.IsAny <CommandResponse>()))
            .ReturnsAsync(_commandResponse);

            _handlerResolver = new Mock <IHandlerResolver>();
            _handlerResolver
            .Setup(x => x.ResolveHandler <ICommandHandlerAsync <CreateSomething> >())
            .Returns(_commandHandlerAsync.Object);
            _handlerResolver
            .Setup(x => x.ResolveHandler <ICommandHandlerAsync <CreateAggregate> >())
            .Returns(_domainCommandHandlerAsync.Object);
            _handlerResolver
            .Setup(x => x.ResolveHandler <ISequenceCommandHandlerAsync <CommandInSequence> >())
            .Returns(_sequenceCommandHandlerAsync.Object);

            _mainOptionsMock = new Mock <IOptions <MainOptions> >();
            _mainOptionsMock
            .Setup(x => x.Value)
            .Returns(new MainOptions());

            _validationOptionsMock = new Mock <IOptions <ValidationOptions> >();
            _validationOptionsMock
            .Setup(x => x.Value)
            .Returns(new ValidationOptions());

            _sut = new CommandSender(_handlerResolver.Object,
                                     _eventPublisher.Object,
                                     _objectFactory.Object,
                                     _storeProvider.Object,
                                     _validationService.Object,
                                     _mainOptionsMock.Object,
                                     _validationOptionsMock.Object);
        }
        protected override void RunJob(Job job)
        {
            CommandResponse response = null;

            if (EnsurePortIsOpen())
            {
                _port.DiscardInBuffer();
                requestIndex++;
                try
                {
                    if (_logJobs)
                    {
                        Log.WriteLine("[{0:0000}] SERIAL: [{1}] Sending command", requestIndex, job.Command);
                    }
                    _port.Write(job.Command);
                }
                catch (Exception ex)
                {
                    Log.WriteLine("[{0:0000}] SERIAL: [{1}] Failed to send command. {2}", requestIndex, job.Command, ex.Message);
                    job.OnFulFilled(new CommandResponse(string.Empty, false, $"Unable to write to {_portName}. " + ex.Message));
                    return;
                }

                try
                {
                    switch (job.ResponseType)
                    {
                    case ResponseType.NoResponse:
                    {
                        if (_logJobs)
                        {
                            Log.WriteLine("[{0:0000}] SERIAL: [{1}] No response needed for command", requestIndex, job.Command);
                        }
                        response = new CommandResponse(string.Empty, true);
                    }
                    break;

                    case ResponseType.DigitResponse:
                    {
                        if (_logJobs)
                        {
                            Log.WriteLine("[{0:0000}] SERIAL: [{1}] Expecting single digit response for command, waiting...", requestIndex, job.Command);
                        }
                        string responseStr = new string((char)_port.ReadChar(), 1);
                        if (_logJobs)
                        {
                            Log.WriteLine("[{0:0000}] SERIAL: [{1}] Received single digit response '{2}' for command", requestIndex, job.Command, responseStr);
                        }
                        response = new CommandResponse(responseStr, true);
                    }
                    break;

                    case ResponseType.FullResponse:
                    {
                        if (_logJobs)
                        {
                            Log.WriteLine("[{0:0000}] SERIAL: [{1}] Expecting #-delimited response for Command, waiting...", requestIndex, job.Command);
                        }
                        string responseStr = _port.ReadTo("#");
                        if (_logJobs)
                        {
                            Log.WriteLine("[{0:0000}] SERIAL: [{1}] Received response '{2}' for command", requestIndex, job.Command, responseStr);
                        }
                        response = new CommandResponse(responseStr, true);
                    }
                    break;

                    case ResponseType.DoubleFullResponse:
                    {
                        if (_logJobs)
                        {
                            Log.WriteLine("[{0:0000}] SERIAL: [{1}] Expecting two #-delimited responses for Command, waiting for first...", requestIndex, job.Command);
                        }
                        string responseStr = _port.ReadTo("#");
                        if (_logJobs)
                        {
                            Log.WriteLine("[{0:0000}] SERIAL: [{1}] Received first response '{2}' for command", requestIndex, job.Command, responseStr);
                        }
                        response    = new CommandResponse(responseStr, true);
                        responseStr = _port.ReadTo("#");
                        if (_logJobs)
                        {
                            Log.WriteLine("[{0:0000}] SERIAL: [{1}] Received second response '{2}' for command, ignoring", requestIndex, job.Command, responseStr);
                        }
                    }
                    break;
                    }
                }
                catch (Exception ex)
                {
                    Log.WriteLine("[{0:0000}] SERIAL: [{1}] Failed to receive response to command. {2}", requestIndex, job.Command, ex.Message);
                    response = new CommandResponse(string.Empty, false, $"Unable to read response to {job.Command} from {_portName}. {ex.Message}");
                    _port.Close();
                }
            }
            else
            {
                Log.WriteLine("[{0:0000}] SERIAL: Failed to open port {1}", requestIndex, _portName);
                response = new CommandResponse(string.Empty, false, $"Unable to open {_portName}");
            }

            job.OnFulFilled(response);
        }
Beispiel #20
0
 /// <summary>
 ///  Enqueue a command and block until completed
 /// </summary>
 /// <param name="command"></param>
 /// <param name="response"></param>
 /// <param name="responseTimeout"></param>
 /// <param name="ackTimeout"></param>
 /// <returns>Command returned success</returns>
 public bool TrySend(
     Command command,
     out CommandResponse response,
     TimeSpan?responseTimeout = null,
     TimeSpan?ackTimeout      = null)
 => _queuedPublisher.TrySend(command, out response, responseTimeout, ackTimeout);
Beispiel #21
0
            /// <summary>
            /// Received the specified connected command.
            /// </summary>
            /// <param name="response">The response.</param>
            /// <returns><see langword="true"/> if the response is complete; otherwise <see langword="false"/>.</returns>
            public bool Received([NotNull] Response response)
            {
                if (response == null)
                {
                    throw new ArgumentNullException("response");
                }

                IObserver <Response> observer = _observer;

                if (observer == null)
                {
                    return(true);
                }
                bool      complete = false;
                Exception error    = null;

                try
                {
                    lock (_oooResponses)
                    {
                        CommandResponse commandResponse = response as CommandResponse;
                        if (commandResponse == null)
                        {
                            observer.OnNext(response);
                            complete = true;
                            return(true);
                        }
                        int sequence = commandResponse.Sequence;

                        if (sequence != _expectedSequence)
                        {
                            if (sequence < 0)
                            {
                                complete = true;
                                if (_oooResponses.Count > 0)
                                {
                                    // Suppress actual completion/error, as we received out of order messages.
                                    error =
                                        new ApplicationException(
                                            ClientResources.Err_ConnectedCommand_Received_MissingSequenceElements);
                                    return(true);
                                }

                                if (sequence == -1)
                                {
                                    observer.OnNext(response);
                                }
                                else
                                {
                                    error = new ApplicationException(((CommandResponse)response).Chunk);
                                }
                                return(true);
                            }

                            if (sequence < _expectedSequence)
                            {
                                Log.Add(
                                    LoggingLevel.Warning,
                                    () => ClientResources.Wrn_ConnectedCommand_Received_DuplicateSequence);
                                return(false);
                            }

                            LinkedListNode <CommandResponse> current = _oooResponses.First;
                            while (current != null &&
                                   // ReSharper disable once PossibleNullReferenceException
                                   current.Value.Sequence < sequence)
                            {
                                current = current.Next;
                            }

                            if (current == null)
                            {
                                _oooResponses.AddLast(commandResponse);
                            }
                            // ReSharper disable once PossibleNullReferenceException
                            else if (current.Value.Sequence < sequence)
                            {
                                _oooResponses.AddAfter(current, commandResponse);
                            }
                            else
                            {
                                _oooResponses.AddBefore(current, commandResponse);
                            }
                        }
                        else
                        {
                            observer.OnNext(response);
                            _expectedSequence++;
                            while (_oooResponses.First != null &&
                                   // ReSharper disable once PossibleNullReferenceException
                                   _oooResponses.First.Value.Sequence == _expectedSequence)
                            {
                                observer.OnNext(_oooResponses.First.Value);
                                _expectedSequence++;
                                _oooResponses.RemoveFirst();
                            }
                        }
                    }
                }
                catch
                {
                    complete = true;
                }
                finally
                {
                    if (complete)
                    {
                        _observer = null;
                        TaskCompletionSource <bool> cts = Interlocked.Exchange(ref _completionTask, null);
                        if (cts != null)
                        {
                            cts.TrySetResult(true);
                        }

                        if (error != null)
                        {
                            observer.OnError(error);
                        }
                        else
                        {
                            observer.OnCompleted();
                        }
                    }
                }
                return(complete);
            }
        public static IEnumerable <Pair <NetworkFileSystemEntry, string> > ReadEntries(Func <string> readNextLine)
        {
            string               currentFile     = null;
            NodeType             currentNodeType = null;
            AttributesEnumerable attributesEnumerable;
            ValueBox <string>    currentLine = new ValueBox <string>();

            Predicate <string> isAttributeLine = delegate(string s)
            {
                return(s[0] == ' ');
            };

            currentLine.Value = readNextLine();

            try
            {
                for (; ;)
                {
                    currentFile     = null;
                    currentNodeType = null;

                    if (currentLine.Value.StartsWith(ResponseCodes.RESPONSE_MARKER, StringComparison.CurrentCultureIgnoreCase))
                    {
                        if (currentLine.Value.EqualsIgnoreCase(ResponseCodes.READY))
                        {
                            break;
                        }
                        else if (currentLine.Value.StartsWith(ResponseCodes.ERROR, StringComparison.CurrentCultureIgnoreCase))
                        {
                            yield return(new Pair <NetworkFileSystemEntry, string>
                                         (
                                             new NetworkFileSystemEntry(),
                                             currentLine.Value
                                         ));

                            yield break;
                        }
                        else if (currentLine.Value.StartsWith(ResponseCodes.ENCODING))
                        {
                            string value = null, encoding = "url";

                            currentLine.Value = currentLine.Value.Substring(ResponseCodes.ENCODING.Length);

                            foreach (KeyValuePair <string, string> keyValuePair in CommandResponse.ParseTupleString(currentLine.Value))
                            {
                                if (keyValuePair.Key == "value")
                                {
                                    value = keyValuePair.Value;
                                }
                                else if (keyValuePair.Key == "encoding")
                                {
                                    encoding = keyValuePair.Key;
                                }
                                else if (keyValuePair.Key == "type")
                                {
                                    currentNodeType = GetNodeType(keyValuePair.Value);
                                }
                            }

                            if (value == null || currentNodeType == null)
                            {
                                AttributesEnumerable.ConsumeAttributes(readNextLine, currentLine, isAttributeLine);

                                continue;
                            }

                            try
                            {
                                currentFile = ProtocolTypes.DecodeString(value, encoding);
                            }
                            catch (NotSupportedException)
                            {
                                AttributesEnumerable.ConsumeAttributes(readNextLine, currentLine, isAttributeLine);

                                continue;
                            }
                        }
                        else
                        {
                            // Major error

                            throw new TextNetworkProtocolException();
                        }
                    }

                    if (currentLine.Value.Length == 0)
                    {
                        continue;
                    }

                    if (currentFile == null)
                    {
                        Pair <string, string> result;

                        result          = currentLine.Value.SplitAroundFirstCharFromLeft(':');
                        currentFile     = TextConversion.FromEscapedHexString(result.Right);
                        currentNodeType = GetNodeType(result.Left);
                    }

                    if (currentNodeType == null)
                    {
                        AttributesEnumerable.ConsumeAttributes(readNextLine, currentLine, isAttributeLine);

                        continue;
                    }

                    attributesEnumerable = new AttributesEnumerable
                                           (
                        readNextLine,
                        isAttributeLine,
                        currentLine
                                           );

                    try
                    {
                        yield return(new Pair <NetworkFileSystemEntry, string>
                                     (
                                         new NetworkFileSystemEntry(currentFile, currentNodeType, attributesEnumerable),
                                         null
                                     ));
                    }
                    finally
                    {
                        attributesEnumerable.Finish();
                    }
                }
            }
            finally
            {
                while (!currentLine.Value.StartsWith(ResponseCodes.READY))
                {
                    currentLine.Value = readNextLine();
                }
            }
        }
Beispiel #23
0
        void manager_UnhandledEvent(object sender, ManagerEvent e)
        {
            log.Debug("New unhandled event received: " + e.GetType().Name);
            LineControl lc = null;

            //StateServer
            switch (e.GetType().Name)
            {
            case "AGIExecEvent":
                AGIExecEvent agievent = e as AGIExecEvent;
                break;

            case "AlarmClearEvent":
                AlarmClearEvent alarmclear = e as AlarmClearEvent;
                break;

            case "AlarmEvent":
                AlarmEvent alarmevent = e as AlarmEvent;
                break;

            case "AsyncAGIEvent":
                AsyncAGIEvent asyncagievent = e as AsyncAGIEvent;
                break;

            case "BridgeEvent":
                BridgeEvent bridgeevent = e as BridgeEvent;
                break;

            case "CdrEvent":
                CdrEvent cdrevent = e as CdrEvent;
                break;

            case "ChannelReloadEvent":
                ChannelReloadEvent channelreload = e as ChannelReloadEvent;
                break;

            case "ChannelUpdateEvent":
                ChannelUpdateEvent channelupdate = e as ChannelUpdateEvent;
                break;

            case "ConnectEvent":
                ConnectEvent connectevent = e as ConnectEvent;
                break;

            case "ConnectionStateEvent":
                ConnectionStateEvent connectionstate = e as ConnectionStateEvent;
                break;

            case "DBGetResponseEvent":
                DBGetResponseEvent dbget = e as DBGetResponseEvent;
                log.Debug("DBGet response: " + dbget.ToString());
                switch (dbget.Family)
                {
                case "DND":
                    ss.SetLineControl(setLineControlDND(dbget.Key, true));
                    break;

                case "CF":
                    ss.SetLineControl(setLineControlForward(dbget.Key, dbget.Val));
                    break;
                }
                break;

            case "DialEvent":
                DialEvent dial = e as DialEvent;
                log.Debug("Dial event: " + dial.ToString());
                break;

            case "DisconnectEvent":
                DisconnectEvent disconnect = e as DisconnectEvent;
                log.Debug("Disconnect event: " + disconnect.ToString());
                break;

            case "DNDStateEvent":
                DNDStateEvent dndstate = e as DNDStateEvent;
                log.Debug("DND state event: " + dndstate.ToString());
                break;

            case "ExtensionStatusEvent":
                ExtensionStatusEvent extensionstatus = e as ExtensionStatusEvent;
                log.Debug("Extension status event: " + extensionstatus.ToString() + ", status: " + extensionstatus.Status + ", hint: " + extensionstatus.Hint);
                ss.SetLineControl(getLineControlFromExtensionStatusEvent(extensionstatus));
                break;

            case "FaxReceivedEvent":
                FaxReceivedEvent faxreceived = e as FaxReceivedEvent;
                break;

            case "HangupEvent":
                HangupEvent hangup = e as HangupEvent;
                log.Debug("Hangup event: " + hangup.ToString() + " callerid: " + hangup.CallerId + " calleridnum: " + hangup.CallerIdNum);
                //line control
                if (channels.Contains(hangup.Channel))
                {
                    lc = getLineControl((string)channels[hangup.Channel]);
                    int hi = 0;
                    LineControlConnection[] newLCC = null;
                    if (lc.lineControlConnection.Length > 1)
                    {
                        newLCC = new LineControlConnection[lc.lineControlConnection.Length - 1];
                        foreach (LineControlConnection hlcc in lc.lineControlConnection)
                        {
                            if (hlcc.callid != hangup.Channel)
                            {
                                newLCC[hi] = hlcc;
                                hi++;
                            }
                        }
                    }
                    lc.lineControlConnection = newLCC;
                    ss.SetLineControl(lc);
                    channels.Remove(hangup.Channel);
                }

                //missed calls
                callToFind = hangup.UniqueId.Substring(0, 6) + "," + hangup.UniqueId.Substring(6);
                Call mCall = missedCalls.Find(FindCall);
                if (mCall != null)
                {
                    log.Debug("Missed call finded for callid: " + hangup.UniqueId);
                    AddCallLogs(mCall.callee, mCall);
                    if (missedCalls.Remove(mCall))
                    {
                        log.Debug("Call " + mCall.callId + " successfully removed from missedcall cache");
                    }
                    else
                    {
                        log.Debug("Call " + mCall.callId + " cannot be removed from missedcall cache");
                    }
                }
                break;

            case "HoldedCallEvent":
                HoldedCallEvent holdedcall = e as HoldedCallEvent;
                break;

            case "HoldEvent":
                HoldEvent holdevent = e as HoldEvent;
                break;

            case "JabberEvent":
                JabberEvent jabberevent = e as JabberEvent;
                break;

            case "JitterBufStatsEvent":
                JitterBufStatsEvent jitter = e as JitterBufStatsEvent;
                break;

            case "JoinEvent":
                JoinEvent join = e as JoinEvent;
                break;

            case "LeaveEvent":
                LeaveEvent leave = e as LeaveEvent;
                break;

            case "LinkEvent":
                LinkEvent link = e as LinkEvent;
                log.Debug("Link event: " + link.ToString());
                lc = getLineControl(link.CallerId1);
                if (lc != null)
                {
                    foreach (LineControlConnection linklcc in lc.lineControlConnection)
                    {
                        if (linklcc.callid == link.Channel1)
                        {
                            linklcc.contact = link.CallerId2;
                            ss.SetLineControl(lc);
                            break;
                        }
                    }
                }
                lc = getLineControl(link.CallerId2);
                if (lc != null)
                {
                    foreach (LineControlConnection linklcc in lc.lineControlConnection)
                    {
                        if (linklcc.callid == link.Channel2)
                        {
                            linklcc.contact = link.CallerId1;
                            ss.SetLineControl(lc);
                            break;
                        }
                    }
                }
                break;

            case "LogChannelEvent":
                LogChannelEvent logchannel = e as LogChannelEvent;
                break;

            case "ManagerEvent":
                ManagerEvent managerevent = e;
                break;

            case "MeetmeEndEvent":
                MeetmeEndEvent meetmeend = e as MeetmeEndEvent;
                break;

            case "MeetmeJoinEvent":
                MeetmeJoinEvent meetmejoin = e as MeetmeJoinEvent;
                break;

            case "MeetmeLeaveEvent":
                MeetmeLeaveEvent meetmeleave = e as MeetmeLeaveEvent;
                break;

            case "MeetmeMuteEvent":
                MeetmeMuteEvent meetmemute = e as MeetmeMuteEvent;
                break;

            case "MeetmeStopTalkingEvent":
                MeetmeStopTalkingEvent meetmestoptalking = e as MeetmeStopTalkingEvent;
                break;

            case "MeetmeTalkingEvent":
                MeetmeTalkingEvent meetmetalking = e as MeetmeTalkingEvent;
                break;

            case "MeetmeTalkRequestEvent":
                MeetmeTalkRequestEvent meetmetalkrequest = e as MeetmeTalkRequestEvent;
                break;

            case "MessageWaitingEvent":
                MessageWaitingEvent messagewaiting = e as MessageWaitingEvent;
                log.Debug("Message waiting event: " + messagewaiting.ToString());
                lc = getLineControl(messagewaiting.Mailbox.Substring(0, messagewaiting.Mailbox.IndexOf("@")));
                if (lc != null)
                {
                    if (messagewaiting.Waiting > 0)
                    {
                        lc.mwiOn = true;
                    }
                    else
                    {
                        lc.mwiOn = false;
                    }
                    ss.SetLineControl(lc);
                }
                break;

            case "MobileStatusEvent":
                MobileStatusEvent mobilestatus = e as MobileStatusEvent;
                break;

            case "ModuleLoadReportEvent":
                ModuleLoadReportEvent moduleload = e as ModuleLoadReportEvent;
                break;

            case "MonitorStartEvent":
                MonitorStartEvent monitorstart = e as MonitorStartEvent;
                break;

            case "MonitorStopEvent":
                MonitorStopEvent monitorstop = e as MonitorStopEvent;
                break;

            case "NewAccountCodeEvent":
                NewAccountCodeEvent newaccountcode = e as NewAccountCodeEvent;
                break;

            case "NewCallerIdEvent":
                NewCallerIdEvent newcallerid = e as NewCallerIdEvent;
                log.Debug("New caller id envent: " + newcallerid.ToString());
                break;

            case "NewChannelEvent":
                NewChannelEvent newchannel = e as NewChannelEvent;
                log.Debug("New Channel event: " + newchannel.ToString());
                CommandAction   ca = new CommandAction("core show channel " + newchannel.Channel);
                CommandResponse cr = (CommandResponse)manager.SendAction(ca, 10000);
                log.Debug("Channel info: " + cr.ToString());
                string dn = newchannel.CallerIdNum;
                log.Debug("Retreive call information...");
                bool callerIdUnknown = true;
                if (newchannel.CallerIdNum != "<unknown>")
                {
                    callerIdUnknown = false;
                }
                else
                {
                    foreach (string s in cr.Result)
                    {
                        if (s.Contains("Caller ID:"))
                        {
                            dn = s.Substring(s.LastIndexOf(" "));
                            break;
                        }
                    }
                }
                Call newOutboundCall = getOutboundCallFromChannelInfo(cr.Result, callerIdUnknown);
                if (newOutboundCall != null)
                {
                    Call missedCall = newOutboundCall;
                    AddCallLogs(dn, newOutboundCall);
                    dnToFind = newOutboundCall.callee;
                    if (linecontrols.Find(FindLineControl) != null)
                    {
                        log.Debug("This call will be put in missedcall cache: " + missedCall.callId);
                        missedCall.type = CallType.missed;
                        missedCalls.Add(missedCall);
                    }
                }
                break;

            case "NewExtenEvent":
                NewExtenEvent newexten = e as NewExtenEvent;
                log.Debug("New exten event: " + newexten.ToString());
                string   channel      = "";
                char[]   splitter     = { '/' };
                string[] splitchannel = newexten.Channel.Split(splitter);
                splitter[0]  = '-';
                splitchannel = splitchannel[1].Split(splitter);
                channel      = splitchannel[0];
                //DND?
                if (newexten.Extension == Properties.Settings.Default.FeatureCodeDNDToggle && newexten.Application == "Playback")
                {
                    switch (newexten.AppData)
                    {
                    case "do-not-disturb&activated":
                        log.Debug("Successfully activate dnd for channel: " + channel);
                        ss.SetLineControl(setLineControlDND(channel, true));
                        break;

                    case "do-not-disturb&de-activated":
                        log.Debug("Successfully deactivate dnd for channel: " + channel);
                        ss.SetLineControl(setLineControlDND(channel, false));
                        break;
                    }
                }
                //Forward all?
                else if (newexten.Extension.Contains(Properties.Settings.Default.FeatureCodeCallForwardAllActivate) && newexten.Application == "Playback" && newexten.AppData == "call-fwd-unconditional&for&extension")
                {
                    string forward = newexten.Extension.Substring(Properties.Settings.Default.FeatureCodeCallForwardAllActivate.Length);
                    log.Debug("Call forward all from channel: " + channel + " to " + forward);
                    ss.SetLineControl(setLineControlForward(channel, forward));
                }
                // UnForwardAll
                else if (newexten.Extension == Properties.Settings.Default.FeatureCodeCallForwardAllDeactivate && newexten.Application == "Playback" && newexten.AppData == "call-fwd-unconditional&de-activated")
                {
                    log.Debug("Call unforward all from channel: " + channel);
                    ss.SetLineControl(setLineControlForward(channel, ""));
                }
                break;

            case "NewStateEvent":
                NewStateEvent newstate = e as NewStateEvent;
                log.Debug("New State event: " + newstate.ToString());
                LineControl             newstateLc   = getLineControl(newstate.CallerId);
                LineControlConnection[] newStateLccs = null;
                int i = 0;
                if (newstateLc.lineControlConnection != null)
                {
                    bool isContained = false;
                    foreach (LineControlConnection elcc in newstateLc.lineControlConnection)
                    {
                        if (elcc.callid == newstate.Channel)
                        {
                            isContained  = true;
                            newStateLccs = newstateLc.lineControlConnection;
                            break;
                        }
                        i++;
                    }
                    if (!isContained)
                    {
                        i            = 0;
                        newStateLccs = new LineControlConnection[newstateLc.lineControlConnection.Length + 1];
                        foreach (LineControlConnection newstateLcc in newstateLc.lineControlConnection)
                        {
                            newStateLccs[i] = newstateLcc;
                            i++;
                        }
                    }
                }
                else
                {
                    newStateLccs    = new LineControlConnection[1];
                    newStateLccs[0] = new LineControlConnection();
                }
                try
                {
                    switch (newstate.State)
                    {
                    case "Up":
                        //received call?
                        callToFind = newstate.UniqueId;
                        Call rCall = missedCalls.Find(FindCall);
                        if (rCall != null)
                        {
                            log.Debug("Missed call finded: " + callToFind + ", this call will be received");
                            rCall.type = CallType.received;
                            AddCallLogs(rCall.callee, rCall);
                            missedCalls.Remove(rCall);
                        }
                        if (newStateLccs != null)
                        {
                            if (!channels.Contains(newstate.Channel))
                            {
                                channels.Add(newstate.Channel, newstate.CallerId);
                            }
                            newStateLccs[i].callid        = newstate.Channel;
                            newStateLccs[i].remoteState   = Wybecom.TalkPortal.CTI.Proxy.ConnectionState.established;
                            newStateLccs[i].state         = Wybecom.TalkPortal.CTI.Proxy.ConnectionState.established;
                            newStateLccs[i].terminalState = TerminalState.talking;
                        }
                        break;

                    case "Ringing":
                        if (newStateLccs != null)
                        {
                            if (!channels.Contains(newstate.Channel))
                            {
                                channels.Add(newstate.Channel, newstate.CallerId);
                            }
                            newStateLccs[i].callid        = newstate.Channel;
                            newStateLccs[i].remoteState   = Wybecom.TalkPortal.CTI.Proxy.ConnectionState.established;
                            newStateLccs[i].state         = Wybecom.TalkPortal.CTI.Proxy.ConnectionState.alerting;
                            newStateLccs[i].terminalState = TerminalState.ringing;
                        }
                        break;

                    case "Ring":
                        if (newStateLccs != null)
                        {
                            if (!channels.Contains(newstate.Channel))
                            {
                                channels.Add(newstate.Channel, newstate.CallerId);
                            }
                            newStateLccs[i].callid        = newstate.Channel;
                            newStateLccs[i].remoteState   = Wybecom.TalkPortal.CTI.Proxy.ConnectionState.alerting;
                            newStateLccs[i].state         = Wybecom.TalkPortal.CTI.Proxy.ConnectionState.dialing;
                            newStateLccs[i].terminalState = TerminalState.inuse;
                        }
                        break;
                    }
                }
                catch (Exception stateException)
                {
                    log.Debug("NewState exception: " + stateException.Message);
                }
                if (newstateLc != null)
                {
                    newstateLc.lineControlConnection = newStateLccs;
                    ss.SetLineControl(newstateLc);
                }
                break;

            case "OriginateResponseEvent":
                OriginateResponseEvent originateresponse = e as OriginateResponseEvent;
                break;

            case "ParkedCallEvent":
                ParkedCallEvent parkedcall = e as ParkedCallEvent;
                break;

            case "ParkedCallGiveUpEvent":
                ParkedCallGiveUpEvent parkedcallgiveup = e as ParkedCallGiveUpEvent;
                break;

            case "ParkedCallsCompleteEvent":
                ParkedCallsCompleteEvent parkedcallscomplete = e as ParkedCallsCompleteEvent;
                break;

            case "ParkedCallTimeOutEvent":
                ParkedCallTimeOutEvent parkedcalltimeout = e as ParkedCallTimeOutEvent;
                break;

            case "PeerEntryEvent":
                log.Debug("SipAction: one peer entry event received, " + e.ToString());
                PeerEntryEvent peerentry = e as PeerEntryEvent;
                peers.Add(peerentry);
                ss.SetLineControl(getLineControlFromPeerEntry(peerentry));
                break;

            case "PeerlistCompleteEvent":
                log.Debug("SipAction: peer list completed " + e.ToString());
                PeerlistCompleteEvent peerlistcomplete = e as PeerlistCompleteEvent;
                acs.setPeers(peers);
                break;

            case "PeerStatusEvent":
                PeerStatusEvent peerstatus = e as PeerStatusEvent;
                log.Debug("Peer status: " + peerstatus.ToString());
                break;

            case "PRIEvent":
                PRIEvent pri = e as PRIEvent;
                break;

            case "RegistryEvent":
                RegistryEvent registry = e as RegistryEvent;
                break;

            case "ReloadEvent":
                ReloadEvent reload = e as ReloadEvent;
                break;

            case "RenameEvent":
                RenameEvent rename = e as RenameEvent;
                break;

            case "ResponseEvent":
                ResponseEvent response = e as ResponseEvent;
                break;

            case "RTCPReceivedEvent":
                RTCPReceivedEvent rtcpreceived = e as RTCPReceivedEvent;
                break;

            case "RTCPSentEvent":
                RTCPSentEvent rtcpsent = e as RTCPSentEvent;
                break;

            case "RTPReceiverStatEvent":
                RTPReceiverStatEvent rtpreceiver = e as RTPReceiverStatEvent;
                break;

            case "RTPSenderStatEvent":
                RTPSenderStatEvent rtpsender = e as RTPSenderStatEvent;
                break;

            case "ShowDialPlanCompleteEvent":
                ShowDialPlanCompleteEvent showdialplan = e as ShowDialPlanCompleteEvent;
                break;

            case "ShutdownEvent":
                ShutdownEvent shutdown = e as ShutdownEvent;
                break;

            case "StatusCompleteEvent":
                StatusCompleteEvent statuscomplete = e as StatusCompleteEvent;
                break;

            case "StatusEvent":
                StatusEvent status = e as StatusEvent;
                break;

            case "TransferEvent":
                TransferEvent transfer = e as TransferEvent;
                break;

            case "UnholdEvent":
                UnholdEvent unhold = e as UnholdEvent;
                break;

            case "UnknownEvent":
                UnknownEvent unknown = e as UnknownEvent;
                break;

            case "UnlinkEvent":
                UnlinkEvent unlink = e as UnlinkEvent;
                log.Debug("Unlink event : " + unlink.ToString());
                LineControlConnection[] lccs = null;
                i  = 0;
                lc = getLineControl(unlink.CallerId1);
                if (lc != null)
                {
                    if (lc.lineControlConnection.Length > 1)
                    {
                        lccs = new LineControlConnection[lc.lineControlConnection.Length - 1];
                        foreach (LineControlConnection linklcc in lc.lineControlConnection)
                        {
                            if (linklcc.callid != unlink.Channel1)
                            {
                                lccs[i] = linklcc;
                                i++;
                                break;
                            }
                        }
                    }
                    else
                    {
                        lc.lineControlConnection = null;
                    }
                    ss.SetLineControl(lc);
                }
                i  = 0;
                lc = getLineControl(unlink.CallerId2);
                if (lc != null)
                {
                    if (lc.lineControlConnection.Length > 1)
                    {
                        lccs = new LineControlConnection[lc.lineControlConnection.Length - 1];
                        foreach (LineControlConnection linklcc in lc.lineControlConnection)
                        {
                            if (linklcc.callid != unlink.Channel2)
                            {
                                lccs[i] = linklcc;
                                i++;
                                break;
                            }
                        }
                    }
                    else
                    {
                        lc.lineControlConnection = null;
                    }
                    ss.SetLineControl(lc);
                }
                break;

            case "UnparkedCallEvent":
                UnparkedCallEvent unparked = e as UnparkedCallEvent;
                break;

            case "UserEvent":
                UserEvent user = e as UserEvent;
                break;

            case "VarSetEvent":
                VarSetEvent varset = e as VarSetEvent;
                break;

            case "ZapShowChannelsCompleteEvent":
                ZapShowChannelsCompleteEvent zapshowchannelscomplete = e as ZapShowChannelsCompleteEvent;
                break;

            case "ZapShowChannelsEvent":
                ZapShowChannelsEvent zapshowchannels = e as ZapShowChannelsEvent;
                break;
            }
            //ACDConnector
            switch (e.GetType().Name)
            {
            case "AgentCallbackLoginEvent":
                AgentCallbackLoginEvent agentcallbacklogin = e as AgentCallbackLoginEvent;
                break;

            case "AgentCallbackLogoffEvent":
                AgentCallbackLogoffEvent agentcallbacklogoff = e as AgentCallbackLogoffEvent;
                break;

            case "AgentCalledEvent":
                AgentCalledEvent agentcalled = e as AgentCalledEvent;
                break;

            case "AgentCompleteEvent":
                AgentCompleteEvent agentcomplete = e as AgentCompleteEvent;
                break;

            case "AgentConnectEvent":
                AgentConnectEvent agentconnect = e as AgentConnectEvent;
                break;

            case "AgentDumpEvent":
                AgentDumpEvent agentdump = e as AgentDumpEvent;
                break;

            case "AgentLoginEvent":
                AgentLoginEvent agentlogin = e as AgentLoginEvent;
                break;

            case "AgentLogoffEvent":
                AgentLogoffEvent agentlogoff = e as AgentLogoffEvent;
                break;

            case "AgentsCompleteEvent":
                AgentsCompleteEvent agentscomplete = e as AgentsCompleteEvent;
                break;

            case "AgentsEvent":
                AgentsEvent agentevent = e as AgentsEvent;
                break;

            case "QueueCallerAbandonEvent":
                QueueCallerAbandonEvent queuecallerabandon = e as QueueCallerAbandonEvent;
                break;

            case "QueueEntryEvent":
                QueueEntryEvent queueentry = e as QueueEntryEvent;
                break;

            case "QueueEvent":
                QueueEvent queue = e as QueueEvent;
                break;

            case "QueueMemberEvent":
                QueueMemberEvent queuemember = e as QueueMemberEvent;
                break;

            case "QueueMemberPausedEvent":
                QueueMemberPausedEvent queuememberpaused = e as QueueMemberPausedEvent;
                break;

            case "QueueMemberPenaltyEvent":
                QueueMemberPenaltyEvent queuememberpenalty = e as QueueMemberPenaltyEvent;
                break;

            case "QueueMemberRemovedEvent":
                QueueMemberRemovedEvent queuememberremoved = e as QueueMemberRemovedEvent;
                break;

            case "QueueMemberStatusEvent":
                QueueMemberStatusEvent queuememberstatus = e as QueueMemberStatusEvent;
                break;

            case "QueueParamsEvent":
                QueueParamsEvent queueparams = e as QueueParamsEvent;
                break;

            case "QueueStatusCompleteEvent":
                QueueStatusCompleteEvent queuestatuscomplete = e as QueueStatusCompleteEvent;
                break;
            }
        }
Beispiel #24
0
        public CommandResponse ParseCommand()
        {
            var message = new StringBuilder();

            if (string.IsNullOrWhiteSpace(_resource))
            {
                return CommandResponse.Set(false, $"The Resource OPTION is missing. All requests require a Resource type to be specified.");
            }

            message.AppendLine("Resource: " + _resource);
            message.AppendLine("Format: " + _format);

            if (_headers == null || !_headers.Any())
            {
                return CommandResponse.Set(false, $"All requests requires the setheaders option.");
            }

            if (!ValidMethods.Contains(_method))
            {
                return CommandResponse.Set(false, $"The Method {_method} is invalid.");
            }

            if (_method == "get" || _method == "delete" || _method == "put")
            {
                if (_parameters == null || !_parameters.Any())
                {
                    return CommandResponse.Set(false, $"The Parameters OPTION is missing or invalid. The GET, PUT and DELETE method requires parameters.");
                }

                message.AppendLine("Parameters: " + _parameters);
            }

            if ((_method == "put" || _method == "post"))
            {
                if (!string.IsNullOrWhiteSpace(_body))
                {
                    try
                    {
                        _pointerBody = JsonConvert.DeserializeObject<NrlsPointerBody>(_body);
                    }
                    catch(Exception ex)
                    {
                        return CommandResponse.Set(false, $"The Body OPTION is invalid. Exception Message: {ex.Message}");
                    }

                }
                else if (!string.IsNullOrWhiteSpace(_input))
                {
                    var inputLocation = GetInputLocation();

                    if (inputLocation == null)
                    {
                        return CommandResponse.Set(false, $"The Input OPTION is invalid. See --help for more details.");
                    }
                    else
                    {
                        if (!inputLocation.Success)
                        {
                            return inputLocation;
                        }

                        try
                        {
                            var jsonParser = new FhirJsonParser();
                            var pointer = File.ReadAllText(inputLocation.Result);
                            _pointer = jsonParser.Parse<DocumentReference>(pointer);
                        }
                        catch(Exception ex)
                        {
                            return CommandResponse.Set(false, $"Error trying to parse input. Exception Message: {ex.Message}");
                        }
                        
                       
                    }
                }
                else
                {
                    return CommandResponse.Set(false, $"Both the Body OPTION and the Input OPTION are missing. PUT and POST methods require at least one.");
                }
            }

            ////not for beta
            //if (_method == "put")
            //{
            //    //its now a parameter
            //    if (string.IsNullOrWhiteSpace(_uniqueId))
            //    {
            //        return CommandResponse.Set(false, $"The id OPTION is missing. PUT methods require a id.");
            //    }

            //    message.AppendLine("id: " + _uniqueId);
            //}

            return CommandResponse.Set(true, message.ToString());
        }
Beispiel #25
0
 public CommandResponseEventArgs(CommandResponse response)
 {
     Response = response;
 }
 public IProcessResponse <string> Process(ProcessExecutionResult response)
 {
     Response = response.ToResponse(true, string.Empty, $"ExitCode={response.ExitCode}");
     return(this);
 }
Beispiel #27
0
    private IEnumerator ExecCapture()
    {
        string json;

        // start session
        json = "{ \"name\": \"camera.startSession\", \"parameters\": { } }";
        yield return(ExecCommand("/osc/commands/execute", json));

        if (_resultJson == null)
        {
            yield break;
        }

        // set API version
        ResStartSession res_start_session = LitJson.JsonMapper.ToObject <ResStartSession>(_resultJson);

        string version = "1";

        _sessionId = res_start_session.results.sessionId;
        json       = "{\"name\": \"camera.setOptions\", \"parameters\": { \"sessionId\": \"" + _sessionId + "\", \"options\": { \"clientVersion\": " + version + "} } }";
        yield return(ExecCommand("/osc/commands/execute", json));

        // get pre-state
        json = "{}";
        yield return(ExecCommand("/osc/state", json));

        // update property
        StateFinger res_state_finger = LitJson.JsonMapper.ToObject <StateFinger>(_resultJson);

        /*
         * json = "{\"name\": \"camera.getOptions\", \"parameters\": { \"optionNames\": [\"fileFormat\",\"fileFormatSupport\"]}}";
         * yield return ExecCommand("/osc/commands/execute", json);
         *
         * OptionRoot option = LitJson.JsonMapper.ToObject<OptionRoot>(_resultJson);
         *
         * json = "{\"name\": \"camera.setOptions\",\"parameters\": {\"options\": {\"fileFormat\": {\"type\": \"jpeg\",\"width\": 2048,\"height\": 1024}}}}";
         * yield return ExecCommand("/osc/commands/execute", json);
         *
         * OptionRoot option2 = LitJson.JsonMapper.ToObject<OptionRoot>(_resultJson);
         *
         * json = "{\"name\": \"camera.getOptions\", \"parameters\": { \"optionNames\": [\"fileFormat\",\"fileFormatSupport\"]}}";
         * yield return ExecCommand("/osc/commands/execute", json);
         *
         * OptionRoot option3 = LitJson.JsonMapper.ToObject<OptionRoot>(_resultJson);
         *
         */

        // take picture
        json = "{\"name\": \"camera.takePicture\", \"parameters\": {\"sessionId\": \"" + _sessionId + "\"}}";
        yield return(ExecCommand("/osc/commands/execute", json));

        CommandResponse res_takepicture = LitJson.JsonMapper.ToObject <CommandResponse>(_resultJson);

        CommandResponse res_takepicture2 = null;

        for (int i = 0; i < 600; i++)
        {
            json = "{\"id\": \"" + res_takepicture.id + "\"}";
            yield return(ExecCommand("/osc/commands/status", json));

            res_takepicture2 = LitJson.JsonMapper.ToObject <CommandResponse>(_resultJson);
            if (res_takepicture2.results != null)
            {
                break;
            }

            yield return(new WaitForSeconds(1.1f));
        }

        if (res_takepicture2 == null || res_takepicture2.results == null)
        {
            yield break;
        }
        // get pre-state
        json = "{\"name\":\"camera.getImage\", \"parameters\": {\"fileUri\": \"" + res_takepicture2.results.fileUri + "\"}}";
        yield return(ExecCommand("/osc/commands/execute", json));

        string pth = res_takepicture2.results.fileUri;

#if UNITY_EDITOR
        string base_path = Directory.GetCurrentDirectory();
#else
        string base_path = Application.persistentDataPath;
#endif

        string path = base_path + "/" + pth.Substring(pth.LastIndexOf('/') + 1);
        Debug.Log(path);

        File.WriteAllBytes(path, _resultBytes);

        Texture2D texture = new Texture2D(7776, 3888);
        texture.LoadImage(_resultBytes);

        if (_sphereMaterial.mainTexture != null)
        {
            MonoBehaviour.Destroy(_sphereMaterial.mainTexture);
        }
        _sphereMaterial.mainTexture = texture;

        _captureButton.gameObject.SetActive(true);
        _closeButton.gameObject.SetActive(true);
    }
Beispiel #28
0
 public virtual T Request <T>(object arguments, Server server, out CommandResponse commandResponse,
                              ProxyRequestType requestType = ProxyRequestType.Xml)
 {
     return(ProxyManager.Request <T>(CommandName, server, arguments, out commandResponse, requestType: requestType));
 }
Beispiel #29
0
        private static void checkManagerAPI()
        {
            manager = new ManagerConnection(ASTERISK_HOST, ASTERISK_PORT, ASTERISK_LOGINNAME, ASTERISK_LOGINPWD);

            // Register user event class
            manager.RegisterUserEventClass(typeof(UserAgentLoginEvent));

            // Add or Remove events
            manager.UserEvents += new UserEventHandler(dam_UserEvents);

            // Dont't display this event
            manager.NewExten += new NewExtenEventHandler(manager_IgnoreEvent);

            // Display all other
            manager.UnhandledEvent += new ManagerEventHandler(dam_Events);

            // +++ Only to debug purpose
            manager.FireAllEvents = true;
            // manager.DefaultEventTimeout = 0;
            // manager.DefaultResponseTimeout = 0;
            manager.PingInterval = 0;
            // +++
            try
            {
                manager.Login();                                        // Login only (fast)

                Console.WriteLine("Asterisk version : " + manager.Version);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                Console.ReadLine();
                manager.Logoff();
                return;
            }

            {
                Console.WriteLine("\nGetConfig action");
                ManagerResponse response = manager.SendAction(new GetConfigAction("manager.conf"));
                if (response.IsSuccess())
                {
                    GetConfigResponse responseConfig = (GetConfigResponse)response;
                    foreach (int key in responseConfig.Categories.Keys)
                    {
                        Console.WriteLine(string.Format("{0}:{1}", key, responseConfig.Categories[key]));
                        foreach (int keyLine in responseConfig.Lines(key).Keys)
                        {
                            Console.WriteLine(string.Format("\t{0}:{1}", keyLine, responseConfig.Lines(key)[keyLine]));
                        }
                    }
                }
                else
                {
                    Console.WriteLine(response);
                }
            }

            {
                Console.WriteLine("\nUpdateConfig action");
                UpdateConfigAction config = new UpdateConfigAction("manager.conf", "manager.conf");
                config.AddCommand(UpdateConfigAction.ACTION_NEWCAT, "testadmin");
                config.AddCommand(UpdateConfigAction.ACTION_APPEND, "testadmin", "secret", "blabla");
                ManagerResponse response = manager.SendAction(config);
                Console.WriteLine(response);
            }

            // Originate call example
            Console.WriteLine("\nPress ENTER key to originate call.\n"
                              + "Start phone (or connect) or make a call to see events.\n"
                              + "After all events press a key to originate call.");
            Console.ReadLine();

            OriginateAction oc = new OriginateAction();

            oc.Context  = ORIGINATE_CONTEXT;
            oc.Priority = "1";
            oc.Channel  = ORIGINATE_CHANNEL;
            oc.CallerId = ORIGINATE_CALLERID;
            oc.Exten    = ORIGINATE_EXTEN;
            oc.Timeout  = ORIGINATE_TIMEOUT;
            // oc.Variable = "VAR1=abc|VAR2=def";
            // oc.SetVariable("VAR3", "ghi");
            ManagerResponse originateResponse = manager.SendAction(oc, oc.Timeout);

            Console.WriteLine("Response:");
            Console.WriteLine(originateResponse);

            Console.WriteLine("Press ENTER key to next test.");
            Console.ReadLine();

            //
            // Display result of Show Queues command
            //
            {
                CommandAction   command  = new CommandAction();
                CommandResponse response = new CommandResponse();
                if (manager.AsteriskVersion == AsteriskVersion.ASTERISK_1_6)
                {
                    command.Command = "queue show";
                }
                else
                {
                    command.Command = "show queues";
                }
                try
                {
                    response = (CommandResponse)manager.SendAction(command);
                    Console.WriteLine("Result of " + command.Command);
                    foreach (string str in response.Result)
                    {
                        Console.WriteLine("\t" + str);
                    }
                }
                catch (Exception err)
                {
                    Console.WriteLine("Response error: " + err);
                }
                Console.WriteLine("Press ENTER to next test or CTRL-C to exit.");
                Console.ReadLine();
            }
            //
            // Display Queues and Members
            //
            ResponseEvents re;

            try
            {
                re = manager.SendEventGeneratingAction(new QueueStatusAction());
            }
            catch (EventTimeoutException e)
            {
                // this happens with Asterisk 1.0.x as it doesn't send a QueueStatusCompleteEvent
                re = e.PartialResult;
            }

            foreach (ManagerEvent e in re.Events)
            {
                if (e is QueueParamsEvent)
                {
                    QueueParamsEvent qe = (QueueParamsEvent)e;
                    Console.WriteLine("QueueParamsEvent" + "\n\tQueue:\t\t" + qe.Queue + "\n\tServiceLevel:\t" + qe.ServiceLevel);
                }
                else if (e is QueueMemberEvent)
                {
                    QueueMemberEvent qme = (QueueMemberEvent)e;
                    Console.WriteLine("QueueMemberEvent" + "\n\tQueue:\t\t" + qme.Queue + "\n\tLocation:\t" + qme.Location);
                }
                else if (e is QueueEntryEvent)
                {
                    QueueEntryEvent qee = (QueueEntryEvent)e;
                    Console.WriteLine("QueueEntryEvent" + "\n\tQueue:\t\t" + qee.Queue + "\n\tChannel:\t" + qee.Channel + "\n\tPosition:\t" + qee.Position);
                }
            }

            Console.WriteLine("Press ENTER to next test or CTRL-C to exit.");
            Console.ReadLine();

            //
            //	To test create 3 extensions:
            //	1 - SIP/4012 w/o voicemail (with eyeBeam softphone)
            //	2 - IAX2/4008 w/o voicemail (with iaxComm softphone)
            //	3 - SIP/4010 w/ voicemal but no phone connect

            //	RedirectCall: call from IAX2/4008 to SIP/4012
            //	Don't answer on SIP/4012 and call must redirect to SIP/4010 (to voicemail really)
            //	Dial event used to define redirect channel

            Console.WriteLine("Redirect Call from " + ORIGINATE_CHANNEL + " to " + ORIGINATE_EXTRA_CHANNEL + " or press ESC.");
            // Wait for Dial Event from ORIGINATE_CHANNEL
            DialEventHandler de = new DialEventHandler(dam_Dial);

            manager.Dial += de;
            while (transferChannel == null)
            {
                System.Threading.Thread.Sleep(100);
                if (Console.KeyAvailable && Console.ReadKey(true).Key == ConsoleKey.Escape)
                {
                    break;
                }
            }
            manager.Dial -= de;

            // Now send Redirect action
            RedirectAction ra = new RedirectAction();

            ra.Channel      = transferChannel;
            ra.ExtraChannel = ORIGINATE_EXTRA_CHANNEL;
            ra.Context      = ORIGINATE_CONTEXT;
            ra.Exten        = ORIGINATE_EXTRA_EXTEN;
            ra.Priority     = 1;
            try
            {
                ManagerResponse mr = manager.SendAction(ra, 10000);
                Console.WriteLine("Transfer Call"
                                  + "\n\tResponse:" + mr.Response
                                  + "\n\tMessage:" + mr.Message
                                  );
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            //	Monitor call.
            //	Call from IA2/4008 to SIP/4012
            //	Link event used to define monitor channel
            Console.WriteLine("Monitor call. Please call " + ORIGINATE_CHANNEL + " and answer or press ESC.");
            // Wait for Link event
            LinkEventHandler le = new LinkEventHandler(dam_Link);

            manager.Link += le;
            while (monitorChannel == null)
            {
                System.Threading.Thread.Sleep(100);
                if (Console.KeyAvailable && Console.ReadKey(true).Key == ConsoleKey.Escape)
                {
                    break;
                }
            }
            manager.Link -= le;
            // Now send Monitor action
            MonitorAction ma = new MonitorAction();

            ma.Channel = monitorChannel;
            ma.File    = "voicefile";
            ma.Format  = "gsm";
            ma.Mix     = true;
            try
            {
                ManagerResponse mr = manager.SendAction(ma, 10000);
                Console.WriteLine("Monitor Call"
                                  + "\n\tResponse:" + mr.Response);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            manager.Logoff();
        }
Beispiel #30
0
 public virtual T Request <T>(object arguments, int serverId, out CommandResponse commandResponse,
                              ProxyRequestType requestType = ProxyRequestType.Xml)
 {
     return(ProxyManager.Request <T>(CommandName, Server.GetServerFromCache(serverId), arguments, out commandResponse, requestType: requestType));
 }
Beispiel #31
0
 public static void AddToViewData(this CommandResponse commandResponse, ViewDataDictionary viewData)
 {
     viewData["_CommandResponse"] = commandResponse;
 }
Beispiel #32
0
 public virtual void Request(object arguments, int serverId, out CommandResponse commandResponse,
                             ProxyRequestType requestType = ProxyRequestType.Xml)
 {
     ProxyManager.Request <object>(CommandName, new Server(serverId), arguments, out commandResponse, requestType: requestType);
 }
 public virtual void SendCommand(ICommand command, CommandResponse callback)
 {
     Session.SendCommand(command, callback);
 }
Beispiel #34
0
        private void _run()
        {
            connect();
            myevents();
            Resume();
            //Linger to get all remaining events before closing
            linger();
            myevents();
            if (_iseventjson)
            {
                EventJson("CUSTOM conference::maintenance agbara::dial");
            }
            else
            {
                EventPlain("CUSTOM conference::maintenance agbara::dial");
            }

            //get channel unique Id
            this.channel_uuid = get_channel_unique_id();
            AccountSid        = get_channel().GetHeader("variable_agbara_accountsid");
            CallSid           = get_channel().GetHeader("variable_agbara_callsid");
            ApiVersion        = get_channel().GetHeader("variable_agbara_apiversion");
            //Set agbara app flag
            set("agbara_app=true");
            //Don"t hangup after bridge
            set("hangup_after_bridge=false");
            CommandResponse channel   = get_channel();
            string          call_uuid = get_channel_unique_id();
            string          called_no = channel.GetHeader("Caller-Destination-Number");
            string          from_no   = channel.GetHeader("Caller-Caller-ID-Number");

            //Set To to Session Params
            session_params.Add("To", called_no.TrimStart(new Char['+']));
            //Set From to Session Params
            session_params.Add("From", from_no.TrimStart(new Char['+']));

            string aleg_uuid         = "";
            string aleg_request_uuid = "";
            string sched_hangup_id   = channel.GetHeader("variable_agbara_sched_hangup_id");
            string forwarded_from;
            string variable_sip_h_Diversion = channel.GetHeader("variable_sip_h_Diversion");

            if (string.IsNullOrEmpty(variable_sip_h_Diversion))
            {
                forwarded_from = "";
            }
            else
            {
                int startindex = variable_sip_h_Diversion.IndexOf(':');
                int length     = variable_sip_h_Diversion.IndexOf('@') - startindex;
                forwarded_from = variable_sip_h_Diversion.Substring(startindex, length);
            }
            var direction = channel.GetHeader("Call-Direction");

            if (direction == "outbound")
            {
                //# Look for variables in channel headers
                aleg_uuid         = channel.GetHeader("Caller-Unique-ID");
                aleg_request_uuid = channel.GetHeader("variable_agbara_request_uuid");
                // Look for target url in order below :
                // get agbara_transfer_url from channel var
                //  get agbara_answer_url from channel var
                string xfer_url   = channel.GetHeader("variable_agbara_transfer_url");
                string answer_url = channel.GetHeader("variable_agbara_answer_url");
                if (CurrentElement == "Dial")
                {
                    session_params.Add("Direction", CallDirection.outbounddial);
                }
                else
                {
                    session_params.Add("Direction", CallDirection.outboundapi);
                }

                if (!string.IsNullOrEmpty(xfer_url))
                {
                    this.target_url = xfer_url;
                }
                else if (!string.IsNullOrEmpty(answer_url))
                {
                    this.target_url = answer_url;
                }
                else
                {
                    return;
                }
                //Look for a sched_hangup_id

                //Don"t post hangup in outbound direction because it is handled by inboundsocket
                default_hangup_url = "";
                hangup_url         = "";
                //Set CallStatus to Session Params
                session_params.Add("CallStatus", CallStatus.inprogress);
            }
            else
            {
                session_params.Add("Direction", CallDirection.inbound);
                //Look for target url in order below :
                //get agbara_transfer_url from channel var
                //get agbara_answer_url from channel var
                //get default answer_url from config
                string xfer_url   = this.GetVar("agbara_transfer_url");
                string answer_url = this.GetVar("agbara_answer_url");
                if (!string.IsNullOrEmpty(xfer_url))
                {
                    this.target_url = xfer_url;
                }
                else if (!string.IsNullOrEmpty(answer_url))
                {
                    this.target_url = answer_url;
                }
                else if (!string.IsNullOrEmpty(default_answer_url))
                {
                    this.target_url = default_answer_url;
                }
                else
                {
                    return;
                }
            }

            //Look for a sched_hangup_id
            sched_hangup_id = GetVar("agbara_sched_hangup_id", get_channel_unique_id());
            //Set CallStatus to Session Params
            //this.session_params.Add("CallStatus", CallStatus.ringing);

            if (string.IsNullOrEmpty(sched_hangup_id))
            {
                sched_hangup_id = "";
            }

            //Add more Session Params
            session_params.Add("AccountSid", channel.GetHeader("variable_agbara_accountsid"));
            session_params.Add("CallSid", channel.GetHeader("variable_agbara_callsid"));
            if (!string.IsNullOrEmpty(forwarded_from))
            {
                session_params.Add("ForwardedFrom", forwarded_from.TrimStart(new Char[] { '+' }));
            }

            // Remove sched_hangup_id from channel vars
            if (!string.IsNullOrEmpty(sched_hangup_id))
            {
                unset("agbara_sched_hangup_id");
            }

            // Run application
            try
            {
                Console.WriteLine("Processing call");
                ProcessCall();
            }
            catch (Exception ex)
            {
                //except RESTHangup:
                //    this.log.warn("Channel has hung up, breaking Processing Call")
                //except Exception, e:
                //    this.log.error("Processing Call Failure !")
                //    # If error occurs during xml parsing
                //    # log exception and break
                //    this.log.error(str(e))
                //    [ this.log.error(line) for line in \
                //                traceback.format_exc().splitlines() ]
                //this.log.info("Processing Call Ended")
            }
        }
Beispiel #35
0
 private void OnStartGameCommandAction(CommandResponse c)
 {
     SceneManager.LoadScene("first-round-explanation");
 }
Beispiel #36
0
        public static string GetHttpResponse(HttpListenerRequest request)
        {
            string response = "";

            string body;
            using (var breader = new StreamReader(request.InputStream, request.ContentEncoding))
            {
                body = breader.ReadToEnd();
            }

            switch (request.HttpMethod)
            {
                case "POST":
                    JObject json;
                    try
                    {
                        json = JObject.Parse(body);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("[JSON]:{0}:{1}", e.Message, e.StackTrace);
                        return "{\"error\":\"Invalid Json\"}";
                    }
                    string[] path = request.Url.AbsolutePath.ToLower().Split('/');
                    path = path.Where(w => w != path[0]).ToArray();
                    string at = "";
                    if (path.Length >= 1)
                    {
                        if(accessToken.Length > 0)
                        {
                            if (path.Length > 1)
                            {
                                if(path[0].ToLower() != accessToken)
                                {
                                    response = "{\"error\":\"token invalid\"}";
                                    break;
                                }
                                else
                                {
                                    at = path[0];
                                    List<string> pathl = new List<string>(path);
                                    pathl.RemoveAt(0);
                                    path = pathl.ToArray();
                                }
                            }
                            else
                            {
                                response = "{\"error\":\"token error\"}";
                                break;
                            }
                        }
                        switch (path[0])
                        {
                            case "service":

                                List<CommandResult> results = new List<CommandResult>();

                                if (json["commands"].GetType() == typeof(Newtonsoft.Json.Linq.JArray))
                                {
                                    JArray commands = (JArray)json["commands"];
                                    foreach (JObject command in commands)
                                    {
                                        var type = Type.GetType("SteelCityAutomatonServiceCommands." + ((string)command["command"]).ToLower());
                                        if (type != null)
                                        {
                                            ServiceCommand cmd = (ServiceCommand)Activator.CreateInstance(type);
                                            cmd.Setup(command);
                                            cmd.Excecute(automatons,at);
                                            results.Add(cmd.result);
                                        }
                                        else
                                        {
                                            CommandResult result = new CommandResult(((string)command["command"]).ToLower());
                                            result.success = false;
                                            result.data = "unrecognized command";
                                            results.Add(result);
                                            Console.WriteLine("CMD NOT RECOGNIZED - {0} : {1}", ((string)command["command"]).ToLower(), "null");
                                        }
                                    }
                                    CommandResponse resp = new CommandResponse((string)json["label"],results);
                                    response = resp.serialise();
                                }
                                break;
                            case "automaton":
                                if (path.Length > 1)
                                {
                                    string session = path[1];
                                    if (automatons.ContainsKey(at + session))
                                    {
                                        response = automatons[at + session].processCommands(json);
                                    }
                                    else response = "{\"error\":\"unrecognized session id\"}";
                                }
                                else response = "{\"error\":\"missing session id\"}";
                                break;
                            default:
                                Console.WriteLine("------Parts------");
                                foreach (string s in path) Console.WriteLine(s);
                                Console.WriteLine("-----------------");
                                response = "{\"error\":\"unrecognized endpoint, not automaton or service\"}";
                                break;
                        }
                    }
                    else response = "{\"error\":\"unrecognized endpoint, not specifed\"}";
                    break;
                case "GET":
                    if(webPage)
                    {
                        string pathf = request.Url.AbsolutePath.ToLower();
                        if (pathf.Length < 3) pathf = "BasicWebTest.html";
                        pathf = "Resources/" + pathf;
                        //string f = @"Resources/BasicWebTest.html";
                        if (File.Exists(pathf))response =  File.ReadAllText(pathf);
                        else response = "{\"error\":\"BasicWebTest Missing\"}";
                    }
                    else response = "{\"error\":\"Web Page not enabled\"}";
                    break;
                default:
                    response = "{\"error\":\"Unsuported Method\"}";
                    break;
            }

            return response;
        }