void buttonSave_Click(object sender, EventArgs e)
	{
		try
		{
			Page.Validate();
			if (Page.IsValid)
			{
				Association association = AssociationBL.GetBy(base.AssociationId, false);
				if (association == null)
				{
					// insert
					association = new Association();
					association.Name = TextName.Text;
					association.Description = TextDescription.Text;
					association = AssociationBL.Insert(association);
				}
				else
				{
					// update
					association.Name = TextName.Text;
					association.Description = TextDescription.Text;
					association = AssociationBL.Update(association);
				}
				if (association == null) { message.Text = "Save failed"; }
				else { _redirectToListUrl(); }
			}
		}
		catch (Exception ex)
		{
			message.Text = ex.Message;
		}
	}
        public void Add(Association association)
        {
            if (string.IsNullOrEmpty(association.Name))
            {
                throw new Exception("You must complete the field name to continue!");
            }
            else if(string.IsNullOrEmpty(association.Action))
            {
                throw new Exception("You must choose an action to continue!");
            }
            else if (string.IsNullOrEmpty(association.Destination))
            {
                throw new Exception("You must complete the field destination choosing a folder to continue!");
            }
            else if (string.IsNullOrEmpty(association.Extension))
            {
                throw new Exception("You must add a file extension to continue!");
            }
            else if (!isValidExtension(association.Extension))
            {
                throw new Exception("The extension is not correct, It must be in this format example: *.jpg or *.yourExtension");
            }
            else
            {
                if (!(_dassociation.Add(association) >= 1))
                {
                    throw new Exception("There was a problem adding this association, please try again.");
                }
            }

        }
 public static void SendAccept(Accept accept, Association asc)
 {
     var stream = asc.Stream;
     byte[] message = accept.Write();
     asc.Logger.Log("-->" + accept);
     stream.Write(message, 0, message.Length);
 }
Exemple #4
0
        public void Simple()
        {
            var assoc = new Association<int, string>(5, "aa");

            Assert.AreEqual(assoc.Key, 5);
            Assert.AreEqual(assoc.Value, "aa");
        }
        /// <summary>
        ///     Splits the DICOM object into chunks that are within the max PDU size
        /// </summary>
        /// <param name="dicomObject"> the DICOM objec to be split</param>
        /// <param name="maxPduSize">the max length (in bytes) for a PDU</param>
        /// <param name="asc">the association that the file will be sent</param>
        /// <returns></returns>
        private static List<byte[]> GetChunks(DICOMObject dicomObject, int maxPduSize, Association asc)
        {
            byte[] dicomBytes;
            using (var stream = new MemoryStream())
            {
                using (var dw = new DICOMBinaryWriter(stream))
                {
                    DICOMObjectWriter.Write(dw,
                        new DICOMWriteSettings
                        {
                            TransferSyntax =
                                TransferSyntaxHelper.GetSyntax(asc.PresentationContexts.First().TransferSyntaxes.First()),
                            DoWriteIndefiniteSequences = false
                        }, dicomObject);
                    dicomBytes = stream.ToArray();
                }
            }

            var split = new List<byte[]>();
            int i = 0;
            while (i < dicomBytes.Length)
            {
                int toTake = dicomBytes.Length >= (maxPduSize - 6) + i ? maxPduSize - 6 : dicomBytes.Length - i;
                byte[] fragment = dicomBytes.Skip(i).Take(toTake).ToArray();
                i += fragment.Length;
                split.Add(fragment);
            }
            return split;
        }
 public static Association createAssociation(string name, string rolename, Group group)
 {
     Association asso = new Association();
     asso.name = name;
     asso.roleName = rolename;
     asso.Item = group;
     return asso;
 }
        public AssociationsManager()
        {
            _association = null;

            InitializeComponent();
            //
            _bassociation = new BAssociation();
        }
Exemple #8
0
 public void Equality()
 {
     var assoc = new Association<int, string>(5, "aa");
     var assoc2 = new Association<int, string>(5, "aa");
     Assert.AreEqual(assoc.Key, assoc2.Key);
     Assert.AreEqual(assoc.Key, assoc2.Key);
     Assert.AreEqual(assoc, assoc2);
 }
		/// <summary>
		/// Stores an <see cref="Association"/> in the collection.
		/// </summary>
		/// <param name="association">The association to add to the collection.</param>
		public void Set(Association association) {
			Requires.NotNull(association, "association");
			lock (this.associations) {
				this.associations.Remove(association.Handle); // just in case one already exists.
				this.associations.Add(association);
			}

			Assumes.True(this.Get(association.Handle) == association);
		}
Exemple #10
0
        public void Simple()
        {
            var assoc = new Association<int, string>(5, "aa");
            var newAssoc = SerializeUtil.BinarySerializeDeserialize(assoc);

            Assert.AreEqual(assoc.Key, newAssoc.Key);
            Assert.AreEqual(assoc.Value, newAssoc.Value);
            Assert.AreNotSame(assoc, newAssoc);
        }
 public int Add(Association association)
 {
     try
     {
         _FileOContext.Associations.Add(association);
         return _FileOContext.SaveChanges();
     }
     catch (Exception) { return 0; }
 }
Exemple #12
0
		/// <summary>
		/// Stores an <see cref="Association"/> in the collection.
		/// </summary>
		/// <param name="association">The association to add to the collection.</param>
		public void Set(Association association) {
			Contract.Requires<ArgumentNullException>(association != null);
			Contract.Ensures(this.Get(association.Handle) == association);
			lock (this.associations) {
				this.associations.Remove(association.Handle); // just in case one already exists.
				this.associations.Add(association);
			}

			Contract.Assume(this.Get(association.Handle) == association);
		}
        public int Delete(Association association)
        {
            try
            {
               _FileOContext.Associations.Remove(association);
                return _FileOContext.SaveChanges(); 
            }
            catch (Exception) { return 0; }

        }
        public void ToKeyValuePairExample()
        {
            var association = new Association<int, string>(1, "dove");

            var pair = association.ToKeyValuePair();

            // The value and key will be the same as in the association.
            Assert.AreEqual(pair.Key, association.Key);
            Assert.AreEqual(pair.Value, association.Value);
        }
		public Association Insert(Association association)
		{
			association.Enabled = true;
			association.ID = Guid.NewGuid();
			association.Created = DateTime.Now;
			association.Modified = DateTime.Now;
			DataContextHelper.CurrentContext.Associations.InsertOnSubmit(association);
			DataContextHelper.CurrentContext.SubmitChanges();
			return association;
		}
 public static void SendReleaseResponse(Association asc)
 {
     var resp = new ReleaseResponse();
     asc.Logger.Log("-->" + resp);
     byte[] message = resp.Write();
     if (asc.Stream.CanWrite)
     {
         asc.Stream.Write(message, 0, message.Length);
     }
 }
Exemple #17
0
        public void XmlSimple()
        {
            var assoc = new Association<int, string>(5, "aa");
            var serialize = assoc.Serialize();
            var newAssoc = ObjectExtensions.Deserialize<Association<int, string>>(serialize);

            Assert.AreEqual(assoc.Key, newAssoc.Key);
            Assert.AreEqual(assoc.Value, newAssoc.Value);
            Assert.AreEqual(assoc, newAssoc);
        }
 public static void SendReject(Association asc)
 {
     var rej = new Reject
     {
         Result = RejectResult.REJECTED_PERMANENT,
         Reason = (byte) RejectReason_SCU.NO_REASON_GIVEN
     };
     asc.Logger.Log("-->" + rej);
     byte[] rejBytes = rej.Write();
     asc.Stream.Write(rejBytes, 0, rejBytes.Length);
 }
        public void ConstructorExample()
        {
            // Create a new association
            var association = new Association<int, string>(4, "four");

            // Key will be equal to 4
            Assert.AreEqual(association.Key, 4);

            // Value will be equal to "four"
            Assert.AreEqual(association.Value, "four");
        }
 public static void SendReleaseRequest(Association asc)
 {
     var req = new ReleaseRequest();
     asc.State = NetworkState.AWAITING_RELEASE_RESPONSE;
     asc.Logger.Log("-->" + req);
     byte[] message = req.Write();
     if ( asc.Stream.CanWrite)
     {
         asc.Stream.Write(message, 0, message.Length);
     }
    
 }
	void buttonCreate_ServerClick(object sender, EventArgs e)
	{
		Association association = new Association();
		association.Description = textDescription.InnerText.Trim();
		association.Name = textName.Value.Trim();
		association.Website = textWebsite.Value.Trim();
		association = AssociationBL.Insert(association);
		if (association != null)
		{
			this.DataBind();
		}
	}
 public static Association createAssociation(string name, string rolename, Group group, Attribute attr, Association association)
 {
     Association asso = new Association();
     asso.name = name;
     asso.roleName = rolename;
     if (group != null)
         asso.Item = group;
     else if (attr != null)
         asso.Item = attr;
     else if (association != null)
         asso.Item = association;
     return asso;
 }
        public void ValueExample()
        {
            var association = new Association<int, string>(1, "dove");

            // The value will be "dove".
            Assert.AreEqual(association.Value, "dove");

            // Set the value to "monkey".
            association.Value = "monkey";

            // The value will be "monkey".
            Assert.AreEqual(association.Value, "monkey");
        }
        public void KeyExample()
        {
            var association = new Association<int, string>(1, "monkey");

            // The key's value will be 1.
            Assert.AreEqual(association.Key, 1);

            // Set the key's value to 3.
            association.Key = 3;

            // The key's value will be 3.
            Assert.AreEqual(association.Key, 3);
        }
 public void Delete(Association association)
 {
     if (association.Id == 0)
     {
         throw new Exception("You must choose an association from the list!");
     }
     else
     {
         if (!(_dassociation.Delete(association) >= 1))
         {
             throw new Exception("There was a problem deleting the association, please try again!");
         }
     }
 }
		public Association Update(Association association)
		{
			Association value = DataContextHelper.CurrentContext.Associations.FirstOrDefault<Association>(n => n.ID.Equals(association.ID));
			if (value != null)
			{
				value.Name = association.Name.Trim();
				value.Website =  association.Website;
				value.Description = association.Description.Trim();
				value.Enabled = association.Enabled;
				value.Modified = DateTime.Now;
				DataContextHelper.CurrentContext.SubmitChanges();
			}
			return value;
		}
 public static void LogData(this AbstractDIMSEBase dimse, Association asc)
 {
     if (dimse is AbstractDIMSE)
     {
         var abd = dimse as AbstractDIMSE;
         if (abd.HasData)
         {
             foreach (var el in abd.Data.Elements)
             {
                 asc.Logger.Log(el);
             }
             asc.Logger.Log("");//Space
         }
     }
 }
        public int Update(Association association)
        {
            try
            {

                var old = _FileOContext.Associations.Find(association.Id);
                old.Name = association.Name;
                old.Extension = association.Extension;
                old.Destination = association.Destination;
                old.Action = association.Action;

                return _FileOContext.SaveChanges();
            }
            catch (Exception) { return 0; }
        }
        public ActionResult Edit(int id, int associationType, int constiuent)
        {
            var association = new Association();

            var constituentId =  Convert.ToInt32(Session["loggedInConstituentId"]);
            TryUpdateModel(association);
            association.Type = new AssociationType {Id = associationType};
            association.Constituent = new Constituent {Id =constituentId };
            association.AssociatedConstituent = new Constituent() { Id = constiuent };

            mapper = new AutoDataContractMapper();
            var associationData = new AssociationData();
            mapper.Map(association, associationData);

            HttpHelper.Put(string.Format(serviceBaseUri+"/Associations/{0}", id), associationData);
            return PartialView(new GridModel(GetAssociations( Convert.ToInt32(Session["loggedInConstituentId"]))));
        }
Exemple #30
0
        public void Simple()
        {
            var associationKeyComparer = new AssociationKeyComparer<int, string>();

            var association1 = new Association<int, string>(5, "5");
            var association2 = new Association<int, string>(5, "6");
            var association3 = new Association<int, string>(3, "5");
            var association4 = new Association<int, string>(5, "5");

            Assert.AreEqual(associationKeyComparer.Compare(association1, association2), 0);
            Assert.AreEqual(associationKeyComparer.Compare(association1, association3), 1);
            Assert.AreEqual(associationKeyComparer.Compare(association1, association4), 0);

            Assert.AreEqual(associationKeyComparer.Compare(association2, association1), 0);
            Assert.AreEqual(associationKeyComparer.Compare(association3, association1), -1);
            Assert.AreEqual(associationKeyComparer.Compare(association4, association1), 0);
        }
Exemple #31
0
        protected override void InvokeInternal(CommandProcessorContext cpc)
        {
            var service  = cpc.EditingContext.GetEFArtifactService();
            var artifact = service.Artifact;

            // the model that we want to add the association to
            var model = artifact.StorageModel();

            // check for uniqueness
            var assocName    = Name;
            var assocSetName = assocName;

            if (UniquifyNames)
            {
                assocName    = ModelHelper.GetUniqueName(typeof(Association), model, assocName);
                assocSetName = ModelHelper.GetUniqueName(typeof(AssociationSet), model.FirstEntityContainer, assocName);
            }
            else
            {
                // check for uniqueness of the association name
                string msg = null;
                if (ModelHelper.IsUniqueName(typeof(Association), model, assocName, false, out msg) == false)
                {
                    throw new InvalidOperationException(msg);
                }

                // check for uniqueness of the association set name
                if (ModelHelper.IsUniqueName(typeof(AssociationSet), model.FirstEntityContainer, assocSetName, false, out msg) == false)
                {
                    throw new InvalidOperationException(msg);
                }
            }

            // create the new item in our model
            var association = new Association(model, null);

            association.LocalName.Value = assocName;
            model.AddAssociation(association);
            XmlModelHelper.NormalizeAndResolve(association);

            // create the ends of the association
            var fkEnd = new AssociationEnd(association, null);

            fkEnd.Type.SetRefName(FkTable);
            fkEnd.Role.Value = FkRoleNameOverride ?? ModelHelper.CreateFKAssociationEndName(FkTable.LocalName.Value);
            if (FkMultiplicityOverride != null)
            {
                fkEnd.Multiplicity.Value = FkMultiplicityOverride;
            }
            else
            {
                fkEnd.Multiplicity.Value = DoesFkFormPk ? ModelConstants.Multiplicity_ZeroOrOne : ModelConstants.Multiplicity_Many;
            }
            association.AddAssociationEnd(fkEnd);
            XmlModelHelper.NormalizeAndResolve(fkEnd);

            var pkEnd = new AssociationEnd(association, null);

            pkEnd.Type.SetRefName(PkTable);
            pkEnd.Role.Value = PkRoleNameOverride ?? ModelHelper.CreatePKAssociationEndName(PkTable.LocalName.Value);
            if (PkMultiplicityOverride != null)
            {
                pkEnd.Multiplicity.Value = PkMultiplicityOverride;
            }
            else
            {
                pkEnd.Multiplicity.Value = IsNullableFk ? ModelConstants.Multiplicity_ZeroOrOne : ModelConstants.Multiplicity_One;
            }
            association.AddAssociationEnd(pkEnd);
            XmlModelHelper.NormalizeAndResolve(pkEnd);

            var cmd = new CreateAssociationSetCommand(assocSetName, association, ModelSpace.Storage);

            CommandProcessor.InvokeSingleCommand(cpc, cmd);
            var set = cmd.AssociationSet;

            Debug.Assert(set != null, "failed to create an AssociationSet");

            Association = association;
            _createdAssociationFkEnd = fkEnd;
            _createdAssociationPkEnd = pkEnd;
        }
Exemple #32
0
        protected override DesignTimeMetadata GetDesignTimeMetadata(bool isDraft)
        {
            var metadata = new DesignTimeMetadata();

            var container     = this.DB.MetadataWorkspace.GetEntityContainer(this.DB.DefaultContainerName, DataSpace.CSpace);
            var entitySetsDic = (from meta in container.BaseEntitySets
                                 where meta.BuiltInTypeKind == BuiltInTypeKind.EntitySet
                                 select new { EntitySetName = meta.Name, EntityTypeName = meta.ElementType.Name }).ToDictionary(es => es.EntityTypeName);


            var CSpace         = this.DB.MetadataWorkspace.GetItemCollection(System.Data.Metadata.Edm.DataSpace.CSpace);
            var SSpace         = this.DB.MetadataWorkspace.GetItemCollection(System.Data.Metadata.Edm.DataSpace.SSpace);
            var entityEdmTypes = CSpace.GetItems <EntityType>().OrderBy(e => e.Name).ToArray();

            //var dbEntityEdmTypes = SSpace.GetItems<EntityType>().ToDictionary(r => r.Name);

            Array.ForEach(entityEdmTypes, (entityEdmType) =>
            {
                if (entityEdmType.Abstract)
                {
                    return;
                }

                string entityTypeName = entityEdmType.Name;
                string name           = entityTypeName;
                if (entityEdmType.BaseType != null)
                {
                    name = entityEdmType.BaseType.Name;
                }
                string entitySetName = entitySetsDic[name].EntitySetName;
                var keys             = entityEdmType.KeyMembers.Select(k => k.Name).ToArray();
                //string dbTableName = this.GetMappedEntitySetName(entitySetName);
                //var dbEntityEdm =  dbEntityEdmTypes[dbTableName];
                //Type entityType = this.GetEntityType(entitySetName);
                Type entityType     = this.GetEntityType2(entityTypeName);
                DbSetInfo dbSetInfo = new DbSetInfo()
                {
                    dbSetName = entityTypeName
                };
                dbSetInfo.SetEntityType(entityType);
                metadata.DbSets.Add(dbSetInfo);
                var edmProps = entityEdmType.Properties.ToArray();

                short pkNum = 0;
                Array.ForEach(edmProps, (edmProp) =>
                {
                    Field fieldInfo = new Field()
                    {
                        fieldName = edmProp.Name
                    };
                    if (keys.Contains(fieldInfo.fieldName))
                    {
                        ++pkNum;
                        fieldInfo.isPrimaryKey = pkNum;
                        fieldInfo.isReadOnly   = true;
                    }
                    bool isComputed           = this.isComputed(edmProp);
                    fieldInfo.isAutoGenerated = this.isAutoGenerated(edmProp);
                    fieldInfo.isNullable      = edmProp.Nullable;
                    fieldInfo.isReadOnly      = fieldInfo.isAutoGenerated;
                    bool isArray       = false;
                    string propType    = edmProp.TypeUsage.EdmType.Name;
                    fieldInfo.dataType = this.DataTypeFromType(propType, out isArray);
                    var facets         = edmProp.TypeUsage.Facets;
                    var maxLenFacet    = facets.Where(f => f.Name == "MaxLength").FirstOrDefault();
                    if (maxLenFacet != null)
                    {
                        try
                        {
                            fieldInfo.maxLength = (short)Convert.ChangeType(maxLenFacet.Value, typeof(short));
                        }
                        catch
                        {
                        }
                    }
                    //gess that the property is rowversion
                    fieldInfo.fieldType = (isComputed && fieldInfo.dataType == DataType.Binary) ? FieldType.RowTimeStamp : FieldType.None;
                    dbSetInfo.fieldInfos.Add(fieldInfo);
                });
            });

            var associations = CSpace.GetItems <AssociationType>().Where(a => a.IsForeignKey).OrderBy(e => e.Name);

            Func <EdmType, string> fn_name = (EdmType n) =>
            {
                if (n.FullName.Contains('['))
                {
                    Regex  regex = new Regex(".*?\\[(.*?)\\].*?");
                    Match  match = regex.Match(n.FullName);
                    string table = match.Groups[1].Value;
                    return(table);
                }
                else
                {
                    return(n.FullName);
                }
            };

            foreach (AssociationType asstype in associations)
            {
                var endMembers = asstype.RelationshipEndMembers;

                foreach (ReferentialConstraint constraint in asstype.ReferentialConstraints)
                {
                    try
                    {
                        Association ass = metadata.Associations.Where(a => a.name == constraint.ToString()).FirstOrDefault();

                        if (ass == null)
                        {
                            var    parentEnd        = (constraint.FromRole.RelationshipMultiplicity == RelationshipMultiplicity.One || constraint.FromRole.RelationshipMultiplicity == RelationshipMultiplicity.ZeroOrOne) ? constraint.FromRole : constraint.ToRole;
                            var    childEnd         = constraint.FromRole == parentEnd ? constraint.ToRole : constraint.FromRole;
                            var    parent           = parentEnd.TypeUsage.EdmType;
                            var    child            = childEnd.TypeUsage.EdmType;
                            string parentName       = fn_name(parent);
                            string childName        = fn_name(child);
                            var    parentEntity     = entityEdmTypes.Where(en => parentName == en.FullName).First();
                            var    childEntity      = entityEdmTypes.Where(en => childName == en.FullName).First();
                            var    parentToChildren = parentEntity.NavigationProperties.Where(np => np.FromEndMember.Name == parentEnd.Name && np.ToEndMember.Name == childEnd.Name).FirstOrDefault();
                            var    childToParent    = childEntity.NavigationProperties.Where(np => np.FromEndMember.Name == childEnd.Name && np.ToEndMember.Name == parentEnd.Name).FirstOrDefault();

                            ass      = new Association();
                            ass.name = constraint.ToString();
                            metadata.Associations.Add(ass);
                            ass.parentDbSetName      = parentEntity.Name;
                            ass.childDbSetName       = childEntity.Name;
                            ass.parentToChildrenName = parentToChildren == null ? "" : parentToChildren.Name;
                            ass.childToParentName    = childToParent == null ? "" : childToParent.Name;

                            var parentArr = constraint.FromRole == parentEnd?constraint.FromProperties.ToArray() : constraint.ToProperties.ToArray();

                            var childArr = constraint.FromRole == parentEnd?constraint.ToProperties.ToArray() : constraint.FromProperties.ToArray();

                            for (int i = 0; i < parentArr.Length; ++i)
                            {
                                FieldRel frel = null;
                                frel = ass.fieldRels.Where(fr => fr.parentField == parentArr[i].Name && fr.childField == childArr[i].Name).FirstOrDefault();
                                if (frel == null)
                                {
                                    frel = new FieldRel();
                                    ass.fieldRels.Add(frel);
                                    frel.parentField = parentArr[i].Name;
                                    frel.childField  = childArr[i].Name;
                                }
                            }
                        }
                    }
                    catch (Exception)
                    {
                        throw;
                    }
                }
            }
            return(metadata);
        }
Exemple #33
0
 public static GeometryAttribute <T> CheckAssociation <T>(this GeometryAttribute <T> self, Association assoc) where T : unmanaged
 => self?.Descriptor?.Association == assoc ? self : null;
Exemple #34
0
 /// <summary>
 /// Event handler for the SCTP association successfully initialising.
 /// </summary>
 public void onAssociated(Association a)
 {
     IsAssociated = true;
     OnAssociated?.Invoke();
 }
Exemple #35
0
        internal static void CreateEntityTypeShapeAndConnectorsInDiagram(
            CommandProcessorContext cpc, Diagram diagram, ConceptualEntityType entity, Color entityTypeShapeFillColor,
            bool createRelatedEntityTypeShapes)
        {
            // if the entity type shape has been created, return immediately.
            if (entity == null ||
                entity.GetAntiDependenciesOfType <EntityTypeShape>().Count(ets => ets.Diagram.Id == diagram.Id.Value) > 0)
            {
                return;
            }

            var createEntityTypeShapecommand = new CreateEntityTypeShapeCommand(diagram, entity, entityTypeShapeFillColor);

            createEntityTypeShapecommand.PostInvokeEvent += (o, eventsArgs) =>
            {
                if (createEntityTypeShapecommand.EntityTypeShape != null)
                {
                    var relatedEntityTypesNotInDiagram = new List <EntityType>();

                    var entityTypesInDiagram = new HashSet <EntityType>(diagram.EntityTypeShapes.Select(ets => ets.EntityType.Target));

                    // add inheritance connector if the base type exists in the diagram.
                    if (entity.SafeBaseType != null)
                    {
                        if (entityTypesInDiagram.Contains(entity.SafeBaseType))
                        {
                            CommandProcessor.InvokeSingleCommand(cpc, new CreateInheritanceConnectorCommand(diagram, entity));
                        }
                        else
                        {
                            relatedEntityTypesNotInDiagram.Add(entity.SafeBaseType);
                        }
                    }

                    // add the inheritance connector if the derived type exist in the diagram.
                    foreach (var derivedEntityType in entity.ResolvableDirectDerivedTypes)
                    {
                        if (entityTypesInDiagram.Contains(derivedEntityType))
                        {
                            CommandProcessor.InvokeSingleCommand(cpc, new CreateInheritanceConnectorCommand(diagram, derivedEntityType));
                        }
                        else
                        {
                            relatedEntityTypesNotInDiagram.Add(derivedEntityType);
                        }
                    }

                    // Find all associations which the entity type participates.
                    var participatingAssociations = Association.GetAssociationsForEntityType(entity);

                    foreach (var association in participatingAssociations)
                    {
                        var entityTypesInAssociation = association.AssociationEnds().Select(ae => ae.Type.Target).ToList();
                        var entityTypesNotInDiagram  = entityTypesInAssociation.Except(entityTypesInDiagram).ToList();

                        if (entityTypesNotInDiagram.Count == 0)
                        {
                            CommandProcessor.InvokeSingleCommand(cpc, new CreateAssociationConnectorCommand(diagram, association));
                        }
                        relatedEntityTypesNotInDiagram.AddRange(entityTypesNotInDiagram);
                    }

                    if (createRelatedEntityTypeShapes)
                    {
                        foreach (var entityType in relatedEntityTypesNotInDiagram)
                        {
                            // we only want to bring entity-type directly related to the entity-type, so set createRelatedEntityTypeShapes flag to false.
                            CreateEntityTypeShapeAndConnectorsInDiagram(
                                cpc, diagram, entityType as ConceptualEntityType, entityTypeShapeFillColor, false);
                        }
                    }
                }
            };
            CommandProcessor.InvokeSingleCommand(cpc, createEntityTypeShapecommand);
        }
 internal AssociationDelete(Association association)
 {
     _association = association;
 }
        /// <summary>
        /// Loads the new entry.
        /// </summary>
        /// <returns></returns>
        protected override Entry LoadNewEntry()
        {
            // Load using base implementation
            Entry entry = base.LoadNewEntry();

            // Add additional association to accomodate service plan and demonstrate dynamic products
            List <Association> associationList = new List <Association>();

            Association optionsAssoc = null;

            if (entry.Associations != null)
            {
                foreach (Association assoc in entry.Associations)
                {
                    if (assoc.Name.Equals("AdditionalOptions", StringComparison.OrdinalIgnoreCase))
                    {
                        optionsAssoc = assoc;
                    }

                    associationList.Add(assoc);
                }
            }

            if (optionsAssoc == null)
            {
                optionsAssoc             = new Association();
                optionsAssoc.Name        = "AdditionalOptions";
                optionsAssoc.Description = "Additional Options";
                associationList.Add(optionsAssoc);
            }

            List <EntryAssociation> entryAssociationList = new List <EntryAssociation>();

            if (optionsAssoc.EntryAssociations == null)
            {
                optionsAssoc.EntryAssociations = new EntryAssociations();
            }

            if (optionsAssoc.EntryAssociations.Association != null)
            {
                foreach (EntryAssociation assoc in optionsAssoc.EntryAssociations.Association)
                {
                    entryAssociationList.Add(assoc);
                }
            }

            // Add new association and made up entry
            Entry newEntry = new Entry();

            newEntry.ID                         = "@2YEARSERVICEPLAN-" + entry.ID;
            newEntry.Name                       = "2 Years Service Plan";
            newEntry.ItemAttributes             = new ItemAttributes();
            newEntry.ItemAttributes.MinQuantity = 1;
            newEntry.ItemAttributes.MaxQuantity = 1;
            newEntry.ParentEntry                = entry;

            Price listPrice = StoreHelper.GetSalePrice(entry, 1);

            newEntry.ItemAttributes.ListPrice = ObjectHelper.CreatePrice(decimal.Multiply(listPrice.Amount, (decimal)0.10), listPrice.CurrencyCode);

            EntryAssociation newAssociation = new EntryAssociation();

            newAssociation.AssociationType = "OPTIONAL";
            newAssociation.SortOrder       = 0;
            newAssociation.AssociationDesc = "";
            newAssociation.Entry           = newEntry;
            entryAssociationList.Add(newAssociation);

            optionsAssoc.EntryAssociations.Association = entryAssociationList.ToArray();
            entry.Associations = associationList.ToArray();

            return(entry);
        }
Exemple #38
0
        void WriteDbContextEF6(ModelRoot modelRoot)
        {
            Output("using System;");
            Output("using System.Collections.Generic;");
            Output("using System.Linq;");
            Output("using System.ComponentModel.DataAnnotations.Schema;");
            Output("using System.Data.Entity;");
            Output("using System.Data.Entity.Infrastructure.Annotations;");
            NL();

            BeginNamespace(modelRoot.Namespace);

            if (!string.IsNullOrEmpty(modelRoot.Summary))
            {
                Output("/// <summary>");
                WriteCommentBody(modelRoot.Summary);
                Output("/// </summary>");

                if (!string.IsNullOrEmpty(modelRoot.Description))
                {
                    Output("/// <remarks>");
                    WriteCommentBody(modelRoot.Description);
                    Output("/// </remarks>");
                }
            }
            else
            {
                Output("/// <inheritdoc/>");
            }

            Output($"{modelRoot.EntityContainerAccess.ToString().ToLower()} partial class {modelRoot.EntityContainerName} : System.Data.Entity.DbContext");
            Output("{");

            PluralizationService pluralizationService = ModelRoot.PluralizationService;

            /***********************************************************************/
            // generate DBSets
            /***********************************************************************/

            ModelClass[] classesWithTables = null;

            switch (modelRoot.InheritanceStrategy)
            {
            case CodeStrategy.TablePerType:
                classesWithTables = modelRoot.Classes.Where(mc => !mc.IsDependentType).OrderBy(x => x.Name).ToArray();

                break;

            case CodeStrategy.TablePerConcreteType:
                classesWithTables = modelRoot.Classes.Where(mc => !mc.IsDependentType && !mc.IsAbstract).OrderBy(x => x.Name).ToArray();

                break;

            case CodeStrategy.TablePerHierarchy:
                classesWithTables = modelRoot.Classes.Where(mc => !mc.IsDependentType && mc.Superclass == null).OrderBy(x => x.Name).ToArray();

                break;
            }

            if (classesWithTables?.Any() == true)
            {
                Output("#region DbSets");

                foreach (ModelClass modelClass in modelRoot.Classes.Where(x => !x.IsDependentType).OrderBy(x => x.Name))
                {
                    string dbSetName;

                    if (!string.IsNullOrEmpty(modelClass.DbSetName))
                    {
                        dbSetName = modelClass.DbSetName;
                    }
                    else
                    {
                        dbSetName = pluralizationService?.IsSingular(modelClass.Name) == true
                                 ? pluralizationService.Pluralize(modelClass.Name)
                                 : modelClass.Name;
                    }

                    if (!string.IsNullOrEmpty(modelClass.Summary))
                    {
                        NL();
                        Output("/// <summary>");
                        WriteCommentBody($"Repository for {modelClass.FullName} - {modelClass.Summary}");
                        Output("/// </summary>");
                    }

                    Output($"{modelRoot.DbSetAccess.ToString().ToLower()} virtual System.Data.Entity.DbSet<{modelClass.FullName}> {dbSetName} {{ get; set; }}");
                }

                Output("#endregion DbSets");
                NL();
            }

            Output("#region Constructors");
            NL();
            Output("partial void CustomInit();");
            NL();

            /***********************************************************************/
            // constructors
            /***********************************************************************/

            if (!string.IsNullOrEmpty(modelRoot.ConnectionString) || !string.IsNullOrEmpty(modelRoot.ConnectionStringName))
            {
                string connectionString = string.IsNullOrEmpty(modelRoot.ConnectionString)
                                         ? $"Name={modelRoot.ConnectionStringName}"
                                         : modelRoot.ConnectionString;

                Output("/// <summary>");
                Output("/// Default connection string");
                Output("/// </summary>");
                Output($"public static string ConnectionString {{ get; set; }} = @\"{connectionString}\";");

                Output("/// <inheritdoc />");
                Output($"public {modelRoot.EntityContainerName}() : base(ConnectionString)");
                Output("{");
                Output($"Configuration.LazyLoadingEnabled = {modelRoot.LazyLoadingEnabled.ToString().ToLower()};");
                Output($"Configuration.ProxyCreationEnabled = {modelRoot.ProxyGenerationEnabled.ToString().ToLower()};");

                Output(modelRoot.DatabaseInitializerType == DatabaseInitializerKind.None
                      ? $"System.Data.Entity.Database.SetInitializer<{modelRoot.EntityContainerName}>(null);"
                      : $"System.Data.Entity.Database.SetInitializer<{modelRoot.EntityContainerName}>(new {modelRoot.EntityContainerName}DatabaseInitializer());");

                Output("CustomInit();");
                Output("}");
                NL();
            }
            else
            {
                Output($"#warning Default constructor not generated for {modelRoot.EntityContainerName} since no default connection string was specified in the model");
                NL();
            }

            Output("/// <inheritdoc />");
            Output($"public {modelRoot.EntityContainerName}(string connectionString) : base(connectionString)");
            Output("{");
            Output($"Configuration.LazyLoadingEnabled = {modelRoot.LazyLoadingEnabled.ToString().ToLower()};");
            Output($"Configuration.ProxyCreationEnabled = {modelRoot.ProxyGenerationEnabled.ToString().ToLower()};");

            Output(modelRoot.DatabaseInitializerType == DatabaseInitializerKind.None
                   ? $"System.Data.Entity.Database.SetInitializer<{modelRoot.EntityContainerName}>(null);"
                   : $"System.Data.Entity.Database.SetInitializer<{modelRoot.EntityContainerName}>(new {modelRoot.EntityContainerName}DatabaseInitializer());");

            Output("CustomInit();");
            Output("}");
            NL();

            Output("/// <inheritdoc />");
            Output($"public {modelRoot.EntityContainerName}(string connectionString, System.Data.Entity.Infrastructure.DbCompiledModel model) : base(connectionString, model)");
            Output("{");
            Output($"Configuration.LazyLoadingEnabled = {modelRoot.LazyLoadingEnabled.ToString().ToLower()};");
            Output($"Configuration.ProxyCreationEnabled = {modelRoot.ProxyGenerationEnabled.ToString().ToLower()};");

            Output(modelRoot.DatabaseInitializerType == DatabaseInitializerKind.None
                   ? $"System.Data.Entity.Database.SetInitializer<{modelRoot.EntityContainerName}>(null);"
                   : $"System.Data.Entity.Database.SetInitializer<{modelRoot.EntityContainerName}>(new {modelRoot.EntityContainerName}DatabaseInitializer());");

            Output("CustomInit();");
            Output("}");
            NL();

            Output("/// <inheritdoc />");
            Output($"public {modelRoot.EntityContainerName}(System.Data.Common.DbConnection existingConnection, bool contextOwnsConnection) : base(existingConnection, contextOwnsConnection)");
            Output("{");
            Output($"Configuration.LazyLoadingEnabled = {modelRoot.LazyLoadingEnabled.ToString().ToLower()};");
            Output($"Configuration.ProxyCreationEnabled = {modelRoot.ProxyGenerationEnabled.ToString().ToLower()};");

            Output(modelRoot.DatabaseInitializerType == DatabaseInitializerKind.None
                   ? $"System.Data.Entity.Database.SetInitializer<{modelRoot.EntityContainerName}>(null);"
                   : $"System.Data.Entity.Database.SetInitializer<{modelRoot.EntityContainerName}>(new {modelRoot.EntityContainerName}DatabaseInitializer());");

            Output("CustomInit();");
            Output("}");
            NL();

            Output("/// <inheritdoc />");
            Output($"public {modelRoot.EntityContainerName}(System.Data.Common.DbConnection existingConnection, System.Data.Entity.Infrastructure.DbCompiledModel model, bool contextOwnsConnection) : base(existingConnection, model, contextOwnsConnection)");
            Output("{");
            Output($"Configuration.LazyLoadingEnabled = {modelRoot.LazyLoadingEnabled.ToString().ToLower()};");
            Output($"Configuration.ProxyCreationEnabled = {modelRoot.ProxyGenerationEnabled.ToString().ToLower()};");

            Output(modelRoot.DatabaseInitializerType == DatabaseInitializerKind.None
                   ? $"System.Data.Entity.Database.SetInitializer<{modelRoot.EntityContainerName}>(null);"
                   : $"System.Data.Entity.Database.SetInitializer<{modelRoot.EntityContainerName}>(new {modelRoot.EntityContainerName}DatabaseInitializer());");

            Output("CustomInit();");
            Output("}");
            NL();

            Output("/// <inheritdoc />");
            Output($"public {modelRoot.EntityContainerName}(System.Data.Entity.Infrastructure.DbCompiledModel model) : base(model)");
            Output("{");
            Output($"Configuration.LazyLoadingEnabled = {modelRoot.LazyLoadingEnabled.ToString().ToLower()};");
            Output($"Configuration.ProxyCreationEnabled = {modelRoot.ProxyGenerationEnabled.ToString().ToLower()};");

            Output(modelRoot.DatabaseInitializerType == DatabaseInitializerKind.None
                   ? $"System.Data.Entity.Database.SetInitializer<{modelRoot.EntityContainerName}>(null);"
                   : $"System.Data.Entity.Database.SetInitializer<{modelRoot.EntityContainerName}>(new {modelRoot.EntityContainerName}DatabaseInitializer());");

            Output("CustomInit();");
            Output("}");
            NL();

            Output("/// <inheritdoc />");
            Output($"public {modelRoot.EntityContainerName}(System.Data.Entity.Core.Objects.ObjectContext objectContext, bool dbContextOwnsObjectContext) : base(objectContext, dbContextOwnsObjectContext)");
            Output("{");
            Output($"Configuration.LazyLoadingEnabled = {modelRoot.LazyLoadingEnabled.ToString().ToLower()};");
            Output($"Configuration.ProxyCreationEnabled = {modelRoot.ProxyGenerationEnabled.ToString().ToLower()};");

            Output(modelRoot.DatabaseInitializerType == DatabaseInitializerKind.None
                   ? $"System.Data.Entity.Database.SetInitializer<{modelRoot.EntityContainerName}>(null);"
                   : $"System.Data.Entity.Database.SetInitializer<{modelRoot.EntityContainerName}>(new {modelRoot.EntityContainerName}DatabaseInitializer());");

            Output("CustomInit();");
            Output("}");
            NL();
            Output("#endregion Constructors");
            NL();

            /***********************************************************************/
            // OnModelCreating
            /***********************************************************************/
            Output("partial void OnModelCreatingImpl(System.Data.Entity.DbModelBuilder modelBuilder);");
            Output("partial void OnModelCreatedImpl(System.Data.Entity.DbModelBuilder modelBuilder);");
            NL();

            Output("/// <inheritdoc />");
            Output("protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)");
            Output("{");
            Output("base.OnModelCreating(modelBuilder);");
            Output("OnModelCreatingImpl(modelBuilder);");
            NL();

            Output($"modelBuilder.HasDefaultSchema(\"{modelRoot.DatabaseSchema}\");");

            List <string> segments = new List <string>();

            List <Association> visited           = new List <Association>();
            List <string>      foreignKeyColumns = new List <string>();

            foreach (ModelClass modelClass in modelRoot.Classes.OrderBy(x => x.Name))
            {
                segments.Clear();
                foreignKeyColumns.Clear();
                NL();

                // class level
                bool isDependent = modelClass.IsDependentType;
                segments.Add($"modelBuilder.{(isDependent ? "ComplexType" : "Entity")}<{modelClass.FullName}>()");

                foreach (ModelAttribute transient in modelClass.Attributes.Where(x => !x.Persistent))
                {
                    segments.Add($"Ignore(t => t.{transient.Name})");
                }

                // note: this must come before the 'ToTable' call or there's a runtime error
                if (modelRoot.InheritanceStrategy == CodeStrategy.TablePerConcreteType && modelClass.Superclass != null)
                {
                    segments.Add("Map(x => x.MapInheritedProperties())");
                }

                if (classesWithTables.Contains(modelClass))
                {
                    segments.Add(modelClass.DatabaseSchema == modelClass.ModelRoot.DatabaseSchema
                               ? $"ToTable(\"{modelClass.TableName}\")"
                               : $"ToTable(\"{modelClass.TableName}\", \"{modelClass.DatabaseSchema}\")");

                    // primary key code segments must be output last, since HasKey returns a different type
                    List <ModelAttribute> identityAttributes = modelClass.IdentityAttributes.ToList();

                    if (identityAttributes.Count == 1)
                    {
                        segments.Add($"HasKey(t => t.{identityAttributes[0].Name})");
                    }
                    else if (identityAttributes.Count > 1)
                    {
                        segments.Add($"HasKey(t => new {{ t.{string.Join(", t.", identityAttributes.Select(ia => ia.Name))} }})");
                    }
                }

                if (segments.Count > 1)
                {
                    if (modelRoot.ChopMethodChains)
                    {
                        OutputChopped(segments);
                    }
                    else
                    {
                        Output(string.Join(".", segments) + ";");
                    }
                }

                if (modelClass.IsDependentType)
                {
                    continue;
                }

                // indexed properties
                foreach (ModelAttribute indexed in modelClass.Attributes.Where(x => x.Indexed && !x.IsIdentity))
                {
                    segments.Clear();

                    segments.Add(indexed.AutoProperty
                               ? $"modelBuilder.Entity<{modelClass.FullName}>().HasIndex(t => t.{indexed.Name})"
                               : $"modelBuilder.Entity<{modelClass.FullName}>().HasIndex(\"_{indexed.Name}\")");

                    if (indexed.IndexedUnique)
                    {
                        segments.Add("IsUnique()");
                    }

                    if (segments.Count > 1)
                    {
                        if (modelRoot.ChopMethodChains)
                        {
                            OutputChopped(segments);
                        }
                        else
                        {
                            Output(string.Join(".", segments) + ";");
                        }
                    }
                }

                // attribute level
                foreach (ModelAttribute modelAttribute in modelClass.Attributes.Where(x => x.Persistent && !SpatialTypes.Contains(x.Type)))
                {
                    segments.Clear();

                    if (modelAttribute.MaxLength > 0)
                    {
                        segments.Add($"HasMaxLength({modelAttribute.MaxLength})");
                    }

                    if (modelAttribute.Required)
                    {
                        segments.Add("IsRequired()");
                    }

                    if (modelAttribute.ColumnName != modelAttribute.Name && !string.IsNullOrEmpty(modelAttribute.ColumnName))
                    {
                        segments.Add($"HasColumnName(\"{modelAttribute.ColumnName}\")");
                    }

                    if (!string.IsNullOrEmpty(modelAttribute.ColumnType) && modelAttribute.ColumnType.ToLowerInvariant() != "default")
                    {
                        segments.Add($"HasColumnType(\"{modelAttribute.ColumnType}\")");
                    }

                    if (modelAttribute.Indexed && !modelAttribute.IsIdentity)
                    {
                        segments.Add("HasColumnAnnotation(\"Index\", new IndexAnnotation(new IndexAttribute()))");
                    }

                    if (modelAttribute.IsConcurrencyToken)
                    {
                        segments.Add("IsRowVersion()");
                    }

                    if (modelAttribute.IsIdentity)
                    {
                        segments.Add(modelAttribute.IdentityType == IdentityType.AutoGenerated
                                  ? "HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)"
                                  : "HasDatabaseGeneratedOption(DatabaseGeneratedOption.None)");
                    }

                    if (segments.Any())
                    {
                        segments.Insert(0, $"modelBuilder.{(isDependent ? "ComplexType" : "Entity")}<{modelClass.FullName}>()");
                        segments.Insert(1, $"Property(t => t.{modelAttribute.Name})");

                        if (modelRoot.ChopMethodChains)
                        {
                            OutputChopped(segments);
                        }
                        else
                        {
                            Output(string.Join(".", segments) + ";");
                        }
                    }
                }

                if (!isDependent)
                {
                    // Navigation endpoints are distingished as Source and Target. They are also distinguished as Principal
                    // and Dependent. How do these map?
                    // In the case of one-to-one or zero-to-one-to-zero-to-one, it's model dependent and the user has to tell us
                    // In all other cases, we can tell by the cardinalities of the associations
                    // What matters is the Principal and Dependent classifications, so we look at those.
                    // Source and Target are accidents of where the user started drawing the association.

                    // navigation properties
                    // ReSharper disable once LoopCanBePartlyConvertedToQuery
                    foreach (UnidirectionalAssociation association in Association.GetLinksToTargets(modelClass)
                             .OfType <UnidirectionalAssociation>()
                             .Where(x => x.Persistent && !x.Target.IsDependentType))
                    {
                        if (visited.Contains(association))
                        {
                            continue;
                        }

                        visited.Add(association);

                        segments.Clear();
                        segments.Add($"modelBuilder.Entity<{modelClass.FullName}>()");

                        switch (association.TargetMultiplicity) // realized by property on source
                        {
                        case Sawczyn.EFDesigner.EFModel.Multiplicity.ZeroMany:
                            segments.Add($"HasMany(x => x.{association.TargetPropertyName})");

                            break;

                        case Sawczyn.EFDesigner.EFModel.Multiplicity.One:
                            segments.Add($"HasRequired(x => x.{association.TargetPropertyName})");

                            break;

                        case Sawczyn.EFDesigner.EFModel.Multiplicity.ZeroOne:
                            segments.Add($"HasOptional(x => x.{association.TargetPropertyName})");

                            break;

                            //case Sawczyn.EFDesigner.EFModel.Multiplicity.OneMany:
                            //   segments.Add($"HasMany(x => x.{association.TargetPropertyName})");
                            //   break;
                        }

                        switch (association.SourceMultiplicity) // realized by property on target, but no property on target
                        {
                        case Sawczyn.EFDesigner.EFModel.Multiplicity.ZeroMany:
                            segments.Add("WithMany()");

                            if (association.TargetMultiplicity == Sawczyn.EFDesigner.EFModel.Multiplicity.ZeroMany)
                            {
                                if (modelClass == association.Source)
                                {
                                    segments.Add("Map(x => { "
                                                 + $@"x.ToTable(""{association.Source.Name}_x_{association.TargetPropertyName}""); "
                                                 + $@"x.MapLeftKey(""{association.Source.Name}_{association.Source.AllAttributes.FirstOrDefault(a => a.IsIdentity)?.Name}""); "
                                                 + $@"x.MapRightKey(""{association.Target.Name}_{association.Target.AllAttributes.FirstOrDefault(a => a.IsIdentity)?.Name}""); "
                                                 + "})");
                                }
                                else
                                {
                                    segments.Add("Map(x => { "
                                                 + $@"x.ToTable(""{association.Source.Name}_x_{association.TargetPropertyName}""); "
                                                 + $@"x.MapRightKey(""{association.Source.Name}_{association.Source.AllAttributes.FirstOrDefault(a => a.IsIdentity)?.Name}""); "
                                                 + $@"x.MapLeftKey(""{association.Target.Name}_{association.Target.AllAttributes.FirstOrDefault(a => a.IsIdentity)?.Name}""); "
                                                 + "})");
                                }
                            }

                            break;

                        case Sawczyn.EFDesigner.EFModel.Multiplicity.One:
                            if (association.TargetMultiplicity == Sawczyn.EFDesigner.EFModel.Multiplicity.One)
                            {
                                segments.Add(association.TargetRole == EndpointRole.Dependent
                                           ? "WithRequiredDependent()"
                                           : "WithRequiredPrincipal()");
                            }
                            else
                            {
                                segments.Add("WithRequired()");
                            }

                            break;

                        case Sawczyn.EFDesigner.EFModel.Multiplicity.ZeroOne:
                            if (association.TargetMultiplicity == Sawczyn.EFDesigner.EFModel.Multiplicity.ZeroOne)
                            {
                                segments.Add(association.TargetRole == EndpointRole.Dependent
                                           ? "WithOptionalDependent()"
                                           : "WithOptionalPrincipal()");
                            }
                            else
                            {
                                segments.Add("WithOptional()");
                            }

                            break;

                            //case Sawczyn.EFDesigner.EFModel.Multiplicity.OneMany:
                            //   segments.Add("HasMany()");
                            //   break;
                        }

                        string foreignKeySegment = CreateForeignKeyColumnSegmentEF6(association, foreignKeyColumns);

                        if (foreignKeySegment != null)
                        {
                            segments.Add(foreignKeySegment);
                        }

                        // Certain associations cascade delete automatically. Also, the user may ask for it.
                        // We only generate a cascade delete call if the user asks for it.
                        if ((association.TargetDeleteAction != DeleteAction.Default && association.TargetRole == EndpointRole.Principal) ||
                            (association.SourceDeleteAction != DeleteAction.Default && association.SourceRole == EndpointRole.Principal))
                        {
                            string willCascadeOnDelete = association.TargetDeleteAction != DeleteAction.Default && association.TargetRole == EndpointRole.Principal
                                                     ? (association.TargetDeleteAction == DeleteAction.Cascade).ToString().ToLowerInvariant()
                                                     : (association.SourceDeleteAction == DeleteAction.Cascade).ToString().ToLowerInvariant();

                            segments.Add($"WillCascadeOnDelete({willCascadeOnDelete})");
                        }

                        if (modelRoot.ChopMethodChains)
                        {
                            OutputChopped(segments);
                        }
                        else
                        {
                            Output(string.Join(".", segments) + ";");
                        }
                    }

                    // ReSharper disable once LoopCanBePartlyConvertedToQuery
                    foreach (BidirectionalAssociation association in Association.GetLinksToSources(modelClass)
                             .OfType <BidirectionalAssociation>()
                             .Where(x => x.Persistent))
                    {
                        if (visited.Contains(association))
                        {
                            continue;
                        }

                        visited.Add(association);

                        segments.Clear();
                        segments.Add($"modelBuilder.Entity<{modelClass.FullName}>()");

                        switch (association.SourceMultiplicity) // realized by property on target
                        {
                        case Sawczyn.EFDesigner.EFModel.Multiplicity.ZeroMany:
                            segments.Add($"HasMany(x => x.{association.SourcePropertyName})");

                            break;

                        case Sawczyn.EFDesigner.EFModel.Multiplicity.One:
                            segments.Add($"HasRequired(x => x.{association.SourcePropertyName})");

                            break;

                        case Sawczyn.EFDesigner.EFModel.Multiplicity.ZeroOne:
                            segments.Add($"HasOptional(x => x.{association.SourcePropertyName})");

                            break;

                            //one or more constraint not supported in EF. TODO: make this possible ... later
                            //case Sawczyn.EFDesigner.EFModel.Multiplicity.OneMany:
                            //   segments.Add($"HasMany(x => x.{association.SourcePropertyName})");
                            //   break;
                        }

                        switch (association.TargetMultiplicity) // realized by property on source
                        {
                        case Sawczyn.EFDesigner.EFModel.Multiplicity.ZeroMany:
                            segments.Add($"WithMany(x => x.{association.TargetPropertyName})");

                            if (association.SourceMultiplicity == Sawczyn.EFDesigner.EFModel.Multiplicity.ZeroMany)
                            {
                                if (modelClass == association.Source)
                                {
                                    segments.Add("Map(x => { "
                                                 + $@"x.ToTable(""{association.SourcePropertyName}_x_{association.TargetPropertyName}""); "
                                                 + $@"x.MapLeftKey(""{association.Source.Name}_{association.Source.AllAttributes.FirstOrDefault(a => a.IsIdentity)?.Name}""); "
                                                 + $@"x.MapRightKey(""{association.Target.Name}_{association.Target.AllAttributes.FirstOrDefault(a => a.IsIdentity)?.Name}""); "
                                                 + "})");
                                }
                                else
                                {
                                    segments.Add("Map(x => { "
                                                 + $@"x.ToTable(""{association.SourcePropertyName}_x_{association.TargetPropertyName}""); "
                                                 + $@"x.MapRightKey(""{association.Source.Name}_{association.Source.AllAttributes.FirstOrDefault(a => a.IsIdentity)?.Name}""); "
                                                 + $@"x.MapLeftKey(""{association.Target.Name}_{association.Target.AllAttributes.FirstOrDefault(a => a.IsIdentity)?.Name}""); "
                                                 + "})");
                                }
                            }

                            break;

                        case Sawczyn.EFDesigner.EFModel.Multiplicity.One:
                            if (association.SourceMultiplicity == Sawczyn.EFDesigner.EFModel.Multiplicity.One)
                            {
                                segments.Add(association.SourceRole == EndpointRole.Dependent
                                           ? $"WithRequiredDependent(x => x.{association.TargetPropertyName})"
                                           : $"WithRequiredPrincipal(x => x.{association.TargetPropertyName})");
                            }
                            else
                            {
                                segments.Add($"WithRequired(x => x.{association.TargetPropertyName})");
                            }

                            break;

                        case Sawczyn.EFDesigner.EFModel.Multiplicity.ZeroOne:
                            if (association.SourceMultiplicity == Sawczyn.EFDesigner.EFModel.Multiplicity.ZeroOne)
                            {
                                segments.Add(association.SourceRole == EndpointRole.Dependent
                                           ? $"WithOptionalDependent(x => x.{association.TargetPropertyName})"
                                           : $"WithOptionalPrincipal(x => x.{association.TargetPropertyName})");
                            }
                            else
                            {
                                segments.Add($"WithOptional(x => x.{association.TargetPropertyName})");
                            }

                            break;

                            //one or more constraint not supported in EF. TODO: make this possible ... later
                            //case Sawczyn.EFDesigner.EFModel.Multiplicity.OneMany:
                            //   segments.Add($"HasMany(x => x.{association.TargetPropertyName})");
                            //   break;
                        }

                        string foreignKeySegment = CreateForeignKeyColumnSegmentEF6(association, foreignKeyColumns);

                        if (foreignKeySegment != null)
                        {
                            segments.Add(foreignKeySegment);
                        }

                        if ((association.TargetDeleteAction != DeleteAction.Default && association.TargetRole == EndpointRole.Principal) ||
                            (association.SourceDeleteAction != DeleteAction.Default && association.SourceRole == EndpointRole.Principal))
                        {
                            string willCascadeOnDelete = association.TargetDeleteAction != DeleteAction.Default && association.TargetRole == EndpointRole.Principal
                                                     ? (association.TargetDeleteAction == DeleteAction.Cascade).ToString().ToLowerInvariant()
                                                     : (association.SourceDeleteAction == DeleteAction.Cascade).ToString().ToLowerInvariant();

                            segments.Add($"WillCascadeOnDelete({willCascadeOnDelete})");
                        }

                        if (modelRoot.ChopMethodChains)
                        {
                            OutputChopped(segments);
                        }
                        else
                        {
                            Output(string.Join(".", segments) + ";");
                        }
                    }
                }
            }

            NL();

            Output("OnModelCreatedImpl(modelBuilder);");
            Output("}");

            Output("}");

            EndNamespace(modelRoot.Namespace);
        }
 internal AssociationAdd(Association association)
 {
     _association = association;
 }
        private void ButtonGetRelatedValues_Click(object sender, RoutedEventArgs e)
        {
            if (SelectedProperty == null)
            {
                return;
            }

            List <ModelCode> selectedProperties = new List <ModelCode>();

            foreach (var child in PropertiesInRelated.Children)
            {
                if (child is CheckBox checkBox && checkBox.IsChecked.Value)
                {
                    foreach (KeyValuePair <ModelCode, string> keyValuePair in propertiesDesc)
                    {
                        if (keyValuePair.Value.Equals(checkBox.Content))
                        {
                            selectedProperties.Add(keyValuePair.Key);
                        }
                    }
                }
            }

            StringBuilder sb = new StringBuilder();

            sb.Append("Returned entities" + Environment.NewLine + Environment.NewLine);

            ////////////////////////////////////////////
            List <long>         gidReferences = new List <long>();
            ResourceDescription rd            = tgda.GetValues(SelectedGID.GID, new List <ModelCode>()
            {
                SelectedProperty.Property
            });

            if (rd != null)
            {
                Property prop = rd.GetProperty(SelectedProperty.Property);

                if ((short)(unchecked ((long)SelectedProperty.Property & (long)ModelCodeMask.MASK_ATTRIBUTE_TYPE)) == (short)PropertyType.Reference)
                {
                    gidReferences.Add(prop.AsReference());
                }
                else if ((short)(unchecked ((long)SelectedProperty.Property & (long)ModelCodeMask.MASK_ATTRIBUTE_TYPE)) == (short)PropertyType.ReferenceVector)
                {
                    gidReferences.AddRange(prop.AsReferences());
                }
            }

            HashSet <DMSType> referencedDmsTypes = new HashSet <DMSType>();

            if (gidReferences.Count > 0)
            {
                foreach (long gidReference in gidReferences)
                {
                    DMSType dmsType = (DMSType)ModelCodeHelper.ExtractTypeFromGlobalId(gidReference);
                    if (!referencedDmsTypes.Contains(dmsType))
                    {
                        referencedDmsTypes.Add(dmsType);
                    }
                }
            }
            ////////////////////////////////////////////////////////

            try
            {
                if (SelectedDmsType != null)
                {
                    Association association = new Association(SelectedProperty.Property, modelResourcesDesc.GetModelCodeFromType(SelectedDmsType.DmsType));
                    List <long> gids        = tgda.GetRelatedValues(SelectedGID.GID, selectedProperties, association, sb);
                }
                else
                {
                    /////////////////////////////////////////////////////////////
                    HashSet <ModelCode> referencedDmsTypesProperties      = new HashSet <ModelCode>(modelResourcesDesc.GetAllPropertyIds(referencedDmsTypes.First()));
                    List <ModelCode>    toBeRemovedFormSelectedProperties = new List <ModelCode>();
                    foreach (ModelCode property in selectedProperties)
                    {
                        if (!referencedDmsTypesProperties.Contains(property))
                        {
                            toBeRemovedFormSelectedProperties.Add(property);
                        }
                    }

                    foreach (ModelCode property in toBeRemovedFormSelectedProperties)
                    {
                        selectedProperties.Remove(property);
                    }

                    foreach (var child in PropertiesInRelated.Children)
                    {
                        if (child is CheckBox checkBox && checkBox.IsChecked.Value)
                        {
                            foreach (KeyValuePair <ModelCode, string> keyValuePair in propertiesDesc)
                            {
                                if (keyValuePair.Value.Equals(checkBox.Content) && toBeRemovedFormSelectedProperties.Contains(keyValuePair.Key))
                                {
                                    checkBox.IsChecked = false;
                                }
                            }
                        }
                    }

                    CheckAllBtn.IsEnabled = true;
                    /////////////////////////////////////////////////////////////

                    Association association = new Association(SelectedProperty.Property, 0x0000000000000000);
                    List <long> gids        = tgda.GetRelatedValues(SelectedGID.GID, selectedProperties, association, sb);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "GetRelatedValues", MessageBoxButton.OK, MessageBoxImage.Error);
            }

            RelatedValues.Document.Blocks.Clear();
            RelatedValues.AppendText(sb.ToString());
        }
Exemple #41
0
 public static string ToSerialString(this Association value) => value switch
 {
        private void Test_WithOneAssAndOneTemplateTypeAss(int TemplateEvents, TemplateStateEnum templateState, Association ass, string ItemCTId, SPEventType eventType, bool shouldFound)
        {
            var moleSourceList = CreateSourceListAllOnTheRootSite(ItemCTId, 1);
            var expected       = CreateTemplate(TemplateEvents, templateState,
                                                new AssociationCollection
            {
                ass
            });

            TemplateList.Add(expected);
            DefaultTemplatesManager target  = new DefaultTemplatesManager(logger.Object, configManager.Object);
            ISearchContext          context = SearchContext.Create(moleSourceList, 1, Properties.Resources.EventDataTskAdded, eventType, "*****@*****.**");

            if (shouldFound)
            {
                var actual = target.GetTemplate(context);
                Assert.AreSame(expected, actual);
            }
            else
            {
                try
                {
                    var actual = target.GetTemplate(context);
                    Assert.Fail("shouldn't found any templates");
                }
                catch (SeTemplateNotFound)
                {
                }
            }
        }
 internal CreateForeignKeyProperties(CommandProcessorContext context, Association association)
 {
     _context     = context;
     _association = association;
 }
Exemple #44
0
 public override bool Contains(Association association)
 {
     return(_model.Contains(association));
 }
Exemple #45
0
        private CQLQueryResults getImageAnnotationCQLInfo()
        {
            object[]    obj      = null;
            Attribute   attrTemp = null;
            Association assoTemp = null;
            var         proxy    = new AIM3DataServicePortTypeClient();

            proxy.Endpoint.Address = new System.ServiceModel.EndpointAddress(AIMDataServiceSettings.Default.AIMDataServiceUrl);
            var         associationList = new ArrayList();
            Association aecAssociation  = null;

            foreach (var queryData in _queryParameters.AecQueryParameters)
            {
                var results = new ArrayList();
                if (!queryData.CodeValue.IsEmpty)
                {
                    results.Add(CreateAttribute("codeValue", queryData.CodeValue));
                }
                //if (!queryData.CodeMeaning.IsEmpty)
                results.Add(CreateAttribute("codeMeaning", queryData.CodeMeaning));
                if (!queryData.CodingSchemeDesignator.IsEmpty)
                {
                    results.Add(CreateAttribute("codingSchemeDesignator", queryData.CodingSchemeDesignator));
                }
                if (!queryData.CodingSchemeVersion.IsEmpty)
                {
                    results.Add(CreateAttribute("codingSchemeVersion", queryData.CodingSchemeVersion));
                }
                if (!queryData.Confidence.IsEmpty)
                {
                    results.Add(CreateAttribute("annotatorConfidence", queryData.Confidence));
                }
                if (results.Count > 0)
                {
                    obj = (object[])results.ToArray(typeof(object));
                }
                if (obj != null && obj.Length > 0)
                {
                    Group grpAnnatomicEntityCharacteristic = null;
                    if (obj.Length > 1)
                    {
                        grpAnnatomicEntityCharacteristic = CreateQRAttrAssoGroup.createGroup(obj, LogicalOperator.AND);
                        obj = null;
                    }
                    else
                    {
                        attrTemp = obj[0] as Attribute;
                    }

                    aecAssociation = CreateQRAttrAssoGroup.createAssociation("edu.northwestern.radiology.aim.AnatomicEntityCharacteristic", "anatomicEntityCharacteristicCollection", grpAnnatomicEntityCharacteristic, attrTemp, null);
                }
            }

            obj = null;
            if (aecAssociation != null && _queryParameters.AeQueryParameters.Count == 0)
            {
                var queryData = new AimAnatomicEntityQueryData();
                queryData.CodeMeaning = new QueryData(String.Empty, QueryPredicate.LIKE);
                _queryParameters.AeQueryParameters.Add(queryData);
            }
            foreach (var queryData in _queryParameters.AeQueryParameters)
            {
                var results = new ArrayList();
                if (!queryData.CodeValue.IsEmpty)
                {
                    results.Add(CreateAttribute("codeValue", queryData.CodeValue));
                }
                //if (!queryData.CodeMeaning.IsEmpty)
                results.Add(CreateAttribute("codeMeaning", queryData.CodeMeaning));
                if (!queryData.CodingSchemeDesignator.IsEmpty)
                {
                    results.Add(CreateAttribute("codingSchemeDesignator", queryData.CodingSchemeDesignator));
                }
                if (!queryData.CodingSchemeVersion.IsEmpty)
                {
                    results.Add(CreateAttribute("codingSchemeVersion", queryData.CodingSchemeVersion));
                }
                if (!queryData.Confidence.IsEmpty)
                {
                    results.Add(CreateAttribute("annotatorConfidence", queryData.Confidence));
                }
                if (aecAssociation != null)
                {
                    results.Add(aecAssociation);
                }
                if (results.Count > 0)
                {
                    obj = (object[])results.ToArray(typeof(object));
                }
                if (obj != null && obj.Length > 0)
                {
                    Group grpAnnatomicEntity = null;
                    if (obj.Length > 1)
                    {
                        grpAnnatomicEntity = CreateQRAttrAssoGroup.createGroup(obj, LogicalOperator.AND);
                        obj = null;
                    }
                    else
                    {
                        attrTemp = obj[0] as Attribute;
                    }
                    associationList.Add(CreateQRAttrAssoGroup.createAssociation("edu.northwestern.radiology.aim.AnatomicEntity", "anatomicEntityCollection", grpAnnatomicEntity, attrTemp, null));
                }
            }

            obj = null;
            Association iocAssociation = null;

            foreach (var queryData in _queryParameters.ImcQueryParameters)
            {
                var results = new ArrayList();
                if (!queryData.CodeValue.IsEmpty)
                {
                    results.Add(CreateAttribute("codeValue", queryData.CodeValue));
                }
                if (!queryData.CodeMeaning.IsEmpty)
                {
                    results.Add(CreateAttribute("codeMeaning", queryData.CodeMeaning));
                }
                if (!queryData.CodingSchemeDesignator.IsEmpty)
                {
                    results.Add(CreateAttribute("codingSchemeDesignator", queryData.CodingSchemeDesignator));
                }
                if (!queryData.CodingSchemeVersion.IsEmpty)
                {
                    results.Add(CreateAttribute("codingSchemeVersion", queryData.CodingSchemeVersion));
                }
                if (!queryData.Confidence.IsEmpty)
                {
                    results.Add(CreateAttribute("annotatorConfidence", queryData.Confidence));
                }
                if (!queryData.Comment.IsEmpty)
                {
                    results.Add(CreateAttribute("comment", queryData.Comment));
                }
                if (results.Count > 0)
                {
                    obj = (object[])results.ToArray(typeof(object));
                }
                if (obj != null && obj.Length > 0)
                {
                    Group grpImagingObservationCharacteristic = null;
                    if (obj.Length > 1)
                    {
                        grpImagingObservationCharacteristic = CreateQRAttrAssoGroup.createGroup(obj, LogicalOperator.AND);
                        obj = null;
                    }
                    else
                    {
                        attrTemp = obj[0] as Attribute;
                    }

                    iocAssociation = CreateQRAttrAssoGroup.createAssociation("edu.northwestern.radiology.aim.ImagingObservationCharacteristic", "imagingObservationCharacteristicCollection", grpImagingObservationCharacteristic, attrTemp, null);
                }
            }

            obj = null;
            if (iocAssociation != null && _queryParameters.ImQueryParameters.Count == 0)
            {
                var queryData = new AimImagingObservationQueryData();
                queryData.CodeMeaning = new QueryData(String.Empty, QueryPredicate.LIKE);
                _queryParameters.ImQueryParameters.Add(queryData);
            }
            foreach (var queryData in _queryParameters.ImQueryParameters)
            {
                var results = new ArrayList();
                if (!queryData.CodeValue.IsEmpty)
                {
                    results.Add(CreateAttribute("codeValue", queryData.CodeValue));
                }
                //if (!queryData.CodeMeaning.IsEmpty)
                results.Add(CreateAttribute("codeMeaning", queryData.CodeMeaning));
                if (!queryData.CodingSchemeDesignator.IsEmpty)
                {
                    results.Add(CreateAttribute("codingSchemeDesignator", queryData.CodingSchemeDesignator));
                }
                if (!queryData.CodingSchemeVersion.IsEmpty)
                {
                    results.Add(CreateAttribute("codingSchemeVersion", queryData.CodingSchemeVersion));
                }
                if (!queryData.Comment.IsEmpty)
                {
                    results.Add(CreateAttribute("comment", queryData.Comment));
                }
                if (!queryData.Confidence.IsEmpty)
                {
                    results.Add(CreateAttribute("annotatorConfidence", queryData.Confidence));
                }
                if (iocAssociation != null)
                {
                    results.Add(iocAssociation);
                }
                if (results.Count > 0)
                {
                    obj = (object[])results.ToArray(typeof(object));
                }
                if (obj != null && obj.Length > 0)
                {
                    attrTemp = null;
                    Group grpImagingObservation = null;
                    if (obj.Length > 1)
                    {
                        grpImagingObservation = CreateQRAttrAssoGroup.createGroup(obj, LogicalOperator.AND);
                        obj = null;
                    }
                    else
                    {
                        attrTemp = obj[0] as Attribute;
                    }
                    associationList.Add(CreateQRAttrAssoGroup.createAssociation("edu.northwestern.radiology.aim.ImagingObservation", "imagingObservationCollection", grpImagingObservation, attrTemp, null));
                }
            }

            obj = null;
            foreach (QueryData queryData in _queryParameters.UserParameters)
            {
                var results = new ArrayList();
                if (!queryData.IsEmpty)
                {
                    results.Add(CreateAttribute("loginName", queryData));
                    results.Add(CreateAttribute("name", queryData));
                }
                if (results.Count > 0)
                {
                    obj = (object[])results.ToArray(typeof(Attribute));
                }
                if (obj != null && obj.Length > 0)
                {
                    Group grpAnnatomicEntityCharacteristic = null;
                    if (obj.Length > 1)
                    {
                        grpAnnatomicEntityCharacteristic = CreateQRAttrAssoGroup.createGroup(obj, LogicalOperator.OR);
                        obj = null;
                    }
                    else
                    {
                        attrTemp = obj[0] as Attribute;
                    }
                    associationList.Add(CreateQRAttrAssoGroup.createAssociation("edu.northwestern.radiology.aim.User", "user", grpAnnatomicEntityCharacteristic, attrTemp, null));
                }
            }
            var         resultStudy = new ArrayList();
            Association assoStudy   = null;

            obj = null;
            foreach (QueryData queryData in _queryParameters.StudyInstanceUidParameters)
            {
                if (!queryData.IsEmpty)
                {
                    resultStudy.Add(CreateAttribute("instanceUID", queryData));
                }
            }
            if (resultStudy.Count > 0)
            {
                obj = (object[])resultStudy.ToArray(typeof(Attribute));
            }
            if (obj != null && obj.Length > 0)
            {
                attrTemp = null;
                Group grpStudy = null;
                if (obj.Length > 1)
                {
                    grpStudy = CreateQRAttrAssoGroup.createGroup(obj, LogicalOperator.OR);
                    obj      = null;
                }
                else
                {
                    attrTemp = obj[0] as Attribute;
                }
                assoStudy = CreateQRAttrAssoGroup.createAssociation("edu.northwestern.radiology.aim.ImageStudy", "imageStudy", grpStudy, attrTemp, null);
            }
            if (assoStudy != null)
            {
                associationList.Add(CreateQRAttrAssoGroup.createAssociation("edu.northwestern.radiology.aim.DICOMImageReference", "imageReferenceCollection", null, null, assoStudy));
            }
            obj = null;
            Group grpImageAnnotation = null;

            if (associationList.Count > 0)
            {
                obj = (object[])associationList.ToArray(typeof(Association));
            }
            if (obj != null && obj.Length > 0)
            {
                assoTemp = null;
                if (obj.Length > 1)
                {
                    grpImageAnnotation = CreateQRAttrAssoGroup.createGroup(obj, LogicalOperator.AND);
                }
                else
                {
                    assoTemp = obj[0] as Association;
                }
            }
            QueryRequestCqlQuery arg = CreateQRAttrAssoGroup.createQueryRequestCqlQuery("edu.northwestern.radiology.aim.ImageAnnotation", null, null, assoTemp, grpImageAnnotation);

            var doc = XMLSerializingDeserializing.Serialize(arg);

            Console.WriteLine(doc.InnerXml);

            CQLQueryResults result;

            try
            {
                result = proxy.query(arg);
            }
            catch (System.Net.WebException ex)
            {
                Console.WriteLine(ex.Message);
                result = null;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                result = null;
                throw new GridServicerException("Error querying AIM data service", e);
            }
            return(result);
        }
Exemple #46
0
        /// <summary>
        /// Finds the shortest paths to all other vertices from the specified source vertex.
        /// </summary>
        /// <param name="weightedGraph">The weighted graph.</param>
        /// <param name="fromVertex">The source vertex.</param>
        /// <returns>A graph representing the shortest paths from the source node to all other nodes in the graph.</returns>
        public static Graph <T> FindShortestPaths(Graph <T> weightedGraph, Vertex <T> fromVertex)
        {
            #region Parameter Checks

            if (weightedGraph == null)
            {
                throw new ArgumentNullException("weightedGraph");
            }

            if (fromVertex == null)
            {
                throw new ArgumentNullException("fromVertex");
            }

            if (!weightedGraph.ContainsVertex(fromVertex))
            {
                throw new ArgumentException(Resources.VertexCouldNotBeFound);
            }

            #endregion

            Heap <Association <double, Vertex <T> > > heap =
                new Heap <Association <double, Vertex <T> > >(
                    HeapType.MinHeap,
                    new Comparers.AssociationKeyComparer <double, Vertex <T> >());

            Dictionary <Vertex <T>, VertexInfo <T> > vertexStatus = new Dictionary <Vertex <T>, VertexInfo <T> >();

            // Initialise the vertex distances to
            using (IEnumerator <Vertex <T> > verticeEnumerator = weightedGraph.Vertices) {
                while (verticeEnumerator.MoveNext())
                {
                    vertexStatus.Add(verticeEnumerator.Current, new VertexInfo <T>(double.MaxValue, null, false));
                }
            }

            vertexStatus[fromVertex].Distance = 0;

            // Add the source vertex to the heap - we'll be branching out from it.
            heap.Add(new Association <double, Vertex <T> >(0, fromVertex));

            while (heap.Count > 0)
            {
                Association <double, Vertex <T> > item = heap.RemoveRoot();

                VertexInfo <T> vertexInfo = vertexStatus[item.Value];

                if (!vertexInfo.IsFinalised)
                {
                    List <Edge <T> > edges = item.Value.EmanatingEdgeList;

                    vertexStatus[item.Value].IsFinalised = true;

                    // Enumerate through all the edges emanating from this node
                    for (int i = 0; i < edges.Count; i++)
                    {
                        Vertex <T> partnerVertex = edges[i].GetPartnerVertex(item.Value);

                        // Calculate the new distance to this distance
                        double distance = vertexInfo.Distance + edges[i].Weight;

                        VertexInfo <T> newVertexInfo = vertexStatus[partnerVertex];

                        // Found a better path, update the vertex status and add the
                        // vertex to the heap for further analysis
                        if (distance < newVertexInfo.Distance)
                        {
                            newVertexInfo.EdgeFollowed = edges[i];
                            newVertexInfo.Distance     = distance;
                            heap.Add(new Association <double, Vertex <T> >(distance, partnerVertex));
                        }
                    }
                }
            }

            // Now build the new graph
            Graph <T> newGraph = new Graph <T>(weightedGraph.IsDirected);

            Dictionary <Vertex <T>, VertexInfo <T> > .Enumerator enumerator = vertexStatus.GetEnumerator();

            // This dictionary is used for mapping between the old vertices and the new vertices put into the graph
            Dictionary <Vertex <T>, Vertex <T> > vertexMap = new Dictionary <Vertex <T>, Vertex <T> >(vertexStatus.Count);

            Vertex <T>[] newVertices = new Vertex <T> [vertexStatus.Count];

            while (enumerator.MoveNext())
            {
                Vertex <T> newVertex = new Vertex <T>(
                    enumerator.Current.Key.Data,
                    enumerator.Current.Value.Distance
                    );

                vertexMap.Add(enumerator.Current.Key, newVertex);

                newGraph.AddVertex(newVertex);
            }

            enumerator = vertexStatus.GetEnumerator();

            while (enumerator.MoveNext())
            {
                VertexInfo <T> info = enumerator.Current.Value;

                // Check if an edge has been included to this vertex
                if ((info.EdgeFollowed != null) && (enumerator.Current.Key != fromVertex))
                {
                    newGraph.AddEdge(
                        vertexMap[info.EdgeFollowed.GetPartnerVertex(enumerator.Current.Key)],
                        vertexMap[enumerator.Current.Key],
                        info.EdgeFollowed.Weight);
                }
            }


            return(newGraph);
        }
        internal CreateAssociationSetMappingCommand(
            EntityContainerMapping entityContainerMapping, AssociationSet associationSet, Association association,
            StorageEntitySet storageEntitySet)
            : base(PrereqId)
        {
            CommandValidation.ValidateEntityContainerMapping(entityContainerMapping);
            CommandValidation.ValidateAssociationSet(associationSet);
            CommandValidation.ValidateAssociation(association);
            CommandValidation.ValidateStorageEntitySet(storageEntitySet);

            EntityContainerMapping = entityContainerMapping;
            AssociationSet         = associationSet;
            Association            = association;
            StorageEntitySet       = storageEntitySet;
        }
Exemple #48
0
        public List <long> GetRelatedValues(long sourceGlobalId, Association association)
        {
            string message = "Getting related values method started.";

            Console.WriteLine(message);
            CommonTrace.WriteTrace(CommonTrace.TraceError, message);

            List <long> resultIds = new List <long>();


            XmlTextWriter xmlWriter         = null;
            int           numberOfResources = 2;

            try
            {
                List <ModelCode> properties = new List <ModelCode>();
                properties.Add(ModelCode.IDOBJ_DESCRIPTION);
                properties.Add(ModelCode.IDOBJ_MRID);
                properties.Add(ModelCode.IDOBJ_NAME);

                int iteratorId    = GdaQueryProxy.GetRelatedValues(sourceGlobalId, properties, association);
                int resourcesLeft = GdaQueryProxy.IteratorResourcesLeft(iteratorId);

                xmlWriter            = new XmlTextWriter(Config.Instance.ResultDirecotry + "\\GetRelatedValues_Results.xml", Encoding.Unicode);
                xmlWriter.Formatting = Formatting.Indented;

                while (resourcesLeft > 0)
                {
                    List <ResourceDescription> rds = GdaQueryProxy.IteratorNext(numberOfResources, iteratorId);

                    for (int i = 0; i < rds.Count; i++)
                    {
                        resultIds.Add(rds[i].Id);
                        rds[i].ExportToXml(xmlWriter);
                        xmlWriter.Flush();
                    }

                    resourcesLeft = GdaQueryProxy.IteratorResourcesLeft(iteratorId);
                }

                GdaQueryProxy.IteratorClose(iteratorId);

                message = "Getting related values method successfully finished.";
                Console.WriteLine(message);
                CommonTrace.WriteTrace(CommonTrace.TraceError, message);
            }
            catch (Exception e)
            {
                message = string.Format("Getting related values method  failed for sourceGlobalId = {0} and association (propertyId = {1}, type = {2}). Reason: {3}", sourceGlobalId, association.PropertyId, association.Type, e.Message);
                Console.WriteLine(message);
                CommonTrace.WriteTrace(CommonTrace.TraceError, message);
            }
            finally
            {
                if (xmlWriter != null)
                {
                    xmlWriter.Close();
                }
            }

            return(resultIds);
        }
Exemple #49
0
 public void onDisAssociated(Association a)
 {
     logger.LogDebug($"SCTP disassociated.");
 }
        private static void ReadCSDLType(XElement schemaElement, XElement entityTypeElement, CSDLContainer container, TypeBase baseType)
        {
            if (baseType.Name == null)
            {
                baseType.Name = entityTypeElement.Attribute("Name").Value;
            }
            SetVisibilityValueFromAttribute(entityTypeElement, "TypeAccess", typeAccess => baseType.Visibility = typeAccess);

            foreach (var propertyElement in entityTypeElement.Elements(XName.Get("Property", csdlNamespace.NamespaceName)))
            {
                var          name         = propertyElement.Attribute("Name").Value;
                var          keyElement   = entityTypeElement.Element(XName.Get("Key", csdlNamespace.NamespaceName));
                var          propertyType = GetScalarPropertyTypeFromAttribute(propertyElement);
                PropertyBase property;
                if (propertyType == null)
                {
                    property = new ComplexProperty(GetName(propertyElement.Attribute("Type").Value))
                    {
                        Name = name
                    };
                    baseType.ComplexProperties.Add((ComplexProperty)property);
                }
                else
                {
                    property = new ScalarProperty()
                    {
                        Name = name, IsKey = keyElement != null && keyElement.Elements(XName.Get("PropertyRef", csdlNamespace.NamespaceName)).Any(pr => pr.Attribute("Name").Value == name), Type = propertyType.Value
                    };
                    var scalarProp = (ScalarProperty)property;
                    SetBoolValueFromAttribute(propertyElement, "Nullable", nullable => scalarProp.Nullable = nullable);
                    SetVisibilityValueFromAttribute(propertyElement, "SetterAccess", setterAccess => scalarProp.SetVisibility = setterAccess);
                    SetIntValueFromAttribute(propertyElement, "MaxLength", maxLength => scalarProp.MaxLength        = maxLength);
                    SetBoolValueFromAttribute(propertyElement, "Unicode", unicode => scalarProp.Unicode             = unicode);
                    SetBoolValueFromAttribute(propertyElement, "FixedLength", fixedLength => scalarProp.FixedLength = fixedLength);
                    SetIntValueFromAttribute(propertyElement, "Precision", precision => scalarProp.Precision        = precision);
                    SetIntValueFromAttribute(propertyElement, "Scale", scale => scalarProp.Scale = scale);
                    SetStringValueFromAttribute(propertyElement, "ConcurrencyMode", concurrencyMode => scalarProp.ConcurrencyMode = ConcurrencyMode.None);
                    SetStringValueFromAttribute(propertyElement, "DefaultValue", defaultValue => scalarProp.DefaultValue          = defaultValue);
                    SetStringValueFromAttribute(propertyElement, "Collation", collation => scalarProp.Collation = collation);
                    baseType.ScalarProperties.Add(scalarProp);
                }
                SetVisibilityValueFromAttribute(propertyElement, "GetterAccess", getterAccess => property.GetVisibility = getterAccess);
            }
            var entityType = baseType as EntityType;

            if (entityType != null)
            {
                foreach (var navigationPropertyElement in entityTypeElement.Elements(XName.Get("NavigationProperty", csdlNamespace.NamespaceName)))
                {
                    var         navigationPropertyname = navigationPropertyElement.Attribute("Name").Value;
                    var         associationName        = GetName(navigationPropertyElement.Attribute("Relationship").Value);
                    var         associationElement     = schemaElement.Elements(XName.Get("Association", csdlNamespace.NamespaceName)).First(ae => ae.Attribute("Name").Value == associationName);
                    Association association            = container.AssociationsCreated.GetByName(associationName);
                    bool        associationExisting    = association != null;
                    if (!associationExisting)
                    {
                        association = new Association {
                            Name = associationName
                        };
                        container.AssociationsCreated.Add(association);
                    }
                    var navigationProperty = new NavigationProperty(association)
                    {
                        Name = navigationPropertyname
                    };
                    var roleName = navigationPropertyElement.Attribute("FromRole").Value;
                    SetCardinalityValueFromAttribute(associationElement.Elements(XName.Get("End", csdlNamespace.NamespaceName)).First(ee => ee.Attribute("Role").Value == roleName), cardinality => navigationProperty.Cardinality = cardinality);
                    SetVisibilityValueFromAttribute(navigationPropertyElement, "GetterAccess", visibility => navigationProperty.GetVisibility = visibility);
                    SetVisibilityValueFromAttribute(navigationPropertyElement, "SetterAccess", visibility => navigationProperty.SetVisibility = visibility);
                    if (associationExisting)
                    {
                        association.PropertyEnd2     = navigationProperty;
                        association.PropertyEnd2Role = roleName;
                    }
                    else
                    {
                        association.PropertyEnd1     = navigationProperty;
                        association.PropertyEnd1Role = roleName;
                        string             toRoleName             = navigationPropertyElement.Attribute("ToRole").Value;
                        NavigationProperty fakeNavigationProperty = new NavigationProperty(association)
                        {
                            Name = roleName, Generate = false
                        };
                        SetCardinalityValueFromAttribute(associationElement.Elements(XName.Get("End", csdlNamespace.NamespaceName)).First(ee => ee.Attribute("Role").Value == toRoleName), cardinality => fakeNavigationProperty.Cardinality = cardinality);
                        association.PropertyEnd2     = fakeNavigationProperty;
                        association.PropertyEnd2Role = toRoleName;
                    }
                    var referentialConstraintElement = associationElement.Element(XName.Get("ReferentialConstraint", csdlNamespace.NamespaceName));
                    if (referentialConstraintElement != null)
                    {
                        var referentialConstraintRoleElement = referentialConstraintElement.Elements().First(rce => rce.Attribute("Role").Value == roleName);
                        var scalarProperties = referentialConstraintRoleElement.Elements(XName.Get("PropertyRef", csdlNamespace.NamespaceName)).Select(e => entityType.AllScalarProperties.First(sp => sp.Name == e.Attribute("Name").Value));
                        switch (referentialConstraintRoleElement.Name.LocalName)
                        {
                        case "Principal":
                            association.PrincipalRole       = roleName;
                            association.PrincipalProperties = scalarProperties;
                            break;

                        case "Dependent":
                            association.DependentRole       = roleName;
                            association.DependentProperties = scalarProperties;
                            break;

                        default:
                            throw new NotImplementedException();
                        }
                    }
                    entityType.NavigationProperties.Add(navigationProperty);
                }
            }
        }
Exemple #51
0
 public static GeometryAttribute <T> CheckArityAndAssociation <T>(this GeometryAttribute <T> self, int arity, Association assoc) where T : unmanaged
 => self?.CheckArity(arity)?.CheckAssociation(assoc);
Exemple #52
0
            public AssociatedTableContext(ExpressionBuilder builder, TableContext parent, Association association)
                : base(builder, parent.SqlQuery)
            {
                var type = TypeHelper.GetMemberType(association.MemberAccessor.MemberInfo);

                var left = association.CanBeNull;

                if (TypeHelper.IsSameOrParent(typeof(IEnumerable), type))
                {
                    var etypes = TypeHelper.GetGenericArguments(type, typeof(IEnumerable));
                    type   = etypes != null && etypes.Length > 0 ? etypes[0] : TypeHelper.GetListItemType(type);
                    IsList = true;
                }

                OriginalType = type;
                ObjectType   = GetObjectType();
                ObjectMapper = Builder.MappingSchema.GetObjectMapper(ObjectType);
                SqlTable     = new SqlTable(builder.MappingSchema, ObjectType);

                var psrc = parent.SqlQuery.From[parent.SqlTable];
                var join = left ? SqlTable.WeakLeftJoin() : IsList?SqlTable.InnerJoin() : SqlTable.WeakInnerJoin();

                _parentAssociation    = parent;
                ParentAssociationJoin = join.JoinedTable;

                psrc.Joins.Add(join.JoinedTable);

                //Init(mappingSchema);

                for (var i = 0; i < association.ThisKey.Length; i++)
                {
                    SqlField field1;

                    SqlField field2;

                    if (!parent.SqlTable.Fields.TryGetValue(association.ThisKey[i], out field1))
                    {
                        throw new LinqException("Association key '{0}' not found for type '{1}.", association.ThisKey[i], parent.ObjectType);
                    }

                    if (!SqlTable.Fields.TryGetValue(association.OtherKey[i], out field2))
                    {
                        throw new LinqException("Association key '{0}' not found for type '{1}.", association.OtherKey[i], ObjectType);
                    }

                    join.Field(field1).Equal.Field(field2);
                }
            }
Exemple #53
0
 /// <summary>
 /// Compares two objects and returns a value indicating whether one is less than, equal to, or greater than the other.
 /// </summary>
 /// <param name="x">The first object to compare.</param>
 /// <param name="y">The second object to compare.</param>
 /// <returns>
 /// Value Condition Less than zerox is less than y.Zerox equals y.Greater than zerox is greater than y.
 /// </returns>
 public int Compare(Association <TKey, TValue> x, Association <TKey, TValue> y)
 {
     return(nestedComparer.Compare(x.Key, y.Key));
 }
        /// <summary>
        /// 处理关联
        /// </summary>
        /// <param name="sql">Select语句</param>
        /// <param name="context">SQL构造上下文</param>
        /// <param name="association">关联</param>
        private void HandlingAssociation(SelectSqlStatement sql, SqlBuildingContext context, Association association)
        {
            if (association.AssoDomainObject == null)
                throw new Exception("Association cannot find Associate Model: " + association.ID);
            if (association.AssoDomainObject == null)
                throw new Exception("Association cannot find Associate ModelObject: " + association.ID);
            if (association.AssoDomainObject.DataObject == null)
                throw new Exception("Association cannot find Associate DataObject: " + association.ID);

            //关联中使用的SqlTable,通过关联的ID进行标识,存在一个节点上的多个元素关联同一个表的情况
            SqlTable associatedSqlTable = base.FindSqlTable(association.ID, sql.SqlBuildingInfo);
            if (associatedSqlTable == null)
            {
                var assoTableName = context.DataObjectTableMapping[association.AssoDomainObject.DataObject.ID];
                associatedSqlTable = base.TryFindAndRegistSqlTable(association.AssoDomainObject.DataObject.ID, assoTableName, assoTableName, assoTableName, sql.SqlBuildingInfo);
            }

            var childAssociation = new InternalAssociation()
            {
                AssociatedCommonObject = association.AssoDomaiModel,
                AssociatedCoNode = association.AssoDomainObject,
                AssociatedDataObject = association.AssoDomainObject.DataObject,
                AssociatedTable = associatedSqlTable,
                LocatedCommonObject = sql.SqlBuildingInfo.CommonObject,
                LocatedDataObject = sql.SqlBuildingInfo.CurrentDataObject,
                LocatedNode = sql.SqlBuildingInfo.CurrentNode,
                LocatedTable = sql.SqlBuildingInfo.CurrentSqlTable,
                Association = association,
                AdditionalCondition = association.FilterCondition
            };

            foreach (var refElement in association.RefElements)
            {
                var element = association.AssoDomainObject.Elements.FirstOrDefault(i => i.ID == refElement.ElementID);
                var assElement = new InternalRefElement()
                {
                    Element = element,
                    Label = element.Alias
                };
                childAssociation.RefElements.Add(assElement);
            }

            BuildLeftJoin(sql, childAssociation, context);
        }
        public ActionResult Edit(Association association)
        {
            Association CA = new Association();

            if (association.AssociationID != Guid.Empty)
            {
                CA = reposetory.GetAssociation(association.AssociationID);
                if (CA == null)
                {
                    return(RedirectToAction("Index"));
                }
            }

            if (ModelState.ContainsKey("Name"))
            {
                ModelState["Name"].Errors.Clear();
            }

            if (ModelState.IsValid)
            {
                bool StatusChanged = false;
                //CA.Name = association.Name;
                //if (CA.Status != association.Status)
                //{
                //    CA.Status = association.Status; //TODO: Implement notification if Status changes
                //    StatusChanged = true;
                //}
                //CA.Governance = association.Governance;
                CA.AssociationEmail = association.AssociationEmail;
                //CA.Established = association.Established;
                CA.CVRNR        = association.CVRNR;
                CA.TeamPhone    = association.TeamPhone;
                CA.ContactPhone = association.ContactPhone;
                CA.Address      = association.Address;
                CA.Zip          = association.Zip;
                CA.City         = association.City;
                CA.TextServiceProviderUserName = association.TextServiceProviderUserName;
                CA.TextServiceProviderPassword = association.TextServiceProviderPassword;
                CA.SendTeamText          = association.SendTeamText;
                CA.SendTeamTextDays      = association.SendTeamTextDays;
                CA.TeamMessage           = association.TeamMessage;
                CA.TeamMessageTeamLeader = association.TeamMessageTeamLeader;
                CA.SendNoteTeamleader    = association.SendNoteTeamleader;
                CA.NoteTextTime          = association.NoteTextTime;
                CA.Comments     = association.Comments;
                CA.Scheduletext = association.Scheduletext.CleanHTML();
                //Setup
                CA.UseSchedulePlanning     = association.UseSchedulePlanning;
                CA.UseShiftTeam            = association.UseShiftTeam;
                CA.UseTakeTeamSpot         = association.UseTakeTeamSpot;
                CA.UseTeamExchange         = association.UseTeamExchange;
                CA.UseKeyBox               = association.UseKeyBox;
                CA.UseLists                = association.UseLists;
                CA.UsePolicePlanning       = association.UsePolicePlanning;
                CA.DeadlineHoursTeamChange = association.DeadlineHoursTeamChange;
                CA.UsePressPage            = association.UsePressPage;
                CA.UseLinksPage            = association.UseLinksPage;
                CA.UseSponsorPage          = association.UseSponsorPage;



                if (reposetory.SaveAssociation(CA))
                {
                    ViewBag.FormSucces = true;
                    if (StatusChanged)
                    {
                        Notification not = reposetory.Notify(CA, String.Format(Notifications.AssociationStatusChanged, CA.Name, CA.Status.DisplayName()));
                        reposetory.NotifyAddAdministration(not);
                        reposetory.NotifyAddAssociation(not, CA.AssociationID);
                        reposetory.NotifySave(not);
                    }
                }
            }

            return(View(association));
        }
 public ExplorerAssociation(EditingContext context, Association assoc, ExplorerEFElement parent)
     : base(context, assoc, parent)
 {
     // do nothing
 }
 protected abstract AssociationEnd GetEnd(Association association);
Exemple #58
0
        private void button3_Click(object sender, RoutedEventArgs e)
        {
            StringBuilder       s  = new StringBuilder();
            ResourceDescription rd = null;

            ModelCode   mc  = new ModelCode();
            List <long> ids = new List <long>();
            long        gid = 0;

            gid = (long)comboBox3.SelectedItem;
            mc  = (ModelCode)comboBox5.SelectedItem;
            Association asoc = new Association();

            if (comboBox4.SelectedItem == null)
            {
                asoc.Type = 0;
            }
            else
            {
                asoc.Type = (ModelCode)comboBox4.SelectedItem;
            }

            asoc.PropertyId = mc;


            ids = gda.GetRelatedValues(gid, asoc);

            textBox3.Text = "";
            for (int i = 0; i < ids.Count; i++)
            {
                rd = gda.GetValues(ids[i]);
                short            type       = ModelCodeHelper.ExtractTypeFromGlobalId(ids[i]);
                List <ModelCode> properties = mrd.GetAllPropertyIds((DMSType)type);

                textBox3.Text += "ID: ";
                textBox3.Text += s.Append(String.Format("0x{0:x16}", gid)).ToString() + "\n";
                textBox3.Text += "TYPE: ";
                textBox3.Text += ((DMSType)ModelCodeHelper.ExtractTypeFromGlobalId(ids[i])).ToString();

                for (int x = 0; x < rd.Properties.Count(); x++)
                {
                    if (rd.Properties[x].Type == PropertyType.ReferenceVector)
                    {
                        textBox3.Text += "\n";
                        textBox3.Text += properties[x].ToString();
                        textBox3.Text += ": ";

                        for (int j = 0; j < rd.Properties[x].PropertyValue.LongValues.Count(); j++)
                        {
                            textBox3.Text += rd.Properties[x].PropertyValue.LongValues[j].ToString();

                            textBox3.Text += " ";
                        }
                    }
                    else
                    {
                        textBox3.Text += "\n";
                        textBox3.Text += properties[x].ToString();
                        textBox3.Text += ": ";
                        textBox3.Text += rd.Properties[x].ToString();
                    }
                }
                textBox3.Text += "\n\n";
            }
        }
        public List <ManageFilterTemplateModel> GetFiletTemplateManageData(string BPID)
        {
            //added Smit userid,Fhnumb,associate
            string UserID                = Session["UserID"].ToString();
            string FHnumb                = Session["FHnumber"].ToString();
            string Associate             = Session["Associate"].ToString();
            string fullPathUrlTemplate   = "";
            string fullPathUrlHarmonized = "";
            string host       = Request.Url.Host;
            string port       = Request.Url.Port.ToString();
            string rootDomain = ConfigurationManager.AppSettings["rootDomain"].ToString();

            if (!string.IsNullOrEmpty(port))
            {
                fullPathUrlTemplate   = rootDomain + host.TrimEnd('/') + ":" + port + "/Target/" + Session["BPID"] + "/";
                fullPathUrlHarmonized = rootDomain + host.TrimEnd('/') + ":" + port + "/Harmonized/" + Session["BPID"] + "/";
            }
            else
            {
                fullPathUrlTemplate   = rootDomain + host.TrimEnd('/') + "/Target/" + Session["BPID"] + "/";
                fullPathUrlHarmonized = rootDomain + host.TrimEnd('/') + "/Harmonized/" + Session["BPID"] + "/";
            }
            //added Smit
            Association        association                     = new Association();
            Template           _template                       = new Template();
            CHFilter           _chFilter                       = new CHFilter();
            HarmonizeTemplate  _harmonizeTemplate              = new HarmonizeTemplate();
            FileUploadDownload _fileUploadDownload             = new FileUploadDownload();
            List <ManageFilterTemplateModel> lstFilterTemplate = new List <ManageFilterTemplateModel>();
            DataSet ds = _fhManage.GetFilterTemplateDetailsByBPID(BPID);

            if (ds.Tables[0].Rows.Count > 0)
            {
                //added smit
                association.FHnumber        = FHnumb;
                association.Associate       = Associate;
                association.AssocStatus     = true;
                association.AssocCanceledBy = UserID;
                int    createAssociation = _fhFileData.CreateAssociation(association);
                string recordId1         = _fhFileData.GetAssociationInActiveId(FHnumb, Associate);
                if (recordId1 != "")
                {
                    Session["RecordId"] = recordId1;
                }
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    // Add template data
                    _template = new Template
                    {
                        BPID             = row["BPID"].ToString(),
                        HFLTRID          = row["HFLTRID"].ToString(),
                        TEMPID           = row["TEMPID"].ToString(),
                        Partner          = row["Partner"].ToString(),
                        TemplateType     = row["TemplateType"].ToString(),
                        TemplateDesc     = row["TemplateDesc"].ToString(),
                        TemplateName     = row["TemplateName"].ToString(),
                        DocExt           = row["DocExt"].ToString(),
                        CreatedDate      = Convert.ToDateTime(row["TempCDate"]),
                        UpdatedDate      = Convert.ToDateTime(row["TempUDate"]),
                        FileID           = Convert.ToInt32(row["FileID"]),
                        SECCODE          = row["TempSECCode"].ToString(),
                        TemplateText     = row["TemplateText"].ToString(),
                        IsDeleted        = Convert.ToBoolean(row["TempDeleted"]),
                        IsArchive        = Convert.ToBoolean(row["TempArchive"]),
                        InternalExternal = row["InternalExternal"].ToString()
                    };
                    // Add Filter data
                    _chFilter = new CHFilter
                    {
                        SECID        = row["CSECID"].ToString(),
                        FLTRNUM      = row["CFILTERNUM"].ToString(),
                        FLTRID       = row["CFLTERID"].ToString(),
                        FilterDesc   = row["FilterDesc"].ToString(),
                        FilterText   = row["FilterText"].ToString(),
                        FilterName   = row["FilterName"].ToString(),
                        CreatedDate  = Convert.ToDateTime(row["CFCDate"]),
                        UpdatedDate  = Convert.ToDateTime(row["CFUDate"]),
                        AssignScheme = Convert.ToInt32(row["AssignScheme"])
                    };
                    // Add File history data
                    _fileUploadDownload = new FileUploadDownload
                    {
                        OrginalFileName      = row["OrignalFileName"].ToString(),
                        SourceFilePath       = row["SourceFilePath"].ToString(),
                        TargetFilePath       = row["TargetFilePath"].ToString(),
                        IsDeleted            = Convert.ToBoolean(row["FileDelete"]),
                        IsArchive            = Convert.ToBoolean(row["FileArchive"]),
                        TemplateDownloadPath = fullPathUrlTemplate + row["NewFileName"].ToString()
                    };
                    _harmonizeTemplate = new HarmonizeTemplate
                    {
                        ID            = Convert.ToInt32(row["HTID"]),
                        TemplateName  = row["TemplateName"].ToString(),
                        TemplateID    = Convert.ToInt32(row["HTTemplateID"]),
                        NoOfDownloads = Convert.ToInt32(row["NoOfDownloads"]),
                        CreatedDate   = Convert.ToDateTime(row["HTCreatedDate"]),
                        UpdatedDate   = Convert.ToDateTime(row["HTUpdateDate"]),
                        TemplatePath  = fullPathUrlHarmonized + row["TemplatePath"].ToString(),
                        Comment       = row["HTComment"].ToString(),
                        HTFHNumber    = row["HTFHNumber"].ToString(),
                        IsArchive     = Convert.ToBoolean(row["HTIsArchive"])
                    };
                    // Main file to Add list of element
                    lstFilterTemplate.Add(new ManageFilterTemplateModel
                    {
                        Template           = _template,
                        Filter             = _chFilter,
                        FileUploadDownload = _fileUploadDownload,
                        HarmonizeTemplate  = _harmonizeTemplate
                    });
                }
            }
            return(lstFilterTemplate);
        }
 public IActionResult AddToCategory(Association newAssoc)
 {
     dbContext.Associations.Add(newAssoc);
     dbContext.SaveChanges();
     return(RedirectToAction("ShowProduct", new { ProductId = newAssoc.ProductId }));
 }