Get specific CRM organization instead of all - dynamics-crm

There are multiple organizations on a CRM on-prem environment. I have stored DiscoveryService URL and organization name in a configuration file.
I want to get an Organization instance for a specific organization using organization name available in the configuration file, instead of loading all organizations.
something similar to,
select organizations from Organizations where orgName = 'XYZ'
Currently, I am using the below code, which is taking more than 3 seconds to retrieve an instance.
private OrganizationDetail DiscoverOrganization(Uri discoveryUri, string organizationName, ClientCredentials lclClientCredentials)
{
DiscoveryServiceProxy serviceProxy;
using (serviceProxy = new DiscoveryServiceProxy(discoveryUri, null, lclClientCredentials, null))
{
IDiscoveryService service = serviceProxy;
var orgsRequest = new RetrieveOrganizationsRequest() { AccessType = EndpointAccessType.Default, Release = OrganizationRelease.Current };
var organizations = (RetrieveOrganizationsResponse)service.Execute(orgsRequest);
return organizations.Details.FirstOrDefault(x => x.UniqueName.ToLower() == organizationName.ToLower());
}
}

You can try web api version as well. Read more
GET https://dev.{servername}/api/discovery/v9.0/Instances(UniqueName='myorg')

Related

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
}

Accessing user attributes using UserAccessor

The class com.sap.cloud.sdk.cloudplatform.security.user.UserAccessor allows to me to retrieve the current user and it's attributes.
For example:
Optional<UserAttribute> optionalfirstName = user.getAttribute("firstname");
UserAttribute ua = optionalfirstName.get();
Once I have retrieved the UserAttribute, it has two properites "Name" and "Value". However there is no method available to get the Value. How can I access the value?
Depending on the SAP CP environment you are using, the UserAttribute is an instance of:
SimpleUserAttribute<String> on Neo
CollectionUserAttribute<String> on Cloud Foundry
You can access the respective values by type-casting to the required instance:
if( ua instanceof SimpleUserAttribute ) {
String value = (String) ((SimpleUserAttribute<?>)ua).getValue();
}
else if ( ua instanceof CollectionUserAttribute ) {
Collection<?> values = ((CollectionUserAttribute<?>)ua).getValues();
}
Note: We plan to simplify this in future releases of the SDK so that StringUserAttribute and StringCollectionUserAttribute instances are returned for more convenient consumption.

How to get client's contact details in lync sdk c#

Which Object has the client contact information like office,company,IM, etc,. in Lync SDK 2013? I want to know the user's(client's) location/address information.
User location/office information can be obtained from contact object as given below:
LyncClient lyncClient = LyncClient.GetClient();
Contact contact = lyncClient.ContactManager.GetContactByUri("sip:contact#organization.com");
String officeLocation = contact.GetContactInformation(ContactInformationType.Office).ToString();
More information can be obtained using Contact information types Personal Note, Company, Location, Department etc.
In addition to Kannan's answer, getting the phone numbers from a contact is different and requires more work. Here's how you do it:
LyncClient lyncClient = LyncClient.GetClient();
Contact contact = lyncClient.ContactManager.GetContactByUri("sip:contact#organization.com");
List<object> endPoints = new List<object>();
var telephoneNumber = (List<object>)contact.GetContactInformation(ContactInformationType.ContactEndpoints);
endPoints = telephoneNumber.Where<object>(N => ((ContactEndpoint)N).Type == ContactEndpointType.HomePhone || ((ContactEndpoint)N).Type == ContactEndpointType.MobilePhone || ((ContactEndpoint)N).Type == ContactEndpointType.OtherPhone || ((ContactEndpoint)N).Type == ContactEndpointType.WorkPhone).ToList<object>();
foreach (var endPoint in endPoints)
{
//((ContactEndpoint)endPoint).DisplayName.ToString(); //This is the phone number in string format
}

Work Item Linked Queries/Scripts for Reporting in Visual Studio Team Services (VSTS)

I wanted to create a report on my VSTS Team Project which has the details of the Work Item Linking relationships in a Team Project. Ex: Epics→Features→UserStories. Since there are parent/child relationships between Epics & Features and also between Features & UserStories, I wanted to create a report (.csv or .xls) which has all the details of these workitems and their relationships.
Could someone let me know on what is the best and easy way to achieve this?
I suggest that you could check it via project with TFS add-in (included in VS or team explorer).
Create a query (Tree of work items)
Open Project
Click Team=>Choose Team project
Click Get Work Items=>Select that query=>Find=>Select All=>OK
After that you can check the result in project, you also can collapse parent item by clicking corresponding title.
You can achieve it programmatically by using TFS API with Excel add-in.
Create a document level excel add-in project
Install Microsoft Team Foundation Server Extended Client package
Run query by using Query.RunLinkQuery method.
Get test cases in requirement test suites
Check test results of these test cases
Get associated work item of test result
Save data to excel per your detail requirement.
Simple code:
var credentials = new NetworkCredential("[user name]", "[password]");
TfsTeamProjectCollection tfsCollection = new TfsTeamProjectCollection(new Uri("https://XX.visualstudio.com"));
ITestManagementService tms = tfsCollection.GetService<ITestManagementService>();
ITestManagementTeamProject teamProject = tms.GetTeamProject("[team project name]");
WorkItemStore workitemstore = tfsCollection.GetService<WorkItemStore>();
QueryHierarchy queryRoot = workitemstore.Projects["[team project name]"].QueryHierarchy;
QueryFolder queryFolder = queryRoot["Shared Queries"] as QueryFolder;
QueryDefinition qd = queryFolder["[query name]"] as QueryDefinition;
Dictionary<string, string> variables = new Dictionary<string, string>();
variables.Add("project", "[team project name]");
Query query = new Query(workitemstore, qd.QueryText, variables);
var results = query.RunLinkQuery();
foreach(var lr in results)
{
//check relationship according to sourceId, TargetId and LinkTypeId (2: child)
int parentId = lr.SourceId;
int currentId = lr.TargetId;
}
foreach (ITestPlan p in teamProject.TestPlans.Query("Select * From TestPlan"))
{
Console.WriteLine("Plan - {0} : {1}", p.Id, p.Name);
foreach (var suite in p.RootSuite.SubSuites)
{
IRequirementTestSuite requirementSuite = suite as IRequirementTestSuite;
if (requirementSuite != null)
{
var requirementId = requirementSuite.RequirementId;
//check requirementId with user story Id
foreach(var tc in requirementSuite.TestCases)
{
var lastResult = teamProject.TestResults.ByTestId(tc.Id).OrderByDescending(tr => tr.DateStarted).FirstOrDefault();
if(lastResult.Outcome== Microsoft.TeamFoundation.TestManagement.Client.TestOutcome.Failed)
{
int[] ids= lastResult.QueryAssociatedWorkItems();
foreach(int id in ids)
{
var wit = workitemstore.GetWorkItem(id);
}
}
}
}
}
}

LINQ to Entities many to many relationship

I am new to LINQ and the Entity Framework and am having trouble coming up with a suitable query.
I have the following entities. I have included primary keys and some other relevant fields.
Contact
Int ContactId(PK),
String Name,
String EMailAddress
Project
Int ProjectId(PK)
ProjectContact
Int ProjectId(PK),
Int ContactId(PK),
Boolean IsPrimaryContact,
Boolean IsSecondaryContact
A project can have 1..n contacts, one of which is the primary contact for that project. Additionally if the project has more than one contact, one of the other contacts can be the secondary contact for that project.
A contact can be associated with many projects and may be the primary or secondary contact for several projects.
I need to generate an email for each group of projects that have a shared combination of primary and secondary contact. The idea is that the To field of the email contains the primary contact's email address, the CC field contains the secondary contact's email address (if there is a secondary contact) and the body of the email contains details of all the projects that have this combination of primary and secondary contacts.
I would like to populate a list containing objects with the following structure:
class EmailDetails
{
public Contact PrimaryContact;
public Contact SecondaryContact;
public IEnumerable<Project> Projects = new List<Project>();
}
So far I have this:
var QueryResults =
from project in ProjectSet
join primaryContact in ProjectContacts on project.ProjectId equals primaryContact.ProjectId where primaryContact.IsPrimary
join secondaryContact in ProjectContacts on project.ProjectId equals secondaryContact.ProjectId where secondaryContact.IsSecondary
select new {primaryContact, secondaryContact, project}
Where do I go from here?
Thanks.
It's rarely correct to use join in L2E/L2S. Use associations/navigation properties instead.
Off the top of my head (may require some tweaking):
var QueryResults = from project in ProjectSet
let p = project.Contacts.FirstOrDefault(c => c.IsPrimary)
let s = project.Contacts.FirstOrDefault(c => c.IsSecondary)
group project by new { Primary = p, Secondary = s } into g
select new EmailDetails
{
PrimaryContact = g.Key.Primary,
SecondaryContact = g.Key.Secondary,
Projects = from proj in g
select new ProjectDetails
{
Project = proj,
Region = proj.Region,
ProjectItems = proj.ProjectItems
}
};

Resources