Check if current user is a member of exchange distribution list - Outlook C# - outlook

I want to find out if current Outlook user is a member of particular exchange distribution list. If he is, then he should see child form and if he isn't; then he should see message box.
My following code is working up to the point, if user is a member of DistList, he get child form but I don't know how to check show him message box if he isn't member.
string UserName = (string)application.ActiveExplorer().Session.CurrentUser.Name;
string PersonalPublicFolder = "Public Folders - " + application.ActiveExplorer().Session.CurrentUser.AddressEntry.GetExchangeUser().PrimarySmtpAddress;
Outlook.MAPIFolder contactsFolder = outlookNameSpace.Folders[PersonalPublicFolder].Folders["Favorites"];
Outlook.DistListItem addressList = contactsFolder.Items["ContactGroup"];
if (addressList.MemberCount != 0)
{
for (int i = 1; i <= addressList.MemberCount; i++)
{
Outlook.Recipient recipient = addressList.GetMember(i);
string contact = recipient.Name;
if (contact == UserName)
{
var assignOwnership = new AssignOwnership();
assignOwnership.Show();
}
}
}
Any help would be appreciated.
Thank you.

Use Application.Session.CurrentUser.AddressEntry.GetExchangeUser().GetMemberOfList() - it will return AddressEntries object that contains all DLs that the user is a member of.
Be prepared to handle nulls and errors.

Related

How can I check email validation in cypress

I want to check validation for input element. Can I check if typing wrong or valid Email format in my input.
Like this.
cy.get('#email_signup').type(validateEmail())
var email = "";
var possible = "abcd#.gh";
for (var i = 0; i < 10; i++)
email += possible.charAt(Math.floor(Math.random() * possible.length));
return email;
}
cy.get('.nextBtn').click();
cy.get('.error-message').should('be.visible');
According to what you expect to do, you need two external functions to create emails and to get a valid state of emails. Then you need to loop the it hook throughout all the emails.
//Create Emails
//Did a small modification so that you can decied the email length you need
const emails = (val) => {
var email = "";
var possible = "abcd#.gh";
for (var i = 0; i < val; i++){
email += possible.charAt(Math.floor(Math.random() * possible.length));}
return email;
}
//validate emails
//I have used a general Regex here, use the regex you have used in your website insted
const validateEmail = (email) => {
var re = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
return re.test(email);
}
//Test Cases (I have added 10 loops so it will create 10 test cases)
//Change the test case count as much as you need
for (let index = 0; index < 10; index++) {
const TestEmail = emails(10)
const EmailState = validateEmail(TestEmail)
it("EmailTest -"+ TestEmail +" - " + EmailState,() => {
cy.get('#email_signup').type(TestEmail)
cy.get('.nextBtn').click();
if(!EmailState){
cy.get('.error-message').should('be.visible');
}else{
cy.get('.error-message').should('not.be.visible');
}
})
}
Your method of creating emails is awesome. But make sure you add a separate test to check specific and valid scenarios as random emails might not cover them all
This is how the tests are going to look like.
Note: As I have mentioned earlier. It's always better to know your test data. So Without a random generation. Try to have a list of valid, invalid email scenarios with true false conditions And loop through them.
First of all it's good to generate random emails, but the best way to do is have a set of emails in a array. (may be in a JSON) and loop through them and check for the email validity.
Eg:
{
"Email_1":"['robot#mail.com','valid']",
"Email_2":"['robotmail.com','InValid']",
}
Because then you know the email conditions you are testing. But if you want to go with a random email generation method. I totally agree with the Muditha Perera's answer. It works perfectly.

Acumatica - How to update custom field in Customer Location from custom field in Customer

I've tried a few different ways to do this and each way has a piece of code I am just not getting right. I need to update a custom field UsrCustomerShipAccount in Customer Locations if it is updated in the Customer Delivery Tab. I tried SetValueExt and creating a graph instance. Sorry about the dumb question.
The way that seemed to get me the closest is below:
protected void LocationExtAddress_UsrCustomerShipAccnt_FieldUpdated(PXCache cache, PXFieldUpdatedEventArgs e, PXFieldUpdated InvokeBaseHandler)
{
if(InvokeBaseHandler != null)
InvokeBaseHandler(cache, e);
var row = (LocationExtAddress)e.Row;
if (row == null) return;
PXSelectBase<Location> locationObj = new PXSelect<Location, Where<Location.bAccountID, Equal<Required<Location.bAccountID>>>>(Base);
Location deliveryLocation = locationObj.Select(row.LocationBAccountID);
var locationExt = PXCache<Location>.GetExtension<LocationExt>(location); <-- This generates error that there is no LocationExt.
deliveryLocation.Cache.SetValueExt(deliveryLocation, "UsrCustomerShipAccount", -->This needs to be the value that changed LocationExtAddress.UsrCustomerShipAccount but I don't see how to get this<--);
deliveryLocation.Cache.IsDirty = true;
deliveryLocation.Update(deliveryLocation); <--I don't know if this doesn't work because it is wrong or if it is because "UsrCustomerShipAccount" is not in deliverLocation.
}
You have
var locationExt = PXCache<Location>.GetExtension<LocationExt>(location);
shouldn't this be
var locationExt = PXCache<Location>.GetExtension<LocationExt>(deliveryLocation );
?

Automatically map a Contact to an Account

I want to add a field to Accounts which shows the email domain for that account e.g. #BT.com. I then have a spreadsheet which lists all the Accounts and their email domains. What I want to do is when a new Contact is added to Dynamics that it checks the spreadsheet for the same email domain (obviously without the contacts name in the email) and then assigned the Contact to the Account linked to that domain. Any idea how I would do this. Thanks
Probably best chance would be to develop CRM plugin. Register your plugin to be invoked when on after contact is created or updated (so called post-event phase). And in your plugin update the parentaccountid property of the contact entity to point to account of your choice.
Code-wise it goes something like (disclaimer: not tested):
// IPluginExecutionContext context = null;
// IOrganizationService organizationService = null;
var contact = (Entity)context.InputParameters["Target"];
var email = organizationService.Retrieve("contact", contact.Id, new ColumnSet("emailaddress1")).GetAttributeValue<string>("emailaddress1");
string host;
try
{
var address = new MailAddress(email);
host = address.Host;
}
catch
{
return;
}
var query = new QueryExpression("account");
query.TopCount = 1;
// or whatever the name of email domain field on account is
query.Criteria.AddCondition("emailaddress1", ConditionOperator.Contains, "#" + host);
var entities = organizationService.RetrieveMultiple(query).Entities;
if (entities.Count != 0)
{
contact["parentaccountid"] = entities[0].ToEntityReference();
}
organizationService.Update(contact);
I took Ondrej's code and cleaned it up a bit, re-factored for pre-operation. I also updated the logic to only match active account records and moved the query inside the try/catch. I am unfamiliar with the MailAddress object, I personally would just use string mapping logic.
var target = (Entity)context.InputParameters["Target"];
try
{
string host = new MailAddress(target.emailaddress1).Host;
var query = new QueryExpression("account");
query.TopCount = 1;
// or whatever the name of email domain field on account is
query.Criteria.AddCondition("emailaddress1", ConditionOperator.Contains, "#" + host);
query.Criteria.AddCondition("statecode", ConditionOperator.Equals, 0); //Active records only
var entities = organizationService.RetrieveMultiple(query).Entities;
if (entities.Count != 0)
{
target["parentaccountid"] = entities[0].ToEntityReference();
}
}
catch
{
//Log error
}

CRM 2011 accessing webcontext with outlook plugin

I have found some plugin code on the web that enables me to get the entity ID and the object type code for an entity in a plugin. The plugin is fired on RetrieveMultiple on activitypointer. The code lets me get the id and object code of the entity that is currently being viewed (which is displaying the activities grid which is firing the plugin).
This code works fine when using the web interface. However I need it to also work in the Outlook preview pane and currently it does not. The activities grid in the Outlook preview pane just says "an error has occurred". Below is the code that the plugin is using to get the details from the web header.
internal static Dictionary<string, string> GetHeaderFields(HttpContext webcontext, string objectTypeCode, string objectId)
{
Dictionary<string, string> fields = new Dictionary<string, string>();
string callerentitytype = null;
string callerentityidstring = null;
try
{
// Activities Navigation Pane
if (new List<string>(webcontext.Request.Params.AllKeys).Contains("oType"))
{
callerentitytype = webcontext.Request.Params["oType"];
callerentityidstring = webcontext.Request.Params["oId"];
}
// Activities Sub Grid
else
{
string requeststring = webcontext.Request.UrlReferrer.Query;
requeststring = requeststring.Substring(1);
string[] parts = requeststring.Split(new string[] { "=", "&" }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < parts.Length - 1; i++)
if (parts[i].ToLower() == "otype" || parts[i].ToLower() == "etc")
callerentitytype = parts[i + 1];
else if (parts[i].ToLower() == "oid" || parts[i].ToLower() == "id")
callerentityidstring = parts[i + 1];
}
fields.Add(objectTypeCode, callerentitytype);
fields.Add(objectId, callerentityidstring);
}
catch (Exception ex)
{
throw new Plugin.LoggableException(string.Format("Failed to obtain header information; {0}", ex.Message), ex.InnerException);
}
return fields;
}
The reason is that webcontext.Request.UrlReferrer is NULL. Is there anywhere else I can get this info of the 'calling' entity? (Not the activity sub grid that is triggering the plugin, but the actual parent entity that the sub grid is on).
Thanks for any help or direction with this.
This might work. Each of the activitypointers that are returned should all be "regarding" the same record (if in a sub grid). If you take say the 1st one and examine the regardingobjectid property, that should be an entity reference which will give you the logical name of the parent and it's guid. If that works, it will work across all clients (in theory anyway).

To save a user name into a people field

To save a user name into a people field:
Provided a people editor control in my custom form and saved each resolved entity as follows:
if (currentPeopleEditor.Entities.Count != 0)
{
SPFieldUserValueCollection userCollection = new SPFieldUserValueCollection();
for (int index = 0; index < currentPeopleEditor.ResolvedEntities.Count; index++)
{
PickerEntity ObjEntity = (PickerEntity)currentPeopleEditor.ResolvedEntities[index];
userCollection.Add(new SPFieldUserValue(objSPWeb,Convert.ToInt32(ObjEntity.EntityData["SPUserID"]), ObjEntity.Key));
}
newItem[Field.Key.ToString()] = userCollection;
}
It was working very fine until some user stated getting this exception:
"Invalid Look-up Value
A look-up field contains invalid data, Please check the value and try again."
On investigating we found that this error was occurring because
ObjEntity.EntityData["SPUserID"]) was returning as null.
It was happening because the requirement is to save some users name who don't access this site collection but they are member of corporate AD system.
To resolve this issue we looked up to SharePoint and replicated what they do.
In one of the list add a column of type people and group allowed it to pick any user.
create new item in this list and Pick a user whose name is not present in all users list.
save the item.
go back to all users list you will see that new user name got added to this list.
Note: To see all users list in UI browse to following location:
site collection URL/_catalogs/users/simple.aspx
so now to achieve the same functionality. I updated the code as follows
if (currentPeopleEditor.Entities.Count != 0)
{
SPFieldUserValueCollection userCollection = new SPFieldUserValueCollection();
for (int index = 0; index < currentPeopleEditor.ResolvedEntities.Count; index++)
{
PickerEntity ObjEntity = (PickerEntity)currentPeopleEditor.ResolvedEntities[index];
if (ObjEntity.EntityData["SPUserID"] == null)
{
SPContext.Current.Site.RootWeb.AllUsers.Add(ObjEntity.Key, ObjEntity.EntityData["Email"].ToString(), ObjEntity.DisplayText, "");
SPContext.Current.Site.RootWeb.Update();
userCollection.Add(new SPFieldUserValue(objSPWeb, Convert.ToInt32(SPContext.Current.Site.RootWeb.AllUsers[ObjEntity.Key].ID), ObjEntity.Key));
}
else
{ userCollection.Add(new SPFieldUserValue(objSPWeb, Convert.ToInt32(ObjEntity.EntityData["SPUserID"]), ObjEntity.Key));
}
}
newItem[Field.Key.ToString()] = userCollection;
}
Long story short to resolve above problem in SharePoint 2010 just use
web.EnsureUser()
It adds user to the all user list and returns spuser object.

Resources