public virtual JsonRpcResponse Execute()
        {
            JsonRpcResponse response = new JsonRpcResponse();
            // get the method from RpcMethods
            MethodInfo mi = RpcMethods.FirstOrDefault(m => m.Name.Equals(Method, StringComparison.InvariantCultureIgnoreCase));

            // if its not there get it from all methods
            if (mi == null)
            {
                mi = AllMethods.FirstOrDefault(m => m.Name.Equals(Method, StringComparison.InvariantCultureIgnoreCase));
            }
            // if its not there set error in the response
            if (mi == null)
            {
                response = GetErrorResponse(JsonRpcFaultCodes.MethodNotFound);
            }
            else
            {
                ExecutionRequest execRequest = ExecutionRequest.Create(Incubator, mi, GetInputParameters(mi));
                if (execRequest.Execute())
                {
                    response.Result = execRequest.Result;
                }
                else
                {
                    response = GetErrorResponse(JsonRpcFaultCodes.InternalError);
                }
            }

            return(response);
        }
Exemplo n.º 2
0
        private void button2_Click(object sender, EventArgs e)
        {
            string username    = ConfigurationManager.AppSettings.Get("rpcusername");
            string password    = ConfigurationManager.AppSettings.Get("rpcpassword");
            string wallet_url  = ConfigurationManager.AppSettings.Get("wallet_url");
            string wallet_port = ConfigurationManager.AppSettings.Get("wallet_port");

            RpcMethods rpc = new RpcMethods(username, password, wallet_url, wallet_port);

            try
            {
                string tx_id2 = txidbox2.Text;

                JObject obj1 = JObject.Parse(rpc.GetRawTransaction(tx_id2));
                if (string.IsNullOrEmpty(obj1["error"].ToString()))
                {
                    string flodata = "";
                    flodata          = obj1["result"]["flodata"].ToString();
                    label2.Text      = flodata;
                    label2.ForeColor = Color.Green;
                    label2.Visible   = true;
                }
                else
                {
                    label2.Text      = "Error retrieving reviews from the flo!!";
                    label2.ForeColor = Color.Green;
                    label2.Visible   = true;
                }
            }
            catch (RpcInternalServerErrorException ex)
            {
                var errCode    = 0;
                var errMessage = string.Empty;
                if (ex.RpcErrorCode.GetHashCode() != 0)
                {
                    errCode    = ex.RpcErrorCode.GetHashCode();
                    errMessage = ex.RpcErrorCode.ToString();
                }
                Console.WriteLine("Exception :" + errCode + "-" + errMessage);


                label2.Text      = "Internal server error!!";
                label2.ForeColor = Color.Red;
                label2.Visible   = true;
                label2.Visible   = true;
            }
            catch (Exception ex1)
            {
                Console.WriteLine("Exception :" + ex1.ToString());
                label2.Text      = "Error connecting to the server!!";
                label2.ForeColor = Color.Red;
                label2.Visible   = true;
                label2.Visible   = true;
            }
        }
Exemplo n.º 3
0
        T MakeRequest <T>(RpcMethods method, params object[] parameters)
        {
            bool ok;
            T    result = default(T);

            try
            {
                result = _rpcConnector.MakeRequest <T>(method, parameters);
                if (result == null)
                {
                    Console.WriteLine("NMC Connector is not configured");
                    ok = false;
                }
                else
                {
                    ok = true;
                }
            }
            catch (RpcException ex)
            {
                if ((ex.InnerException is System.IO.IOException) || (ex.InnerException is WebException && ((WebException)ex.InnerException).Response == null))
                {
                    Console.WriteLine("Unable to connect to Namecoin client: {0}", ex.Message);
                    if (ex.InnerException != null)
                    {
                        Console.WriteLine(" Inner: {0}", ex.InnerException.Message);
                    }
                }
                else
                {
                    WebException webEx = ex.InnerException as WebException;
                    if (webEx != null && webEx.Response is HttpWebResponse && ((HttpWebResponse)webEx.Response).StatusCode == HttpStatusCode.Unauthorized)
                    {
                        Console.WriteLine(" Not authorized to connect to wallet...");
                        TryUpdateApiCreds();
                    }
                    else
                    {
                        Console.WriteLine("An RPC Error Occurred: {0}", ex.InnerException != null ? ex.InnerException.Message : ex.Message);
                    }
                }
                ok = false;
            }

            if (ok != Available)
            {
                Available = ok;
                EventSink.InvokeNameServerAvailableChanged(this, new NameServerAvailableChangedEventArgs(Available));
            }

            return(result);
        }
Exemplo n.º 4
0
        private void validation_Load(object sender, EventArgs e)
        {
            txtCertificate_no.Focus();
            con = new SqlConnection(connstr);
            con.Open();


            string username    = ConfigurationManager.AppSettings.Get("username");
            string password    = ConfigurationManager.AppSettings.Get("password");
            string wallet_url  = ConfigurationManager.AppSettings.Get("wallet_url");
            string wallet_port = ConfigurationManager.AppSettings.Get("wallet_port");


            RpcMethods rpc = new RpcMethods(username, password, wallet_url, wallet_port);
        }
Exemplo n.º 5
0
        public Certificate(string str1, string str2, int str4, string str5, string str6, string str7, string str8)
        {
            InitializeComponent();
            name.Text   = str1;
            course.Text = str2;
            marks.Text  = str4.ToString();
            grade.Text  = str5;
            jdate.Text  = str6;
            cdate.Text  = str7;
            DateTime now = DateTime.Now;

            parentname.Text = str8;
            string username = ConfigurationManager.AppSettings.Get("rpcusername");
            string passcode = ConfigurationManager.AppSettings.Get("rpcpassword");
            string url1     = ConfigurationManager.AppSettings.Get("wallet_url");
            string port     = ConfigurationManager.AppSettings.Get("wallet_port");

            RpcMethods obj = new RpcMethods(username, passcode, url1, port);

            try
            {
                string  flodata = str1 + "**" + str8 + "**" + str2 + "**" + str5 + "**" + str6 + "**" + str7 + "**" + now.ToString() + "**" + "DIGITAL SIGNATURE BY:-366piTECH";
                JObject Jobj    = JObject.Parse(obj.SendToAddress(address, 1M, "test send", "testing 123", false, false, 1, "UNSET", flodata));
                if (string.IsNullOrEmpty(Jobj["error"].ToString()))
                {
                    url += Jobj["result"].ToString();
                }
            }
            catch (RpcInternalServerErrorException ex1)
            {
                var    err_code    = 0;
                string err_message = "";
                if (ex1.RpcErrorCode.GetHashCode() != 0)
                {
                    err_code    = ex1.RpcErrorCode.GetHashCode();
                    err_message = ex1.RpcErrorCode.ToString();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception:" + ex);
            }
        }
Exemplo n.º 6
0
        private T MakeRequestClient <T>(RpcMethods rpcMethod, params object[] parameters)
        {
            var jsonRpcRequest = new JsonRpcRequest(1, rpcMethod.ToString(), parameters);

            try
            {
                var request_json  = jsonRpcRequest.GetJson();
                var content       = new StringContent(request_json, Encoding.UTF8, "application/json");
                var result        = client.PostAsync(_coinService.Parameters.SelectedDaemonUrl, content).Result;
                var result_string = result.Content.ReadAsStringAsync().Result;
                var resp          = JsonConvert.DeserializeObject <JsonRpcResponse <T> >(result_string);
                return(resp.Result);
            }
            catch (AggregateException aggregate)
            {
                foreach (var e in aggregate.Flatten().InnerExceptions)
                {
                    if (e is HttpRequestException)
                    {
                        throw new ConnectionException(e.Message, 1);
                    }
                    else
                    {
                        throw;
                    }
                }
                throw aggregate;
            }
            catch (JsonException jsonException)
            {
                throw new RpcResponseDeserializationException("There was a problem deserializing the response from the wallet", jsonException);
            }
            catch (ProtocolViolationException protocolViolationException)
            {
                throw new RpcException("Unable to connect to the server", protocolViolationException);
            }
            catch (Exception exception)
            {
                var queryParameters = jsonRpcRequest.Parameters.Cast <string>().Aggregate(string.Empty, (current, parameter) => current + (parameter + " "));
                throw new Exception($"A problem was encountered while calling MakeRpcRequest() for: {jsonRpcRequest.Method} with parameters: {queryParameters}. \nException: {exception.Message}");
            }
        }
Exemplo n.º 7
0
 public T MakeRequest <T>(RpcMethods rpcMethod, params object[] parameters)
 {
     return(MakeRequest <T>(rpcMethod, 0, parameters));
 }
Exemplo n.º 8
0
        public async Task <T> MakeRequestAsync <T>(RpcMethods rpcMethod, CancellationToken cancellationToken, params object[] parameters)
        {
            if (_disposed)
            {
                throw new ObjectDisposedException(nameof(_httpClient));
            }

            var jsonRpcRequest = new JsonRpcRequest(1, rpcMethod.ToString(), parameters);

            using (var request = new HttpRequestMessage(HttpMethod.Post, _coinService.Parameters.SelectedDaemonUrl))
            {
                var requestContent = jsonRpcRequest.GetBytes();

                request.Content = new ByteArrayContent(requestContent);
                request.Content.Headers.ContentType   = new MediaTypeHeaderValue("application/json-rpc");
                request.Content.Headers.ContentLength = requestContent.Length;

                try
                {
                    using (var response = await _httpClient.Value.SendAsync(request,
                                                                            HttpCompletionOption.ResponseContentRead, cancellationToken))
                    {
                        if (response.Content == null)
                        {
                            throw new RpcException(
                                      "The RPC request was either not understood by the server or there was a problem executing the request");
                        }

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

                        if (!response.IsSuccessStatusCode)
                        {
                            switch (response.StatusCode)
                            {
                            case HttpStatusCode.InternalServerError:
                                try
                                {
                                    var jsonRpcResponseObject =
                                        JsonConvert.DeserializeObject <JsonRpcResponse <object> >(responseContent);

                                    var internalServerErrorException =
                                        new RpcInternalServerErrorException(jsonRpcResponseObject.Error.Message)
                                    {
                                        RpcErrorCode = jsonRpcResponseObject.Error.Code
                                    };

                                    throw internalServerErrorException;
                                }
                                catch (JsonException)
                                {
                                    throw new RpcException(responseContent);
                                }

                            default:
                                throw new RpcException(
                                          "The RPC request was either not understood by the server or there was a problem executing the request");
                            }
                        }

                        var rpcResponse = JsonConvert.DeserializeObject <JsonRpcResponse <T> >(responseContent);
                        return(rpcResponse.Result);
                    }
                }
                catch (HttpRequestException httpRequestException)
                {
                    throw new RpcException(
                              "The RPC request was either not understood by the server or there was a problem executing the request",
                              httpRequestException);
                }
                catch (JsonException jsonException)
                {
                    throw new RpcResponseDeserializationException(
                              "There was a problem deserializing the response from the wallet", jsonException);
                }
                catch (TimeoutException)
                {
                    throw new RpcRequestTimeoutException("The operation has timed out");
                }
                catch (RpcInternalServerErrorException)
                {
                    throw;
                }
                catch (RpcException)
                {
                    throw;
                }
                catch (Exception exception)
                {
                    var queryParameters = jsonRpcRequest.Parameters.Cast <string>().Aggregate(string.Empty, (current, parameter) => current + (parameter + " "));
                    throw new Exception($"A problem was encountered while calling MakeRpcRequest() for: {jsonRpcRequest.Method} with parameters: {queryParameters}. \nException: {exception.Message}");
                }
            }
        }
Exemplo n.º 9
0
        public T MakeRequest <T>(RpcMethods rpcMethod, params object[] parameters)
        {
            var jsonRpcRequest = new JsonRpcRequest(1, rpcMethod.ToString(), parameters);

            var webRequest = (HttpWebRequest)WebRequest.Create(_coinService.Parameters.SelectedDaemonUrl);

            SetBasicAuthHeader(webRequest, _coinService.Parameters.RpcUsername, _coinService.Parameters.RpcPassword);
            webRequest.Credentials = new NetworkCredential(_coinService.Parameters.RpcUsername, _coinService.Parameters.RpcPassword);
            webRequest.ContentType = "application/json-rpc";
            webRequest.Method      = "POST";
            webRequest.Proxy       = null;
            webRequest.Timeout     = _coinService.Parameters.RpcRequestTimeoutInSeconds * GlobalConstants.MillisecondsInASecond;
            var byteArray = jsonRpcRequest.GetBytes();

            webRequest.ContentLength = jsonRpcRequest.GetBytes().Length;

            try
            {
                using (var dataStream = webRequest.GetRequestStream())
                {
                    dataStream.Write(byteArray, 0, byteArray.Length);
                    dataStream.Dispose();
                }
            }
            catch (Exception exception)
            {
                throw new RpcException("There was a problem sending the request to the wallet", exception);
            }

            try
            {
                string json;

                using (var webResponse = webRequest.GetResponse())
                {
                    using (var stream = webResponse.GetResponseStream())
                    {
                        using (var reader = new StreamReader(stream))
                        {
                            var result = reader.ReadToEnd();
                            reader.Dispose();
                            json = result;
                        }
                    }
                }

                var rpcResponse = JsonConvert.DeserializeObject <JsonRpcResponse <T> >(json);

                return(rpcResponse.Result);
            }
            catch (WebException webException)
            {
                #region RPC Internal Server Error (with an Error Code)

                var webResponse = webException.Response as HttpWebResponse;

                if (webResponse != null)
                {
                    switch (webResponse.StatusCode)
                    {
                    case HttpStatusCode.InternalServerError:
                    {
                        using (var stream = webResponse.GetResponseStream())
                        {
                            if (stream == null)
                            {
                                throw new RpcException("The RPC request was either not understood by the server or there was a problem executing the request", webException);
                            }

                            using (var reader = new StreamReader(stream))
                            {
                                var result = reader.ReadToEnd();
                                reader.Dispose();

                                try
                                {
                                    var jsonRpcResponseObject = JsonConvert.DeserializeObject <JsonRpcResponse <object> >(result);

                                    var internalServerErrorException = new RpcInternalServerErrorException(jsonRpcResponseObject.Error.Message, webException)
                                    {
                                        RpcErrorCode = jsonRpcResponseObject.Error.Code
                                    };

                                    throw internalServerErrorException;
                                }
                                catch (JsonException)
                                {
                                    throw new RpcException(result, webException);
                                }
                            }
                        }
                    }

                    default:
                        throw new RpcException("The RPC request was either not understood by the server or there was a problem executing the request", webException);
                    }
                }

                #endregion

                #region RPC Time-Out

                if (webException.Message == "The operation has timed out")
                {
                    throw new RpcRequestTimeoutException(webException.Message);
                }

                #endregion

                throw new RpcException("An unknown web exception occured while trying to read the JSON response", webException);
            }
            catch (JsonException jsonException)
            {
                throw new RpcResponseDeserializationException("There was a problem deserializing the response from the wallet", jsonException);
            }
            catch (ProtocolViolationException protocolViolationException)
            {
                throw new RpcException("Unable to connect to the server", protocolViolationException);
            }
            catch (Exception exception)
            {
                var queryParameters = jsonRpcRequest.Parameters.Cast <string>().Aggregate(string.Empty, (current, parameter) => current + (parameter + " "));
                throw new Exception($"A problem was encountered while calling MakeRpcRequest() for: {jsonRpcRequest.Method} with parameters: {queryParameters}. \nException: {exception.Message}");
            }
        }
Exemplo n.º 10
0
        public T MakeRequest <T>(RpcMethods rpcMethod, params object[] parameters)
        {
            JsonRpcResponse <T> rpcResponse = MakeRpcRequest <T>(new JsonRpcRequest(1, rpcMethod.ToString(), parameters));

            return(rpcResponse == null ? default(T) : rpcResponse.Result);
        }
Exemplo n.º 11
0
        private void Button1_Click(object sender, EventArgs e)
        {
            string username = ConfigurationManager.AppSettings.Get("rpcusername");
            string passcode = ConfigurationManager.AppSettings.Get("rpcpassword");
            string url1     = ConfigurationManager.AppSettings.Get("wallet_url");
            string port     = ConfigurationManager.AppSettings.Get("wallet_port");

            RpcMethods obj = new RpcMethods(username, passcode, url1, port);

            try
            {
                string fn      = first.Text.Trim();
                string ln      = last.Text.Trim();
                string c       = college.Text.Trim();
                string r       = roll.Text.Trim();
                string m       = mobile.Text.Trim();
                string em      = email.Text.Trim();
                string p       = pass.Text;
                string t       = type.Text.Trim();
                string g       = guardian.Text.Trim();
                string YYYY    = yj.Text.Trim();
                string MM      = mj.Text.Trim();
                string DD      = dj.Text.Trim();
                string yyyy    = yc.Text.Trim();
                string mm      = mc.Text.Trim();
                string dd      = dc.Text.Trim();
                string jdate   = DD + "/" + MM + "/" + YYYY;
                string cdate   = dd + "/" + mm + "/" + yyyy;
                string n       = fn + " " + ln;
                string txid    = "";
                string qry     = string.Empty;
                string message = fn + "--" + ln + "--" + c + "--" + r + "--" + m + "--" + em + "--" + t + "--" + g + "--" + jdate + "--" + cdate + "--" + ComputeSha256Hash(p);



                JObject jobj = JObject.Parse(obj.SendToAddress(address, 1M, "test send", "testing 123", false, false, 1, "UNSET", message));
                if (string.IsNullOrEmpty(jobj["error"].ToString()))
                {
                    url += jobj["result"].ToString();

                    response.Text      = "MESSAGE SENT SUCCESSFULLY";
                    response.ForeColor = Color.Blue;
                    response.Visible   = true;
                    txid = jobj["result"].ToString();
                    using (SaveFileDialog sfd = new SaveFileDialog()
                    {
                        Filter = "JPEG|*.jpg", ValidateNames = true
                    })
                    {
                        if (sfd.ShowDialog() == DialogResult.OK)
                        {
                            MessagingToolkit.QRCode.Codec.QRCodeEncoder encoder = new MessagingToolkit.QRCode.Codec.QRCodeEncoder();
                            encoder.QRCodeScale = 8;
                            Bitmap bmp = encoder.Encode(jobj["result"].ToString());

                            qr.Image = bmp;

                            bmp.Save(sfd.FileName, ImageFormat.Jpeg);
                        }
                    }

                    SqlConnection conn = new SqlConnection(@"Data Source=BT1707113\SQLEXPRESS02;Initial Catalog=root;Integrated Security=True");
                    conn.Open();
                    qry = "insert into skills values ('" + n + "','" + txid + "',NULL,NULL,NULL,NULL,NULL,NULL,'0','" + t + "','" + jdate + "','" + cdate + "','" + g + "');";
                    SqlCommand cmd = new SqlCommand(qry, conn);
                    cmd.ExecuteNonQuery();
                    conn.Close();
                    Internlogin ob = new Internlogin();
                    this.Hide();
                    ob.Show();
                }
                else
                {
                    response.Text      = "MESSAGE WAS NOT SENT";
                    response.ForeColor = Color.Blue;
                    response.Visible   = true;
                }
            }

            catch (RpcInternalServerErrorException ex1)
            {
                var    err_code    = 0;
                string err_message = "";
                if (ex1.RpcErrorCode.GetHashCode() != 0)
                {
                    err_code    = ex1.RpcErrorCode.GetHashCode();
                    err_message = ex1.RpcErrorCode.ToString();
                }
                Console.WriteLine("Error:" + err_code + "\n" + err_message);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception:" + ex);
                response.Text    = "Message Not Sent";
                response.Visible = true;
            }
        }
Exemplo n.º 12
0
        static void Main(string[] args)
        {
            string username    = ConfigurationManager.AppSettings.Get("username");
            string password    = ConfigurationManager.AppSettings.Get("password");
            string wallet_url  = ConfigurationManager.AppSettings.Get("wallet_url");
            string wallet_port = ConfigurationManager.AppSettings.Get("wallet_port");


            RpcMethods rpc = new RpcMethods(username, password, wallet_url, wallet_port);


            try
            {
                //Get Info
                JObject obj = JObject.Parse(rpc.GetInfo());

                if (string.IsNullOrEmpty(obj["error"].ToString()))
                {
                    Console.WriteLine("Get Info : " + obj["result"]);
                }
                else
                {
                    Console.WriteLine("Get Info Error : " + obj["error"]);
                }


                //Get Help

                obj = JObject.Parse(rpc.Help("getinfo"));

                if (string.IsNullOrEmpty(obj["error"].ToString()))
                {
                    Console.WriteLine("Get Help : " + obj["result"]);
                }
                else
                {
                    Console.WriteLine("Get Help Error : " + obj["error"]);
                }

                //Get Balance

                obj = JObject.Parse(rpc.GetBalance(""));

                if (string.IsNullOrEmpty(obj["error"].ToString()))
                {
                    Console.WriteLine("Balance : " + obj["result"]);
                }
                else
                {
                    Console.WriteLine("Get Balance Error : " + obj["error"]);
                }

                //Get Wallet Info
                obj = JObject.Parse(rpc.GetWalletInfo());

                if (string.IsNullOrEmpty(obj["error"].ToString()))
                {
                    Console.WriteLine("Wallet Info : " + obj["result"]);
                }
                else
                {
                    Console.WriteLine("Wallet Info Error : " + obj["error"]);
                }

                //Send Transaction
                obj = JObject.Parse(rpc.SendToAddress("Flo Address", 1.0M, "Test comment", "Test Comment", false, false, 1, "UNSET", "This is a test message"));

                if (string.IsNullOrEmpty(obj["error"].ToString()))
                {
                    Console.WriteLine("Transaction ID : " + obj["result"]);
                }
                else
                {
                    Console.WriteLine("Send Transaction Error : " + obj["error"]);
                }
            }
            catch (RpcInternalServerErrorException exception)
            {
                var errorCode    = 0;
                var errorMessage = string.Empty;

                if (exception.RpcErrorCode.GetHashCode() != 0)
                {
                    errorCode    = exception.RpcErrorCode.GetHashCode();
                    errorMessage = exception.RpcErrorCode.ToString();
                }

                Console.WriteLine("[Failed] {0} {1} {2}", exception.Message, errorCode != 0 ? "Error code: " + errorCode : string.Empty, !string.IsNullOrWhiteSpace(errorMessage) ? errorMessage : string.Empty);
            }
            catch (Exception exception)
            {
                Console.WriteLine("[Failed]\n\nPlease check your configuration and make sure that the daemon is up and running and that it is synchronized. \n\nException: " + exception);
            }

            Console.Read();
        }
Exemplo n.º 13
0
        private void Submit_Click(object sender, EventArgs e)
        {
            con.Open();
            SqlCommand cmd = con.CreateCommand();

            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "insert into [Short Details Table] (ApplicationNumber,Title,CopyrightDate,AuthorName,StatementOfRight) values('" + textBox11.Text + "','" + titlebox.Text + "','" + dateTimePicker1.Text + "','" + namebox.Text + "','" + listBox1.Text + "')";
            cmd.ExecuteNonQuery();
            con.Close();

            string     username    = ConfigurationManager.AppSettings.Get("rpcusername");
            string     password    = ConfigurationManager.AppSettings.Get("rpcpassword");
            string     wallet_url  = ConfigurationManager.AppSettings.Get("wallet_url");
            string     wallet_port = ConfigurationManager.AppSettings.Get("wallet_port");
            string     flodata     = "";
            RpcMethods rpc         = new RpcMethods(username, password, wallet_url, wallet_port);

            try
            {
                string title   = titlebox.Text;
                string date    = dateTimePicker1.Text;
                string name    = namebox.Text;
                string right   = listBox1.Text;
                string send_to = "oYKg7fpcQs4DCmLSwqJvUFpnnXLdffGGkm";



                if ((titlebox.Text == "") || (dateTimePicker1.Text == "") || (namebox.Text == "") || (send_to == ""))
                {
                    MessageBox.Show("FILL UP ALL THE DETAILS");
                }
                else if ((listBox1.SelectedIndex == -1) || (listBox1.Text == "(none)"))
                {
                    MessageBox.Show("Select either one of the statement of rights\n scroll down and  CLICK on the options to select.");
                }
                else
                {
                    flodata = " \t" + title + "\n" + "copyright ©" + date + " " + name + " " + right;

                    JObject jobj = JObject.Parse(rpc.SendToAddress(send_to, 0.01M, "copyright system", "copyright", false, false, 1, "UNSET", flodata));

                    if (string.IsNullOrEmpty(jobj["error"].ToString()))
                    {
                        url               += jobj["result"];
                        labelmsg.Text      = "Details saved successfully to FLO";
                        labelmsg.Visible   = true;
                        labelmsg.ForeColor = Color.White;
                        data.Text          = flodata;
                        data.Visible       = true;
                        data.ForeColor     = Color.White;
                        linkLabel1.Visible = true;
                    }
                    else
                    {
                        labelmsg.Text      = "Error!!!" + "could not retrieve any transaction details..plzz check ur address";
                        labelmsg.Visible   = true;
                        labelmsg.ForeColor = Color.Red;
                    }
                }
            }
            catch (RpcInternalServerErrorException ex)
            {
                var errCode    = 0;
                var errMessage = string.Empty;
                if (ex.RpcErrorCode.GetHashCode() != 0)
                {
                    errCode    = ex.RpcErrorCode.GetHashCode();
                    errMessage = ex.RpcErrorCode.ToString();
                }
                Console.WriteLine("Exception :" + errCode + "-" + errMessage);


                labelmsg.Text      = "INternal server error!!";
                labelmsg.ForeColor = Color.Red;
                labelmsg.Visible   = true;
                labelmsg.Visible   = true;
            }
            catch (Exception ex1)
            {
                Console.WriteLine("Exception :" + ex1.ToString());
                labelmsg.Text      = "Error connecting to the server!!";
                labelmsg.ForeColor = Color.White;
                labelmsg.Visible   = true;
                labelmsg.Visible   = true;
                MessageBox.Show(labelmsg.Text);
                MessageBox.Show(flodata);
            }
        }
        private void flo_certificate_Load(object sender, EventArgs e)
        {
            string        username    = ConfigurationManager.AppSettings.Get("username");
            string        password    = ConfigurationManager.AppSettings.Get("password");
            string        wallet_url  = ConfigurationManager.AppSettings.Get("wallet_url");
            string        wallet_port = ConfigurationManager.AppSettings.Get("wallet_port");
            string        transid     = "";
            SqlConnection con         = new SqlConnection(connstr);

            con.Open();
            SqlCommand cmd = new SqlCommand("select Trans_no from Flo_record where Certi_no=@certno", con);

            cmd.Parameters.Add(new SqlParameter("@certno", cert_no));
            SqlDataReader reader = cmd.ExecuteReader();

            if (reader.Read())
            {
                transid = reader["Trans_no"].ToString();
            }

            con.Close();


            RpcMethods rpc = new RpcMethods(username, password, wallet_url, wallet_port);


            try
            {
                JObject obj = JObject.Parse(rpc.GetRawTransaction(transid));

                if (string.IsNullOrEmpty(obj["error"].ToString()))
                {
                    string   res  = obj["result"]["floData"].ToString();
                    string[] data = res.Split('#');

                    string name       = data[1].ToString();
                    string fname      = data[2].ToString();
                    string reg        = data[3].ToString();
                    string course     = data[4].ToString();
                    string grade      = data[5].ToString();
                    string percentage = data[6].ToString();
                    string doj        = data[7].ToString();
                    string dop        = data[8].ToString();
                    string cer_date   = data[9].ToString();
                    string cert_num   = data[10].ToString();

                    url = "https://testnet.flocha.in/tx/" + transid;

                    lblName.Text             = name;
                    lblGuardian.Text         = fname;
                    lblReg_no.Text           = reg;
                    lblCourse.Text           = course;
                    lblGrade.Text            = grade;
                    lblPercent.Text          = percentage;
                    lblJoin_Date.Text        = doj;
                    lblCompilition_Date.Text = dop;
                    lblDate.Text             = cer_date;
                    lblCertificate_no.Text   = cert_num;
                    linklblUrl.Text          = url;

                    linklblUrl.Visible = true;
                    QRCodeEncoder enc = new QRCodeEncoder();
                    //Bitmap qrcode = enc.Encode(url);
                    //QRpicbox.Image = qrcode as System.Drawing.Image;
                    Bitmap img;
                    enc.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.H;
                    enc.QRCodeScale        = 10;
                    img            = enc.Encode(url);
                    QRpicbox.Image = img;
                }
                else
                {
                    MessageBox.Show("Get Transaction Error : " + obj["error"]);
                }
            }
            catch (RpcInternalServerErrorException exception)
            {
                var errorCode    = 0;
                var errorMessage = string.Empty;

                if (exception.RpcErrorCode.GetHashCode() != 0)
                {
                    errorCode    = exception.RpcErrorCode.GetHashCode();
                    errorMessage = exception.RpcErrorCode.ToString();
                }

                Console.WriteLine("[Failed] {0} {1} {2}", exception.Message, errorCode != 0 ? "Error code: " + errorCode : string.Empty, !string.IsNullOrWhiteSpace(errorMessage) ? errorMessage : string.Empty);
                MessageBox.Show("Wallet Error Code : " + errorCode);
                linklblUrl.Visible = false;
            }
        }
Exemplo n.º 15
0
        public T MakeRequest <T>(RpcMethods rpcMethod, params object[] parameters)
        {
            id++;
            var jsonRpcRequest = new JsonRpcRequest(id, rpcMethod.ToString(), parameters);
            var webRequest     = (HttpWebRequest)WebRequest.Create(_coinService.Parameters.SelectedDaemonUrl);

            byte[] byteArray;

            if (rpcMethod == RpcMethods.stop) /* Dirty workaround to properly support json notification syntax, lets merge this into library later properly*/
            {
                var jsonRpcRequestNotification = new JsonRpcRequestNotification(rpcMethod.ToString(), parameters);
                SetBasicAuthHeader(webRequest, _coinService.Parameters.RpcUsername, _coinService.Parameters.RpcPassword);
                webRequest.Credentials = new NetworkCredential(_coinService.Parameters.RpcUsername, _coinService.Parameters.RpcPassword);

                webRequest.ContentType = "application/json-rpc";
                webRequest.Method      = "POST";
                webRequest.Proxy       = null;
                webRequest.Timeout     = _coinService.Parameters.RpcRequestTimeoutInSeconds * GlobalConstants.MillisecondsInASecond;
                byteArray = jsonRpcRequestNotification.GetBytes();
                webRequest.ContentLength = jsonRpcRequestNotification.GetBytes().Length;
            }
            else if (rpcMethod == RpcMethods.waitforchange) /* Latest XAYA library addition pases waitforchange arguments as array, this also needs special handling*/
            {
                string[] aRR = new string[parameters.Length];

                for (int s = 0; s < parameters.Length; s++)
                {
                    aRR[s] = parameters[s].ToString();
                }

                var jsonRpcRequestNotification = new JsonRpcRequestArray(id, rpcMethod.ToString(), aRR);
                SetBasicAuthHeader(webRequest, _coinService.Parameters.RpcUsername, _coinService.Parameters.RpcPassword);
                webRequest.Credentials = new NetworkCredential(_coinService.Parameters.RpcUsername, _coinService.Parameters.RpcPassword);

                webRequest.ContentType = "application/json-rpc";
                webRequest.Method      = "POST";
                webRequest.Proxy       = null;
                webRequest.Timeout     = _coinService.Parameters.RpcRequestTimeoutInSeconds * GlobalConstants.MillisecondsInASecond;
                byteArray = jsonRpcRequestNotification.GetBytes();
                webRequest.ContentLength = jsonRpcRequestNotification.GetBytes().Length;
            }
            else
            {
                SetBasicAuthHeader(webRequest, _coinService.Parameters.RpcUsername, _coinService.Parameters.RpcPassword);
                webRequest.Credentials = new NetworkCredential(_coinService.Parameters.RpcUsername, _coinService.Parameters.RpcPassword);

                webRequest.ContentType = "application/json-rpc";
                webRequest.Method      = "POST";
                webRequest.Proxy       = null;
                webRequest.Timeout     = _coinService.Parameters.RpcRequestTimeoutInSeconds * GlobalConstants.MillisecondsInASecond;
                byteArray = jsonRpcRequest.GetBytes();
                webRequest.ContentLength = jsonRpcRequest.GetBytes().Length;
            }

            if (rpcMethod == RpcMethods.waitforchange) /* Dirty workaround to properly support json notification syntax, lets merge this into library later properly*/
            {
                webRequest.Timeout = int.MaxValue;
            }

            try
            {
                using (var dataStream = webRequest.GetRequestStream())
                {
                    dataStream.Write(byteArray, 0, byteArray.Length);
                    dataStream.Dispose();
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine("There was a problem sending the request to the wallet", exception);
                return(default(T));
            }

            try
            {
                string json;

                using (var webResponse = webRequest.GetResponse())
                {
                    using (var stream = webResponse.GetResponseStream())
                    {
                        using (var reader = new StreamReader(stream))
                        {
                            var result = reader.ReadToEnd();
                            reader.Dispose();
                            json = result;
                        }
                    }
                }

                if (json != "")
                {
                    var rpcResponse = JsonConvert.DeserializeObject <JsonRpcResponse <T> >(json);
                    return(rpcResponse.Result);
                }
                else
                {
                    return(default(T));
                }
            }
            catch (WebException webException)
            {
                #region RPC Internal Server Error (with an Error Code)

                var webResponse = webException.Response as HttpWebResponse;

                if (webResponse != null)
                {
                    switch (webResponse.StatusCode)
                    {
                    case HttpStatusCode.InternalServerError:
                    {
                        using (var stream = webResponse.GetResponseStream())
                        {
                            if (stream == null)
                            {
                                throw new RpcException("The RPC request was either not understood by the server or there was a problem executing the request", webException);
                            }

                            using (var reader = new StreamReader(stream))
                            {
                                var result = reader.ReadToEnd();
                                reader.Dispose();

                                try
                                {
                                    var jsonRpcResponseObject = JsonConvert.DeserializeObject <JsonRpcResponse <object> >(result);

                                    var internalServerErrorException = new RpcInternalServerErrorException(jsonRpcResponseObject.Error.Message, webException)
                                    {
                                        RpcErrorCode = jsonRpcResponseObject.Error.Code
                                    };

                                    throw internalServerErrorException;
                                }
                                catch (JsonException)
                                {
                                    throw new RpcException(result, webException);
                                }
                            }
                        }
                    }

                    default:
                        throw new RpcException("The RPC request was either not understood by the server or there was a problem executing the request", webException);
                    }
                }

                #endregion

                #region RPC Time-Out

                if (webException.Message == "The operation has timed out")
                {
                    throw new RpcRequestTimeoutException(webException.Message);
                }

                #endregion

                return(default(T));
            }
            catch (JsonException jsonException)
            {
                throw new RpcResponseDeserializationException("There was a problem deserializing the response from the wallet", jsonException);
            }
            catch (ProtocolViolationException protocolViolationException)
            {
                throw new RpcException("Unable to connect to the server", protocolViolationException);
            }
            catch (Exception exception)
            {
                var queryParameters = jsonRpcRequest.Parameters.Cast <string>().Aggregate(string.Empty, (current, parameter) => current + (parameter + " "));
                throw new Exception($"A problem was encountered while calling MakeRpcRequest() for: {jsonRpcRequest.Method} with parameters: {queryParameters}. \nException: {exception.Message}");
            }
        }
Exemplo n.º 16
0
        private T MakeRequest <T>(RpcMethods rpcMethod, Int16 timedOutRequestsCount, params object[] parameters)
        {
            JsonRpcRequest jsonRpcRequest = new JsonRpcRequest(1, rpcMethod.ToString(), parameters);
            HttpWebRequest webRequest     = (HttpWebRequest)WebRequest.Create(_coinService.Parameters.SelectedDaemonUrl);

            SetBasicAuthHeader(webRequest, _coinService.Parameters.RpcUsername, _coinService.Parameters.RpcPassword);
            webRequest.Credentials = new NetworkCredential(_coinService.Parameters.RpcUsername, _coinService.Parameters.RpcPassword);
            webRequest.ContentType = "application/json-rpc";
            webRequest.Method      = "POST";
            webRequest.Proxy       = null;
            webRequest.Timeout     = _coinService.Parameters.RpcRequestTimeoutInSeconds * GlobalConstants.MillisecondsInASecond;
            Byte[] byteArray = jsonRpcRequest.GetBytes();
            webRequest.ContentLength = jsonRpcRequest.GetBytes().Length;

            try
            {
                using (Stream dataStream = webRequest.GetRequestStream())
                {
                    dataStream.Write(byteArray, 0, byteArray.Length);
                    dataStream.Dispose();
                }
            }
            catch (Exception exception)
            {
                throw new RpcException("There was a problem sending the request to the wallet", exception);
            }

            try
            {
                String json;

                using (WebResponse webResponse = webRequest.GetResponse())
                {
                    using (Stream stream = webResponse.GetResponseStream())
                    {
                        using (StreamReader reader = new StreamReader(stream))
                        {
                            String result = reader.ReadToEnd();
                            reader.Dispose();
                            json = result;
                        }
                    }
                }

                JsonRpcResponse <T> rpcResponse = JsonConvert.DeserializeObject <JsonRpcResponse <T> >(json);
                return(rpcResponse.Result);
            }
            catch (WebException webException)
            {
                #region RPC Internal Server Error (with an Error Code)

                HttpWebResponse webResponse = webException.Response as HttpWebResponse;

                if (webResponse != null)
                {
                    switch (webResponse.StatusCode)
                    {
                    case HttpStatusCode.InternalServerError:
                    {
                        using (Stream stream = webResponse.GetResponseStream())
                        {
                            if (stream == null)
                            {
                                throw new RpcException("The RPC request was either not understood by the server or there was a problem executing the request", webException);
                            }

                            using (StreamReader reader = new StreamReader(stream))
                            {
                                String result = reader.ReadToEnd();
                                reader.Dispose();

                                try
                                {
                                    JsonRpcResponse <Object> jsonRpcResponseObject = JsonConvert.DeserializeObject <JsonRpcResponse <Object> >(result);

                                    RpcInternalServerErrorException internalServerErrorException = new RpcInternalServerErrorException(jsonRpcResponseObject.Error.Message, webException)
                                    {
                                        RpcErrorCode = jsonRpcResponseObject.Error.Code
                                    };

                                    throw internalServerErrorException;
                                }
                                catch (JsonException)
                                {
                                    throw new RpcException(result, webException);
                                }
                            }
                        }
                    }

                    default:
                        throw new RpcException("The RPC request was either not understood by the server or there was a problem executing the request", webException);
                    }
                }

                #endregion

                #region RPC Time-Out

                if (webException.Message == "The operation has timed out")
                {
                    if (_coinService.Parameters.RpcResendTimedOutRequests && ++timedOutRequestsCount <= _coinService.Parameters.RpcTimedOutRequestsResendAttempts)
                    {
                        //  Note: effective delay = delayInSeconds + _rpcRequestTimeoutInSeconds
                        if (_coinService.Parameters.RpcDelayResendingTimedOutRequests)
                        {
                            Double delayInSeconds = _coinService.Parameters.RpcUseBase2ExponentialDelaysWhenResendingTimedOutRequests ? Math.Pow(2, timedOutRequestsCount) : timedOutRequestsCount;

                            if (Debugger.IsAttached)
                            {
                                Console.ForegroundColor = ConsoleColor.Red;
                                Console.WriteLine("RPC request timeout: {0}, will resend {1} of {2} total attempts after {3} seconds (request timeout: {4} seconds)", jsonRpcRequest.Method, timedOutRequestsCount, _coinService.Parameters.RpcTimedOutRequestsResendAttempts, delayInSeconds, _coinService.Parameters.RpcRequestTimeoutInSeconds);
                                Console.ResetColor();
                            }

                            Thread.Sleep((Int32)delayInSeconds * GlobalConstants.MillisecondsInASecond);
                        }

                        return(MakeRequest <T>(rpcMethod, timedOutRequestsCount, parameters));
                    }

                    throw new RpcRequestTimeoutException(webException.Message);
                }

                #endregion

                throw new RpcException("An unknown web exception occured while trying to read the JSON response", webException);
            }
            catch (JsonException jsonException)
            {
                throw new RpcResponseDeserializationException("There was a problem deserializing the response from the wallet", jsonException);
            }
            catch (ProtocolViolationException protocolViolationException)
            {
                throw new RpcException("Unable to connect to the server", protocolViolationException);
            }
            catch (Exception exception)
            {
                String queryParameters = jsonRpcRequest.Parameters.Cast <String>().Aggregate(String.Empty, (current, parameter) => current + (parameter + " "));
                throw new Exception(String.Format("A problem was encountered while calling MakeRpcRequest() for: {0} with parameters: {1}. \nException: {2}", jsonRpcRequest.Method, queryParameters, exception.Message));
            }
        }
        private void Button1_Click(object sender, EventArgs e)
        {
            string username = ConfigurationManager.AppSettings.Get("rpcusername");
            string past     = ConfigurationManager.AppSettings.Get("rpcpassword");
            string url1     = ConfigurationManager.AppSettings.Get("wallet_url");
            string port     = ConfigurationManager.AppSettings.Get("wallet_port");

            RpcMethods rpc = new RpcMethods(username, past, url1, port);

            string us = response.Text;
            string p  = ComputeSha256Hash(pas.Text).ToString();


            try
            {
                JObject obj     = JObject.Parse(rpc.GetRawTransaction(us));
                string  flodata = "";
                if (string.IsNullOrEmpty(obj["error"].ToString()))
                {
                    flodata = obj["result"]["floData"].ToString();
                    string passcode = decrpyt(flodata).ToString();
                    if (passcode.Equals(p))
                    {
                        response.Text      = "****SUCCESSFULLY LOGGED-IN****";
                        response.ForeColor = Color.DarkOliveGreen;
                        response.Visible   = true;
                        verification ob = new verification(us);
                        this.Hide();
                        ob.Show();
                    }
                    else
                    {
                        response.Text      = "****INCORRECT PASSWORD****";
                        response.ForeColor = Color.Firebrick;
                        response.Visible   = true;
                    }
                }
                else
                {
                    Console.WriteLine("Error searching the transactions");
                    response.Text      = "****BLOCKCHAIN ERROR****";
                    response.ForeColor = Color.Blue;
                    response.Visible   = true;
                }
            }
            catch (RpcInternalServerErrorException ex)
            {
                var err_code    = 0;
                var err_message = string.Empty;
                if (ex.RpcErrorCode.GetHashCode() != 0)
                {
                    err_code    = ex.RpcErrorCode.GetHashCode();
                    err_message = ex.RpcErrorCode.ToString();
                }
                Console.WriteLine("Exception:" + err_code + " " + err_message);
                response.Text      = "****BLOCKCHAIN ERROR****";
                response.ForeColor = Color.Blue;
                response.Visible   = true;
            }
            catch (Exception ex1)
            {
                Console.WriteLine("Exception:" + ex1);
                response.Text      = "****VISUAL STUDIO ERROR****" + ex1;
                response.ForeColor = Color.Red;
                response.Visible   = true;
            }
        }
        public T MakeRequest <T>(RpcMethods rpcMethod, object parameters)
        {
            var jsonRpcRequest = new JsonRpcRequest(1, rpcMethod.ToString(), parameters);
            var webRequest     = (HttpWebRequest)WebRequest.Create(seedURL);

            webRequest.ContentType = "application/json";
            webRequest.Method      = "POST";
            webRequest.Proxy       = null;
            webRequest.Timeout     = 10 * 1000;
            var byteArray = jsonRpcRequest.GetBytes();

            webRequest.ContentLength = jsonRpcRequest.GetBytes().Length;

            try
            {
                using (var dataStream = webRequest.GetRequestStream())
                {
                    dataStream.Write(byteArray, 0, byteArray.Length);
                    dataStream.Dispose();
                }
            }
            catch (Exception exception)
            {
                throw new RpcException("There was a problem sending the request to the wallet", exception);
            }

            try
            {
                string json;

                using (var webResponse = webRequest.GetResponse())
                {
                    using (var stream = webResponse.GetResponseStream())
                    {
                        using (var reader = new StreamReader(stream))
                        {
                            var result = reader.ReadToEnd();
                            reader.Dispose();
                            json = result;
                        }
                    }
                }

                var rpcResponse = JsonConvert.DeserializeObject <JsonRpcResponse <T> >(json);
                return(rpcResponse.Result);
            }
            catch (WebException webException)
            {
                #region RPC Internal Server Error (with an Error Code)

                var webResponse = webException.Response as HttpWebResponse;

                if (webResponse != null)
                {
                    switch (webResponse.StatusCode)
                    {
                    case HttpStatusCode.InternalServerError:
                    {
                        using (var stream = webResponse.GetResponseStream())
                        {
                            if (stream == null)
                            {
                                throw new RpcException("The RPC request was either not understood by the server or there was a problem executing the request", webException);
                            }

                            using (var reader = new StreamReader(stream))
                            {
                                var result = reader.ReadToEnd();
                                reader.Dispose();

                                try
                                {
                                    var jsonRpcResponseObject = JsonConvert.DeserializeObject <JsonRpcResponse <object> >(result);

                                    var internalServerErrorException = new RpcInternalServerErrorException(jsonRpcResponseObject.Error.Message, webException)
                                    {
                                        RpcErrorCode = jsonRpcResponseObject.Error.Code
                                    };

                                    throw internalServerErrorException;
                                }
                                catch (JsonException)
                                {
                                    throw new RpcException(result, webException);
                                }
                            }
                        }
                    }

                    default:
                        throw new RpcException("The RPC request was either not understood by the server or there was a problem executing the request", webException);
                    }
                }

                #endregion

                #region RPC Time-Out

                if (webException.Message == "The operation has timed out")
                {
                    throw new RpcRequestTimeoutException(webException.Message);
                }

                #endregion

                throw new RpcException("An unknown web exception occured while trying to read the JSON response", webException);
            }
            catch (JsonException jsonException)
            {
                throw new RpcResponseDeserializationException("There was a problem deserializing the response from the wallet", jsonException);
            }
            catch (ProtocolViolationException protocolViolationException)
            {
                throw new RpcException("Unable to connect to the server", protocolViolationException);
            }
            catch (Exception exception)
            {
                throw new Exception($"A problem was encountered while calling MakeRpcRequest() for: {jsonRpcRequest.Method}. \nException: {exception.Message}");
            }
        }
Exemplo n.º 19
0
        public T MakeRequest <T>(RpcMethods rpcMethod, params object[] parameters)
        {
            if (RpcMethods.xrGetTransactions == rpcMethod || RpcMethods.xrGetBlocks == rpcMethod || RpcMethods.xrService == rpcMethod)
            {
                var parameterList = new List <object>();
                foreach (var param in parameters)
                {
                    if (param != null)
                    {
                        if (!param.GetType().IsArray)
                        {
                            parameterList.Add(param);
                        }
                        else
                        {
                            foreach (var p in (IEnumerable)param)
                            {
                                parameterList.Add(p);
                            }
                        }
                    }
                }
                parameters = parameterList.ToArray();
            }


            var jsonRpcRequest = new JsonRpcRequest(1, rpcMethod.ToString(), parameters);
            var webRequest     = (HttpWebRequest)WebRequest.Create(_coinService.Parameters.SelectedDaemonUrl);

            SetBasicAuthHeader(webRequest, _coinService.Parameters.RpcUsername, _coinService.Parameters.RpcPassword);
            webRequest.Credentials = new NetworkCredential(_coinService.Parameters.RpcUsername, _coinService.Parameters.RpcPassword);
            webRequest.ContentType = "application/json-rpc";
            webRequest.Method      = "POST";
            webRequest.Proxy       = null;
            webRequest.Timeout     = _coinService.Parameters.RpcRequestTimeoutInSeconds * GlobalConstants.MillisecondsInASecond;
            var byteArray = jsonRpcRequest.GetBytes();

            webRequest.ContentLength = jsonRpcRequest.GetBytes().Length;

            try
            {
                using (var dataStream = webRequest.GetRequestStream())
                {
                    dataStream.Write(byteArray, 0, byteArray.Length);
                    dataStream.Dispose();
                }
            }
            catch (Exception exception)
            {
                throw new RpcException("There was a problem sending the request to the wallet", exception);
            }

            try
            {
                string json;
                Console.WriteLine("Executing RPC Call: " + rpcMethod.ToString());
                var timer = new Stopwatch();
                timer.Start();
                using (var webResponse = webRequest.GetResponse())
                {
                    using (var stream = webResponse.GetResponseStream())
                    {
                        using (var reader = new StreamReader(stream))
                        {
                            var result = reader.ReadToEnd();
                            reader.Dispose();
                            json = result;
                        }
                    }
                }
                timer.Stop();
                Console.WriteLine("Rpc Call Time Elapsed: {0} ms", timer.ElapsedMilliseconds);

                var rpcResponse = JsonConvert.DeserializeObject <JsonRpcResponse <T> >(json);

                var errorProperty = rpcResponse.Result.GetType().GetProperty("Error");

                if (errorProperty != null)
                {
                    var errorValue = (JsonRpcError)errorProperty.GetValue(rpcResponse.Result);
                    if (errorValue != null)
                    {
                        var internalServerErrorException = new RpcInternalServerErrorException(errorValue.Message)
                        {
                            RpcErrorCode = errorValue.Code
                        };
                        internalServerErrorException.Data["rpcResponse"] = rpcResponse.Result;
                        throw internalServerErrorException;
                    }
                }

                return(rpcResponse.Result);
            }
            catch (WebException webException)
            {
                #region RPC Internal Server Error (with an Error Code)

                var webResponse = webException.Response as HttpWebResponse;

                if (webResponse != null)
                {
                    switch (webResponse.StatusCode)
                    {
                    case HttpStatusCode.InternalServerError:
                    {
                        using (var stream = webResponse.GetResponseStream())
                        {
                            if (stream == null)
                            {
                                throw new RpcException("The RPC request was either not understood by the server or there was a problem executing the request", webException);
                            }

                            using (var reader = new StreamReader(stream))
                            {
                                var result = reader.ReadToEnd();
                                reader.Dispose();

                                try
                                {
                                    var jsonRpcResponseObject = JsonConvert.DeserializeObject <JsonRpcResponse <object> >(result);

                                    var internalServerErrorException = new RpcInternalServerErrorException(jsonRpcResponseObject.Error.Message, webException)
                                    {
                                        RpcErrorCode = jsonRpcResponseObject.Error.Code
                                    };

                                    throw internalServerErrorException;
                                }
                                catch (JsonException)
                                {
                                    throw new RpcException(result, webException);
                                }
                            }
                        }
                    }

                    default:
                        throw new RpcException("The RPC request was either not understood by the server or there was a problem executing the request", webException);
                    }
                }

                #endregion

                #region RPC Time-Out

                if (webException.Message == "The operation has timed out.")
                {
                    throw new RpcRequestTimeoutException(webException.Message);
                }

                #endregion

                throw new RpcException("An unknown web exception occured while trying to read the JSON response", webException);
            }
            catch (JsonException jsonException)
            {
                throw new RpcResponseDeserializationException("There was a problem deserializing the response from the wallet", jsonException);
            }
            catch (ProtocolViolationException protocolViolationException)
            {
                throw new RpcException("Unable to connect to the server", protocolViolationException);
            }
            catch (RpcInternalServerErrorException rpcInternalServerErrorException)
            {
                throw new RpcInternalServerErrorException(rpcInternalServerErrorException.Message, rpcInternalServerErrorException);
            }
            catch (Exception exception)
            {
                var queryParameters = jsonRpcRequest.Parameters.Cast <string>().Aggregate(string.Empty, (current, parameter) => current + (parameter + " "));
                throw new Exception($"A problem was encountered while calling MakeRpcRequest() for: {jsonRpcRequest.Method} with parameters: {queryParameters}. \nException: {exception.Message}");
            }
        }
Exemplo n.º 20
0
        private void button1_Click_1(object sender, EventArgs e)
        {
            string username    = ConfigurationManager.AppSettings.Get("rpcusername");
            string password    = ConfigurationManager.AppSettings.Get("rpcpassword");
            string wallet_url  = ConfigurationManager.AppSettings.Get("wallet_url");
            string wallet_port = ConfigurationManager.AppSettings.Get("wallet_port");

            RpcMethods rpc = new RpcMethods(username, password, wallet_url, wallet_port);


            try
            {
                string Name    = namebox.Text;
                string Send_to = Send_to_box.Text;

                string Review = reviewbox.Text;



                string flodata = "Review from:" + Name + "-- " + Review;

                JObject jobj = JObject.Parse(rpc.SendToAddress(Send_to, 0.01M, "review purpose", "review purpose", false, false, 1, "UNSET", flodata));
                if (string.IsNullOrEmpty(jobj["error"].ToString()))
                {
                    labelmsg.Text      = "Review saved successfully to FLO";
                    labelmsg.Visible   = true;
                    labelmsg.ForeColor = Color.Green;
                }
                else
                {
                    labelmsg.Text      = "Error!!!" + "could not retrieve any transaction details..plzz check ur transaction id";
                    labelmsg.Visible   = true;
                    labelmsg.ForeColor = Color.Red;
                }
            }
            catch (RpcInternalServerErrorException ex)
            {
                var errCode    = 0;
                var errMessage = string.Empty;
                if (ex.RpcErrorCode.GetHashCode() != 0)
                {
                    errCode    = ex.RpcErrorCode.GetHashCode();
                    errMessage = ex.RpcErrorCode.ToString();
                }
                Console.WriteLine("Exception :" + errCode + "-" + errMessage);


                labelmsg.Text      = "INternal server error!!";
                labelmsg.ForeColor = Color.Red;
                labelmsg.Visible   = true;
                labelmsg.Visible   = true;
            }
            catch (Exception ex1)
            {
                Console.WriteLine("Exception :" + ex1.ToString());
                labelmsg.Text      = "Error connecting to the server!!";
                labelmsg.ForeColor = Color.Red;
                labelmsg.Visible   = true;
                labelmsg.Visible   = true;
            }
        }
Exemplo n.º 21
0
        static void Main(string[] args)
        {
            string username    = ConfigurationManager.AppSettings.Get("username");
            string password    = ConfigurationManager.AppSettings.Get("password");
            string wallet_url  = ConfigurationManager.AppSettings.Get("wallet_url");
            string wallet_port = ConfigurationManager.AppSettings.Get("wallet_port");


            RpcMethods rpc = new RpcMethods(username, password, wallet_url, wallet_port);


            try
            {
                //string toaddr = "oTw4kEvB3MWrN97ujWb6JAs3ye574DvuKV";
                //string fromaddr = "oWVv5huYoVsicv9wLqDSt9hKTYERchm2DY";
                //string response = Call_Service_Get("http://localhost:53722/FloAPI.svc/listunspentbyaddress/"+ fromaddr);
                //JObject objapi = JObject.Parse(response);
                //JArray arrunspent = JArray.Parse(objapi["result"].ToString());
                //decimal amtosent = 2.65m;
                //decimal fee = 0.0001m;
                //decimal bal = 0.0m;



                //CreateRawTransactionRequest req1 = new CreateRawTransactionRequest();
                //List<CreateRawTransactionInput> inputs1 = new List<CreateRawTransactionInput>();

                //foreach (JObject o in arrunspent.Children<JObject>())
                //{
                //    CreateRawTransactionInput input1 = new CreateRawTransactionInput();
                //    string tid = o["txid"].ToString();
                //    string vout = o["vout"].ToString();
                //    string scriptPubKey = o["scriptPubKey"].ToString();
                //    decimal amt = Convert.ToDecimal(o["amount"].ToString());
                //    input1.txid = tid;
                //    input1.vout = Convert.ToInt32(vout);
                //    input1.scriptPubKey = scriptPubKey;
                //    inputs1.Add(input1);

                //    bal += amt;
                //    if(bal >= (amtosent+fee))
                //    {
                //        break;
                //    }

                //}
                //decimal change = bal - (amtosent + fee);
                //Dictionary<string, decimal> output1 = new Dictionary<string, decimal>();
                //output1.Add(toaddr, amtosent);
                //output1.Add(fromaddr, change);

                //req1.Inputs = inputs1;
                //req1.Outputs = output1;
                //req1.floData = "Test Raw Transaction API";
                //req1.locktime = 0;
                //req1.replaceable = false;
                //string rawreqjson = JsonConvert.SerializeObject(req1);

                //string rawresp = Call_Service_Post(rawreqjson, "http://localhost:53722/FloAPI.svc/createrawtransaction","text/plain");

                //JObject objraw1 = JObject.Parse(rpc.CreateRawTransaction(req1));

                //string rawHex1 = "";

                //if (string.IsNullOrEmpty(objraw1["error"].ToString()))
                //{
                //    Console.WriteLine("Raw Transaction : " + objraw1["result"]);
                //    rawHex1 = objraw1["result"].ToString();
                //}
                //else
                //{
                //    Console.WriteLine("Raw Transaction Error : " + objraw1["error"]);
                //}

                //string responsepriv = Call_Service_Get("http://localhost:53722/FloAPI.svc/dumpprivkey/" + fromaddr);
                //JObject objpriv = JObject.Parse(responsepriv);
                //string privkey1 = objpriv["result"].ToString();
                //List<string> privkeys1 = new List<string>();
                //privkeys1.Add(privkey1);


                //SignRawTransactionRequest signreq1 = new SignRawTransactionRequest();
                //signreq1.Inputs = inputs1;
                //signreq1.PrivateKeys = privkeys1;
                //signreq1.RawTransactionHex = rawHex1;
                //signreq1.SigHashType = "ALL";

                //string signjson = JsonConvert.SerializeObject(signreq1);

                //string signresp = Call_Service_Post(signjson,"http://localhost:53722/FloAPI.svc/signrawtransaction","application/json");
                //JObject objsign1 = JObject.Parse(signresp);
                //string signHex1 = "";

                //if (string.IsNullOrEmpty(objsign1["error"].ToString()))
                //{
                //    Console.WriteLine("Sign Raw Transaction : " + objsign1["result"]);
                //    signHex1 = objsign1["result"]["hex"].ToString();
                //}
                //else
                //{
                //    Console.WriteLine("Sign Raw Transaction Error : " + objsign1["error"]);
                //}

                //SendRawTransactionRequest sendreq = new SendRawTransactionRequest();
                //sendreq.signedHex = signHex1;
                //string sendreq1 = JsonConvert.SerializeObject(sendreq);

                //string sendresp1 = Call_Service_Post(sendreq1,"http://localhost:53722/FloAPI.svc/sendrawtransaction","application/json");
                //JObject objsend1 = JObject.Parse(sendresp1);

                //string txid = "";

                //if (string.IsNullOrEmpty(objsend1["error"].ToString()))
                //{
                //    Console.WriteLine("Sign Raw Transaction : " + objsend1["result"]);
                //    txid = objsend1["result"].ToString();
                //}
                //else
                //{
                //    Console.WriteLine("Sign Raw Transaction Error : " + objsend1["error"]);
                //}



                JArray jarrlu = new JArray();
                jarrlu.Add("");
                //jarrlu.Add("oHQMHm1eFz3PLgTPWPcYYDNvrB4G241Atd");
                //List Unspent
                JObject objlu = JObject.Parse(rpc.ListUnspent(jarrlu));

                if (string.IsNullOrEmpty(objlu["error"].ToString()))
                {
                    Console.WriteLine("Get Info : " + objlu["result"]);
                }
                else
                {
                    Console.WriteLine("Get Info Error : " + objlu["error"]);
                }

                CreateRawTransactionRequest req   = new CreateRawTransactionRequest();
                CreateRawTransactionInput   input = new CreateRawTransactionInput();
                input.txid         = "5b30f0bf684b90ccc2a3f8cef896b0ed155c9b785fbaf9fca1c1272dc40af4bd";
                input.vout         = 0;
                input.scriptPubKey = "76a914ac73b43a12d4ef3a2e71384ae3e35460cf4e91df88ac";
                List <CreateRawTransactionInput> inputs = new List <CreateRawTransactionInput>();
                inputs.Add(input);

                Dictionary <string, decimal> output = new Dictionary <string, decimal>();
                output.Add("oJsvAWvNWZ1jk3fV1BpaWHR3wPrYVaVxwZ", 1.0m);
                output.Add("oYbD4joh3G6d3k3wKbFtBQfgq9BPFxzWPn", 181.4795m);

                req.Inputs      = inputs;
                req.Outputs     = output;
                req.floData     = "Test Raw Transaction";
                req.locktime    = 0;
                req.replaceable = false;
                JObject objraw = JObject.Parse(rpc.CreateRawTransaction(req));

                string rawHex = "";

                if (string.IsNullOrEmpty(objraw["error"].ToString()))
                {
                    Console.WriteLine("Raw Transaction : " + objraw["result"]);
                    rawHex = objraw["result"].ToString();
                }
                else
                {
                    Console.WriteLine("Raw Transaction Error : " + objraw["error"]);
                }

                string        privkey  = "cTd24uWL7Sb6KsJXZzwBQR3mkyg2baEzHJNEhkgBmXPpFxy1Ypf9";
                List <string> privkeys = new List <string>();
                privkeys.Add(privkey);

                SignRawTransactionRequest signreq = new SignRawTransactionRequest();
                signreq.Inputs            = inputs;
                signreq.PrivateKeys       = privkeys;
                signreq.RawTransactionHex = rawHex;
                signreq.SigHashType       = "ALL";

                JObject objsign = JObject.Parse(rpc.SignRawTransaction(signreq));

                string signHex = "";

                if (string.IsNullOrEmpty(objsign["error"].ToString()))
                {
                    Console.WriteLine("Sign Raw Transaction : " + objsign["result"]);
                    signHex = objsign["result"]["hex"].ToString();
                }
                else
                {
                    Console.WriteLine("Sign Raw Transaction Error : " + objsign["error"]);
                }

                JObject objsend = JObject.Parse(rpc.SendRawTransaction(signHex));
                string  txid1   = "";

                if (string.IsNullOrEmpty(objsend["error"].ToString()))
                {
                    Console.WriteLine("Sign Raw Transaction : " + objsend["result"]);
                    txid1 = objsend["result"].ToString();
                }
                else
                {
                    Console.WriteLine("Sign Raw Transaction Error : " + objsend["error"]);
                }



                //Get Info
                JObject obj = JObject.Parse(rpc.GetInfo());

                if (string.IsNullOrEmpty(obj["error"].ToString()))
                {
                    Console.WriteLine("Get Info : " + obj["result"]);
                }
                else
                {
                    Console.WriteLine("Get Info Error : " + obj["error"]);
                }

                obj = JObject.Parse(rpc.Preciousblock("31300e805d4f949e455f20f045162290c920b76e14ec6e614c2c8d5bd4fe119e"));

                if (string.IsNullOrEmpty(obj["error"].ToString()))
                {
                    Console.WriteLine("Get Memory Info : " + obj["result"]);
                }
                else
                {
                    Console.WriteLine("Get Memory Info Error : " + obj["error"]);
                }

                //Get Help

                obj = JObject.Parse(rpc.Help("getinfo"));

                if (string.IsNullOrEmpty(obj["error"].ToString()))
                {
                    Console.WriteLine("Get Help : " + obj["result"]);
                }
                else
                {
                    Console.WriteLine("Get Help Error : " + obj["error"]);
                }

                //Get Balance

                obj = JObject.Parse(rpc.GetBalance(""));

                if (string.IsNullOrEmpty(obj["error"].ToString()))
                {
                    Console.WriteLine("Balance : " + obj["result"]);
                }
                else
                {
                    Console.WriteLine("Get Balance Error : " + obj["error"]);
                }

                //Get Wallet Info
                obj = JObject.Parse(rpc.GetWalletInfo());

                if (string.IsNullOrEmpty(obj["error"].ToString()))
                {
                    Console.WriteLine("Wallet Info : " + obj["result"]);
                }
                else
                {
                    Console.WriteLine("Wallet Info Error : " + obj["error"]);
                }

                //Test

                var jsonObject = new JObject();
                jsonObject.Add("oQDkguVz7CW2eEYCWD2G636tWCg23YcnRx", 1.2);
                jsonObject.Add("oXRrzwxUMcpxHCQWP4T1MQAocudWDzL1UJ", 0.2);

                var job1 = new JObject();
                var job2 = new JObject();
                job1.Add("txid", "b1aa06d72323ae923784d80ebb890c286d963d37901d73806fa2a4fff91865f3");
                job1.Add("vout", 1);
                job2.Add("txid", "b1aa06d72323ae923784d80ebb890c286d963d37901d73806fa2a4fff91865f4");
                job2.Add("vout", 2);

                //create raw transaction
                var jarr = new JArray();
                jarr.Add(job1);
                jarr.Add(job2);

                //obj = JObject.Parse(rpc.CreateRawTransaction(jarr, jsonObject));

                //if (string.IsNullOrEmpty(obj["error"].ToString()))
                //{
                //    Console.WriteLine("Create Raw Transaction : " + obj["result"]);
                //}
                //else
                //{
                //    Console.WriteLine("Error : " + obj["error"]);
                //}

                //decode raw transaction
                obj = JObject.Parse(rpc.DecodeRawTransaction("0200000002f36518f9ffa4a26f80731d90373d966d280c89bb0ed8843792ae2323d706aab10100000000fffffffff46518f9ffa4a26f80731d90373d966d280c89bb0ed8843792ae2323d706aab10200000000ffffffff02000e2707000000001976a91450a3f1d1f0d046af51cc150a6d4c33b37b7daf3988ac002d3101000000001976a9149fb715b93dac58ff46cdafd43c34762109ca604388ac0000000000"));

                if (string.IsNullOrEmpty(obj["error"].ToString()))
                {
                    Console.WriteLine("Decode Raw Transaction : " + obj["result"]);
                }
                else
                {
                    Console.WriteLine("Error : " + obj["error"]);
                }

                //create multi sig
                jarr = new JArray();
                jarr.Add("oYbD4joh3G6d3k3wKbFtBQfgq9BPFxzWPn");
                jarr.Add("oJsvAWvNWZ1jk3fV1BpaWHR3wPrYVaVxwZ");

                obj = JObject.Parse(rpc.AddMultisigAddress(2, jarr));

                if (string.IsNullOrEmpty(obj["error"].ToString()))
                {
                    Console.WriteLine("Add Multisig : " + obj["result"]);
                }
                else
                {
                    Console.WriteLine("Error : " + obj["error"]);
                }



                //obj = JObject.Parse(rpc.SendMany("AbhijeetTest", jsonObject));

                //if (string.IsNullOrEmpty(obj["error"].ToString()))
                //{
                //    Console.WriteLine("Send To Many : " + obj["result"]);
                //}
                //else
                //{
                //    Console.WriteLine("Error : " + obj["error"]);
                //}


                //Get Wallet Info
                obj = JObject.Parse(rpc.SubmitBlock("123456ffggg"));

                if (string.IsNullOrEmpty(obj["error"].ToString()))
                {
                    Console.WriteLine("Wallet Info : " + obj["result"]);
                }
                else
                {
                    Console.WriteLine("Wallet Info Error : " + obj["error"]);
                }
            }
            catch (RpcInternalServerErrorException exception)
            {
                var errorCode    = 0;
                var errorMessage = string.Empty;

                if (exception.RpcErrorCode.GetHashCode() != 0)
                {
                    errorCode    = exception.RpcErrorCode.GetHashCode();
                    errorMessage = exception.RpcErrorCode.ToString();
                }

                Console.WriteLine("[Failed] {0} {1} {2}", exception.Message, errorCode != 0 ? "Error code: " + errorCode : string.Empty, !string.IsNullOrWhiteSpace(errorMessage) ? errorMessage : string.Empty);
            }
            catch (Exception exception)
            {
                Console.WriteLine("[Failed]\n\nPlease check your configuration and make sure that the daemon is up and running and that it is synchronized. \n\nException: " + exception);
            }

            Console.Read();
        }
        private void student_form_Load(object sender, EventArgs e)
        {
            con = new SqlConnection(connstr);
            con.Open();
            //string cert = "PTRN005";
            //int count=0;

            lblReg_no.Text    = r;
            lblIssueDate.Text = DateTime.Now.ToShortDateString();


            //count++;
            //label31.Text = cert + count.ToString();

            cmd = new SqlCommand("select Name,Fathers_name,Course,Grade,Marks,Date_j,Date_c from student where Reg_no = @rn", con);
            cmd.Parameters.Add(new SqlParameter("@rn", lblReg_no.Text));
            //cmd.Parameters.Add(new SqlParameter("@r", comboBox1.Text));
            dr = cmd.ExecuteReader();

            if (dr.Read())
            {
                lblName.Text         = (dr[0].ToString());
                lblGuardianName.Text = (dr[1].ToString());
                lblCourse.Text       = (dr[2].ToString());
                lblGrade.Text        = (dr[3].ToString());
                lblPercent.Text      = (dr[4].ToString());
                DateTime dt = DateTime.Parse(dr[5].ToString());
                lblDoj.Text             = (dt.ToString("dd-MM-yyyy"));
                dt                      = DateTime.Parse(dr[6].ToString());
                lblCompletion_Date.Text = (dt.ToString("dd-MM-yyyy"));
            }
            lblCertificate_no.Text = DateTime.Now.ToString("ddMMyyyyhhmmss");

            con.Close();


            string username    = ConfigurationManager.AppSettings.Get("username");
            string password    = ConfigurationManager.AppSettings.Get("password");
            string wallet_url  = ConfigurationManager.AppSettings.Get("wallet_url");
            string wallet_port = ConfigurationManager.AppSettings.Get("wallet_port");


            RpcMethods rpc     = new RpcMethods(username, password, wallet_url, wallet_port);
            string     tranid  = "";
            string     flodata = "deepacertproject#" + lblName.Text + "#" + lblGuardianName.Text + "#" + lblReg_no.Text + "#" + lblCourse.Text + "#" + lblGrade.Text + "#" + lblPercent.Text + "#" + lblDoj.Text + "#" + lblCompletion_Date.Text + "#" + lblIssueDate.Text + "#" + lblCertificate_no.Text;

            try
            {
                JObject obj = JObject.Parse(rpc.SendToAddress("oXFZb6CJFfw5E46hLFwiMKdPt3LEUtuV4L", 0.01M, "Test comment", "Test Comment", false, false, 1, "UNSET", flodata));

                if (string.IsNullOrEmpty(obj["error"].ToString()))
                {
                    tranid = obj["result"].ToString();
                    con    = new SqlConnection(connstr);
                    con.Open();
                    cmd = new SqlCommand("insert into Flo_record values(@r,@t,@c)", con);
                    cmd.Parameters.Add(new SqlParameter("@r", lblReg_no.Text));
                    cmd.Parameters.Add(new SqlParameter("@t", tranid));
                    cmd.Parameters.Add(new SqlParameter("@c", lblCertificate_no.Text));
                    cmd.ExecuteNonQuery();
                    con.Close();


                    Console.WriteLine("Transaction ID : " + obj["result"]);
                }
                else
                {
                    MessageBox.Show("Send Transaction Error : " + obj["error"]);
                }
            }
            catch (RpcInternalServerErrorException exception)
            {
                var errorCode    = 0;
                var errorMessage = string.Empty;

                if (exception.RpcErrorCode.GetHashCode() != 0)
                {
                    errorCode    = exception.RpcErrorCode.GetHashCode();
                    errorMessage = exception.RpcErrorCode.ToString();
                }

                Console.WriteLine("[Failed] {0} {1} {2}", exception.Message, errorCode != 0 ? "Error code: " + errorCode : string.Empty, !string.IsNullOrWhiteSpace(errorMessage) ? errorMessage : string.Empty);
                MessageBox.Show("Wallet Error Code : " + errorCode);
            }
            catch (Exception exception)
            {
                MessageBox.Show("[Failed]\n\nPlease check your configuration and make sure that the daemon is up and running and that it is synchronized. \n\nException: " + exception);
            }
        }