Forum Xamarin.Android
We are excited to announce that the Xamarin Forums are moving to the new Microsoft Q&A experience. Q&A is the home for technical questions and answers at across all products at Microsoft now including Xamarin!

We encourage you to head over to Microsoft Q&A for .NET for posting new questions and get involved today.

How to run a web api and xamarin in same solution

Hi I am a novice and using a webapi {asp.net} and xamarin forms project in same solution my question is do I have to run both the projects coz when I run only xamarin project it gives me a null reference exception
Any help would be appreciated
thanks

Tagged:

Best Answer

  • NitishsantpurNitishsantpur Member ✭✭✭
    Accepted Answer
    Thanks for the help seems to be that it was missing an reference of shared project
    Thanks for acknowledging my issue

Answers

  • JarvanJarvan Member, Xamarin Team Xamurai

    To reference the web api, try the following steps:

    • Create a helper class to return the

      public static class Constants
      {
      // URL of REST service
      public static string RestUrl = ...;
      }
      
    • Pass the service URL to process HttpClient get operation

    • Create a model class that contains the data structure of the object received from the service call
    • Create a ViewModel that invokes the service call and receives data.

    You could google with the keyword as Steps to Consume ASP.NET Core Web API in Xamarin Applications or How To Fetch Data Using Web API in Xamarin.Forms to check the related guideline.

  • NitishsantpurNitishsantpur Member ✭✭✭

    Thanks for the reply but I am not using MVVM and I know the process to get the data my doubt is that both my xamarin and API are in the same solution do I have to run both of them because when I run a separate instance of web API it doesn't let me run my emulator

  • JarvanJarvan Member, Xamarin Team Xamurai

    my doubt is that both my xamarin and API are in the same solution do I have to run both of them ...

    No, just select the sample project and the platform to deploy the application.

  • NitishsantpurNitishsantpur Member ✭✭✭

    I mean should it be one or both the projects running simultaneously ?

  • JarvanJarvan Member, Xamarin Team Xamurai

    Only one project will run at the same time. In the above screenshot, the TodoREST project will be deployed on the Android platform. The API will be referenced by the TodoREST project. The API project is just like a library to be referenced, you don't need to run the API project.

  • NitishsantpurNitishsantpur Member ✭✭✭

    Hey thanks for replying and constantly guiding me
    I am facing an issue wherein I get a null reference exception please go through my code once I am using sql server management studio and the add functionality works fine when I try it with postman.
    `//xamarin
    using Iot.Models;
    using Newtonsoft.Json;
    using System.Net.Http;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    using Xamarin.Forms;
    using Xamarin.Forms.Xaml;

    namespace Iot
    {
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class AddLiving : ContentPage
    {
    Response res = new Response();

        public AddLiving()
        {
            InitializeComponent();
    
        }
        private async void Button_Clicked(object sender, EventArgs e)
        {
    
    
    
            try
            {
                var app = new Living()
                {
                    fans = fan.Text,
                    lights = light.Text
                };
              //  await DisplayAlert("Hi",fan.Text,light.Text,"ok");
    
    
    
    
    
    
                    string url = "https://192.168.1.5:80/api/Living/AddUser";
                    HttpClient client = new HttpClient();
                    string jsonData = JsonConvert.SerializeObject(app);
                    StringContent content = new StringContent(jsonData, Encoding.UTF8, "application/json");
                    HttpResponseMessage response = await client.PostAsync(url, content);
                    string result = await response.Content.ReadAsStringAsync();
                    res = JsonConvert.DeserializeObject<Response>(result);
                    if (res.responsestatus==true)
                    {
                        await Navigation.PopToRootAsync();
                    }
                    else
                    {
                      //  await DisplayAlert("Hmm..", "failed insert to in livingroom", "ok");
                    }
    
    
    
    
            }
            catch(Exception ex)
            {
                // await DisplayAlert("err",ex.Message,"ok");
                throw ex.InnerException;
    
    
            }
        }
    }
    

    }
    //controller
    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.Data;
    using System.Data.SqlClient;
    using System.Linq;
    using System.Net;

    using System.Web.Http;
    using WebApi.Models;

    namespace WebApi.Controllers
    {

    public class LivingController : ApiController
    {
        SqlConnection conn;
    
        void Connection()
        {
            string constring = ConfigurationManager.ConnectionStrings["getConnection"].ToString();
            conn = new SqlConnection(constring);
        }       
        public Response AddUser(Living living)
    
        {
            Response response = new Response();
            try
            {
    
                if (string.IsNullOrEmpty(living.fans) || string.IsNullOrEmpty(living.lights))
                {
                    response.Message = "The Field Cannot be empty";
                    response.Responsestatus = false;
    
                }
                else
                {
                    Connection();
                    SqlCommand cmd = new SqlCommand("spAddUsers", conn);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@fans", living.fans);
                    cmd.Parameters.AddWithValue("@lights", living.lights);
    
    
                    conn.Open();
                    int i = cmd.ExecuteNonQuery();
                    conn.Close();
                    if (i >= 0)
                    {
                        response.Message = "Inserted succesfully";
                        response.Responsestatus = true;
                    }
                    else
                    {
                        response.Message = "failed to insert ";
                        response.Responsestatus = false;
                    }
                }
    
            }
            catch(Exception e)
            {
                response.Message = e.Message;
            }
            return response;
        }
    }
    

    }
    `

  • JarvanJarvan Member, Xamarin Team Xamurai

    I am facing an issue where in I get a null reference exception

    Which line code caused the error? Please post the more details about the error log.

  • NitishsantpurNitishsantpur Member ✭✭✭

    It breaks on HttpResponseMessage response = await client.PostAsync(url, content); but api works fine when I use with postman I have the web api and xamarin forms in the same solution
    and have not referenced the web api coz whenever I do that I get this
    Error: The type or namespace name 'App' could not be found (are you missing a using directive or an assembly reference?)
    This is hosted in iis server and using sql server management studio

  • JarvanJarvan Member, Xamarin Team Xamurai
    edited October 28

    The type or namespace name 'App' could not be found (are you missing a using directive or an assembly reference?)

    Which line code caused the error? I couldn't get the 'App' from the posted code.

  • NitishsantpurNitishsantpur Member ✭✭✭

    that is in the main activity

  • NitishsantpurNitishsantpur Member ✭✭✭

    `using System;
    using Android.App;
    using Android.Content.PM;
    using Android.Runtime;
    using Android.Views;
    using Android.Widget;
    using Android.OS;

    namespace Iot.Droid
    {
    [Activity(Label = "Iot", Icon = "@mipmap/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
    public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
    {
    protected override void OnCreate(Bundle savedInstanceState)
    {
    TabLayoutResource = Resource.Layout.Tabbar;
    ToolbarResource = Resource.Layout.Toolbar;

            base.OnCreate(savedInstanceState);
    
            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
            LoadApplication(new App());
        }
        public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
        {
            Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
    
            base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }
    

    }`

  • JarvanJarvan Member, Xamarin Team Xamurai

    Do you mean the LoadApplication(new App()); line code? Did you change the project name of the Android platform? That will delete the reference to the shared project. Please check if the reference is added: Android project -> References -> Add Reference.

  • NitishsantpurNitishsantpur Member ✭✭✭
    Accepted Answer
    Thanks for the help seems to be that it was missing an reference of shared project
    Thanks for acknowledging my issue
Sign In or Register to comment.