在'app4.MainActivity'类型上找不到'id'成员将Xamarin.Android连接到Azure

时间:2017-06-22 23:46:37

标签: android visual-studio azure xamarin xamarin.android

我只是尝试将数据插入到azure平台。但是那个问题发生了。 在'app4.MainActivity'类型上找不到'id'成员我使用了一个断点来检查问题,它转到了“JObject jo = new JObject();或下一行(现在断点不起作用)的捕获线” “

 using Android.App;
    using Android.Widget;
    using Android.OS;
    using Microsoft.WindowsAzure.MobileServices;
    using Android.Views;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Linq;
    using System;

    namespace App4
    {
    [Activity(Label = "App4", MainLauncher = true, Icon = "@drawable/icon")]

    public class MainActivity : Activity
    {


        public TextView txtShow;
        public EditText txtEnter;
        public Button btnSave;



       // string id;
       [JsonProperty(PropertyName = "id")]
        public string Id
        {
            get { return Id; }
            set { Id = value; }
        }

        [JsonProperty(PropertyName = "Questions")]
        public string Questions { get; set; }

       /* [JsonProperty(PropertyName = "complete")]
        public bool Complete { get; set; }*/


        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            SetContentView(Resource.Layout.Main);

            Button btnSave = FindViewById<Button>(Resource.Id.btnSave);


            TextView txtShow = FindViewById<TextView>(Resource.Id.txtSoru);
            EditText txtEnter = FindViewById<EditText>(Resource.Id.txtSoruGir);

            Microsoft.WindowsAzure.MobileServices.CurrentPlatform.Init();
            SQLitePCL.Batteries.Init();

            // IMobileServiceTable<MainActivity> SurveyTable = client.GetTable<MainActivity>();




            // Initialization for Azure Mobile Apps
            Microsoft.WindowsAzure.MobileServices.CurrentPlatform.Init();
            // This MobileServiceClient has been configured to communicate with the Azure Mobile App and
            // Azure Gateway using the application url. You're all set to start working with your Mobile App!
            Microsoft.WindowsAzure.MobileServices.MobileServiceClient TrendDemoClient = new Microsoft.WindowsAzure.MobileServices.MobileServiceClient(
            "http://xxxx.azurewebsites.net");

            // Set our view from the "main" layout resource
            // SetContentView (Resource.Layout.Main);

        }

        // It is save button. ( or insert button)using on xml 
       // using via   android:onClick="AddItem"
        [Java.Interop.Export()]
        public async void AddItem(View view)
        {
            var client = new MobileServiceClient("http://*****.azurewebsites.net/");
            IMobileServiceTable SurveyTable = client.GetTable("Survey");
            var table = client.GetSyncTable<MainActivity>();
            txtEnter.Text = txtShow.Text;
            string txt;
            txt = txtShow.Text;

            var item = new MainActivity
            {
                Questions = txtShow.Text,


            };

                  Questions = txt;

            try
            {

////the problem occur over here and goes to catch
                JObject jo = new JObject();
                jo.Add("id", "myemail@emaildomain.com");
                jo.Add("Questions", "Hello World");
               // jo.Add("Complete", false);
            ////  It does't come so far
                var inserted = await table.InsertAsync(jo);


                // var inserted = await table.InsertAsync(Questions);



            }
            catch (Exception e)
            {
                CreateAndShowDialog(e, "Amk Necosu");
            }



        }

        private void CreateAndShowDialog(Exception exception, String title)
        {
            CreateAndShowDialog(exception.Message, title);
        }

        private void CreateAndShowDialog(string message, string title)
        {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);

            builder.SetMessage(message);
            builder.SetTitle(title);
            builder.Create().Show();
        }
    }
    }

后端部分在这里 Backend Part is here

Controller.cs

using System.Linq;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.OData;
using Microsoft.Azure.Mobile.Server;
using TrendDemoService.DataObjects;
using TrendDemoService.Models;
using Microsoft.Azure.Mobile.Server.Config;

namespace TrendDemoService.Controllers
{
    [MobileAppController]
    public class Controller : TableController<MyFirstDbTableModel>
    {
        protected override void Initialize(HttpControllerContext controllerContext)
        {
            base.Initialize(controllerContext);
            Context context = new Context();
            DomainManager = new EntityDomainManager<MyFirstDbTableModel>(context, Request);
        }

        // GET tables/TodoItem
        public IQueryable<MyFirstDbTableModel> GetAllMyFirstDbTableModels()
        {
            return Query();
        }

        // GET tables/TodoItem/48D68C86-6EA6-4C25-AA33-223FC9A27959
        public SingleResult<MyFirstDbTableModel> GetMyFirstDbTableModel(string id)
        {
            return Lookup(id);
        }

        // PATCH tables/TodoItem/48D68C86-6EA6-4C25-AA33-223FC9A27959
        public Task<MyFirstDbTableModel> PatchMyFirstDbTableModel(string id, Delta<MyFirstDbTableModel> patch)
        {
            return UpdateAsync(id, patch);
        }

        // POST tables/TodoItem
        public async Task<IHttpActionResult> PostMyFirstDbTableModel(MyFirstDbTableModel item)
        {
            MyFirstDbTableModel current = await InsertAsync(item);
            return CreatedAtRoute("Tables", new { id = current.Id }, current);
        }

        // DELETE tables/TodoItem/48D68C86-6EA6-4C25-AA33-223FC9A27959
        public Task DeleteTodoItem(string id)
        {
            return DeleteAsync(id);
        }
    }
}

Context.cs

using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Linq;
using Microsoft.Azure.Mobile.Server;
using Microsoft.Azure.Mobile.Server.Tables;
using TrendDemoService.DataObjects;

namespace TrendDemoService.Models
{
    public class Context : DbContext
    {
        // You can add custom code to this file. Changes will not be overwritten.
        // 
        // If you want Entity Framework to alter your database
        // automatically whenever you change your model schema, please use data migrations.
        // For more information refer to the documentation:
        // http://msdn.microsoft.com/en-us/data/jj591621.aspx

        private const string connectionStringName = "Name=MS_TableConnectionString";

        public Context() : base(connectionStringName)
        {
        }

        public DbSet<MyFirstDbTableModel> MyFirstDbTableModel { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Add(
                new AttributeToColumnAnnotationConvention<TableColumnAttribute, string>(
                    "ServiceTableColumn", (property, attributes) => attributes.Single().ColumnType.ToString()));
        }
    }

}

MyFirstDbTableModel     使用Microsoft.Azure.Mobile.Server;

namespace TrendDemoService.DataObjects
{
    public class MyFirstDbTableModel : EntityData
    {

        public string Questions { get; set; }

        public bool Complete { get; set; }
    }
}

编辑后

Startup.MobileApp

Backend Part
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.Entity;
using System.Web.Http;
using Microsoft.Azure.Mobile.Server;
using Microsoft.Azure.Mobile.Server.Authentication;
using Microsoft.Azure.Mobile.Server.Config;
using TrendDemoService.DataObjects;
using TrendDemoService.Models;
using Owin;

namespace TrendDemoService
{
    public partial class Startup
    {
        public static void ConfigureMobileApp(IAppBuilder app)
        {
            HttpConfiguration config = new HttpConfiguration();

            //For more information on Web API tracing, see http://go.microsoft.com/fwlink/?LinkId=620686 
            config.EnableSystemDiagnosticsTracing();

            new MobileAppConfiguration()
                .UseDefaultConfiguration()
                .ApplyTo(config);

            // Use Entity Framework Code First to create database tables based on your DbContext
            Database.SetInitializer(new TrendDemoInitializer());

            // To prevent Entity Framework from modifying your database schema, use a null database initializer
            // Database.SetInitializer<TrendDemoContext>(null);

            MobileAppSettingsDictionary settings = config.GetMobileAppSettingsProvider().GetMobileAppSettings();

            if (string.IsNullOrEmpty(settings.HostName))
            {
                // This middleware is intended to be used locally for debugging. By default, HostName will
                // only have a value when running in an App Service application.
                app.UseAppServiceAuthentication(new AppServiceAuthenticationOptions
                {
                    SigningKey = ConfigurationManager.AppSettings["SigningKey"],
                    ValidAudiences = new[] { ConfigurationManager.AppSettings["ValidAudience"] },
                    ValidIssuers = new[] { ConfigurationManager.AppSettings["ValidIssuer"] },
                    TokenHandler = config.GetAppServiceTokenHandler()
                });
            }
            app.UseWebApi(config);
        }
    }

    public class TrendDemoInitializer : CreateDatabaseIfNotExists<Context>
    {
        protected override void Seed(Context context)
        {
            List<MyFirstDbTableModel> todoItems = new List<MyFirstDbTableModel>
            {
                new MyFirstDbTableModel { Id = Guid.NewGuid().ToString(), Questions = "First item", Complete = false },
                new MyFirstDbTableModel { Id = Guid.NewGuid().ToString(), Questions = "Second item", Complete = false },
            };

            foreach (MyFirstDbTableModel todoItem in todoItems)
            {
                context.Set<MyFirstDbTableModel>().Add(todoItem);
            }

            base.Seed(context);
        }
    }
}

前端

MainActivity

using Android.App;
using Android.Widget;
using Android.OS;
using Microsoft.WindowsAzure.MobileServices;
using Android.Views;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Runtime.Serialization;



namespace App4
{
    [Activity(Label = "App4", MainLauncher = true, Icon = "@drawable/icon")]

    public class MainActivity : Activity
    {


        public TextView txtShow;
        public EditText txtEnter;
        public Button btnSave;










        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            SetContentView(Resource.Layout.Main);

            Button btnSave = FindViewById<Button>(Resource.Id.btnSave);


            TextView txtShow = FindViewById<TextView>(Resource.Id.txtSoru);
            EditText txtEnter = FindViewById<EditText>(Resource.Id.txtSoruGir);

            Microsoft.WindowsAzure.MobileServices.CurrentPlatform.Init();
            SQLitePCL.Batteries.Init();

            // IMobileServiceTable<MainActivity> SurveyTable = client.GetTable<MainActivity>();




            // Initialization for Azure Mobile Apps
            Microsoft.WindowsAzure.MobileServices.CurrentPlatform.Init();
            // This MobileServiceClient has been configured to communicate with the Azure Mobile App and
            // Azure Gateway using the application url. You're all set to start working with your Mobile App!
            Microsoft.WindowsAzure.MobileServices.MobileServiceClient TrendDemoClient = new Microsoft.WindowsAzure.MobileServices.MobileServiceClient(
            "http://******.azurewebsites.net");

            // Set our view from the "main" layout resource
            // SetContentView (Resource.Layout.Main);

        }


);




        [Java.Interop.Export()]
        public async void AddItem(View view)
        {
              var client = new MobileServiceClient("http://xx.azurewebsites.net/");
            // IMobileServiceTable SurveyTable = client.GetTable("Survey");
            var table = client.GetSyncTable<MyFirstDbTableModel>();





            var myFirstModelInstance = new MyFirstDbTableModel();

            myFirstModelInstance.Id = Guid.NewGuid().ToString();
            myFirstModelInstance.Questions = "Could I help you with this answer?";
            myFirstModelInstance.Complete = false;



            try
            {






                await table.InsertAsync(myFirstModelInstance);

            }




            catch (Exception e)
            {
              CreateAndShowDialog(e, "Error");

            }



        }

        private void CreateAndShowDialog(Exception exception, String title)
        {
            CreateAndShowDialog(exception.Message, title);
        }

        private void CreateAndShowDialog(string message, string title)
        {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);

            builder.SetMessage(message);
            builder.SetTitle(title);
            builder.Create().Show();
        }
    }
}

MyFirstDbTableModel类

using Newtonsoft.Json;

namespace App4
{
    public class MyFirstDbTableModel
    {
        // string id;
        public string Id { get; set; }

        public string Questions { get; set; }

        public bool Complete { get; set; }
    }

}

enter image description here

错误消息已更改。

错误 -Synccontext尚未初始化

输出(当我按下按钮时)

06-28 14:20:48.971 D/ViewRootImpl@16dc384[MainActivity]( 4390): ViewPostImeInputStage processPointer 0
06-28 14:20:49.025 D/ViewRootImpl@16dc384[MainActivity]( 4390): ViewPostImeInputStage processPointer 1
06-28 14:20:49.075 D/ViewRootImpl@5067e47[MainActivity]( 4390): ThreadedRenderer.create() translucent=true
06-28 14:20:49.079 D/InputTransport( 4390): Input channel constructed: fd=74
06-28 14:20:49.079 D/ViewRootImpl@5067e47[MainActivity]( 4390): setView = DecorView@279674[MainActivity] touchMode=true
06-28 14:20:49.081 D/ViewRootImpl@5067e47[MainActivity]( 4390): dispatchAttachedToWindow
06-28 14:20:49.093 D/ViewRootImpl@5067e47[MainActivity]( 4390): Relayout returned: oldFrame=[0,0][0,0] newFrame=[36,1062][1404,1593] result=0x27 surface={isValid=true 504091385344} surfaceGenerationChanged=true
06-28 14:20:49.094 D/ViewRootImpl@5067e47[MainActivity]( 4390): mHardwareRenderer.initialize() mSurface={isValid=true 504091385344} hwInitialized=true
06-28 14:20:49.099 D/mali_winsys( 4390): EGLint new_window_surface(egl_winsys_display*, void*, EGLSurface, EGLConfig, egl_winsys_surface**, egl_color_buffer_format*, EGLBoolean) returns 0x3000,  [1624x787]-format:1
06-28 14:20:49.099 D/ScrollView( 4390):  onsize change changed 
06-28 14:20:49.110 D/ViewRootImpl@5067e47[MainActivity]( 4390): MSG_WINDOW_FOCUS_CHANGED 1
06-28 14:20:49.110 D/ViewRootImpl@5067e47[MainActivity]( 4390): mHardwareRenderer.initializeIfNeeded()#2 mSurface={isValid=true 504091385344}
06-28 14:20:49.124 D/ViewRootImpl@5067e47[MainActivity]( 4390): MSG_RESIZED_REPORT: ci=Rect(0, 0 - 0, 0) vi=Rect(0, 0 - 0, 0) or=1
06-28 14:20:49.141 D/ViewRootImpl@16dc384[MainActivity]( 4390): MSG_WINDOW_FOCUS_CHANGED 0
06-28 14:20:49.142 D/SEM_CLIP_SemClipboardManager( 4390): isCocktailBarDisplayed : false

2 个答案:

答案 0 :(得分:1)

您将MainActivity用作数据库模型。你不应该这样做。

你应该做什么:

  1. 创建数据库表模型:

    public class MyFirstDbTableModel
    {
       // string id;
       public string Id { get; set; }
    
       public string Questions { get; set; }
    
       public bool Complete { get; set; }
    }
    
  2. 获取如下表格:

    var table = client.GetTable<MyFirstDbTableModel>();
    
  3. 创建数据库表模型的实例并添加值:

    var myFirstModelInstance = new MyFirstDbTableModel();
    myFirstModelInstance.Id = Guid.NewGuid().ToString();
    myFirstModelInstance.Questions = "Could I help you with this answer?";
    myFirstModelInstance.Complete = false;
    
  4. 将实例放入Azure中的数据库:

    var inserted = await table.InsertAsync(myFirstModelInstance);
    
  5. 注意:您必须从后端或直接在数据库中创建数据库表。您可以直接在后端使用“MyFirstDbTableModel”模型,但它必须继承自

      

    public class MyFirstDbTableModel:EntityData {...}

    并且你必须做更多的事情,比如创建一个控制器,这在Azure文档中有描述,或者你可以在Azure移动应用程序快速入门示例中看到它。

    根据问题的修改进行更新:

    您应该将类​​名从“Controller”更改为“MyFirstDbTableModelController”。控制器的名称反映在请求链接中。

    您应该使用SSMS(SQL Server Management Studio)连接到数据库。使用此程序,您可以看到表是否已创建。注意:只有在向后端发送请求后才会创建表。

    您不在模型中使用属性,因此,我已删除了步骤3中的属性。

    您是否更改了Startup.MobileApp.cs中的初始化程序?

    如果您在我的回答中使用代码,它应该与我的更新中的更改一起使用。

    如果您遇到异常,请发布堆栈跟踪。此外,您还可以调试后端以获取堆栈跟踪。

    注意:如果更改模型,例如MyFirstDbTableModel,则数据库不会再次创建表。您必须删除数据库中的所有表。

答案 1 :(得分:0)

这部分错了:

    [JsonProperty(PropertyName = "id")]
    public string Id
    {
        get { return Id; }
        set { Id = value; }
    }

您正在返回Id,它依次返回Id,因此它是一个递归调用。它无法工作。

我同意Sean的说法,这不是将数据添加到Azure的最佳做法。