EWS: How can I know who created a meeting in the conference rooms calendar directly? - powershell-2.0

When an user creates a meeting directly in the calendar of a conference room, the organizer field is set as the room's name(Not has the user who has created the meeting).
Is it possible to get the name of the user who has created the meeting using EWS 2010?.

If you check the Sender Extended properties that should show the creators name (while send on behalf would be the Mailbox name) e.g.
Mailbox MeetingRoom = new Mailbox("room#domain.com");
FindItemsResults<Appointment> appts = service.FindAppointments(new FolderId(WellKnownFolderName.Calendar,MeetingRoom),new CalendarView(DateTime.Now,DateTime.Now.AddMonths(1),1000));
ExtendedPropertyDefinition PR_SENDER_EMAIL_ADDRESS_W = new ExtendedPropertyDefinition(0x0C1F,MapiPropertyType.String);
ExtendedPropertyDefinition PR_SENDER_ADDRTYPE_W = new ExtendedPropertyDefinition(0x0C1E,MapiPropertyType.String);
PropertySet psProps = new PropertySet();
psProps.Add(PR_SENDER_ADDRTYPE_W);
psProps.Add(PR_SENDER_EMAIL_ADDRESS_W);
if(appts.Items.Count > 0){
service.LoadPropertiesForItems(from Item item in appts select item,psProps);
foreach(Appointment apt in appts){
Object SenderAddressType = null;
Object SenderAddress = null;
if(apt.TryGetProperty(PR_SENDER_ADDRTYPE_W,out SenderAddressType)){
if(apt.TryGetProperty(PR_SENDER_EMAIL_ADDRESS_W,out SenderAddress)){
if(SenderAddressType.ToString() == "EX")
{
NameResolutionCollection nccol = service.ResolveName(SenderAddress.ToString(),ResolveNameSearchLocation.DirectoryOnly,true);
if(nccol.Count == 1){
Console.WriteLine(nccol[0].Mailbox.Address);
}
}
else
{
Console.WriteLine(SenderAddress);
}
}
}
}
}

Related

How can I remove members from TFS groups programmatically in c#?

I have access to TFS users. I can get them into list but need to remove some of them from all the groups in our TFS. I've done so many researchers so far. Simply, I need to remove user from TFS groups.
I am open to any suggestions. Even for the crazy ones!
I've tried programmatical stuff. Don't have any clue.
After so many tries, finally got somewhere. My final code:
bool isError = false;
TeamFoundationIdentity memberId = ims.ReadIdentity(IdentitySearchFactor.DisplayName, id.DisplayName, MembershipQuery.Expanded, ReadIdentityOptions.None);
IIdentityManagementService2 ims2 = tcs.GetService<IIdentityManagementService2>();
string group = "Confidential Group;
TeamFoundationIdentity groupId = ims2.ReadIdentity(group);
if (groupId == null)
{
isError = true;
}
if (memberId == null)
{
isError = true;
}
if (!isError)
{
ims2.RemoveMemberFromApplicationGroup(groupId.Descriptor, memberId.Descriptor);
}
The error:
'TF50621: The Team Foundation group that you wish to manage is not owned by service host TEAM FOUNDATION, it is owned by . Please target your request at the correct host.'**
Check out the Azure Boards Team Tools.
It does most of what you need already:
message = string.Empty;
bool ret = true;
TeamFoundationTeam t = this.teamService.ReadTeam(this.projectInfo.Uri, team, null);
TeamFoundationIdentity i = this.identityManagementService.ReadIdentity(IdentitySearchFactor.AccountName, user, MembershipQuery.Direct, ReadIdentityOptions.None);
if (t == null)
{
message = "Team [" + team + "] not found";
ret = false;
}
if (i == null)
{
message = "User [" + user + "] not found";
ret = false;
}
if (ret)
{
this.identityManagementService.RemoveMemberFromApplicationGroup( t.Identity.Descriptor, i.Descriptor);
message = "User removed ";
}
return ret;
This function removes a user from a Team. A Team is a special kind of group, the function is easy to adapt to retrieve a Group to delete the user from though:
Replace
TeamFoundationTeam t = this.teamService.ReadTeam(this.projectInfo.Uri, team, null);
With:
string group = ...
var t = this.identityManagementService.ReadIdentity(group);
Or use the REST API :
DELETE https://vsaex.dev.azure.com/{organization}/_apis/GroupEntitlements/{groupId}/members/{memberId}?api-version=7.1-preview.1

Update Contact using Microsoft Graph Client Library

How do you update a Contact using the Microsoft Graph Client Library (v1.5)? I cannot find any documentation on the project page or via Google.
In the sample code below I want to set the SpouseName for all Contacts to "Single". I have no idea how to commit the change.
_graphClient = new GraphServiceClient(_Authenticator);
var request = _graphClient.Me.Contacts.Request();
var contacts = await request.GetAsync();
while (contacts.Count > 0)
{
foreach (var ct in contacts)
{
ct.SpouseName = "Single";
//
// how do you commit this change?
//
}
if (contacts.NextPageRequest != null)
{
contacts = await contacts.NextPageRequest.GetAsync();
}
else
{
break;
}
}
You use the UpdateAsync() method:
await graphClient.Me.Contacts["id"].Request().UpdateAsync(new Contact()
{
SpouseName = "Single"
});
Note that you only pass in the property you want to change. Do not pass the entire Contact object you previously retrieved.

EF4 update navigation property An entity object cannot be referenced by multiple instances of IEntityChangeTracker

I am trying to implement a let's say "change my account email address" fonctionality.
I want to keep backup of all user emails in (R_EmailAddressHistory table).
Here are some of my project's code.
public bool ChangeEmailAddress(string username, string newEmailAddress, string callbackUrl)
{
DateTime currentUtcTime = DateTime.UtcNow;
R_User currentUser = UserRepo.GetSingle(whereCondition: w=>w.Username == username);
currentUser.UpdateDate = currentUtcTime;
if (currentUser.HasPendingNewEmail)
{
R_EmailAddressHistory currentPendingRequest = EmailHistoRepo.GetSingle(whereCondition: w => w.StatusID == (int)Reno.Common.Enums.RecordStatus.Pending && w.R_User.GId == currentUser.GId);
currentPendingRequest.NewEmail = newEmailAddress;
currentPendingRequest.UpdateDate = currentUtcTime;
EmailHistoRepo.Update(currentPendingRequest);
}
else
{
currentUser.HasPendingNewEmail = true;
R_EmailAddressHistory newEmail = new R_EmailAddressHistory();
newEmail.UserId = currentUser.GId;
newEmail.R_User = currentUser;
newEmail.NewEmail = newEmailAddress;
newEmail.InsertDate = currentUtcTime;
newEmail.StatusID = (int) Reno.Common.Enums.RecordStatus.Pending;
currentUser.R_EmailAddressHistory.Add(newEmail);
}
IdentityResult idtResult = UserRepo.Update(currentUser);
if(idtResult == IdentityResult.Succeeded)
{
//Send notification to current email address for validation before proceeding change email process
bool sendResult = Communication.EmailService.SendChangeEmailValidation(username,currentUser.Email, newEmailAddress, callbackUrl);
return sendResult;
}
else
{
return false;
}
}
The previous method is use to change an email address. Each of my tables (R_User and EmailAddressHistory ) has Repository (UserRepo and EmailHistoRepo). The implement the same IRepositoryBase class, here is the Update methode
public IdentityResult Update(T entity)
{
try
{
if (_currentContext.DbContext.Entry(entity).State == EntityState.Detached)
{
_currentContext.DbContext.Set<T>().Attach(entity);
}
_currentContext.DbContext.Entry(entity).State = EntityState.Modified;
return IdentityResult.Succeeded;
}
catch
{
return IdentityResult.Failed;
}
}
When a user has already a non validate new email address, when he request to change his current email address, I show him the pending new email address and he can change it, in this case I whant to update my historical table instead of creating a new one, cause only one pending new email address is allow. In such a case, my code failed in the line EmailHistoRepo.Update(currentPendingRequest) throwing the error : An entity object cannot be referenced by multiple instances of IEntityChangeTracker.
Can anyone help me?
Thanks
EDIT
I am using MVC(4) with a unitOfWork. My UOW is initialized in a the Controller the first time the DB is queried and the Commit is done in the global.asax file in Appalication_EndRequest (see below).
protected void Application_EndRequest(Object sender, EventArgs e)
{
CommitChanges();
}
private void CommitChanges()
{
Reno.BLL.Services.Singleton.UnitOfWork unitOfWork = Reno.BLL.Services.Singleton.UnitOfWork.GetCurrentInstance(false);
if (unitOfWork != null)
{
unitOfWork.Commit();
unitOfWork.Dispose();
}
}
Your currentUser is modified before updating the emailaddress. Save the changes to currentUser first.
Something like this:
R_User currentUser = UserRepo.GetSingle(whereCondition: w=>w.Username == username);
currentUser.UpdateDate = currentUtcTime;
bool pendingNewEmail = currentUser.HasPendingNewEmail;
UserRepo.Update(currentUser);
if (pendingNewEmail)
{
R_EmailAddressHistory currentPendingRequest = EmailHistoRepo.GetSingle(whereCondition: w => w.StatusID == (int)Reno.Common.Enums.RecordStatus.Pending && w.R_User.GId == currentUser.GId);
currentPendingRequest.NewEmail = newEmailAddress;
currentPendingRequest.UpdateDate = currentUtcTime;
EmailHistoRepo.Update(currentPendingRequest);
}
else
I finally found the answer. The problem was that when I first get the user in line
R_User currentUser = UserRepo.GetSingle(whereCondition: w=>w.Username == username);
The currentUser variable hold a refrence of all of its R_EmailAddressHistory.
And then after, I queried the DB (2nd time) to get the pending email change request (or type R_EmailAddressHistory) to modify its new email and its update date, in line
R_EmailAddressHistory currentPendingRequest = EmailHistoRepo.GetSingle(whereCondition: w => w.StatusID == (int)Reno.Common.Enums.RecordStatus.Pending && w.R_User.GId == currentUser.GId);
currentPendingRequest.NewEmail = newEmailAddress;
currentPendingRequest.UpdateDate = currentUtcTime;
But te last code updates only currentPendingRequest while another reference of the same object which is in currentUser.R_EmailAddressHistory is not update and was already tracked by the context. Therefore, by doing an update on the new instance (EmailHistoRepo.Update(currentPendingRequest)), the code failed: the same object if referenced in 2 places.
So, the solution was (the only thing I modified):
R_User currentUser = UserRepo.GetSingle(whereCondition: w=>w.Username == username);
currentUser.UpdateDate = currentUtcTime;
if (currentUser.HasPendingNewEmail)
{
R_EmailAddressHistory currentPendingRequest = currentUser.R_EmailAddressHistory.Where(h => h.StatusID == (int)Reno.Common.Enums.RecordStatus.Pending).First(); // EmailHistoRepo.GetSingle(whereCondition: w => w.StatusID == (int)Reno.Common.Enums.RecordStatus.Pending && w.R_User.GId == currentUser.GId);
currentPendingRequest.NewEmail = newEmailAddress;
currentPendingRequest.UpdateDate = currentUtcTime;
}
I decided to modify the instance in currentUser variable.

How to create an ad-hoc email and send it using Acumatica

In Acumatica you can use notifications to automate some emails.
In my scenario, we are creating a process that will at non-specific (non-set) times need to send an email when a specific condition is triggered, such as an employee needs to know they need to do something.
We are building this logic into the system and I am looking for a code sample of how to send the email when this happens.
We will be using an email template, but need to accomplish the feat in code.
I would hope there should be some kind of acumatica email class where we could just call it and pass the required info something like:
PX.Common.email.Send(params)...
Any example code would be appreciated.
It turns out that there is a KB article that gives an example of how to do this.
for our scenario, Here is a more recent version of the code that has been verified to send an email using either of 2 email templates.
private void mSendEmail(string toEmail, int? emailTemplateID, long? noteid, string source, string toDisplayName)
{
bool sent = false;
string sError = "Failed to send E-mail.";
POOrder porec = poOrder.Select(noteid);
EPExpenseClaim eprec = epExpense.Select(noteid);
try
{
Notification rowNotification = PXSelect<Notification,
Where<Notification.notificationID, Equal<Required<Notification.notificationID>>>>.Select(this, emailTemplateID);
if (rowNotification == null)
throw new PXException(PXMessages.Localize("Notification Template for Escalation is not specified."));
if (String.IsNullOrEmpty(toEmail))
throw new PXException(PXMessages.Localize("E-mail is not specified for Escalation Employee. Name=[" + toDisplayName +"]"));
if (source == "PO")
{
var sender = TemplateNotificationGenerator.Create(porec, rowNotification.NotificationID.Value);
sender.MailAccountId = rowNotification.NFrom.HasValue ?
rowNotification.NFrom.Value :
PX.Data.EP.MailAccountManager.DefaultMailAccountID;
sender.To = toEmail;
IEnumerable<EPActivity> epActivityArray = sender.Send();
if (epActivityArray.Count() > 0)
{ sent = true; }
}
if (source == "EP")
{
var sender = TemplateNotificationGenerator.Create(eprec, rowNotification.NotificationID.Value);
sender.MailAccountId = rowNotification.NFrom.HasValue ?
rowNotification.NFrom.Value :
PX.Data.EP.MailAccountManager.DefaultMailAccountID;
sender.To = toEmail;
IEnumerable<EPActivity> epActivityArray = sender.Send();
if (epActivityArray.Count() > 0)
{ sent = true; }
}
}
catch (Exception Err)
{
sent = false;
sError = Err.Message;
}
if (!sent)
throw new PXException(PXMessages.Localize(sError));
}
Here I want to present shorter version of sending email:
using PX.Objects.EP;
using PX.Data.EP;
**...**
var sender = new NotificationGenerator
{
To = "someone#example.com",
Subject = $"Subject information {DateTime.Now:d}",
Body = "Body of message",
BodyFormat = EmailFormatListAttribute.Text
};
sender.Send();

Get all clientID from MCC adwords account by adwordsAPI

I want to retrieve all clientID from my MCC account. I'm using this code
AdWordsUser user = new AdWordsUser(adwordsPropertyService.getEmail(), adwordsPropertyService.getPassword(),
null, adwordsPropertyService.getUseragent(), adwordsPropertyService.getDeveloperToken(),
adwordsPropertyService.getUseSandbox());
InfoServiceInterface infoService = user.getService(AdWordsService.V201109.INFO_SERVICE);
InfoSelector selector = new InfoSelector();
selector.setApiUsageType(ApiUsageType.UNIT_COUNT_FOR_CLIENTS);
String today = new SimpleDateFormat("yyyyMMdd").format(new Date());
selector.setDateRange(new DateRange(today, today));
selector.setIncludeSubAccounts(true);
ApiUsageInfo apiUsageInfo = infoService.get(selector);
for (ApiUsageRecord record : apiUsageInfo.getApiUsageRecords()) {
......
But apiUsageInfo.getApiUsageRecords return my only some clientId.
Have you any suggests?
My Answer will be helpful for PHP Developers
I am using v201502(php), You will get all account details from ManagedCustomerService api. Please refer the following URL https://developers.google.com/adwords/api/docs/reference/v201502/ManagedCustomerService
This is the sample code i used,
function DisplayAccountTree($account, $link, $accounts, $links, $depth) {
print str_repeat('-', $depth * 2);
printf("%s, %s\n", $account->customerId, $account->name);
if (array_key_exists($account->customerId, $links)) {
foreach ($links[$account->customerId] as $childLink) {
$childAccount = $accounts[$childLink->clientCustomerId];
DisplayAccountTree($childAccount, $childLink, $accounts, $links,
$depth +1);
}
}
}
function GetAccountHierarchyExample(AdWordsUser $user) {
// Get the service, which loads the required classes.
$user->SetClientCustomerId('xxx-xxx-xxxx');
$managedCustomerService =
$user->GetService('ManagedCustomerService');
// Create selector.
$selector = new Selector();
// Specify the fields to retrieve.
$selector->fields = array('CustomerId', 'Name');
// Make the get request.
$graph = $managedCustomerService->get($selector);
// Display serviced account graph.
if (isset($graph->entries)) {
// Create map from customerId to parent and child links.
$childLinks = array();
$parentLinks = array();
if (isset($graph->links)) {
foreach ($graph->links as $link) {
$childLinks[$link->managerCustomerId][] = $link;
$parentLinks[$link->clientCustomerId][] = $link;
}
}
// Create map from customerID to account, and find root account.
$accounts = array();
$rootAccount = NULL;
foreach ($graph->entries as $account) {
$accounts[$account->customerId] = $account;
if (!array_key_exists($account->customerId, $parentLinks)) {
$rootAccount = $account;
}
}
// The root account may not be returned in the sandbox.
if (!isset($rootAccount)) {
$rootAccount = new Account();
$rootAccount->customerId = 0;
}
// Display account tree.
print "(Customer Id, Account Name)\n";
DisplayAccountTree($rootAccount, NULL, $accounts, $childLinks, 0);
} else {
print "No serviced accounts were found.\n";
}
}
GetAccountHierarchyExample($user);
SetClientCustomerId will be the parent ID of your all accounts, It will be appeared near the Sign Out button of you google AdWords account, Please see the attached image
I hope this answer will be helpful, Please add your comments below if you want any further help
If you need just the list of clientCustomerIds, try ServicedAccountService.
Here is a code example that shows how this may be done.
Next time, you might also want to consider asking the question on the official forum for AdWords API: https://groups.google.com/forum/?fromgroups#!forum/adwords-api

Resources