I've been trying to get the name and only the name.
Like this shows everything:
fb.GetAsync("me", (val) =>
{
if (val.Error == null)
{
var result = (IDictionary<string, object>)val.Result;
Dispatcher.BeginInvoke(() => InfoBox.ItemsSource = result);
}
else
{
// TODO: Need to let the user know there was an error
//failedLogin();
}
});
So how do I just get the name?
regards
Even
I'm JeongSeop Kim. Korean.
You can access infomation by using Dispatcher.BeginInvoke() func.
for example.
Dispatcher.BeginInvoke(() => firstNameTxtBlock.Text = result["first_name"].ToString());
Maybe you can see:)
Good Lock!
Related
I have the following code I am working on. This is implemented on a Vue app and uses a number of methods which each return with an Axios promise. I am trying to chain these so when a new review is submitted, the server checks if a movie exists already. If not, it creates a new movie. Then it should create a new review using postReview with a parameter of movieId. A movieId is required to create a new review. The methods checkMovieExists() and postMovie() both return a movieId as a response.
The problem is that when I log x.data() or y.data() into the console, the movieId is displayed correctly. However, if I assign x.data or y.data to movieId, it is undefined. This means I can't use it as a parameter to post a movie.
submit() {
let movieId = 0;
this.checkMovieExists(this.movie.imdb_id)
.then((x) => {
console.log(x.data);
if (x.data == 404) {
this.postMovie(this.movie.imdb_id, this.movie.original_title).then(
(y) => {
console.log(y.data); //Displays correctly
movieId = y.data;
console.log(movieId); //Displays as undefined
}
);
} else {
movieId = x.data;
}
})
.then(this.postReview(movieId));
},
(Btw, I am aware of the bug where a movie id is 404. This is my next task!)
I would advise you to stay away from callback hell and to use async/await.
async submit() {
let movieId = 0;
const checkMovieResponse = await this.checkMovieExists(this.movie.imdb_id);
if (checkMovieResponse.data == 404) {
const postMovieResponse = await this.postMovie(this.movie.imdb_id, this.movie.original_title);
movieId = postMovieResponse.data;
}
else {
movieId = checkMovieResponse.data;
}
await this.postReview(movieId);
}
Your problem should be fixed with my solution (there was an asynchronous issue with your code).
Your postMovie callback was executed after your checkMovie callback (causing an "undefined" (should be 0 by just reading your code) movieId in your postReview method).
If for some reasons, you cannot use async/await, here is your "fixed" code:
submit() {
this.checkMovieExists(this.movie.imdb_id)
.then((x) => {
if (x.data == 404) {
this.postMovie(this.movie.imdb_id, this.movie.original_title).then(
(y) => {
this.postReview(y.data)
}
);
} else {
this.postReview(x.data);
}
});
}
By the way, if the data from your Axios response is a number (for your identifier), I would advise you to use the === operator instead of the ==.
Good luck with your project!
Inspired by Akavache I am trying to create a solution that provides me with an IObservable<IArticle>. The method essentially first try to get all the articles that are present in the database, then it tries to fetch updated articles from the webservice and as it is getting the latest articles from webservice it tries to save them back to the database.
Since the webservice is essentially a cold observable and I don't want to subscribe twice, I used Publish to connect to it. My understanding is that I am using the correct version of the Publish method, however, many times the method tend to miss first couple of Articles from the GetNewsArticles. This was observed through the UI and also the Trace calls added in the call below.
Apart from solving the problem, it would be great to also understand how to debug/test this code (apart from introducing DI to inject NewsService).
public IObservable<IArticle> GetContents(string newsUrl, IScheduler scheduler)
{
var newsService = new NewsService(new HttpClient());
scheduler = scheduler ?? TaskPoolScheduler.Default;
var fetchObject = newsService
.GetNewsArticles(newsUrl,scheduler)
.Do(x => Trace.WriteLine($"Parsing Articles {x.Title}"));
return fetchObject.Publish(fetchSubject =>
{
var updateObs = fetchSubject
.Do( x =>
{
// Save to database, all sync calls
})
.Where(x => false)
.Catch(Observable.Empty<Article>());
var dbArticleObs = Observable.Create<IArticle>(o =>
{
return scheduler.ScheduleAsync(async (ctrl, ct) =>
{
using (var session = dataBase.GetSession())
{
var articles = await session.GetArticlesAsync(newsUrl, ct);
foreach (var article in articles)
{
o.OnNext(article);
}
}
o.OnCompleted();
});
});
return
dbArticleObs // First get all the articles from dataBase cache
.Concat(fetchSubject // Get the latest articles from web service
.Catch(Observable.Empty<Article>())
.Merge(updateObs)) // Update the database with latest articles
.Do(x => Trace.WriteLine($"Displaying {x.Title}"));
});
}
UPDATE - Added GetArticles
public IObservable<IContent> GetArticles(string feedUrl, IScheduler scheduler)
{
return Observable.Create<IContent>(o =>
{
scheduler = scheduler ?? DefaultScheduler.Instance;
scheduler.ScheduleAsync(async (ctrl, ct) =>
{
try
{
using (var inputStream = await Client.GetStreamAsync(feedUrl))
{
var settings = new XmlReaderSettings
{
IgnoreComments = true,
IgnoreProcessingInstructions = true,
IgnoreWhitespace = true,
Async = true
};
//var parsingState = ParsingState.Channel;
Article article = null;
Feed feed = null;
using (var reader = XmlReader.Create(inputStream, settings))
{
while (await reader.ReadAsync())
{
ct.ThrowIfCancellationRequested();
if (reader.IsStartElement())
{
switch (reader.LocalName)
{
...
// parsing logic goes here
...
}
}
else if (reader.LocalName == "item" &&
reader.NodeType == XmlNodeType.EndElement)
{
o.OnNext(article);
}
}
}
o.OnCompleted();
}
}
catch (Exception e)
{
o.OnError(e);
}
});
return Disposable.Empty;
});
}
UPDATE 2
Sharing the link to source code here.
There's a few things I don't like about your code. I assume NewsService is an IDisposable as it takes an HttpClient (which is disposable). You're not doing a proper clean up.
Also, you haven't provided a complete method - because you've tried cutting it down for the question - but that makes it hard to reason about how to rewrite the code.
That said, the one thing that sticks out to me as quite horrid looking is the Observable.Create. Can you please try this code instead and see if it helps things work for you?
var dbArticleObs =
Observable
.Using(
() => dataBase.GetSession(),
session =>
from articles in Observable.FromAsync(ct => session.GetArticlesAsync(newsUrl, ct))
from article in articles
select article);
Now, if that does, try rewriting fetchObject to use the same Observable.Using when newing up the `NewService.
In any case, it would be good if you could provide a complete implementation of GetContents, NewsService and your dataBase code in your question.
I created a kick command with reason, but it doesn't kick the member, I don't have any errors...
Also, why when I send the command, it deletes it?
I tried to fix it myself, but still doesn't work. Thanks for your help.
Here my code:
client.on('message', message => {
if(message.content.startsWith(prefix + "kick")) {
if(message.channel.type === 'DM') {
message.channel.send('This command can use only in guide');
return;
};
if(!message.member.hasPermission('KICK_MEMBERS')) {
const KickEmbed = new Discord.MessageEmbed()
.setColor("YELLOW")
.setAuthor(message.author.username)
.setDescription("Sorry, but you don't have the permission to use the kick command.")
message.channel.send(KickEmbed);
return;
};
let mentionMember = message.mentions.members.first();
if(!mentionMember) {
const ErrEmbed = new Discord.MessageEmbed()
.setColor('YELLOW')
.setAuthor(message.author.username)
.setDescription('**Usage:** `y!kick <#user> or ID` You need to mention an user!')
message.channel.send(ErrEmbed);
return;
};
let args = message.content.slice(prefix.length).trim().split(/ +/g);
if(!args.lenght) {
const ReasonError = new Discord.MessageEmbed()
.setColor('YELLOW')
.setAuthor(message.author.username)
.setDescription('Before kicking this member, you need to provide a reason of your kick.')
message.channel.send(ReasonError)
return;
};
let authorHighestRole = message.member.roles.highest.position;
let mentionHighestRole = mentionMember.roles.highest.position;
if(mentionHighestRole >= authorHighestRole) {
message.channel.send('You can`t kick members with equal or higher position');
return;
};
if(!mentionMember.kickable) {
message.channel.send('I have no permissions to kick this user');
return
};
mentionMember.kick()
.then(() => message.channel.send(`Kicked ${mentionMember.tag} with reason: ${args}`))
.catch(console.error);
}
}
);
Should look at docs before posting:
https://discord.js.org/#/docs/main/stable/class/GuildMember?scrollTo=kick
But anyways:
<Member>.kick(Reason), it's just a string you pass in.
Also args looks like an array so you can't just use args inside of a string, try args.join(" "). (Inside of message.channel.send("Kicked..."))
All in all here's the change:
So mentionMember.kick() => mentionMember.kick(args.join(" "))
I have a problem with saving default photo in my mongodb. User can upload photo and it's saving in db with no problems. But I want to add a default photo, when user didn't upload his photo.
This is the part of code I added:
busboy.on('file', (fieldname, file, filename, encoding, mimetype) => {
console.log("file");
defaultPhoto = false;
file.pipe(fs.createWriteStream(saveTo));
newProfile.photo.contentType = mimetype;
});
busboy.on('field', (fieldname, val, fieldnameTruncated, valTruncated, encoding, mimetype) => {
if(fieldname == "voice") {
newProfile.voice.data = val;
newProfile.voice.contentType = 'audio/webm';
} else {
newProfile[fieldname] = val;
}
});
busboy.on('finish', () => {
if(defaultPhoto) {
newProfile.photo.contentType = 'image/png';
newProfile.photo.data = fs.readFileSync(path.join(__dirname + '/../images/', "profile-default.png"));
} else {
newProfile.photo.data = fs.readFileSync(saveTo);
fs.unlink(saveTo);
}
newProfile.alias = newProfile.firstName + "" + newProfile.surname;
newProfile.alias = newProfile.alias.toLowerCase();
Profile.addProfile(newProfile, (err) => {
if(err) console.log(err);
})
With this code, uploading working ok, but when user didn't upload his photo I have error :
ValidationError: Profile validation failed: photo: Cast to Object failed for value "null" at path "photo"
Thanks for help.
Firstly, it's usually not a good idea to store images in a database for performance reasons. It would be better to store the images on your server and then store references to them in your database.
Secondly, I am guessing that this line is causing the problem:
newProfile.photo.data = fs.readFileSync(path.join(__dirname + '/../images/', "profile-default.png"));
newProfile.photo.data is getting set to null because the call to readFileSync is returning null. Check that you actually have the default profile photo stored in the directory that you are passing to it.
I have properly set firebase authentication in my app for Facebook and twitter but I have a problem.
Once an user is connected, if he decides to logout and enter with a different credentials he can't do it. Indeed if he tries to logout again with Facebook the system doesn't ask his username and password but uses credentials inserted before.
I tried with rememberMe option but it didn't solve the problem.
Can someone help me?
I strictly followed the example that can be found here: https://www.firebase.com/docs/security/simple-login-overview.html
Any way i modified it a little bit for doing some check.
Here is the code I'm using
firebaseRef = new Firebase('https://cicero.firebaseio.com');
authClient = new FirebaseAuthClient(firebaseRef, function(error, user) {
if (error) {
/*login error*/
switch(error.code) {
case 'INVALID_EMAIL':
case 'INVALID_PASSWORD':
EventDispatcher.trigger("login_error","invaild user or email");
break;
case 'INVALID_USER':
EventDispatcher.trigger("login_error","user does not exist.");
break;
case 'UNKNOWN_ERROR':
EventDispatcher.trigger("login_error","unknown error, please contact event administrator.");
}
} else if (user) {
/*user si logga*/
cicero_user = user;
var users = new Users();
users.firebase.on('value',function(){
if(cicero_user.provider == 'password'){
var user = users.findWhere({id: cicero_user.id, type:'password'});
cicero_user.displayName = user.get('name');
alert(cicero_user.displayName);
} else {
var social_user = users.findWhere({id: cicero_user.id,type: cicero_user.provider});
if(social_user == undefined){
var new_social_user = new User({id: cicero_user.id, name: cicero_user.displayName, type: cicero_user.provider});
users.add(new_social_user);
}
}
Ciceronotifier.on();
EventDispatcher.trigger("hide_spinner");
Backbone.history.navigate("map", {trigger: true});
},this);
} else {
/*user si slogga*/
cicero_user = undefined;
firebaseRef.unauth(); <-- i have added these two lines right now but the problem seems unresolved
firebaseRef = new Firebase('https://cicero.firebaseio.com');
Backbone.history.navigate("login", {trigger: true});