DropNet File upload fails permanently - c#

I am developing a C# application which should connect to the user`s Dropbox using the DropNet C# Api.
I connect my application like this:
UserLogin login=client.GetToken();
client.UserLogin = login;
String url = client.BuildAuthorizeUrl();
ConnectForm authorizer = new ConnectForm(url);
authorizer.ShowDialog(this);
try
{
UserLogin accessToken = client.GetAccessToken();
this.toolStripStatusLabel1.Text = "connected";
}
catch (DropboxException exc)
{
client = new DropNetClient("API KEY", "API SECRET");
this.toolStripStatusLabel1.Text = "error";
}
My toolStripStatusLabel displays "connected" after this code part and after I try to upload a file (or to create a folder) like this
client.UploadFile("/", "test.txt", File.ReadAllBytes("C:/Users/Me/Desktop/test.txt"));
this.toolStripStatusLabel1.Text = "File uploaded";
it displays "File uploaded" but there are still no files in my Dropbox.. My Dropbox Api Error Log shows some 403 errors but without any further information.
Does anybody know whats wrong here?

I've found the solution.
When you register your application for "App-Folder" permission only you have to set client.useSandbox=true; directly after initalizing.

Related

WebClient FileUpload - problem with upload file

I'm trying to upload files with WebClient on network disc.
Everything is fine until I publish my app.
Code to upload:
public IFormFile Image{ get; set; }
(...)
imagename = FileHelper.GenerateFilename(Image.FileName);
var imgsave = Path.Combine(PathHelper.NewsFilePath, imagename);
WebClient client = new WebClient();
client.Credentials = new NetworkCredential("username", "password");
try
{
client.UploadFile(imgsave, Image.FileName);
}
catch (Exception e)
{
}
When I run application locally, it's working perfect, but when I publish my app, I get an error:
Error message: System.IO.FileNotFoundException: Could not find file 'C:\inetpub\wwwroot\application\test.PNG'.
File name: 'C:\inetpub\wwwroot\application\test.PNG' at (...)
Seems that published app is looking for this file somewhere within app folder. How can I indicate this file to upload it correctly?

How to create google translation using windows application without getting the error The Application Default Credentials are not available.?

I am trying to create a google api to extract text from image and later do a translation to English, my sample code bellow
try
{
var JsonFilePath = #"C:\Users\shanjeeva\source\repos\TranslatorWindowsApp\Translator-fa8e022a7ba1.json";
//Authenticate to the service by using Service Account
var credential = GoogleCredential.FromFile(JsonFilePath).CreateScoped(ImageAnnotatorClient.DefaultScopes);
var channel = new Grpc.Core.Channel(ImageAnnotatorClient.DefaultEndpoint.ToString(), credential.ToChannelCredentials());
var client = ImageAnnotatorClient.Create(); // getting an error here
var image = Image.FromFile(#"D:\Work Temp\Translate.JPG");
// Performs label detection on the image file
var response = client.DetectLabels(image);
foreach (var annotation in response)
{
if (annotation.Description != null)
Console.WriteLine(annotation.Description);
}
}
catch (AnnotateImageException ex)
{
AnnotateImageResponse response = ex.Response;
Console.WriteLine(response.Error);
}
catch (Exception ee)
{
Console.WriteLine(ee.Message);
throw;
}
}
also I have setup google cloud application, generated necessary json file eg- Translator-XXXXX.json
some suggested to setup environment variable with the key "GOOGLE_APPLICATION_CREDENTIALS" also I tried, but am getting bellow error
'The Application Default Credentials are not available. They are available if running in Google Compute Engine. Otherwise, the environment variable GOOGLE_APPLICATION_CREDENTIALS must be defined pointing to a file defining the credentials. See https://developers.google.com/accounts/docs/application-default-credentials for more information.'
Can someone please help me?
I was able to resolve with experts help, sample code bellow, added bellow code just before all other code and it works fine
try
{
var GAC = Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS");
if (GAC == null)
{
var path = #"D:\Work Temp\translator-298603-2bb5a20655a2.json";
Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", path);
}
}
catch (Exception)
{
}

Microsoft winsdkfb Not Logged In: You are not logged in. Please login and try again. C# WinRT

For our new Windows 10 application (C# + XAML) we are using the new https://github.com/Microsoft/winsdkfb/ login, however since we have migrated to this login I am having no luck with facebook login.
We are using FBResult result = await sess.LoginAsync(permissions); and I am getting this error all the time: "Not Logged In: You are not logged in. Please login and try again."
My code is litteraly a copy and paste from the samples they did on github:
I have checked my SID and FacebookAppId and they are the same on both the app and the Facebook website.
public async Task<string> LogIntoFacebook()
{
//getting application Id
string SID = WebAuthenticationBroker.GetCurrentApplicationCallbackUri().ToString();
//// Get active session
FBSession sess = FBSession.ActiveSession;
sess.FBAppId = FacebookAppId;
sess.WinAppId = SID;
//setting Permissions
FBPermissions permissions = new FBPermissions(PermissionList);
try
{
// Login to Facebook
FBResult result = await sess.LoginAsync(permissions);
if (result.Succeeded)
{
// Login successful
return sess.AccessTokenData.AccessToken;
}
else
{
// Login failed
return null;
}
}
catch (InvalidOperationException ex)
{
SimpleIoc.Default.GetInstance<IErrorService>().ReportErrorInternalOnly(ex);
return null;
}
catch (Exception ex)
{
SimpleIoc.Default.GetInstance<IErrorService>().ReportErrorInternalOnly(ex);
return null;
}
return null;
}
by doing this:
//getting application Id
string SID = WebAuthenticationBroker.GetCurrentApplicationCallbackUri().ToString();
it is generating me an SID that looks like this:
ms-app://s-1-15-2-0000-bla-bla-bla-667/
so I tried adding ms-app:// to the facebook developer settings page but it did not want it, so I tried removing ms-app:// from the SID when passing it to WinAppId but still no luck
I have filled the field Windows Store SID wih My FBAppId :
does anyone have this issue?
Edit 1:
My code is copy and paste from here: http://microsoft.github.io/winsdkfb/
Edit2: playing the samples from Microsoft my issues is coming from my Application Id.
I did follow step 6:
(Enable OAuth login)
Select the created app on developers.facebook.com.
Click “Settings” from the menu on the left.
Click on the “Advanced” tab.
Under the “OAuth Settings” section, enable “Client OAuth Login” and “Embedded browser OAuth Login”.
Click on “Save Changes”.
After trying everything and NOT wanting to use WebAuthentificationBroker I have found the solution.
Go on the Facebook Developer website: https://developers.facebook.com
Then:
Go to your app name -> Settings -> Advance:
Under: Valid OAuth redirect URIs
you need to add: https://www.facebook.com/connect/login_success.html
Save and you are good to go now!

Google API Autentication - redirect_uri_mismatch error

I'm trying to authenticate my web app with Google Plus API. In the Google Developer console under Credentials for my Cliend Id for Web Application.
I add the following redirect uri: http://localhost:50883/oauth/add_oauth_token
When I run my application I get the following Error:
400. That’s an error.
Error: redirect_uri_mismatch
Application: SID3
You can email the developer of this application at: carlosmoralesdiego#gmail.com
The redirect URI in the request: http://localhost:55404/authorize/ did not match a registered redirect URI.
Learn more
Request Details
from_login=1
response_type=code
scope=https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile
access_type=offline
redirect_uri=http://localhost:55404/authorize/
as=-45fed094242eac62
pli=1
client_id=389029010035-knoo3a2445r77pirc06h8fhgdc5q0dsv.apps.googleusercontent.com
authuser=0
hl=es
So for any reason google changes my redirect uri to the port 55404, why?. Thanks so much and regards
This is the code:
protected void LoginToGooglePlus(object sender, ImageClickEventArgs e)
{
PlusService service = null;
UserCredential credential = null;
string[] scopes = new string[] {PlusService.Scope.PlusLogin, PlusService.Scope.UserinfoEmail,
PlusService.Scope.UserinfoProfile};
// here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData%
try
{
// here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData%
UserCredential credentials;
using (var stream = new FileStream("C:\\Users\\Usuario\\Documents\\Visual Studio 2010\\Projects\\WebApplication1\\WebApplication1\\client_secret.json", FileMode.Open, FileAccess.Read))
{
credentials= GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets, scopes, Environment.UserName, CancellationToken.None, new FileDataStore("WebApplication1")).Result;
}
}
catch (Exception ex)
{
//If the user hits cancel you wont get access.
if (ex.InnerException.Message.IndexOf("access_denied") != -1)
{
Console.WriteLine("User declined access");
Console.ReadLine();
return;
}
else
{
Console.WriteLine("Unknown Authentication Error:" + ex.Message);
Console.ReadLine();
return;
}
}
// Now we create a Google service. All of our requests will be run though this.
service = new PlusService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "SID3",
});
}
The json file which I use it's this one:
{"web":{"auth_uri":"https://accounts.google.com/o/oauth2/auth","client_secret":"jpkVDaaMjlLCHGh67DJ9Zv19","token_uri":"https://accounts.google.com/o/oauth2/token","client_email":"389029010035-knoo3a2445r77pirc06h8fhgdc5q0dsv#developer.gserviceaccount.com","redirect_uris":["http://localhost:50880/Paneles.aspx"],"client_x509_cert_url":"https://www.googleapis.com/robot/v1/metadata/x509/389029010035-knoo3a2445r77pirc06h8fhgdc5q0dsv#developer.gserviceaccount.com","client_id":"389029010035-knoo3a2445r77pirc06h8fhgdc5q0dsv.apps.googleusercontent.com","auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs"}}
I just solved the same problem simply by changing DataStore to null.
credentials= GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
scopes,
Environment.UserName,
CancellationToken.None,
null // <-- here
).Result;
I don't know why but it stops the random port shenanigans.
I should also add, that in my case, it just solved one problem since I needed to publish my app online, where this solution was just wrong. If anyone needs the online version (asp.net 4.5 MVC 5) you can use the code here.
API redirect URL and your application Redirect URL Should be same....
For example (if your application URL Like this localhost:55404/authorize/ and need to add same URL in API Redirect URL localhost:55404/authorize/ )

Download a file from a Claims auth based SharePoint 2010 site programmatically

I have a console application to download a file from a SharePoint site. The sharepoint site uses claims based authentication.
This code throws a 403 Forbidden exception. The specified Network credential has full access to the site, and is able to download the same file from a browser.
WebClient webClient = new WebClient();
webClient.Credentials = new NetworkCredential(username,Password,domain);
byte[] fileData = webClient.DownloadData(urlOfAFile);
FileStream file = File.Create(localPath);
file.Write(fileData, 0, fileData.Length);
Any idea how to fix this?
Maybe a bit late, but adding the right request header before making the request solves the problem:
webClient.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
I also encounter this issue, and below is my research:
{
ClientContext m_clientContext = new ClientContext(strSiteUrl);
m_clientContext.ExecutingWebRequest += new EventHandler<WebRequestEventArgs>(ctx_MixedAuthRequest);
m_clientContext.AuthenticationMode = ClientAuthenticationMode.Default;
m_clientContext.Credentials = new NetworkCredential(uname, pwd);
Web m_currentWeb = m_clientContext.Web;
m_clientContext.Load(m_currentWeb);
m_clientContext.ExecuteQuery();
}
private void ctx_MixedAuthRequest(object sender, WebRequestEventArgs e)
{
try
{
//Add the header that tells SharePoint to use Windows authentication.
e.WebRequestExecutor.RequestHeaders.Add(
"X-FORMS_BASED_AUTH_ACCEPTED", "f");
}
catch (Exception ex)
{
MessageBox.Show("Error setting authentication header: " + ex.Message);
}
}
here is the article: https://msdn.microsoft.com/en-us/library/office/hh124553(v=office.14).aspx

Categories

Resources