Updating Exchange contact group upon contact deletion - contacts

I use contact groups with members from a contact list.
Whenever a contact in the contact list is deleted, this previously-added member still exists in the contact group until I hit "update now" in Outlook where the contact group is open for editing. Then a pop-up comes up asking whether I want to delete the no-longer-existing member.
Since I use multiple contact groups I do not want to update each of them individually but with a background job based on the EWS managed API. Thus far I have managed to select each contact group, display members' email addresses, but I do not know how to accomplish this "update now" button-function of outlook! The ordinary update method with AlwaysOverwrite works, but does not do what I want: delete the nonexistent contacts.
(By the way, the contact groups / contact lists reside in public folders.)

EWS doesn't expose that functionality. Essentially, Outlook tries to retrieve the contact by Entry ID, and when it fails, it prompts you to remove it. You could implement something similar (get each email address, try to resolve it back to a contact, etc).

## $service excahnge service referend
## $folder .. ExchangeFolder where group and contacts are
## $group ... instance of contact group
$members = $service.ExpandGroup($group.id)
for($l=0;$l -lt $members.members.count;$l++) {
$curMember = $members.members[$l]
$objViewUser = New-Object Microsoft.Exchange.WebServices.Data.ItemView(1)
$curEmail = $members.members[$l].address
## check if there still exists a contact with this email-address
$searchFilterEA1 = New-Object Microsoft.Exchange.WebServices.Data.SearchFilter+ContainsSubstring([Microsoft.Exchange.WebServices.Data.ContactSchema]::EmailAddress1,$curEmail)
$resultContact = $folder.FindItems($searchFilterEA1,$objViewUser).Items.Count
if ($resultContact -eq 0) {
"delete Contact $curEmail"
???????
}
}
}

Related

delete phone number using ews

I want to manage mailbox contacts in Exchange online using EWS 2.2 in PowerShell. I am able to create, delete and modify (most of the properties)
But I can not set any PhoneNumber (BusinessPhone, MobilePhone, HomePhone) to an empty value. Tried $updateItem.PhoneNumbers[[Microsoft.Exchange.WebServices.Data.PhoneNumberKey]::BusinessPhone] = $null;
and a lot of variations. Always get: "An object within a change description must contain one and only one property to modify."
I saw this post and using the code from there does not create any error message, but the phone number also isn't empty: EWS Delete PhoneNumber Entry on Contact
Any ideas how to set these field empty?

Get user's AD role without using Remote Server Administration Tools

I'm trying to write a powershell command that checks to see if a user is part of an AD Group, however, I don't want to use the RSAT modules, as this may end up being a logon script (and we don't want users having those modules installed). This did lead me to this question, Search AD with PowerShell without using AD module (RSAT), however, I can't figure out how to filter the results check it the value is in there.
For example, the below does return a list of users, in LDAP form, for the group IT, but how do I then check a specific user (with their Username, not display name) is in there?
([System.DirectoryServices.DirectorySearcher]"(&(objectCategory=group)(name=IT))").FindOne().Properties["Member"]
FindOne() despite what it says as well, returns multiple rows; in fact FindAll() and FindOne() both return the same results.
Should I be using a different command to search AD? Specifically I want to either check an AD group contains a user (the current user), or the inverse, check a user (the current user) is a member of a particular AD group.
You can do it that way if you really need to (and I can help you do it that way if you really need) but if you are going to be running this script under the credentials of the user you are interested in, then you can get all the groups from the user's login token. That already contains a recursive list of all security groups that the user is in. (It won't include groups where the 'Group type' is "Distribution")
The login token contains a list of SIDs, so the absolute fastest way is to compare using the SID of the group you are interested in, since it won't have to make any network request at all. That's especially convenient for laptop users who may not be online when they login - your script would still work.
$currentIdentity = [Security.Principal.WindowsIdentity]::GetCurrent()
if ($currentIdentity.Groups.Where({$_.Value -eq "S-1-1-0"}, "First")) { #Is in "Everyone"?
"Yes"
} else {
"No"
}
To find the SID of a group, use this:
(Get-ADGroup "GroupName").SID.Value
Then copy/paste that value into the script.
If you would prefer to use the name of the group in the script, then you can convert it to a WindowsPrincipal and use IsInRole. However, this will need to make a network request to find the group by its name.
$currentIdentity = [Security.Principal.WindowsIdentity]::GetCurrent()
$currentPrincipal = New-Object System.Security.Principal.WindowsPrincipal($currentIdentity)
if ($currentPrincipal.IsInRole("Everyone")) {
"Yes"
} else {
"No"
}

Get Website Permission with Powershell

I am trying to figure out how to get the well known Website Permission Lists with Powershell. I tried several methods. The best solution seems to me to try something like $spWeb.RoleAssignments but this delivers me not only the users and groups with ist permissions on the spweb. I also get the roleassignments from the unique lists and libraries on the website.
Do you have suggestions how can I filter to check if a user has, for example, read permission on the spweb (without regarding the lists and subwebs)?
My target is to check the spweb and ist subwebs and unique lists and libraries step by step for a user(group) like "NT AUTHORITY\Authenticated Users". Then I want to remove the roleassignment and add a new roleassignment with a group of my colleagues, so that not everybody can see the content. The uniqe permission structure should remain.
You could check if a user has specific permission level using SPWeb.DoesUserHavePermissions method:
public bool DoesUserHavePermissions(
string login,
SPBasePermissions permissionMask
)
SPWeb.DoesUserHavePermissions method (String, SPBasePermissions)
using (SPSite site = new SPSite("http://sp/"))
{
using (SPWeb web = site.OpenWeb())
{
// Make sure the current user can enumerate permissions.
if (web.DoesUserHavePermissions(SPBasePermissions.EnumeratePermissions))
{
// Specify the permission to check.
SPBasePermissions permissionToCheck = SPBasePermissions.ViewListItems;
Console.WriteLine("The following users have {0} permission:", permissionToCheck);
// Check the permissions of users who are explicitly assigned permissions.
SPUserCollection users = web.Users;
foreach (SPUser user in users)
{
string login = user.LoginName;
if (web.DoesUserHavePermissions(login, permissionToCheck))
{
Console.WriteLine(login);
}
}
}
}
}
Console.ReadLine();

Get sender email address in Infopath

I have a form sent by email that travels through different persons like this.
Person A --> Person B --> Person C
I want the person A to be informed when the form is treated by person C. So Person A needs to be in copy of the email sent by person B.
Because person A isn't always the same one, I think the best way to put him/her in copy is to use the "from" field of the email received by person B and to put it in copy.
But how can I find this address with infopath and how can I place it into my email data connection ?
I had this same question today myself and could not find much in the way of answers.
So... I did some work myself and came up with a few solutions.
First I don't believe there is any way to get/set the "From" address using the InfoPath OM. This means you will have to use one of the following options:
No Code:
You will be limited to providing a field on the form where "Person A" can put their email address and use this in the CC. for subsequent stages. That's kind of the only way and while it an extra burden to the user it does have the benefit of providing flexibility.
Code:
Write your own code to send the mail using Outlook Interop or System.Net.Mail and then you will be setting all of the addresses manually anyway.
If you are using AD or something else then you could always get the email address of the current use using System.DirectoryServices.AccountManagement.
Based on an assumption which I cannot find any documentation to back up. That InfoPath uses the account associated with the default store to send email using EmailSubmitConnection. You should be able to use Outlook Interop to find the address that InfoPath will use.
Here is a code sample:
using Outlook = Microsoft.Office.Interop.Outlook;
public string GetDefaultSenderAddress()
{
// This actually opens outlook in the same way as InfoPath does to send the message.
// which can be slow.
string DefaultAddress = string.Empty;
Outlook.Application OutlookApplication = new Outlook.Application();
string DefaultStoreId = OutlookApplication.Session.DefaultStore.StoreID;
foreach (Outlook.Account Account in OutlookApplication.Session.Accounts)
{
if (Account.DeliveryStore.StoreID == DefaultStoreId)
{
DefaultAddress = Account.SmtpAddress;
}
}
// Note you probably won't want to quit if you are about to send the email.
// However I have noticed that this doesn't seem to close Outlook anyway.
OutlookApplication.Quit();
return DefaultAddress;
}
You may have to provide a few more checks in case of different account types etc. But I believe it will work. (I tested it for my scenario and it does).
Note: Of course this opens an outlook instance which you will have to close as well. And it can be slow. Unless outlook is already open in which case it will be very quick. Anyhow when sending from InfoPath Outlook will have to be opened so if you do this just before sending then there should be no noticeable difference.
I would advise using a combination of the no code/with code options so provide a return address which is automatically complete to save the user time. But can be corrected if the user wishes to have the email returned to a different address of if there is a mistake.
Hope that you find that useful.

Changing the From field for an email activity in a plug-in

When an email is sent to a queue and there is a contact associated with the "From" email in CRM, upon promoting an email to an email activity the system automatically fills in the "From" field with the contact information. However, if a user with the same email exists in CRM, too, then the system always picks up the system user instead of the contact. I need to override this behaviour to ALWAYS pick up the contact if one with the email exists.
I created a post-operation plug-in (tried a pre-operation plug-in, too) for the event Create for email, trying to override the From field. The problem is, it does not work. When I debug the plug-in, it goes quietly past the assignment without any errors and then the same plug-in fires for the same email again. And again. And again.
When I try instead to create a new email and use the same ActivityList[] I was trying to use for the entity that triggered the event, it works. It seems that the problem is that CRM does not allow changing the From field from a plug-in, or am I doing something wrong? If it's a limitation enforced by CRM, is there a way around it?
My code is below:
var email = ((Entity)context.InputParameters["Target"]).ToEntity<Email>();
...
var oldFrom = ((EntityCollection)email.Attributes["from"]).Entities;
List<ActivityParty> newFrom = new List<ActivityParty>();
foreach (Entity party in oldFrom)
{
EntityReference entRef = (EntityReference)party.Attributes["partyid"];
if (entRef.LogicalName == SystemUser.EntityLogicalName)
user = userLogic.Get(new Guid(entRef.Id.ToString()));
if (user == null) return;
string emailAddress = user.InternalEMailAddress;
Contact contact = contactLogic.LookupPASIndividual("", emailAddress);
if (contact != null)
{ newFrom.Add(new ActivityParty() {PartyId = new EntityReference(Contact.EntityLogicalName, contact.ContactId.Value) });
}
else
return;
}
email.From = newFrom;
Update: So I registered the plug-in on Pre-validation now and it's not triggered when an email activity is created by a router, it IS triggered when a user creates an email in CRM though...
The problem is that you aren't changing the email which is processed at all.
var email = ((Entity)context.InputParameters["Target"]).ToEntity<Email>();
This line converts the record which is currently processed to an object of type email. You modify the record which is not in scope of the operation. You have to modify the From of the target (either directly or write it back).
For the processing stages: take a look at the Event Execution Pipeline. Pre-Validation is to early for your task. I'am not quite sure when the address resolution is done, but I would try to do your conversion Pre-Create.
I ended up using a workaround: created an async Post-Event that associates the email activity with the contact if a contact with the same email exists, leaving the user associated with the email in the "From" field.