Example #1
0
        public virtual CatalogProduct ToModel(CatalogProduct product, bool convertChildrens = true, bool convertAssociations = true)
        {
            if (product == null)
            {
                throw new ArgumentNullException(nameof(product));
            }


            product.Id           = Id;
            product.CreatedDate  = CreatedDate;
            product.CreatedBy    = CreatedBy;
            product.ModifiedDate = ModifiedDate;
            product.ModifiedBy   = ModifiedBy;

            product.CatalogId              = CatalogId;
            product.CategoryId             = CategoryId;
            product.Code                   = Code;
            product.DownloadExpiration     = DownloadExpiration;
            product.DownloadType           = DownloadType;
            product.EnableReview           = EnableReview;
            product.EndDate                = EndDate;
            product.Gtin                   = Gtin;
            product.HasUserAgreement       = HasUserAgreement;
            product.Height                 = Height;
            product.IsActive               = IsActive;
            product.IsBuyable              = IsBuyable;
            product.Length                 = Length;
            product.MainProductId          = ParentId;
            product.ManufacturerPartNumber = ManufacturerPartNumber;
            product.MaxNumberOfDownload    = MaxNumberOfDownload;
            product.MaxQuantity            = (int)MaxQuantity;
            product.MeasureUnit            = MeasureUnit;
            product.MinQuantity            = (int)MinQuantity;
            product.Name                   = Name;
            product.PackageType            = PackageType;
            product.Priority               = Priority;
            product.ProductType            = ProductType;
            product.ShippingType           = ShippingType;
            product.StartDate              = StartDate;
            product.TaxType                = TaxType;
            product.TrackInventory         = TrackInventory;
            product.Vendor                 = Vendor;
            product.Weight                 = Weight;
            product.WeightUnit             = WeightUnit;
            product.Width                  = Width;

            //Links
            product.Links = CategoryLinks.Select(x => x.ToModel(AbstractTypeFactory <CategoryLink> .TryCreateInstance())).ToList();
            //Images
            product.Images = Images.OrderBy(x => x.SortOrder).Select(x => x.ToModel(AbstractTypeFactory <Image> .TryCreateInstance())).ToList();
            //Assets
            product.Assets = Assets.OrderBy(x => x.CreatedDate).Select(x => x.ToModel(AbstractTypeFactory <Asset> .TryCreateInstance())).ToList();
            // EditorialReviews
            product.Reviews = EditorialReviews.Select(x => x.ToModel(AbstractTypeFactory <EditorialReview> .TryCreateInstance())).ToList();

            if (convertAssociations)
            {
                // Associations
                product.Associations           = Associations.Select(x => x.ToModel(AbstractTypeFactory <ProductAssociation> .TryCreateInstance())).OrderBy(x => x.Priority).ToList();
                product.ReferencedAssociations = ReferencedAssociations.Select(x => x.ToReferencedAssociationModel(AbstractTypeFactory <ProductAssociation> .TryCreateInstance())).OrderBy(x => x.Priority).ToList();
            }

            //item property values
            product.PropertyValues = ItemPropertyValues
                                     .OrderBy(x => x.DictionaryItem?.SortOrder)
                                     .ThenBy(x => x.Name)
                                     .SelectMany(x => x.ToModel(AbstractTypeFactory <PropertyValue> .TryCreateInstance())).ToList();

            if (Parent != null)
            {
                product.MainProduct = Parent.ToModel(AbstractTypeFactory <CatalogProduct> .TryCreateInstance(), false, convertAssociations);
            }

            if (convertChildrens)
            {
                // Variations
                product.Variations = new List <CatalogProduct>();
                foreach (var variation in Childrens)
                {
                    var productVariation = variation.ToModel(AbstractTypeFactory <CatalogProduct> .TryCreateInstance());
                    productVariation.MainProduct   = product;
                    productVariation.MainProductId = product.Id;
                    product.Variations.Add(productVariation);
                }
            }
            return(product);
        }
Example #2
0
 public void AddAssociation(NewFileIconAssociation association)
 {
     Associations.Add(association);
     Rows.Add(association.FileIcon, association.FileType);
 }
Example #3
0
        public object Render()
        {
            AssociationView derivedBaseProperty = Property.DerivedBaseProperty();

            var derivedName = derivedBaseProperty != null
                ? derivedBaseProperty.OtherEntity.Name
                : null;

            var desc = this[ResourceRenderer.DescriptionOverride] != null
                ? this[ResourceRenderer.DescriptionOverride]
                       .ScrubForXmlDocumentation()
                : UniqueIdSpecification.IsUniqueId(Property.PropertyName)
                    ? string.Format(
                "A unique alphanumeric code assigned to a {0}.",
                Property.RemoveUniqueIdOrUsiFromPropertyName()
                .ToLower())
                    : Property.Description.ScrubForXmlDocumentation();

            var propertyNamespacePrefix = Property.ProperCaseSchemaName() == null
                ? null
                : $"{Namespaces.Entities.Common.RelativeNamespace}.{Property.ProperCaseSchemaName()}.";

            return(new
            {
                Description = desc,
                Misc = this[ResourceRenderer.MiscellaneousComment],
                JsonPropertyName = Property.JsonPropertyName,
                PropertyName = IsReferencedProperty
                    ? string.Format(
                    "backReference.{0} != null && backReference.{0}.{1}",
                    Property.EntityProperty.Entity.Aggregate.Name,
                    Property.PropertyName)
                    : Property.PropertyName,
                CSharpSafePropertyName = Property.PropertyName.MakeSafeForCSharpClass(Property.ParentFullName.Name),
                ParentName =
                    Property.EntityProperty.IsFromParent
                        ? Property.EntityProperty.Entity.Parent.Name
                        : Property.EntityProperty.Entity.Name,
                PropertyFieldName = Property.EntityProperty.Entity
                                    .ResolvedEdFiEntityName()
                                    .ToCamelCase(),
                PropertyType = Property.PropertyType.ToCSharp(true),
                IsFirstProperty = IsFirstProperty,
                IsLastProperty = IsLastProperty,
                IsUnique = IsUnique,
                NumericAttribute = Property.ToRangeAttributeCSharp(),
                IsDateOnlyProperty = Property.PropertyType.DbType == DbType.Date,
                IsTimeSpanProperty = Property.PropertyType.DbType == DbType.Time,
                ClassName = this[ResourceRenderer.ClassName]
                            ?? Property.EntityProperty.Entity
                            .ResolvedEdFiEntityName(),
                UnifiedKeys = Associations.Any()
                    ? AssembleOtherUnifiedChild(Associations)
                    : null,
                UnifiedExtensions = ExtensionAssociations.Any()
                    ? AssembleOtherUnifiedChild(ExtensionAssociations)
                    : null,
                ImplicitPropertyName = Associations.Any()
                    ? Associations.OrderByDescending(x => x.IsRequired)
                                       .First()
                                       .Name
                    : null,
                ImplicitNullable = Property.PropertyType.IsNullableCSharpType()
                    ? ".GetValueOrDefault()"
                    : null,
                ParentPropertyName = this[ResourceRenderer.ParentPropertyName],
                DerivedName = derivedName,
                PropertyNamespacePrefix = propertyNamespacePrefix,
                NullPropertyPrefix = Property.EntityProperty.Entity.IsEntityExtension
                    ? $"{propertyNamespacePrefix}I{Property.EntityProperty.Entity.Name}."
                    : $"{propertyNamespacePrefix}I{Property.EntityProperty.Entity.ResolvedEdFiEntityName()}."
            });
        }
        private Associations GetAssociations(int constituentId)
        {
            var associationsData = HttpHelper.Get<AssociationsData>(string.Format(serviceBaseUri + "/Associations?ConstituentId={0}", constituentId));

            mapper = new AutoDataContractMapper();
            var associations = new Associations();
            mapper.MapList(associationsData, associations, typeof(Association));
            return associations;
        }
Example #5
0
        public IEnumerable <ApplicationRelationshipDefinition> CollectionRelationships()
        {
            IEnumerable <ApplicationRelationshipDefinition> applicationAssociations = Associations.Where(a => a.Collection);
            IEnumerable <ApplicationRelationshipDefinition> applicationCompositions = Compositions.Where(a => a.Collection);

            return(applicationAssociations.Union(applicationCompositions));
        }
Example #6
0
        public Associations AddAssociations(Associations dictionary1, Associations dictionary2)
        {
            var result = AddDictionaries(dictionary1, dictionary2);

            return(new Associations(result));
        }
Example #7
0
        void Init(MappingSchema mappingSchema)
        {
            var ta = mappingSchema.GetAttribute <TableAttribute>(TypeAccessor.Type, a => a.Configuration);

            if (ta != null)
            {
                TableName    = ta.Name;
                SchemaName   = ta.Schema;
                DatabaseName = ta.Database;
                IsColumnAttributeRequired = ta.IsColumnAttributeRequired;
            }

            if (TableName == null)
            {
                TableName = TypeAccessor.Type.Name;

                if (TypeAccessor.Type.IsInterfaceEx() && TableName.Length > 1 && TableName[0] == 'I')
                {
                    TableName = TableName.Substring(1);
                }
            }

            var attrs = new List <ColumnAttribute>();

            foreach (var member in TypeAccessor.Members)
            {
                var aa = mappingSchema.GetAttribute <AssociationAttribute>(TypeAccessor.Type, member.MemberInfo, attr => attr.Configuration);

                if (aa != null)
                {
                    Associations.Add(new AssociationDescriptor(
                                         TypeAccessor.Type, member.MemberInfo, aa.GetThisKeys(), aa.GetOtherKeys(), aa.ExpressionPredicate, aa.Storage, aa.CanBeNull));
                    continue;
                }

                var ca = mappingSchema.GetAttribute <ColumnAttribute>(TypeAccessor.Type, member.MemberInfo, attr => attr.Configuration);

                if (ca != null)
                {
                    if (ca.IsColumn)
                    {
                        if (ca.MemberName != null)
                        {
                            attrs.Add(new ColumnAttribute(member.Name, ca));
                        }
                        else
                        {
                            var cd = new ColumnDescriptor(mappingSchema, ca, member);
                            Columns.Add(cd);
                            _columnNames.Add(member.Name, cd);
                        }
                    }
                }
                else if (
                    !IsColumnAttributeRequired && mappingSchema.IsScalarType(member.Type) ||
                    mappingSchema.GetAttribute <IdentityAttribute>(TypeAccessor.Type, member.MemberInfo, attr => attr.Configuration) != null ||
                    mappingSchema.GetAttribute <PrimaryKeyAttribute>(TypeAccessor.Type, member.MemberInfo, attr => attr.Configuration) != null)
                {
                    var cd = new ColumnDescriptor(mappingSchema, new ColumnAttribute(), member);
                    Columns.Add(cd);
                    _columnNames.Add(member.Name, cd);
                }
                else
                {
                    var caa = mappingSchema.GetAttribute <ColumnAliasAttribute>(TypeAccessor.Type, member.MemberInfo, attr => attr.Configuration);

                    if (caa != null)
                    {
                        if (Aliases == null)
                        {
                            Aliases = new Dictionary <string, string>();
                        }

                        Aliases.Add(member.Name, caa.MemberName);
                    }
                }
            }

            var typeColumnAttrs = mappingSchema.GetAttributes <ColumnAttribute>(TypeAccessor.Type, a => a.Configuration);

            foreach (var attr in typeColumnAttrs.Concat(attrs))
            {
                if (attr.IsColumn)
                {
                    SetColumn(attr, mappingSchema);
                }
            }
        }
Example #8
0
        public virtual async Task <ActionResult> QueryEntity <T>(string query, string fields, string orderBy, int start, int size)
            where T : class
        {
            string includeList = Request.QueryString["include"] ?? "";

            if (!string.IsNullOrWhiteSpace(includeList))
            {
                IQueryable <T> q    = db.Query <T>().WhereJsonQuery(query, db);
                Type           type = typeof(T);

                var propList = includeList.Split(',').Where(x => !string.IsNullOrWhiteSpace(x)).ToArray();

                foreach (string inc in propList)
                {
                    q = q.Include(inc);
                }

                List <T> entites = await q.ToListAsync();

                Associations relEntities = new Associations();

                var f = relatedExpressions.GetOrAdd(type.FullName + ":" + includeList, key => CreateRelatedLoadExpression(type, propList));

                int i = 0;
                foreach (T entity in entites)
                {
                    f(relEntities, i++, entity);
                }

                var model = new
                {
                    items        = entites,
                    total        = entites.Count,
                    associations = relEntities
                };

                return(JsonResult(model));
            }

            long total = 0;

            var aq = db.Query <T>();

            if (!string.IsNullOrWhiteSpace(query))
            {
                aq = aq.WhereJsonQuery(query, db);
            }
            if (size != -1)
            {
                if (string.IsNullOrWhiteSpace(orderBy))
                {
                    return(JsonError("orderBy missing"));
                }
                aq    = aq.OrderBy(orderBy);
                total = await aq.CountAsync();

                aq = aq.Skip(start).Take(size);
            }
            else
            {
                if (!string.IsNullOrWhiteSpace(orderBy))
                {
                    aq = aq.OrderBy(orderBy);
                }
            }

            IQueryable rq = aq;

            if (!string.IsNullOrWhiteSpace(fields))
            {
                var d = PrepareFields <T>(fields);
                rq = aq.SelectDynamic(d);
            }

            try
            {
                object result = await rq.ToListAsync();

                if (size != -1)
                {
                    result = new
                    {
                        items = result,
                        total = total,
                        merge = true
                    };
                }
                return(JsonResult(result));
            }
            catch (Exception ex) {
                throw new InvalidOperationException(rq.ToString(), ex);
            }
        }
		//======================================================================
		//
		// Do the metadata creation. The metadata will be randomly initialized
		// based on the channel type and the structure specified. For recognized
		// components the number of metadata elements will correspond to the count
		// of components in the selected mesh, otherwise a random number of metadata
		// elements between 1 and 100 will be created (at consecutive indices).
		//
		// The previously existing metadata is preserved for later undo.
		//
		override public void doIt(MArgList args)
		{
			MArgDatabase argsDb = new MArgDatabase(syntax, args);

			checkArgs(ref argsDb);
			
			clearResult();

            MColorArray myColorArray = new MColorArray();
			MFnDependencyNode node = new MFnDependencyNode(fObj);

			// Get the current metadata (empty if none yet)
			Associations newMetadata = new Associations(node.metadata);
			Channel newChannel = newMetadata.channel( "vertex" );

			// Check to see if the requested stream name already exists
			Stream oldStream = newChannel.dataStream(fStreamName);
			if (oldStream != null)
			{

				string fmt = MStringResource.getString(MetaDataRegisterMStringResources.kCreateMetadataHasStream);
				string msg = String.Format(fmt, fStreamName);
				MGlobal.displayError( msg );
				return;
			}

            StreamForType<MyStructureClass> newStream = new StreamForType<MyStructureClass>(fStreamName);

            int indexCount = fMesh.numVertices;

            Random rndIndexCount = new Random();

			// Fill specified stream ranges with random data
			int m;
            Random rnd = new Random();
            for (m = 0; m < indexCount; ++m)
			{
				// Walk each structure member and fill with random data
				// tailored to the member data type.

                MyStructureClass myClass = new MyStructureClass();

                // int
                myClass.a = rnd.Next(Int32.MinValue, Int32.MaxValue);
                // float
                myClass.b = (float)rnd.NextDouble();
                // string
                string[] randomStrings = new string[] { "banana", "tomatoe", "apple", "pineapple", "apricot", "pepper", "olive", "grapefruit" };
                int index = rnd.Next( randomStrings.Length );
    			myClass.c = randomStrings[index];
                // bool
				int randomInt = rnd.Next(0, 2);
                myClass.d = randomInt == 1 ? true : false;

                myClass.e = rnd.Next(Int32.MinValue, Int32.MaxValue);

                myClass.f = rnd.Next(Int32.MinValue, Int32.MaxValue);

                myClass.xyz[0] = (float)rnd.NextDouble();
                myClass.xyz[1] = (float)rnd.NextDouble();
                myClass.xyz[2] = (float)rnd.NextDouble();

				newStream[m] = myClass;						
			}

			newChannel.setDataStream(newStream);
			newMetadata.setChannel(newChannel);

            // Note: the following will not work if "obj" is a shape constructed by a source object
            // You need to delete the history of the shape before calling this...
            fDGModifier.setMetadata(fObj, newMetadata);
            fDGModifier.doIt();

            Associations meshMetadata = fMesh.metadata;

            // This code is for debugging only
            {
                Channel chn = meshMetadata["vertex"];

                Console.WriteLine("Channel : type = {0}, nbStreams = {1}", chn.nameProperty, chn.dataStreamCount);

                Stream chnStream = chn[fStreamName];

                Structure strct = chnStream.structure;

                var strm = new StreamForType<MyStructureClass>(chnStream);

                Console.WriteLine("Stream : name = {0}, nbElements = {1}", chnStream.name, chnStream.Count );

                var tomatoes = strm.Where( ( KeyValuePair<Index,MyStructureClass> keyvalue ) => keyvalue.Value.c == "tomatoe");

                foreach (var keyvalue in tomatoes)
//                        foreach (MyStructureClass myClass in strm.Values )
                {
                    Console.WriteLine("Vertex #{0}, a = {1}", keyvalue.Key.asString, keyvalue.Value.a.ToString());
                    Console.WriteLine("Vertex #{0}, b = {1}", keyvalue.Key.asString, keyvalue.Value.b.ToString());
                    Console.WriteLine("Vertex #{0}, c = {1}", keyvalue.Key.asString, keyvalue.Value.c.ToString());
                    Console.WriteLine("Vertex #{0}, d = {1}", keyvalue.Key.asString, keyvalue.Value.d.ToString());
                    Console.WriteLine("Vertex #{0}, e = {1}", keyvalue.Key.asString, keyvalue.Value.e.ToString());
                    Console.WriteLine("Vertex #{0}, f = {1}", keyvalue.Key.asString, keyvalue.Value.f.ToString());
                    Console.WriteLine("Vertex #{0}, xyz = {1},{2},{3}", keyvalue.Key.asString, keyvalue.Value.xyz[0].ToString(), keyvalue.Value.xyz[1].ToString(), keyvalue.Value.xyz[2].ToString());
                    Console.WriteLine("Vertex #{0}, abc = {1},{2}", keyvalue.Key.asString, keyvalue.Value.abc[0], keyvalue.Value.abc[1] );
                }
            }
		}
        // Module defining this command


        // Optional custom code for this activity


        /// <summary>
        /// Returns a configured instance of System.Management.Automation.PowerShell, pre-populated with the command to run.
        /// </summary>
        /// <param name="context">The NativeActivityContext for the currently running activity.</param>
        /// <returns>A populated instance of Sytem.Management.Automation.PowerShell</returns>
        /// <remarks>The infrastructure takes responsibility for closing and disposing the PowerShell instance returned.</remarks>
        protected override ActivityImplementationContext GetPowerShell(NativeActivityContext context)
        {
            System.Management.Automation.PowerShell invoker       = global::System.Management.Automation.PowerShell.Create();
            System.Management.Automation.PowerShell targetCommand = invoker.AddCommand(PSCommandName);

            // Initialize the arguments

            if (ApplicationName.Expression != null)
            {
                targetCommand.AddParameter("ApplicationName", ApplicationName.Get(context));
            }

            if (BasePropertiesOnly.Expression != null)
            {
                targetCommand.AddParameter("BasePropertiesOnly", BasePropertiesOnly.Get(context));
            }

            if ((ComputerName.Expression != null) && (PSRemotingBehavior.Get(context) != RemotingBehavior.Custom))
            {
                targetCommand.AddParameter("ComputerName", ComputerName.Get(context));
            }

            if (ConnectionURI.Expression != null)
            {
                targetCommand.AddParameter("ConnectionURI", ConnectionURI.Get(context));
            }

            if (Dialect.Expression != null)
            {
                targetCommand.AddParameter("Dialect", Dialect.Get(context));
            }

            if (Enumerate.Expression != null)
            {
                targetCommand.AddParameter("Enumerate", Enumerate.Get(context));
            }

            if (Filter.Expression != null)
            {
                targetCommand.AddParameter("Filter", Filter.Get(context));
            }

            if (Fragment.Expression != null)
            {
                targetCommand.AddParameter("Fragment", Fragment.Get(context));
            }

            if (OptionSet.Expression != null)
            {
                targetCommand.AddParameter("OptionSet", OptionSet.Get(context));
            }

            if (Port.Expression != null)
            {
                targetCommand.AddParameter("Port", Port.Get(context));
            }

            if (Associations.Expression != null)
            {
                targetCommand.AddParameter("Associations", Associations.Get(context));
            }

            if (ResourceURI.Expression != null)
            {
                targetCommand.AddParameter("ResourceURI", ResourceURI.Get(context));
            }

            if (ReturnType.Expression != null)
            {
                targetCommand.AddParameter("ReturnType", ReturnType.Get(context));
            }

            if (SelectorSet.Expression != null)
            {
                targetCommand.AddParameter("SelectorSet", SelectorSet.Get(context));
            }

            if (SessionOption.Expression != null)
            {
                targetCommand.AddParameter("SessionOption", SessionOption.Get(context));
            }

            if (Shallow.Expression != null)
            {
                targetCommand.AddParameter("Shallow", Shallow.Get(context));
            }

            if (UseSSL.Expression != null)
            {
                targetCommand.AddParameter("UseSSL", UseSSL.Get(context));
            }

            if (Credential.Expression != null)
            {
                targetCommand.AddParameter("Credential", Credential.Get(context));
            }

            if (Authentication.Expression != null)
            {
                targetCommand.AddParameter("Authentication", Authentication.Get(context));
            }

            if (CertificateThumbprint.Expression != null)
            {
                targetCommand.AddParameter("CertificateThumbprint", CertificateThumbprint.Get(context));
            }

            if (GetIsComputerNameSpecified(context) && (PSRemotingBehavior.Get(context) == RemotingBehavior.Custom))
            {
                targetCommand.AddParameter("ComputerName", PSComputerName.Get(context));
            }

            return(new ActivityImplementationContext()
            {
                PowerShellInstance = invoker
            });
        }
Example #11
0
 public void SetUp()
 {
     assocs = new Associations();
 }
Example #12
0
        public dataModel.Item[] GetItemByIds(string[] itemIds, coreModel.ItemResponseGroup respGroup = coreModel.ItemResponseGroup.ItemLarge)
        {
            if (itemIds == null)
            {
                throw new ArgumentNullException("itemIds");
            }

            if (!itemIds.Any())
            {
                return(new dataModel.Item[] { });
            }

            // Use breaking query EF performance concept https://msdn.microsoft.com/en-us/data/hh949853.aspx#8
            var retVal         = Items.Include(x => x.Images).Where(x => itemIds.Contains(x.Id)).ToArray();
            var propertyValues = PropertyValues.Where(x => itemIds.Contains(x.ItemId)).ToArray();

            // Load product catalogs separately
            var catalogIds = retVal.Select(x => x.CatalogId).Distinct().ToArray();
            var catalogs   = Catalogs.Include(x => x.CatalogLanguages).Where(x => catalogIds.Contains(x.Id)).ToArray();

            // Load product categories separately
            var categoryIds            = retVal.Select(x => x.CategoryId).Where(x => !string.IsNullOrEmpty(x)).Distinct().ToArray();
            var categoriesReponseGroup = coreModel.CategoryResponseGroup.WithParents;

            if (respGroup.HasFlag(coreModel.ItemResponseGroup.Outlines))
            {
                categoriesReponseGroup |= coreModel.CategoryResponseGroup.WithLinks | coreModel.CategoryResponseGroup.WithParents;
                respGroup |= coreModel.ItemResponseGroup.Links;
            }

            if (respGroup.HasFlag(coreModel.ItemResponseGroup.ItemProperties))
            {
                // Load categories with all properties for property inheritance
                categoriesReponseGroup |= coreModel.CategoryResponseGroup.WithProperties;
            }

            var categories = GetCategoriesByIds(categoryIds, categoriesReponseGroup);

            if (respGroup.HasFlag(coreModel.ItemResponseGroup.Links))
            {
                var relations             = CategoryItemRelations.Where(x => itemIds.Contains(x.ItemId)).ToArray();
                var allForeignCatalogsIds = relations.Where(x => x.CategoryId == null && x.CatalogId != null)
                                            .Select(x => x.CatalogId).Distinct().ToArray();
                var allForeginCategoriesIds = relations.Where(x => x.CategoryId != null)
                                              .Select(x => x.CategoryId).Distinct().ToArray();
                if (!allForeginCategoriesIds.IsNullOrEmpty())
                {
                    var linkedCategories = GetCategoriesByIds(allForeginCategoriesIds.ToArray(), coreModel.CategoryResponseGroup.WithLinks | coreModel.CategoryResponseGroup.WithParents);
                }
                if (!allForeignCatalogsIds.IsNullOrEmpty())
                {
                    var linkedCatalogs = Catalogs.Include(x => x.CatalogLanguages).Where(x => allForeignCatalogsIds.Contains(x.Id)).ToArray();
                }
            }

            // Load all properties meta information and data for inheritance from parent categories and catalog
            if (respGroup.HasFlag(coreModel.ItemResponseGroup.ItemProperties))
            {
                // Load catalogs with properties for products not belongs to any category (EF auto populated all Catalog nav properties for all objects)
                foreach (var catalogId in retVal.Where(x => x.CategoryId == null).Select(x => x.CatalogId))
                {
                    var catalog = GetCatalogById(catalogId);
                }
            }

            if (respGroup.HasFlag(coreModel.ItemResponseGroup.ItemAssets))
            {
                var assets = Assets.Where(x => itemIds.Contains(x.ItemId)).ToArray();
            }

            if (respGroup.HasFlag(coreModel.ItemResponseGroup.ItemEditorialReviews))
            {
                var editorialReviews = EditorialReviews.Where(x => itemIds.Contains(x.ItemId)).ToArray();
            }

            if (respGroup.HasFlag(coreModel.ItemResponseGroup.Variations))
            {
                var variationIds = Items.Where(x => itemIds.Contains(x.ParentId)).Select(x => x.Id).ToArray();
                // For variations load only info and images
                var variations = Items.Include(x => x.Images).Include(x => x.Assets).Where(x => variationIds.Contains(x.Id)).ToArray();
                // Load variations property values separately
                var variationPropertyValues = PropertyValues.Where(x => variationIds.Contains(x.ItemId)).ToArray();
            }

            if (respGroup.HasFlag(coreModel.ItemResponseGroup.ItemAssociations))
            {
                var assosiations            = Associations.Where(x => itemIds.Contains(x.ItemId)).ToArray();
                var assosiatedCategoriesIds = assosiations.Where(x => x.AssociatedCategoryId != null)
                                              .Select(x => x.AssociatedCategoryId).Distinct().ToArray();
                var assosiatedProductIds = assosiations.Where(x => x.AssociatedItemId != null)
                                           .Select(x => x.AssociatedItemId).Distinct().ToArray();

                var assosiatedCategories = GetCategoriesByIds(assosiatedCategoriesIds, coreModel.CategoryResponseGroup.Info | coreModel.CategoryResponseGroup.WithImages);
                var assosiatedItems      = GetItemByIds(assosiatedProductIds, coreModel.ItemResponseGroup.ItemInfo | coreModel.ItemResponseGroup.ItemAssets);
            }

            // Load parents
            var parentIds = retVal.Where(x => x.Parent == null && x.ParentId != null).Select(x => x.ParentId).ToArray();
            var parents   = GetItemByIds(parentIds, respGroup);

            return(retVal);
        }
Example #13
0
 public IActionResult AddCategoryToProduct(Associations newAssociation)
 {
     dbContext.Associations.Add(newAssociation);
     dbContext.SaveChanges();
     return(RedirectToAction("Product", new{ Id = newAssociation.ProductId }));
 }
Example #14
0
 public IActionResult AddProductToCategory(Associations newAssociation)
 {
     dbContext.Associations.Add(newAssociation);
     dbContext.SaveChanges();
     return(RedirectToAction("Category", new{ Id = newAssociation.CategoryId }));
 }
Example #15
0
        public virtual void Patch(ItemEntity target)
        {
            if (target == null)
            {
                throw new ArgumentNullException(nameof(target));
            }

            target.IsBuyable      = IsBuyable;
            target.IsActive       = IsActive;
            target.TrackInventory = TrackInventory;
            target.MinQuantity    = MinQuantity;
            target.MaxQuantity    = MaxQuantity;
            target.EnableReview   = EnableReview;

            target.CatalogId              = CatalogId;
            target.CategoryId             = CategoryId;
            target.Name                   = Name;
            target.Code                   = Code;
            target.ManufacturerPartNumber = ManufacturerPartNumber;
            target.Gtin                   = Gtin;
            target.ProductType            = ProductType;
            target.MaxNumberOfDownload    = MaxNumberOfDownload;
            target.DownloadType           = DownloadType;
            target.HasUserAgreement       = HasUserAgreement;
            target.DownloadExpiration     = DownloadExpiration;
            target.Vendor                 = Vendor;
            target.TaxType                = TaxType;
            target.WeightUnit             = WeightUnit;
            target.Weight                 = Weight;
            target.MeasureUnit            = MeasureUnit;
            target.PackageType            = PackageType;
            target.Height                 = Height;
            target.Length                 = Length;
            target.Width                  = Width;
            target.ShippingType           = ShippingType;
            target.Priority               = Priority;
            target.ParentId               = ParentId;
            target.StartDate              = StartDate;
            target.EndDate                = EndDate;

            #region Assets
            if (!Assets.IsNullCollection())
            {
                Assets.Patch(target.Assets, (sourceAsset, targetAsset) => sourceAsset.Patch(targetAsset));
            }
            #endregion

            #region Images
            if (!Images.IsNullCollection())
            {
                Images.Patch(target.Images, (sourceImage, targetImage) => sourceImage.Patch(targetImage));
            }
            #endregion

            #region ItemPropertyValues
            if (!ItemPropertyValues.IsNullCollection())
            {
                ItemPropertyValues.Patch(target.ItemPropertyValues, (sourcePropValue, targetPropValue) => sourcePropValue.Patch(targetPropValue));
            }
            #endregion

            #region Links
            if (!CategoryLinks.IsNullCollection())
            {
                CategoryLinks.Patch(target.CategoryLinks, new CategoryItemRelationComparer(),
                                    (sourcePropValue, targetPropValue) => sourcePropValue.Patch(targetPropValue));
            }
            #endregion

            #region EditorialReviews
            if (!EditorialReviews.IsNullCollection())
            {
                EditorialReviews.Patch(target.EditorialReviews, (sourcePropValue, targetPropValue) => sourcePropValue.Patch(targetPropValue));
            }
            #endregion

            #region Association
            if (!Associations.IsNullCollection())
            {
                var associationComparer = AnonymousComparer.Create((AssociationEntity x) => x.AssociationType + ":" + x.AssociatedItemId + ":" + x.AssociatedCategoryId);
                Associations.Patch(target.Associations, associationComparer,
                                   (sourceAssociation, targetAssociation) => sourceAssociation.Patch(targetAssociation));
            }
            #endregion
        }
 public void AddAssociation(XElement association, string associationKey)
 {
     Associations.Add(association);
     _addedAssociations.Add(associationKey);
 }
        public override GEDCOMTag AddTag(string tagName, string tagValue, TagConstructor tagConstructor)
        {
            GEDCOMTag result;

            if (tagName == "NAME")
            {
                result = AddPersonalName(new GEDCOMPersonalName(Owner, this, tagName, tagValue));
            }
            else if (tagName == "SUBM")
            {
                result = Submittors.Add(new GEDCOMPointer(Owner, this, tagName, tagValue));
            }
            else if (tagName == "ANCI")
            {
                result = AncestorsInterest.Add(new GEDCOMPointer(Owner, this, tagName, tagValue));
            }
            else if (tagName == "DESI")
            {
                result = DescendantsInterest.Add(new GEDCOMPointer(Owner, this, tagName, tagValue));
            }
            else if (tagName == "_GROUP")
            {
                result = fGroups.Add(new GEDCOMPointer(Owner, this, tagName, tagValue));
            }
            else
            {
                result = fTagsFactory.CreateTag(Owner, this, tagName, tagValue);

                if (result != null)
                {
                    if (result is GEDCOMChildToFamilyLink)
                    {
                        result = ChildToFamilyLinks.Add(result as GEDCOMChildToFamilyLink);
                    }
                    else if (result is GEDCOMSpouseToFamilyLink)
                    {
                        result = SpouseToFamilyLinks.Add(result as GEDCOMSpouseToFamilyLink);
                    }
                    else if (result is GEDCOMIndividualOrdinance)
                    {
                        result = IndividualOrdinances.Add(result as GEDCOMIndividualOrdinance);
                    }
                    else if (result is GEDCOMAssociation)
                    {
                        result = Associations.Add(result as GEDCOMAssociation);
                    }
                    else if (result is GEDCOMIndividualEvent)
                    {
                        result = AddEvent(result as GEDCOMCustomEvent);
                    }
                    else if (result is GEDCOMIndividualAttribute)
                    {
                        result = AddEvent(result as GEDCOMCustomEvent);
                    }
                    else if (result is GEDCOMAlias)
                    {
                        result = Aliases.Add(result as GEDCOMAlias);
                    }
                }
                else
                {
                    result = base.AddTag(tagName, tagValue, tagConstructor);
                }
            }

            return(result);
        }
Example #18
0
        private void ReflectOutMethods()
        {
            //do methods
            foreach (MethodInfo mi in TypeInAssembly.GetMethods(RequiredBindings))
            {
                if (TypeInAssembly == mi.DeclaringType)
                {
                    string mDetail = mi.Name + "( ";
                    string pDetail = "";
                    //do we want to display method arguments, if we do create the
                    //appopraiate string
                    if (ShowMethodArguments)
                    {
                        ParameterInfo[] pif = mi.GetParameters();
                        foreach (ParameterInfo p in pif)
                        {
                            //add all the parameter types to the associations List, so that
                            //the association lines for this class can be obtained, and
                            //possibly drawn on the container
                            string pName = GetGenericsForType(p.ParameterType);
                            pName = LowerAndTrim(pName);

                            if (IncludeMethodArgumentAsAssociations)
                            {
                                string association = p.ParameterType.IsGenericType ? p.ParameterType.GetGenericTypeDefinition().FullName : p.ParameterType.FullName;
                                if (!Associations.Contains(association))
                                {
                                    Associations.Add(association);
                                }
                            }

                            pDetail  = pName + " " + p.Name + ", ";
                            mDetail += pDetail;
                        }
                        if (mDetail.LastIndexOf(",") > 0)
                        {
                            mDetail = mDetail.Substring(0, mDetail.LastIndexOf(","));
                        }
                    }
                    mDetail += " )";
                    //add the return type to the associations List, so that
                    //the association lines for this class can be obtained, and
                    //possibly drawn on the container
                    string rName = GetGenericsForType(mi.ReturnType);
                    //dont want to include void as an association type
                    if (!string.IsNullOrEmpty(rName))
                    {
                        rName = GetGenericsForType(mi.ReturnType);
                        rName = LowerAndTrim(rName);
                        string association = mi.ReturnType.IsGenericType ? mi.ReturnType.GetGenericTypeDefinition().FullName : mi.ReturnType.FullName;
                        if (!Associations.Contains(association))
                        {
                            Associations.Add(association);
                        }
                        //do we want to display method return types
                        if (ShowMethodReturnValues)
                        {
                            mDetail += " : " + rName;
                        }
                    }
                    else
                    {
                        //do we want to display method return types
                        if (ShowMethodReturnValues)
                        {
                            mDetail += " : void";
                        }
                    }

                    //work out whether this is a normal method, in which case add it
                    //or if its a property get/set method, should it be added
                    if (!ShowGetMethodForProperty && propGetters.Contains(mi))
                    {
                        /* hidden get method */
                    }
                    else if (!ShowSetMethodForProperty && propSetters.Contains(mi))
                    {
                        /* hidden set method */
                    }
                    else
                    {
                        if (ParseMethodBodyIL)
                        {
                            Methods.Add(new SerializableMethodData(mDetail, ReadMethodBodyAndAddAssociations(mi)));
                        }
                        else
                        {
                            Methods.Add(new SerializableMethodData(mDetail, ""));
                        }
                    }
                }
            }
            HasMethods = Methods.Any();
        }
Example #19
0
        public Associations ScaleAssociations(Associations dict, double factor)
        {
            var list = dict.Select(k => new KeyValuePair <string, double>(k.Key, k.Value * factor));

            return(new Associations(list.ToDictionary(x => x.Key, x => x.Value)));
        }
		public override void SetUp() {
			this.sha1Secret = new byte[sha1.HashSize / 8];
			this.assocs = new Associations();
		}
Example #21
0
		public void SetUp() {
			assocs = new Associations();
		}
Example #22
0
 public void ConnectWith(IEnumerable <NodeNFA> nodes, string symbol)
 {
     Associations.Add(symbol, nodes);
 }
Example #23
0
		//======================================================================
		//
		// Do the metadata creation. The metadata will be randomly initialized
		// based on the channel type and the structure specified. For recognized
		// components the number of metadata elements will correspond to the count
		// of components in the selected mesh, otherwise a random number of metadata
		// elements between 1 and 100 will be created (at consecutive indices).
		//
		// The previously existing metadata is preserved for later undo.
		//
		override public void doIt(MArgList args)
		{
			MArgDatabase argsDb = new MArgDatabase(syntax, args);

			checkArgs(ref argsDb);

			clearResult();

			uint numNodes = fNodes.length;
			int i;
			for (i = 0; i < numNodes; ++i)
			{
                // fNodes[i] is the transform not the shape itself
                MFnDagNode dagNode = new MFnDagNode(fNodes[i]);
                MObject obj = dagNode.child(0);
                // obj is the shape, which is where we can add the meta data
				MFnDependencyNode node = new MFnDependencyNode(obj);
				// Get the current metadata (empty if none yet)
				Associations newMetadata = new Associations(node.metadata);
				Channel newChannel = newMetadata.channel(fChannelType);

				// Check to see if the requested stream name already exists
				Stream oldStream = newChannel.dataStream(fStreamName);
				if (oldStream != null)
				{

					string fmt = MStringResource.getString(MetaDataRegisterMStringResources.kCreateMetadataHasStream);
					string msg = String.Format(fmt, fStreamName);
					MGlobal.displayError( msg );
					continue;
				}

				Stream newStream = new Stream(fStructure, fStreamName);

                string strmName = newStream.name;

				int indexCount = 0;
                MFnMesh mesh = null;
                Random rndIndexCount = new Random();
                // Treat the channel type initializations different for meshes
				if (obj.hasFn(MFn.Type.kMesh))
				{
                    mesh = new MFnMesh(obj);
					// Get mesh-specific channel type parameters
					if (fChannelType == "face")
					{
						indexCount = mesh.numPolygons;
					}
					else if (fChannelType == "edge")
					{
						indexCount = mesh.numEdges;
					}
					else if (fChannelType == "vertex")
					{
						indexCount = mesh.numVertices;
					}
					else if (fChannelType == "vertexFace")
					{
						indexCount = mesh.numFaceVertices;
					}
					else
					{
						// Set a random number between 1 to 100
                        indexCount = rndIndexCount.Next(1, 100);
					}
				}
				else
				{
					// Create generic channel type information
                    indexCount = rndIndexCount.Next(1, 100);
				}

				// Fill specified stream ranges with random data
				int structureMemberCount = fStructure.memberCount;
				uint m,n,d;
                Random rnd = new Random();
                for (m = 0; m < indexCount; ++m)
				{
					// Walk each structure member and fill with random data
					// tailored to the member data type.
					Handle handle = new Handle(fStructure);
					for (n = 0; n < structureMemberCount; ++n)
					{
						handle.setPositionByMemberIndex(n);

						switch (handle.dataType)
						{
						case Member.eDataType.kBoolean:
							{
                                bool[] data = new bool[handle.dataLength];
						        for (d = 0; d < handle.dataLength; ++d)
						        {
									int randomInt = rnd.Next(0, 2);
									bool randomBool = randomInt == 1 ? true : false;
                                    data[d] = randomBool;
                                }
                                handle.asBooleanArray = data;
								break;
							}
						case Member.eDataType.kDouble:
							{
                                double[] data = new double[handle.dataLength];
						        for (d = 0; d < handle.dataLength; ++d)
						        {
									// Set a random number between -2000000000.0.0 and 2000000000.0.0
									data[d] = rnd.NextDouble()*4000000000.0 - 2000000000.0 ;
                                }
                                handle.asDoubleArray = data;
								break;
							}
						case Member.eDataType.kDoubleMatrix4x4:
							{
                                double[] data = new double[handle.dataLength * 16];
						        for (d = 0; d < handle.dataLength; ++d)
						        {
									data[d*16+0] = rnd.NextDouble()*4000000000.0 - 2000000000.0 ;
									data[d*16+1] = rnd.NextDouble()*4000000000.0 - 2000000000.0 ;
									data[d*16+2] = rnd.NextDouble()*4000000000.0 - 2000000000.0 ;
									data[d*16+3] = rnd.NextDouble()*4000000000.0 - 2000000000.0 ;
									data[d*16+4] = rnd.NextDouble()*4000000000.0 - 2000000000.0 ;
									data[d*16+5] = rnd.NextDouble()*4000000000.0 - 2000000000.0 ;
									data[d*16+6] = rnd.NextDouble()*4000000000.0 - 2000000000.0 ;
									data[d*16+7] = rnd.NextDouble()*4000000000.0 - 2000000000.0 ;
									data[d*16+8] = rnd.NextDouble()*4000000000.0 - 2000000000.0 ;
									data[d*16+9] = rnd.NextDouble()*4000000000.0 - 2000000000.0 ;
									data[d*16+10] = rnd.NextDouble()*4000000000.0 - 2000000000.0 ;
									data[d*16+11] = rnd.NextDouble()*4000000000.0 - 2000000000.0 ;
									data[d*16+12] = rnd.NextDouble()*4000000000.0 - 2000000000.0 ;
									data[d*16+13] = rnd.NextDouble()*4000000000.0 - 2000000000.0 ;
									data[d*16+14] = rnd.NextDouble()*4000000000.0 - 2000000000.0 ;
									data[d*16+15] = rnd.NextDouble()*4000000000.0 - 2000000000.0 ;
                                }
                                handle.asDoubleMatrix4x4 = data;
								break;
							}
						case Member.eDataType.kFloat:
							{
                                float[] data = new float[handle.dataLength];
						        for (d = 0; d < handle.dataLength; ++d)
						        {
    								// Set a random number between -2000000.0 and 2000000.0
	    							data[d] = (float)rnd.NextDouble()*4000000.0f - 2000000.0f ;
                                }
                                handle.asFloatArray = data;
								break;
							}
						case Member.eDataType.kFloatMatrix4x4:
							{
                                float[] data = new float[handle.dataLength * 16];
						        for (d = 0; d < handle.dataLength; ++d)
						        {
									// Set a random number between -2000000.0 and 2000000.0
									data[d*16+0] = (float)rnd.NextDouble()*4000000.0f - 2000000.0f ;
									data[d*16+1] = (float)rnd.NextDouble()*4000000.0f - 2000000.0f ;
									data[d*16+2] = (float)rnd.NextDouble()*4000000.0f - 2000000.0f ;
									data[d*16+3] = (float)rnd.NextDouble()*4000000.0f - 2000000.0f ;
									data[d*16+4] = (float)rnd.NextDouble()*4000000.0f - 2000000.0f ;
									data[d*16+5] = (float)rnd.NextDouble()*4000000.0f - 2000000.0f ;
									data[d*16+6] = (float)rnd.NextDouble()*4000000.0f - 2000000.0f ;
									data[d*16+7] = (float)rnd.NextDouble()*4000000.0f - 2000000.0f ;
									data[d*16+8] = (float)rnd.NextDouble()*4000000.0f - 2000000.0f ;
									data[d*16+9] = (float)rnd.NextDouble()*4000000.0f - 2000000.0f ;
									data[d*16+10] = (float)rnd.NextDouble()*4000000.0f - 2000000.0f ;
									data[d*16+11] = (float)rnd.NextDouble()*4000000.0f - 2000000.0f ;
									data[d*16+12] = (float)rnd.NextDouble()*4000000.0f - 2000000.0f ;
									data[d*16+13] = (float)rnd.NextDouble()*4000000.0f - 2000000.0f ;
									data[d*16+14] = (float)rnd.NextDouble()*4000000.0f - 2000000.0f ;
									data[d*16+15] = (float)rnd.NextDouble()*4000000.0f - 2000000.0f ;
                                }
                                handle.asFloatMatrix4x4 = data;
								break;
							}
						case Member.eDataType.kInt8:
							{
                                sbyte[] data = new sbyte[handle.dataLength];
						        for (d = 0; d < handle.dataLength; ++d)
						        {
                                    data[d] = (sbyte)rnd.Next(SByte.MinValue, SByte.MaxValue+1);
                                }
                                handle.asInt8Array = data;
								break;
							}
						case Member.eDataType.kInt16:
							{
								short[] data = new short[handle.dataLength];
						        for (d = 0; d < handle.dataLength; ++d)
						        {
                                    data[d] = (short)rnd.Next(Int16.MinValue, Int16.MaxValue+1);
                                }
                                handle.asInt16Array = data;
								break;
							}
						case Member.eDataType.kInt32:
							{
								int[] data = new int[handle.dataLength];
						        for (d = 0; d < handle.dataLength; ++d)
						        {
                                    // rnd.Next returns a number between [arg1,arg2[
                                    // but unfortunately I can't pass Int32.MaxValue+1 here....
                                    data[d] = rnd.Next(Int32.MinValue, Int32.MaxValue);
                                }
                                handle.asInt32Array = data;
								break;
							}
						case Member.eDataType.kInt64:
							{
								long[] data = new long[handle.dataLength];
						        for (d = 0; d < handle.dataLength; ++d)
						        {
                                    // rnd.Next() gives a number between [0,Int32
                                    data[d] = (long)rnd.Next(Int32.MinValue, Int32.MaxValue);
                                    if( data[d] >= 0 )
                                        data[d] *= Int64.MaxValue / Int32.MaxValue;
                                    else
                                        data[d] *= Int64.MinValue / Int32.MinValue;
                                }
                                handle.asInt64Array = data;
								break;
							}
						case Member.eDataType.kUInt8:
							{
								byte[] data = new byte[handle.dataLength];
						        for (d = 0; d < handle.dataLength; ++d)
						        {
                                    data[d] = (byte)rnd.Next(0, Byte.MaxValue + 1);
                                }
                                handle.asUInt8Array = data;
								break;
							}
						case Member.eDataType.kUInt16:
							{
								ushort[] data = new ushort[handle.dataLength];
						        for (d = 0; d < handle.dataLength; ++d)
						        {
                                    data[d] = (ushort)rnd.Next(0, UInt16.MaxValue + 1);
                                }
                                handle.asUInt16Array = data;
								break;
							}
						case Member.eDataType.kUInt32:
							{
								uint[] data = new uint[handle.dataLength];
						        for (d = 0; d < handle.dataLength; ++d)
						        {
                                    data[d] = (uint)rnd.Next();
                                }
                                handle.asUInt32Array = data;
								break;
							}
						case Member.eDataType.kUInt64:
							{
								ulong[] data = new ulong[handle.dataLength];
						        for (d = 0; d < handle.dataLength; ++d)
						        {
    								data[d] = ((ulong)rnd.Next()) * UInt64.MaxValue / UInt32.MaxValue;
                                }
                                handle.asUInt64Array = data;
								break;
							}
						case Member.eDataType.kString:
							{
                                string[] randomStrings = new string[] { "banana", "tomatoe", "apple", "pineapple", "apricot", "pepper", "olive", "grapefruit" };
                                string[] data = new string[handle.dataLength];
						        for (d = 0; d < handle.dataLength; ++d)
						        {
                                    int index = rnd.Next( randomStrings.Length );
    								data[d] = randomStrings[index];
                                }
                                handle.asStringArray = data;
								break;
							}
						default:
							{
								Debug.Assert(false, "This should never happen");
								break;
							}
						}
					}
					newStream.setElement(new Index(m), handle);
				}
				newChannel.setDataStream(newStream);
				newMetadata.setChannel(newChannel);

                // Note: the following will not work if "obj" is a shape constructed by a source object
                // You need to delete the history of the shape before calling this...
                fDGModifier.setMetadata(obj, newMetadata);
                fDGModifier.doIt();

				// Set the result to the number of actual metadata values set as a
				// triple value:
				//	 	(# nodes, # metadata elements, # members per element)
				//
				MIntArray theResult = new MIntArray();
				theResult.append( (int) fNodes.length );
				theResult.append( (int) indexCount );
				theResult.append( (int) structureMemberCount );
				setResult( theResult );

			}
		}
Example #24
0
        private static void PerformUpdate(Associations associations)
        {
            GetContext().Entry(associations).CurrentValues.SetValues(associations);

            GetContext().SaveChanges();
        }