public async Task <T> SendRequestAsync <T>(RPCRequest request)
        {
            var rpcRequestJson = JsonConvert.SerializeObject(request.Parameters, JsonSerializerSettings);
            var response       = await UnityCoroutineHandler.ExecuteCoroutineOnMainThread(SendRequest <RPCResponse>(_url + request.Route, rpcRequestJson));

            return(response.GetData <T>());
        }
        /// <summary>
        /// Shares the specified video with a list of sharee accounts
        /// </summary>
        /// <param name="video_id">
        /// The id of the video whose status you'd like to get.
        /// </param>
        /// <param name="auto_accept">
        /// If the target account has the option enabled, setting this flag to true will bypass
        /// the approval process, causing the shared video to automatically appear in the target
        /// account's library. If the target account does not have the option enabled, or this
        /// flag is unspecified or false, then the shared video will be queued up to be approved
        /// by the target account before appearing in their library.
        /// defaults to false
        /// </param>
        /// <param name="sharee_account_ids">
        /// List of Account IDs to share video with.
        /// </param>
        /// <returns></returns>
        public RPCResponse <BCCollection <long> > ShareVideo(long video_id, bool auto_accept, List <long> sharee_account_ids)
        {
            // Generate post objects
            Dictionary <string, object> postParams = new Dictionary <string, object>();

            //add video to the post params
            RPCRequest rpc = new RPCRequest();

            rpc.method      = "share_video";
            rpc.parameters  = "\"video_id\": " + video_id;
            rpc.parameters += ", \"auto_accept\": " + auto_accept.ToString().ToLower();
            rpc.parameters += ", \"sharee_account_ids\": [";
            for (int i = 0; i < sharee_account_ids.Count; i++)
            {
                if (i > 0)
                {
                    rpc.parameters += ", ";
                }
                rpc.parameters += "\"" + sharee_account_ids[i].ToString() + "\"";
            }
            rpc.parameters += "]";
            rpc.parameters += ", \"token\": \"" + Account.WriteToken.Value + "\"";
            postParams.Add("json", rpc.ToJSON());

            //Get the JSon reader returned from the APIRequest
            RPCResponse <BCCollection <long> > rpcr = BCAPIRequest.ExecuteWrite <BCCollection <long> >(postParams, Account);

            return(rpcr);
        }
Example #3
0
        private async ValueTask <int> callMethod(WebSocket socket, string data)
        {
            try
            {
                RPCRequest request = JsonConvert.DeserializeObject <RPCRequest>(data);

                switch (request.Method)
                {
                case "getStatus":
                    sendMessage(new RpcResponse {
                        Event = "OnDeviceStatus", Data = Program.Recorder.getCurrentChannel() != null ? "0" : "-1"
                    });
                    break;

                default:
                    var response = RpcService.Invoke(request);
                    sendMessage(response);
                    break;
                }
            }
            catch (Exception ex)
            {
                sendMessage(new RpcResponse {
                    Event = "OnError", Data = ex.Message
                });
            }



            return(0);
        }
        private RPCResponse DeleteCaptioning(long video_id, string video_reference_id)
        {
            Dictionary <string, object> postParams = new Dictionary <string, object>();

            Builder builder = new Builder()
                              .AppendField("token", Account.WriteToken.Value);

            // Either a video_id or video_reference_id is required
            if (video_id > 0)
            {
                builder.Append(",").AppendField("video_id", video_id);
            }
            else if (!string.IsNullOrEmpty(video_reference_id))
            {
                builder.Append(",").AppendField("video_reference_id", video_reference_id);
            }
            else
            {
                throw new System.ArgumentException("A video_id or video_reference_id is required for delete_captioning");
            }

            RPCRequest rpc = new RPCRequest();

            rpc.method     = "delete_captioning";
            rpc.parameters = builder.ToString();
            postParams.Add("json", rpc.ToJSON());

            // Get the JSon reader returned from the APIRequest
            RPCResponse rpcr = BCAPIRequest.ExecuteWrite(postParams, this.Account);

            return(rpcr);
        }
        /// <summary>
        /// Deletes a video.
        /// </summary>
        /// <param name="video_id">
        /// The id of the video you'd like to delete
        /// </param>
        /// <param name="reference_id">
        /// The publisher-assigned reference id of the video you'd like to delete.
        /// </param>
        /// <param name="cascade">
        /// Set this to true if you want to delete this video even if it is part of a
        /// manual playlist or assigned to a player. The video will be removed from
        /// all playlists and players in which it appears, then deleted.
        /// defaults to true
        /// </param>
        /// <param name="delete_shares">
        /// Set this to true if you want also to delete shared copies of this video.
        /// Note that this will delete all shared copies from sharee accounts, regardless
        /// of whether or not those accounts are currently using the video in playlists or players.
        /// defaults to true
        /// </param>
        private RPCResponse DeleteVideo(long video_id, string reference_id, bool cascade, bool delete_shares)
        {
            // Generate post objects
            Dictionary <string, object> postParams = new Dictionary <string, object>();

            //add video to the post params
            RPCRequest rpc = new RPCRequest();

            rpc.method = "delete_video";
            if (video_id > -1)
            {
                rpc.parameters = "\"video_id\": " + video_id.ToString();
            }
            else if (reference_id != null)
            {
                rpc.parameters = "\"reference_id\": \"" + reference_id.ToString() + "\"";
            }
            rpc.parameters += ", \"token\": \"" + Account.WriteToken.Value + "\"";
            rpc.parameters += ", \"cascade\": " + cascade.ToString().ToLower();
            rpc.parameters += ", \"delete_shares\": " + delete_shares.ToString().ToLower();
            postParams.Add("json", rpc.ToJSON());

            //Get the JSon reader returned from the APIRequest
            RPCResponse rpcr = BCAPIRequest.ExecuteWrite(postParams, Account);

            return(rpcr);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="videoId"></param>
        /// <param name="reference_id"></param>
        /// <returns></returns>
        private RPCResponse <BCVideo> RemoveLogoOverlay(long video_id, string video_reference_id)
        {
            // Generate post objects
            Dictionary <string, object> postParams = new Dictionary <string, object>();

            //add video to the post params
            RPCRequest rpc = new RPCRequest();

            rpc.method = "remove_logo_overlay";
            if (video_id > -1)
            {
                rpc.parameters += ",\"video_id\": \"" + video_id.ToString() + "\"";
            }
            else if (video_reference_id != null)
            {
                rpc.parameters += ",\"video_reference_id\": \"" + video_reference_id + "\"";
            }
            rpc.parameters += ", \"token\": \"" + Account.WriteToken.Value + "\"";
            postParams.Add("json", rpc.ToJSON());

            //Get the JSon reader returned from the APIRequest
            RPCResponse <BCVideo> rpcr = BCAPIRequest.ExecuteWrite <BCVideo>(postParams, Account);

            return(rpcr);
        }
Example #7
0
        public static async Task <Repository.SavedTransaction> TryGetRawTransaction(this RPCClient client, uint256 txId)
        {
            var request = new RPCRequest(RPCOperations.getrawtransaction, new object[] { txId, true })
            {
                ThrowIfRPCError = false
            };
            var response = await client.SendCommandAsync(request);

            if (response.Error == null && response.Result is JToken rpcResult && rpcResult["hex"] != null)
            {
                uint256 blockHash = null;
                if (rpcResult["blockhash"] != null)
                {
                    blockHash = uint256.Parse(rpcResult.Value <string>("blockhash"));
                }
                DateTimeOffset timestamp = DateTimeOffset.UtcNow;
                if (rpcResult["time"] != null)
                {
                    timestamp = NBitcoin.Utils.UnixTimeToDateTime(rpcResult.Value <long>("time"));
                }

                var rawTx = client.Network.Consensus.ConsensusFactory.CreateTransaction();
                rawTx.ReadWrite(Encoders.Hex.DecodeData(rpcResult.Value <string>("hex")), client.Network);
                return(new Repository.SavedTransaction()
                {
                    BlockHash = blockHash,
                    Timestamp = timestamp,
                    Transaction = rawTx
                });
            }
            return(null);
        }
        public CertificateVerify CertificateVerify(string serialnumber, string subject, string signature, string data)
        {
            CertificateVerify certificateVerify;

            try
            {
                string     strResponse = "";
                RPCRequest rpcRequest  = new RPCRequest();

                rpcRequest.Method = "certificate";
                rpcRequest.Params = new object[] { "verify", serialnumber, subject, signature, data };
                strResponse       = SendCommand(rpcRequest).ResultString;
                certificateVerify = JsonConvert.DeserializeObject <CertificateVerify>(strResponse);
            }
            catch (Exception ex)
            {
                //TODO: Log error messages
                //throw new Exception($"Failed to verify certificate", ex);
                certificateVerify       = new CertificateVerify();
                certificateVerify.valid = "false";
                if (ex.InnerException != null)
                {
                    certificateVerify.error_message = ex.InnerException.Message;
                }
                else
                {
                    certificateVerify.error_message = ex.Message;
                }
            }
            return(certificateVerify);
        }
Example #9
0
        public int DownloadMovieByNzbLink(string link)
        {
            RPCRequest request = new RPCRequest();

            request.jsonrpc = "2.0";
            request.id      = 1;
            request.method  = "append";
            request.parms   = new object[]
            {
                "",
                link,
                "",
                0,
                true,
                false,
                "",
                0,
                "SCORE",
                new object[] { new PPParameter()
                               {
                                   Name = "Unpack", Value = "True"
                               } }
            };
            var jsonRequest = JsonConvert.SerializeObject(request);

            jsonRequest = jsonRequest.Replace("parms", "params");
            int id = 0;

            using (var webClient = new WebClient())
            {
                JObject jsonObj = JObject.Parse(webClient.UploadString("http://127.0.0.1:6789/jsonrpc/append", jsonRequest));
                id = Convert.ToInt32(jsonObj["result"]);
            }
            return(id);
        }
Example #10
0
        public void Deserialize <PARSER>(PARSER parser, ref RPCRequest <JsonParser> outValue) where PARSER : IParser <PARSER>
        {
            foreach (var kv in parser.ObjectItems)
            {
                switch (kv.Key)
                {
                case "jsonrpc":
                    if (kv.Value.GetString() != "2.0")
                    {
                        throw new FormatException("jsonrpc should 2.0");
                    }
                    break;

                case "method":
                    outValue.Method = kv.Value.GetString();
                    break;

                case "args":
                case "params":
                    outValue.ParamsBytes = kv.Value.Dump();
                    break;

                case "id":
                    outValue.Id = kv.Value.GetInt32();
                    break;

                default:
                    throw new FormatException("unknown key: " + kv.Key);
                }
            }
        }
Example #11
0
        private async Task UpdateItemsAsync()
        {
            m_timer.Stop();
            var        webClient = new WebClient();
            RPCRequest request   = new RPCRequest();

            request.jsonrpc = "2.0";
            request.id      = 1;
            request.method  = "listgroups";
            request.parms   = new object[]
            {
                0,
            };
            try
            {
                string queueItemsJson = await webClient.UploadStringTaskAsync(new Uri("http://127.0.0.1:6789/jsonrpc/listgroups"), JsonConvert.SerializeObject(request));

                request.method = "history";
                request.parms  = new object[]
                {
                    false,
                };
                string historyItemsJson = await webClient.UploadStringTaskAsync(new Uri("http://127.0.0.1:6789/jsonrpc/listgroups"), JsonConvert.SerializeObject(request));

                List <DownloadItem> downloadItems = ParseQueueItems(queueItemsJson);
                downloadItems.AddRange(ParseHistoryItems(historyItemsJson));
                m_downloadItems = downloadItems;
            }
            catch
            {
                m_downloadItems = null;
            }
            m_timer.Start();
        }
            public Task <T> SendRequestAsync <T>(RPCRequest request)
            {
                JsonSerializerSettings jsonSerializerSettings = new JsonSerializerSettings
                {
                    NullValueHandling     = NullValueHandling.Ignore,
                    MissingMemberHandling = MissingMemberHandling.Ignore
                };

                string responseMessage = "";

                if (request.Route == "account.get_utxos")
                {
                    responseMessage = PlasmaMockupResponses.GetUtxos(request.Parameters.Value <string>("address"));
                }
                else if (request.Route == "account.get_balance")
                {
                    responseMessage = PlasmaMockupResponses.GetBalance(request.Parameters.Value <string>("address"));
                }
                else if (request.Route == "transaction.submit")
                {
                    responseMessage = PlasmaMockupResponses.SubmitTransaction(request.Parameters.Value <string>("transaction"));
                }
                else if (request.Route == "utxo.get_challenge_data")
                {
                    responseMessage = PlasmaMockupResponses.GetChallengeData();
                }

                using (var reader = new JsonTextReader(new StringReader(responseMessage)))
                {
                    var serializer = JsonSerializer.Create(jsonSerializerSettings);
                    var message    = serializer.Deserialize <RPCResponse>(reader);

                    return(Task.FromResult(message.GetData <T>()));
                }
            }
        public Audit AuditAdd(string hasharray, string account, string description, string algorithm)
        {
            Audit auditAdd;

            try
            {
                string     strResponse = "";
                RPCRequest rpcRequest  = new RPCRequest();

                rpcRequest.Method = "audit";
                rpcRequest.Params = new object[] { "add", hasharray, account, description, algorithm };
                strResponse       = SendCommand(rpcRequest).ResultString;
                auditAdd          = JsonConvert.DeserializeObject <Audit>(strResponse);
            }
            catch (Exception ex)
            {
                //TODO: Log error messages
                auditAdd = new Audit();
                if (ex.InnerException != null)
                {
                    auditAdd.error_message = ex.InnerException.Message;
                }
                else
                {
                    auditAdd.error_message = ex.Message;
                }
            }
            return(auditAdd);
        }
        public Certificate CertificateView(string serialnumber)
        {
            Certificate certificate;

            try
            {
                string     strResponse = "";
                RPCRequest rpcRequest  = new RPCRequest();

                rpcRequest.Method = "certificate";
                rpcRequest.Params = new object[] { "view", serialnumber };
                strResponse       = SendCommand(rpcRequest).ResultString;
                certificate       = JsonConvert.DeserializeObject <Certificate>(strResponse);
            }
            catch (Exception ex)
            {
                //TODO: Log error messages
                //throw new Exception($"Failed to view certificate", ex);
                //return empty Certificate if not found
                certificate = new Certificate();
                if (ex.InnerException != null)
                {
                    certificate.error_message = ex.InnerException.Message;
                }
                else
                {
                    certificate.error_message = ex.Message;
                }
            }
            return(certificate);
        }
Example #15
0
        public IActionResult CallByName([FromBody] JObject body)
        {
            Guard.NotNull(body, nameof(body));

            try
            {
                if (!this.rpcSettings.Server)
                {
                    return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.MethodNotAllowed, "Method not allowed",
                                                           "Method not allowed when RPC is disabled."));
                }

                var ignoreCase = StringComparison.InvariantCultureIgnoreCase;
                var methodName = (string)body.GetValue("methodName", ignoreCase);

                ControllerActionDescriptor actionDescriptor = null;
                if (!GetActionDescriptors()?.TryGetValue(methodName, out actionDescriptor) ?? false)
                {
                    throw new Exception($"RPC method '{methodName}' not found.");
                }

                // Prepare the named parameters that were passed via the query string in the order that they are expected by SendCommand.
                var paramInfos = actionDescriptor.Parameters.OfType <ControllerParameterDescriptor>().ToList();

                var paramsAsObjects = new object[paramInfos.Count];
                for (var i = 0; i < paramInfos.Count; i++)
                {
                    var pInfo    = paramInfos[i];
                    var hasValue = body.TryGetValue(pInfo.Name, ignoreCase, out var jValue);
                    if (hasValue && !jValue.HasValues)
                    {
                        paramsAsObjects[i] = jValue.ToString();
                    }
                    else
                    {
                        paramsAsObjects[i] = pInfo.ParameterInfo.DefaultValue?.ToString();
                    }
                }

                var request = new RPCRequest(methodName, paramsAsObjects);

                // Build RPC request object.
                var response = SendRPCRequest(request);

                // Throw error if any.
                if (response?.Error?.Message != null)
                {
                    throw new Exception(response.Error.Message);
                }

                // Return a Json result from the API call.
                return(Json(response?.Result));
            }
            catch (Exception e)
            {
                this.logger.LogError("Exception occurred: {0}", e.ToString());
                return(ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, e.Message, e.ToString()));
            }
        }
        /// <summary>
        /// Processes a RPCRequest.
        /// </summary>
        /// <param name="request">The request to process.</param>
        /// <returns></returns>
        private RPCResponse SendRPCRequest(RPCRequest request)
        {
            // Find the binding to 127.0.0.1 or the first available. The logic in RPC settings ensures there will be at least 1.
            IPEndPoint nodeEndPoint = this.rpcSettings.Bind.Where(b => b.Address.ToString() == "127.0.0.1").FirstOrDefault() ?? this.rpcSettings.Bind[0];
            IRPCClient rpcClient    = this.rpcClientFactory.Create($"{this.rpcSettings.RpcUser}:{this.rpcSettings.RpcPassword}", new Uri($"http://{nodeEndPoint}"), this.fullNode.Network);

            return(rpcClient.SendCommand(request));
        }
Example #17
0
 public override bool Authenticate(RPCRequest request)
 {
     // NOTE: the token comes from the client, so it can be tampered with, however it should be
     // cryptographically hard to generate a new valid token.
     // we _could_ check the server to see if the user truly has access to the guild as a second layer of security,
     // but the incoming user id could also be faked.
     return(Authentication.VerifyToken(request.Token, request.GuildId.ToString()));
 }
Example #18
0
        public RPCRequest Create(string method, string id = "1")
        {
            var request = new RPCRequest()
            {
                Method = method.ToString().ToLower(), Id = id
            };

            return(request);
        }
Example #19
0
        public async Task <string> GetOmniTransaction(string transactionId)
        {
            var request  = new RPCRequest("omni_gettransaction", new object[] { transactionId });
            var response = await Client.SendCommandAsync(request);

            var json = response.Result;

            return(json.ToString());
        }
Example #20
0
        public LobbyViewModel()
        {
            this._wifPrivateKey = "93Loqe8T3Qn3fCc87AiJHYHJfFFMLy6YuMpXzffyFsiodmAMCZS";

            this.NetworkPlayers = new ObservableCollection <Peer>();
            this.Clients        = new List <BitPoker.NetworkClient.INetworkClient>(1);

            this.Clients.Add(new BitPoker.NetworkClient.APIClient("https://www.bitpoker.io/api/"));
            //this.Clients.Add(new Clients.NetSocketClient(IPAddress.Parse("127.0.0.1")));

            this.Tables = new ObservableCollection <BitPoker.Models.Contracts.Table>();

            Wallet = new WalletViewModel(_wifPrivateKey);

            _secret = new BitcoinSecret(_wifPrivateKey, Constants.Network);
            BitcoinAddress address = _secret.GetAddress();

            //move this
            this.Me = new TexasHoldemPlayer()
            {
                Position       = 0,
                BitcoinAddress = address.ToString(),
                IsDealer       = true,
                IsBigBlind     = true,
                Stack          = 0
            };

            this.Backend = new ChatBackend(this.ProcessMessage, Wallet.Address.ToString());

            this.InComingRequests = new ObservableCollection <IRequest>();
            this.SentRequests     = new ObservableCollection <IRequest>();

            this.InComingResponses = new ObservableCollection <IResponse>();
            this.SentResponses     = new ObservableCollection <IResponse>();

            //Announce
            IRequest request = new RPCRequest()
            {
                Method = "NewPeer",
                Params = new NewPeerRequest()
                {
                    BitcoinAddress = Wallet.Address.ToString(),
                    Version        = 1.0M,
                    Player         = new Peer()
                    {
                        BitcoinAddress = Wallet.Address.ToString()
                    },
                    TimeStamp = DateTime.UtcNow
                }
            };

            this.Backend.SendRequest(request);
            this.SentRequests.Add(request);

            this.Logs = new ObservableCollection <Models.Log>();
        }
Example #21
0
        /// <summary>
        /// Adds a Captioning to an existing video
        /// http://docs.brightcove.com/en/media/reference.html#Video_Write
        /// The captions can either be uploaded to BC or be referred to by an external url
        /// BrightCove supports the DFXP and SMPTE-TT formats
        /// http://support.brightcove.com/en/docs/using-captions-smart-player-api
        /// </summary>
        /// <param name="caption_source">Metadata about the captions</param>
        /// <param name="options">Parameters (options) including the ID of the video that MUST be set</param>
        /// <param name="captions">a buffer containing DFXP or SMPTE-TT caption data</param>
        /// <returns>the captionSources object</returns>
        public RPCResponse <BCCaptionSources> AddCaptioning(BCCaptionSource caption_source, BCAddCaptioningOptions options, byte[] captions)
        {
            Dictionary <string, object> postParams = new Dictionary <string, object>();

            Builder builder = new Builder()
                              .AppendObject("caption_source", caption_source.ToJSON(JSONType.Create))
                              .Append(",").AppendField("token", Account.WriteToken.Value);

            if (!string.IsNullOrEmpty(options.filename))
            {
                builder.Append(",").AppendField("filename", options.filename);
            }

            if (options.maxsize > 0)
            {
                builder.Append(",").AppendField("maxsize", options.maxsize);
            }

            if (!string.IsNullOrEmpty(options.file))
            {
                throw new System.ArgumentException("The file property not supported.  Pass the captions in as a byte array.");
            }

            if (!string.IsNullOrEmpty(options.file_checksum))
            {
                builder.Append(",").AppendField("file_checksum", options.file_checksum);
            }

            // Either a video_id or video_reference_id is required
            if (options.video_id > 0)
            {
                builder.Append(",").AppendField("video_id", options.video_id);
            }
            else if (!string.IsNullOrEmpty(options.video_reference_id))
            {
                builder.Append(",").AppendField("video_reference_id", options.video_reference_id);
            }
            else
            {
                throw new System.ArgumentException("A video_id or video_reference_id is required for add_captioning");
            }

            RPCRequest rpc = new RPCRequest();

            rpc.method     = "add_captioning";
            rpc.parameters = builder.ToString();
            postParams.Add("json", rpc.ToJSON());

            postParams.Add("file", new UploadBufferParameter(captions, "captions.dfxp"));

            // Get the JSon reader returned from the APIRequest
            // RPCResponse<BCCaptionSources> rpcr = BCAPIRequest.ExecuteWriteFile<BCCaptionSources>(postParams, this.Account, @"C:\dev\svn\BrightCove\TestFormApp\sample_captions.dfxp");
            RPCResponse <BCCaptionSources> rpcr = BCAPIRequest.ExecuteWriteNew <BCCaptionSources>(postParams, this.Account);

            return(rpcr);
        }
Example #22
0
        /// <summary>
        /// Returns exit data for a given utxo
        /// </summary>
        /// <param name="position">utxo position</param>
        /// <returns></returns>
        public async Task <ExitData> SendRequestAsync(BigInteger position)
        {
            if (position == null)
            {
                throw new ArgumentNullException(nameof(position));
            }

            JObject    obj     = JObject.Parse(string.Format("{{\"utxo_pos\":{0}}}", position.ToString()));
            RPCRequest request = new RPCRequest(route, obj);

            return(await client.SendRequestAsync <ExitData>(request));
        }
Example #23
0
        public void Deserialize <PARSER>(PARSER parser, ref RPCRequest <MessagePackParser> outValue) where PARSER : IParser <PARSER>
        {
            var it = parser.ListItems.GetEnumerator();

            it.MoveNext(); if (it.Current.GetInt32() != 0)
            {
                throw new FormatException("request should 0");
            }
            it.MoveNext(); outValue.Id          = it.Current.GetInt32();
            it.MoveNext(); outValue.Method      = it.Current.GetString();
            it.MoveNext(); outValue.ParamsBytes = it.Current.Dump();
        }
        /// <summary>
        /// Call this function in an HTTP POST request to determine the status of an upload.
        /// </summary>
        /// <param name="video_id">
        /// The id of the video whose status you'd like to get.
        /// </param>
        /// <param name="reference_id">
        /// The publisher-assigned reference id of the video whose status you'd like to get.
        /// </param>
        /// <returns>
        /// an UploadStatusEnum that specifies the current state of the upload.
        /// </returns>
        private RPCResponse <UploadStatusEnum> GetUploadStatus(long video_id, string reference_id)
        {
            // Generate post objects
            Dictionary <string, object> postParams = new Dictionary <string, object>();

            //add video to the post params
            RPCRequest rpc = new RPCRequest();

            rpc.method = "get_upload_status";
            if (video_id > -1)
            {
                rpc.parameters = "\"video_id\": " + video_id.ToString();
            }
            else if (reference_id != null)
            {
                rpc.parameters = "\"reference_id\": " + video_id.ToString();
            }
            rpc.parameters += " ,\"token\": \"" + Account.WriteToken.Value + "\"";

            postParams.Add("json", rpc.ToJSON());

            //Get the JSon reader returned from the APIRequest
            RPCResponse rpcr = BCAPIRequest.ExecuteWrite(postParams, Account);
            RPCResponse <UploadStatusEnum> rpcr2 = new RPCResponse <UploadStatusEnum>();

            rpcr2.error = rpcr.error;
            rpcr2.id    = rpcr.id;

            switch (rpcr.result)
            {
            case "COMPLETE":
                rpcr2.result = UploadStatusEnum.COMPLETE;
                break;

            case "ERROR":
                rpcr2.result = UploadStatusEnum.ERROR;
                break;

            case "PROCESSING":
                rpcr2.result = UploadStatusEnum.PROCESSING;
                break;

            case "UPLOADING":
                rpcr2.result = UploadStatusEnum.UPLOADING;
                break;

            default:
                rpcr2.result = UploadStatusEnum.UNDEFINED;
                break;
            }
            return(rpcr2);
        }
        /// <summary>
        /// Submits signed transaction to the child chain and returns transaction receipt
        /// </summary>
        /// <param name="transaction">signed transaction</param>
        /// <returns></returns>
        public async Task <TransactionReceipt> SendRequestAsync(string transaction)
        {
            if (transaction == null || transaction == string.Empty || transaction == "0x")
            {
                throw new ArgumentException("Invalid transaction data");
            }

            RPCRequest request = new RPCRequest(route);

            request.Parameters.Add("transaction", transaction.EnsureHexPrefix());

            return(await client.SendRequestAsync <TransactionReceipt>(request));
        }
Example #26
0
        /// <summary>
        /// Returns balance data of given address
        /// </summary>
        /// <param name="address">account address</param>
        /// <returns></returns>
        public async Task <BalanceData[]> SendRequestAsync(string address)
        {
            if (address == null)
            {
                throw new ArgumentNullException(nameof(address));
            }

            RPCRequest request = new RPCRequest(route);

            request.Parameters.Add("address", address.EnsureHexPrefix());

            return(await client.SendRequestAsync <BalanceData[]>(request));
        }
Example #27
0
 private static void _messageConsumer()
 {
     while (!taskCts.IsCancellationRequested)
     {
         try {
             RPCRequest req = MessageQueue.Take(taskCts.Token);
             //send the message, populate the reply and notify the listeners
             req.Send();
         } catch (OperationCanceledException) {
             break;
         }
     }
 }
Example #28
0
        /// <summary>
        /// Proves transaction is canonical
        /// </summary>
        /// <param name="txBytes">in-flight transaction bytes body</param>
        /// <returns></returns>
        public async Task <CanonicalProofData> SendRequestAsync(string txBytes)
        {
            if (txBytes == null)
            {
                throw new ArgumentNullException(nameof(txBytes));
            }

            RPCRequest request = new RPCRequest(route);

            request.Parameters.Add("txBytes", txBytes.EnsureHexPrefix());

            return(await client.SendRequestAsync <CanonicalProofData>(request));
        }
Example #29
0
        public void ScopeInjectionTest()
        {
            var env = new RPCExecutor();

            var cla = new TestClassA();

            env.AddTargetObject(cla);

            var req    = new RPCRequest(typeof(int), nameof(TestClassA.Add2), 1);
            var result = env.Invoke(req, new object[] { new TestClassB(2) });

            Assert.AreEqual(3, result);
        }
Example #30
0
        /// <summary>
        /// Returns transaction data with given hash
        /// </summary>
        /// <param name="txHash">transaction hash (id)</param>
        /// <returns></returns>
        public async Task <TransactionDetails> SendRequestAsync(string txHash)
        {
            if (txHash == null)
            {
                throw new ArgumentNullException(nameof(txHash));
            }

            RPCRequest request = new RPCRequest(route);

            request.Parameters.Add("id", txHash.EnsureHexPrefix());

            return(await client.SendRequestAsync <TransactionDetails>(request));
        }
Example #31
0
		public RPCResponse SendCommand(RPCRequest request, bool throwIfRPCError = true)
		{
			try
			{
				return SendCommandAsync(request, throwIfRPCError).Result;
			}
			catch(AggregateException aex)
			{
				ExceptionDispatchInfo.Capture(aex.InnerException).Throw();
				return null; //Can't happen
			}
		}
Example #32
0
        public RPCResponse SendCommand(RPCRequest request)
        {
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(Address);
            webRequest.Credentials = Credentials;
            webRequest.ContentType = "application/json-rpc";
            webRequest.Method = "POST";

            var writer = new StringWriter();
            request.WriteJSON(writer);
            writer.Flush();
            var json = writer.ToString();
            var bytes = Encoding.UTF8.GetBytes(json);
            webRequest.ContentLength = bytes.Length;
            Stream dataStream = webRequest.GetRequestStream();
            dataStream.Write(bytes, 0, bytes.Length);
            dataStream.Close();

            RPCResponse response = null;
            try
            {
                WebResponse webResponse = webRequest.GetResponse();
                response = RPCResponse.Load(webResponse.GetResponseStream());
                response.ThrowIfError();
            }
            catch(WebException ex)
            {
                if(ex.Response == null)
                    throw;
                response = RPCResponse.Load(ex.Response.GetResponseStream());
                response.ThrowIfError();
            }
            return response;
        }
Example #33
0
		public async Task<RPCResponse> SendCommandAsync(RPCRequest request, bool throwIfRPCError = true)
		{
			var webRequest = (HttpWebRequest)WebRequest.Create(Address);
			webRequest.Credentials = Credentials;
			webRequest.ContentType = "application/json-rpc";
			webRequest.Method = "POST";

			var writer = new StringWriter();
			request.WriteJSON(writer);
			writer.Flush();
			var json = writer.ToString();
			var bytes = Encoding.UTF8.GetBytes(json);
#if !PORTABLE
			webRequest.ContentLength = bytes.Length;
#endif
			var dataStream = await webRequest.GetRequestStreamAsync().ConfigureAwait(false);
			await dataStream.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
			dataStream.Dispose();
			RPCResponse response;
			try
			{
				using(var webResponse = await webRequest.GetResponseAsync().ConfigureAwait(false))
				{
					response = RPCResponse.Load(webResponse.GetResponseStream());
				}
				if(throwIfRPCError)
					response.ThrowIfError();
			}
			catch(WebException ex)
			{
				if(ex.Response == null)
					throw;
				response = RPCResponse.Load(ex.Response.GetResponseStream());
				if(throwIfRPCError)
					response.ThrowIfError();
			}
			return response;
		}