I created a new table "TravauxDBs" using Visual Studio, but when i call PullAsync it returns count = 0, so i guess it's empty. Then i get an error "not found".
Everything works fine using basic table ToDoItems, and i use the same code for this new table.
My item mobile side :
public class TravauxDB
{
public string Id { get; set; }
[JsonProperty(PropertyName = "nomtravail")]
public string NomTravail { get; set; }
[JsonProperty(PropertyName = "voie")]
public string Voie { get; set; }
[JsonProperty(PropertyName = "pk")]
public string PK { get; set; }
[JsonProperty(PropertyName = "quantity")]
public string Quantity { get; set; }
[JsonProperty(PropertyName = "unite")]
public string Unite { get; set; }
[JsonProperty(PropertyName = "observation")]
public string Observation { get; set; }
[JsonProperty(PropertyName = "idchantier")]
public string IdChantier { get; set; }
}
Service side :
public class TravauxDB : EntityData
{
public string NomTravail { get; set; }
public string Voie { get; set; }
public string PK { get; set; }
public string Quantity { get; set; }
public string Unite { get; set; }
public string Observation { get; set; }
public string IdChantier { get; set; }
}
Activity :
public class Travaux : ActionBarActivity
{
private Android.Support.V7.Widget.SearchView _searchView3;
private ListView _listView3;
private ArrayAdapter _adapter3;
private MobileServiceClient client;
private IMobileServiceSyncTable<TravauxDB> TravauxTable;
const string applicationURL = #"myurl";
const string applicationKey = #"mykey";
const string localDbFilename = "localstore.db";
public List<string> travaux { get; private set; }
protected override async void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.Layout_travaux);
CurrentPlatform.Init();
client = new MobileServiceClient(applicationURL, applicationKey);
await InitLocalStoreAsync();
TravauxTable = client.GetSyncTable<TravauxDB>();
await SyncAsync();
List<string> travaux = await ItemsOnly();
_listView3 = FindViewById<ListView>(Resource.Id.listView3);
_adapter3 = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItem1, travaux);
_listView3.Adapter = _adapter3;
_listView3.ItemClick += _listView3_ItemClick;
}
void _listView3_ItemClick(object sender, AdapterView.ItemClickEventArgs e)
{
int pos = e.Position;
Intent b = new Intent(this, typeof(Travail));
Bundle bundle = new Bundle();
bundle.PutInt("Ntravail", pos);
b.PutExtras(bundle);
StartActivity(b);
}
public override bool OnCreateOptionsMenu(IMenu menu)
{
MenuInflater.Inflate(Resource.Menu.main, menu);
var item = menu.FindItem(Resource.Id.action_search);
var searchItem = MenuItemCompat.GetActionView(item);
_searchView3 = searchItem.JavaCast<Android.Support.V7.Widget.SearchView>();
_searchView3.QueryTextChange += (s, e) => _adapter3.Filter.InvokeFilter(e.NewText);
_searchView3.QueryTextSubmit += (s, e) =>
{
Toast.MakeText(this, "Searched for: " + e.Query, ToastLength.Short).Show();
e.Handled = true;
};
return true;
}
private void CreateAndShowDialog(Exception exception, String title)
{
CreateAndShowDialog(exception.Message, title);
}
private void CreateAndShowDialog(string message, string title)
{
Android.App.AlertDialog.Builder builder = new Android.App.AlertDialog.Builder(this);
builder.SetMessage(message);
builder.SetTitle(title);
builder.Create().Show();
}
private async Task InitLocalStoreAsync()
{
string path = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), localDbFilename);
if (!File.Exists(path))
{
File.Create(path).Dispose();
}
var store = new MobileServiceSQLiteStore(path);
store.DefineTable<TravauxDB>();
await client.SyncContext.InitializeAsync(store);
}
private async Task SyncAsync()
{
try
{
await client.SyncContext.PushAsync();
await TravauxTable.PullAsync("alltravaux", TravauxTable.CreateQuery()); // query ID is used for incremental sync
}
catch (Java.Net.MalformedURLException)
{
CreateAndShowDialog(new Exception("There was an error creating the Mobile Service. Verify the URL"), "Error");
}
catch (Exception e)
{
CreateAndShowDialog(e, "Error");
}
}
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
AuthenticationAgentContinuationHelper.SetAuthenticationAgentContinuationEventArgs(requestCode, resultCode, data);
}
public async Task<List<string>> ItemsOnly()
{
try
{
List<string> travaux = await TravauxTable
.Select(tr => tr.NomTravail).ToListAsync();
return travaux;
}
catch (MobileServiceInvalidOperationException e)
{
Console.Error.WriteLine(#"ERROR {0}", e.Message);
return null;
}
}
I also added a new controller for this, just replaced ToDoItem by TravauxDB :
public class TravauxController : TableController<TravauxDB>
{
protected override void Initialize(HttpControllerContext controllerContext)
{
base.Initialize(controllerContext);
ChantierContext context = new ChantierContext();
DomainManager = new EntityDomainManager<TravauxDB>(context, Request, Services);
}
// GET tables/TodoItem
public IQueryable<TravauxDB> GetAllTravauxDB()
{
return Query();
}
// GET tables/TodoItem/48D68C86-6EA6-4C25-AA33-223FC9A27959
public SingleResult<TravauxDB> GetTravauxDB(string id)
{
return Lookup(id);
}
// PATCH tables/TodoItem/48D68C86-6EA6-4C25-AA33-223FC9A27959
public Task<TravauxDB> PatchTravauxDB(string id, Delta<TravauxDB> patch)
{
return UpdateAsync(id, patch);
}
// POST tables/TodoItem
public async Task<IHttpActionResult> PostTravauxDB(TravauxDB item)
{
TravauxDB current = await InsertAsync(item);
return CreatedAtRoute("Tables", new { id = current.Id }, current);
}
// DELETE tables/TodoItem/48D68C86-6EA6-4C25-AA33-223FC9A27959
public Task DeleteTravauxDB(string id)
{
return DeleteAsync(id);
}
}
If something is missing or you need more details let me know.
Thank you by advance.
The client class name needs to match the server controller name. So, your class should be called Travaux instead of TravauxDB. Alternatively, you can use the attribute [TableName] on the class.
Related
I am new to Blazor and I am encountering the following issue when trying to post for data with an authentication token : at the time of the API call, an exception is lifted with the message "The JSON value could not be converted to System.Int32. Path: $ | LineNumber: 0 | BytePositionInLine: 1."
Here's the code in my blazor page's code-behind :
public partial class ContactCreate : AuthenticatedPageBase
{
[Inject]
public IContactDataService ContactDataService { get; set; }
[Inject]
public ICountryDataService CountryDataService { get; set; }
public Contact.Post Model { get; set; } = new Contact.Post();
protected string CountryIdString { get; set; } = string.Empty;
protected string TokenString { get; set; } = string.Empty;
public string ErrorMessage { get; set; } = string.Empty;
protected List<Country.ListItem> Countries { get; set; } = new List<Country.ListItem>();
protected async override Task OnInitializedAsync()
{
await base.OnInitializedAsync();
Countries = (await CountryDataService.GetCountryListAsync(Token.Token)).ToList();
TokenString = Token.Token;
}
protected async Task HandleValidSubmit()
{
try
{
Model.CountryId = int.Parse(CountryIdString);
var response = await ContactDataService.PostContactAsync(TokenString, Model);
NavManager.NavigateTo("/contacts");
}
catch(Exception ex)
{
ErrorMessage = ex.Message;
}
}
protected void HandleInvalidSubmit()
{
ErrorMessage = "Le formulaire n'est pas valide. Veuillez réessayer.";
}
}
and here's the relevant code in the data service :
public async Task<int> PostContactAsync(string token, Contact.Post model)
{
var response = await PostAuthenticatedAsync<int>(token, Url, model);
return response;
}
public async Task<T> PostAuthenticatedAsync<T>(string token, string url, object model)
{
var jsonBody = model.ToJson();
var request = new HttpRequestMessage()
{
RequestUri = new Uri(HttpClient.BaseAddress.ToString() + url),
Method = HttpMethod.Post,
Content = jsonBody
};
request.Headers.Authorization = new AuthenticationHeaderValue("bearer", token);
var response = await HttpClient.SendAsync(request);
return await response.FromJson<T>(Options);
}
...and the extension method that serializes the object into json :
public static StringContent ToJson(this object o)
{
return new StringContent(JsonSerializer.Serialize(o), Encoding.UTF8, "application/json");
}
Here's the object model that I'm passing through :
public class Contact
{
public class Post
{
[MaxLength(50)]
public string FirstName { get; set; }
[MaxLength(50)]
public string LastName { get; set; }
[MaxLength(50)]
public string CompanyName { get; set; }
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
[MaxLength(20)]
public string PostCode { get; set; }
[MaxLength(60)]
public string Locality { get; set; }
public int CountryId { get; set; }
}
}
And, finally, here's the API method that I'm trying to reach :
[HttpPost]
public async Task<ActionResult> PostContact(Contact.Post model)
{
try
{
var createdId = await _contactRepository.CreateAsync(model);
return Ok(new { Id = createdId });
}
catch (Exception ex)
{
return BadRequest(new { ex.Message });
}
}
Any idea what is happening or what actual exception lies behind this cryptic error message ?
P.S. : I know that there is a question with that exact exception message but it concerns .NET Core while I'm targeting .NET Standard 2.1. I've read it and it visibly doesn't apply to this case.
You are not returning an int (the Id). You're returning an anonymous object with an int property named Id.
Try
return Ok(createdId);
I am using EF Core 2.2.2 in my project, and I am getting this error when trying to fetch any data from DB, I am not sure what is the reason of this, but it works fine when trying to insert new item to DB:
Error Message :
"A column has been specified more than once in the order by list.
Columns in the order by list must be unique"
I think the issue happened because of using nested OwnsMany many times but not sure:
public class Program
{
private static void Main(string[] args)
{
using(var context = new OwnsManyIssueContext())
{
var accidentEstimationDetails = new List<AccidentEstimationDetails>
{
new AccidentEstimationDetails(true, "test1"),
new AccidentEstimationDetails(false, "test2"),
new AccidentEstimationDetails(true, "test3")
};
var accidentEstimation = new AccidentEstimation(12, 11, accidentEstimationDetails);
var partiesLiabilityAmounts = new List<PartyAmountDetails>
{
new PartyAmountDetails(1,11,120),
new PartyAmountDetails(1,12,121),
new PartyAmountDetails(1,10,122)
};
var accident = new Accident(accidentEstimation, partiesLiabilityAmounts);
context.Accidents.Add(accident);
context.SaveChanges();
var dbAggregate = context.Accidents.FirstOrDefault();
}
}
}
public class Accident
{
public int Id { get; private set; }
public AccidentEstimation AccidentEstimation { get; private set; }
private List<PartyAmountDetails> _partiesAmountDetails;
public IReadOnlyCollection<PartyAmountDetails> PartiesAmountDetails => _partiesAmountDetails;
private Accident()
{
_partiesAmountDetails = new List<PartyAmountDetails>();
}
public Accident(AccidentEstimation accidentEstimation, List<PartyAmountDetails> partiesLiabilityAmount)
{
AccidentEstimation = accidentEstimation;
_partiesAmountDetails = partiesLiabilityAmount;
}
}
public class AccidentEstimation
{
public int EstimationPartyId { get; private set; }
public int FollowerId { get; private set; }
private readonly List<AccidentEstimationDetails> _details;
public IReadOnlyCollection<AccidentEstimationDetails> Details => _details;
private AccidentEstimation()
{
_details = new List<AccidentEstimationDetails>();
}
public AccidentEstimation(int estimationPartyId, int followerId, List<AccidentEstimationDetails> details)
{
EstimationPartyId = estimationPartyId;
FollowerId = followerId;
_details = details;
}
}
public class AccidentEstimationDetails
{
public bool IsApproved { get; private set; }
public string Name { get; private set; }
private AccidentEstimationDetails()
{
}
public AccidentEstimationDetails(bool isApproved, string name)
{
IsApproved = isApproved;
Name = name;
}
}
public class PartyAmountDetails
{
public int ItemTypeId { get; private set; }
public decimal Amount { get; private set; }
public decimal? Discount { get; private set; }
private PartyAmountDetails()
{
}
public PartyAmountDetails(int itemTypeId, decimal amount, decimal? discount)
{
ItemTypeId = itemTypeId;
Amount = amount;
Discount = discount;
}
}
public class AccidentTypeConfiguration : IEntityTypeConfiguration<Accident>
{
public void Configure(EntityTypeBuilder<Accident> builder)
{
builder.ToTable("Accidents");
builder.Property(b => b.Id).ValueGeneratedOnAdd(); ;
builder.HasKey(b => b.Id);
builder.OwnsOne(a => a.AccidentEstimation, a =>
{
a.Property(p => p.FollowerId).HasColumnName("FollowerId");
a.Property(p => p.EstimationPartyId).HasColumnName("EstimationPartyId");
a.OwnsMany(dd => dd.Details, dd =>
{
dd.ToTable("AccidentEstimationDetails");
dd.Property<int>("Id");
dd.HasKey("Id");
});
});
builder.OwnsMany(a => a.PartiesAmountDetails, a =>
{
a.ToTable("PartiesLiabilityAmounts");
a.Property<long>("Id");
a.HasKey("Id");
});
}
}
public class OwnsManyIssueContext : DbContext
{
public DbSet<Accident> Accidents { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(#"ConnectionString");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.ApplyConfiguration(new AccidentTypeConfiguration());
base.OnModelCreating(modelBuilder);
}
}
I have used custom InputFormatters for creating a subset of request from the generic request that request body receives in API request.
var reqModel = new XmlSerializer(CurrentType).Deserialize(xmlDoc.CreateReader());
SubSetRequest model = ConvertToSubSetRequestObject(reqModel as BigRequest);
return InputFormatterResult.Success(model);
Now in controller ModelState.IsValid is not pointing to SubSetRequest but to BigRequest, which I have received request body
public ActionResult<object> Calculate(SubSetRequest request)
{
if (!ModelState.IsValid){ }
// other codes..
}
Any idea how can we validate ModelState against SubSetRequest type.
Important Classes :
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddMvcCore(options =>
{
options.OutputFormatters.Add(new XmlSerializerOutputFormatter());
options.InputFormatters.Insert(0, new XMLDocumentInputFormatter());
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
.AddXmlSerializerFormatters()
.AddXmlDataContractSerializerFormatters();
}
BigRequest.cs
[System.SerializableAttribute()]
public class BigRequest
{
public string Name { get; set; }
public string Email { get; set; }
public string Address { get; set; }
public string Company { get; set; }
public string Designation { get; set; }
public string CompanyAddress { get; set; }
}
SubSetRequest.cs
[System.SerializableAttribute()]
public class SubSetRequest
{
public string Name { get; set; }
[Required] //This should tiger **Validation** error
public string Email { get; set; }
public string Address { get; set; }
}
XMLDocumentInputFormatter.cs
internal class XMLDocumentInputFormatter : InputFormatter
{
private Type CurrentType { get; set; }
public XMLDocumentInputFormatter()
{
SupportedMediaTypes.Add("application/xml");
}
public override async Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context)
{
using (var streamReader = new StreamReader(context.HttpContext.Request.Body))
{
CurrentType = typeof(BigRequest);
var xmlDoc = await XDocument.LoadAsync(streamReader, LoadOptions.None, CancellationToken.None);
var reqModel = new XmlSerializer(CurrentType).Deserialize(xmlDoc.CreateReader());
var model = ConvertToSubSetRequestObject(reqModel as BigRequest);
return InputFormatterResult.Success(model);
}
}
public SubSetRequest ConvertToSubSetRequestObject(BigRequest request)
{
var retObject = new SubSetRequest
{
Name = request.Name,
Address = request.Address
};
return retObject;
}
}
ValueController.cs
[HttpPost]
[Route("/api/Value/Calculate")]
public virtual ActionResult<object> Calculate(SubSetRequest request)
{
TryValidateModel(request);
if (ModelState.IsValid) // is giving as TRUE, even if EMAIL is NULL
{
var context = new ValidationContext(request, serviceProvider: null, items: null);
var results = new List<ValidationResult>();
// this is working properly
var isValid = Validator.TryValidateObject(request, context, results);
}
return new ActionResult<object>(request.ToString());
}
I got the code of detecting poor grammar from here - Detecting Poor grammar
I am new to C# and Xamarin. I want to merge this code into my speech to text conversion app.
I tried to do it, but I am not getting the desired results.
using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Widget;
using Android.OS;
using Android.Speech;
using Android.Util;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Net;
namespace SpeechToText
{
[Activity(Label = "SpeechToText", MainLauncher = true, Icon = "#drawable/icon")]
public class MainActivity : Activity, IRecognitionListener
{
public const string Tag = "VoiceRec";
SpeechRecognizer Recognizer { get; set; }
Intent SpeechIntent { get; set; }
TextView Label { get; set; }
TextView Label1 { get; set; }
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.Main);
Recognizer = SpeechRecognizer.CreateSpeechRecognizer(this);
Recognizer.SetRecognitionListener(this);
SpeechIntent = new Intent(RecognizerIntent.ActionRecognizeSpeech);
SpeechIntent.PutExtra(RecognizerIntent.ExtraLanguageModel, RecognizerIntent.LanguageModelFreeForm);
SpeechIntent.PutExtra(RecognizerIntent.ExtraCallingPackage, PackageName);
var button = FindViewById<Button>(Resource.Id.btn);
button.Click += ButtonClick;
var Grammarbutton = FindViewById<Button>(Resource.Id.btn1);
Grammarbutton.Click += new EventHandler(ButtonClick2);
Label = FindViewById<TextView>(Resource.Id.tv);
Label1 = FindViewById<TextView>(Resource.Id.tv1);
}
private void ButtonClick(object sender, EventArgs e)
{
Recognizer.StartListening(SpeechIntent);
}
public void OnResults(Bundle results)
{
var matches = results.GetStringArrayList(SpeechRecognizer.ResultsRecognition);
if (matches != null && matches.Count > 0)
{
Label.Text = matches[0];
}
}
private void ButtonClick2(object sender, EventArgs e)
{
var api = new GingerItApi();
for (; ; )
{
Console.Write("Text to check: ");
var text = Label.Text;
if (string.IsNullOrEmpty(text)) break;
try
{
var result = api.Check(text);
if (result?.Corrections?.Count != 0)
{
for (int i = 0; i < result.Corrections.Count; i++)
{
var item = result.Corrections[i];
var mistakes = string.Join(", ", item.Mistakes.Select(x => $"\"{text.Substring(x.From, x.To - x.From + 1)}\""));
var suggestions = string.Join(", ", item.Suggestions.Select(x => $"\"{x.Text}\""));
Label1.Text = $" {i + 1}: {mistakes} >> {suggestions}";
}
}
else
{
Console.WriteLine("Looks okay.\n");
}
}
catch (Exception ex)
{
Console.WriteLine($"**Error: {ex.Message}\n");
}
}
}
public void OnReadyForSpeech(Bundle #params)
{
Log.Debug(Tag, "OnReadyForSpeech");
}
public void OnBeginningOfSpeech()
{
Log.Debug(Tag, "OnBeginningOfSpeech");
}
public void OnEndOfSpeech()
{
Log.Debug(Tag, "OnEndOfSpeech");
}
public void OnError([GeneratedEnum] SpeechRecognizerError error)
{
Log.Debug("OnError", error.ToString());
}
public void OnBufferReceived(byte[] buffer) { }
public void OnEvent(int eventType, Bundle #params) { }
public void OnPartialResults(Bundle partialResults) { }
public void OnRmsChanged(float rmsdB) { }
}
}
class GingerItApi
{
public CheckResult Check(string text)
{
var request = WebRequest.Create($"https://services.gingersoftware.com/Ginger/correct/jsonSecured/GingerTheTextFull?callback=jQuery172015406464511272344_1490987331365&apiKey=GingerWebSite&lang=US&clientVersion=2.0&text={text}&_=1490987518060") as HttpWebRequest;
WebResponse response = null;
try
{
response = request.GetResponse();
if (response != null)
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
string data = reader.ReadToEnd();
var first = data.IndexOf('{');
var last = data.LastIndexOf('}');
var json = data.Substring(first, last - first + 1);
return JsonConvert.DeserializeObject<CheckResult>(json);
}
}
}
catch (Exception)
{
throw;
}
return null;
}
}
public class LrnFrgOrigIndx
{
[JsonProperty("From")]
public int From { get; set; }
[JsonProperty("To")]
public int To { get; set; }
}
public class Mistake
{
[JsonProperty("Definition")]
public string Definition { get; set; }
[JsonProperty("CanAddToDict")]
public bool CanAddToDict { get; set; }
[JsonProperty("From")]
public int From { get; set; }
[JsonProperty("To")]
public int To { get; set; }
}
public class Suggestion
{
[JsonProperty("Definition")]
public string Definition { get; set; }
[JsonProperty("LrnCatId")]
public int LrnCatId { get; set; }
[JsonProperty("Text")]
public string Text { get; set; }
}
public class Correction
{
[JsonProperty("Confidence")]
public int Confidence { get; set; }
[JsonProperty("From")]
public int From { get; set; }
[JsonProperty("LrnFrg")]
public string LrnFrg { get; set; }
[JsonProperty("LrnFrgOrigIndxs")]
public IList<LrnFrgOrigIndx> LrnFrgOrigIndxs { get; set; }
[JsonProperty("Mistakes")]
public IList<Mistake> Mistakes { get; set; }
[JsonProperty("ShouldReplace")]
public bool ShouldReplace { get; set; }
[JsonProperty("Suggestions")]
public IList<Suggestion> Suggestions { get; set; }
[JsonProperty("To")]
public int To { get; set; }
[JsonProperty("TopLrnCatId")]
public int TopLrnCatId { get; set; }
[JsonProperty("Type")]
public int Type { get; set; }
[JsonProperty("UXFrgFrom")]
public int UXFrgFrom { get; set; }
[JsonProperty("UXFrgTo")]
public int UXFrgTo { get; set; }
}
public class Sentence
{
[JsonProperty("FromIndex")]
public int FromIndex { get; set; }
[JsonProperty("IsEnglish")]
public bool IsEnglish { get; set; }
[JsonProperty("ToIndex")]
public int ToIndex { get; set; }
}
public class CheckResult
{
[JsonProperty("Corrections")]
public IList<Correction> Corrections { get; set; }
[JsonProperty("Sentences")]
public IList<Sentence> Sentences { get; set; }
}
I want to get the recognized speech, send it to grammar corrector, and display the output.
Please help me to solve this, or at least help me to further research the problem.
Thank you.
You have put an infinite loop in your code. Please remove it.
For example:
private void ButtonClick2(object sender, EventArgs e)
{
var api = new GingerItApi();
Console.Write("Text to check: ");
var text = Label.Text;
if (!string.IsNullOrEmpty(text))
{
try
{
var result = api.Check(text);
if (result?.Corrections?.Count != 0)
{
for (int i = 0; i < result.Corrections.Count; i++)
{
var item = result.Corrections[i];
var mistakes = string.Join(", ", item.Mistakes.Select(x => $"\"{text.Substring(x.From, x.To - x.From + 1)}\""));
var suggestions = string.Join(", ", item.Suggestions.Select(x => $"\"{x.Text}\""));
Label1.Text = $" {i + 1}: {mistakes} >> {suggestions}";
}
}
else
{
Label1.Text = "Looks okay.\n";
Console.WriteLine("Looks okay.\n");
}
}
catch (Exception ex)
{
Console.WriteLine($"**Error: {ex.Message}\n");
}
}
}
And the result is:
I am writing an app that has an Azure database. I've never did nything connected with Azure, so I am new to all the stuff. I've found on the internet and at microsoft documentation some tutorials, but I must have got sth wrong, cause it doesn't work. So I have a table at my database called Week, I've created a model in my code:
[DataContract]
public class Week
{
//[JsonProperty(PropertyName = "Id")]
//[DataMember]
public int Id { get; set; }
[JsonProperty(PropertyName = "Book")]
[DataMember]
public Book CurrentBook { get; set; }
[JsonProperty(PropertyName = "Is_Read")]
[DataMember]
public Boolean IsRead { get; set; }
[JsonProperty(PropertyName = "Pages_Read")]
[DataMember]
public int PagesRead { get; set; }
[JsonProperty(PropertyName = "Start_Date")]
[DataMember]
public DateTime StartDate { get; set; }
[JsonProperty(PropertyName = "User")]
[DataMember]
public User Reader { get; set; }
[JsonProperty(PropertyName = "Week_Number")]
[DataMember]
public int WeekNumber { get; set; }
public Week(Book currentBook, Boolean isRead, int pagesRead, DateTime startDate, User reader, int weekNumber)
{
CurrentBook = currentBook;
IsRead = isRead;
PagesRead = pagesRead;
StartDate = startDate;
Reader = reader;
WeekNumber = weekNumber;
}
public Week()
{
}
public int GetMonth()
{
//TODO: Implement the method.
return 0;
}
}
Then I created the WeekRepository for CRUD operations:
public class WeekRepository : BaseRepository<Week>
{
private IMobileServiceTable<Week> weekTable;
public string errorMesage = string.Empty;
public WeekRepository()
{
weekTable = MobileService.GetTable<Week>();
}
public async override Task<int> Save(Week entity)
{
try
{
await weekTable.InsertAsync(entity);
// .ContinueWith(t =>
//{
// if (t.IsFaulted)
// {
// errorMesage = "Insert failed";
// }
// else
// {
// errorMesage = "Inserted a new item with id " + entity.Id;
// }
//});
}
catch (WebException ex)
{
errorMesage = ex.Message;
}
return entity.Id;
}
public override void Update(Week entity)
{
return;
}
public override Week Load(int bookId)
{
var week = weekTable.Where(w => w.IsRead == false).ToListAsync();
return week.Result.Single();
}
public override List<Week> LoadByUserId(int userId)
{
return new List<Week>();
}
public Week LoadCurrentWeek(int userId)
{
return new Week();
}
}
To test if it works, I wrote a simple test:
[TestMethod]
public void ShouldSaveWeekToTheDB()
{
//ARANGE
Week weekTestEntity = new Week(null, false, 10, new DateTime(), null, 1);
//ACT
int id = weekRepository.Save(weekTestEntity).Result;
//ASSERT
var savedItem = weekRepository.Load(1);
Assert.AreEqual(false, savedItem.IsRead);
}
However, InsertAsync() throws an exception - Not Found. I've no idea what I am doing wrong, cause it seems a simple thing as far as I can see from the material on the Internet.
If You could help me, I would be really grateful!
Thank You in advance!
Best Regards,
Roman.