Пример #1
4
        public static string Serialise(EntityCollection value)
        {
            string valueXml = string.Empty;
          
            // Check the type
            if (value.GetType() != typeof(EntityCollection))
                throw new Exception("An attribute value of type 'EntityCollection' must contain an EntityCollection instance");
            EntityCollection arrayValue = value as EntityCollection;

            valueXml += "<a:Entities>";
            for (int i = 0; i < arrayValue._entities.Count; i++)
            { 
                valueXml += ((Entity)arrayValue[i]).Serialise(false);
            }
            valueXml += "</a:Entities>";
            return valueXml;
        }
Пример #2
1
        /// <summary>
        /// Extracts additional column display values from the search result
        /// The name attribute can now be a column separated list of attribute logical names
        /// </summary>
        /// <param name="columnAttributes"></param>
        /// <param name="fetchResult"></param>
        /// <param name="results"></param>
        /// <param name="i"></param>
        internal static void GetExtraColumns(string[] columnAttributes, EntityCollection fetchResult, AutoCompleteItem[] results, int i)
        {
            if (columnAttributes != null)
            {
                List<string> columnValues = new List<string>();
                bool first = true;
                // Get the additional column attributes to display
                foreach (string attribute in columnAttributes)
                {
                    if (first)
                    {
                        first = false;
                        continue;
                    }
                    string value = "";
                    Entity record = fetchResult.Entities[i];

                    if (record.FormattedValues.ContainsKey(attribute + "name"))
                    {
                        value = record.FormattedValues[attribute + "name"];
                    }
                    else
                    {
                        object attributeValue = record.GetAttributeValue(attribute);
                        if (attributeValue != null)
                        {
                            switch (attributeValue.GetType().Name)
                            {
                                case "EntityReference":
                                    value = ((EntityReference)attributeValue).Name;
                                    break;
                                default:
                                    value = attributeValue.ToString();
                                    break;
                            }
                        }
                    }
                    if (value != null && value.Length>0)
                    {
                        columnValues.Add(value);
                    }

                }
                results[i].ColumnValues = (string[])columnValues;
            }
        }
Пример #3
0
 public static EntityCollection DeSerialise(XmlNode node)
 {
     List<Entity> entities = new List<Entity>();
     EntityCollection collection = new EntityCollection(entities);
     collection.EntityName = XmlHelper.SelectSingleNodeValue(node, "EntityName");
     XmlNode entitiesNode = XmlHelper.SelectSingleNodeDeep(node, "Entities");
     foreach (XmlNode entityNode in entitiesNode.ChildNodes)
     {
         Entity entity = new Entity(collection.EntityName);
         entity.DeSerialise(entityNode);
         ArrayEx.Add(entities, entity);
     }
     return collection;
 }
Пример #4
0
        public void RecordSearchCommand(string term, Action<EntityCollection> callback)
        {
            if (_queryParser==null)
            {
                // Get the quick find metadata on first search
                _queryParser = new QueryParser(connectToTypes);
                _queryParser.GetQuickFinds();
                _queryParser.QueryMetadata();
            }

            // Get the option set values
            int resultsBack = 0;
            List<Entity> mergedEntities = new List<Entity>();
            Action<EntityCollection> result = delegate(EntityCollection fetchResult)
            {
                resultsBack++;
                FetchQuerySettings config = _queryParser.EntityLookup[fetchResult.EntityName].QuickFindQuery;
                // Add in the display Columns
                foreach (Dictionary<string,object> row in fetchResult.Entities)
                {
                    Entity entityRow = (Entity)(object)row;
                    int columnCount = config.Columns.Count<3 ? config.Columns.Count :3;
                    // Only get up to 3 columns
                    for (int i = 0; i < columnCount; i++)
                    {
                        // We use col<n> as the alias name so that we can show the correct values irrespective of the entity type
                        string aliasName = "col" + i.ToString();
                        row[aliasName] = row[config.Columns[i].Field];
                        entityRow.FormattedValues[aliasName + "name"] = entityRow.FormattedValues[config.Columns[i].Field + "name"];
                    }

                }
                // Merge in the results
                mergedEntities.AddRange((Entity[])(object)fetchResult.Entities.Items());
                
                mergedEntities.Sort(delegate (Entity x, Entity y){
                    return string.Compare(x.GetAttributeValueString("name"), y.GetAttributeValueString("name"));
                });
                if (resultsBack == connectToTypes.Length)
                {
                    EntityCollection results = new EntityCollection(mergedEntities);
                    callback(results);
                }
            };

            foreach (string entity in connectToTypes)
            {
                SearchRecords(term, result, entity);
            }
        }
        private static EntityCollection GetEntityCollectionResults(XmlDocument resultXml, Type entityType)
        {
            // Get the id of the created object from the returned xml
            XmlNode soapBody = resultXml.FirstChild.FirstChild;
            XmlNode resultNode = XmlHelper.SelectSingleNodeDeep(soapBody, "RetrieveMultipleResult");
            XmlNode results = XmlHelper.SelectSingleNode(resultNode, "Entities");

            // Parse result into array of Entity objects
            int resultCount = 0;
            if (results != null)
                resultCount = results.ChildNodes.Count;

            List<Entity> businessEntities = new List<Entity>();

            for (int i = 0; i < resultCount; i++)
            {
                XmlNode entityNode = results.ChildNodes[i];

                Entity entity = (Entity)Type.CreateInstance(entityType, null);
                entity.DeSerialise(entityNode);
                businessEntities[i] = entity;
            }
            EntityCollection entities = new EntityCollection(businessEntities);
            entities.MoreRecords = XmlHelper.SelectSingleNodeValue(resultNode, "MoreRecords") == "true";
            entities.PagingCookie = XmlHelper.SelectSingleNodeValue(resultNode, "PagingCookie");
            entities.TotalRecordCount = int.Parse(XmlHelper.SelectSingleNodeValue(resultNode, "TotalRecordCount"));
            entities.TotalRecordCountLimitExceeded = XmlHelper.SelectSingleNodeValue(resultNode, "TotalRecordCountLimitExceeded") == "true";
            return entities;
        }
Пример #6
0
        public void ActivitySearchCommand(string term, Action<EntityCollection> callback)
        {
            // Get the option set values

                string fetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                                  <entity name='activitypointer'>
                                    <attribute name='activitytypecode' />
                                    <attribute name='subject' />
                                    <attribute name='activityid' />
                                    <attribute name='instancetypecode' />
                                    <attribute name='regardingobjectid' />
                                    <order attribute='modifiedon' descending='false' />
                                    <filter type='and'>
                                      <condition attribute='ownerid' operator='eq-userid' />
                                        <condition attribute='subject' operator='like' value='%{0}%' />
                                          <condition attribute='activitytypecode' operator='in'>
                                            <value>4202</value>
                                            <value>4207</value>
                                            <value>4210</value>
                                            <value>4212</value>
                                          </condition>
                                            {2}
                                    </filter>
                                    {1}
                                  </entity>
                                </fetch>";
            // Get the account to filter on if there is one
            string regardingObjectIdFilterFetchXml = @"<condition attribute='regardingobjectid' operator='eq' value='{0}'/>";

            string opportunityAccountFilterFetchXml = @"<link-entity name='opportunity' from='opportunityid' to='regardingobjectid' visible='false' link-type='inner' alias='opportunity' >
                                        <attribute name='customerid' />
                                        <filter type='and' >
                                            <condition attribute='customerid' operator='eq' value='{0}' />
                                        </filter>
                                        </link-entity>";

            string incidentAccountFilterFetchXml = @" <link-entity name='incident' from='incidentid' to='regardingobjectid' visible='false' link-type='inner' alias='incident' >
                                        <attribute name='customerid' />
                                        <filter type='and' >
                                            <condition attribute='customerid' operator='eq' value='{0}' />
                                        </filter>
                                        </link-entity>";
            
            string contractAccountFilterFetchXml = @" <link-entity name='contract' from='contractid' to='regardingobjectid' visible='false' link-type='inner' alias='contract' >
                                        <attribute name='customerid' />
                                        <filter type='and' >
                                            <condition attribute='customerid' operator='eq' value='{0}' />
                                        </filter>
                                        </link-entity>";

            string regardingAccountFilterFetchXml = @" <link-entity name='account' from='accountid' to='regardingobjectid' visible='false' link-type='inner' alias='account' >
                                        <attribute name='accountid'/>
                                        <attribute name='name'/>
                                        <filter type='and' >
                                            <condition attribute='accountid' operator='eq' value='{0}' />
                                        </filter>
                                        </link-entity>";

            DayEntry selectedItem = this.Days.SelectedItems[0];
            string regardingObjectFilter = String.Empty;
            string regardingAccountFilter = String.Empty;
            string opportunityAccountFilter = String.Empty;
            string incidentAccountFilter = String.Empty;
            string contractAccountFilter = String.Empty;

            if (selectedItem != null && selectedItem.RegardingObjectId != null)
            {
                regardingObjectFilter = string.Format(regardingObjectIdFilterFetchXml, selectedItem.RegardingObjectId.Id.Value);
            }

            if (selectedItem != null && selectedItem.Account!=null)
            {
                // Add in the regarding account filter
                regardingAccountFilter = string.Format(regardingAccountFilterFetchXml, selectedItem.Account.Id.Value);
                opportunityAccountFilter = string.Format(opportunityAccountFilterFetchXml, selectedItem.Account.Id.Value);
                incidentAccountFilter = string.Format(incidentAccountFilterFetchXml, selectedItem.Account.Id.Value);
                contractAccountFilter = string.Format(contractAccountFilterFetchXml, selectedItem.Account.Id.Value);
            }
            
            List<Entity> unionedResults = new List<Entity>();

            // We need to union the activities regarding the account directly with those that are regarding related records
            Action<string, string, Action, Action> unionSearch = delegate(string additionalFilter, string additionalCriteria, Action completeCallBack, Action errorCallBack)
            {
                string queryFetchXml = string.Format(fetchXml, XmlHelper.Encode(term), additionalFilter,additionalCriteria);
                OrganizationServiceProxy.BeginRetrieveMultiple(queryFetchXml, delegate(object result)
                {
                    EntityCollection fetchResult = OrganizationServiceProxy.EndRetrieveMultiple(result, typeof(ActivityPointer));
                    // Adjust the entity types
                    foreach (ActivityPointer a in fetchResult.Entities)
                    {
                        a.UpdateCalculatedFields();
                        unionedResults.Add(a);
                    }

                    completeCallBack();
                });
            };

            TaskIterrator tasks = new TaskIterrator();

            // Default Search
            tasks.AddTask(delegate(Action completeCallBack, Action errorCallBack) { unionSearch(regardingAccountFilter, regardingObjectFilter, completeCallBack, errorCallBack); });
            
            // Associated record searches
            if (opportunityAccountFilter!=String.Empty)
                tasks.AddTask(delegate(Action completeCallBack, Action errorCallBack) { unionSearch(opportunityAccountFilter, String.Empty, completeCallBack, errorCallBack); });
            if (incidentAccountFilter!=String.Empty)
                tasks.AddTask(delegate(Action completeCallBack, Action errorCallBack) { unionSearch(incidentAccountFilter, String.Empty, completeCallBack, errorCallBack); });
            if (contractAccountFilter!=String.Empty)
                tasks.AddTask(delegate(Action completeCallBack, Action errorCallBack) { unionSearch(contractAccountFilter, String.Empty, completeCallBack, errorCallBack); });


            Action queryComplete = delegate()
            {
                // Sort
                unionedResults.Sort(delegate(Entity a, Entity b) { return Entity.SortDelegate("subject", a, b); });
                // Completed the queryies, so sort then and add to Entity Collection
                EntityCollection results = new EntityCollection(unionedResults);
                
                callback(results);
            };

            // Start processing queue   
            tasks.Start(queryComplete, null);

           
        }
Пример #7
0
        public void RegardingObjectSearchCommand(string term, Action<EntityCollection> callback)
        {
            string regardingAccountFetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                                  <entity name='account'>
                                    <attribute name='name' />
                                    <attribute name='accountid' />
                                    <order attribute='name' descending='false' />
                                    <filter type='and'>
                                      <condition attribute='statecode' operator='eq' value='0' />
                                      <condition attribute='name' operator='like' value='%{0}%' />
                                      {1}
                                    </filter>
                                   </entity>
                                </fetch>";
            string regardingOpportunityFetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                                                  <entity name='opportunity'>
                                                    <attribute name='name' />
                                                    <attribute name='opportunityid' />
                                                    <order attribute='name' descending='false' />
                                                    <filter type='and'>
                                                      <condition attribute='statecode' operator='eq' value='0' />
                                                      <condition attribute='name' operator='like' value='%{0}%' />
                                                     {1}
                                                    </filter>
                                                  </entity>
                                                </fetch>";

            string regardingIncidentFetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                                              <entity name='incident'>
                                                <attribute name='title' />
                                                <attribute name='incidentid' />
                                                <order attribute='title' descending='false' />
                                                <filter type='and'>
                                                  <condition attribute='title' operator='like' value='%{0}%' />
                                                  {1}
                                                </filter>
                                              </entity>
                                            </fetch>";

            string accountCriteriaFetchXml = @"<condition attribute='{0}' operator='eq' value='{1}' />";
            DayEntry selectedItem = this.Days.SelectedItems[0];
            

            List<Entity> unionedResults = new List<Entity>();

            // We need to union the activities regarding the account directly with those that are regarding related records
            Action<string, string, string, Action, Action> unionSearch = delegate(string fetchXml,string nameAttribute,string accountAttribute, Action completeCallBack, Action errorCallBack)
            {
                // Add Account filter if an account is selected
                string additionalCriteria = "";
                if (selectedItem != null && selectedItem.Account != null)
                {
                    additionalCriteria = string.Format(accountCriteriaFetchXml, accountAttribute, selectedItem.Account.Id.Value);
                }
                string queryFetchXml = string.Format(fetchXml, XmlHelper.Encode(term),additionalCriteria);
                OrganizationServiceProxy.BeginRetrieveMultiple(queryFetchXml, delegate(object result)
                {
                    EntityCollection fetchResult = OrganizationServiceProxy.EndRetrieveMultiple(result, typeof(ActivityPointer));
                    // Adjust the entity types
                    foreach (Entity a in fetchResult.Entities)
                    {
                       // Set name
                        a.SetAttributeValue("displayName", a.GetAttributeValueString(nameAttribute));
                        unionedResults.Add(a);
                    }

                    completeCallBack();
                });
            };

            TaskIterrator tasks = new TaskIterrator();

            // Add Searches
            tasks.AddTask(delegate(Action completeCallBack, Action errorCallBack) { unionSearch(regardingAccountFetchXml,"name", "accountid", completeCallBack, errorCallBack); });
            tasks.AddTask(delegate(Action completeCallBack, Action errorCallBack) { unionSearch(regardingOpportunityFetchXml, "name","customerid", completeCallBack, errorCallBack); });
            tasks.AddTask(delegate(Action completeCallBack, Action errorCallBack) { unionSearch(regardingIncidentFetchXml, "title", "customerid",completeCallBack, errorCallBack); });
            
            Action queryComplete = delegate()
            {
                //  Sort Alphabetically
                unionedResults.Sort(delegate(Entity a, Entity b) { return Entity.SortDelegate("displayName", a, b); });
                // Completed the queryies, so sort then and add to Entity Collection
                EntityCollection results = new EntityCollection(unionedResults);

                callback(results);
            };

            // Start processing queue   
            tasks.Start(queryComplete, null);
        }
        public void GetLanguages(string term, Action<EntityCollection> callback)
        {
            // Get the languages
            if (_languages == null)
            {
                _languages = new List<Entity>();

                AddLanguage("00000000-0000-0000-0000-000000000001", "English");
                AddLanguage("00000000-0000-0000-0000-000000000002", "French");
                AddLanguage("00000000-0000-0000-0000-000000000003", "German");
                AddLanguage("00000000-0000-0000-0000-000000000004", "Japanese");
                AddLanguage("00000000-0000-0000-0000-000000000005", "Hungarian");

            }

            List<Entity> entities = new List<Entity>();
            foreach (Entity language in _languages)
            {
                if (language.GetAttributeValueString("name").ToLowerCase().IndexOf(term.ToLowerCase()) > -1)
                {
                    entities.Add(language);
                }
            }
            EntityCollection results = new EntityCollection(entities);
            callback(results);
        }
        /// <summary>
        /// Maps activity party references
        /// </summary>
        /// <param name="dictionary">Contains the root entity as a <c>Dictionary</c>.</param>
        /// <param name="entity">The entity to map the activity parties to, if the property that is being mapped is an option set.</param>
        /// <param name="propertyName">The property that the activities are associated to on the root entity.</param>
        /// <param name="field">The <see cref="FieldDefinition"/> that contains the activity parties.</param>
        /// <returns>An <c>EntityCollection</c> of the mapped activity entities.</returns>
        protected EntityCollection MapActivityPartyReferences(Dictionary<string, object> dictionary, Entity entity, string propertyName, FieldDefinition field)
        {
            if (field == null)
            {
                throw new AdapterException(string.Format(CultureInfo.CurrentCulture, Resources.ArgumentNullExceptionMessage), new ArgumentNullException("field")) { ExceptionId = AdapterException.SystemExceptionGuid };
            }

            var partyEntityCollection = dictionary[propertyName] as Dictionary<string, object>;
            var entities = partyEntityCollection["ActivityParties"] as Dictionary<string, object>;

            if (entities.Count > 0)
            {
                var tempEntityCollection = new EntityCollection();

                foreach (var partyEntity in entities)
                {
                    Entity tempEntity = new Entity("activityparty");
                    var attributes = partyEntity.Value as Dictionary<string, object>;

                    foreach (var attribute in attributes)
                    {
                        var fieldDef = field.TypeDefinition.Children.FirstOrDefault<FieldDefinition>(x => x.Name == attribute.Key);
                        if (fieldDef != null)
                        {
                            if (fieldDef.TypeDefinition.Name == "EntityReference")
                            {
                                var mappedValue = attribute.Value as Dictionary<string, object>;
                                var entityReference = this.MapEntityReference(fieldDef, mappedValue);

                                if (entityReference != null)
                                {
                                    tempEntity.Attributes.Add(new KeyValuePair<string, object>(attribute.Key, entityReference));
                                }
                                else
                                {
                                    throw new AdapterException(string.Format(CultureInfo.CurrentCulture, Resources.ArgumentNullExceptionMessage), new ArgumentNullException("activityparty")) { ExceptionId = AdapterException.SystemExceptionGuid };
                                }
                            }
                            else if (fieldDef.TypeDefinition.Name == "OptionSetValue")
                            {
                                var mappedValue = attribute.Value as Dictionary<string, object>;
                                OptionSetValue pickList = CRM2011AdapterUtilities.MapPicklist(entity, fieldDef, mappedValue, this.CrmAdapter, this.ProvidedEntityName);
                                if (pickList != null)
                                {
                                    entity[propertyName] = pickList;
                                }
                                else
                                {
                                    throw new AdapterException(string.Format(CultureInfo.CurrentCulture, Resources.ArgumentNullExceptionMessage), new ArgumentNullException("activityparty")) { ExceptionId = AdapterException.SystemExceptionGuid };
                                }
                            }
                            else
                            {
                                tempEntity.Attributes.Add(attribute);
                            }
                        }
                    }

                    tempEntityCollection.Entities.Add(tempEntity);
                }

                return tempEntityCollection;
            }

            return null;
        }
Пример #10
0
        private void ProcessQueryResults(QueuedLoad load, EntityCollection rootResults)
        {
            int total = rootResults.Entities.Count;
            int index = 0;
            List<string> ids = new List<string>();

            foreach (Entity record in rootResults.Entities)
            {
                if (IsCancelRequested())
                    return;
                SetMessage(ResourceStrings.Processing, load.Entity.DisplayName, index, total);

                // Check if this is a pending load - and remove it
                RemovePendingID(record.LogicalName, record.Id);

                index++;
                ids.Add(record.Id);
                string name = record.GetAttributeValueString(load.Entity.NameAttribute == null ? "name" : load.Entity.NameAttribute);
                // If this is the root entity then set the window title
                bool rootNode = (RootEntityId.Value.ToLowerCase().Substr(1, 36) == record.Id.ToLowerCase());

                if (rootNode)
                {
                    Window.Document.Title = name;
                }

                if (!IsAlsoAUser(record) && !IndexContainsEntity(record))
                {
                    EntityNode newNode = new EntityNode(name, 100);
                    newNode.Root = rootNode;
                    newNode.X = _startX;
                    newNode.Y = _startY;
                    newNode.SourceData = record;
                    if (!AddEntity(record, newNode, load.Entity, false))
                        return;

                    // Add User reference for owner
                    EntityReference owner = record.GetAttributeValueEntityReference("ownerid");
                    if (owner != null)
                    {
                        UserOrTeam user = GetUserOrTeamReference(owner);
                        user.Parties[record.Id.ToString()] = record.ToEntityReference();
                    }
                }
            }

            Trace("Linking to Parents {0} {1} records", new object[] { load.Entity.LogicalName, rootResults.Entities.Count });
            index = 0;
            // Add the parent links
            foreach (Entity record in rootResults.Entities)
            {
                if (IsCancelRequested())
                    return;
                SetMessage(ResourceStrings.Linking, load.Entity.DisplayName, index, total);

                EntityNode thisNode = GetEntity(record);

                if (thisNode == null)
                    continue;
                // Add the heiarchical links
                EntityNode parentNode = GetParentEntity(record, load.Entity.ParentAttributeId, load.Entity.LogicalName);

                if (parentNode != null)
                {
                    // Create Link
                    AddLink(thisNode, parentNode, false);
                }

                // Add the backlinks
                // e.g. if this is a contact then back link via the parentcustomerid field
                if (load.Join != null)
                {
                    Trace("Adding backlinks {0}->{1}", new object[] { load.Entity.LogicalName, load.Join.RightEntity });
                    EntityNode joinedNode = GetParentEntity(record, load.Join.RightAttribute, load.Join.RightEntity);
                    if (joinedNode != null)
                    {
                        AddLink(thisNode, joinedNode, false);
                    }
                    else
                    {

                        // Add pending link

                    }
                }
            }

            if (ids.Count > 0)
            {

                // add links
                if (load.Entity.Joins != null)
                {
                    Trace("Adding Joins to {0}", new object[] { ids.Count });
                    foreach (JoinSetting join in load.Entity.Joins)
                    {
                        EntitySetting joinedTo = Config.Entities[join.RightEntity];
                        if (joinedTo != null)
                        {
                            Trace("Queing Join  {0}.{1} -> {2}.{3} {4}", new object[] { join.LeftEntity, join.LeftAttribute, join.RightEntity, join.RightAttribute, join.Name });
                            Queue.Enqueue(new QueuedLoad(ids, joinedTo, join));
                        }
                    }
                }

                if (load.Entity.LoadActivities)
                {
                    Queue.Enqueue(new QueuedLoad(ids, load.Entity, NewJoinSetting(load.Entity.LogicalName, "activity")));
                }

                if (load.Entity.LoadConnections)
                {
                    Queue.Enqueue(new QueuedLoad(ids, load.Entity, NewJoinSetting(load.Entity.LogicalName, "connection")));
                }
            }
            _currentLoad = null;
            CallNextProcessQueue();
        }
Пример #11
0
 public virtual void PreProcessResultsData(EntityCollection results)
 {
     // Allows overriding to change the results - prefiltering or adding items
 }
Пример #12
0
        private void ProcessConnection(EntityCollection rootResults2, int index, int total)
        {
            Connection record = (Connection)rootResults2.Entities[index];

            SetMessage(ResourceStrings.Processing, ResourceStrings.Connections, index, total);

            EntityReference record1id = record.Record1Id; // we have this already
            EntityReference record2id = record.Record2Id;

            // Get the roles
            EntityReference role1 = record.Record1RoleId;
            EntityReference role2 = record.Record2RoleId;

            EntityNode linkFrom = GetEntityFromReference(record1id);
            EntityLink linkToExisting = AddLinkIfLoaded(linkFrom, record2id, false);

            bool record1UserOrTeam = record1id.LogicalName == "systemuser" || record1id.LogicalName == "team";
            bool record2UserOrTeam = record2id.LogicalName == "systemuser" || record2id.LogicalName == "team";

            if (!record1UserOrTeam && !record2UserOrTeam && linkToExisting != null)
            {
                // Add the the connection role index
                if (role1 != null)
                {
                    if (!ConnectionRoleIndex.ContainsKey(role1.Name))
                    {
                        ConnectionRoleIndex[role1.Name] = new Dictionary<string, EntityLink>();
                    }

                    if (!ConnectionRoleIndex[role1.Name].ContainsKey(linkToExisting.Id))
                    {
                        // Add the connection
                        ConnectionRoleIndex[role1.Name][linkToExisting.Id] = linkToExisting;
                    }
                    if (!ConnectionRoles.GetItems().Contains(role1.Name))
                    {
                        ConnectionRoles.Push(role1.Name);
                    }
                }

                if (role2 != null)
                {
                    if (!ConnectionRoleIndex.ContainsKey(role2.Name))
                    {
                        ConnectionRoleIndex[role2.Name] = new Dictionary<string, EntityLink>();
                    }
                    // Add the connection

                    if (!ConnectionRoleIndex[role2.Name].ContainsKey(linkToExisting.Id))
                    {
                        // Add the connection
                        ConnectionRoleIndex[role2.Name][linkToExisting.Id] = linkToExisting;
                    }
                    if (!ConnectionRoles.GetItems().Contains(role2.Name))
                    {
                        ConnectionRoles.Push(role2.Name);
                    }
                }

            }

            if (linkToExisting == null)
            {

                // Any records not loaded - add a pending link
                if (record2UserOrTeam)
                {
                    UserOrTeam user = GetUserOrTeamReference(record2id);
                    user.Parties[record2id.Id.ToString()] = record1id;
                }
                else if (record1UserOrTeam)
                {
                    UserOrTeam user = GetUserOrTeamReference(record1id);
                    user.Parties[record1id.Id.ToString()] = record2id;
                }
                else
                {
                    //Trace(String.Format("Pending Connections to {0} -> {1}", linkFrom.Name, record2id.Name));
                    AddPendingLink(linkFrom, record2id);
                }
            }
        }
Пример #13
0
        private void ProcessActivity(EntityCollection rootResults2, int index, int total)
        {
            Entity record = rootResults2.Entities[index];

            SetMessage(ResourceStrings.Processing, ResourceStrings.Activities, index, total);
            EntityNode newNode;
            record.LogicalName = record.GetAttributeValueString("activitytypecode");

            bool alreadyAdded = false;
            if (!IndexContainsEntity(record))
            {

                newNode = new EntityNode(record.GetAttributeValueString("name"), 100);
                newNode.IsActivity = true;
                newNode.X = _startX;
                newNode.Y = _startY;
                newNode.SourceData = record;

                if (!AddEntity(record, newNode, null, true))
                    return;
            }
            else
            {
                newNode = GetEntity(record);
                alreadyAdded = true;
            }

            // Go through the activity parties and link to the records
            EntityCollection allParties = (EntityCollection)record.GetAttributeValue("allparties");
            int i = 0;
            bool overflow = false;

            foreach (Entity item in allParties.Entities)
            {
                if (IsCancelRequested())
                    return;
                if ((index % 20) == 0)
                {
                    SetMessage(ResourceStrings.Processing, ResourceStrings.ActivityLinks, index, total);
                }
                i++;

                ActivityParty party = (ActivityParty)item;
                EntityReference partyid = party.PartyId;
                if (partyid != null) // Only load resolved parties
                {
                    //Trace(String.Format("Party {0} {1} {2}",partyid.LogicalName, partyid.Name,partyid.Id));
                    // Do we have it?
                    // We must have at least one since the activity has been loaded in the first place!
                    EntityLink linkToExisting = AddLinkIfLoaded(newNode, partyid, true);

                    if (linkToExisting == null)
                    {

                        // Any records not loaded - add a pending link
                        if (party.PartyId.LogicalName == "systemuser" || party.PartyId.LogicalName == "team")
                        {

                            party.ActivityID.LogicalName = ((Entity)newNode.SourceData).LogicalName;
                            UserOrTeam user = GetUserOrTeamReference(party.PartyId);

                            user.Parties[party.ActivityID.Id.ToString()] = party.ActivityID;
                        }
                        else
                        {

                            AddPendingLink(newNode, partyid);
                        }
                    }
                    else
                    {
                        if (newNode.ParentNode == null)
                        {
                            // Allocate each entity a single parent - which is the first found party

                            newNode.ParentNode = linkToExisting.Target;
                            newNode.ParentNode.ActivityCount++;
                        }

                        // Check the count of activities

                        bool overflowAlreadyAdded = false;

                        bool overflowed = newNode.ParentNode.ActivityCount > OverflowMax && newNode.ParentNode == linkToExisting.Target;

                        // If the linked to source activity is already load then don't overflow it
                        if (alreadyAdded)
                        {

                            overflow = false;
                        }

                        if (overflowed)
                        {

                            if (newNode.ParentNode.OverflowNode == null)
                            {

                                // Create overflow node if not already
                                EntityNode overflowNode = new EntityNode(ResourceStrings.DoubleClickToExpand, 1);
                                overflowNode.Id = "overflow" + partyid.Id.Value;
                                overflowNode.ParentNode = newNode.ParentNode;
                                overflowNode.X = _startX;
                                overflowNode.Y = _startY;
                                Entity overflowEntity = new Entity("overflow");
                                overflowEntity.Id = "overflow" + ((Entity)newNode.SourceData).Id;
                                overflowNode.SourceData = overflowEntity;

                                Nodes.Add(overflowNode);
                                newNode.ParentNode.OverflowNode = overflowNode;
                                newNode.ReplacedByOverflow = overflowNode;

                            }
                            else if (linkToExisting.Source.ParentNode == linkToExisting.Target && !alreadyAdded)
                            {
                                overflowAlreadyAdded = true;
                                linkToExisting.Source.ReplacedByOverflow = linkToExisting.Target.OverflowNode;

                            }

                            if (newNode.ReplacedByOverflow != null)
                            {
                                if (newNode.ReplacedByOverflow.Children == null)
                                    newNode.ReplacedByOverflow.Children = new List<EntityNode>();
                                if (!newNode.ReplacedByOverflow.Children.Contains(newNode))
                                    newNode.ReplacedByOverflow.Children.Add(newNode);
                            }

                        }

                        if (!overflowAlreadyAdded)
                        {
                            if (linkToExisting.Source.ReplacedByOverflow != null)
                            {
                                linkToExisting.Source = linkToExisting.Source.ReplacedByOverflow;
                                linkToExisting.Source.Links.Add(linkToExisting);
                                if (!linkToExisting.Id.StartsWith("overflow"))
                                    linkToExisting.Id = "overflow" + linkToExisting.Id;
                            }

                            if (!linkIndex.ContainsKey(linkToExisting.Id))
                            {
                                linkIndex[linkToExisting.Id] = linkToExisting;

                                Links.Add(linkToExisting);
                            }
                            else
                            {

                            }
                        }

                    }

                }
            }
            if (newNode.ReplacedByOverflow == null)
            {
                if (!alreadyAdded)
                {
                    Nodes.Add(newNode);
                }
            }
        }
Пример #14
0
        /// <summary>
        /// Extracts additional column display values from the search result
        /// The name attribute can now be a column separated list of attribute logical names
        /// </summary>
        /// <param name="columnAttributes"></param>
        /// <param name="fetchResult"></param>
        /// <param name="results"></param>
        /// <param name="i"></param>
        internal static void GetExtraColumns(string[] columnAttributes, EntityCollection fetchResult, AutoCompleteItem[] results, int i)
        {
            if (columnAttributes != null)
            {
                List<string> columnValues = new List<string>();
                bool first = true;
                // Get the additional column attributes to display
                foreach (string attribute in columnAttributes)
                {
                    if (first)
                    {
                        first = false;
                        continue;
                    }
                    string value = "";
                    Entity record = fetchResult.Entities[i];

                    if (record.FormattedValues.ContainsKey(attribute + "name"))
                    {
                        value = record.FormattedValues[attribute + "name"];
                    }
                    else
                    {
                        value = record.GetAttributeValue(attribute).ToString();
                    }
                    columnValues.Add(value);

                }
                results[i].ColumnValues = (string[])columnValues;
            }
        }
Пример #15
0
        public void OwnerSearchCommand(string term, Action<EntityCollection> callback)
        {

            Dictionary<string, string> searchTypes = new Dictionary<string, string>();
            searchTypes["systemuser"] = "******";
            searchTypes["team"] = "name";

            int resultsBack = 0;
            List<Entity> mergedEntities = new List<Entity>();
            Action<EntityCollection> result = delegate(EntityCollection fetchResult)
            {
                resultsBack++;
                // Merge in the results
                mergedEntities.AddRange((Entity[])(object)fetchResult.Entities.Items());

                mergedEntities.Sort(delegate(Entity x, Entity y)
                {
                    return string.Compare(x.GetAttributeValueString("name"), y.GetAttributeValueString("name"));
                });
                if (resultsBack == searchTypes.Count)
                {
                    EntityCollection results = new EntityCollection(mergedEntities);
                    callback(results);
                }
            };

            foreach (string entity in searchTypes.Keys)
            {
                SearchRecords(term, result, entity, searchTypes[entity]);
            }
        }
Пример #16
0
        public void RecordSearchCommand(string term, Action<EntityCollection> callback)
        {
            // Get the option set values

            int resultsBack = 0;
            List<Entity> mergedEntities = new List<Entity>();
            Action<EntityCollection> result = delegate(EntityCollection fetchResult)
            {
                resultsBack++;
                // Merge in the results
                mergedEntities.AddRange((Entity[])(object)fetchResult.Entities.Items());

                mergedEntities.Sort(delegate (Entity x, Entity y){
                    return string.Compare(x.GetAttributeValueString("name"), y.GetAttributeValueString("name"));
                });
                if (resultsBack == connectToTypes.Count)
                {
                    EntityCollection results = new EntityCollection(mergedEntities);
                    callback(results);
                }
            };

            foreach (string entity in connectToTypes.Keys)
            {
                SearchRecords(term, result, entity, connectToTypes[entity]);
            }
        }