Exemplo n.º 1
0
        // creates and returns a History object by calling Eth functions GetFileAddressGivenId
        // and GetNumberOfReceipts, which are used to loop a series of calls to
        // GetReceiptAddressAtIndex, GetVerificationDateTime, and GetVerifiedBy
        public async Task <History> GetHistory(string registryAddress, string fileId)
        {
            History history = new History();

            // get address of file contract with corresponding fileid
            string fileAddress = await GetFileAddressGivenId.SendRequestAsync(MyWeb3, registryAddress, fileId);

            // call number of receipts function on file contract
            int numReceipts = await GetNumberOfReceipts.SendRequestAsync(MyWeb3, fileAddress);

            // for each receipt
            for (int i = 0; i < numReceipts; ++i)
            {
                // get receipt address at index
                string receiptAddress = await GetReceiptAddressAtIndex.SendRequestAsync(MyWeb3, fileAddress, i);

                // get datetime
                string dateTime = await GetVerificationDateTime.SendRequestAsync(MyWeb3, receiptAddress);

                // get state of receipt
                string state = StateConvert.IntToString(await GetState.SendRequestAsync(MyWeb3, receiptAddress));

                // get user that created receipt
                string verifiedBy = await GetVerifiedBy.SendRequestAsync(MyWeb3, receiptAddress);

                // add values to History object
                history.AddLine(dateTime, state, verifiedBy);
            }

            return(history);
        }
Exemplo n.º 2
0
        public void AddGetState()
        {
            const string code         = @"int ione
                                  ione = 5
                                  int itwo
                                  itwo = 2
                                  int three
                                  int four
                                  int five";
            const int    indexToAdd   = 6;
            var          commandToAdd = new GetState("three", 2);
            var          commands     = GenerateCommands(code);
            var          mutation     = GetMutationForGetState(commands, commandToAdd, indexToAdd);

            mutation.Transform();

            const string resultCode     = @"int ione
                                        ione = 5
                                        int itwo
                                        itwo = 2
                                        int three
                                        int four
                                        three = getState 2
                                        int five";
            var          resultCommands = GenerateCommands(resultCode);

            Assert.IsTrue(AreCollectionsEquals(commands, resultCommands));
        }
Exemplo n.º 3
0
 public Transition(TEvent @event, GetState <TState> getTargetStateId, bool isStatic, Action?action)
 {
     Event            = @event;
     GetTargetStateId = getTargetStateId;
     IsStatic         = isStatic;
     _action          = action;
 }
Exemplo n.º 4
0
        public void Accept(GetState command)
        {
            var comparableCommand = _second as GetState;

            _isEqual = command.TargetName == comparableCommand.TargetName &&
                       command.Direction == comparableCommand.Direction;
        }
        public void RegisterBoardActions(
            Dispatcher dispatch,
            GetState getState,
            BoardActions actions
            )
        {
            DebugLogConsole.AddCommand(
                command: "AddPawn",
                description: "Adds a new Pawn to the Board",
                method: (string prefabKey, string displayName, float cameraWeight) => {
                dispatch(actions.AddPawn(prefabKey, displayName, cameraWeight, GetMousePosition()));
            }
                );

            DebugLogConsole.AddCommand(
                command: "AddCombatant",
                description: "Adds a Combatant Pawn to the Board",
                method: (string prefabKey, int health, string displayName, float cameraWeight) => {
                dispatch(actions.AddCombatant(prefabKey, health, displayName, cameraWeight, GetMousePosition()));
            }
                );

            DebugLogConsole.AddCommand(
                command: "RemovePawn",
                description: "Removes a pawn from the board",
                method: (string id) => { dispatch(actions.RemovePawn(Guid.Parse(id))); }
                );
        }
Exemplo n.º 6
0
        public App(string configFolder)
        {
            Log.Information("App started");

            string s = "";

            _tagFilepath          = Path.Combine(configFolder, "tags.txt");
            _currentStateFilepath = Path.Combine(configFolder, "state.txt");

            if (File.Exists(_currentStateFilepath))
            {
                Log.Information("Current state file exists {CurrentStateFile}", _currentStateFilepath);
                string c = File.ReadAllText(_currentStateFilepath);
                currentState = JsonConvert.DeserializeObject <GetState>(c);
            }
            else
            {
                Log.Warning("Current state file does not exist {CurrentStateFile}", _currentStateFilepath);
                currentState = new GetState()
                {
                    currentPage = 0,
                    pageSize    = 100,
                    has_more    = true
                };
            }
            Log.Verbose("Current state is {CurrentState}", currentState);

            if (File.Exists(_tagFilepath))
            {
                Log.Information("Tag file exists {TagFile}", _tagFilepath);
                var tagData = File.ReadAllLines(_tagFilepath);
                _tags = new List <string>(tagData);
            }
        }
Exemplo n.º 7
0
        private async Task <ResponsePayload> GetTags()
        {
            var newState = currentState;

            newState.currentPage++;

            var uri = $"/2.2/tags?page={newState.currentPage}&pagesize={newState.pageSize}&order=asc&sort=name&site=stackoverflow";

            HttpClientHandler handler = new HttpClientHandler()
            {
                AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
            };

            using (var client = new HttpClient(handler))
            {
                ServicePointManager.ServerCertificateValidationCallback = delegate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return(true); };

                client.BaseAddress = new Uri("https://api.stackexchange.com");
                client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json; charset=utf-8");
                client.DefaultRequestHeaders.Add("X-Content-Type-Options", "nosniff");

                var response = await client.GetAsync(uri);

                var json = await response.Content.ReadAsStringAsync();

                var tags = JsonConvert.DeserializeObject <ResponsePayload>(json);

                newState.has_more        = tags.has_more;
                newState.quota_remaining = tags.quota_remaining;
                newState.quota_max       = tags.quota_max;

                currentState = newState;
                return(tags);
            }
        }
Exemplo n.º 8
0
        public void ReplaceGetState()
        {
            const string code             = @"int ione
                                  ione = 5
                                  int itwo
                                  itwo = 2
                                  int ithree
                                  ithree = ione
                                  itwo = getState 3";
            const int    indexToReplace   = 6;
            var          commandToReplace = new GetState("ithree", 0);
            var          commands         = GenerateCommands(code);
            var          mutation         = GetMutationForGetState(commands, indexToReplace, commandToReplace);

            mutation.Transform();

            const string resultCode     = @"int ione
                                        ione = 5
                                        int itwo
                                        itwo = 2
                                        int ithree
                                        ithree = ione
                                        ithree = getState 0";
            var          resultCommands = GenerateCommands(resultCode);

            Assert.IsTrue(AreCollectionsEquals(commands, resultCommands));
        }
        public IValue GetState(HashDigest <SHA256> blockHash, Address address)
        {
            var request = new GetState(blockHash, address);
            var reply   = SendMultipartMessageWithReply <State>(request);

            return(reply.Payload.Decode());
        }
Exemplo n.º 10
0
        public GetState CreateGetState(int placeIndex)
        {
            var declaration = GetRandomDeclarationBefore(placeIndex);
            var direction   = GetRandomDirection();
            var command     = new GetState(declaration.Name, direction);

            return(command);
        }
Exemplo n.º 11
0
        private AddCommandMutation GetMutationForGetState(ICommandsList commands, GetState command, int indexToAdd)
        {
            var random = new AddRandom();
            var targetDeclarationIndex = GetDeclarationIndexOfVariable(command.TargetName, commands);
            var direction = command.Direction;

            random.TuneGetState(targetDeclarationIndex, direction, indexToAdd);
            return(new AddCommandMutation(random, commands));
        }
Exemplo n.º 12
0
        public void Accept(GetState command)
        {
            if (!_conditions.Peek())
            {
                return;
            }

            _variables[command.TargetName] = _executorToolset.GetState(command.Direction);
        }
Exemplo n.º 13
0
 public void Accept(GetState command)
 {
     if (!_variables.ContainsKey(command.TargetName))
     {
         _isExecutable = false;
         return;
     }
     //TODO
     _variables[command.TargetName] = _executorToolset.GetState(command.Direction);
 }
Exemplo n.º 14
0
 public IUserService CreateUserService(State currentState)
 {
     return(currentState switch
     {
         SaveState _ => new SaveContextUserService(storage),
         DefaultState _ => new RegistrationContextUserService(storage, logger),
         InitState _ => new InitUserService(storage),
         GetState _ => new GetContextUserService(storage),
         _ => throw new Exception($"{nameof(currentState)}:{currentState}")
     });
Exemplo n.º 15
0
        // returns state
        private async Task <int> NewReceiptPrivate(string registryAddress, string fileId, string fileHash,
                                                   string metadataHash, string verifiedBy)
        {
            // deploy new receipt contract to blockchain
            string receiptAddress = await DeployReceipt.SendRequestAsync(MyWeb3, registryAddress, fileId,
                                                                         fileHash, metadataHash, verifiedBy);

            // get state of receipt
            return(await GetState.SendRequestAsync(MyWeb3, receiptAddress));
        }
        public Task <ByteString> HandleGetState(string collection, string key, string channelId, string txId)
        {
            var payload = new GetState
            {
                Key        = key,
                Collection = collection
            };

            return(CreateMessageAndListen <ByteString>(MessageMethod.GetState, ChaincodeMessage.Types.Type.GetState,
                                                       payload, channelId, txId));
        }
Exemplo n.º 17
0
        public void GetStateParse()
        {
            const string targetName    = "target";
            const int    direction     = 2;
            var          command       = new GetState(targetName, direction);
            var          commandParser = new CommandToStringParser();

            var parsedCommand = commandParser.ParseCommand(command).Trim(' ', '\n', '\r');
            var result        = $"{targetName} = getState {direction}";

            Assert.AreEqual(parsedCommand, result);
        }
Exemplo n.º 18
0
        void GetStateHandler(GetState get)
        {
            if (_state == null)
            {
                // To demonstrate a failure response,
                // when state is null will post an exception
                get.ResponsePort.Post(new InvalidOperationException());
                return;
            }

            // return the state as a message on the response port
            get.ResponsePort.Post(_state);
        }
Exemplo n.º 19
0
        private void initState()
        {
            makeAction += PreventSleep;
            getState   += () => this.appState;

            this.FormBorderStyle              = FormBorderStyle.FixedSingle;
            this.MaximizeBox                  = false;
            this.notifyIcon.Visible           = true;
            this.notifyIcon.MouseDoubleClick += NotifyIcon_MouseDoubleClick;

            this.ShowInTaskbar    = false;
            this.btnStart.Enabled = true;
            this.btnStop.Enabled  = false;
        }
Exemplo n.º 20
0
    public void GetDailyPresent()
    {
        if (_cuurState == GetState.NEW)
        {
            //獲得對應禮物(待實作)

            _getButton.enabled = false;
            _getButton.GetComponent <Image>().sprite         = _buttonBG[1];
            _getButton.GetComponentInChildren <Text>().text  = "已領取";
            _getButton.GetComponentInChildren <Text>().color = Color.gray;

            _cuurState = GetState.GOT;

            Lobby_UIManager.instance.CallReceviedPanel(_dailyActItemType, _dailyActItemNum);
        }
    }
Exemplo n.º 21
0
 public string GetStateList()
 {
     if (SecureAuthentication != null)
     {
         int Output = CheckLoginReturnUserId(SecureAuthentication).ValueFromSQL;
         if (Output > 0)
         {
             GetState proc = new GetState();
             return("{\"StateList\" : " + Serialize(proc.GetSTateList()) + "}");
         }
         else
         {
             return(Serialize(new AuthResponse(0, Output == -1 ? "Authentication is NULL" : "Invalid Authentication")));
         }
     }
     return(Serialize(new AuthResponse(0, "Authentication information not provided.")));
 }
Exemplo n.º 22
0
        /// <summary>
        /// Create an UndoService.
        /// </summary>
        /// <param name="getState">Method to get the state of the tracked object</param>
        /// <param name="setState">Method to set the state of the tracked object</param>
        /// <param name="cap">Capacity of Undo history</param>
        public UndoService(GetState <T> getState, SetState <T> setState, int?cap = null)
        {
            GetState = getState ?? throw new ArgumentNullException(nameof(getState));
            SetState = setState ?? throw new ArgumentNullException(nameof(setState));
            var stackFactory = new StackFactory <StateRecord <T> >();

            _undoStack = stackFactory.MakeStack(cap);
            // T currentState;
            GetState(out T currentState);
            _originalState = currentState;
            _currentState  = new StateRecord <T> {
                State = currentState
            };
            _redoStack                  = new StandardStack <StateRecord <T> >();
            _undoServiceValidator       = new UndoServiceValidator <StateRecord <T> >(_undoStack, _redoStack);
            _undoStack.HasItemsChanged += UndoStack_HasItemsChanged;
            _redoStack.HasItemsChanged += RedoStack_HasItemsChanged;
        }
Exemplo n.º 23
0
 /// <inheritdoc cref="GetStateAsync(Commands.GetState, CancellationToken)"/>
 public GetStateResponse GetState(GetState getState)
 => Post <GetState, GetStateResponse>(getState);
Exemplo n.º 24
0
 /// <summary>
 /// Возвращает текущий статус платежа
 /// </summary>
 /// <param name="getState"></param>
 /// <param name="token"></param>
 /// <returns></returns>
 public Task <GetStateResponse> GetStateAsync(GetState getState, CancellationToken token)
 => PostAsync <GetState, GetStateResponse>(getState, token);
Exemplo n.º 25
0
        private ReplaceCommandMutation GetMutationForGetState(ICommandsList commands, int replaceIndex, GetState command)
        {
            var random           = new ReplaceRandom();
            var declarationIndex = GetDeclarationIndexOfVariable(command.TargetName, commands);
            var direction        = command.Direction;

            random.TuneGetState(replaceIndex, declarationIndex, direction);
            return(new ReplaceCommandMutation(random, commands));
        }
Exemplo n.º 26
0
 public void Accept(GetState command)
 {
     _builder.AppendLine($"{command.TargetName} = getState {command.Direction}");
 }
Exemplo n.º 27
0
 private bool EqualsGetState(GetState x, GetState y)
 {
     return(x.Direction == y.Direction && x.TargetName == y.TargetName);
 }
Exemplo n.º 28
0
        /// <summary>
        /// Service start
        /// </summary>
        protected override void Start()
        {
            //
            // Add service specific initialization here
            //

            base.Start();
            int exampleNum = 3;

            switch (exampleNum)
            {
            case 1:
                // Create port that accepts instances of System.Int32
                Port <int> portInt1 = new Port <int>();

                // Add the number 10 to the port
                portInt1.Post(10);

                // Display number of items to the console
                Console.WriteLine(portInt1.ItemCount);
                break;

            case 2:
                // Create port that accepts instances of System.Int32
                var portInt2 = new Port <int>();

                // Add the number 10 to the port
                portInt2.Post(10);

                // Display number of items to the console
                Console.WriteLine(portInt2.ItemCount);

                // retrieve the item using Test
                int item2;
                var hasItem2 = portInt2.Test(out item2);
                if (hasItem2)
                {
                    Console.WriteLine("Found item in port:" + item2);
                }
                portInt2.Post(11);
                // alternative to using Test is just assignment of port to variable using
                // implicit operator
                var nextItem = portInt2;

                Console.WriteLine("Found item in port:" + nextItem);
                break;

            case 3:
                // Create port that accepts instances of System.Int32
                var portInt3 = new Port <int>();

                // Add the number 10 to the port
                portInt3.Post(10);

                // Display number of items to the console
                Console.WriteLine(portInt3.ItemCount);

                // create dispatcher and dispatcher queue for scheduling tasks
                Dispatcher      dispatcher = new Dispatcher();
                DispatcherQueue taskQueue  = new DispatcherQueue("sample queue", dispatcher);

                // retrieve the item by attaching a one time receiver
                Arbiter.Activate(
                    taskQueue,
                    portInt3.Receive(delegate(int item3)     // anonymous method
                {
                    // this code executes in parallel with the method that
                    // activated it
                    Console.WriteLine("Received item:" + item3);
                }
                                     ));
                // any code below runs in parallel with delegate

                break;

            case 4:
                // Create a PortSet using generic type arguments
                var genericPortSet4 = new PortSet <int, string, double>();
                genericPortSet4.Post(10);
                genericPortSet4.Post("hello");
                genericPortSet4.Post(3.14159);

                // Create a runtime PortSet, using the initialization
                // constructor to supply an array of types
                PortSet runtimePortSet4 = new PortSet(
                    typeof(int),
                    typeof(string),
                    typeof(double)
                    );

                runtimePortSet4.PostUnknownType(10);
                runtimePortSet4.PostUnknownType("hello");
                runtimePortSet4.PostUnknownType(3.14159);
                break;

            case 5:
                // create dispatcher and dispatcher queue for scheduling tasks
                Dispatcher      dispatcher5 = new Dispatcher();
                DispatcherQueue taskQueue5  = new DispatcherQueue("sample queue", dispatcher5);
                CcrConsolePort  port5       = CcrConsoleService.Create(taskQueue5);
                break;

            case 6:
                Dispatcher      dispatcher6 = new Dispatcher();
                DispatcherQueue taskQueue6  = new DispatcherQueue("sample queue", dispatcher6);
                CcrConsolePort  port6       = CcrConsoleService.Create(taskQueue6);
                var             portSet6    = new PortSet <int, string, double>();
                // the following statement compiles because of the implicit assignment operators
                // that "extract" the instance of Port<int> from the PortSet
                var portInt6 = portSet6;

                // the implicit assignment operator is used below to "extract" the Port<int>
                // instance so the int receiver can be registered
                Arbiter.Activate(taskQueue6,
                                 Arbiter.Receive <int>(true, portSet6, item => Console.WriteLine(item))
                                 );

                break;

            case 7:
                Dispatcher      dispatcher7 = new Dispatcher();
                DispatcherQueue taskQueue7  = new DispatcherQueue("sample queue", dispatcher7);
                var             port7       = new Port <int>();
                Arbiter.Activate(taskQueue7,
                                 Arbiter.Receive(
                                     true,
                                     port7,
                                     item => Console.WriteLine(item)

                                     /** older syntax
                                      *    delegate(int item){
                                      *        Console.WriteLine(item);
                                      *    }
                                      *
                                      **/

                                     )
                                 );

                // post item, so delegate executes
                port7.Post(5);
                break;

            case 8:
                Dispatcher      dispatcher8 = new Dispatcher();
                DispatcherQueue taskQueue8  = new DispatcherQueue("sample queue", dispatcher8);
                var             port8       = new Port <int>();
                // alternate version that explicitly constructs a Receiver by passing
                // Arbiter class factory methods
                var persistedReceiver = new Receiver <int>(
                    true,                                           // persisted
                    port8,
                    null,                                           // no predicate
                    new Task <int>(item => Console.WriteLine(item)) // task to execute
                    );
                Arbiter.Activate(taskQueue8, persistedReceiver);
                break;

            case 9:
                Dispatcher      dispatcher9 = new Dispatcher();
                DispatcherQueue taskQueue9  = new DispatcherQueue("sample queue", dispatcher9);
                // create a simple service listening on a port
                ServicePort servicePort9 = SimpleService.Create(taskQueue9);

                // create request
                GetState get = new GetState();

                // post request
                servicePort9.Post(get);

                // use the extension method on the PortSet that creates a choice
                // given two types found on one PortSet. This a common use of
                // Choice to deal with responses that have success or failure
                Arbiter.Activate(taskQueue9,
                                 get.ResponsePort.Choice(
                                     s => Console.WriteLine(s),  // delegate for success
                                     ex => Console.WriteLine(ex) // delegate for failure
                                     ));
                break;

            case 10:
                Dispatcher      dispatcher10 = new Dispatcher();
                DispatcherQueue taskQueue10  = new DispatcherQueue("sample queue", dispatcher10);
                var             portDouble   = new Port <double>();
                var             portString   = new Port <string>();

                // activate a joined receiver that will execute only when one
                // item is available in each port.
                Arbiter.Activate(taskQueue10,
                                 portDouble.Join(
                                     portString,             // port to join with
                                     (value, stringValue) => // delegate
                {
                    value      /= 2.0;
                    stringValue = value.ToString();
                    // post back updated values
                    portDouble.Post(value);
                    portString.Post(stringValue);
                })
                                 );

                // post items. The order does not matter, which is what Join its power
                portDouble.Post(3.14159);
                portString.Post("0.1");

                //after the last post the delegate above will execute
                break;
            }
        }
Exemplo n.º 29
0
            public async Task <string> Handle(GetState query)
            {
                await ReadState();

                return(State.Data);
            }