Box API, Unable to get sharedlink of a file. Shows Bad Request Error - box-api

BoxApi.V2.BoxManager boxManager = new BoxManager(response1.Data.access_token);
var sharedLink = new SharedLink()
{
Access = Access.Open,
Permissions = new Permissions() { CanDownload = true, CanPreview = true },
UnsharedAt = DateTime.Now.AddYears(1)
};
boxManager.ShareLink(file, sharedLink);
This below code throws "Bad request" error to me, can anyone help me on this?

Can you verify what type of account you have with Box?
If you have a personal account, removing
UnsharedAt = DateTime.Now.AddYears(1)
should allow the request to work.
Expiring shared links requires an upgraded account

Related

NLog configuration from both code and config file

I have NLog code currently reading from NLog.config to set up logging to text files and then I'd like to add logging fatal errors to email. However, the email settings are in my appsettings.json file.
What I tried so far is this in my Startup.cs
var emailConfig = Configuration
.GetSection("EmailConfiguration")
.Get<EmailConfiguration>();
services.AddSingleton(emailConfig);
var mailTarget = new MailTarget()
{
SmtpServer = emailConfig.SmtpServer,
SmtpUserName = emailConfig.UserName,
SmtpPort = emailConfig.Port,
SmtpPassword = services.BuildServiceProvider().CreateScope().ServiceProvider.GetService<IEmailSender>().Decrypt(emailConfig.Password),
To = emailConfig.To
};
NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(mailTarget, LogLevel.Fatal);
However I have 2 problems when I try to _logger.Fatal("testing, please ignore");:
Under _logger.Factory.Configuration.AllTargets I now only see the mail settings I configured above, which I understand is due to SimpleConfigurator overwriting (yet I'm not sure what I need to do so that I add rather than overwrite).
I still didn't receive an email despite and I'm not sure how I can debug this now.
I fixed both issues.
var mailTarget = new MailTarget()
{
SmtpServer = emailConfig.SmtpServer,
SmtpUserName = emailConfig.UserName,
SmtpPort = emailConfig.Port,
SmtpPassword = services.BuildServiceProvider().CreateScope().ServiceProvider.GetService<IEmailSender>().Decrypt(emailConfig.Password),
From = emailConfig.UserName,
To = emailConfig.To,
EnableSsl = true,
SmtpAuthentication = SmtpAuthenticationMode.Basic,
Html = true
};
var configuration = LogManager.Configuration;
configuration.AddRuleForOneLevel(LogLevel.Fatal, mailTarget);
LogManager.ReconfigExistingLoggers();
The first problem related to the last 3 lines, whereas the second issue was related to the SMTP configuration.

GMail OAUTH not asking for permission when published

I've started using the GMail API and it's working fine on my local machine; it will open the Google permissions page and I can select my account. It then stores the return json token and only asks again if this token is removed.
When I publish to the server, the OAUTH page is never displayed and the application appears to timeout with a 'Thread was being aborted' exception.
My code;
try
{
using (var stream = new FileStream(HttpContext.Current.Server.MapPath("~/credentials/client_id.json"), FileMode.Open, FileAccess.Read))
{
string credPath = HttpContext.Current.Server.MapPath("~/credentials/gmail_readonly_token.json");
_credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
db.writeLog("INFO", "Gmail Credentials Saved","Credential file saved to: " + credPath);
}
// Create Gmail API service.
service = new GmailService(new BaseClientService.Initializer()
{
HttpClientInitializer = _credential,
});
}
catch (Exception e)
{
db.writeLog("Error", "Failure when creating Gmail class", e.Message, null, _username, null);
}
Is there something I need to change within the 'client_id.json' (formally client_secret.json) file? The only thing I have altered is the redirect_uris line.
Any other suggestions would be welcome, the only other question I could find that is similar is here but there is no answer.
Thanks,
Danny.
The first one worked because you followed the intended use case, which is client-side. But, to implement authorization on the server, follow the Implementing Server-Side AUthorization guide.

EWS error ErrorNoRespondingCASInDestinationSite

m having an issue with Office 365 EWS (its only Office 365, Exchange 2010 and 2013 work fine). I can create my pull subscription without error but when I go to use it by calling
getEvents()
I receive an error:
ErrorNoRespondingCASInDestinationSite
The following error occured while retrieving events for exchange
resource: - Exchange Web Services are not currently
available for this request because none of the Client Access Servers
in the destination site could process the request.
Here is some code snippets
Using autodiscover and setting up credentials
this.exchangeService.Credentials = new NetworkCredential(this.Username, this.Password);
try {
this.exchangeService.AutodiscoverUrl(this.Username, RedirectionCallback);
}
catch(Exception ex)
{
Logger.WriteToEventLog(EventLogEntryType.Warning, 104, "ExchangeDataAccess, AutodiscoverURL error: " + ex.Message);
}
if (exchangeService.Url == null)
{
this.ExchangeServerURL = GetOffice365EWSUrl(this.Username);
this.exchangeService.Url = new Uri(this.ExchangeServerURL);
this.exchangeService.CookieContainer = new CookieContainer();
}
Afterwhich we Login and find our exchange user that we will perform all operations under
ServicePointManager.ServerCertificateValidationCallback = (sender1, certificate, chain, errors) => true;
string username = this.Username;
if (this.authenticateContext.GetExchangeServerVersion().Contains("365"))
{
username = this.Username.Remove(this.Username.IndexOf("#"));
}
NameResolutionCollection resolveNameResult = this.exchangeService.ResolveName(username, ResolveNameSearchLocation.ContactsThenDirectory, true);
if (resolveNameResult.Count() > 0)
{
roomEmailAddress = resolveNameResult[0].Mailbox.Address;
if (!string.IsNullOrEmpty(roomEmailAddress))
{
this.ExchangeUserEmailAddress = roomEmailAddress;
logMsg.AppendLine("Logged into Exchange with " + roomEmailAddress + " successfully, RetrieveRoomsList is next");
}
}
We then get a SubscribeResponse and save it to a list
subscribeResponse = this.exchangeDataAccess.ExchangeSubscribe(syncPoint.ThirdPartyId, syncPoint.Watermark, true);
We pass the above object into a wrapper method to get all Events from the EWS
Dictionary<PullSubscription, IEnumerable<ItemEvent>> mailboxEvents = null;
GetEventsResults eventsResults = subscription.GetEvents();
if (eventsResults == null || eventsResults.ItemEvents.Count() == 0) {
return mailboxEvents;
}
mailboxEvents = new Dictionary<PullSubscription, IEnumerable<ItemEvent>>();
mailboxEvents.Add(subscription, eventsResults.ItemEvents);
return mailboxEvents;
The line that calls subscription.GetEvents() is where the exception indicated at the top is returned.
There is another layer of complexity added on because our Exchange user has a domain name of #FOOlab.onmicrosoft.com where as all of the rooms being managed have a domain name of #LAB.FOO.COM
According to the customer this is ADFS authentication, however I really don't know much about it.
I can say however that this code base did work (got events) and then something seemed to change and the error started popping up. Originally I thought the customer changed something but we have tested this against another Office 365 (without ADFS) and saw the same error, so now I don't know what to think.
The links below can explain it far better then I can, but what I have done so far which has resolved my issue is to surround the GetEvents
with the add and removal of the header data X-AnchorMailbox
MSDN Link1 Link2
public Dictionary<PullSubscription, IEnumerable<ItemEvent>> GetEvents(SyncPoint syncpoint)
{
Dictionary<PullSubscription, IEnumerable<ItemEvent>> mailboxEvents = null;
if (this.authenticateContext.GetExchangeServerVersion().Contains("365"))
{
try
{
//this is to maintain affinity (see here https://msdn.microsoft.com/en-us/library/office/dn458789(v=exchg.150).aspx)
//it was added to fix an error: The following error occured while retrieving events for exchange resource: <room address> - Exchange Web Services are not currently available for this request because none of the Client Access Servers in the destination site could process the request.
//according to docs it is only when getting notifications that its important
if (this.exchangeService.HttpHeaders.Any(m => m.Key.Equals("X-AnchorMailbox")))
{
this.exchangeService.HttpHeaders.Remove("X-AnchorMailbox");
}
this.exchangeService.HttpHeaders.Add("X-AnchorMailbox", syncpoint.ThirdPartyId); //this is the email address of the mailbox being queried
}
catch { }
}
GetEventsResults eventsResults = syncpoint.pullSubscription.GetEvents();
if (eventsResults == null || eventsResults.ItemEvents.Count() == 0)
{
return mailboxEvents;
}
mailboxEvents = new Dictionary<PullSubscription, IEnumerable<ItemEvent>>();
mailboxEvents.Add(syncpoint.pullSubscription, eventsResults.ItemEvents);
try
{
this.exchangeService.HttpHeaders.Remove("X-AnchorMailbox");
} catch { }
return mailboxEvents;
}

save Facebook information in my remote data base with titanium

I want to ask I have developed a mobile application which you can login using Facebook username and password so I want to know how can I save the username and password from Facebook into my remote database.
This is my code any help please:
var fb = require('facebook'); fb.appid = "281158112043247";
// Set the URL
fb.permissions = ['email'];
fb.authorize();
fb.addEventListener('login', function(e) {
if (e.success) {
fb.requestWithGraphPath('me', {}, 'GET', function(e) {
if (e.success) {
var data= JSON.parse(e.result);
xhr = Titanium.Network.createHTTPClient();
xhr.open("Post", "http://192.168.131.145:5220/Create.svc/createClient");
var params = {
Clientusername: data.name,
//password:password1.value,
// Clientpassword: Ti.Utils.md5HexDigest(password1.value),
Clientnom: data.name,
Clientid:data.id,
Clientemail: data.email
};
xhr.send(JSON.stringify(params));
//xhr.send(e.result);
Ti.API.info("Name:"+data.name);
Ti.API.info("email:"+data.email);
Ti.API.info("facebook Id:"+data.id);
} else if (e.error) {
alert(e.error);
} else {
alert('Unknown response.');
}
});// request graph
}else{
if(e.error){
alert(e.error);
}else{
alert("Unkown error while trying to login to facebook.");
}
}
});
You don't have access to their Facebook password. The oauth specifically protects against you having to know their access credentials. It allows Facebook to separately identify you, and what you are doing with the API. The user can also then disable your access to their data, if they see fit. But if you had their password, you could do anything that they can do, even temporarily steal their account. Plus their account would only be as secure as your storage of their password (is it encrypted? are you servers secure? on premise? compromised? running any malware?). So generally, no, it's a bad idea, don't do that, even if you figure out a way to do so.
In the case of your code above, you have already authorized the user inside your app, so you won't need to authorize them again. They'll already be logged in. You should check if (fb.loggedIn) and then do your logged-in-only code, else fb.authorize();.

Occasional (and recurrent) problems with FacebookMobile.init()

Seems this API is broken and/or abandoned because in some days, this API call always fails during a few hours. Today is happening again, but it's taking more time than previous times.
I don't know what to do. I have 2 Air apps and they aren't working today.
Any solution on this?
Here is a simple piece of code:
FacebookMobile.init(APP_ID, onInit);
private function onInit(fbSession:Object, fail:Object):void
{
if (fbSession){
trace(fbSession.accessToken);
}
else{
traceV2(fail); // it's a "deep" trace
// other API methods related to login
}
}
In FacebookMobile.init(), we have to expect for an session object (containing FB acess token), or a "fail" object.
The fail object is returning this to me:
[Object]
| [error:Object]
| code = 190
| message = Malformed access token AAAEWSUA8XjUBAJo4JuO5hUMwSnKC95LNRr1nHHIU8rwPGzxvHIuhUcDziZA9ZC3xDf4ZBwYcqjVU1ir5wf5jlEsJ5zwyMhnnWGyWxXeKQZDZD,AAAEWSUA8XjUBAJo4JuO5hUMwSnKC95LNRr1nHHIU8rwPGzxvHIuhUcDziZA9ZC3xDf4ZBwYcqjVU1ir5wf5jlEsJ5zwyMhnnWGyWxXeKQZDZD
| type = OAuthException
Thanks in advance!
Problem fixed.
The solution to this specific problem is at at com.facebook.graph.FacebookMobile:560, inside the handleLogin() function.
protected function handleLogin(result:Object, fail:Object):void {
loginWindow.loginCallback = null;
if (fail) {
loginCallback(null, fail);
return;
}
// ---------------||--------------------//
// ---------------\/--------------------//
// This line below solves this problem
result.access_token = String(result.access_token).split(',')[0];
// ---------------/\-------------------//
// ---------------||-------------------//
session = new FacebookSession();
session.accessToken = result.access_token;
session.expireDate = (result.expires_in == 0) ? null : FacebookDataUtils.stringToDate(result.expires_in) ;
if (_manageSession) {
var so:SharedObject = SharedObject.getLocal(SO_NAME);
so.data.accessToken = session.accessToken;
so.data.expireDate = session.expireDate;
so.flush();
}
verifyAccessToken();
}
Seems like its a bug with Facebook returning the Access token as an Array:
http://developers.facebook.com/bugs/276418065796236?browse=search_5034a345a2cb15e92344737
I would try edit the String that is returned by removing the second access token value in it. (Everything after the comma) and signing that to your local sessions access token variable. It might resolve the issue