using MyProjectWith_Entities;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Metadata;
using Microsoft.Xrm.Sdk.Query;
using NUnit.Framework;
using System;
using System.Linq;
using System.Reflection;
using TechTalk.SpecFlow;
namespace NAMESPACE_TESTS.Steps
{
[Binding]
public class Generic_Steps
{
public static XrmContext CRM { get; set; }
public static IOrganizationService service { get; set; }
public Generic_Steps()
{
CRM = new XrmContext();
service = CRM.FakeXrmContext.GetOrganizationService();
}
#region GIVEN STEPS
[Given(@"the entity ""(.*)"" known as (.*) exists with the fields")]
public void GivenEntityNameKnownAs(string entityname, string known, Table fields)
{
Entity entity = new Entity(entityname);
foreach (var row in fields.Rows)
{
var key = row["Field"];
var value = row["Value"];
CRM.AddAttributeToEntity(key, value, entityname, ref entity);
}
CRM.AddEntityToMockCRM(known, entity);
}
[Given(@"the entity name contains primary attribute name")]
public void GivenEntityNameWithPrimaryNameField(Table table)
{
foreach (var row in table.Rows)
{
var entity = row["Field"];
var attribute = row["Value"];
CRM.AddPrimaryAttributeNameMetadataToMock(entity,attribute);
}
}
#endregion
#region THEN STEPS
[Then(@"The fields should be ""(.*)""")]
public void ThenTheFieldsShouldBe(string value)
{
var _value = CRM.Bag.ContainsKey("Result") ? CRM.Bag["Result"] : "";
Assert.AreEqual(_value, value);
}
[Then(@"The entity should be a ""(.*)""")]
[Then(@"The entity should be an ""(.*)""")]
public void ThenTheEntityShouldBe(string logicalName)
{
Entity entity = CRM.Bag.ContainsKey("Result") ? (Entity)CRM.Bag["Result"] : null;
Assert.AreEqual(entity.LogicalName, logicalName);
}
[Then(@"The fields should be")]
public void ThenTheFieldsShouldBe(Table fields)
{
Entity entity = CRM.Bag.ContainsKey("Result") ? (Entity)CRM.Bag["Result"] : null;
bool pass = true;
foreach (var row in fields.Rows)
{
if (!pass) { continue; }
var key = row["Field"];
var value = row["Value"];
if (entity.Attributes.Count > 0 && entity.Attributes.Contains(key) && entity.Attributes[key] != null)
{
var attribute = entity.Attributes[key];
var fieldSource = CheckAttribute(key, entity)?.ToString();
if (fieldSource != value.ToLower())
{
pass = false;
}
}
}
Assert.IsTrue(pass);
}
[Then(@"The fields should not be ""(.*)""")]
public void ThenTheFieldsShouldNotBe(string value)
{
var _value = CRM.Bag.ContainsKey("Result") ? CRM.Bag["Result"] : "";
Assert.AreNotEqual(_value, value);
}
[Then(@"the field ""(.*)"" should be null")]
public void ThenTheFieldShouldBeNull(string field)
{
Entity entity = CRM.Bag.ContainsKey("Result") ? (Entity)CRM.Bag["Result"] : null;
var fieldSource = CheckAttribute(field, entity)?.ToString();
Assert.IsNull(fieldSource);
}
[Then(@"the field ""(.*)"" should not be null")]
public void ThenTheFieldShouldNotBeNull(string field)
{
Entity entity = CRM.Bag.ContainsKey("Result") ? (Entity)CRM.Bag["Result"] : null;
var fieldSource = CheckAttribute(field, entity)?.ToString();
Assert.IsNotNull(fieldSource);
}
[Then(@"the (.*) on attribute ""(.*)"" should have (.*) ""(.*)""")]
public void ThenTheEntityOnAttributeShouldHaveXRecords(string targetname, string attribute, int number, string entitynameToCheck)
{
Entity entity = (Entity)CRM.Bag[targetname];
// Query using ConditionExpression and FilterExpression
ConditionExpression conditionentity = new ConditionExpression();
conditionentity.AttributeName = attribute;
conditionentity.Operator = ConditionOperator.Equal;
conditionentity.Values.Add(entity.Id);
FilterExpression filterexp = new FilterExpression();
filterexp.Conditions.Add(conditionentity);
QueryExpression query = new QueryExpression(entitynameToCheck);
query.Criteria.AddFilter(filterexp);
var entitiesRetrieved = service.RetrieveMultiple(query);
var countEntities = 0;
if (entitiesRetrieved.Entities != null && entitiesRetrieved.Entities.Count > 0)
{
countEntities = entitiesRetrieved.Entities.Count;
Assert.AreEqual(entitynameToCheck, entitiesRetrieved.Entities[0].LogicalName, $"The result is {entitiesRetrieved.Entities[0].LogicalName} but is should have been {entitynameToCheck}");
}
Assert.AreEqual(number, countEntities, $"The item numbers are different it has been {countEntities} instead {number}");
}
[Then(@"the Result should not be null")]
public void ThenTheResultShouldNotBeNull()
{
var resultBag = CRM.Bag.ContainsKey("Result") ? (string)CRM.Bag["Result"] : null;
Assert.IsNotNull(resultBag);
}
[Then(@"the Result should be null")]
public void ThenTheResultShouldBeNull()
{
var resultBag = CRM.Bag.ContainsKey("Result") ? (string)CRM.Bag["Result"] : null;
Assert.IsNull(resultBag);
}
[Then(@"the Result should be ""(.*)""")]
public void ThenTheResultShouldBe(string result)
{
var resultBag = CRM.Bag.ContainsKey("Result") ? (string)CRM.Bag["Result"] : null;
Assert.AreEqual(result, resultBag);
}
[Then(@"the service should have an entity (.*) with fields")]
public void ThenTheServiceShouldHaveAnEntityWithFields(string entityname, Table fields)
{
string getEntityRecords = $@"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
<entity name='{entityname}'>
</entity>
</fetch>";
var entities = service.RetrieveMultiple(new FetchExpression(getEntityRecords));
bool pass = false;
foreach (var entity in entities.Entities)
{
if (pass) { continue; }
foreach (var row in fields.Rows)
{
var key = row["Field"];
var value = row["Value"];
if (entity.Attributes.Count > 0 && entity.Attributes.Contains(key) && entity.Attributes[key] != null)
{
var attribute = entity.Attributes[key];
var fieldSource = CheckAttribute(key, entity)?.ToString();
pass = fieldSource == value.ToLower() ? true : false;
}
}
}
Assert.IsTrue(pass);
}
[Then(@"the service should have (.*) records of the entity (.*)")]
public void ThenTheServiceShouldHaveXRecordsOfEntity(int records, string entityname)
{
string getEntityRecords = $@"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
<entity name='{entityname}'>
</entity>
</fetch>";
var entities = service.RetrieveMultiple(new FetchExpression(getEntityRecords));
Assert.AreEqual(records, entities.Entities.Count);
Assert.AreEqual(entityname.ToLower(), entities.Entities[0].LogicalName.ToLower());
}
#endregion
#region GENERIC FUNCTIONS
public string CheckAttribute(string field, Entity entity)
{
var attribute = entity.Attributes[field];
var fieldSource = string.Empty;
switch (attribute.GetType().Name)
{
case "EntityReference":
var fieldReference = ((EntityReference)attribute);
if (fieldReference != null && fieldReference.Id != Guid.Empty)
{
var mainField = GetPrimaryFieldName(fieldReference.LogicalName);
var fieldName = service.Retrieve(fieldReference.LogicalName, fieldReference.Id, new Microsoft.Xrm.Sdk.Query.ColumnSet(new string[] { mainField }));
fieldSource = fieldName?.Attributes[mainField]?.ToString()?.ToLower();
}
else
{
fieldSource = null;
}
break;
case "OptionSetValue":
fieldSource = ((OptionSetValue)attribute)?.Value.ToString()?.ToLower();
break;
case "DateTime":
fieldSource = ((DateTime)attribute) != null ? ((DateTime)attribute).ToString()?.ToLower() : null;
break;
default:
fieldSource = attribute?.ToString()?.ToLower();
break;
}
return fieldSource;
}
public static string GetPrimaryFieldName(string entityname)
{
RetrieveEntityRequest retrievesEntityRequest = new RetrieveEntityRequest
{
EntityFilters = EntityFilters.Entity,
LogicalName = entityname
};
//Execute Request
RetrieveEntityResponse retrieveEntityResponse = (RetrieveEntityResponse)service.Execute(retrievesEntityRequest);
// Gets the primaryid attribute
// var idFieldName = retrieveEntityResponse.EntityMetadata.PrimaryIdAttribute;
// Gets the primary field name
return retrieveEntityResponse.EntityMetadata.PrimaryNameAttribute;
}
#endregion
}
}