protected void AddMultiValueRelation(IAssetType assetType, Asset asset, string TableName, string attributeName, string valueList)
        {
            IAttributeDefinition customerAttribute = assetType.GetAttributeDefinition(attributeName);
            string[] values = valueList.Split(';');
            foreach (string value in values)
            {
                //SPECIAL CASE: Skip "Member:20" for Scope.Members attribute.
                if (assetType.Token == "Scope" && attributeName == "Members" && value == "Member:20") continue;

                if (String.IsNullOrEmpty(value)) continue;

                string newAssetOID = GetNewAssetOIDFromDB(value, TableName);

                if (String.IsNullOrEmpty(newAssetOID) == false)

                    //SPECIAL CASE: Epic conversion issue. If setting story dependants or dependencies, ensure that we do not set for Epic values.
                    if ((attributeName == "Dependants" || attributeName == "Dependencies") && newAssetOID.Contains("Epic"))
                    {
                        continue;
                    }
                    else
                    {
                        asset.AddAttributeValue(customerAttribute, newAssetOID);
                    }
            }
        }
 internal Entity(Asset asset, IEntityFieldTypeResolver typeResolver)
     : base(asset)
 {
     Id = asset.Oid.Momentless.ToString();
     TypeName = asset.AssetType.Token;
     TypeResolver = typeResolver;
 }
 private void ValidateAsset(Asset asset, IDictionary<Asset, List<RequiredFieldsDto>> validationResults) {
     var fields = Validate(asset);
     
     if (fields.Count > 0) {
         validationResults.Add(asset, fields);
     }
 }
        private Project(Asset asset) : base(asset, null) {
            // the following check is for unit tests
            if(asset == null || asset.Children == null) {
                return;
            }

            Children.AddRange(asset.Children.Select(item => WorkitemFactory.CreateProject(item, this)));
        }
        private void DeleteAsset(Asset subject)
        {
            if(subject == null) {
                return;
            }

            var operation = subject.AssetType.GetOperation(VersionOneProcessor.DeleteOperation);
            services.ExecuteOperation(operation, subject.Oid);
        }
 internal static new PrimaryWorkitem Create(Asset asset, IDictionary<string, PropertyValues> listPropertyValues, IEntityFieldTypeResolver typeResolver, IList<Member> owners = null) {
     switch(asset.AssetType.Token) {
         case VersionOneProcessor.StoryType:
             return new Story(asset, listPropertyValues, typeResolver, owners);
         case VersionOneProcessor.DefectType:
             return new Defect(asset, listPropertyValues, typeResolver, owners);
         default:
             throw new NotSupportedException("Type " + asset.AssetType.Token + " is not supported in factory method");
     }
 }
 private static void SetAssetAttribute(Asset asset, string attrName, object value) {
     var type = asset.AssetType;
     var def = type.GetAttributeDefinition(attrName);
     
     if (value == null || (value is Oid && value.Equals(Oid.Null))) {
         asset.EnsureAttribute(def);
     } else {
         asset.SetAttributeValue(def, value);
     }
 }
        public void WriteAsset(Asset asset) {
            writer.WriteStartElement("Asset");

            if(!asset.Oid.IsNull) {
                writer.WriteAttributeString("id", asset.Oid.Token);
            }

            foreach(var attribute in asset.Attributes.Values) {
                WriteAttributeReference(attribute);
            }

            writer.WriteEndElement();
        }
        /// <summary>
        /// Validate single Asset attribute. If attribute is not loaded, it is just considered invalid.
        /// </summary>
        /// <param name="asset">Asset to validate</param>
        /// <param name="attributeDefinition">Attribute definition of validated attribute</param>
        /// <returns>Validation result</returns>
        // TODO create separate private method to avoid excessive GetRequiredFields() calls
        public bool Validate(Asset asset, IAttributeDefinition attributeDefinition)
        {
            GetRequiredFields(asset.AssetType);
            asset.EnsureAttribute(attributeDefinition);
            Attribute attribute = asset.GetAttribute(attributeDefinition);
            bool result = attribute != null && !(IsMultiValueAndUnfilled(attribute) || IsSingleValueAndUnfilled(attribute));

            if (!result && attribute != null)
            {
                result = !attribute.HasChanged && !isAttributeUnfilledOnServer(asset, attributeDefinition);
            }

            return result;
        }
		public void AddLinkToWorkitem()
		{
			const string url = "http://qqq.com";
			const string title = "Url title";
			var workitemAsset = new Asset(new TestOid(new TestAssetType("Workitem"), 100, null));
			var workitem = new TestWorkitem(workitemAsset, null);
			var link = new Link(url, title);
			var linkAsset = new TestAssetType("Link");
			var asset = new Asset(new TestOid(new TestAssetType("Link"), 10, null));

			Expect.Call(_mockMetaModel.GetAssetType(VersionOneProcessor.LinkType)).Return(linkAsset);
			Expect.Call(_mockQueryBuilder.Query(string.Empty, Filter.Empty())).IgnoreArguments().Return(new AssetList());
			Expect.Call(_mockServices.New(null, null)).IgnoreArguments().Return(asset);
			Expect.Call(() => _mockServices.Save(asset));

			_repository.ReplayAll();
			_processor.AddLinkToEntity(workitem, link);
			_repository.VerifyAll();
		}
        internal Asset CreateAssetForPrimaryWorkitem(string typeToken) {
            var type = ResolveAssetTypeFor(typeToken);

            try {
                var asset = new Asset(type);

                SetupAssetAttributes(asset, typeToken);
                LoadAssetAttribute(asset, "Scope.Name", currentProject.GetProperty(Entity.NameProperty));
                LoadAssetAttribute(asset, "Timebox.Name", currentProject.GetProperty("Schedule.EarliestActiveTimebox.Name"));
                SetAssetAttribute(asset, "Timebox", currentProject.GetProperty("Schedule.EarliestActiveTimebox"));
                SetAssetAttribute(asset, "Scope", currentProject.Asset.Oid);

                return asset;
            } catch(MetaException ex) {
                throw new DataLayerException("Cannot create new " + typeToken, ex);
            } catch(APIException ex) {
                throw new DataLayerException("Cannot create new " + typeToken, ex);
            }
        }
        /// <summary>
        /// Validate all available Asset attributes. 
        /// If there are required attributes that haven't been loaded, these are considered failures.
        /// In some cases, attributes could exist on server and have valid values, but it's up to user to retrieve them or ignore corresponding validation errors.
        /// </summary>
        /// <param name="asset">Asset to validate</param>
        /// <returns>Collection of attribute definitions for attributes which values do not pass validation</returns>
        public ICollection<IAttributeDefinition> Validate(Asset asset)
        {
            GetRequiredFields(asset.AssetType);
            ICollection<IAttributeDefinition> results = new List<IAttributeDefinition>();
            ICollection<IAttributeDefinition> requiredAttributes = requiredFields[asset.AssetType];

            foreach (IAttributeDefinition attributeDefinition in requiredAttributes)
            {
                asset.EnsureAttribute(attributeDefinition);
                Attribute attribute = asset.GetAttribute(attributeDefinition);
                
                if(attribute == null || !Validate(asset, attributeDefinition)) 
                {
                    results.Add(attributeDefinition);
                }
            }

            return results;
        }
        internal Workitem(Asset asset, Workitem parent, IEntityContainer entityContainer) : base(asset, entityContainer) {
            Parent = parent;

            //TODO maybe make one more constructor for tests instead of this?
            // the following check is for unit tests            
            if(asset == null || asset.Children == null) {
                return;
            }

            if(!SupportedTypes.Contains(asset.AssetType.Token)) {
                throw new ArgumentException(string.Format("Illegal asset type, '{0}' is not supported.", asset.AssetType.Token));
            }

            foreach (var childAsset in asset.Children.Where(childAsset => DataLayer.ShowAllTasks || DataLayer.AssetPassesShowMyTasksFilter(childAsset))) {
                Children.Add(WorkitemFactory.CreateWorkitem(childAsset, this, entityContainer));
                Children.Sort(new WorkitemComparer(TestType, TaskType));
            }

            Children.TrimExcess();
        }
        internal Asset CreateAssetForSecondaryWorkitem(string typeToken, Workitem parent) {
            var type = ResolveAssetTypeFor(typeToken);

            try {
                var asset = new Asset(type);

                SetupAssetAttributes(asset, typeToken);
                SetAssetAttribute(asset, "Parent", parent.Asset.Oid);
                LoadAssetAttribute(asset, "Scope.Name", currentProject.GetProperty(Entity.NameProperty));
                LoadAssetAttribute(asset, "Parent.Name", parent.GetProperty(Entity.NameProperty));
                LoadAssetAttribute(asset, "Timebox.Name", parent.GetProperty("Timebox.Name"));

                parent.Asset.Children.Add(asset);

                return asset;
            } catch(MetaException ex) {
                throw new DataLayerException("Cannot create new " + typeToken, ex);
            } catch(APIException ex) {
                throw new DataLayerException("Cannot create new " + typeToken, ex);
            }
        }
        public static Asset CreateTeamRoom(Project project, Asset schedule)
        {
            IAssetType assetType = Program.MetaModel.GetAssetType("TeamRoom");
            IAttributeDefinition nameAttribute = assetType.GetAttributeDefinition("Name");
            IAttributeDefinition scheduleAttribute = assetType.GetAttributeDefinition("Schedule");
            IAttributeDefinition scopeAttribute = assetType.GetAttributeDefinition("Scope");
            IAttributeDefinition participantAttribute = assetType.GetAttributeDefinition("Participants");
            
            Asset newTeamRoom = Program.Services.New(assetType, null);
            newTeamRoom.SetAttributeValue(nameAttribute, project.Name + " TeamRoom");
            newTeamRoom.SetAttributeValue(scheduleAttribute, schedule.Oid);
            newTeamRoom.SetAttributeValue(scopeAttribute, project.Id);

            foreach (Member member in project.Members)
            {
                newTeamRoom.AddAttributeValue(participantAttribute, member.Id);
            }

            Program.Services.Save(newTeamRoom);
            return newTeamRoom;
        }
		public void AddLinkToWorkitemWithExistingLink()
		{
			const string type = "Link";
			const string url = "http://qqq.com";
			const string title = "Url title";
			var workitemAsset = new Asset(new TestOid(new TestAssetType("Workitem"), 100, null));
			var workitem = new TestWorkitem(workitemAsset, null);
			var link = new Link(url, title);
			var linkAsset = new TestAssetType(type);
			var definitions = new Dictionary<string, IAttributeDefinition> {
                {Entity.NameProperty, new TestAttributeDefinition(linkAsset)},
                {Link.OnMenuProperty, new TestAttributeDefinition(linkAsset)},
                {Link.UrlProperty, new TestAttributeDefinition(linkAsset)},
            };
			var linkOid = new TestOid(new TestAssetType(type, definitions), 10, null);
			var existedLink = new Asset(linkOid);

			Expect.Call(_mockMetaModel.GetAssetType(VersionOneProcessor.LinkType)).Return(linkAsset);
			Expect.Call(_mockQueryBuilder.Query(string.Empty, Filter.Empty())).IgnoreArguments().Return(new AssetList { existedLink });

			_repository.ReplayAll();
			_processor.AddLinkToEntity(workitem, link);
			_repository.VerifyAll();
		}
 internal MultiValueAttribute(IAttributeDefinition def, Asset asset) : base(def, asset) { }
 protected Attribute(IAttributeDefinition def, Asset asset)
 {
     this.def   = def;
     this.asset = asset;
 }
 internal FieldInfo(Asset asset) : base(asset) {
 }        
        private bool isAttributeUnfilledOnServer(Asset asset, IAttributeDefinition attributeDefinition)
        {
            if (asset.Oid == Oid.Null)
            {
                return true;
            }
            Query query = new Query(asset.Oid);
            query.Selection.Add(attributeDefinition);
            QueryResult result = null;
            try
            {
                result = services.Retrieve(query);
            }
            catch (Exception)
            {
                //do nothing
            }

            if (result != null)
            {
                Attribute attr = result.Assets[0].GetAttribute(attributeDefinition);
                try
                {
                    return IsSingleValueAndUnfilled(attr) && IsMultiValueAndUnfilled(attr);
                }
                catch (APIException)
                {
                    // do nothing
                }
            }

            return true; // there is no data on the server.
        }
 internal Test(Asset asset, IDictionary<string, PropertyValues> listValues, IList<Member> owners, IEntityFieldTypeResolver typeResolver) 
     : base(asset, listValues, owners, typeResolver) { }
 internal VirtualWorkitem(Asset asset, Workitem parent, IEntityContainer entityContainer) : base(asset, parent, entityContainer) { }
 public Member(Asset asset)
     : base(asset, null)
 {
 }
        private IEnumerable<ProjectWrapper> GetProjectWrapperList(Asset asset, IAttributeDefinition attrName, int depth) {
            var list = new List<ProjectWrapper>{new ProjectWrapper(asset, asset.GetAttribute(attrName).Value.ToString(), depth)};

            foreach (var child in asset.Children) {
                list.AddRange(GetProjectWrapperList(child, attrName, depth + 1));
            }
            
            return list;
        }
        protected void AddRallyMentionsValue(IAssetType assetType, Asset asset, string baseAssetType, string assetOID)
        {
            IAttributeDefinition mentionsAttribute = assetType.GetAttributeDefinition("Mentions");
            string newAssetOID = String.Empty;

            if (baseAssetType == "Story")
            {
                //First try stories table.
                newAssetOID = GetNewAssetOIDFromDB(assetOID, "Stories");

                //If not found, try epics table.
                if (String.IsNullOrEmpty(newAssetOID) == true)
                {
                    newAssetOID = GetNewAssetOIDFromDB(assetOID, "Epics");
                }
            }
            else if (baseAssetType == "Defect")
            {
                newAssetOID = GetNewAssetOIDFromDB(assetOID, "Defects");
            }
            else if (baseAssetType == "Task")
            {
                newAssetOID = GetNewAssetOIDFromDB(assetOID, "Tasks");
            }
            else if (baseAssetType == "Test")
            {
                //First try tests table.
                newAssetOID = GetNewAssetOIDFromDB(assetOID, "Tests");

                //If not found, try regression tests table.
                if (String.IsNullOrEmpty(newAssetOID) == true)
                {
                    newAssetOID = GetNewAssetOIDFromDB(assetOID, "RegressionTests");
                }
            }

            if (String.IsNullOrEmpty(newAssetOID) == false)
                asset.AddAttributeValue(mentionsAttribute, newAssetOID);
        }
 internal BuildRun(Asset asset, IDictionary<string, PropertyValues> listValues, IEntityFieldTypeResolver typeResolver) : base(asset, typeResolver) {
     ListValues = listValues;
 }
		public void CreateWorkitem()
		{
			const string type = "Story";
			const string title = "Story Name";
			const string description = "Story description";
			const string projectToken = "Scope:0";
			const string externalFieldName = "FieldName";
			const string externalId = "externalId";
			const string externalSystemName = "External System Name";
			const string priorityId = "Priority:12";
			const string owners = "Onwer_1,Owners_2";

			var memberAssetType = new TestAssetType("Member");
			var projectAssetType = new TestAssetType("Project");
			var priorityAssetType = new TestAssetType("Priority");

			var storyAttributes = new Dictionary<string, IAttributeDefinition> {
                {"Owners", new TestAttributeDefinition(memberAssetType, true, false, false)},
            };
			var storyAssetType = new TestAssetType("Story", storyAttributes);

			var source = TestValueId.Create(externalSystemName, "Source", 333);
			var sources = new PropertyValues(new List<ValueId> { source });
			var assetStory = new Asset(storyAssetType);
			var ownersAssets = new AssetList {
                new Asset(new TestOid(new TestAssetType("Member"), 1, null)),
                new Asset(new TestOid(new TestAssetType("Member"), 2, null)),
            };
			var queryResult = new QueryResult(ownersAssets, 2, null);

			Expect.Call(_mockMetaModel.GetAssetType("Scope")).Return(projectAssetType);
			Expect.Call(_mockQueryBuilder.QueryPropertyValues(VersionOneProcessor.WorkitemSourceType)).Return(sources);
			Expect.Call(_mockMetaModel.GetAssetType("Story")).Return(storyAssetType);
			Expect.Call(_mockServices.New(storyAssetType, Oid.Null)).Return(assetStory);
			Expect.Call(_mockMetaModel.GetAssetType("Member")).Return(memberAssetType);
			Expect.Call(_mockServices.Retrieve(null)).IgnoreArguments().Return(queryResult);
			Expect.Call(_mockMetaModel.GetAssetType("Priority")).Return(priorityAssetType);
			Expect.Call(() => _mockServices.Save(assetStory));

			Expect.Call(_mockMetaModel.GetAssetType("Story")).Return(storyAssetType);
			Expect.Call(_mockQueryBuilder.Query("Story", new FilterTerm(null))).IgnoreArguments().Return(new AssetList { assetStory });
			Expect.Call(_mockQueryBuilder.ListPropertyValues).Return(null);
			Expect.Call(_mockQueryBuilder.TypeResolver).Return(null);

			_repository.ReplayAll();

			_processor.CreateWorkitem(type, title, description, projectToken,
				externalFieldName, externalId, externalSystemName,
				priorityId, owners);
			_repository.VerifyAll();
		}
 protected internal FeatureGroup(Asset asset, IDictionary<string, PropertyValues> listValues, IList<Workitem> children, IList<Member> owners, IEntityFieldTypeResolver typeResolver)
     : base(asset, listValues, owners, typeResolver)
 {
     Children = children;
 }
 private static string GetAttributeValue(Asset asset, IAttributeDefinition attributeDef)
 {
     var value = asset.GetAttribute(attributeDef).Value;
     return (null != value) ? value.ToString() : "";
 }
 private void AssertMultiValueAttribute(object expected, Asset subject, string attributeToken)
 {
     IAttributeDefinition def = _svc.StubCentral.MetaModel.GetAttributeDefinition(attributeToken);
     IList values = subject.GetAttribute(def).ValuesList;
     Assert.IsNotNull(values);
     Assert.IsTrue(values.Contains(expected), "Attribute: {0}\n Values: {1}\n Expected: {2}", attributeToken, EnumerateValues(values), expected);
 }
 private void AssertSingleValueAttribute(object expected, Asset subject, string attributeToken)
 {
     IAttributeDefinition def = _svc.StubCentral.MetaModel.GetAttributeDefinition(attributeToken);
     object actual = subject.GetAttribute(def).Value;
     Assert.AreEqual(expected, actual, attributeToken);
 }