public void Handles_GET_Request_404_Error_With_Body()
        {
            Uri baseUrl = new Uri("http://localhost:8080/");

            using (SimpleServer.Create(baseUrl.AbsoluteUri, this.UrlToStatusCodeHandler))
            {
                var client = new RestClient(baseUrl);
                var request = new RestRequest("404");

                request.AddBody("This is the body");

                var response = client.Execute(request);

                Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
            }
        }
Example #2
0
        public override ActionResult Execute(ISpecialExecutionTaskTestAction testAction)
        {
            String paraCommand = testAction.GetParameterAsInputValue("Command", false).Value;

            if (string.IsNullOrEmpty(paraCommand))
            {
                throw new ArgumentException(string.Format("Es muss ein Command angegeben sein."));
            }

            String paraTarget = testAction.GetParameterAsInputValue("Target", false).Value;

            // Wenn Target null, dann leer uebergeben.
            if (string.IsNullOrEmpty(paraTarget))
            {
                paraTarget = "";
            }

            String paraValue = testAction.GetParameterAsInputValue("Value", false).Value;

// Wenn Value null, dann leer uebergeben.
            if (string.IsNullOrEmpty(paraValue))
            {
                paraValue = "";
            }

            // rest server address + port can be configured via buffer settings.
            // key should be: LOCAL_VEBTAL_PORT
            String outServer;
            bool   adrServer = Buffers.Instance.TryGetBuffer("LOCAL_VEBTAL_SERVER", out outServer);

            if (string.IsNullOrEmpty(outServer))
            {
                outServer = "http://127.0.0.1";                 // fallback to default
            }

            // key should be: LOCAL_VEBTAL_PORT
            String outPort;
            bool   port = Buffers.Instance.TryGetBuffer("LOCAL_VEBTAL_PORT", out outPort);

            if (string.IsNullOrEmpty(outPort))
            {
                outPort = "84";                 // fallback to default
            }
            var client  = new RestClient(outServer + ":" + outPort);
            var request = new RestRequest("pdf/execute", Method.POST);

            request.RequestFormat = DataFormat.Json;
            request.AddHeader("Content-Type", "application/json");
            request.AddHeader("Accept", "application/json");
            request.AddBody(new {
                command = paraCommand,
                target  = paraTarget,
                value   = paraValue
            });

            IRestResponse response = client.Execute(request);
            var           content  = response.Content;

// Deserialisieren
            RestSharp.Deserializers.JsonDeserializer deserial = new JsonDeserializer();
            var    JSONObj = deserial.Deserialize <Dictionary <string, string> >(response);
            string rowCode = JSONObj["code"];

// storedKey und storedValue beruecksichtigen
            if (JSONObj.ContainsKey("storedValue"))
            {
                string storedValue = JSONObj["storedValue"];
                string storedKey   = JSONObj["storedKey"];
                Buffers.Instance.SetBuffer(storedKey, storedValue, false);
            }

            if (rowCode == "0")
            {
                return(new PassedActionResult("Got response: " + content));
            }
            else
            {
                return(new  NotFoundFailedActionResult("Command failed: " + content + " for request: [command=" + paraCommand + "; target=" + paraTarget + "; value=" + paraValue + "]"));
            }
        }
Example #3
0
        private void add_Click(object sender, EventArgs e)
        {
            var client  = new RestClient(URL);
            var request = new RestRequest(ROUTE, Method.POST);  //index is kellett mögé

            request.RequestFormat = DataFormat.Json;
            string tmp    = textBox_lovechrismas.Text.ToUpper();
            string tmp2   = textBox_lovewinter.Text.ToUpper();
            string name   = textBox_name.Text;
            string classs = textBox_classs.Text;



            /*
             * request.AddBody(new
             *         {
             *
             *             name = name,
             *             classs = classs,
             *             lovechrismas = int.Parse(tmp),
             *             lovewinter = int.Parse(tmp2)
             *
             *         });
             */


            if (tmp == "IGEN" || tmp == "IGAZ" || tmp == "SZERETI" || tmp == "TRUE" || tmp == "1")
            {
                if (tmp2 == "IGEN" || tmp2 == "IGAZ" || tmp2 == "SZERETI" || tmp2 == "TRUE" || tmp2 == "1")
                {
                    request.AddBody(new
                    {
                        name         = name,
                        classs       = classs,
                        lovechrismas = 1,
                        lovewinter   = 1
                    });
                }
                else
                {
                    if (tmp2 == "NEM" || tmp2 == "HAMIS" || tmp2 == "NEM SZERETI" || tmp2 == "FALSE" || tmp2 == "0")
                    {
                        request.AddBody(new
                        {
                            name         = name,
                            classs       = classs,
                            lovechrismas = 1,
                            lovewinter   = 0
                        });
                    }
                    else
                    {
                        MessageBox.Show("Hibás érték! \n Értékek lehetnek:'IGEN','IGAZ' , 'SZERETI' , 'TRUE' ,'NEM', 'HAMIS' , 'NEM SZERETI' , 'FALSE' , '0'\n Nem kis/nagy betű érzékeny \n(TÉL)");
                    }
                }
            }
            else
            {
                if (tmp == "NEM" || tmp == "HAMIS" || tmp == "NEM SZERETI" || tmp == "FALSE" || tmp == "0")
                {
                    if (tmp2 == "IGEN" || tmp2 == "IGAZ" || tmp2 == "SZERETI" || tmp2 == "TRUE" || tmp2 == "1")
                    {
                        request.AddBody(new
                        {
                            name         = name,
                            classs       = classs,
                            lovechrismas = 0,
                            lovewinter   = 1
                        });
                    }
                    else
                    {
                        if (tmp2 == "NEM" || tmp2 == "HAMIS" || tmp2 == "NEM SZERETI" || tmp2 == "FALSE" || tmp2 == "0")
                        {
                            request.AddBody(new
                            {
                                name         = name,
                                classs       = classs,
                                lovechrismas = 0,
                                lovewinter   = 0
                            });
                        }
                        else
                        {
                            MessageBox.Show("Hibás érték! \n Értékek lehetnek:'IGEN','IGAZ' , 'SZERETI' , 'TRUE' ,'NEM', 'HAMIS' , 'NEM SZERETI' , 'FALSE' , '0'\n Nem kis/nagy betű érzékeny \n(TÉL)");
                        }
                    }
                }


                else
                {
                    MessageBox.Show("Hibás érték! \n Értékek lehetnek:'IGEN','IGAZ' , 'SZERETI' , 'TRUE' ,'NEM', 'HAMIS' , 'NEM SZERETI' , 'FALSE' , '0'\n Nem kis/nagy betű érzékeny \n(Karácsony)");
                }
            }



            IRestResponse response = client.Execute(request);
        }
        private void CheckRFIDTag()
        {
            try
            {
                //btnVerifyAsset.Text = "Verifying Tag. Please wait ...";
                //btnVerifyAsset.BackColor = Color.GreenYellow;
                //btnVerifyAsset.Refresh();
                lblLoadingInformation.Visible = true;
                lblLoadingInformation.Refresh();

                VerifyRequest verifyRequest = new VerifyRequest();
                verifyRequest.tag       = txtRFIDTag.Text;
                verifyRequest.companyId = 1;
                verifyRequest.tagType   = 1;

                //initialize web service
                RestClient  client    = new RestClient("http://52.163.93.95:8080/FeatherAssets/");
                RestRequest verify    = new RestRequest("/api/asset/verify", Method.POST);
                var         authToken = tokenvalue;

                verify.AddHeader("X-Auth-Token", authToken);
                verify.AddHeader("Content-Type", "application/json; charset=utf-8");
                verify.RequestFormat = DataFormat.Json;
                verify.AddBody(verifyRequest);

                //retrieve response
                IRestResponse response = client.Execute(verify);
                var           content  = response.Content;

                //btnVerifyAsset.Text = "Click to verify RFID Tag";
                //btnVerifyAsset.BackColor = Color.Orange;
                lblLoadingInformation.Visible = false;

                if (response.StatusCode == HttpStatusCode.OK)
                {
                    //deserialize JSON -> Object
                    JsonDeserializer deserial     = new JsonDeserializer();
                    VerifyResult     verifyResult = deserial.Deserialize <VerifyResult>(response);

                    if (verifyResult.result == "OK")
                    {
                        //txtAssetName.Text = verifyResult.name;
                        txtDescription.Text = verifyResult.description;
                        //if (Boolean.Parse(verifyResult.takOutAllowed.ToString()))
                        //{
                        //    txtTakeOutAvailability.Text = "Allowed to take-out.";
                        //}
                        //else
                        //{
                        //    txtTakeOutAvailability.Text = "Not allowed to take-out.";
                        //}
                        txtTakeOutNote.Text = verifyResult.takeOutInfo;
                        //if (File.Exists(verifyResult.imageUrls))
                        //{
                        //picOwner.Image = Image.FromFile(verifyResult.imageUrls);

                        string   Urls     = verifyResult.imageUrls;
                        string[] ReadUrls = Urls.Split(',');

                        if (ReadUrls.Length > 1)
                        {
                            imgCapture1.Load("http://52.163.93.95:8080/FeatherAssets/api/images/1/asset/" + ReadUrls[1]);
                            lblOwnerPhoto.Visible = false;
                        }
                        if (ReadUrls.Length > 2)
                        {
                            imgCapture2.Load("http://52.163.93.95:8080/FeatherAssets/api/images/1/asset/" + ReadUrls[2]);
                            lblValidIDPhoto.Visible = false;
                        }
                        if (ReadUrls.Length > 3)
                        {
                            imgCapture3.Load("http://52.163.93.95:8080/FeatherAssets/api/images/1/asset/" + ReadUrls[3]);
                            lblAssetPhoto1.Visible = false;
                        }
                        if (ReadUrls.Length > 4)
                        {
                            imgCapture4.Load("http://52.163.93.95:8080/FeatherAssets/api/images/1/asset/" + ReadUrls[4]);
                            lblAssetPhoto2.Visible = false;
                        }
                        if (ReadUrls.Length > 5)
                        {
                            imgCapture5.Load("http://52.163.93.95:8080/FeatherAssets/api/images/1/asset/" + ReadUrls[5]);
                            lblAssetPhoto3.Visible = false;
                        }

                        //foreach (string GetUrls in ReadUrls)
                        //{
                        //    if (ReadUrls.Length > 1 && File.Exists(ReadUrls[1]))
                        //    {
                        //        imgCapture1.Image = Image.FromFile(ReadUrls[1]);
                        //        lblOwnerPhoto.Visible = false;
                        //    }
                        //    if (ReadUrls.Length > 2 && File.Exists(ReadUrls[2]))
                        //    {
                        //        imgCapture2.Image = Image.FromFile(ReadUrls[2]);
                        //        lblValidIDPhoto.Visible = false;
                        //    }
                        //    if (ReadUrls.Length > 3 && File.Exists(ReadUrls[3]))
                        //    {
                        //        imgCapture3.Image = Image.FromFile(ReadUrls[3]);
                        //        lblAssetPhoto1.Visible = false;
                        //    }
                        //    if (ReadUrls.Length > 4 && File.Exists(ReadUrls[4]))
                        //    {
                        //        imgCapture4.Image = Image.FromFile(ReadUrls[4]);
                        //        lblAssetPhoto2.Visible = false;
                        //    }
                        //    if (ReadUrls.Length > 5 && File.Exists(ReadUrls[5]))
                        //    {
                        //        imgCapture5.Image = Image.FromFile(ReadUrls[5]);
                        //        lblAssetPhoto3.Visible = false;
                        //    }
                        //}
                        //}
                        //else
                        //{
                        //    MessageBox.Show("Image not found for this path: " + verifyResult.imageUrls, "Asset Verification", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        //    //btnVerifyAsset.Focus();
                        //    //return;
                        //}

                        //Display User's Information
                        //if (File.Exists(verifyResult.owner.imageUrl)) picOwner.Image =  Image.FromFile(verifyResult.owner.imageUrl);
                        //txtOwnerName.Text = verifyResult.owner.lastName + " " + verifyResult.owner.firstName;
                        //txtOwnerPosition.Text = verifyResult.owner.position;
                        //txtOwnerDescription.Text = verifyResult.owner.description;

                        //VerifyTimer.Stop();
                        //VerifyTimer.Start();

                        //ClearTimer.Stop();
                        //ClearTimer.Start();

                        return;
                    }
                    else
                    {
                        MessageBox.Show(verifyResult.result + " " + verifyResult.message);
                        //MessageBox.Show("RFID Tag: " + txtRFIDTag.Text + " " + verifyResult.message);
                    }
                }
                else if (response.StatusCode == HttpStatusCode.NotFound)
                {
                    MessageBox.Show("Error connecting to server.. please try again later");
                }
                else
                {
                    HttpStatusCode statusCode        = response.StatusCode;
                    int            numericStatusCode = (int)statusCode;
                    //show error code
                    MessageBox.Show("Error" + numericStatusCode);
                }

                ClearFields();

                #region old connection

                /*MySqlConnection con = new MySqlConnection(connectionString);
                 * con.Open();
                 * MySqlCommand cmd = new MySqlCommand("select * from asset where rfid_tag='" + txtRFIDTag.Text + "'", con);
                 * MySqlDataReader rd = cmd.ExecuteReader();
                 */


                /*if (rd.Read())
                 * {
                 *  txtAssetName.Text = (rd["name"].ToString());
                 *  txtOwnerName.Text = (rd["description"].ToString());
                 *  ////txtTakeOutAvailability.Text = (rd["take_out_allowed"].ToString());
                 *  if (Boolean.Parse(rd["take_out_allowed"].ToString()))
                 *  {
                 *      txtTakeOutAvailability.Text = "Allowed to take-out.";
                 *  }
                 *  else
                 *  {
                 *      txtTakeOutAvailability.Text = "Not allowed to take-out.";
                 *  }
                 *  txtTakeOutNote.Text = (rd["take_out_info"].ToString());
                 *
                 *  if (File.Exists(rd["images"].ToString()))
                 *  {
                 *      picOwner.Image = Image.FromFile(rd["images"].ToString());
                 *  }
                 *  else
                 *  {
                 *      MessageBox.Show("Image not found for this path: " + rd["images"].ToString(), "Asset Verification", MessageBoxButtons.OK, MessageBoxIcon.Information);
                 *      btnVerifyAsset.Focus();
                 *      rd.Close();
                 *      return;
                 *  }
                 *
                 *  VerifyTimer.Stop();
                 *  VerifyTimer.Start();
                 *
                 *  ClearTimer.Stop();
                 *  ClearTimer.Start();
                 *
                 *  rd.Close();
                 *  return;
                 * }*/
                /*else
                 * {
                 *  rd.Close();
                 *  DialogResult result = MessageBox.Show("RFID Tag not found. Do you want to register the asset?", "Asset Verification", MessageBoxButtons.YesNo, MessageBoxIcon.Information, MessageBoxDefaultButton.Button2);
                 *  if (result == DialogResult.Yes)
                 *  {
                 *      this.Hide();
                 *      reader.CloseCom();
                 *      AssetRegistration AssetForm = new AssetRegistration(portname);
                 *      AssetForm.Show();
                 *  }
                 *  else
                 *  {
                 *      btnVerifyAsset.Focus();
                 *      return;
                 *  }
                 *
                 * }*/
                #endregion
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        public void uploadStatus()
        {
            //Console.WriteLine("Updating Status...");

            RestClient client         = new RestClient(fireBase);
            RestClient clientActivity = new RestClient(fireBaseActivity);

            RestRequest timeStampRequest = new RestRequest(String.Format("{0}.json", System.Environment.MachineName), Method.PUT);

            timeStampRequest.RequestFormat = DataFormat.Json;
            timeStampRequest.AddBody(new { now = DateTime.Now.ToString("MM-dd-yyyy H:mm:ss zzz") });
            clientActivity.Execute(timeStampRequest);

            //var httpWebRequest = (HttpWebRequest)WebRequest.Create(fireBase + "/status.json");
            //httpWebRequest.Accept = "application/json";
            //httpWebRequest.ContentType = "application/json";
            //httpWebRequest.Method = "PUT";
            //try
            //{
            //    using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            //    {
            //        string json = String.Format("{{\"isPlaying\":{0}, \"isPaused\":{1}}}", IsPlaying ? 1 : 0, IsPaused ? 1 : 0);
            //        Console.WriteLine(json);

            //        streamWriter.Write(json);
            //        streamWriter.Flush();
            //        streamWriter.Close();

            //        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            //        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            //        {
            //            var result = streamReader.ReadToEnd();
            //            Console.WriteLine(result);
            //        }
            //    }
            //}
            //catch (WebException webException)
            //{
            //    Console.WriteLine(webException.Message);
            //}
            RestRequest statusRequest = new RestRequest("status.json", Method.PUT);

            statusRequest.RequestFormat = DataFormat.Json;
            statusRequest.AddBody(new { isPlaying = IsPlaying ? 1 : 0, isPaused = IsPaused ? 1 : 0, volume = volume, volumeDB = volumnDB });
            client.Execute(statusRequest);

            //client.ExecuteAsync(statusRequest, response =>
            //{
            //    if (response.ErrorException != null)
            //    {
            //        Console.WriteLine(response.ErrorMessage);
            //    }
            //    if (response.ResponseStatus != ResponseStatus.Completed)
            //    {
            //        Console.WriteLine(response.ErrorMessage);
            //    }
            //    else
            //    {
            //        Console.WriteLine(response.Content);
            //    }
            //});

            RestRequest progressRequest = new RestRequest("playing/progress.json", Method.PUT);

            progressRequest.RequestFormat = DataFormat.Json;
            progressRequest.AddBody(new { position = currentPosition, length = totalLength });
            client.Execute(progressRequest);

            if (currentSongShouldUpdate)
            {
                RestRequest songRequest = new RestRequest("playing/song.json", Method.PUT);
                songRequest.RequestFormat = DataFormat.Json;
                songRequest.AddBody(new { title = currentSong.title, album = currentSong.album, albumArtist = currentSong.albumArtist, trackArtist = currentSong.trackArtist, codec = currentSong.codec, CD = currentSong.discNumber, track = currentSong.trackNumber, sampleRate = currentSong.sampleRate, bitRate = currentSong.bitRate, channels = currentSong.channels });
                client.Execute(songRequest);

                currentSongShouldUpdate = false;
            }

            //Console.WriteLine("Status update finished.");
        }
Example #6
0
        private static Dictionary <string, ActionDelegate> GetActions(Siren content)
        {
            //Include blocked actions to actions. TODO: add way to check on runtime if action is blocked or not
            var actions        = content.actions;
            var blockedActions = content.blockedActions;

            if (blockedActions != null)
            {
                actions.AddRange(blockedActions);
            }

            var actionDictionary = new Dictionary <string, ActionDelegate>();

            if (actions == null)
            {
                return(actionDictionary);
            }

            foreach (var action in actions)
            {
                actionDictionary.Add(action.name,
                                     (Dictionary <string, object> UserDefinedFields, string plainText) =>
                {
                    var actionClient  = new RestClient(new Uri(action.href));
                    var actionRequest = new RestRequest("", action.method.ToRestSharpMethod());
                    IRestResponse <object> resp;

                    if (action.type == "text/plain")
                    {
                        actionRequest.AddHeader("Content-Type", "text/plain");
                        actionRequest.AddParameter("text/plain", plainText, ParameterType.RequestBody);
                    }
                    else
                    {
                        actionRequest.AddHeader("Content", "application/vnd.siren+json");
                        actionRequest.RequestFormat = DataFormat.Json;

                        if (UserDefinedFields != null)
                        {
                            foreach (var userfield in UserDefinedFields.Keys)
                            {
                                bool found = false;

                                if (action.fields != null)
                                {
                                    foreach (var actionfield in action.fields)
                                    {
                                        if (actionfield.name == userfield)
                                        {
                                            found = true;
                                        }
                                    }
                                }

                                if (!found)
                                {
                                    throw new ArgumentException("Field '" + userfield + "' not available at action '" + action.name +
                                                                "'. Check actions (with browser) from " + action.href.Replace("/" + action.name, ""));
                                }
                            }
                        }

                        if (action.fields != null)
                        {
                            var obj = new ExpandoObject();

                            foreach (var field in action.fields)
                            {
                                if (UserDefinedFields != null && UserDefinedFields.ContainsKey(field.name))
                                {
                                    obj.AddProperty(field.name, UserDefinedFields[field.name]);
                                }
                                else if (field.value != null)
                                {
                                    obj.AddProperty(field.name, field.value);
                                }
                                else if (!field.optional)
                                {
                                    throw new ArgumentException("Value of field missing");
                                }
                            }

                            actionRequest.AddBody(obj);
                        }
                    }
                    resp = actionClient.Execute <object>(actionRequest);
                    HandleResponse(resp);

                    if (resp.ContentType.Contains("json"))
                    {
                        return(resp.Data);
                    }
                    if (resp.ContentType.Contains("text/plain"))
                    {
                        return(resp.Content);
                    }
                    else
                    {
                        throw new NotSupportedException("Other than json or text/plain responses are not supported. Response type is " +
                                                        resp.ContentType);
                    }
                });
            }

            return(actionDictionary);
        }
        private static void CrearFactura()
        {
            try
            {
                Console.WriteLine("Ejemplo Factura");
                var documento = new DocumentoElectronico
                {
                    Emisor   = CrearEmisor(),
                    Receptor = new Contribuyente
                    {
                        NroDocumento  = "20100039207",
                        TipoDocumento = "6",
                        NombreLegal   = "RANSA COMERCIAL S.A."
                    },
                    IdDocumento       = "FF11-001",
                    FechaEmision      = DateTime.Today.AddDays(-5).ToString("yyyy-MM-dd"),
                    Moneda            = "PEN",
                    MontoEnLetras     = "SON CIENTO DIECIOCHO SOLES CON 0/100",
                    CalculoIgv        = 0.18m,
                    CalculoIsc        = 0.10m,
                    CalculoDetraccion = 0.04m,
                    TipoDocumento     = "01",
                    TotalIgv          = 18,
                    TotalVenta        = 118,
                    Gravadas          = 100,
                    Items             = new List <DetalleDocumento>
                    {
                        new DetalleDocumento
                        {
                            Id                = 1,
                            Cantidad          = 5,
                            PrecioReferencial = 20,
                            PrecioUnitario    = 20,
                            TipoPrecio        = "01",
                            CodigoItem        = "1234234",
                            Descripcion       = "Arroz Costeño",
                            UnidadMedida      = "KG",
                            Impuesto          = 18,
                            TipoImpuesto      = "10", // Gravada
                            TotalVenta        = 100,
                            Suma              = 100
                        }
                    }
                };

                Console.WriteLine("Generando XML....");

                var client = new RestClient(BaseUrl);

                var requestInvoice = new RestRequest("GenerarFactura", Method.POST)
                {
                    RequestFormat = DataFormat.Json
                };

                requestInvoice.AddBody(documento);

                var documentoResponse = client.Execute <DocumentoResponse>(requestInvoice);

                if (!documentoResponse.Data.Exito)
                {
                    throw new ApplicationException(documentoResponse.Data.MensajeError);
                }

                Console.WriteLine("Firmando XML...");
                // Firmado del Documento.
                var firmado = new FirmadoRequest
                {
                    TramaXmlSinFirma    = documentoResponse.Data.TramaXmlSinFirma,
                    CertificadoDigital  = Convert.ToBase64String(File.ReadAllBytes("certificado.pfx")),
                    PasswordCertificado = string.Empty,
                    UnSoloNodoExtension = false
                };

                var requestFirma = new RestRequest("Firmar", Method.POST)
                {
                    RequestFormat = DataFormat.Json
                };
                requestFirma.AddBody(firmado);

                var responseFirma = client.Execute <FirmadoResponse>(requestFirma);

                if (!responseFirma.Data.Exito)
                {
                    throw new ApplicationException(responseFirma.Data.MensajeError);
                }

                Console.WriteLine("Enviando a SUNAT....");

                var sendBill = new EnviarDocumentoRequest
                {
                    Ruc             = documento.Emisor.NroDocumento,
                    UsuarioSol      = "MODDATOS",
                    ClaveSol        = "MODDATOS",
                    EndPointUrl     = UrlSunat,
                    IdDocumento     = documento.IdDocumento,
                    TipoDocumento   = documento.TipoDocumento,
                    TramaXmlFirmado = responseFirma.Data.TramaXmlFirmado
                };

                var requestSendBill = new RestRequest("EnviarDocumento", Method.POST)
                {
                    RequestFormat = DataFormat.Json
                };
                requestSendBill.AddBody(sendBill);

                var responseSendBill = client.Execute <EnviarDocumentoResponse>(requestSendBill);

                if (!responseSendBill.Data.Exito)
                {
                    throw new ApplicationException(responseSendBill.Data.MensajeError);
                }

                Console.WriteLine("Respuesta de SUNAT:");
                Console.WriteLine(responseSendBill.Data.MensajeRespuesta);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                Console.ReadLine();
            }
        }
Example #8
0
        private void GetJson(string url)
        {
            using (var client = new HttpClient(

                       new HttpClientHandler()
            {
                AutomaticDecompression = DecompressionMethods.GZip
            }))

                HttpResponseMessage resp = client.GetAsync(Uri).Result;
            response = resp.Content.ReadAsAsync <T>().Result;
            return(response);

            //SearchFilter.RootObject rootObject = new SearchFilter.RootObject();

            //w.Headers.Add("X-Signature", GetAuthenticed.Signature());
            //w.Headers.Add("secret", "hC4G64FvN9");
            //w.Headers.Add("Api-Key", "9g9e3fpc5ea8e692pdznrk52");
            //w.Headers.Add("Accept", "application/json");
            RestClient client  = new RestClient("https://api.test.hotelbeds.com");
            var        request = new RestRequest(Method.POST);

            request.AddHeader("X-Signature", GetAuthenticed.Signature());
            request.AddHeader("secret", "hC4G64FvN9");
            request.AddHeader("Api-Key", "9g9e3fpc5ea8e692pdznrk52");
            request.AddHeader("Accept", "application/json");
            request.AddHeader("Content-type", "application/json");

            request.Resource = "/activity-content-api/3.0/activities";
            //request.AddParameter("application/json", "{from:2018-04-28}",ParameterType.RequestBody);
            //request.AddParameter("application/json", "{to:2018-05-10}", ParameterType.RequestBody);
            //request.AddParameter("application/json", "{language:en}", ParameterType.RequestBody);

            request.RequestFormat = DataFormat.Json;
            List <Tuple <string, string> > param;

            param = new List <Tuple <string, string> >
            {
                new Tuple <string, string>("${from}", "2018-04-28"),
                new Tuple <string, string>("${to}", "2018-05-10"),
                new Tuple <string, string>("${language}", "en")
            };


            request.AddBody(param);



            IRestResponse response = client.Execute(request);



            //rootObject.from = "2018-04-28";
            //rootObject.to = "2018-05-30";
            //rootObject.language = "en";
            //rootObject.order = "DEFAULT";



            //var json = new JavaScriptSerializer().Serialize(rootObject);

            //Newtonsoft.Json.JsonSerializer(rootObject);

            //var response = request.UploadValues(url,"POST", rootObject);

            //var responseString = Encoding.Default.GetString(response);



            ////HotelObject rootObject = new HotelObject();
            //var json_data = string.Empty;
            //try
            //{
            //    json_data = request.DownloadString(url);
            //}
            //catch(Exception ex)
            //{
            //    Debug.WriteLine(ex.Message);
            //}
            //var test = JsonConvert.DeserializeObject<Activitiescontent[]>(json_data);
            //return JsonConvert.DeserializeObject<Activitiescontent[]>(json_data);
        }
Example #9
0
        // Make a payment
        // Should do validation of the returned data
        public async Task <PayPalExecutePaymentResult> MakePayment(IPayPalReceipt receipt)
        {
            try{
                var accessTokenData = await GetAccessToken();

                var executePaymentResult = new PayPalExecutePaymentResult();

                if (accessTokenData.DisplayError == null)
                {
                    var restRequest = new RestRequest("/payments/payment", Method.POST);

                    // Add headers
                    restRequest.AddHeader("Content-Type", "application/json");
                    restRequest.AddHeader("Authorization", "Bearer " + accessTokenData.AccessToken);

                    // Add data to send
                    restRequest.RequestFormat = DataFormat.Json;
                    // This transaction information should be made dynamic!
                    // Source: https://developer.paypal.com/docs/api/#create-a-payment
                    restRequest.AddBody(new PayPalMakePaymentData {
                        intent        = "sale",
                        redirect_urls = new PayPalMakePaymentRedirectUrls {
                            return_url = PayPalConfig.ReturnUrl,
                            cancel_url = PayPalConfig.CancelUrl
                        },
                        payer = new PayPalPayer {
                            payment_method = "paypal"
                        },
                        transactions = new [] {
                            new PayPalTransaction {
                                amount = new PayPalAmount {
                                    total    = receipt.Total.ToString().Trim(' '),
                                    currency = receipt.Currency,
                                    details  = new PayPalAmountDetails {
                                        subtotal = receipt.SubTotal.ToString().Trim(' '),
                                        tax      = receipt.TaxTotal.ToString().Trim(' '),
                                        shipping = receipt.Shipping.ToString().Trim(' '),
                                    }
                                },
                                item_list = new PayPalItemList {
                                    items = new [] {
                                        new PayPalItem {
                                            quantity    = receipt.Quantity.ToString().Trim(' '),
                                            name        = "Reservation Detail",
                                            price       = receipt.Price.ToString().Trim(' '),
                                            currency    = receipt.Currency,
                                            description = receipt.Desc,
                                            tax         = receipt.SubTax.ToString().Trim(' '),
                                        }
                                    }
                                }
                            }
                        }
                    });

                    var response = restClient.Execute <PayPalPaymentResponse> (restRequest);

                    executePaymentResult.DisplayError = CheckResponseStatus(response, HttpStatusCode.Created);

                    if (executePaymentResult.DisplayError == null)
                    {
                        // Get the approval url from the links provided by the response
                        var links = from link in response.Data.Links
                                    where link.Rel == "approval_url"
                                    select link.Href;

                        if (!String.IsNullOrEmpty(links.First()))
                        {
                            executePaymentResult.Url         = links.First();
                            executePaymentResult.AccessToken = accessTokenData.AccessToken;

                            // Send the approval url along with the access token the paypal webview
                            return(executePaymentResult);
                        }
                        else
                        {
                            executePaymentResult.DisplayError = "Something went wrong. Please try again.";
                        }
                    }
                }
                else
                {
                    executePaymentResult.DisplayError = accessTokenData.DisplayError;
                }

                return(executePaymentResult);
            }
            catch (Exception ex)
            {
                AppStyle.Log.sendException("MakePayment", ex);
                return(null);
            }
        }
        public BeGlobalV4Translator(BeGlobalTranslationOptions beGlobalTranslationOptions, MessageBoxService messageBoxService, TranslationProviderCredential credentials)
        {
            try
            {
                _messageBoxService    = messageBoxService;
                _flavor               = beGlobalTranslationOptions.Model;
                _authenticationMethod = !string.IsNullOrEmpty(beGlobalTranslationOptions.AuthenticationMethod)
                                        ? beGlobalTranslationOptions.AuthenticationMethod
                                        : Constants.APICredentials;
                _studioCredentials = new StudioCredentials();
                _client            = new RestClient($"{Url}/v4")
                {
                    CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore)
                };

                if (!string.IsNullOrEmpty(_authenticationMethod))
                {
                    if (_authenticationMethod.Equals(Constants.APICredentials))
                    {
                        var splitedCredentials = credentials?.Credential.Split('#');
                        // the below condition is needed in case the ClientId is not set and credentials exists
                        if (string.IsNullOrEmpty(beGlobalTranslationOptions.ClientId) &&
                            splitedCredentials.Length == 2 && !string.IsNullOrEmpty(splitedCredentials[0]) && !string.IsNullOrEmpty(splitedCredentials[1]))
                        {
                            beGlobalTranslationOptions.ClientId             = splitedCredentials[0];
                            beGlobalTranslationOptions.ClientSecret         = splitedCredentials[1];
                            beGlobalTranslationOptions.AuthenticationMethod = _authenticationMethod;
                        }
                        if (!string.IsNullOrEmpty(beGlobalTranslationOptions.ClientId) && !string.IsNullOrEmpty(beGlobalTranslationOptions.ClientSecret))
                        {
                            var request = new RestRequest("/token", Method.POST)
                            {
                                RequestFormat = DataFormat.Json
                            };
                            request.AddBody(new { clientId = beGlobalTranslationOptions.ClientId, clientSecret = beGlobalTranslationOptions.ClientSecret });
                            request.RequestFormat = DataFormat.Json;
                            var response = _client.Execute(request);
                            if (response.StatusCode != HttpStatusCode.OK)
                            {
                                throw new Exception(Constants.TokenFailed + response.Content);
                            }
                            dynamic json = JsonConvert.DeserializeObject(response.Content);
                            _client.AddDefaultHeader("Authorization", $"Bearer {json.accessToken}");
                        }
                    }
                    else
                    {
                        var accessToken = string.Empty;
                        Application.Current?.Dispatcher?.Invoke(() =>
                        {
                            accessToken = _studioCredentials.GetToken();
                        });
                        accessToken = _studioCredentials.GetToken();

                        if (!string.IsNullOrEmpty(accessToken))
                        {
                            _client.AddDefaultHeader("Authorization", $"Bearer {accessToken}");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Logger.Error($"{Constants.BeGlobalV4Translator} {ex.Message}\n {ex.StackTrace}");
            }
        }
Example #11
0
        void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = (BackgroundWorker)sender;

            XmlSerializer serializerV = new XmlSerializer(typeof(VisualizationInfo));

            int newIssueCounter       = 0;
            int updateIssueCounter    = 0;
            int unchangedIssueCounter = 0;

            for (int i = 0; i < issues.Count(); i++)
            {
                try
                {
                    Markup issue = issues[i];
                    worker.ReportProgress((100 * i + 1) / issues.Count(), getProgressString(i + 1));// HAS TO BE OUT OF THE DISPATCHER!
                    // check status on each step
                    if (worker.CancellationPending == true)
                    {
                        e.Cancel = true;
                        return; // abort work, if it's cancelled
                    }

                    //CHECK IF ALREADY EXISTING
                    // could use the expression: cf[11600] ~ "aaaa"
                    // = operator not supported
                    string fields = " AND  GUID~" + issue.Topic.Guid + "&fields=key,comment";
                    string query  = "search?jql=project=" + projectKey + fields;

                    var request4 = new RestRequest(query, Method.GET);
                    request4.AddHeader("Content-Type", "application/json");
                    request4.RequestFormat = Arup.RestSharp.DataFormat.Json;
                    var response4 = JiraClient.Client.Execute <Issues>(request4);

                    if (!RestCallback.Check(response4))
                    {
                        break;
                    }

                    //DOESN'T exist already
                    if (!response4.Data.issues.Any())
                    {
                        //files to be uploaded
                        List <string> filesToBeUploaded = new List <string>();
                        if (File.Exists(Path.Combine(path, issue.Topic.Guid, "markup.bcf")))
                        {
                            filesToBeUploaded.Add(Path.Combine(path, issue.Topic.Guid, "markup.bcf"));
                        }
                        issue.Viewpoints.ToList().ForEach(vp => {
                            if (!string.IsNullOrWhiteSpace(vp.Snapshot) && File.Exists(Path.Combine(path, issue.Topic.Guid, vp.Snapshot)))
                            {
                                filesToBeUploaded.Add(Path.Combine(path, issue.Topic.Guid, vp.Snapshot));
                            }
                            if (!string.IsNullOrWhiteSpace(vp.Viewpoint) && File.Exists(Path.Combine(path, issue.Topic.Guid, vp.Viewpoint)))
                            {
                                filesToBeUploaded.Add(Path.Combine(path, issue.Topic.Guid, vp.Viewpoint));
                            }
                        });
                        string key = "";

                        //update view - it might be a new issue (for direct Jira upload)
                        // Serialize the object, and close the TextWriter
                        string viewpoint = Path.Combine(path, issue.Topic.Guid, "viewpoint.bcfv");
                        if (!File.Exists(viewpoint))
                        {
                            Stream writerV = new FileStream(viewpoint, FileMode.Create);
                            serializerV.Serialize(writerV, issue.Viewpoints[0].VisInfo);
                            writerV.Close();
                        }
                        if (filesToBeUploaded.Find(file => file == viewpoint) == null)
                        {
                            filesToBeUploaded.Add(viewpoint);
                        }

                        var request = new RestRequest("issue", Method.POST);
                        request.AddHeader("Content-Type", "application/json");
                        request.RequestFormat = Arup.RestSharp.DataFormat.Json;

                        newIssueCounter++;
                        var newissue =
                            new
                        {
                            fields = new Dictionary <string, object>()
                        };
                        newissue.fields.Add("project", new { key = projectKey });
                        //newissue.fields.Add("parent", new { key = "BCF-20" });
                        if (!string.IsNullOrWhiteSpace(issuesJira[i].fields.description))
                        {
                            newissue.fields.Add("description", issuesJira[i].fields.description);
                        }
                        newissue.fields.Add("summary", (string.IsNullOrWhiteSpace(issue.Topic.Title)) ? "no title" : issue.Topic.Title);
                        newissue.fields.Add("issuetype", new { id = issuesJira[i].fields.issuetype.id });
                        newissue.fields.Add(MySettings.Get("guidfield"), issue.Topic.Guid);

                        // validate assignee name if present
                        if (issuesJira[i].fields.assignee != null)
                        {
                            if (!string.IsNullOrWhiteSpace(issuesJira[i].fields.assignee.name))
                            {
                                if (isAssigneeAssignable(issuesJira[i].fields.assignee.name, projectKey))
                                {
                                    newissue.fields.Add("assignee", new { name = issuesJira[i].fields.assignee.name });
                                }
                                else
                                {
                                    newissue.fields.Add("assignee", new { name = issuesJira[i].fields.creator.name });
                                }
                            }
                        }


                        if (issuesJira[i].fields.priority != null)
                        {
                            newissue.fields.Add("priority", new { id = issuesJira[i].fields.priority.id });
                        }

                        if (issuesJira[i].fields.components != null && issuesJira[i].fields.components.Any())
                        {
                            newissue.fields.Add("components", issuesJira[i].fields.components);
                        }

                        if (issuesJira[i].fields.labels != null && issuesJira[i].fields.labels.Any())
                        {
                            newissue.fields.Add("labels", issuesJira[i].fields.labels);
                        }

                        request.AddBody(newissue);

                        var response = JiraClient.Client.Execute(request);

                        var responseIssue = new Issue();
                        if (RestCallback.Check(response))
                        {
                            responseIssue = Arup.RestSharp.SimpleJson.DeserializeObject <Issue>(response.Content);
                            key           = responseIssue.key;//attach and comment sent to the new issue
                        }
                        else
                        {
                            uploadErrors++;
                            break;
                        }

                        //upload all viewpoints and snapshots
                        var request2 = new RestRequest("issue/" + key + "/attachments", Method.POST);
                        request2.AddHeader("X-Atlassian-Token", "nocheck");
                        request2.RequestFormat = Arup.RestSharp.DataFormat.Json;
                        filesToBeUploaded.ForEach(file => request2.AddFile("file", File.ReadAllBytes(file), Path.GetFileName(file)));
                        var response2 = JiraClient.Client.Execute(request2);
                        RestCallback.Check(response2);

                        //ADD COMMENTS
                        if (issue.Comment.Any())
                        {
                            issue.Comment = new System.Collections.ObjectModel.ObservableCollection <BCF2.Comment>(issue.Comment.Reverse());
                            foreach (var c in issue.Comment)
                            {
                                if (string.IsNullOrEmpty(c.Comment1))
                                {
                                    continue;
                                }
                                var request3 = new RestRequest("issue/" + key + "/comment", Method.POST);
                                request3.AddHeader("Content-Type", "application/json");
                                request3.RequestFormat = Arup.RestSharp.DataFormat.Json;
                                var newcomment = new { body = c.Comment1 };
                                request3.AddBody(newcomment);
                                var response3 = JiraClient.Client.Execute <Comment2>(request3);
                                if (!RestCallback.Check(response3))
                                {
                                    break;
                                }
                            }
                        }

                        if (i == issues.Count() - 1)
                        {
                            worker.ReportProgress(100, getProgressString(i + 1));
                        }
                    }
                    else //UPDATE ISSUE
                    {
                        var oldIssue = response4.Data.issues.First();
                        if (issue.Comment.Any())
                        {
                            issue.Comment = new System.Collections.ObjectModel.ObservableCollection <BCF2.Comment>(issue.Comment.Reverse());
                            int unmodifiedCommentNumber = 0;
                            foreach (var c in issue.Comment)
                            {
                                //clean all metadata annotations
                                string newComment  = cleanAnnotationInComment(c.Comment1);
                                string normalized1 = Regex.Replace(newComment, @"\s", "");
                                if (oldIssue.fields.comment.comments.Any(o => Regex.Replace(cleanAnnotationInComment(o.body), @"\s", "").Equals(normalized1, StringComparison.OrdinalIgnoreCase)))
                                {
                                    unmodifiedCommentNumber++;
                                    continue;
                                }

                                var request3 = new RestRequest("issue/" + oldIssue.key + "/comment", Method.POST);
                                request3.AddHeader("Content-Type", "application/json");
                                request3.RequestFormat = Arup.RestSharp.DataFormat.Json;
                                var newcomment = new { body = c.Comment1 };
                                request3.AddBody(newcomment);
                                var response3 = JiraClient.Client.Execute <Comment2>(request3);

                                //upload viewpoint and snapshot
                                var request5 = new RestRequest("issue/" + oldIssue.key + "/attachments", Method.POST);
                                request5.AddHeader("X-Atlassian-Token", "nocheck");
                                request5.RequestFormat = Arup.RestSharp.DataFormat.Json;
                                issue.Viewpoints.ToList().ForEach(vp => {
                                    if (c.Viewpoint != null)
                                    {
                                        if (vp.Guid == c.Viewpoint.Guid)
                                        {
                                            if (File.Exists(Path.Combine(path, issue.Topic.Guid, vp.Snapshot)))
                                            {
                                                request5.AddFile("file", File.ReadAllBytes(Path.Combine(path, issue.Topic.Guid, vp.Snapshot)), vp.Snapshot);
                                            }
                                            if (File.Exists(Path.Combine(path, issue.Topic.Guid, vp.Viewpoint)))
                                            {
                                                request5.AddFile("file", File.ReadAllBytes(Path.Combine(path, issue.Topic.Guid, vp.Viewpoint)), vp.Viewpoint);
                                            }
                                        }
                                    }
                                });
                                if (request5.Files.Count > 0)
                                {
                                    var response5 = JiraClient.Client.Execute(request5);
                                    RestCallback.Check(response5);
                                }


                                if (!RestCallback.Check(response3))
                                {
                                    break;
                                }
                            }

                            if (unmodifiedCommentNumber == issue.Comment.Count)
                            {
                                unchangedIssueCounter++;
                            }
                            else
                            {
                                updateIssueCounter++;
                            }
                        }
                        else
                        {
                            unchangedIssueCounter++;
                        }
                    }
                } // END TRY
                catch (System.Exception ex1)
                {
                    MessageBox.Show("exception: " + ex1);
                }
            }// END LOOP

            string msg = string.Format("{0} new issue(s) added, {1} issue(s) updated, and {2} issue(s) unchanged.", newIssueCounter, updateIssueCounter, unchangedIssueCounter);

            MessageBox.Show(msg, "Success", MessageBoxButton.OK, MessageBoxImage.Information);
        }
Example #12
0
        private static string ExecuteFiddle(FiddleExecuteModel model)
        {
            var client = new RestClient(ApiUrl);

            // execute request through API
            var request = new RestRequest("execute", Method.POST);

            request.RequestFormat = DataFormat.Json;
            request.AddBody(model);

            IRestResponse <FiddleExecuteResult> response = client.Execute <FiddleExecuteResult>(request);

            StringBuilder result = new StringBuilder();

            if (response.StatusCode != HttpStatusCode.OK)
            {
                result.AppendLine("Failed to execute API request. Here is an answer from API");
                result.AppendLine("Response Code: " + response.StatusCode);
                result.AppendLine("Response Body: " + response.Content);
            }
            else
            {
                // write usage statistics
                foreach (var header in response.Headers)
                {
                    //if (header.Name == "X-RateLimit-Limit")
                    //{
                    //    result.AppendLine("Your total per hour limit is " + header.Value);
                    //}

                    //if (header.Name == "X-RateLimit-Remaining")
                    //{
                    //    result.AppendLine("Your remaining executions count per hour is " + header.Value);
                    //}

                    if (header.Name == "X-RateLimit-Reset")
                    {
                        var epochTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
                        epochTime = epochTime.AddSeconds(int.Parse(header.Value.ToString()));
                        //result.AppendLine("UTC Time when limit will be refreshed " + epochTime);
                    }
                }

                //result.AppendLine();
                //result.AppendLine("Code output:");
                result.AppendLine(response.Data.ConsoleOutput);
            }
            var   resultString = result.Replace(Environment.NewLine, "<br/>").ToString();
            Regex regex        = new Regex("error");
            Regex regex1       = new Regex("exception");

            if (regex.IsMatch(resultString.ToLower()) || regex1.IsMatch(resultString.ToLower()))
            {
                correct = false;
                return("Не верно <br/>" + resultString);
            }


            correct = true;
            return("ЗАДАНИЕ ВЫПОЛНЕНО <br/>" + resultString);
        }
Example #13
0
        internal static RestRequest Get(Type type, RestObject restObj)
        {
            restObj.type = restObj.Type;

            var request = new RestRequest
            {
                RequestFormat = DataFormat.Json
            };

            switch (type)
            {
            case Type.Get:
                request.Method   = Method.GET;
                request.Resource = restObj.Uri + "/" + restObj.id + "?depth=" + restObj.depth;
                break;

            case Type.Put:
                request.Method   = Method.PUT;
                request.Resource = restObj.Uri + "/" + restObj.id;
                request.AddBody(restObj);
                break;

            case Type.Post:
                request.Method   = Method.POST;
                request.Resource = restObj.Uri;
                request.AddBody(restObj);
                break;

            case Type.Delete:
                request.Method   = Method.DELETE;
                request.Resource = restObj.Uri + "/" + restObj.id;
                break;

            case Type.Search:
                request.Method = Method.GET;

                var resource = new StringBuilder(100);
                resource.Append(restObj.Uri);

                if (restObj.id != null && restObj.id > 0)
                {
                    resource.Append("/" + restObj.id);
                }
                else
                {
                    resource.Append("s");     // pluralize the endpoint
                }

                var searchObj = restObj as ISearchable;
                resource.Append("?search=" + searchObj.searchTerm +
                                "&count=" + searchObj.pageSize +
                                "&page=" + searchObj.page +
                                "&depth=" + restObj.depth
                                );

                request.Resource = resource.ToString();

                break;

            default:
                throw new NotSupportedException(type.ToString());
            }
            return(request);
        }
        public bool get_am_par(ref ws_rec_lmparam AMData)
        {
            string ServiceUrl = "";


            if (Production)
            {
                ServiceUrl = @"http://lm.giessedati.it/lmAPI/v1/getAMParam";
            }
            else
            {
                ServiceUrl = @"http://test.giessedati.it/licenseManagerAPI/v1/getAMParam";
            }

            try
            {
                var client = new RestClient(ServiceUrl);

                if (!String.IsNullOrEmpty(this._ProxyUser))
                {
                    client.Proxy             = new WebProxy(_ProxyHost, _ProxyPort);
                    client.Proxy.Credentials = new NetworkCredential(_ProxyUser, _ProxyPassword);
                }


                var request = new RestRequest("/", Method.POST);

                request.RequestFormat = DataFormat.Json;
                request.AddBody(new { AuthKeyAPI = AuthKeyLM });
                var response = client.Execute <ws_rec_lmparam>(request);

                if (response.ResponseStatus != ResponseStatus.Completed)
                {
                    throw new Exception("ResponseStatus: " + response.ErrorMessage);
                }

                if (response.StatusCode != HttpStatusCode.OK)
                {
                    throw new Exception("StatusCode: " + response.StatusCode);
                }

                if (response.ErrorException != null)
                {
                    throw new Exception("Error retrieving response 2.  Check inner details for more info.");
                }

#if NET20
                var myDeserializedData = JsonConvert.DeserializeObject <ws_rec_lmparam>(response.Content);
#endif

#if NET35 || NET40
                var myDeserializedData = response.Data;
#endif

                _ResponseURI = response.ResponseUri.ToString();

                AMData = myDeserializedData;

                if (AMData != null)
                {
                    _CodProgetto      = AMData.cod_prog;
                    AMData.url_am_api = AMData.url_am_api + "/" + AMData.cod_prog;
                }
            }
            catch (Exception ex)
            {
                throw new Exception("get_am_par: " + ex.Message, ex);
            }
            return(true);
        }
Example #15
0
 /// <summary>
 /// Sends a post request to the rest server
 /// </summary>
 public override void SendPostRequest()
 {
     SetPost();
     request.AddBody(Body);
     var response = client.Execute(request);
 }
Example #16
0
        /// <summary>
        /// Build up and execute a REST request
        /// </summary>
        /// <param name="uri">The URI of the REST request. Don't prepend the host information since that will be set automatically.</param>
        /// <param name="p">A Dictionary of parameters</param>
        /// <param name="method">Which HTTP method to use</param>
        /// <returns>The REST response object</returns>
        private IRestResponse buildRESTRequest(string uri, Dictionary <string, string> p, Method method = Method.GET, Dictionary <string, FileInfo> files = null, object body = null)
        {
            if (p == null)
            {
                p = new Dictionary <string, string>();
            }

            p.Add("application_version", "10.0");
            p.Add("device_type", "BIM 360 Field .NET API Client");

            IRestClient client = new RestClient();

            client.BaseUrl = _url;

            IRestRequest request = new RestRequest(uri, method);

            request.RequestFormat = DataFormat.Json;

            if (body != null && (method == Method.PUT || method == Method.POST))
            {
                if (_token != null)
                {
                    ((Dictionary <string, object>)body).Add("ticket", _token.ticket);
                }
                request.AddBody(body);
                request.AddUrlSegment("id", p["id"]);

                // This is a hack for the document delete method
                if (p.ContainsKey("rev"))
                {
                    request.AddUrlSegment("rev", p["rev"]);
                }
            }
            else
            {
                if (_token != null)
                {
                    p.Add("ticket", _token.ticket);
                }

                if (files != null)
                {
                    foreach (var upload in files)
                    {
                        request.AddFile(upload.Key, upload.Value.FullName);
                    }
                }

                if (p != null)
                {
                    foreach (string key in p.Keys)
                    {
                        if (key == "id")
                        {
                            request.AddUrlSegment(key, p[key]);
                        }
                        else
                        {
                            request.AddParameter(key, p[key]);
                        }
                    }
                }
            }

            IRestResponse response = client.Execute(request);

            if (response.StatusCode == HttpStatusCode.Unauthorized)
            {
                throw new UnauthorizedAccessException(response.Content);
            }

            int code = (int)response.StatusCode;

            if (code >= 400)
            {
                throw new BIM360FieldAPIException(response.Content, code);
            }

            return(response);
        }
Example #17
0
        public RestAPIResponse Request(string endpoint, dynamic parameters = null, RestSharp.Method method = Method.GET)
        {
            RestClient client;

            client = new RestClient(_baseUrl + "v" + _apiVersion);
            client.Authenticator = _auth;
            client.UserAgent     = _userAgent;

            var request = new RestRequest(endpoint, method);

            RestAPIResponse result = null;

            if (parameters != null)
            {
                var parsedParams = APIHelpers.ParseParameters(endpoint, parameters);

                if (method == Method.POST || method == Method.PUT)
                {
                    request.RequestFormat = DataFormat.Json;
                    request.AddBody(parsedParams);
                }
                else
                {
                    foreach (var prm in (IDictionary <string, object>)parsedParams)
                    {
                        request.AddParameter(prm.Key, prm.Value, ParameterType.GetOrPost);
                    }
                }
            }


            IRestResponse response = client.Execute(request);

            if (endpoint == "pull")
            {
                result = new PullAPIResponse()
                {
                    RateLimit = APIHelpers.ParseRateLimitHeaders(response.Headers), StatusCode = response.StatusCode, PullDetails = APIHelpers.ParsePullDetailHeaders(response.Headers)
                };
                result.Data = APIHelpers.DeserializeResponse(response.Content, ((PullAPIResponse)result).PullDetails.Format);
            }
            else
            {
                result = new RestAPIResponse()
                {
                    RateLimit = APIHelpers.ParseRateLimitHeaders(response.Headers), StatusCode = response.StatusCode
                };
                result.Data = APIHelpers.DeserializeResponse(response.Content);
            }

            switch ((int)response.StatusCode)
            {
            // Ok status codes
            case 200:
            case 201:
            case 202:
            case 204:
                break;

            //Error status codes
            case 400:
            case 401:
            case 403:
            case 404:
            case 405:
            case 409:
            case 413:
            case 416:
            case 500:
            case 503:
                throw new RestAPIException(result, (APIHelpers.HasAttr(result.Data, "error")) ? result.Data.error : "The request failed, please see the Data & StatusCode properties for more details.");

            case 429:
                throw new TooManyRequestsException(result, (APIHelpers.HasAttr(result.Data, "error")) ? result.Data.error : "The request failed because you've exceeded your API request limit.");
            }

            return(result);
        }
        private static void CrearResumenDiario()
        {
            try
            {
                Console.WriteLine("Ejemplo de Resumen Diario");
                var documentoResumenDiario = new ResumenDiario
                {
                    IdDocumento     = string.Format("RC-{0:yyyyMMdd}-001", DateTime.Today),
                    FechaEmision    = DateTime.Today.ToString("yyyy-MM-dd"),
                    FechaReferencia = DateTime.Today.AddDays(-1).ToString("yyyy-MM-dd"),
                    Emisor          = CrearEmisor(),
                    Resumenes       = new List <GrupoResumen>()
                };

                documentoResumenDiario.Resumenes.Add(new GrupoResumen
                {
                    Id = 1,
                    CorrelativoInicio = 33386,
                    CorrelativoFin    = 33390,
                    Moneda            = "PEN",
                    TotalVenta        = 190.9m,
                    TotalIgv          = 29.12m,
                    Gravadas          = 161.78m,
                    Exoneradas        = 0,
                    Exportacion       = 0,
                    TipoDocumento     = "03",
                    Serie             = "BB50"
                });
                documentoResumenDiario.Resumenes.Add(new GrupoResumen
                {
                    Id = 2,
                    CorrelativoInicio = 40000,
                    CorrelativoFin    = 40500,
                    Moneda            = "PEN",
                    TotalVenta        = 9580m,
                    TotalIgv          = 1411.36m,
                    Gravadas          = 8168.64m,
                    Exoneradas        = 0,
                    Exportacion       = 0,
                    TipoDocumento     = "03",
                    Serie             = "BB30"
                });


                Console.WriteLine("Generando XML....");
                var client         = new RestClient(BaseUrl);
                var requestInvoice = new RestRequest("GenerarResumenDiario", Method.POST)
                {
                    RequestFormat = DataFormat.Json
                };
                requestInvoice.AddBody(documentoResumenDiario);
                var documentoResponse = client.Execute <DocumentoResponse>(requestInvoice);
                if (!documentoResponse.Data.Exito)
                {
                    throw new ApplicationException(documentoResponse.Data.MensajeError);
                }
                Console.WriteLine("Firmando XML...");
                // Firmado del Documento.
                var firmado = new FirmadoRequest
                {
                    TramaXmlSinFirma    = documentoResponse.Data.TramaXmlSinFirma,
                    CertificadoDigital  = Convert.ToBase64String(File.ReadAllBytes("Certificado.pfx")),
                    PasswordCertificado = string.Empty,
                    UnSoloNodoExtension = true
                };

                var requestFirma = new RestRequest("Firmar", Method.POST)
                {
                    RequestFormat = DataFormat.Json
                };
                requestFirma.AddBody(firmado);

                var responseFirma = client.Execute <FirmadoResponse>(requestFirma);

                if (!responseFirma.Data.Exito)
                {
                    throw new ApplicationException(responseFirma.Data.MensajeError);
                }

                Console.WriteLine("Enviando a SUNAT....");

                var sendBill = new EnviarDocumentoRequest
                {
                    Ruc             = documentoResumenDiario.Emisor.NroDocumento,
                    UsuarioSol      = "MODDATOS",
                    ClaveSol        = "MODDATOS",
                    EndPointUrl     = UrlSunat,
                    IdDocumento     = documentoResumenDiario.IdDocumento,
                    TramaXmlFirmado = responseFirma.Data.TramaXmlFirmado
                };

                var requestSendBill = new RestRequest("EnviarResumen", Method.POST)
                {
                    RequestFormat = DataFormat.Json
                };

                requestSendBill.AddBody(sendBill);

                var responseSendBill = client.Execute <EnviarDocumentoResponse>(requestSendBill);

                if (!responseSendBill.Data.Exito)
                {
                    throw new ApplicationException(responseSendBill.Data.MensajeError);
                }
                File.WriteAllBytes(string.Format(".\\{0}.xml", responseSendBill.Data.NombreArchivo), Convert.FromBase64String(responseFirma.Data.TramaXmlFirmado));

                File.WriteAllBytes(string.Format(".\\R-{0}.zip", responseSendBill.Data.NombreArchivo), Convert.FromBase64String(responseSendBill.Data.TramaZipCdr));


                Console.WriteLine("Respuesta de SUNAT:");
                Console.WriteLine(responseSendBill.Data.MensajeRespuesta);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                Console.ReadLine();
            }
        }
Example #19
0
        public bool POSTTrans(SyncForm sync, int idUser, string pwd, int idClient)
        {
            Directory.CreateDirectory(pathFolderName);
            string[]      filePaths  = Directory.GetFiles(pathFolderName);
            List <string> upcFiles   = new List <string>();
            List <string> epcFiles   = new List <string>();
            List <string> messages   = new List <string>();
            int           numInputs  = 0;
            int           numOutputs = 0;

            foreach (String path in filePaths)
            {
                if (path.Contains("epc"))
                {
                    epcFiles.Add(path);
                }
                if (path.Contains("message"))
                {
                    messages.Add(path);
                }
                if (path.Contains("iepc"))
                {
                    numInputs++;
                }
                if (path.Contains("oepc"))
                {
                    numOutputs++;
                }
            }

            sync.updateInputs(numInputs.ToString() + " Inventarios");
            sync.updateOutputs(numOutputs.ToString() + " Salidas");
            Application.DoEvents();

            foreach (String path1 in epcFiles)
            {
                var request = new RestRequest("sync", Method.POST);
                request.RequestFormat = DataFormat.Json;
                request.AddBody(buildPOSTRequest(path1, ""));
                IRestResponse response = client.Execute(request);
                if (!requestError(response.StatusCode.ToString()))
                {
                    return(false);
                }

                Application.DoEvents();
                String nameFileMessage = path1.Replace("iepcs", "message").Replace("oepcs", "message");
                File.Move(nameFileMessage, nameFileMessage.Replace("rfiddata", "rfiddataold"));
                File.Move(path1, path1.Replace("rfiddata", "rfiddataold"));
                File.Move(path1.Replace("epc", "upc"), path1.Replace("rfiddata", "rfiddataold").Replace("epc", "upc"));
                if (path1.Contains("iepc"))
                {
                    numInputs--;
                    sync.updateInputs(numInputs.ToString() + " Entradas");
                }
                else if (path1.Contains("oepc"))
                {
                    numOutputs--;
                    sync.updateOutputs(numOutputs.ToString() + " Salidas");
                }
            }
            return(true);
        }
Example #20
0
        private static void WriteDetails(String token, String worker, string date, String timesheetNbr, String project, String activity, string hours, String dataAreaId)
        {
            //var entry = new JObject
            //{
            //    { "parmResource", worker },
            //    { "parmTimesheetNumber", headerId },
            //    { "parmProjectDataAreaId", dataAreaId },
            //    { "parmProjId", project },
            //    { "parmProjActivityNumber", activity },
            //    { "parmEntryDate", date },
            //    { "parmHrsPerDay", 4 },
            //    { "customFields", new JArray() },
            //};
            //var eList = new JArray();
            //eList.Add(entry);

            //var entryList = new JObject
            //{
            //    {"entryList", eList }
            //};


            //var tsEntryList = new JObject
            //{
            //    { "_tsTimesheetEntryList", entryList }
            //};

            var entry = new
            {
                parmResource           = worker,
                parmTimesheetNumber    = timesheetNbr,
                parmProjectDataAreaId  = dataAreaId,
                parmProjId             = project,
                parmProjActivityNumber = activity,
                parmEntryDate          = date,
                parmHrsPerDay          = 4
            };

            object[] eList = new object[1];
            eList[0] = entry;

            var entryList = new
            {
                entryList = eList
            };

            var tsEntryList = new
            {
                _tsTimesheetEntryList = entryList
            };

            var client  = new RestClient("https://ad-ctp-10-38eb6867baef10230aos.cloudax.dynamics.com/api/services/TSTimesheetServices/TSTimesheetSubmissionService/createOrUpdateTimesheetLine");
            var request = new RestRequest(Method.POST);

            request.AddHeader("authorization", "Bearer " + token);
            request.AddHeader("Content-Type", "application/json");

            request.RequestFormat = DataFormat.Json;
            request.AddBody(tsEntryList);

            IRestResponse response = client.Execute(request);
            dynamic       resp     = JObject.Parse(response.Content);

            Console.WriteLine($"StatusCode: {response.StatusCode}, ErrorMessage: {response.ErrorMessage}, Content: {response.Content}");
        }
Example #21
0
        /// <summary>
        /// Standardizes and Geocodes an address using Smarty Streets service
        /// </summary>
        /// <param name="location">The location.</param>
        /// <param name="resultMsg">The result MSG.</param>
        /// <returns>
        /// True/False value of whether the verification was successful or not
        /// </returns>
        public override VerificationResult Verify(Rock.Model.Location location, out string resultMsg)
        {
            VerificationResult result = VerificationResult.None;

            resultMsg = string.Empty;

            string authId    = null;
            string authToken = null;

            if (GetAttributeValue("UseManagedAPIKey").AsBooleanOrNull() ?? true)
            {
                var lastKeyUpdate        = Rock.Web.SystemSettings.GetValue("core_SmartyStreetsApiKeyLastUpdate").AsDateTime() ?? DateTime.MinValue;
                var hoursSinceLastUpdate = (RockDateTime.Now - lastKeyUpdate).TotalHours;
                if (hoursSinceLastUpdate > 24 || true)
                {
                    var rockInstanceId  = Rock.Web.SystemSettings.GetRockInstanceId();
                    var getAPIKeyClient = new RestClient("https://www.rockrms.com/api/SmartyStreets/GetSmartyStreetsApiKey?rockInstanceId={rockInstanceId}");

                    // If debugging locally
                    // var getAPIKeyClient = new RestClient( $"http://localhost:57822/api/SmartyStreets/GetSmartyStreetsApiKey?rockInstanceId={rockInstanceId}" );

                    var getApiKeyRequest  = new RestRequest(Method.GET);
                    var getApiKeyResponse = getAPIKeyClient.Get <SmartyStreetsAPIKey>(getApiKeyRequest);

                    if (getApiKeyResponse.StatusCode == HttpStatusCode.OK)
                    {
                        SmartyStreetsAPIKey managedKey = getApiKeyResponse.Data;
                        if (managedKey.AuthID != null && managedKey.AuthToken != null)
                        {
                            Rock.Web.SystemSettings.SetValue("core_SmartyStreetsApiKeyLastUpdate", RockDateTime.Now.ToString("o"));
                            Rock.Web.SystemSettings.SetValue("core_SmartyStreetsAuthID", Rock.Security.Encryption.EncryptString(managedKey.AuthID));
                            Rock.Web.SystemSettings.SetValue("core_SmartyStreetsAuthToken", Rock.Security.Encryption.EncryptString(managedKey.AuthToken));
                        }
                    }
                }

                string encryptedAuthID    = Rock.Web.SystemSettings.GetValue("core_SmartyStreetsAuthID");
                string encryptedAuthToken = Rock.Web.SystemSettings.GetValue("core_SmartyStreetsAuthToken");

                authId    = Rock.Security.Encryption.DecryptString(encryptedAuthID);
                authToken = Rock.Security.Encryption.DecryptString(encryptedAuthToken);
            }

            if (authId == null || authToken == null)
            {
                authId    = GetAttributeValue("AuthID");
                authToken = GetAttributeValue("AuthToken");
            }

            var dpvCodes   = GetAttributeValue("AcceptableDPVCodes").SplitDelimitedValues();
            var precisions = GetAttributeValue("AcceptablePrecisions").SplitDelimitedValues();

            var payload = new[] { new { addressee = location.Name, street = location.Street1, street2 = location.Street2, city = location.City, state = location.State, zipcode = location.PostalCode, candidates = 1 } };

            var client  = new RestClient(string.Format("https://api.smartystreets.com/street-address?auth-id={0}&auth-token={1}", authId, authToken));
            var request = new RestRequest(Method.POST);

            request.RequestFormat = DataFormat.Json;
            request.AddHeader("Accept", "application/json");
            request.AddBody(payload);
            var response = client.Execute(request);

            if (response.StatusCode == HttpStatusCode.OK)
            {
                var candidates = JsonConvert.DeserializeObject(response.Content, typeof(List <CandidateAddress>)) as List <CandidateAddress>;
                if (candidates.Any())
                {
                    var candidate = candidates.FirstOrDefault();
                    resultMsg = string.Format("RecordType:{0}; DPV MatchCode:{1}; Precision:{2}",
                                              candidate.metadata.record_type, candidate.analysis.dpv_match_code, candidate.metadata.precision);

                    location.StandardizeAttemptedResult = candidate.analysis.dpv_match_code;
                    if (dpvCodes.Contains(candidate.analysis.dpv_match_code))
                    {
                        location.Street1    = candidate.delivery_line_1;
                        location.Street2    = candidate.delivery_line_2;
                        location.City       = candidate.components.city_name;
                        location.County     = candidate.metadata.county_name;
                        location.State      = candidate.components.state_abbreviation;
                        location.PostalCode = candidate.components.zipcode + "-" + candidate.components.plus4_code;
                        location.Barcode    = candidate.delivery_point_barcode;
                        result = result | VerificationResult.Standardized;
                    }

                    location.GeocodeAttemptedResult = candidate.metadata.precision;
                    if (precisions.Contains(candidate.metadata.precision))
                    {
                        if (location.SetLocationPointFromLatLong(candidate.metadata.latitude, candidate.metadata.longitude))
                        {
                            result = result | VerificationResult.Geocoded;
                        }
                    }
                }
                else
                {
                    resultMsg = "No Match";
                }
            }
            else
            {
                result    = VerificationResult.ConnectionError;
                resultMsg = response.StatusDescription;
            }

            return(result);
        }
Example #22
0
        public void EnvioSunat()
        {
            try
            {
                var estadoProceso = Negocio.Helper.ObtenerValorParametro("ESTADO_SERVICIO_WINDOWS").ToString();

                if (estadoProceso.Equals("P"))
                {
                    return;
                }

                if (estadoProceso.Equals("N"))
                {
                    Negocio.Helper.ActualizarColumnasTabla("ParametrosGlobales", new string[] { "ValorParametro" }, new string[] { "P" }, new string[] { "NombreParametro" }, new string[] { "ESTADO_SERVICIO_WINDOWS" });
                    var ventaPendienteListaInfo = new Venta().Listar(0).Where(v => v.Exito.Equals(0)).ToList();

                    foreach (var v in ventaPendienteListaInfo)
                    {
                        //var ventaId = 1;
                        var ventaId = v.VentaId;
                        var mensaje = String.Empty;

                        //var usuarioInfo = ObtenerUsuarioInfo();
                        var usuarioInfo      = new Usuario().Listar(1, "", "", "", 0, 0).FirstOrDefault();
                        var ventaInfo        = new Venta().Listar(ventaId).FirstOrDefault();
                        var ventaDetalleInfo = new Venta().ListarDetalle(ventaId, 0);
                        var empresaInfo      = new Empresa().Listar(usuarioInfo.EmpresaId).FirstOrDefault();
                        var clienteInfo      = new Cliente().Listar(ventaInfo.ClienteId).FirstOrDefault();

                        _documento = new DocumentoElectronico();

                        #region Documento
                        _documento.CalculoDetraccion = 0;
                        _documento.CalculoIgv        = Decimal.Divide(18, 100);
                        _documento.CalculoIsc        = 0;
                        _documento.DescuentoGlobal   = ventaInfo.Descuento;
                        // _documento.DocAnticipo = String.Empty;

                        #region Emisor
                        var emisor = new DocumentoElectronico().Emisor;
                        emisor.Departamento = empresaInfo.Departamento;
                        //emisor.Departamento = "LIMA";
                        emisor.Direccion = empresaInfo.Direccion;
                        //emisor.Direccion = "LADERAS DE CHILLON";
                        emisor.Distrito = empresaInfo.Distrito;
                        //emisor.Distrito = "PUENTE PIEDRA";
                        emisor.NombreComercial = empresaInfo.RazonSocial;
                        emisor.NombreLegal     = empresaInfo.RazonSocial;
                        //emisor.NombreComercial = "ABARCA URBANO";
                        //emisor.NombreLegal = "MIGUEL ABARCA URBANO";
                        //emisor.NroDocumento = empresaInfo.NumeroDocumento;
                        emisor.NroDocumento = "10421895452";
                        emisor.Provincia    = empresaInfo.Provincia;
                        //emisor.Provincia = "LIMA";
                        emisor.TipoDocumento = empresaInfo.TipoDocumentoId.ToString();
                        emisor.Ubigeo        = empresaInfo.Departamento;
                        emisor.Urbanizacion  = empresaInfo.Direccion;
                        //emisor.Urbanizacion = "LADERAS DE CHILLON";
                        _documento.Emisor = emisor;
                        #endregion

                        _documento.Exoneradas   = 0;
                        _documento.FechaEmision = ventaInfo.FechaEmision.ToString("dd/MM/yyyy");
                        //_documento.FechaEmision = "2017-11-27";
                        _documento.Gratuitas = 0;
                        _documento.Gravadas  = ventaInfo.MontoVenta;
                        //_documento.Gravadas = 1000;
                        _documento.IdDocumento = ventaInfo.NumeroSerie + "-" + ventaInfo.NumeroComprobante;
                        _documento.Inafectas   = 0;

                        #region Items
                        var itemId = 1;
                        foreach (var vd in ventaDetalleInfo)
                        {
                            var item = new DetalleDocumento();
                            item.Cantidad = vd.Cantidad;
                            // item.CodigoItem = vd.Codigo;

                            item.Descripcion = vd.Producto;
                            //item.Descuento = vd.Descuento;
                            item.Id = itemId;
                            itemId++;
                            item.Impuesto = vd.Igv;
                            //item.ImpuestoSelectivo = 0;
                            //item.OtroImpuesto = 0;
                            //item.PrecioReferencial = 0;
                            item.PrecioUnitario = vd.PrecioUnitario;
                            item.Suma           = vd.SubTotal;
                            //item.TipoImpuesto = "10";
                            //item.TipoPrecio = "01";
                            item.TotalVenta   = vd.MontoTotal;
                            item.UnidadMedida = vd.UnidadMedida;
                            //item.CodigoItem = "A0001";
                            item.Descuento = 0;
                            //item.Id = 1;
                            item.ImpuestoSelectivo = 0;
                            item.OtroImpuesto      = 0;
                            item.PrecioReferencial = 0;
                            // item.PrecioUnitario = 50;
                            item.TipoImpuesto = "10";
                            item.TipoPrecio   = "01";
                            // item.UnidadMedida = "NIU";
                            _documento.Items.Add(item);
                        }
                        #endregion

                        _documento.Moneda = ventaInfo.MonedaId.Equals(Constantes.MonedaSoles) ? Constantes.MonedaSolesSunat : Constantes.MonedaDolaresSunat;
                        // _documento.MonedaAnticipo = 0.18;
                        _documento.MontoAnticipo   = 0;
                        _documento.MontoDetraccion = 0;
                        _documento.MontoEnLetras   = Herramientas.NumeroALetras.numeroAletras(ventaInfo.MontoVenta);
                        //_documento.MontoEnLetras = "MIL";
                        _documento.MontoPercepcion = 0;
                        // _documento.PlacaVehiculo = ventaInfo.Placa;

                        #region Receptor
                        var receptor = new DocumentoElectronico().Receptor;
                        receptor.Departamento    = clienteInfo.Departamento;
                        receptor.Direccion       = clienteInfo.Direccion;
                        receptor.Distrito        = clienteInfo.Distrito;
                        receptor.NombreComercial = clienteInfo.RazonSocial;
                        receptor.NombreLegal     = clienteInfo.RazonSocial;
                        //receptor.NombreComercial = "RENE ABARCA URBANO";
                        //receptor.NombreLegal = "RENE ABARCA URBANO";
                        //receptor.NroDocumento = clienteInfo.NumeroDocumento;
                        receptor.NroDocumento  = "10415787796";
                        receptor.Provincia     = clienteInfo.Provincia;
                        receptor.TipoDocumento = clienteInfo.TipoDocumentoId.ToString();
                        receptor.Ubigeo        = clienteInfo.Departamento;
                        receptor.Urbanizacion  = clienteInfo.Direccion;
                        _documento.Receptor    = receptor;
                        #endregion

                        // _documento.TipoDocAnticipo = 0;
                        _documento.TipoDocumento = ventaInfo.TipoComprobanteId;
                        // _documento.TipoOperacion = ventaInfo.TipoOperacionId;
                        _documento.TotalIgv = ventaInfo.MontoImpuesto;
                        //_documento.TotalIgv = 180;
                        _documento.TotalIsc           = 0;
                        _documento.TotalOtrosTributos = 0;
                        _documento.TotalVenta         = ventaInfo.MontoTotal;
                        //_documento.TotalVenta = 1180;
                        #endregion

                        //var proxy = new HttpClient { BaseAddress = new Uri(ConfigurationManager.AppSettings["UrlOpenInvoicePeruApi"]) };

                        string metodoApi;
                        switch (_documento.TipoDocumento)
                        {
                        case "07":
                            metodoApi = "api/GenerarNotaCredito";
                            break;

                        case "08":
                            metodoApi = "api/GenerarNotaDebito";
                            break;

                        default:
                            metodoApi = "api/GenerarFactura";
                            break;
                        }

                        //var response = await proxy.PostAsJsonAsync(metodoApi, _documento);
                        //var respuesta = await response.Content.ReadAsAsync<DocumentoResponse>();

                        #region Generando XML
                        var client = new RestClient(BaseUrl);

                        var requestInvoice = new RestRequest("GenerarFactura", Method.POST)
                        {
                            RequestFormat = DataFormat.Json
                        };

                        requestInvoice.AddBody(_documento);

                        var documentoResponse = client.Execute <DocumentoResponse>(requestInvoice);

                        if (!documentoResponse.Data.Exito)
                        {
                            throw new ApplicationException(documentoResponse.Data.MensajeError);
                        }
                        //string rutaXml = HostingEnvironment.MapPath("~/Archivos/Facturacion/XML/" + _documento.IdDocumento + ".xml");
                        string rutaXml = @"D:\ASOLUTIONS\APU\APU.Presentacion\Archivos\Facturacion\XML\" + _documento.IdDocumento + ".xml";
                        File.WriteAllBytes(rutaXml, Convert.FromBase64String(documentoResponse.Data.TramaXmlSinFirma));
                        #endregion

                        #region Firma
                        //string rutaCertificado = HostingEnvironment.MapPath("~/Archivos/Facturacion/certificado.pfx");
                        var rutaCertificado = @"D:\ASOLUTIONS\APU\APU.Presentacion\certificado.pfx";
                        var firmado         = new FirmadoRequest
                        {
                            TramaXmlSinFirma = documentoResponse.Data.TramaXmlSinFirma,
                            //CertificadoDigital = Convert.ToBase64String(File.ReadAllBytes("certificado.pfx")),
                            CertificadoDigital  = Convert.ToBase64String(File.ReadAllBytes(rutaCertificado)),
                            PasswordCertificado = string.Empty,
                            UnSoloNodoExtension = false
                        };

                        var requestFirma = new RestRequest("Firmar", Method.POST)
                        {
                            RequestFormat = DataFormat.Json
                        };
                        requestFirma.AddBody(firmado);

                        var responseFirma = client.Execute <FirmadoResponse>(requestFirma);

                        if (!responseFirma.Data.Exito)
                        {
                            throw new ApplicationException(responseFirma.Data.MensajeError);
                        }
                        //string rutaXmlFirmado = HostingEnvironment.MapPath("~/Archivos/Facturacion/XML/" + _documento.IdDocumento + "_Firmado.xml");
                        string rutaXmlFirmado = @"D:\ASOLUTIONS\APU\APU.Presentacion\Archivos\Facturacion\XML\" + _documento.IdDocumento + "_Firmado.xml";
                        File.WriteAllBytes(rutaXmlFirmado, Convert.FromBase64String(responseFirma.Data.TramaXmlFirmado));
                        #endregion

                        #region Envio SUNAT
                        var sendBill = new EnviarDocumentoRequest
                        {
                            //Ruc = _documento.Emisor.NroDocumento,
                            Ruc = "10421895452",
                            //UsuarioSol = "MODDATOS",
                            UsuarioSol = "MMINSIOT",
                            //ClaveSol = "MODDATOS",
                            ClaveSol        = "saywalcod",
                            EndPointUrl     = UrlSunat,
                            IdDocumento     = _documento.IdDocumento,
                            TipoDocumento   = _documento.TipoDocumento,
                            TramaXmlFirmado = responseFirma.Data.TramaXmlFirmado
                        };

                        var requestSendBill = new RestRequest("EnviarDocumento", Method.POST)
                        {
                            RequestFormat = DataFormat.Json
                        };
                        requestSendBill.AddBody(sendBill);

                        var responseSendBill = client.Execute <EnviarDocumentoResponse>(requestSendBill);

                        if (!responseSendBill.Data.Exito)
                        {
                            // throw new ApplicationException(responseSendBill.Data.MensajeError);
                        }
                        else
                        {
                            //string rutaCdr = HostingEnvironment.MapPath("~/Archivos/Facturacion/CDR/" + responseSendBill.Data.NombreArchivo + ".zip");
                            string rutaCdr = @"D:\ASOLUTIONS\APU\APU.Presentacion\Archivos\Facturacion\CDR\" + responseSendBill.Data.NombreArchivo + ".zip";
                            File.WriteAllBytes(rutaCdr, Convert.FromBase64String(responseSendBill.Data.TramaZipCdr));
                        }

                        //Console.WriteLine("Respuesta de SUNAT:");
                        //Console.WriteLine(responseSendBill.Data.MensajeRespuesta);
                        var data = responseSendBill.Data;
                        mensaje = data.Exito ? data.MensajeRespuesta : data.MensajeError;

                        var ventaSunatInfo = new VentaSunatInfo();
                        ventaSunatInfo.VentaId           = ventaId;
                        ventaSunatInfo.CodigoRespuesta   = (data.CodigoRespuesta == null) ? String.Empty : data.CodigoRespuesta;
                        ventaSunatInfo.Exito             = data.Exito ? 1 : 0;
                        ventaSunatInfo.MensajeError      = (data.MensajeError == null) ? String.Empty : data.MensajeError;
                        ventaSunatInfo.MensajeRespuesta  = (data.MensajeRespuesta == null) ? String.Empty : data.MensajeRespuesta;
                        ventaSunatInfo.NombreArchivo     = (data.NombreArchivo == null) ? String.Empty : data.NombreArchivo;
                        ventaSunatInfo.Pila              = (data.Pila == null) ? String.Empty : data.Pila;
                        ventaSunatInfo.TramaZipCdr       = (data.TramaZipCdr == null) ? String.Empty : data.TramaZipCdr;
                        ventaSunatInfo.UsuarioCreacionId = usuarioInfo.UsuarioId;
                        new VentaSunat().Insertar(ventaSunatInfo);
                        #endregion
                    }
                }
            }
            catch (Exception ex)
            {
                // Console.WriteLine(e);
                System.Diagnostics.EventLog.WriteEntry("MyEventSource", ex.StackTrace, System.Diagnostics.EventLogEntryType.Warning);
            }
        }
Example #23
0
        public void CityPostGetPutDeleteFlow()
        {
            var postCity = new RestRequest("api/City/", Method.POST)
            {
                RequestFormat = DataFormat.Json
            };

            postCity.AddBody(new CityApiDto
            {
                Name      = "CityController integration test",
                CountryId = 1
            });
            var postCityResult = _client.Execute <CityApiDto>(postCity);

            _testCityId = postCityResult.Data.Id;

            Assert.AreEqual(postCityResult.ResponseStatus, ResponseStatus.Completed);
            Assert.AreEqual((int)postCityResult.StatusCode, 201);


            var getCity = new RestRequest("api/City/{id}", Method.GET);

            getCity.AddParameter("id", _testCityId);
            var getCityResult = _client.Execute <CityApiDto>(getCity);

            Assert.AreEqual(getCityResult.ResponseStatus, ResponseStatus.Completed);
            Assert.AreEqual((int)getCityResult.StatusCode, 200);
            Assert.AreEqual(getCityResult.Data.Name, "CityController integration test");


            var putCity = new RestRequest("api/City/", Method.PUT)
            {
                RequestFormat = DataFormat.Json
            };

            putCity.AddBody(new CityApiDto
            {
                Id        = _testCityId,
                Name      = "CityController integration test check put",
                CountryId = 2
            });
            var putCityResult = _client.Execute <CityApiDto>(putCity);

            Assert.AreEqual(putCityResult.ResponseStatus, ResponseStatus.Completed);
            Assert.AreEqual((int)putCityResult.StatusCode, 204);

            var getCityResultAfterPut = _client.Execute <CityApiDto>(getCity);

            Assert.AreEqual(getCityResultAfterPut.ResponseStatus, ResponseStatus.Completed);
            Assert.AreEqual((int)getCityResultAfterPut.StatusCode, 200);
            Assert.AreEqual(getCityResultAfterPut.Data.Name, "CityController integration test check put");
            Assert.AreEqual(getCityResultAfterPut.Data.CountryId, 2);


            var deleteCity = new RestRequest("api/City/{id}", Method.DELETE);

            deleteCity.AddParameter("id", _testCityId);
            var deleteCityResult = _client.Execute <CityApiDto>(deleteCity);

            Assert.AreEqual(deleteCityResult.ResponseStatus, ResponseStatus.Completed);
            Assert.AreEqual((int)deleteCityResult.StatusCode, 204);

            var getDeletedCityResult = _client.Execute <CityApiDto>(getCity);

            Assert.AreEqual(getDeletedCityResult.ResponseStatus, ResponseStatus.Completed);
            Assert.AreEqual((int)getDeletedCityResult.StatusCode, 404);
        }
        public static IRestResponse Notify(string data, string interest)
        {
            var PusehrAppId     = "app_id";
            var PusehrAppKey    = "app_key";
            var PusehrAppSecret = "app_secret";

            int timeNow      = (int)((DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds);
            var auth_version = "1.0";

            SortedDictionary <string, string> queryParams = new SortedDictionary <string, string>();

            queryParams.Add("auth_key", PusehrAppKey);
            queryParams.Add("auth_timestamp", timeNow.ToString());
            queryParams.Add("auth_version", "1.0");

            dynamic apnsPayload = new ExpandoObject();

            apnsPayload.aps       = new ExpandoObject();
            apnsPayload.aps.alert = new
            {
                body = data
            };
            string gcmPayload = "";
            string fcmPayload = "";

            var body = new
            {
                interests = new string[] { interest },

/*                webhook_url = "",
 *              webhook_level = "",*/
                apns = apnsPayload,

                /*gcm = gcmPayload,
                *  fcm = fcmPayload,*/
            };
            JsonSerializer serializer     = new JsonSerializer();
            var            serializedBody = serializer.Serialize(body);

            var body_md5 = CryptoHelper.GetMd5Hash(serializedBody);

            queryParams.Add("body_md5", body_md5);

            string queryString = string.Empty;

            foreach (KeyValuePair <string, string> parameter in queryParams)
            {
                queryString += parameter.Key + "=" + parameter.Value + "&";
            }
            queryString = queryString.TrimEnd('&');

            var resource = "notifications";

            resource = resource.TrimStart('/');
            string path = string.Format("/server_api/v1/apps/{0}/{1}", PusehrAppId, resource);

            string authToSign = String.Format(
                "POST" +
                "\n{0}\n{1}",
                path,
                queryString);

            var authSignature = CryptoHelper.GetHmac256(PusehrAppSecret, authToSign);

            var basePath   = "https://nativepush-cluster1.pusher.com";
            var requestUrl = path + "?" + queryString + "&auth_signature=" + authSignature;
            var request    = new RestRequest(requestUrl);

            request.RequestFormat = DataFormat.Json;
            request.Method        = RestSharp.Method.POST;
            request.AddBody(body);

            var           client   = new RestClient(basePath);
            IRestResponse response = client.Execute(request);

            return(response);
        }
        private IRestResponse <T> GenericRestSharp <T>(string url, string method = null, object data = null) where T : new()
        {
            #region Client

            RestClient rest = null;
            if (url != null)
            {
                rest = new RestClient(url);
            }
            else
            {
                throw new Exception("URL is not defined!");
            }

            #endregion


            #region Request

            RestRequest request = new RestRequest();
            switch (method)
            {
            case "GET":
                request.Method = Method.GET;
                break;

            case "POST":
                request.Method = Method.POST;
                break;

            case "PATCH":
                request.Method = Method.PATCH;
                break;

            case "PUT":
                request.Method = Method.PUT;
                break;

            case "DELETE":
                request.Method = Method.DELETE;
                break;

            default:
                request.Method = Method.GET;
                break;
            }
            ;
            request.JsonSerializer = CustomSerializer.CamelCaseIngoreDictionaryKeys;
            request.RequestFormat  = DataFormat.Json;
            request.AddBody(data);
            if (Headers != null)
            {
                foreach (var item in Headers)
                {
                    if (item.Key == "authentication")
                    {
                        rest.Authenticator = new HttpBasicAuthenticator("username", item.Key);
                    }
                    else if (item.Key == "contentType")
                    {
                        request.AddParameter(new Parameter {
                            ContentType = item.Value
                        });
                    }
                    else
                    {
                        request.AddParameter(new Parameter {
                            Name = item.Key, Value = item.Value
                        });
                    }
                }
            }
            #endregion


            return(rest.Execute <T>(request));
        }
Example #26
0
        public string TestPost()
        {
            var client = new RestClient("http://localhost:5000");
            // client.Authenticator = new HttpBasicAuthenticator(username, password);

            var request = new RestRequest("/api/auth/login", Method.POST);

            request.RequestFormat = DataFormat.Json;

            request.AddBody(new
            {
                userName      = "******",
                passWord      = "******",
                IMEI          = "123456789012345",
                firebaseToken = "abcdefghijklmnopqrstuvwxyz"
            });

            //var jsonOj = new Object { };

            //JsonConvert.SerializeObject(yourobject);

            //request.AddParameter("application/json; charset=utf-8", jsonOj, ParameterType.RequestBody);

            //request.AddParameter("name", "value"); // adds to POST or URL querystring based on Method

            //request.AddUrlSegment("id", "123"); // replaces matching token in request.Resource

            // easily add HTTP Headers
            //request.AddHeader("header", "value");

            // add files to upload (works with compatible verbs)
            //request.AddFile(path);

            request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };

            // execute the request
            IRestResponse response = client.Execute(request);
            var           content  = response.Content; // raw content as string

            // or automatically deserialize result
            // return content type is sniffed but can be explicitly set via RestClient.AddHandler();
            //RestResponse<Person> response2 = client.Execute<Person>(request);
            //var name = response2.Data.Name;

            //// easy async support
            //client.ExecuteAsync(request, response =>
            //{
            //    Console.WriteLine(response.Content);
            //});

            //// async with deserialization
            //var asyncHandle = client.ExecuteAsync<Person>(request, response =>
            //{
            //    Console.WriteLine(response.Data.Name);
            //});

            //// abort the request on demand
            //asyncHandle.Abort();

            return(response.Content);
        }
Example #27
0
        public Issue UpdateIssue(string issueKey, string fieldName, string fieldValue)
        {
            dynamic editMetadata = GetEditMetadata(issueKey);
            dynamic fieldMeta    = editMetadata.fields[fieldName];

            if (fieldMeta == null)
            {
                throw new JiraException("Field metadata is missing", null);
            }

            var type = fieldMeta.schema["type"];

            if (type == null)
            {
                throw new JiraException("Field metadata is missing a type", null);
            }

            var request = new RestRequest
            {
                Method        = Method.PUT,
                Resource      = "issue/{issueIdOrKey}",
                RequestFormat = DataFormat.Json,
            };

            request.AddUrlSegment("issueIdOrKey", issueKey);

            dynamic body;

            if (type.ToString().Equals("array"))
            {
                var custom = fieldMeta.schema["custom"];

                if (custom != null && (custom.ToString().Equals("com.atlassian.jira.plugin.system.customfieldtypes:multiselect")))
                {
                    dynamic operation = new ExpandoObject();
                    ((IDictionary <string, object>)operation).Add(fieldName, new List <dynamic>
                    {
                        new
                        {
                            set = new List <object> {
                                new { value = fieldValue }
                            }
                        }
                    });
                    body = new { update = operation };
                }
                else
                {
                    dynamic operation = new ExpandoObject();
                    ((IDictionary <string, object>)operation).Add(fieldName, new List <dynamic>
                    {
                        new
                        {
                            set = new List <string> {
                                fieldValue
                            }
                        }
                    });
                    body = new { update = operation };
                }
            }
            else
            {
                dynamic field = new ExpandoObject();
                ((IDictionary <string, object>)field).Add(fieldName, fieldValue);
                body = new { fields = field };
            }
            request.AddBody(body);

            var response = client.Execute(request);

            if (response.StatusCode.Equals(HttpStatusCode.NoContent))
            {
                return(GetIssue(issueKey));
            }
            if (response.StatusCode.Equals(HttpStatusCode.Unauthorized))
            {
                throw new JiraLoginException();
            }
            throw new JiraException(response.StatusDescription, new Exception(response.Content));
        }
Example #28
0
        /// <summary>
        /// Provides all logic for constructing a new RestSharp <see cref="RestRequest"/>.
        /// At this point, all information for querying the service is known. Here, it is simply
        /// mapped into the RestSharp request.
        /// </summary>
        /// <param name="method">The http verb.</param>
        /// <param name="path">The target path (or resource).</param>
        /// <param name="options">The additional request options.</param>
        /// <param name="configuration">A per-request configuration object. It is assumed that any merge with
        /// GlobalConfiguration has been done before calling this method.</param>
        /// <returns>[private] A new RestRequest instance.</returns>
        /// <exception cref="ArgumentNullException"></exception>
        private RestRequest newRequest(
            HttpMethod method,
            String path,
            RequestOptions options,
            IReadableConfiguration configuration)
        {
            if (path == null)
            {
                throw new ArgumentNullException("path");
            }
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }
            if (configuration == null)
            {
                throw new ArgumentNullException("configuration");
            }

            RestRequest request = new RestRequest(Method(method))
            {
                Resource       = path,
                JsonSerializer = new CustomJsonCodec(configuration)
            };

            if (options.PathParameters != null)
            {
                foreach (var pathParam in options.PathParameters)
                {
                    request.AddParameter(pathParam.Key, pathParam.Value, ParameterType.UrlSegment);
                }
            }

            if (options.QueryParameters != null)
            {
                foreach (var queryParam in options.QueryParameters)
                {
                    foreach (var value in queryParam.Value)
                    {
                        request.AddQueryParameter(queryParam.Key, value);
                    }
                }
            }

            if (configuration.DefaultHeaders != null)
            {
                foreach (var headerParam in configuration.DefaultHeaders)
                {
                    request.AddHeader(headerParam.Key, headerParam.Value);
                }
            }

            if (options.HeaderParameters != null)
            {
                foreach (var headerParam in options.HeaderParameters)
                {
                    foreach (var value in headerParam.Value)
                    {
                        request.AddHeader(headerParam.Key, value);
                    }
                }
            }

            if (options.FormParameters != null)
            {
                foreach (var formParam in options.FormParameters)
                {
                    request.AddParameter(formParam.Key, formParam.Value);
                }
            }

            if (options.Data != null)
            {
                if (options.HeaderParameters != null)
                {
                    var contentTypes = options.HeaderParameters["Content-Type"];
                    if (contentTypes == null || contentTypes.Any(header => header.Contains("application/json")))
                    {
                        request.RequestFormat = DataFormat.Json;
                    }
                    else
                    {
                        // TODO: Generated client user should add additional handlers. RestSharp only supports XML and JSON, with XML as default.
                    }
                }
                else
                {
                    // Here, we'll assume JSON APIs are more common. XML can be forced by adding produces/consumes to openapi spec explicitly.
                    request.RequestFormat = DataFormat.Json;
                }

                request.AddBody(options.Data);
            }

            if (options.FileParameters != null)
            {
                foreach (var fileParam in options.FileParameters)
                {
                    var bytes      = ClientUtils.ReadAsBytes(fileParam.Value);
                    var fileStream = fileParam.Value as FileStream;
                    if (fileStream != null)
                    {
                        FileParameter.Create(fileParam.Key, bytes, System.IO.Path.GetFileName(fileStream.Name));
                    }
                    else
                    {
                        FileParameter.Create(fileParam.Key, bytes, "no_file_name_provided");
                    }
                }
            }

            if (options.Cookies != null && options.Cookies.Count > 0)
            {
                foreach (var cookie in options.Cookies)
                {
                    request.AddCookie(cookie.Name, cookie.Value);
                }
            }

            return(request);
        }
        public Response <OrderResponse> Post([FromBody] OrderRequest order)
        {
            var result = new Response <OrderResponse>("order/submit", 1);

            result.Downstream = new List <Response>();
            result.Data       = new OrderResponse();

            try
            {
                // Validate Payment
                {
                    var payment = new RestClient("http://payment.default.svc.cluster.local");

                    var request = new RestRequest("/validate", Method.POST);
                    Logger.LogDebug($"Executing {request.Method.ToString()} to {payment.BaseUrl.ToString()} on {request.Resource}");

                    request.RequestFormat = DataFormat.Json;
                    request.AddBody(new { CreditCardNumber = order.Payment });

                    var response = payment.Execute <Response <ValidationResponse> >(request);

                    if (response == null)
                    {
                        throw new Exception("payment validation error [null]");
                    }

                    Logger.LogDebug(response.Content);

                    if (response.StatusCode != HttpStatusCode.OK)
                    {
                        throw new Exception($"payment validation error [{response.StatusCode}]");
                    }

                    if (response != null && response.Data != null && response.Data.Data != null)
                    {
                        result.Downstream.Add(response.Data);
                        result.Data.Status  = response.Data.Data.Status;
                        result.Data.Message = response.Data.Data.Message;
                    }
                }

                if (result.Data.Status)
                {
                    // Validate Address
                    {
                        var address = new RestClient("http://address.default.svc.cluster.local");

                        var request = new RestRequest("/validate", Method.POST);
                        Logger.LogDebug($"Executing {request.Method.ToString()} to {address.BaseUrl.ToString()} on {request.Resource}");
                        request.RequestFormat = DataFormat.Json;
                        request.AddBody(new
                        {
                            Address = "Unit 1, 100 John Street, Sydney",
                            Country = "Australia",
                            Zip     = order.Zip,
                        });

                        var response = address.Execute <Response <ValidationResponse> >(request);

                        if (response == null)
                        {
                            throw new Exception("address validation error [null]");
                        }

                        Logger.LogDebug(response.Content);

                        if (response.StatusCode != HttpStatusCode.OK)
                        {
                            throw new Exception($"address validation error [{response.StatusCode}]");
                        }

                        if (response != null && response.Data != null && response.Data.Data != null)
                        {
                            result.Downstream.Add(response.Data);
                            result.Data.Status  = response.Data.Data.Status;
                            result.Data.Message = response.Data.Data.Message;
                        }
                    }
                }

                if (result.Data.Status)
                {
                    // Fetch Product
                    {
                        var product = new RestClient("http://product.default.svc.cluster.local");
                        var request = new RestRequest($"/products/{order.Product.ToString()}", Method.GET);
                        Logger.LogDebug($"Executing {request.Method.ToString()} to {product.BaseUrl.ToString()} on {request.Resource}");

                        var response = product.Execute <Response <ProductDetail> >(request);

                        if (response == null)
                        {
                            throw new Exception("product read error [null]");
                        }

                        Logger.LogDebug(response.Content);

                        if (response.StatusCode != HttpStatusCode.OK)
                        {
                            throw new Exception($"product read error [{response.StatusCode}]");
                        }

                        result.Data.Total = response.Data.Data.Price * order.Quantity;
                    }
                }
            }
            catch (Exception e)
            {
                result.Data.Status  = false;
                result.Data.Message = e.Message;
                result.Data.Total   = -1;
            }

            return(result);
        }
Example #30
0
        public CreateEnvironmentResponse CreateTargetEnv(string sqlServerName, string sqlServerIp, string serverPassword, string serverUser, string buildNumber, bool wait = false)
        {
            dynamic hostEnvironment = new JObject();

            hostEnvironment.description          = "Generated by MultiRestore: " + buildNumber; //Fix this
            hostEnvironment.logCollectionEnabled = false;
            hostEnvironment.type = "WindowsHostEnvironment";
            hostEnvironment.name = "TARGET - " + sqlServerName;

            dynamic host = new JObject();

            host.address       = sqlServerIp;
            host.connectorPort = 9100;
            host.javaHome      = null;
            host.sshPort       = 22;
            host.type          = "WindowsHost";

            dynamic hostParameters = new JObject();

            hostParameters.type = "WindowsHostCreateParameters";
            hostParameters.host = host;

            dynamic credential = new JObject();

            credential.password = serverPassword;
            credential.type     = "PasswordCredential"; //Fix this

            dynamic primaryUser = new JObject();

            primaryUser.type       = "EnvironmentUser";
            primaryUser.name       = serverUser;
            primaryUser.credential = credential;

            dynamic ProvisionParameters = new JObject();

            ProvisionParameters.hostEnvironment      = hostEnvironment;
            ProvisionParameters.hostParameters       = hostParameters;
            ProvisionParameters.primaryUser          = primaryUser;
            ProvisionParameters.logCollectionEnabled = false;
            ProvisionParameters.type = "HostEnvironmentCreateParameters";



            ProvisionParameters = JsonConvert.SerializeObject(ProvisionParameters);
            var request = new RestRequest("resources/json/delphix/environment", Method.POST);

            request.RequestFormat = DataFormat.Json;
            request.AddBody(ProvisionParameters);

            request.AddHeader("content-header", "application/json");
            request.AddCookie(Session.jSessionId.Name, Session.jSessionId.Value);
            logger.Info(request.ToString());
            try
            {
                var    result = Session.delphixClient.Post(request);
                string dbs    = result.Content;
                Console.WriteLine(ProvisionParameters);
                var response = JsonConvert.DeserializeObject <CreateEnvironmentResponse>(dbs);
                if (response.status.Equals("OK"))
                {
                    var deserializedDbs = response.job.ToString();
                    logger.Info(deserializedDbs);

                    //If we want to wait until the Job is completed...
                    if (wait)
                    {
                        JobService jobHelper    = new JobService();
                        DelphixJob completedJob = jobHelper.GetJobByRefAndWait(deserializedDbs);
                        jobHelper.Dispose();
                        //return completedJob.parentActionState;
                        return(response);
                    }
                    return(response);
                }
                else
                {
                    //This means there was an error actually creating a job to create a target.  Check Request Body + if Delphix was reachable.
                    Console.WriteLine("The status returned from the CreateTargetEnv call was NOT OK");
                    logger.Error("There was an error creating a Job for the CreateTargetEnv call.  The response status was: " + response.status + "Request Body:");
                    logger.Info(ProvisionParameters.ToString());

                    return(response);
                }
            }
            catch (Exception ex)
            {
                logger.Error("There was an error running CreateTargetEnvironments:" + ex);
                logger.Warn("JSON Body: " + ProvisionParameters);

                throw ex;
            }
        }
Example #31
0
        private void btnSubmit_Click(object sender, EventArgs e)
        {
            try
            {
                ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; //use TLS1.2
                var request = new RestRequest("api/transaction/redirect", Method.POST)
                {
                    RequestFormat = DataFormat.Json
                };
                //object built here to be converted to json (what is sent to the web post)
                //This is our line item object build, broken out in a couple differnt objects//
                var identifiersDesc = new List <String>();
                identifiersDesc.Add(txtPaymentIDOne.Text);

                var vtRequestLineItemBody = new vtRequest.LineItem
                {
                    paymentType = txtPaymentType.Text,
                    identifiers = identifiersDesc,
                    amount      = Convert.ToDouble(txtPaymentIDAmount.Text),
                };
                //End line item object build//
                var vtRequestBody = new vtRequest.VT_TRANSACTION
                {
                    CLIENTKEY             = txtClientKey.Text,
                    TRANSACTIONIDENTIFIER = txtTransactionID.Text,
                    AMOUNT    = txtTotalAmount.Text,
                    LINEITEMS = new List <vtRequest.LineItem>()
                    {
                        vtRequestLineItemBody
                    },
                    NAME    = txtName.Text,
                    ADDRESS = txtAddress.Text,
                    CITY    = txtCity.Text,
                    STATE   = txtState.Text,
                    //control not in webform but shown as a way to hardcode values in if needed...
                    ZIP            = "32503",
                    COLLECTIONMODE = "1",
                    CSIUSERID      = "1",
                    URLSILENTPOST  = "",
                    //end control comment//
                    COUNTRY = txtCountry.Text,
                    EMAIL   = txtEmail.Text,
                    PHONE   = txtPhone.Text,
                    NOTES   = txtNotes.Text,
                };
                request.AddBody(vtRequestBody);
                var response = client.Execute(request);
                //here I am assinging the json response back to object format so we can access all the different props like: feeamount, reponsecode, etc
                vtResponse.VT_TRANSACTION vtResponseBody = JsonConvert.DeserializeObject <vtResponse.VT_TRANSACTION>(response.Content);
                txtResponse.Text = vtResponseBody.status.ToString();
                if (vtResponseBody.status == "ok")
                {
                    //the pending payment has been successfully posted, now time to complete the payment with a redirect to magic//
                    //this is the url - "https://stage.collectorsolutions.com/magic-ui/VirtualTerminal/seminole-county/" + vtResponseBody.TRANSACTIONID
                    //create a way to redirect to it however you want...
                }
            }
            catch (Exception)
            {
                //error
            }
        }