Consumin Services on Xamarin Visual Studio

fytofyto CLMember ✭✭

I am with a PCL project in Xamarin, this enters traffic violations ... I have to consume a service for the POST method ... although I try with a try catch, this tells me that the service was consumed ... but Do not make changes in and out (SQL SERVER), please someone can help me?

public partial class NewInfraccionPage : ContentPage
{
private Usuarios usuarios;

    public NewInfraccionPage(Usuarios usuarios)
    {

        InitializeComponent();
        this.usuarios = usuarios;      

        saveButton.Clicked += saveButton_Clicked;
    }

    private async void saveButton_Clicked(object sender, EventArgs e)
    {

        if (string.IsNullOrEmpty(motivoEntry.Text))
        {
            await DisplayAlert("Error", "Debe Ingresar un Motivo de Infraccion", "Aceptar");
            motivoEntry.Focus();
            return;
        }

        if (string.IsNullOrEmpty(patenteEntry.Text))
        {
            await DisplayAlert("Error", "Debe Ingresar una patente", "Aceptar");
            patenteEntry.Focus();
            return;
        }


        if (string.IsNullOrEmpty(lugarEntry.Text))
        {
            await DisplayAlert("Error", "Debe Ingresar un Lugar", "Aceptar");
            lugarEntry.Focus();
            return;
        }


        if (string.IsNullOrEmpty(lugarEntry.Text))
        {
            await DisplayAlert("Error", "Debe Ingresar un Lugar", "Aceptar");
            lugarEntry.Focus();
            return;
        }

        waitActivityIndicator.IsRunning = true;

        var infraccion = new Infraccion
        {               
            //FechaInfraccion = fechaDatePicker.Date,              
            Motivo = motivoEntry.Text,
            PatenteAuto = patenteEntry.Text,
            LugarInfraccion = lugarEntry.Text,
            Observacion = observacionEntry.Text,
            MarcaAuto = marcaEntry.Text,
            ModeloAuto = modeloEntry.Text,
            ColorAuto = colorEntry.Text,
            RutInfractor = rutEntry.Text,                            
        };


        //serializar el objeto infraccion
        var jsonRequest = JsonConvert.SerializeObject(infraccion);

        //codificamos el objeto infraccion y lo guardamos en una variable content
        var content = new StringContent(jsonRequest, Encoding.UTF8, "text/json");

        string result;
        try
        {                
            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri("http://200.27.70.5/web_sit/");
            string url = string.Format("api/InfraccionsAPI/{0}", infraccion.IdInfraccion);
            var response = await client.PostAsync(url, content);
            result = response.Content.ReadAsStringAsync().Result;
        }

        catch (Exception ex)
        {
            await DisplayAlert("Error", "No se encuentra la Conexion", "Aceptar");
            waitActivityIndicator.IsRunning = false;
            return;
        }

        waitActivityIndicator.IsRunning = false;
        await DisplayAlert("Confirmacion", "Infraccion correctamente creada!", "Aceptar");
        await Navigation.PushAsync(new InfraccionPage(usuarios));

    }

}

Best Answers

Answers

  • fytofyto CLMember ✭✭

    Attached my backend api code, the problem is only with the PUT AND POST method (when I pass more than 1 parameter) @nadjib

    public IHttpActionResult PutInfraccion(int id, Infraccion infraccion)
    {
    if (!ModelState.IsValid)
    {
    return BadRequest(ModelState);
    }

            if (id != infraccion.IdInfraccion)
            {
                return BadRequest();
            }
    
            db.Entry(infraccion).State = EntityState.Modified;
    
            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!InfraccionExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }
    
            return StatusCode(HttpStatusCode.NoContent);
        }
    
        // POST: api/InfraccionsAPI
        [ResponseType(typeof(Infraccion))]
        public IHttpActionResult PostInfraccion(Infraccion infraccion)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
    
            db.Infraccion.Add(infraccion);
            db.SaveChanges();
    
            return CreatedAtRoute("DefaultApi", new { id = infraccion.IdInfraccion }, infraccion);
        }
    
  • Amar_BaitAmar_Bait DZMember ✭✭✭✭✭

    I see that you're POSTing with a parameter, Shouldn't POST have no Id parameter because it's a new record? PUT should have the Id parameter though.

  • Amar_BaitAmar_Bait DZMember ✭✭✭✭✭
    edited April 2017

    Also

    result = await response.Content.ReadAsStringAsync(); // Don't use .Result, await it instead
    
  • fytofyto CLMember ✭✭

    How would I modify my post method in the backend? @nadjib

  • fytofyto CLMember ✭✭

    Modify the parameter and continue without inserting data in my DB even though it gives a "SUCCESS" message, will not my WEB API code BACKEND POST have something wrong?
    Your help is important to me Nadjid @nadjib
    The infractions are not mine clearly lol :)

  • Amar_BaitAmar_Bait DZMember ✭✭✭✭✭
    edited April 2017

    I don't see anywhere in your backend POST code something that returns "SUCCESS". It should return a URL for the new created infraccion (lol), along with the new record in json (or XML more likely, because you're not specifying an accept:application/json header). Can you show me the response result? Also make sure your db is not erased each time you start the web app (check in global.asx or Startup.cs)

    Also, the correct mime type for json is "application/json" not "text/json".

    var content = new StringContent(jsonRequest, Encoding.UTF8, "application/json");
    
  • fytofyto CLMember ✭✭

    I was referring to the message "success" of my app in xamarin ... the BD is not deleted, since within the app I can consult the different infractions ... The problem is only with the method PUT AND POST .... Is it ok my Backend API? .... I attach my code WebAPIConfig.cs for verification

    // Web API routes
    config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}/{param2}",
                defaults: new { id = RouteParameter.Optional, param2 = RouteParameter.Optional }
    
  • Amar_BaitAmar_Bait DZMember ✭✭✭✭✭
    edited April 2017

    What is param2 used for? why did you add it?
    Anyway I can't help you further without you showing me the content of the response result:

    result = response.Content.ReadAsStringAsync().Result; // what does this return?
    
  • fytofyto CLMember ✭✭

    Param2, add it because my app contains a users login, which receives two parameters ... a user and a password .... these parameters are optional anyway ...

    result = response.Content.ReadAsStringAsync().Result;

    The previous line of code I think this other, when doing a breakpoint never happens there, is there any possibility of sending you my project? This does not let me sleep, my brother !!
    Anyway thanks for your help

  • Amar_BaitAmar_Bait DZMember ✭✭✭✭✭

    So... basically, you're sending username and passwords... as URL parameters... just wow.

    Try to debug your code line by line, sorry can't help you more without knowing what's happening. You can also try to call the API directly using a Rest client (like Postman), like that you can see the response, and see if it's a backend or app problem.

    Sorry but I don't have time to run your code, my wife is mad at me and I need to convince her to forgive me.

Sign In or Register to comment.