Get another User events using MS Graph API - azure-active-directory

I`m using https://github.com/microsoftgraph/aspnet-snippets-sample sample to access my AD using Graph API, but I need to get events of specific user. There are only sample for getting my events:
public async Task<List<ResultsItem>> GetMyEvents(GraphServiceClient graphClient)
{
List<ResultsItem> items = new List<ResultsItem>();
// Get events.
IUserEventsCollectionPage events = await graphClient.Me.Events.Request().GetAsync();
if (events?.Count > 0)
{
foreach (Event current in events)
{
items.Add(new ResultsItem
{
Display = current.Subject,
Id = current.Id
});
}
}
return items;
}
And according to guide I should request
GET /users/{id | userPrincipalName}/calendar/events
To access another user events, but how? There is no possibility to get events from Users prop:
graphClient.Users[id].Request();
Please explain me. Every info will be usefull.

You can get to the events from the users property:
var events = await graphClient.Users[userid].Events.Request().GetAsync();

Related

How to especify a current key-node in xamarin with firebase?

I’m working with Xamarin and FireBase, I have the next problem:
I have Users in my database and each one has a list of items. I need to retrieve the list of items of the current user, and the problem is that I don’t know how to replace the key of each user in the tree, (I just hard-wrote it). This is the snippet :
var products = (await client.Child("Users").Child("-MXf6T19md1UOTVvHWRU").Child("Items")
.OnceAsync<Item>())
.Select(f => new Item
{ . . .
Here is a picture of the database tree.
How do I replace the Child("-MXf6T19md1UOTVvHWRU") by the current branch where I’m at?, taking into account that I have to access another Child next to that. Of course I have access to the Username value that is stored in preferences.
I would appreciate some enlightenment, thanks in advance.
I need to retrieve the list of items of the current user, and the problem is that I don’t know how to replace the key of each user in the tree, (I just hard-wrote it).
You could use the code below to get all the items first and then get the specific item.
public async Task<List<User>> GetAllUsers()
{
return (await firebase
.Child("Users")
.OnceAsync<User>()).Select(item => new User
{
Name = item.Object.Name,
UserId = item.Object.UserId,
}).ToList();
}
public async Task<User> GetUser(int userId)
{
var allUsers = await GetAllUsers();
await firebase
.Child("Users")
.OnceAsync<User>();
return allUsers.Where(a => a.UserId == userId).FirstOrDefault();
}
Model:
public class User
{
public int UserId { get; set; }
public string Name { get; set; }
}
You could download the similar source code from the GitHub.
https://github.com/susairajs/Xamarin-Firebase-RealtimeDatabase

Microsoft graph API: getting 403 while trying to read user groups

I am trying to get user's group information who log-Ins into the application.
Using below code, when I am hitting https://graph.microsoft.com/v1.0/users/{user}, then I am able to see that user is exist (200), but when trying to hit https://graph.microsoft.com/v1.0/users/{user}/memberOf, then I am getting 403.
private static async Task Test()
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "TOKEN HERE");
var user = "testuser#onmicrosoft.com";
var userExist = await DoesUserExistsAsync(client, user);
Console.WriteLine($"Does user exists? {userExist}");
if (userExist)
{
var groups = await GetUserGroupsAsync(client, user);
foreach (var g in groups)
{
Console.WriteLine($"Group: {g}");
}
}
}
}
private static async Task<bool> DoesUserExistsAsync(HttpClient client, string user)
{
var payload = await client.GetStringAsync($"https://graph.microsoft.com/v1.0/users/{user}");
return true;
}
private static async Task<string[]> GetUserGroupsAsync(HttpClient client, string user)
{
var payload = await client.GetStringAsync($"https://graph.microsoft.com/v1.0/users/{user}/memberOf");
var obj = JsonConvert.DeserializeObject<JObject>(payload);
var groupDescription = from g in obj["value"]
select g["displayName"].Value<string>();
return groupDescription.ToArray();
}
Is this something related to permission issue, my token has below scope now,
Note - Over here I am not trying to access other user/group information, only who log-ins. Thanks!
Calling /v1.0/users/[a user]/memberOf requires your access token to have either Directory.Read.All, Directory.ReadWrite.All or Directory.AccessAsUser.All and this is
documented at https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/user_list_memberof.
A great way to test this API call before implementing it in code is to use the Microsoft Graph explorer where you can change which permissions your token has by using the "modify permissions" dialog.

Swift EKCalendar not persisting

I can create a new calendar and save it with the following function:
func createCalendarForUser() {
let sourcesInEventStore = self.eventStore.sources
//works but doesn't persist
let subscribedSourceIndex = sourcesInEventStore.index {$0.title == "Subscribed Calendars"}
if let subscribedSourceIndex = subscribedSourceIndex {
let userCalendar = EKCalendar(for: .event, eventStore: self.eventStore)
userCalendar.title = "newCalendar"
userCalendar.source = sourcesInEventStore[subscribedSourceIndex]
do {
try self.eventStore.saveCalendar(userCalendar, commit: true)
print("calendar creation successful")
} catch {
print("cal \(userCalendar.source.title) failed : \(error)")
}
}
}
This functions great while the app is open and running. I can save events to them, i can see them in my local calendar, and life is good. However, once the app is terminated and goes into the background the calendars disappear, along with any events created in them. I've tried saving the calendar to different sources other then the Subscribed Calendars source but when i do that the calendars wont even save in the first place. Heres one of the attempts at using the local source:
func createCalendarForUser() {
let sourcesInEventStore = self.eventStore.sources
//never saves calendar
let localSourceIndex = sourcesInEventStore.index {$0.sourceType == .local}
if let localSourceIndex = localSourceIndex {
let userCalendar = EKCalendar(for: .event, eventStore: self.eventStore)
userCalendar.title = "newCalendar"
userCalendar.source = sourcesInEventStore[localSourceIndex]
do {
try self.eventStore.saveCalendar(userCalendar, commit: true)
print("creating new calendar successful")
} catch {
print("creating new calendar failed : \(error)")
}
}
}
I also tried this method :
func createCalendarForUser() {
let sourcesInEventStore = self.eventStore.sources
//doesnt work
let userCalendar = EKCalendar(for: .event, eventStore: self.eventStore)
userCalendar.title = "newCalendar"
userCalendar.source = sourcesInEventStore.filter{
(source: EKSource) -> Bool in
source.sourceType.rawValue == EKSourceType.local.rawValue
}.first!
do {
try self.eventStore.saveCalendar(userCalendar, commit: true)
print("creating new calendar succesful")
} catch {
print("creating new calendar failed : \(error)")
}
}
As metioned here as mentioned here https://www.andrewcbancroft.com/2015/06/17/creating-calendars-with-event-kit-and-swift/
Has anyone else come across this problem?
The blog post you link do does two things when it saves the calendar, it uses the saveCalendar(, commit) method to save the calendar to the event store, and then also saves the identifier for the calendar to user defaults so that it can be retrieved at a later time:
NSUserDefaults.standardUserDefaults().setObject(newCalendar.calendarIdentifier, forKey: "EventTrackerPrimaryCalendar")
You're doing the first, but not the second step, so your calendars will be persisting in the store, but you're not keeping the information needed to retrieve them in the future.

SocketIO syncUpdate model for different user

I have been writing an web app, where individual user will post their task and will be displayed on their news feed. I have used socket io with angular fullstack framework by yeoman.
what I am trying to do is, when user adds new data to goal model, on socketSyncUpadtes, $rootScope.getUserGoals get updated and user see new entry. but I want that to happen for each user, thats why I included userid, to make sure, it only pulls user specific data.
But in reality what is happening is, all connected user getting this socket stream and getting their model updated too, but as page refreshed it is always only what that query pulls, only user specific data.
this is how I get user specific data
$rootScope.getUserGoals = function (userid){
//get current todo task views
$http.get('/api/goals/name/'+userid).success(function(goals) {
$rootScope.userGoalArr = goals;
socket.syncUpdates('goal', $rootScope.userGoalArr);
});
};
then it displays in view with this
<ul class = "holdTaskul" ng-repeat="view in filtered = userGoalArr | orderBy:'-created'">
I looked up on google and search a lot to figure out how to separate each user socket stream and attached them to their login credential. I have come across this socket-jwt and session token. I am not expert on socket. I would much appreciate if someone could point me to right direction about this, what I am intending to do..
my socket configuration is as follows for socket.syncUpdate function
syncUpdates: function (modelName, array, cb) {
cb = cb || angular.noop;
/**
* Syncs item creation/updates on 'model:save'
*/
socket.on(modelName + ':save', function (item) {
var oldItem = _.find(array, {_id: item._id});
var index = array.indexOf(oldItem);
var event = 'created';
// replace oldItem if it exists
// otherwise just add item to the collection
if (oldItem) {
array.splice(index, 1, item);
event = 'updated';
} else {
array.push(item);
}
cb(event, item, array);
});
/**
* Syncs removed items on 'model:remove'
*/
socket.on(modelName + ':remove', function (item) {
var event = 'deleted';
_.remove(array, {_id: item._id});
cb(event, item, array);
});
},
I have also configured socket for sending auth token by this
// socket.io now auto-configures its connection when we ommit a connection url
var ioSocket = io('', {
// Send auth token on connection, you will need to DI the Auth service above
query: 'token=' + Auth.getToken(),
path: '/socket.io-client'
});
and used socketio-jwt to send the secret session to socket service by that
module.exports = function (socketio) {
socketio.use(require('socketio-jwt').authorize({
secret: config.secrets.session,
handshake: true
}));

SignalR doesn't push message to client

I am implementing functionality to notify the user of long running job completions using SignalR in an AngularJS application.I have created groups of user based on their name,so for each user a group of his name and different connectionids which he has opened up will be created and he would be notified by his group. I want to notify the user on two pages i.e. landing Page and Job Run Page as even if the user is on landing page and job run completes he should be notified of it.
For the same reason i am creating group by his name on both the pages,so that if he is on any page he would be nofied through the group.
On landing page controller js file i have written code to add the user in group as follow...
$rootScope.signalRHub = $.connection.signalRHub;
$rootScope.hubStart = null;
$rootScope.startHub = function () {
if ($rootScope.hubStart == null)
{
$rootScope.hubStart = $.connection.hub.start();
}
return $rootScope.hubStart;
}
$scope.$on('$locationChangeStart', function (event) {
if ($rootScope.userName != "") {
$rootScope.signalRHub.server.leaveGroup($rootScope.userName);
}
});
// Start the connection
$rootScope.startHub().done(function () {
$rootScope.signalRHub.server.joinGroup($rootScope.userName);
});
on Job Run controller js file i have written following code....
$rootScope.signalRHub.client.showNotification = function (message) {
notify('Your notification message');//notify is the angular js directive injected in this controller which runs fine
};
$scope.$on('$locationChangeStart', function (event) {
$rootScope.signalRHub.server.leaveGroup($rootScope.studyid);
});
// Start the connection
$rootScope.startHub().done(function () {
$rootScope.signalRHub.server.joinGroup($rootScope.userName
});
My Hub File.....
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class SignalRHub : Hub
{
public Task JoinGroup(string groupName)
{
return Groups.Add(Context.ConnectionId, groupName);
}
public Task LeaveGroup(string groupName)
{
return Groups.Remove(Context.ConnectionId, groupName);
}
public void ShowNotification(string jobRunDetailId, string userName)
{
if (!string.IsNullOrEmpty(userName))
{
var context = GlobalHost.ConnectionManager.GetHubContext<SignalRHub>();
context.Clients.Group(userName).showNotification(jobRunDetailId);
}
}
}
The issue is when i run the application the group add functionality for both pages works fine.but when i call "showNotification" from Hub it doesn't show any message.
But strange thing is if i comment the "$rootScope.startHub().done...." function on landing page then the jobrun page notify functionality works fine.I am not sure if writing "$rootScope.startHub().done()..." on two places is creating this problem.please help.
You need to wire up all callbacks before calling start. If you turn client side logging on, it'll tell you what hubs you are subscribed to.
Aside:
[EnableCors] is a webapi specific attribute that does not work in SignalR.

Resources