I'm currently working on a Windows Store app (for a school assignment), and I'm having trouble inserting data into my database which is stored in Azure. Whenever I attempt to insert data into the db, the MobileServiceInvalidOperationException gets thrown. My code is as follows:
In my model class
class Division
{
public string Id {get; set;}
[JsonProperty(PropertyName = "divisionTitle")]
public string DivisionTitle {get; set;}
}
And the relevant code in my MainPage.xaml.cs file
private MobileServiceCollection<Division, Division> divisionItems;
private IMobileServiceTable<Division> divisionTable = App.MobileService.GetTable<Division>();
private async void InsertDivision(Division divisionItem)
{
// This code inserts a new division Item into the database.
// When the operation completes and Mobile Services has
// assigned an Id, the item is added to the collection
try
{
await divisionTable.InsertAsync(divisionItem);
divisionItems.Add(divisionItem);
}
/////////////////////////////////////////////////////////
// The MessageDialog that pops up when this exception //
// gets thrown is: //
// //
// Internal Server Error (HTTP 500) //
////////////////////////////////////////////////////////
catch (MobileServiceInvalidOperationException e)
{
MessageDialog errormsg = new MessageDialog(e.Message,
string.Format("{0} (HTTP {1})",
e.Response.ReasonPhrase,
(int)e.Response.StatusCode));
var ignoreAsyncOpResult = errormsg.ShowAsync();
}
}
private void DivisionButtonSave_Click(object sender, RoutedEventArgs e)
{
var DivisionItem = new Division
{
DivisionTitle = DivisionInput.Text
};
InsertDivision(DivisionItem);
}
I also added a script in the management portal:
function insert(item, user, request) {
if (item.DivisionTitle.length > 15) {
request.respond(statusCodes.BAD_REQUEST, 'Division title must be under 15 characters');
}
else {
request.execute();
}
}
Before making the changes above, I was having no trouble communicating with Azure from within the app and wasn't having any problems inserting data. It's only after editing the script in Azure (the default insert method is simply the request.execute() statement), and since I added the InsertDivision method (I was previously entering data into the db directly from the event handler with the command await App.MobileService.GetTable<Division>().InsertAsync(DivisionItem);) that this problem has started to occur. I've tried a couple of different things and nothing has worked. After looking at my code does anything stick out? Thanks in advance to anyone who can help.
In the request sent to the service, the property DivisionTitle is sent with the first letter in lower case (since you defined it as such with the JsonProperty attribute):
{"divisionTitle":"the actual title"}
On your script, you're trying to access the property item.DivisionTitle (which doesn't exist, JavaScript is case-sensitive), and then access a property (length) of this undefined value. That will cause an error in your script. If you either change the script to use the actual JSON name (item.divisionTitle.length > 15) or change the JsonProperty declaration in the client to send the property with the first letter in upper case, it should work.
By the way, if you go to the "logs" tab in the portal, you should see some error which explains why you're getting the internal server error.
Related
I successfully get the data from realtime database firebase when I put break point on OndataChange but when I put the break point after the OnDataChange method the records are now null.
public void OnDataChange(DataSnapshot dataSnapshot)
{
if (dataSnapshot.Value != null)
{
reclist.Clear();
TempDB rec = new TempDB();
rec.ID = dataSnapshot.Key;
rec.Firstname = dataSnapshot.Child("FirstName").Value.ToString();
rec.Lastname = dataSnapshot.Child("LastName").Value.ToString();
rec.Address = dataSnapshot.Child("Address").Value.ToString();
rec.ContactNo = dataSnapshot.Child("Contact number").Value.ToString();
rec.Email = dataSnapshot.Child("EmailAddress").Value.ToString();
rec.Password = dataSnapshot.Child("Password").Value.ToString();
idd = rec.ID;
Console.WriteLine(id.ToString());
reclist.Add(rec);
}
}
That's because data is loaded from Firebase asynchronously, while the rest of your code continues. Then once the data is loaded, your onDataChange is called with it. This means that the code just after what you shared indeed runs before the code inside the onDataChange, and that is working as intended.
The solution is always the same: any code that needs the data from the database needs to be inside onDataChange, be called from there, or be otherwise synchronized.
Have a look at these two (Android) examples for some ideas:
getContactsFromFirebase() method return an empty list
Setting Singleton property value in Firebase Listener
I have implemented Voice call in my code using .net with NServiceBus version 7.
Below is the code snippet to send voice call:
public Task Handle(AddServiceAuto message, IMessageHandlerContext context)
{
try
{
string VoiceCallCode = null;
Guid userID = User.userID;
VoiceCallCode = GetVoiceCallCode(userID);
if (VoiceCallCode != null)
{
publishAddVoiceCallEvent(context, user.caseID, userID.Mobile,
userID.Voicecall, VoiceMessageText, VoiceCallCode);
}
}
}
private void publishAddVoiceCallEvent(IMessageHandlerContext context,
Guid caseID, string mobile, bool voicecall,
string voiceMessageText, string voiceCallCode)
{
AddVoiceCallEvent addVoiceCallEvent = new AddVoiceCallEvent()
{
CaseID = caseID,
Mobile = mobile,
Voicecall = voicecall,
VoiceMessageText = voiceMessageText,
VoiceCallCode = voiceCallCode
};
context.Publish(addVoiceCallEvent).ConfigureAwait(false);
}
public Task Handle(AddVoiceCallEvent message, IMessageHandlerContext context)
{
try
{
Logger.InfoFormat("message.CaseID: {0}", message.CaseID);
Logger.InfoFormat("message.Voicecall= {0}", message.Voicecall);
Logger.InfoFormat("message.Mobile {0}", message.Mobile);
Logger.InfoFormat("message.VoiceCallCode {0}", message.VoiceCallCode);
// The user should satisfy below conditions in order to receive a voice call.
if ((message.Voicecall) && !string.IsNullOrEmpty(message.Mobile) &&
!string.IsNullOrEmpty(message.VoiceMessageText) &&
!string.IsNullOrEmpty(message.VoiceCallCode))
{
Voicecall(message.Mobile, message.Voicecall,
message.VoiceMessageText, message.VoiceCallCode);
}
else
{
Logger.Error("Mobile Value is Empty (OR) Voicecall is False (OR)
+ VoiceMessageText is Empty (OR) VoiceCallCode is Empty");
}
}
}
If condition satisfied it will send voice call, else it will print log.
Problem:
The Voice call is random i.e. sometimes user is receiving voice call and sometimes not(even though with same settings i.e mobile, VoiceCallCode values stored properly in DB and Voicecall is also true)
and the Strange part is, though the values are stored correctly DB, when we look into the logs that we are printing, it shows the value of Mobile, VoiceCallCode is null and Voicecall is false.
Again after 5 mins I tried, it worked.
One more thing is, when voice call is not working.
Logger.InfoFormat("message.CaseID: {0}", message.CaseID); // CaseID printed
For Below, data is not printing even though data is there in available in DB (i.e. printing as null)
Logger.InfoFormat("message.Voicecall= {0}", message.Voicecall);
Logger.InfoFormat("message.Mobile {0}", message.Mobile);
Logger.InfoFormat("message.VoiceCallCode {0}", message.VoiceCallCode);
Strange is that, for CaseID it printed while for others it is not printing.
Why this is happening? Can someone please help on this?
The code you've shared doesn't seem to be a running code (try w/o catch) therefore it would be hard to pinpoint what contributes to the issue. But the random behaviour could be attributed to improper use of async APIs. The handler methods should return a Task or use async/await. So are operations invoked on IMessageHandlerContext.
For example, publishAddVoiceCallEvent should be returning a Task and not void. The code inside it (context.Publish(addVoiceCallEvent).ConfigureAwait(false);) should be either return context.Publish(addVoiceCallEvent); or await context.Publish(addVoiceCallEvent).ConfigureAwait(false);.
NServiceBus comes with a Rozlyn analyzer to help with these issues.
I'm attempting to retrieve some data from a Firebase database. I've been able to do it fine in the past, but there's something wrong with my GetValueAsync() code below. When debugging it gets stuck at the "await reference.Database" line, but I'm not sure what I'm doing wrong. When running without debugging, none of the information is ever retrieved.
I'm uncertain if the problem is with the path, or the await/async function. Debugging shows that loggedUserId is storing the value before referencing it in the next line, but the rest of the function never completes or faults. The application compiles but I'm never able to capture any info from the snapshot.
The format of my database is "users" -> 78cVqzA8qNTNigsao3VvdnM0Qol2 (Which is correct) -> (several data pairs such as level : 1, lives : 3, etc)
public static async void GetUserData()
{
FirebaseApp app = FirebaseApp.DefaultInstance;
app.SetEditorDatabaseUrl("https://narwhaltrivia.firebaseio.com/");
if (app.Options.DatabaseUrl != null) app.SetEditorDatabaseUrl(app.Options.DatabaseUrl);
DatabaseReference reference = Firebase.Database.FirebaseDatabase.DefaultInstance.RootReference;
loggedUserId = FirebaseAuth.DefaultInstance.CurrentUser.UserId;
await reference.Database.GetReference("users").Child(loggedUserId).GetValueAsync().ContinueWith(task =>
{
if (task.IsFaulted)
{
Debug.LogError("Error retrieving user data");
return;
}
if (task.IsCompleted)
{
DataSnapshot userSnapshot = task.Result;
loggedEmail = userSnapshot.Child("email").GetRawJsonValue();
loggedCurrentScore = userSnapshot.Child("currentScore").GetRawJsonValue();
loggedLevel = userSnapshot.Child("level").GetRawJsonValue();
loggedLives = userSnapshot.Child("lives").GetRawJsonValue();
loggedRound = userSnapshot.Child("round").GetRawJsonValue();
loggedTotalScore = userSnapshot.Child("totalScore").GetRawJsonValue();
return;
}
});
}
Can anyone help me on this section of code? Before I say anything else, the "FillerId" isn't actually there in the actual code, it's replaced with the correct channel id of the discord text channel. The error I'm getting with this code is that every time I run this function, it returns an error saying that in line 170 "channel1 is null". I am absolutely sure that I am using the correct channel id.
*Note: for reference I defined the client above this code as "discord001"
private void CreateTimerWithOutput(string Message, int MonthWanted, int DayWanted)
{
var channel1 = discord001.GetChannel(Fillerid);
CreateTimer(400);
whaddupTimer.Elapsed += new ElapsedEventHandler(NewYearsCheck);
void NewYearsCheck(object sender, System.Timers.ElapsedEventArgs e)
{
DateTime today = DateTime.Today;
if(today.Month != MonthWanted && today.Day != DayWanted)
{
channel1.SendMessage(Message);
}
}
}
Make sure you are running this command and any other methods that get information from Discord after you are certain a connection has been made.
I stored all information (roles, channels, guilds, etc.) within the "Connected" event handler and then accessing them was easy..
I have a few tables in SQL Server that I am using to log when a user logs into a Silverlight application.
I have created an entity for each of those tables. One example is ApplicationUsageLog, where I log the ApplicationID, the Date, and the UserID. Those are mostly pulled from the Silverlight side.
I would like to just create a method called Login(AppID,UserID) that can do an insert into that table.
Is that possible?
Thanks!
EDIT The following does not work for some reason:
[Invoke]
public void Login(int AppID,string EmployeeNo)
{
var aul = new ApplicationUsageLog{ ApplicationID = AppID, LoginDate = System.DateTime.Now, EmployeeNo = EmployeeNo };
if ((aul.EntityState != System.Data.EntityState.Detached))
{
this.ObjectContext.ObjectStateManager.ChangeObjectState(aul, System.Data.EntityState.Added);
}
else
{
try
{
this.ObjectContext.ApplicationUsageLogs.AddObject(aul);
}
catch (System.Exception e) { }
}
}
I can look at aul and all looks good. But when I put a breakpoint at the end, this.ObjectContext.ApplicationUsageLogs is still totally empty....
Yes, you can add a method to your Domain service class marked with the InvokeAttribute attribute. The method will appear as a method on the client context class.
You can add your own custom methods to the DomainService if you want but it will not be called automatically when you insert into your context and SubmitChanges. You will have to call it manually.
If you want to override the implementation of your Insert method you can simply modify the contents of the Insert*EntityName* method in your DomainService.