The request could not be completed (Not Found) - c#

I have added a vanilla mobile service, selecting the defaults all the way. It is a .Net backend, using a new 20MB DB on an existing server I use in the North Europe DC. I created a blank Windows Store App, added the MobileServices nuget package and then followed the instructions to connect my MobileService to my app by adding the MobileServicesClient to my App.xaml class. Then I added a button with an event handler. The handler calls an async function to insert a TodoItem object into the database.
App.xaml.cs
public static MobileServiceClient MobileService = new MobileServiceClient(
"https://???.azure-mobile.net/",
"???");
I have replaced the URI and Token with ???. The one I used came from my Azure Portal for this Mobile Service.
MainPage.xaml.cs
private void Button_Click(object sender, RoutedEventArgs e)
{
CreateItem();
}
private async void CreateItem()
{
TodoItem item = new TodoItem { Text = "Sort This", Complete = false };
try
{
await App.MobileService.GetTable<TodoItem>().InsertAsync(item);
}
catch(MobileServiceInvalidOperationException ex1)
{
Debug.WriteLine(ex1.Message);
}
catch(Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
When I run this code and click the button a MobileServiceInvalidOperationException is raised:
"{"The request could not be completed. (Not Found)"}"
I am using VS2013, with Service Pack 2 installed and WindowsAzure.MobileServices 1.2.3.
The MobileService is running as I can navigate to https://MyMobileService.azure-mobile.net/ but, if I click Check It Out, I am asked to Authenticate (MyMobileService is not the actual Uri).
The post request looks ok, but the response is a 404.
I have been working on this all day, including using Windows Phone, with no luck...
I know I must be doing something wrong, or there is an issue with Azure in Northern Europe, but I can't sort it out.
Any help much appreciated.
Jason.

I had the same issue awhile ago. I switch from .net backend to javascript. Also, make sure your mobileservice and db schema match.

Related

UWP - How to Sync files with OneDrive API in C#

I am creating a UWP application and I want to use the Onedrive API so that users can save a copy of their files in their Onedrive account, but I don't get it, so far I have only managed to login what I want is:
upload files
download files
and synchronize if any of them is modified
Create folders
Delete Files
This code achieves the login, but I can not move beyond this, as would proceed for upload files or download them
private async void btn_Login_Click(object sender, RoutedEventArgs e)
{
if (this.oneDriveClient == null)
{
try
{
// Setting up the client here, passing in our Client Id, Return Url,
// Scopes that we want permission to, and building a Web Broker to
// go do our authentication.
this.oneDriveClient = await OneDriveClient.GetAuthenticatedMicrosoftAccountClient(
clientId,
returnUrl,
scopes,
webAuthenticationUi: new WebAuthenticationBrokerWebAuthenticationUi());
// Show in text box that we are connected.
txtBox_Response.Text = "We are now connected";
// We are either just autheticated and connected or we already connected,
// either way we need the drive button now.
btn_GetDriveId.Visibility = Visibility.Visible;
}
catch (OneDriveException exception)
{
// Eating the authentication cancelled exceptions and resetting our client.
if (!exception.IsMatch(OneDriveErrorCode.AuthenticationCancelled.ToString()))
{
if (exception.IsMatch(OneDriveErrorCode.AuthenticationFailure.ToString()))
{
txtBox_Response.Text = "Authentication failed/cancelled, disposing of the client...";
((OneDriveClient)this.oneDriveClient).Dispose();
this.oneDriveClient = null;
}
else
{
// Or we failed due to someother reason, let get that exception printed out.
txtBox_Response.Text = exception.Error.ToString();
}
}
else
{
((OneDriveClient)this.oneDriveClient).Dispose();
this.oneDriveClient = null;
}
}
}
}
I created a sample repository in github:Onedrive Sync Files Sample
I have already tried using Dropbox, Gdrive, but its implementation for UWP seems to be much more complex, so I chose OneDrive. any answer will be very helpful thanks in advance
How to Sync files with OneDrive API in C#
For using OneDrive, we suggest you implement OneDrive feature with OneDrive Service that is part of Windows Community Toolkit .
Getting Started
To use the OneDrive API, you need to have an access token that authenticates your app to a particular set of permissions for a user. In this section, you'll learn how to:
Register your application to get a client ID and a client secret.
Sign your user in to OneDrive with the specified scopes using the token flow or code flow.
Sign the user out (optional).
And this is official code sample that you could refer.

Bot Framework Missing From.Id & Conversation.Id from Facebook Channels

I've raised a bug item against the C# Bot Builder project on GitHub but to be honest I can't really get to the bottom of whether this is a bug with the framework or a sporadic problem originating on the Facebook side.
We have been building the bot for a couple of months and have been using in development and staging exvironments extensively and have not seen this issue once.
So we go live with our first customer and boom. This issue starts occuring.
Value cannot be null. Parameter name: invalid activity-missing From.Id
And also:
Value cannot be null. Parameter name: invalid activity-missing
Conversation.Id
The chats that produced this issue were started by users coming to the bot via the messenger web page and the Web Chat Plugin.
The users in both instances had used the "Get Started" button thus opting in to the chat. This opting in provides the bot with access to the users basic profile information.
Understandably this is pretty odd and I have been entirely unable to reproduce this issue in any testing in any of our environments (we have Dev, Staging and Live).
Has anyone else seen a similar issue?
What did you do to work around it?
At the moment since I cannot reproduce it anywhere I can't really close the bug or even have a vague level of confidence in it not happening again.
If your bot is designed with the Activity Handler, as demonstrated in the Samples-work-in-progress branch, you can add some code to the controller to log the entire Request.Body:
[Route("api/messages")]
[ApiController]
public class BotController : ControllerBase
{
private readonly IBotFrameworkHttpAdapter Adapter;
private readonly IBot Bot;
public BotController(IBotFrameworkHttpAdapter adapter, IBot bot)
{
Adapter = adapter;
Bot = bot;
}
[HttpPost]
public async Task PostAsync()
{
Request.EnableBuffering();
using (var buffer = new MemoryStream())
{
await Request.Body.CopyToAsync(buffer);
buffer.Position = 0L;
using (var bodyReader = new JsonTextReader(new StreamReader(buffer, Encoding.UTF8)))
{
Debug.Print(BotMessageSerializer.Deserialize(bodyReader).ToString());
buffer.Position = 0L;
}
}
Request.Body.Position = 0;
await Adapter.ProcessAsync(Request, Response, Bot);
}
}
This should provide more information on what type of message is being sent to the bot. My guess is that it has something to do with a Facebook Messenger specific web hook you have subscribed to. For instance, I don't think 'message_echoes' are currently sent to the bot with a .From or conversation.Id. However, we have recently modified our Connector Service to include these: the release should be within the next few weeks.

Operation returned an invalid status code 'Forbidden`. Botframework v4

So i created a bot in azure and downloaded it. The free 1000 calls from LUIS reached its limit. I created a subscription in azure portal (I did do the docker container something). Followed this guide until step 6. When i click the endpoint url and query directly in the browser it is working fine.
I added it to the bot via Bot Emulator by clicking + sign in services and adding the bot model there. But when i run bot i get the title error. I noticed in the .bot file the authoring key and subscription key added by the bot emulator is the same.
So i changed the subscription key to the one of the keys generated by azure and still the same error. I have tried reseting the authoring key still same and deleting my luis.ai account and created a new one. (still same email because that is the one logged in azure portal.) and still the same.
Here are some pictures for reference and the error.
I also tried testing it in luis.ai and got this result.
but when i check it is set to the new resource.
Here is a pic of the bot file after adding luis via Bot emulator. It has same authoring key and subscription key (still forbidden)
so i changed it now with subscription key (still forbidden).
Here it is working properly when tested directly in the URL.
For reference:
azure portal
luis.ai
and the error
How i add luis in the bot.
Here is the code for the bot service.
using System;
using System.Collections.Generic;
using Microsoft.Bot.Builder.AI.Luis;
using Microsoft.Bot.Configuration;
namespace Microsoft.BotBuilderSamples
{
public class BotServices
{
public BotServices(BotConfiguration botConfiguration)
{
foreach (var service in botConfiguration.Services)
{
switch (service.Type)
{
case ServiceTypes.Luis:
{
var luis = (LuisService)service;
if (luis == null)
{
throw new InvalidOperationException("The LUIS service is not configured correctly in your '.bot' file.");
}
var endpoint = (luis.Region?.StartsWith("https://") ?? false) ? luis.Region : luis.GetEndpoint();
var app = new LuisApplication(luis.AppId, luis.AuthoringKey, endpoint);
var recognizer = new LuisRecognizer(app);
this.LuisServices.Add(luis.Name, recognizer);
break;
}
}
}
}
public Dictionary<string, LuisRecognizer> LuisServices { get; } = new Dictionary<string, LuisRecognizer>();
}
}
I am trying to solve this for 4 days already. Thanks!
Thank you for all of the images. That is a HUGE help! Here's the problem:
By default, your code looks for the AuthoringKey in this section (second line):
var endpoint = (luis.Region?.StartsWith("https://") ?? false) ? luis.Region : luis.GetEndpoint();
var app = new LuisApplication(luis.AppId, luis.AuthoringKey, endpoint);
var recognizer = new LuisRecognizer(app);
this.LuisServices.Add(luis.Name, recognizer);
Since your .bot file still has the authoringKey set to the one that starts with ad9c..., which has hit its limit, your bot keeps running into the 403 error.
So, in your .bot file, replace that authoringKey with one of your endpointKeys (they start with 12ccc... or b575...).
I understand your confusion with this, especially since this requires you putting an endpointKey in your authoringKey property. I know there's some changes on the horizon to how LUIS bots will use keys, but those are probably a month or more out.
Alternatively, you can change:
var app = new LuisApplication(luis.AppId, luis.AuthoringKey, endpoint);
to:
var app = new LuisApplication(luis.AppId, luis.SubscriptionKey, endpoint);
Note: If you make either of these changes, LUIS can only query (which is usually fine), since Authoring Keys do everything else (see reference, below)
References
These are not so much for you as much as others that might come across this.
Authoring vs. Endpoint Keys
Key Limits
Troubleshooting LUIS 403 Errors

Send notifications to inactive users using Azure Mobile Services. Where to save the "lastLoginDate" and filter on it?

I have always been using Parse to manage my backend but switched to Azure due to the better integration with ASP.NET and Xamarin. In Parse I created a PFInstallation object and associated whatever property I needed to filter on before sending push notifications.
In Azure Mobile Services I am using the following code (in Xamarin iOS) to register the device:
public override void RegisteredForRemoteNotifications (UIApplication application, NSData deviceToken)
{
try {
var languageCode = NSLocale.PreferredLanguages [0];
ServiceClient.GetPush ().RegisterNativeAsync (deviceToken, new []{ languageCode }).ContinueWith ((t) => {
Console.WriteLine ("Device registration successful!");
});
} catch (Exception e) {
Console.WriteLine ("Could not register device for push notifications: {0}", e.Message);
}
}
I would like to have a way to remind my inactive users that they should play again. In Parse I just associated a "lastLoginDate" attribute to the PFInstallation object. How can I achieve the same with Azure Mobile Services?
As of now I am only able to filter based on the user's device language (because I save it as a tag) but not on the "lastLoginDate".
PS: in my backend I would like to have a code like this
var users = registrations.Where(u => u.LastLoginDate <= testDate);
SendNotificationToUsers(users);
UPDATE
I read on this page that you can use Tag Expressions to filter registrations but in the article it's not specified if you can use boolean expressions involving a date comparison. Any help on this?
Thank you.
One approach would be to have the device register with a tag with the current date each time the user opens the app. So today I use the app, I register my token for the tag "last-use-2015-03-02". Tomorrow if I use the app again I will reregister with the tag "last-use-2015-03-03", replacing the device registration for 2015-03-02.
Then each day have a scheduler that sends a message to the tag for a week ago (for example). So a week from now on March 9, I can send a notification to all devices with the tag "last-use-2015-03-02" reminding them to come back.

C# Desktop application using Google Calendar API .NET v3 -- Howto?

Probably not the only one asking this, but I found nothing that works...It's like a jungle ;)
I have a C# desktop app (5-10 user) that I want to connect to my Google calendar. I want to add, move, delete, update events in the calendar. I downloaded an installed the last .Net api v.3.
From what I read, the difficult part is the authenticate/connecting procedure. I suppose that we need to use OAuth 2.0 authentication ? I want my user to authenticate once, not each time they want to make a action (add, move, delete, update).In some sample I get we have to cut and paste a token from a web page into a Console...not really user friendly. And how to authenticate only 1 times (or just put the token directly in code to not authenticate ?) ?
Now, were I can have a good working sample code in C# to make that ?
Thanks you very much for helping !!
I used something similar to the example here. What I did initially was create a simple web application using the sample logic to setup the initial auth that Google requires. I stepped through and got the Refresh Token from the state. I then saved this in an app setting that I could use later during future GetAuthorization requests. At least for what I was doing this worked well, the user never needed to authorize as long as app stayed connected.
private IAuthorizationState GetAuthorization(WebServerClient client)
{
IAuthorizationState state = new AuthorizationState(new[] { CalendarService.Scopes.Calendar.GetStringValue() });
string refreshToken = LoadRefreshToken();//this where I wrote code to load it from the app settings
if (!string.IsNullOrEmpty(refreshToken))
{
state.RefreshToken = refreshToken;
try
{
if (client.RefreshToken(state))
return state;
}
catch (ProtocolException)
{
return null;
}
}
return null;
}
I have today the same issue and found now the solution
Prepare Api Access https://console.developers.google.com/apis/dashboard
Press button "Enable Apis and services"
Search "Calendar" and choose "Google Calendar API"
Press button "Create Project"
Create Project
Press "Enable"
Press button "Create credentials"
Choose "Where will you be calling the API from?" -> Other UI
Choose "What data will you be accessing?" -> Application data
Create service account
Choose Role Project -> Editor
Choose Key type JSON
Press button "Continue"
Rename the file to "credential.json" and save it in the visual studio project
Change in Visual Studio the Copy to output Directory -> "Copy if newer"
Change share config of your google calendar (Share this Calendar)
Add the email address from the json file "client_email" in the google calendar config "Share with specific people"
Example Code
using Google.Apis.Auth.OAuth2;
using Google.Apis.Calendar.v3;
using Google.Apis.Calendar.v3.Data;
using Google.Apis.Services;
using System.IO;
namespace Test.GoogleCalendar
{
class Program
{
static void Main(string[] args)
{
GoogleCredential credential;
using (var stream = new FileStream("credential.json", FileMode.Open, FileAccess.Read))
{
credential = GoogleCredential.FromStream(stream).CreateScoped(CalendarService.Scope.Calendar);
}
// Create Google Calendar API service.
var service = new CalendarService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Test Calendar Reader",
});
var calendars = service.CalendarList.List().Execute().Items;
foreach (CalendarListEntry calendar in calendars)
{
var events = service.Events.List(calendar.Id).Execute();
}
}
}
}
Here is a link to help download Calendar Client API library for .NET. The library makes OAuth and accessing the Calendar easier. See link for OAuth details but I'm pretty sure it's what you want - user logs in only once to authorize.
On same page there are sample applications using the Client API in VB.NET and MVC.

Categories

Resources