private Multimap<string, string> MaterializeSelects()
        {
            var selects = new Multimap<string, string>();
            var root = _manifest.ConfigurationNode;
            var xndSelects = root.SelectNodes(@"Selects/Select").Cast<XmlElement>();

            foreach (var xel in xndSelects)
            {
                string id = xel.GetAttribute("id").ToSafe();
                if (id.IsEmpty() || selects.ContainsKey(id))
                {
                    throw new SmartException("A 'Select' element must contain a unique id. Affected: '{0}' - element: {1}", _manifest.FullPath, xel.OuterXml);
                }

                var xndOptions = xel.SelectNodes(@"Option").Cast<XmlElement>();
                if (!xndOptions.Any())
                {
                    throw new SmartException("A 'Select' element must contain at least one 'Option' child element. Affected: '{0}' - element: {1}", _manifest.FullPath, xel.OuterXml);
                }

                foreach (var xelOption in xndOptions)
                {
                    string option = xelOption.InnerText;
                    if (option.IsEmpty())
                    {
                        throw new SmartException("A select option cannot be empty. Affected: '{0}' - element: {1}", _manifest.FullPath, xel.OuterXml);
                    }

                    selects.Add(id, option);
                }

            }

            return selects;
        }
示例#2
0
文件: test.cs 项目: mono/gert
	static void Main ()
	{
		Multimap<Type, string> map = new Multimap<Type, string> ();
		map.Add (typeof (int), "int");
		IEnumerable<string> strings = map [typeof (int)];
		strings.GetEnumerator ();
	}
        /// <summary>
        /// Returns any bindings from the specified collection that match the specified service.
        /// </summary>
        /// <param name="bindings">The multimap of all registered bindings.</param>
        /// <param name="service">The service in question.</param>
        /// <returns>The series of matching bindings.</returns>
        public IEnumerable<IBinding> Resolve(Multimap<Type, IBinding> bindings, Type service)
        {
            if (!service.IsGenericType || !bindings.ContainsKey(service.GetGenericTypeDefinition()))
                return Enumerable.Empty<IBinding>();

            return bindings[service.GetGenericTypeDefinition()].ToEnumerable();
        }
        /// <summary>
        /// Returns any bindings from the specified collection that match the specified request.
        /// </summary>
        /// <param name="bindings">The <see cref="Multimap{T1,T2}"/> of all registered bindings.</param>
        /// <param name="request">The request in question.</param>
        /// <returns>The series of matching bindings.</returns>
        public IEnumerable<IBinding> Resolve(Multimap<Type, IBinding> bindings, IRequest request)
        {
            if (typeof(DbContext).IsAssignableFrom(request.Service))
            {
                return new[]
                {
                    new Binding(request.Service)
                    {
                        ProviderCallback = this.mockProviderCallbackProvider.GetCreationCallback(),
                        ScopeCallback = ctx => StandardScopeCallbacks.Singleton,
                        IsImplicit = true
                    }
                };
            }

            if (request.Service.IsGenericType() && request.Service.GetGenericTypeDefinition() == typeof(DbSet<>))
            {
                var binding = new Binding(request.Service)
                {
                    ProviderCallback = this.mockProviderCallbackProvider.GetCreationCallback(),
                    ScopeCallback = ctx => StandardScopeCallbacks.Singleton,
                    IsImplicit = true
                };

                binding.Parameters.Add(new AdditionalInterfaceParameter(typeof(IQueryable<>).MakeGenericType(request.Service.GetGenericArguments())));
#if !NET40
                binding.Parameters.Add(new AdditionalInterfaceParameter(typeof(IDbAsyncEnumerable<>).MakeGenericType(request.Service.GetGenericArguments())));
#endif
                return new[] { binding };
            }

            return Enumerable.Empty<IBinding>();
        }
示例#5
0
		public IEnumerable<IBinding> Resolve(Multimap<Type, IBinding> bindings, IRequest request)
		{
			var binding = new Binding(request.Service);
			AttachToBinding(binding, request.Service);
			binding.ScopeCallback = StandardScopeCallbacks.Singleton;
			binding.IsImplicit = true;
			return new[] { binding };
		}
示例#6
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Cache"/> class.
        /// </summary>
        /// <param name="pipeline">The pipeline component.</param>
        /// <param name="cachePruner">The cache pruner component.</param>
        public Cache(IPipeline pipeline, ICachePruner cachePruner)
        {
            Ensure.ArgumentNotNull(pipeline, "pipeline");
            Ensure.ArgumentNotNull(cachePruner, "cachePruner");

            _entries = new Multimap<IBinding, CacheEntry>();
            Pipeline = pipeline;
            cachePruner.Start(this);
        }
示例#7
0
        public void TryGetValues_WhenKeyNotExists_ReturnsFalse()
        {
            var testee = new Multimap<int, int>();

            IEnumerable<int> values;
            var result = testee.TryGetValues(1, out values);

            result.Should().BeFalse();
        }
        /// <summary>
        /// Returns any bindings from the specified collection that match the specified request.
        /// </summary>
        /// <param name="bindings">The multimap of all registered bindings.</param>
        /// <param name="request">The request in question.</param>
        /// <returns>The series of matching bindings.</returns>
        public IEnumerable<IBinding> Resolve(Multimap<Type, IBinding> bindings, IRequest request)
        {
            var newBindings = this.selfBindingResolver.Resolve(bindings, request);
            foreach (var binding in newBindings)
            {
                binding.ScopeCallback = StandardScopeCallbacks.Singleton;
            }

            return newBindings;
        }
        /// <summary>
        /// Returns any bindings from the specified collection that match the specified service.
        /// </summary>
        /// <param name="bindings">The multimap of all registered bindings.</param>
        /// <param name="service">The service in question.</param>
        /// <returns>The series of matching bindings.</returns>
        public IEnumerable<IBinding> Resolve(Multimap<Type, IBinding> bindings, Type service)
        {
            if (!service.IsGenericType || !bindings.ContainsKey(service.GetGenericTypeDefinition()))
                yield break;

            Type gtd = service.GetGenericTypeDefinition();

            foreach (IBinding binding in bindings[gtd])
                yield return binding;
        }
 public IEnumerable<IBinding> Resolve(Multimap<Type, IBinding> bindings, IRequest request)
 {
     return new[]
         {
             new Binding(request.Service)
             {
                 ProviderCallback = ProviderCallback
             }
         };
 }
示例#11
0
        public void CanAddMultipleValuesToSameKey()
        {
            var testee = new Multimap<int, int>();

            testee.Add(1, 1);
            testee.Add(1, 2);

            testee[1].Should().Contain(1);
            testee[1].Should().Contain(2);
        }
示例#12
0
 /**
  * copy constructor - single level is copied (children not copied)
  */
 public SoundEvent(SoundEvent ev)
 {
     CreateID();
     _ampl = ev._ampl;
     _children = ev._children.Clone();
     _duration = ev._duration;
     _isActive = ev._isActive;
     _pan = ev._pan;
     _repeats = ev._repeats;
 }
        public static void testMultimap()
        {
            Multimap<string, int> testMap = new Multimap<string, int>();
            testMap.Add("even", 2);
            testMap.Add("even", 4);
            testMap.Add("even", 6);
            testMap.Add("prime", 2);
            testMap.Add("prime", 3);

            Console.WriteLine(testMap.ToString());
            Console.ReadKey();
        }
        /// <summary>
        /// Returns any bindings from the specified collection that match the specified GenericTypeDefinition.
        /// </summary>
        public IEnumerable<IBinding> Resolve(Multimap<Type, IBinding> bindings, Type service)
        {
            if (service.IsGenericTypeDefinition)
            {
                var genericType = service.GetGenericTypeDefinition();
                return bindings.Where(kvp => kvp.Key.IsGenericType
                                             && kvp.Key.GetGenericTypeDefinition() == genericType)
                    .SelectMany(kvp => kvp.Value);
            }

            return Enumerable.Empty<IBinding>();
        }
示例#15
0
		public IEnumerable<IBinding> Resolve(Multimap<Type, IBinding> bindings, IRequest request)
		{
			var binding = new Binding(request.Service);
			AttachToBinding(binding, request.Service);
			binding.ScopeCallback = request.Parameters.OfType<CreateSingletonParameter>().Any()
				? StandardScopeCallbacks.Singleton
				: StandardScopeCallbacks.Transient;

			binding.IsImplicit = true;

			return new[] { binding };
		}
        public IBinding resolves_for_factory_of_existing_service()
        {
            request.SetupGet(r => r.Service).Returns(typeof(Func<Sword>));

            var resolver = new FactoryBindingResolver();

            var maps = new Multimap<Type, IBinding>();
            maps.Add(typeof(Sword), new Binding(typeof(Sword)));

            IBinding result = resolver.Resolve(maps, request.Object).Single();

            return result;
        }
        /// <inheritDoc />
        public IEnumerable<IBinding> Resolve(Multimap<Type, IBinding> bindings, IRequest request)
        {
            var service = request.Service;
            if (!service.GetTypeInfo().IsInterface)
            {
                return Enumerable.Empty<IBinding>();
            }

            return new[] { new Binding(service)
            {
                ProviderCallback = CreateDependencyServiceProvider(service)
            }};
        }
        /// <summary>
        /// Returns any bindings from the specified collection that match the specified request.
        /// </summary>
        /// <param name="bindings">The multimap of all registered bindings.</param><param name="request">The request in question.</param>
        /// <returns>
        /// The series of matching bindings.
        /// </returns>
        public IEnumerable<IBinding> Resolve(Multimap<Type, IBinding> bindings, IRequest request)
        {
            var service = request.Service;

            if (!this.TypeIsSelfBindable(service) && !this.TypeIsSystemAssembly(service) && this.Log != null)
            {
                if (BindingMissing != null)
                {
                    BindingMissing(this, new MissingBindingEventArgs(service));
                }
            }

            return Enumerable.Empty<IBinding>();
        }
示例#19
0
        public void TryGetValues_WhenKeyExists_ReturnsValues()
        {
            var testee = new Multimap<int, int>();

            testee.Add(1, 1);
            testee.Add(1, 2);

            IEnumerable<int> values;
            var result = testee.TryGetValues(1, out values);

            result.Should().BeTrue();
            values.Should().Contain(1);
            values.Should().Contain(2);
        }
 /// <summary>
 /// Returns any bindings from the specified collection that match the specified service.
 /// </summary>
 /// <param name="bindings">The multimap of all registered bindings.</param>
 /// <param name="request">The service in question.</param>
 /// <returns>The series of matching bindings.</returns>
 public IEnumerable<IBinding> Resolve(Multimap<Type, IBinding> bindings, IRequest request)
 {
     var service = request.Service;
     return HasDefaultValue(request.Target)
                ? new[]
                      {
                          new Binding(service)
                              {
                                  Condition = r => HasDefaultValue(r.Target),
                                  ProviderCallback = _ => new DefaultParameterValueProvider(service),
                              }
                      }
                : Enumerable.Empty<IBinding>();
 }
示例#21
0
        /// <summary>
        /// Constructor that uses the given TreeControl and equality comparer</summary>
        /// <param name="treeControl">Tree control to use. Use "new TreeControl()" for the default.</param>
        /// <param name="comparer">The comparer used to compare nodes in the tree, or null to use the
        /// default comparer for type T</param>
        public TreeControlAdapter(TreeControl treeControl, IEqualityComparer<object> comparer)
        {
            m_treeControl = treeControl;
            m_itemToNodeMap = new Multimap<object, TreeControl.Node>(comparer);

            m_treeControl.MouseDown += treeControl_MouseDown;
            m_treeControl.MouseUp += treeControl_MouseUp;
            m_treeControl.DragOver += treeControl_DragOver;
            m_treeControl.DragDrop += treeControl_DragDrop;

            m_treeControl.NodeExpandedChanged += treeControl_NodeExpandedChanged;
            m_treeControl.NodeSelectedChanged += treeControl_NodeSelectedChanged;
            m_treeControl.SelectionChanging += treeControl_SelectionChanging;
            m_treeControl.SelectionChanged += treeControl_SelectionChanged;
        }
        /// <summary>
        /// Returns any bindings from the specified collection that match the specified request.
        /// </summary>
        /// <param name="bindings">The multimap of all registered bindings.</param>
        /// <param name="request">The request in question.</param>
        /// <returns>The series of matching bindings.</returns>
        public IEnumerable<IBinding> Resolve(Multimap<Type, IBinding> bindings, IRequest request)
        {
            var service = request.Service;
            if (typeof(Controller).IsAssignableFrom(service))
            {
                var binding = new Binding(service) { ProviderCallback = StandardProvider.GetCreationCallback(service) };
                binding.Parameters.Add(
                    typeof(AsyncController).IsAssignableFrom(service)
                        ? new PropertyValue("ActionInvoker", ctx => ctx.Kernel.Get<NinjectAsyncActionInvoker>())
                        : new PropertyValue("ActionInvoker", ctx => ctx.Kernel.Get<NinjectActionInvoker>()));
                return new[] { binding };
            }

            return Enumerable.Empty<IBinding>();
        }
 /// <summary>
 ///     Returns any bindings from the specified collection that match the specified service.
 /// </summary>
 /// <param name="bindings">The multimap of all registered bindings.</param>
 /// <param name="request">The service in question.</param>
 /// <returns>The series of matching bindings.</returns>
 public IEnumerable<IBinding> Resolve(Multimap<Type, IBinding> bindings, IRequest request)
 {
     var service = request.Service;
     if (!TypeIsSelfBindable(service))
     {
         return Enumerable.Empty<IBinding>();
     }
     return new[]
                {
                    new Binding(service)
                        {
                            ProviderCallback = StandardProvider.GetCreationCallback(service)
                        }
                };
 }
        /// <summary>
        /// Returns any bindings from the specified collection that match the specified request.
        /// </summary>
        /// <param name="bindings">The multimap of all registered bindings.</param>
        /// <param name="request">The request in question.</param>
        /// <returns>The series of matching bindings.</returns>
        public IEnumerable<IBinding> Resolve(Multimap<Type, IBinding> bindings, IRequest request)
        {
            var service = request.Service;
            IList<IBinding> bindingList = new List<IBinding>();

            bindingList.Add(
                new Binding(service)
                {
                    ProviderCallback = this.mockProviderCallbackProvider.GetCreationCallback(),
                    ScopeCallback = ctx => StandardScopeCallbacks.Singleton,
                    IsImplicit = true
                });

            return bindingList;
        }
        public IEnumerable<IBinding> Resolve(Multimap<Type, IBinding> bindings, IRequest request)
        {
            IServiceProvider fallbackProvider = GetFallbackProvider(request.Parameters);
            if (fallbackProvider == null)
            {
                yield break;
            }

            object fallbackService = fallbackProvider.GetServiceOrNull(request.Service);
            if (fallbackService == null)
            {
                yield break;
            }

            // The fallback provider shouldn't be responsible for resolving the service
            // if all it provides is an empty IEnumerable
            var fallbackEnumerable = fallbackService as IEnumerable;
            if (fallbackEnumerable != null && !fallbackEnumerable.GetEnumerator().MoveNext())
            {
                yield break;
            }

            // The fallback provider shouldn't be responsible for resolving an IEnumerable<T> service
            // if Ninject already has any services registered for T
            if (fallbackEnumerable != null)
            {
                var collectionTypeInfo = request.Service.GetTypeInfo();
                if (collectionTypeInfo.IsGenericType &&
                    collectionTypeInfo.GetGenericTypeDefinition() == typeof(IEnumerable<>))
                {
                    var itemType = collectionTypeInfo.GenericTypeArguments.Single();
                    if (bindings.ContainsKey(itemType))
                    {
                        yield break;
                    }
                }
            }

            yield return new Binding(request.Service)
            {
                ProviderCallback = context =>
                {
                    return new ChainedProvider(
                        context.Request.Service,
                        GetFallbackProvider(context.Request.Parameters));
                }
            };
        }
示例#26
0
            /// <summary>
            /// Returns any bindings from the specified collection that match the specified service.
            /// </summary>
            public IEnumerable<IBinding> Resolve(Multimap<Type, IBinding> bindings, Type service)
            {
                if (service.IsGenericType)
                {
                    var genericType = service.GetGenericTypeDefinition();
                    var genericArguments = genericType.GetGenericArguments();
                    if (genericArguments.Count() == 1
                     && genericArguments.Single().GenericParameterAttributes.HasFlag(GenericParameterAttributes.Contravariant))
                    {
                        var argument = service.GetGenericArguments().Single();
                        var matches = bindings.Where(kvp => kvp.Key.IsGenericType
                                                               && kvp.Key.GetGenericTypeDefinition().Equals(genericType)
                                                               && kvp.Key.GetGenericArguments().Single() != argument
                                                               && kvp.Key.GetGenericArguments().Single().IsAssignableFrom(argument))
                            .SelectMany(kvp => kvp.Value);
                        return matches;
                    }
                }

                return Enumerable.Empty<IBinding>();
            }
		public void RegisterAction(Regex widgetZoneExpression, string actionName, string controllerName, RouteValueDictionary routeValues, int order = 0)
		{
			Guard.ArgumentNotNull(() => widgetZoneExpression);
			Guard.ArgumentNotEmpty(() => actionName);
			Guard.ArgumentNotEmpty(() => controllerName);

			if (_zoneExpressionWidgetsMap == null)
			{
				_zoneExpressionWidgetsMap = new Multimap<Regex, WidgetRouteInfo>();
			}

			var routeInfo = new WidgetRouteInfo
			{
				ActionName = actionName,
				ControllerName = controllerName,
				RouteValues = routeValues ?? new RouteValueDictionary(),
				Order = order
			};

			_zoneExpressionWidgetsMap.Add(widgetZoneExpression, routeInfo);
		}
        public virtual Multimap<int, string> DeserializeProductVariantAttributes(string attributes)
        {
            var attrs = new Multimap<int, string>();
            if (String.IsNullOrEmpty(attributes))
                return attrs;

            try
            {
                var xmlDoc = new XmlDocument();
                xmlDoc.LoadXml(attributes);

                var nodeList1 = xmlDoc.SelectNodes(@"//Attributes/ProductVariantAttribute");
                foreach (var node1 in nodeList1.Cast<XmlElement>()) // codehint: sm-edit
                {
                    string sid = node1.GetAttribute("ID").Trim();
                    if (sid.HasValue())
                    {
                        int id = 0;
                        if (int.TryParse(sid, out id))
                        {
                            
                            var nodeList2 = node1.SelectNodes(@"ProductVariantAttributeValue/Value").Cast<XmlElement>();
                            foreach (var node2 in nodeList2)
                            {
                                string value = node2.InnerText.Trim();
                                attrs.Add(id, value);
                            }
                        }
                    }
                }
            }
            catch (Exception exc)
            {
                Debug.Write(exc.ToString());
            }

            return attrs;
        }
示例#29
0
        /// <summary>
        ///     Stores the specified context in the cache.
        /// </summary>
        /// <param name="context">The context to store.</param>
        /// <param name="reference">The instance reference.</param>
        public void Remember(IContext context, InstanceReference reference)
        {
            Ensure.ArgumentNotNull(context, "context");

            var scope = context.GetScope();
            var entry = new CacheEntry(context, reference);

            lock (entries)
            {
                var weakScopeReference = new ReferenceEqualWeakReference(scope);
                if (!entries.ContainsKey(weakScopeReference))
                {
                    entries[weakScopeReference] = new Multimap<IBindingConfiguration, CacheEntry>();
                    var notifyScope = scope as INotifyWhenDisposed;
                    if (notifyScope != null)
                    {
                        notifyScope.Disposed += (o, e) => Clear(weakScopeReference);
                    }
                }

                entries[weakScopeReference].Add(context.Binding.BindingConfiguration, entry);
            }
        }
示例#30
0
        /// <summary>
        /// Will resolve Func[[T]] as FactoryProvider[[T]] if there is a binding for T.
        /// </summary>
        /// <param name="bindings"></param>
        /// <param name="request"></param>
        /// <returns></returns>
        public IEnumerable<IBinding> Resolve(Multimap<Type, IBinding> bindings, IRequest request)
        {
            var targetType = TypeIsFactoryMethodFor(request.Service);

            if (targetType == null)
                return Enumerable.Empty<IBinding>();

            if (!bindings.ContainsKey(targetType))
                return Enumerable.Empty<IBinding>();

            var providerConstructor =
                typeof(FactoryProvider<object>)
                .GetGenericTypeDefinition()
                .MakeGenericType(new[] { targetType })
                .GetConstructor(new Type[] {});

            return new[] { new Binding(request.Service) {
                ProviderCallback = delegate
                {
                    return providerConstructor.Invoke(new object[] {}) as IProvider;
                },
                Target = BindingTarget.Factory
            }};
        }
示例#31
0
 /// <summary>
 /// Gets all entries for a binding within the selected scope.
 /// </summary>
 /// <param name="bindings">The bindings.</param>
 /// <returns>All bindings of a binding.</returns>
 private static IEnumerable <CacheEntry> GetAllBindingEntries(Multimap <IBindingConfiguration, CacheEntry> bindings)
 {
     return(bindings.Values.SelectMany(bindingEntries => bindingEntries));
 }
示例#32
0
        private void Init()
        {
            this.exportEntities = new Multimap <string, ExportEntity>();

            ExportEntity entity;

            foreach (Dictionary <string, string> instruction in this.GetResourceCopyInstructions())
            {
                string command = instruction["TYPE"];
                switch (command)
                {
                case "COPY_CODE":
                    this.EnsureInstructionContainsAttribute(command, instruction, "target");
                    this.EnsureInstructionContainsAttribute(command, instruction, "value");

                    entity = new ExportEntity()
                    {
                        FileOutput = new FileOutput()
                        {
                            Type        = FileOutputType.Text,
                            TextContent = instruction["value"],
                        },
                    };
                    entity.Values["target"] = instruction["target"];
                    this.exportEntities.Add("COPY_CODE", entity);
                    break;

                case "EMBED_CODE":
                    this.EnsureInstructionContainsAttribute(command, instruction, "value");
                    entity = new ExportEntity()
                    {
                        Value = instruction["value"],
                    };
                    this.exportEntities.Add("EMBED_CODE", entity);
                    break;

                case "DOTNET_REF":
                    this.EnsureInstructionContainsAttribute(command, instruction, "name");
                    entity = new ExportEntity()
                    {
                        Type  = "DOTNET_REF",
                        Value = instruction["name"],
                    };
                    this.exportEntities.Add("DOTNET_REF", entity);
                    break;

                case "DOTNET_DLL":
                    this.EnsureInstructionContainsAttribute(command, instruction, "from");
                    this.EnsureInstructionContainsAttribute(command, instruction, "hintpath");

                    if (instruction.ContainsKey("to"))
                    {
                        throw new InvalidOperationException(
                                  "DOTNET_DLL resource types should not use the 'to' field. " +
                                  "The destination is automatically determined by the hintpath.");
                    }

                    string from = instruction["from"];

                    entity = new ExportEntity();

                    entity.FileOutput = new FileOutput()
                    {
                        Type          = FileOutputType.Binary,
                        BinaryContent = this.library.Metadata.ReadFileBytes("native/" + from)
                    };

                    entity.Values["hintpath"] = instruction["hintpath"];
                    foreach (string dllAttr in new string[] {
                        "name", "version", "culture", "token", "architecture", "specificversion"
                    })
                    {
                        if (instruction.ContainsKey(dllAttr))
                        {
                            entity.Values[dllAttr] = instruction[dllAttr];
                        }
                    }
                    this.exportEntities.Add("DOTNET_DLL", entity);
                    break;

                default:
                    throw new InvalidOperationException("The command '" + command + "' is not recongized in the resource manifest of library: '" + this.library.Metadata.ID + "'");
                }
            }
        }
示例#33
0
 public ProxyStore()
 {
     this.proxies = new Multimap <Type, ProxyBinding>();
 }
示例#34
0
        /// <summary>
        /// Converts schemas to NodeTypes, AttributeTypes, and root elements</summary>
        /// <param name="schemaSet">Schemas to register</param>
        public void Load(XmlSchemaSet schemaSet)
        {
            if (!schemaSet.IsCompiled)
            {
                schemaSet.Compile();
            }

            System.Collections.ICollection schemas = schemaSet.Schemas();
            foreach (XmlSchema schema in schemas)
            {
                string targetNamespace = schema.TargetNamespace;
                if (string.IsNullOrEmpty(targetNamespace))
                {
                    throw new InvalidOperationException("Schema has no target namespace");
                }

                // only register the schema once; targetNamespaces must be globally unique
                if (!m_typeCollections.ContainsKey(targetNamespace))
                {
                    XmlQualifiedName[]      nameSpaces     = schema.Namespaces.ToArray();
                    XmlSchemaTypeCollection typeCollection = new XmlSchemaTypeCollection(nameSpaces, targetNamespace, this);
                    m_typeCollections.Add(targetNamespace, typeCollection);
                }
            }

            try
            {
                m_annotations     = new Dictionary <NamedMetadata, IList <XmlNode> >();
                m_typeNameSet     = new HashSet <string>();
                m_localElementSet = new Dictionary <XmlSchemaElement, XmlQualifiedName>();
                // collect global element & type names so we do not generate local type names that collides with those
                foreach (XmlSchemaElement element in schemaSet.GlobalElements.Values)
                {
                    m_typeNameSet.Add(element.QualifiedName.Name);
                }

                foreach (XmlSchemaType type in schemaSet.GlobalTypes.Values)
                {
                    if (type is XmlSchemaComplexType)
                    {
                        m_typeNameSet.Add(type.Name);
                    }
                }

                var substitutionGroups = new Multimap <XmlQualifiedName, ChildInfo>();

                // Get types reachable from global elements
                foreach (XmlSchemaElement element in schemaSet.GlobalElements.Values)
                {
                    XmlSchemaType type      = element.ElementSchemaType;
                    DomNodeType   nodeType  = GetNodeType(type, element);
                    ChildInfo     childInfo = new ChildInfo(GetFieldName(element.QualifiedName), nodeType);
                    m_annotations.Add(childInfo, GetAnnotation(element));

                    // Keep list of substitution groups
                    if (!element.SubstitutionGroup.IsEmpty)
                    {
                        substitutionGroups.Add(element.SubstitutionGroup, childInfo);
                    }

                    // only add root elements once; root element names must be globally unique
                    string name = element.QualifiedName.ToString();
                    if (!m_rootElements.ContainsKey(name))
                    {
                        m_rootElements[name] = childInfo;
                    }
                }

                // Get global complex type definitions
                foreach (XmlSchemaType type in schemaSet.GlobalTypes.Values)
                {
                    if (type is XmlSchemaComplexType)
                    {
                        GetNodeType(type, null);
                    }
                }

                // Parse substitution groups
                foreach (var kvp in m_refElements)
                {
                    XmlQualifiedName refName   = kvp.Value;
                    ChildInfo        childInfo = kvp.Key;

                    var substitutions = substitutionGroups.Find(refName).ToArray();
                    if (substitutions.Length > 0)
                    {
                        childInfo.AddRule(new SubstitutionGroupChildRule(substitutions));
                    }
                }

                // Preserve annotation from any types that were redefined
                foreach (XmlSchema schema in schemas)
                {
                    foreach (XmlSchemaObject schemaInclude in schema.Includes)
                    {
                        XmlSchemaRedefine schemaRedefine = schemaInclude as XmlSchemaRedefine;
                        if (schemaRedefine != null)
                        {
                            MergeRedefinedTypeAnnotations(schemaRedefine);
                        }
                    }
                }

                // Sort DomNodeTypes, so that base types are always before derived types
                // Bucket sort by depth in the inheritance tree
                // Time: O(n * d) with n = number of DomNodeTypes, d = depth of inheritance tree
                var sortedTypes = new List <List <DomNodeType> >();
                foreach (DomNodeType type in GetNodeTypes())
                {
                    // Get inheritance depth of current type
                    int         depth   = 0;
                    DomNodeType curType = type;
                    while (curType != null && curType != DomNodeType.BaseOfAllTypes)
                    {
                        depth++;
                        curType = curType.BaseType;
                    }

                    // We don't need to merge annotations for BaseAllTypes (level 0)
                    // and its immediate child types (level 1)
                    int idx = depth - 2;
                    if (idx >= 0)
                    {
                        while (sortedTypes.Count <= idx)
                        {
                            sortedTypes.Add(new List <DomNodeType>());
                        }
                        sortedTypes[idx].Add(type);
                    }
                }

                // Merge type annotations with base type annotations
                foreach (var list in sortedTypes)
                {
                    foreach (DomNodeType type in list)
                    {
                        if (type.BaseType != null && type.BaseType != DomNodeType.BaseOfAllTypes)
                        {
                            IList <XmlNode> baseAnnotations;
                            IList <XmlNode> annotations;
                            if (m_annotations.TryGetValue(type.BaseType, out baseAnnotations) &&
                                m_annotations.TryGetValue(type, out annotations))
                            {
                                // Call protected virtual merge method - allowing clients to define if & how annotations are being merged
                                IEnumerable <XmlNode> mergedAnnotations = MergeInheritedTypeAnnotations(baseAnnotations, annotations);
                                m_annotations[type] = mergedAnnotations as IList <XmlNode> ?? mergedAnnotations.ToList();
                            }
                        }
                    }
                }

                // Call before the DomNodeTypes are frozen. Note that iterating through Attributes or
                //  calling 'SetIdAttribute' freezes the attributes on DomNodeType.
                OnSchemaSetLoaded(schemaSet);

                // Set up ID attributes where xs:ID has been specified
                foreach (DomNodeType nodeType in GetNodeTypes())
                {
                    foreach (var attribute in nodeType.Attributes.OfType <XmlAttributeInfo>())
                    {
                        if (((XmlAttributeType)attribute.Type).XmlTypeCode == XmlTypeCode.Id)
                        {
                            nodeType.SetIdAttribute(attribute.Name);
                        }
                    }
                }

                // Attach annotation as metadata to the associated type so that other classes can find it
                foreach (var keyValuePair in m_annotations)
                {
                    if (keyValuePair.Value.Count > 0)
                    {
                        keyValuePair.Key.SetTag <IEnumerable <XmlNode> >(keyValuePair.Value);
                    }
                }
                ParseAnnotations(schemaSet, m_annotations);

                // Call this after the ID attributes have been set and after the DomNodeTypes are frozen.
                OnDomNodeTypesFrozen(schemaSet);
            }
            finally
            {
                m_annotations     = null;
                m_typeNameSet     = null;
                m_localElementSet = null;
            }
        }
示例#35
0
        public static RequestContext Build(RequestLine request, IReadOnlyDictionary <string, string> queryString, Multimap <string, string> headerEntries, NetworkStream inputStream)
        {
            RequestParameters parameters = new RequestParameters(headerEntries, queryString);

            int contentLength = 0;

            if (headerEntries.ContainsKey("Content-Length"))
            {
                int.TryParse(headerEntries["Content-Length"].FirstOrDefault(), out contentLength);
            }

            string contentType = null;

            if (headerEntries.ContainsKey("Content-Type"))
            {
                contentType = headerEntries["Content-Type"].FirstOrDefault();
            }

            RequestContent content = new RequestContent(contentType, contentLength, inputStream);

            return(new RequestContext(request, parameters, content, CookieCollection.Build(headerEntries)));
        }
        public async Task <DbSavingChangesResult> SavingChangesAsync(IEnumerable <IHookedEntity> entries, bool importantHooksOnly, CancellationToken cancelToken = default)
        {
            Guard.NotNull(entries, nameof(entries));

            var anyStateChanged = false;

            if (!entries.Any() || !_saveHooks.Any() || (importantHooksOnly && !this.HasImportantSaveHooks()))
            {
                return(DbSavingChangesResult.Empty);
            }

            var processedHooks = new Multimap <IDbSaveHook, IHookedEntity>();

            foreach (var entry in entries)
            {
                var e = entry; // Prevents access to modified closure

                if (cancelToken.IsCancellationRequested)
                {
                    continue;
                }

                if (HandledAlready(e, HookStage.PreSave))
                {
                    // Prevent repetitive hooking of the same entity/state/pre combination within a single request
                    continue;
                }

                var hooks = GetSaveHookInstancesFor(e, HookStage.PreSave, importantHooksOnly);

                foreach (var hook in hooks)
                {
                    // call hook
                    try
                    {
                        Logger.Debug("PRE save hook: {0}, State: {1}, Entity: {2}", hook.GetType().Name, e.InitialState, e.Entity.GetType().Name);
                        var result = await hook.OnBeforeSaveAsync(e, cancelToken);

                        if (result == HookResult.Ok)
                        {
                            processedHooks.Add(hook, e);
                        }
                        else if (result == HookResult.Void)
                        {
                            RegisterVoidHook(hook, e, HookStage.PreSave);
                        }
                    }
                    catch (Exception ex) when(ex is NotImplementedException || ex is NotSupportedException)
                    {
                        RegisterVoidHook(hook, e, HookStage.PreSave);
                    }
                    catch (Exception ex)
                    {
                        Logger.Error(ex, "PreSaveHook exception ({0})", hook.GetType().FullName);
                    }

                    // change state if applicable
                    if (e.HasStateChanged)
                    {
                        e.InitialState  = e.State;
                        anyStateChanged = true;
                    }
                }
            }

            foreach (var hook in processedHooks)
            {
                await hook.Key.OnBeforeSaveCompletedAsync(hook.Value, cancelToken);
            }

            return(new DbSavingChangesResult(processedHooks.Keys, anyStateChanged)
            {
                Entries = entries
            });
        }
示例#37
0
        public virtual async Task RebuildAsync(XmlSitemapBuildContext ctx)
        {
            Guard.NotNull(ctx, nameof(ctx));

            var languageData = new Dictionary <int, LanguageData>();

            foreach (var language in ctx.Languages)
            {
                var lockFilePath = GetLockFilePath(ctx.Store.Id, language.Id);

                if (_lockFileManager.TryAcquireLock(lockFilePath, out var lockFile))
                {
                    // Process only languages that are unlocked right now
                    // It is possible that an HTTP request triggered the generation
                    // of a language specific sitemap.

                    var sitemapDir = BuildSitemapDirPath(ctx.Store.Id, language.Id);
                    var data       = new LanguageData
                    {
                        Store        = ctx.Store,
                        Language     = language,
                        LockFile     = lockFile,
                        LockFilePath = lockFilePath,
                        TempDir      = sitemapDir + "~",
                        FinalDir     = sitemapDir,
                        BaseUrl      = BuildBaseUrl(ctx.Store, language)
                    };

                    _tenantFolder.TryDeleteDirectory(data.TempDir);
                    _tenantFolder.CreateDirectory(data.TempDir);

                    languageData[language.Id] = data;
                }
            }

            if (languageData.Count == 0)
            {
                Logger.Warn("XML sitemap rebuild already in process.");
                return;
            }

            var languages   = languageData.Values.Select(x => x.Language);
            var languageIds = languages.Select(x => x.Id).Concat(new[] { 0 }).ToArray();

            // All sitemaps grouped by language
            var sitemaps = new Multimap <int, XmlSitemapNode>();

            var compositeFileLock = new ActionDisposable(() =>
            {
                foreach (var data in languageData.Values)
                {
                    data.LockFile.Release();
                }
            });

            using (compositeFileLock)
            {
                // Impersonate
                var prevCustomer = _services.WorkContext.CurrentCustomer;
                // no need to vary xml sitemap by customer roles: it's relevant to crawlers only.
                _services.WorkContext.CurrentCustomer = _customerService.GetCustomerBySystemName(SystemCustomerNames.SearchEngine);

                try
                {
                    var nodes = new List <XmlSitemapNode>();

                    var queries = CreateQueries(ctx);
                    var total   = await queries.GetTotalRecordCountAsync();

                    var totalSegments = (int)Math.Ceiling(total / (double)MaximumSiteMapNodeCount);
                    var hasIndex      = totalSegments > 1;
                    var indexNodes    = new Multimap <int, XmlSitemapNode>();
                    var segment       = 0;
                    var numProcessed  = 0;

                    CheckSitemapCount(totalSegments);

                    using (new DbContextScope(autoDetectChanges: false, forceNoTracking: true, proxyCreation: false, lazyLoading: false))
                    {
                        var entities = EnumerateEntities(queries);

                        foreach (var batch in entities.Slice(MaximumSiteMapNodeCount))
                        {
                            if (ctx.CancellationToken.IsCancellationRequested)
                            {
                                break;
                            }

                            segment++;
                            numProcessed = segment * MaximumSiteMapNodeCount;
                            ctx.ProgressCallback?.Invoke(numProcessed, total, "{0} / {1}".FormatCurrent(numProcessed, total));

                            var firstEntityName = batch.First().EntityName;
                            var lastEntityName  = batch.Last().EntityName;

                            var slugs = GetUrlRecordCollectionsForBatch(batch, languageIds);

                            foreach (var data in languageData.Values)
                            {
                                var language = data.Language;
                                var baseUrl  = data.BaseUrl;

                                // Create all node entries for this segment
                                sitemaps[language.Id].AddRange(batch.Select(x => new XmlSitemapNode
                                {
                                    LastMod = x.LastMod,
                                    Loc     = BuildNodeUrl(baseUrl, x, slugs[x.EntityName], language)
                                }));

                                // Create index node for this segment/language combination
                                if (hasIndex)
                                {
                                    indexNodes[language.Id].Add(new XmlSitemapNode
                                    {
                                        LastMod = sitemaps[language.Id].Select(x => x.LastMod).Where(x => x.HasValue).DefaultIfEmpty().Max(),
                                        Loc     = GetSitemapIndexUrl(segment, baseUrl),
                                    });
                                }

                                if (segment % 5 == 0 || segment == totalSegments)
                                {
                                    // Commit every 5th segment (10.000 nodes) temporarily to disk to minimize RAM usage
                                    var documents = GetSiteMapDocuments((IReadOnlyCollection <XmlSitemapNode>)sitemaps[language.Id]);
                                    await SaveTempAsync(documents, data, segment - documents.Count + (hasIndex ? 1 : 0));

                                    documents.Clear();
                                    sitemaps.RemoveAll(language.Id);
                                }
                            }

                            slugs.Clear();

                            //GC.Collect();
                            //GC.WaitForPendingFinalizers();
                        }

                        // Process custom nodes
                        if (!ctx.CancellationToken.IsCancellationRequested)
                        {
                            ctx.ProgressCallback?.Invoke(numProcessed, total, "Processing custom nodes".FormatCurrent(numProcessed, total));
                            ProcessCustomNodes(ctx, sitemaps);

                            foreach (var data in languageData.Values)
                            {
                                if (sitemaps.ContainsKey(data.Language.Id) && sitemaps[data.Language.Id].Count > 0)
                                {
                                    var documents = GetSiteMapDocuments((IReadOnlyCollection <XmlSitemapNode>)sitemaps[data.Language.Id]);
                                    await SaveTempAsync(documents, data, (segment + 1) - documents.Count + (hasIndex ? 1 : 0));
                                }
                                else if (segment == 0)
                                {
                                    // Ensure that at least one entry exists. Otherwise,
                                    // the system will try to rebuild again.
                                    var homeNode = new XmlSitemapNode {
                                        LastMod = DateTime.UtcNow, Loc = data.BaseUrl
                                    };
                                    var documents = GetSiteMapDocuments(new List <XmlSitemapNode> {
                                        homeNode
                                    });
                                    await SaveTempAsync(documents, data, 0);
                                }
                            }
                        }
                    }

                    ctx.CancellationToken.ThrowIfCancellationRequested();

                    ctx.ProgressCallback?.Invoke(totalSegments, totalSegments, "Finalizing...'");

                    foreach (var data in languageData.Values)
                    {
                        // Create index documents (if any)
                        if (hasIndex && indexNodes.Any())
                        {
                            var indexDocument = CreateSitemapIndexDocument(indexNodes[data.Language.Id]);
                            await SaveTempAsync(new List <string> {
                                indexDocument
                            }, data, 0);
                        }

                        // Save finally (actually renames temp folder)
                        SaveFinal(data);
                    }
                }
                finally
                {
                    // Undo impersonation
                    _services.WorkContext.CurrentCustomer = prevCustomer;
                    sitemaps.Clear();

                    foreach (var data in languageData.Values)
                    {
                        if (_tenantFolder.DirectoryExists(data.TempDir))
                        {
                            _tenantFolder.TryDeleteDirectory(data.TempDir);
                        }
                    }

                    //GC.Collect();
                    //GC.WaitForPendingFinalizers();
                }
            }
        }
示例#38
0
            static void AddChildTreeNodes(TreeNode <MediaFolderNode> parentNode, int parentId, Multimap <int, MediaFolderNode> nodeMap)
            {
                var parent = parentNode?.Value;

                if (parent == null)
                {
                    return;
                }

                var nodes = Enumerable.Empty <MediaFolderNode>();

                if (nodeMap.ContainsKey(parentId))
                {
                    nodes = parentId == 0
                        ? nodeMap[parentId].OrderBy(x => x.Order)
                        : nodeMap[parentId].OrderBy(x => x.Name);
                }

                foreach (var node in nodes)
                {
                    var newNode = new TreeNode <MediaFolderNode>(node);

                    // Inherit some props from parent node
                    if (!node.IsAlbum)
                    {
                        node.AlbumName       = parent.AlbumName;
                        node.CanDetectTracks = parent.CanDetectTracks;
                        node.IncludePath     = parent.IncludePath;
                        node.Path            = (parent.Path + "/" + (node.Slug.NullEmpty() ?? node.Name)).Trim('/').ToLower();
                    }

                    // We gonna query nodes by path also, therefore we need 2 keys per node (FolderId and computed path)
                    newNode.Id = new object[] { node.Id, node.Path };

                    parentNode.Append(newNode);

                    AddChildTreeNodes(newNode, node.Id, nodeMap);
                }
            }
示例#39
0
 public RequestParameters(Multimap <string, string> headerEntries, IReadOnlyDictionary <string, string> queryStringValues)
 {
     HeaderEntries     = headerEntries;
     QueryStringValues = queryStringValues;
 }
        public void Seed(SmartObjectContext context)
        {
            var resourceSet  = context.Set <LocaleStringResource>();
            var allLanguages = context.Set <Language>().ToList();

            // Accidents.
            var accidents = resourceSet.Where(x => x.ResourceName == "Admin.Configuration.ActivityLog.ActivityLogType").ToList();

            if (accidents.Any())
            {
                accidents.Each(x => x.ResourceName = "Admin.Configuration.ActivityLog.ActivityLogType");
                context.SaveChanges();
            }

            // Remove unused resources that could be included in the German set.
            var unusedResources = resourceSet.Where(x => _unusedNames.Contains(x.ResourceName)).ToList();

            if (unusedResources.Any())
            {
                resourceSet.RemoveRange(unusedResources);
                context.SaveChanges();
                unusedResources.Clear();
            }

            // Remove duplicate resources.
            foreach (var language in allLanguages)
            {
                var resources       = resourceSet.Where(x => x.LanguageId == language.Id).ToList();
                var deleteResources = new List <LocaleStringResource>();
                var resourcesMap    = new Multimap <string, LocaleStringResource>(StringComparer.OrdinalIgnoreCase);
                resources.Each(x => resourcesMap.Add(x.ResourceName, x));

                foreach (var item in resourcesMap)
                {
                    if (item.Value.Count > 1)
                    {
                        // First is ok, rest is bad.
                        foreach (var resource in item.Value.OrderByDescending(x => x.IsTouched).Skip(1))
                        {
                            deleteResources.Add(resource);
                        }
                    }
                }

                if (deleteResources.Any())
                {
                    resourceSet.RemoveRange(deleteResources);
                    context.SaveChanges();
                    deleteResources.Clear();
                }
            }

            // Remove resources that are not included in the German set.
            // Unfortunately we cannot do that. We have no information about the origin of a resource. We would delete resources of other developers.

            // Add resources included in the German set but missing in the English set.
            var deLanguage = allLanguages.FirstOrDefault(x => x.LanguageCulture.IsCaseInsensitiveEqual("de-DE"));
            var enLanguage = allLanguages.FirstOrDefault(x => x.LanguageCulture.IsCaseInsensitiveEqual("en-US"));

            if (deLanguage != null && enLanguage != null)
            {
                var deResources = resourceSet.AsNoTracking().Where(x => x.LanguageId == deLanguage.Id).ToList();

                var enNames = resourceSet
                              .Where(x => x.LanguageId == enLanguage.Id)
                              .Select(x => x.ResourceName)
                              .Distinct()
                              .ToList();
                var enNamesSet = new HashSet <string>(enNames, StringComparer.OrdinalIgnoreCase);

                foreach (var resource in deResources)
                {
                    if (!enNames.Contains(resource.ResourceName) && _missingEnglishResources.TryGetValue(resource.ResourceName, out string value))
                    {
                        resourceSet.Add(new LocaleStringResource
                        {
                            LanguageId    = enLanguage.Id,
                            ResourceName  = resource.ResourceName,
                            ResourceValue = value,
                            IsFromPlugin  = resource.IsFromPlugin
                        });
                    }
                }

                context.SaveChanges();
                deResources.Clear();
            }
        }
示例#41
0
        public void TestWithValueType()
        {
            var m = new Multimap <int, int>();

            m.Add(0, 0);
            Assert.True(m.ContainsKey(0));
            Assert.True(m.ContainsKeyValue(0, 0));
            Assert.True(m.FindFirst(0) == 0);
            Assert.True(m.FindFirst(-1) == default(int));

            m.Add(0, 1);
            Utilities.TestSequenceEqual(m.Find(0), new[] { 0, 1 });
            Assert.True(m.ContainsKey(0));
            Assert.True(m.ContainsKeyValue(0, 0));
            Assert.True(m.ContainsKey(0));
            Assert.True(m.ContainsKeyValue(0, 1));

            m.Add(0, 2);
            Utilities.TestSequenceEqual(m.Find(0), new[] { 0, 1, 2 });

            m.Add(100, 0);
            Utilities.TestSequenceEqual(m.Find(0), new[] { 0, 1, 2 });
            Utilities.TestSequenceEqual(m.Find(100), new[] { 0 });

            m.Add(100, 1);
            Utilities.TestSequenceEqual(m.Find(0), new[] { 0, 1, 2 });
            Utilities.TestSequenceEqual(m.Find(100), new[] { 0, 1 });

            // Add a duplicate value for a key
            m.Add(100, 0);
            Utilities.TestSequenceEqual(m.Find(0), new[] { 0, 1, 2 });
            Utilities.TestSequenceEqual(m.Find(100), new[] { 1, 0 });//note the 0 is last

            // Add another duplicate value for a key
            m.Add(100, 1);
            Utilities.TestSequenceEqual(m.Find(0), new[] { 0, 1, 2 });
            Utilities.TestSequenceEqual(m.Find(100), new[] { 0, 1 });//note the 1 is last

            m.Add(100, 2);
            Utilities.TestSequenceEqual(m.Find(0), new[] { 0, 1, 2 });
            Utilities.TestSequenceEqual(m.Find(100), new[] { 0, 1, 2 });

            m.AddFirst(100, -1);
            Utilities.TestSequenceEqual(m.Find(0), new[] { 0, 1, 2 });
            Utilities.TestSequenceEqual(m.Find(100), new[] { -1, 0, 1, 2 });
            Assert.True(m.ContainsKeyValue(100, -1));
            Assert.True(m.ContainsKeyValue(100, 0));
            Assert.True(m.ContainsKeyValue(100, 1));
            Assert.True(m.ContainsKeyValue(100, 2));

            m.AddFirst(100, 2);
            Utilities.TestSequenceEqual(m.Find(0), new[] { 0, 1, 2 });
            Utilities.TestSequenceEqual(m.Find(100), new[] { 2, -1, 0, 1 });
            Assert.True(m.FindFirst(0) == 0);
            Assert.True(m.FindFirst(100) == 2);
            Assert.True(m.FindLast(0) == 2);
            Assert.True(m.FindLast(100) == 1);
            Assert.True(m.ContainsKeyValue(100, 2));

            Assert.True(m.ContainsKey(0));
            Assert.True(m.ContainsKey(100));

            // Remove the 0 key
            Assert.True(m.Remove(0));
            Assert.False(m.ContainsKey(0));
            Assert.False(m[0].Any());
            Assert.True(m.ContainsKey(100));
            Utilities.TestSequenceEqual(m.Find(0), new int[] {});
            Utilities.TestSequenceEqual(m.Find(100), new[] { 2, -1, 0, 1 });
            Utilities.TestSequenceEqual(m.Keys, new[] { 100 });

            // Remove values from the 100 key
            Assert.True(m.Remove(100, -1));
            Assert.True(m.Remove(100, 0));
            Utilities.TestSequenceEqual(m.Find(0), new int[] { });
            Utilities.TestSequenceEqual(m.Find(100), new[] { 2, 1 });
            Assert.False(m.Remove(100, -1));
            Assert.False(m.Remove(100, 0));
            Utilities.TestSequenceEqual(m.Find(0), new int[] { });
            Utilities.TestSequenceEqual(m.Find(100), new[] { 2, 1 });
            Assert.True(m.Remove(100, 1));
            Assert.True(m.ContainsKeyValue(100, 2));
            Assert.False(m.ContainsKeyValue(100, 1));
            Assert.True(m.Remove(100, 2));
            Assert.False(m.ContainsKeyValue(100, 2));
            Assert.False(m.ContainsKey(100));
            Assert.False(m[100].Any());
            Utilities.TestSequenceEqual(m.Keys, new int[] {});
        }
示例#42
0
        public virtual IEnumerable <WidgetRouteInfo> GetWidgets(string widgetZone, object model)
        {
            string actionName;
            string controllerName;
            RouteValueDictionary routeValues;
            var storeId = _storeContext.CurrentStore.Id;

            #region Plugin Widgets

            var widgets = _widgetService.LoadActiveWidgetsByWidgetZone(widgetZone, storeId);
            foreach (var widget in widgets)
            {
                widget.Value.GetDisplayWidgetRoute(widgetZone, model, storeId, out actionName, out controllerName, out routeValues);

                if (actionName.HasValue() && controllerName.HasValue())
                {
                    yield return(new WidgetRouteInfo
                    {
                        ActionName = actionName,
                        ControllerName = controllerName,
                        RouteValues = routeValues
                    });
                }
            }

            #endregion

            #region Topic Widgets

            // add special "topic widgets" to the list
            var allTopicsCacheKey = string.Format(ModelCacheEventConsumer.TOPIC_WIDGET_ALL_MODEL_KEY, storeId, _workContext.WorkingLanguage.Id, _workContext.CurrentCustomer.GetRolesIdent());
            // get topic widgets from STATIC cache
            var topicWidgets = _services.Cache.Get(allTopicsCacheKey, () =>
            {
                using (var scope = new DbContextScope(forceNoTracking: true))
                {
                    var allTopicWidgets = _topicService.GetAllTopics(storeId).AlterQuery(q =>
                    {
                        return(q.Where(x => x.RenderAsWidget));
                    });

                    var stubs = allTopicWidgets
                                .Select(t =>
                    {
                        var locTitle = t.GetLocalized(x => t.Title);
                        var locBody  = t.GetLocalized(x => t.Body, detectEmptyHtml: false);

                        return(new TopicWidgetStub
                        {
                            Id = t.Id,
                            Bordered = t.WidgetBordered,
                            WrapContent = !t.WidgetWrapContent.HasValue || t.WidgetWrapContent.Value,
                            ShowTitle = t.WidgetShowTitle,
                            SystemName = t.SystemName.SanitizeHtmlId(),
                            ShortTitle = t.GetLocalized(x => x.ShortTitle),
                            Title = locTitle,
                            TitleRtl = locTitle.CurrentLanguage.Rtl,
                            Intro = t.GetLocalized(x => x.Intro),
                            Body = locBody,
                            BodyRtl = locBody.CurrentLanguage.Rtl,
                            TitleTag = t.TitleTag,
                            WidgetZones = t.GetWidgetZones().ToArray(),
                            Priority = t.Priority,
                            CookieType = t.CookieType
                        });
                    })
                                .OrderBy(t => t.Priority)
                                .ToList();
                    return(stubs);
                }
            });

            var byZoneTopicsCacheKey = "SmartStore.TopicWidgets.ZoneMapped";
            // save widgets to zones map in request cache
            var topicsByZone = _requestCache.Get(byZoneTopicsCacheKey, () =>
            {
                var map = new Multimap <string, WidgetRouteInfo>();

                foreach (var widget in topicWidgets)
                {
                    var zones = widget.WidgetZones;
                    if (zones != null && zones.Any())
                    {
                        foreach (var zone in zones.Select(x => x.ToLower()))
                        {
                            var routeInfo = new WidgetRouteInfo
                            {
                                ControllerName = "Topic",
                                ActionName     = "TopicWidget",
                                RouteValues    = new RouteValueDictionary
                                {
                                    { "Namespaces", "SmartStore.Web.Controllers" },
                                    { "area", null },
                                    { "widgetZone", zone },
                                    { "model", new TopicWidgetModel
                                      {
                                          Id          = widget.Id,
                                          SystemName  = widget.SystemName,
                                          WrapContent = widget.WrapContent,
                                          ShowTitle   = widget.ShowTitle,
                                          IsBordered  = widget.Bordered,
                                          ShortTitle  = widget.ShortTitle.NullEmpty(),
                                          Title       = widget.Title.NullEmpty(),
                                          TitleTag    = widget.TitleTag ?? "h3",
                                          Intro       = widget.Intro.NullEmpty(),
                                          Html        = widget.Body,
                                          HtmlRtl     = widget.BodyRtl,
                                          TitleRtl    = widget.TitleRtl,
                                          CookieType  = widget.CookieType
                                      } }
                                }
                            };

                            map.Add(zone, routeInfo);
                        }
                    }
                }

                return(map);
            });

            if (topicsByZone.ContainsKey(widgetZone.ToLower()))
            {
                var zoneWidgets = topicsByZone[widgetZone.ToLower()];
                foreach (var topicWidget in zoneWidgets)
                {
                    // Handle OC announcement
                    var topicWidgetModel = topicWidget.RouteValues["model"] as TopicWidgetModel;
                    if (topicWidgetModel != null)
                    {
                        _services.DisplayControl.Announce(new Topic {
                            Id = topicWidgetModel.Id
                        });
                    }

                    yield return(topicWidget);
                }
            }

            #endregion

            #region Request scoped widgets (provided by IWidgetProvider)

            var requestScopedWidgets = _widgetProvider.GetWidgets(widgetZone);
            if (requestScopedWidgets != null)
            {
                foreach (var widget in requestScopedWidgets)
                {
                    yield return(widget);
                }
            }

            #endregion
        }
示例#43
0
        private bool IsCategoryAllowed(int categoryId, HashSet <int> limitedStoreIds, Dictionary <int, int> allCategoryIds, Multimap <int, int> storeMappings)
        {
            if (categoryId == 0)
            {
                return(false);
            }

            if (!limitedStoreIds.Any())
            {
                return(true);
            }

            while (categoryId != 0)
            {
                if (storeMappings.ContainsKey(categoryId) && !storeMappings[categoryId].Intersect(limitedStoreIds).Any())
                {
                    // is limited to stores but not to any of allowed stores
                    return(false);
                }

                if (allCategoryIds.ContainsKey(categoryId) && allCategoryIds[categoryId] != categoryId)
                {
                    categoryId = allCategoryIds[categoryId];
                }
                else
                {
                    break;
                }
            }

            return(true);
        }
        public virtual IEnumerable <WidgetRouteInfo> GetWidgets(string widgetZone, object model)
        {
            string actionName;
            string controllerName;
            RouteValueDictionary routeValues;
            var storeId = _storeContext.CurrentStore.Id;

            #region Plugin Widgets

            var widgets = _widgetService.LoadActiveWidgetsByWidgetZone(widgetZone, storeId);
            foreach (var widget in widgets)
            {
                widget.Value.GetDisplayWidgetRoute(widgetZone, model, storeId, out actionName, out controllerName, out routeValues);

                yield return(new WidgetRouteInfo
                {
                    ActionName = actionName,
                    ControllerName = controllerName,
                    RouteValues = routeValues
                });
            }

            #endregion


            #region Topic Widgets

            // add special "topic widgets" to the list
            var allTopicsCacheKey = string.Format(ModelCacheEventConsumer.TOPIC_WIDGET_ALL_MODEL_KEY, storeId, _workContext.WorkingLanguage.Id);
            // get topic widgets from STATIC cache
            var topicWidgets = _services.Cache.Get(allTopicsCacheKey, () =>
            {
                using (var scope = new DbContextScope(forceNoTracking: true))
                {
                    var allTopicWidgets = _topicService.GetAllTopics(storeId).Where(x => x.RenderAsWidget).ToList();
                    var stubs           = allTopicWidgets
                                          .Select(t => new TopicWidgetStub
                    {
                        Id          = t.Id,
                        Bordered    = t.WidgetBordered,
                        ShowTitle   = t.WidgetShowTitle,
                        SystemName  = t.SystemName.SanitizeHtmlId(),
                        Title       = t.GetLocalized(x => t.Title),
                        Body        = t.GetLocalized(x => t.Body),
                        WidgetZones = t.GetWidgetZones().ToArray(),
                        Priority    = t.Priority
                    })
                                          .OrderBy(t => t.Priority)
                                          .ToList();
                    return(stubs);
                }
            });

            var byZoneTopicsCacheKey = "SmartStore.TopicWidgets.ZoneMapped";
            // save widgets to zones map in request cache
            var topicsByZone = _cacheManager.Get(byZoneTopicsCacheKey, () =>
            {
                var map = new Multimap <string, WidgetRouteInfo>();

                foreach (var widget in topicWidgets)
                {
                    var zones = widget.WidgetZones;
                    if (zones != null && zones.Any())
                    {
                        foreach (var zone in zones.Select(x => x.ToLower()))
                        {
                            var routeInfo = new WidgetRouteInfo
                            {
                                ControllerName = "Topic",
                                ActionName     = "TopicWidget",
                                RouteValues    = new RouteValueDictionary()
                                {
                                    { "Namespaces", "SmartStore.Web.Controllers" },
                                    { "area", null },
                                    { "widgetZone", zone },
                                    { "model", new TopicWidgetModel
                                      {
                                          Id         = widget.Id,
                                          SystemName = widget.SystemName,
                                          ShowTitle  = widget.ShowTitle,
                                          IsBordered = widget.Bordered,
                                          Title      = widget.Title,
                                          Html       = widget.Body
                                      } }
                                }
                            };
                            map.Add(zone, routeInfo);
                        }
                    }
                }

                return(map);

                #region Obsolete
                //var result = from t in topicWidgets
                //			 where t.WidgetZones.Contains(widgetZone, StringComparer.InvariantCultureIgnoreCase)
                //			 orderby t.Priority
                //			 select new WidgetRouteInfo
                //			 {
                //				 ControllerName = "Topic",
                //				 ActionName = "TopicWidget",
                //				 RouteValues = new RouteValueDictionary()
                //				 {
                //					{"Namespaces", "SmartStore.Web.Controllers"},
                //					{"area", null},
                //					{"widgetZone", widgetZone},
                //					{"model", new TopicWidgetModel
                //					{
                //						Id = t.Id,
                //						SystemName = t.SystemName,
                //						ShowTitle = t.ShowTitle,
                //						IsBordered = t.Bordered,
                //						Title = t.Title,
                //						Html = t.Body
                //					} }
                //				 }
                //			 };

                //return result.ToList();
                #endregion
            });

            if (topicsByZone.ContainsKey(widgetZone.ToLower()))
            {
                var zoneWidgets = topicsByZone[widgetZone.ToLower()];
                foreach (var topicWidget in zoneWidgets)
                {
                    yield return(topicWidget);
                }
            }

            #endregion


            #region Request scoped widgets (provided by IWidgetProvider)

            var requestScopedWidgets = _widgetProvider.GetWidgets(widgetZone);
            if (requestScopedWidgets != null)
            {
                foreach (var widget in requestScopedWidgets)
                {
                    yield return(widget);
                }
            }

            #endregion
        }
示例#45
0
 protected void ProcessCustomNodes(XmlSitemapBuildContext ctx, Multimap <int, XmlSitemapNode> sitemaps)
 {
 }
        private void Init()
        {
            this.exportEntities         = new Multimap <string, ExportEntity>();
            this.dotNetLibs             = new List <string>();
            this.projectReferenceToGuid = new Dictionary <string, string>();

            ExportEntity entity;

            foreach (Dictionary <string, string> instruction in this.GetResourceCopyInstructions())
            {
                string command = instruction["TYPE"];
                switch (command)
                {
                case "COPY_CODE":
                    this.EnsureInstructionContainsAttribute(command, instruction, "target");
                    this.EnsureInstructionContainsAttribute(command, instruction, "value");

                    entity = new ExportEntity()
                    {
                        FileOutput = new FileOutput()
                        {
                            Type        = FileOutputType.Text,
                            TextContent = instruction["value"],
                        },
                    };
                    entity.Values["target"] = instruction["target"];
                    this.exportEntities.Add("COPY_CODE", entity);
                    break;

                case "EMBED_CODE":
                    this.EnsureInstructionContainsAttribute(command, instruction, "value");
                    entity = new ExportEntity()
                    {
                        Value = instruction["value"],
                    };
                    this.exportEntities.Add("EMBED_CODE", entity);
                    break;

                case "DOTNET_LIB":
                    this.EnsureInstructionContainsAttribute(command, instruction, "name");
                    string dotNetLib = instruction["name"];
                    this.DotNetLibs.Add(dotNetLib);
                    break;

                case "DOTNET_DLL":
                    this.EnsureInstructionContainsAttribute(command, instruction, "from");
                    this.EnsureInstructionContainsAttribute(command, instruction, "hintpath");

                    if (instruction.ContainsKey("to"))
                    {
                        throw new InvalidOperationException(
                                  "DOTNET_DLL resource types should not use the 'to' field. " +
                                  "The destination is automatically determined by the hintpath.");
                    }

                    string from = instruction["from"];
                    bool   isExternalDllSource = from.StartsWith("LIB:");

                    entity = new ExportEntity();

                    if (isExternalDllSource)
                    {
                        string[] parts = from.Split(':');
                        if (parts.Length != 3)
                        {
                            throw new InvalidOperationException("DOTNET_DLL from=LIB: references must contain a library name followed by a ':' followed by the resource path in that library.");
                        }
                        string extLibName = parts[1].Trim();
                        from = parts[2];

                        entity.DeferredFileOutputBytesLibraryName = extLibName;
                        entity.DeferredFileOutputBytesLibraryPath = from.Trim();
                    }
                    else
                    {
                        entity.FileOutput = new FileOutput()
                        {
                            Type          = FileOutputType.Binary,
                            BinaryContent = this.library.Metadata.ReadFileBytes("resources/" + from)
                        };
                    }

                    entity.Values["hintpath"] = instruction["hintpath"];
                    foreach (string dllAttr in new string[] {
                        "name", "version", "culture", "token", "architecture", "specificversion"
                    })
                    {
                        if (instruction.ContainsKey(dllAttr))
                        {
                            entity.Values[dllAttr] = instruction[dllAttr];
                        }
                    }
                    this.exportEntities.Add("DOTNET_DLL", entity);
                    break;

                case "LIB_DLL_REF":
                    this.EnsureInstructionContainsAttribute(command, instruction, "name");
                    this.EnsureInstructionContainsAttribute(command, instruction, "version");
                    string name    = instruction["name"];
                    string version = instruction["version"];
                    projectReferenceToGuid[name] = IdGenerator.GenerateCSharpGuid(name + "|" + version, "library-project");
                    break;

                default:
                    throw new InvalidOperationException("The command '" + command + "' is not recongized in the resource manifest of library: '" + this.library.Metadata.ID + "'");
                }
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="ApiResponse{T}" /> class.
 /// </summary>
 /// <param name="statusCode">HTTP status code.</param>
 /// <param name="headers">HTTP headers.</param>
 /// <param name="data">Data (parsed HTTP body)</param>
 public ApiResponse(HttpStatusCode statusCode, Multimap <string, string> headers, T data) : this(statusCode, headers, data, null)
 {
 }
示例#48
0
        private void AddChildTreeNodes(TreeNode <ICategoryNode> parentNode, int parentItemId, Multimap <int, CategoryNode> nodeMap)
        {
            if (parentNode == null)
            {
                return;
            }

            var nodes = nodeMap.ContainsKey(parentItemId)
                ? nodeMap[parentItemId].OrderBy(x => x.DisplayOrder)
                : Enumerable.Empty <CategoryNode>();

            foreach (var node in nodes)
            {
                var newNode = new TreeNode <ICategoryNode>(node)
                {
                    Id = node.Id
                };

                parentNode.Append(newNode);

                AddChildTreeNodes(newNode, node.Id, nodeMap);
            }
        }
示例#49
0
        public virtual async Task RebuildAsync(XmlSitemapBuildContext ctx)
        {
            Guard.NotNull(ctx, nameof(ctx));

            // TODO: (core) Check later if this is still necessary
            //var dataTokens = _httpContextAccessor.HttpContext?.GetRouteData()?.DataTokens;
            //if (dataTokens != null)
            //{
            //    // Double seo code otherwise
            //    dataTokens["CultureCodeReplacement"] = string.Empty;
            //}

            var languageData = new Dictionary <int, LanguageData>();

            foreach (var language in ctx.Languages)
            {
                var lockFilePath = GetLockFilePath(ctx.Store.Id, language.Id);

                if (_lockFileManager.TryAcquireLock(lockFilePath, out var lockFile))
                {
                    // Process only languages that are unlocked right now
                    // It is possible that an HTTP request triggered the generation
                    // of a language specific sitemap.

                    try
                    {
                        var sitemapDir = BuildSitemapDirPath(ctx.Store.Id, language.Id);
                        var data       = new LanguageData
                        {
                            Store        = ctx.Store,
                            Language     = language,
                            LockFile     = lockFile,
                            LockFilePath = lockFilePath,
                            TempDir      = sitemapDir + "~",
                            FinalDir     = sitemapDir,
                            BaseUrl      = await BuildBaseUrlAsync(ctx.Store, language)
                        };

                        _tenantRoot.TryDeleteDirectory(data.TempDir);
                        _tenantRoot.TryCreateDirectory(data.TempDir);

                        languageData[language.Id] = data;
                    }
                    catch
                    {
                        await lockFile.ReleaseAsync();

                        throw;
                    }
                }
            }

            if (languageData.Count == 0)
            {
                Logger.Warn("XML sitemap rebuild already in process.");
                return;
            }

            var languages   = languageData.Values.Select(x => x.Language);
            var languageIds = languages.Select(x => x.Id).Concat(new[] { 0 }).ToArray();

            // All sitemaps grouped by language
            var sitemaps = new Multimap <int, XmlSitemapNode>();

            var compositeFileLock = new AsyncActionDisposable(async() =>
            {
                foreach (var data in languageData.Values)
                {
                    await data.LockFile.ReleaseAsync();
                }
            });

            await using (compositeFileLock)
            {
                // Impersonate
                var prevCustomer = _services.WorkContext.CurrentCustomer;
                // no need to vary xml sitemap by customer roles: it's relevant to crawlers only.
                // TODO: (core) Do not attempt to update CurrentCustomer entity if it is untracked (determine where applicable)
                _services.WorkContext.CurrentCustomer = (await _customerService.GetCustomerBySystemNameAsync(SystemCustomerNames.SearchEngine, false)) ?? prevCustomer;

                try
                {
                    var nodes = new List <XmlSitemapNode>();

                    var providers = CreateProviders(ctx);
                    var total     = await providers.SelectAsync(x => x.GetTotalCountAsync()).SumAsync(ctx.CancellationToken);

                    var totalSegments = (int)Math.Ceiling(total / (double)MaximumSiteMapNodeCount);
                    var hasIndex      = totalSegments > 1;
                    var indexNodes    = new Multimap <int, XmlSitemapNode>();
                    var segment       = 0;
                    var numProcessed  = 0;

                    CheckSitemapCount(totalSegments);

                    using (new DbContextScope(_db, autoDetectChanges: false, forceNoTracking: true, lazyLoading: false))
                    {
                        var entities = EnlistEntitiesAsync(providers);

                        await foreach (var batch in entities.SliceAsync(ctx.CancellationToken, MaximumSiteMapNodeCount))
                        {
                            if (ctx.CancellationToken.IsCancellationRequested)
                            {
                                break;
                            }

                            segment++;
                            numProcessed = segment * MaximumSiteMapNodeCount;
                            ctx.ProgressCallback?.Invoke(numProcessed, total, "{0} / {1}".FormatCurrent(numProcessed, total));

                            var slugs = await GetUrlRecordCollectionsForBatchAsync(batch.Select(x => x.Entry).ToList(), languageIds);

                            foreach (var data in languageData.Values)
                            {
                                var language = data.Language;
                                var baseUrl  = data.BaseUrl;

                                // Create all node entries for this segment
                                var entries = batch
                                              .Where(x => x.Entry.LanguageId.GetValueOrDefault() == 0 || x.Entry.LanguageId.Value == language.Id)
                                              .Select(x => x.Provider.CreateNode(_linkGenerator, baseUrl, x.Entry, slugs[x.Entry.EntityName], language));
                                sitemaps[language.Id].AddRange(entries.Where(x => x != null));

                                // Create index node for this segment/language combination
                                if (hasIndex)
                                {
                                    indexNodes[language.Id].Add(new XmlSitemapNode
                                    {
                                        LastMod = sitemaps[language.Id].Select(x => x.LastMod).Where(x => x.HasValue).DefaultIfEmpty().Max(),
                                        Loc     = GetSitemapIndexUrl(segment, baseUrl),
                                    });
                                }

                                if (segment % 5 == 0 || segment == totalSegments)
                                {
                                    // Commit every 5th segment (10.000 nodes) temporarily to disk to minimize RAM usage
                                    var documents = GetSiteMapDocuments((IReadOnlyCollection <XmlSitemapNode>)sitemaps[language.Id]);
                                    await SaveTempAsync(documents, data, segment - documents.Count + (hasIndex ? 1 : 0));

                                    documents.Clear();
                                    sitemaps.RemoveAll(language.Id);
                                }
                            }

                            slugs.Clear();
                        }

                        // Process custom nodes
                        if (!ctx.CancellationToken.IsCancellationRequested)
                        {
                            ctx.ProgressCallback?.Invoke(numProcessed, total, "Processing custom nodes".FormatCurrent(numProcessed, total));
                            await ProcessCustomNodesAsync(ctx, sitemaps);

                            foreach (var data in languageData.Values)
                            {
                                if (sitemaps.ContainsKey(data.Language.Id) && sitemaps[data.Language.Id].Count > 0)
                                {
                                    var documents = GetSiteMapDocuments((IReadOnlyCollection <XmlSitemapNode>)sitemaps[data.Language.Id]);
                                    await SaveTempAsync(documents, data, (segment + 1) - documents.Count + (hasIndex ? 1 : 0));
                                }
                                else if (segment == 0)
                                {
                                    // Ensure that at least one entry exists. Otherwise,
                                    // the system will try to rebuild again.
                                    var homeNode = new XmlSitemapNode {
                                        LastMod = DateTime.UtcNow, Loc = data.BaseUrl
                                    };
                                    var documents = GetSiteMapDocuments(new List <XmlSitemapNode> {
                                        homeNode
                                    });
                                    await SaveTempAsync(documents, data, 0);
                                }
                            }
                        }
                    }

                    ctx.CancellationToken.ThrowIfCancellationRequested();

                    ctx.ProgressCallback?.Invoke(totalSegments, totalSegments, "Finalizing...'");

                    foreach (var data in languageData.Values)
                    {
                        // Create index documents (if any)
                        if (hasIndex && indexNodes.Any())
                        {
                            var indexDocument = CreateSitemapIndexDocument(indexNodes[data.Language.Id]);
                            await SaveTempAsync(new List <string> {
                                indexDocument
                            }, data, 0);
                        }

                        // Save finally (actually renames temp folder)
                        await SaveFinalAsync(data);
                    }
                }
                finally
                {
                    // Undo impersonation
                    _services.WorkContext.CurrentCustomer = prevCustomer;
                    sitemaps.Clear();

                    foreach (var data in languageData.Values)
                    {
                        if (_tenantRoot.DirectoryExists(data.TempDir))
                        {
                            _tenantRoot.TryDeleteDirectory(data.TempDir);
                        }
                    }
                }
            }
        }
示例#50
0
 public RefreshRegistry()
 {
     handlerTable = HashMultimap.Create();
 }
示例#51
0
 protected virtual Task ProcessCustomNodesAsync(XmlSitemapBuildContext ctx, Multimap <int, XmlSitemapNode> sitemaps)
 {
     // For inheritors
     return(Task.CompletedTask);
 }
 /// <summary>
 ///     Returns any bindings from the specified collection that match the specified service.
 /// </summary>
 /// <param name="bindings">The multimap of all registered bindings.</param>
 /// <param name="service">The service in question.</param>
 /// <returns>The series of matching bindings.</returns>
 public IEnumerable <IBinding> Resolve(Multimap <Type, IBinding> bindings, Type service)
 {
     return(bindings[service].ToEnumerable());
 }
示例#53
0
        public virtual IDictionary <string, ByteWrapper> toFileParams()
        {
            Multimap <string, ByteWrapper> @params = ArrayListMultimap.create <string, ByteWrapper>();

            return(@params);
        }
示例#54
0
        public virtual ICollection <ProductVariantAttributeValue> ParseProductVariantAttributeValues(Multimap <int, string> attributeCombination, IEnumerable <ProductVariantAttribute> attributes)
        {
            var result = new HashSet <ProductVariantAttributeValue>();

            if (attributeCombination == null || !attributeCombination.Any())
            {
                return(result);
            }

            var allValueIds = new HashSet <int>();

            foreach (var pva in attributes.Where(x => x.ShouldHaveValues()).OrderBy(x => x.DisplayOrder).ToArray())
            {
                if (attributeCombination.ContainsKey(pva.Id))
                {
                    var pvaValuesStr = attributeCombination[pva.Id];
                    var ids          = pvaValuesStr.Where(x => x.HasValue()).Select(x => x.ToInt());

                    allValueIds.UnionWith(ids);
                }
            }

            foreach (int id in allValueIds)
            {
                foreach (var attribute in attributes)
                {
                    var attributeValue = attribute.ProductVariantAttributeValues.FirstOrDefault(x => x.Id == id);
                    if (attributeValue != null)
                    {
                        result.Add(attributeValue);
                        break;
                    }
                }
            }

            return(result);
        }
示例#55
0
        public async Task <IEnumerable <WidgetInvoker> > GetWidgetsAsync(string zone, object model = null)
        {
            Guard.NotEmpty(zone, nameof(zone));

            var storeId = _storeContext.CurrentStore.Id;

            #region Module Widgets

            var widgets = _widgetService.LoadActiveWidgetsByWidgetZone(zone, storeId)
                          .Select(x => x.Value.GetDisplayWidget(zone, model, storeId))
                          .Where(x => x != null);

            #endregion

            #region Topic Widgets

            // Get topic widgets from STATIC cache
            var allTopicsCacheKey = string.Format(TOPIC_WIDGET_ALL_MODEL_KEY, storeId, _workContext.WorkingLanguage.Id, _workContext.CurrentCustomer.GetRolesIdent());

            var topicWidgets = await _cache.GetAsync(allTopicsCacheKey, async() =>
            {
                var allTopicWidgets = await _db.Topics
                                      .AsNoTracking()
                                      .ApplyStandardFilter(customerRoleIds: _workContext.CurrentCustomer.GetRoleIds(), storeId: storeId)
                                      .Where(x => x.RenderAsWidget)
                                      .ToListAsync();

                var stubs = allTopicWidgets
                            .Select(t =>
                {
                    var locTitle = t.GetLocalized(x => t.Title);
                    var locBody  = t.GetLocalized(x => t.Body, detectEmptyHtml: false);

                    return(new TopicWidget
                    {
                        Id = t.Id,
                        Bordered = t.WidgetBordered,
                        WrapContent = !t.WidgetWrapContent.HasValue || t.WidgetWrapContent.Value,
                        ShowTitle = t.WidgetShowTitle,
                        SystemName = t.SystemName.SanitizeHtmlId(),
                        ShortTitle = t.GetLocalized(x => x.ShortTitle),
                        Title = locTitle,
                        TitleRtl = locTitle.CurrentLanguage.Rtl,
                        Intro = t.GetLocalized(x => x.Intro),
                        Body = locBody,
                        BodyRtl = locBody.CurrentLanguage.Rtl,
                        TitleTag = t.TitleTag,
                        WidgetZones = t.GetWidgetZones().ToArray(),
                        Priority = t.Priority,
                        CookieType = t.CookieType
                    });
                })
                            .OrderBy(t => t.Priority)
                            .ToList();

                return(stubs);
            });

            // Save widgets to zones map in request cache
            var topicsByZone = _requestCache.Get(ByZoneTopicsCacheKey, () =>
            {
                var map = new Multimap <string, TopicWidgetInvoker>(StringComparer.OrdinalIgnoreCase);

                foreach (var topicWidget in topicWidgets)
                {
                    var zones = topicWidget.WidgetZones;
                    if (zones != null && zones.Any())
                    {
                        foreach (var zone in zones)
                        {
                            var topicWidgetInvoker = new TopicWidgetInvoker(topicWidget);
                            map.Add(zone, topicWidgetInvoker);
                        }
                    }
                }

                return(map);
            });

            if (topicsByZone.ContainsKey(zone))
            {
                widgets = widgets.Concat(topicsByZone[zone]);
            }

            #endregion

            #region Request scoped widgets (provided by IWidgetProvider)

            widgets = widgets.Concat(_widgetProvider.GetWidgets(zone));

            #endregion

            widgets = widgets
                      .Distinct()
                      .OrderBy(x => x.Prepend)
                      .ThenBy(x => x.Order);

            return(widgets);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="CustomerApiException"/> class.
        /// </summary>
        /// <param name="errorCode">HTTP status code.</param>
        /// <param name="message">Error message.</param>
        /// <param name="errorContent">Error content.</param>
        /// <param name="headers">HTTP headers.</param>
        /// <param name="cookies">HTTP cookies.</param>
        public CustomApiException(int errorCode, string message, dynamic errorContent, Multimap <string, string> headers, List <Cookie> cookies) : base(errorCode, message, (object)errorContent)
        {
            Headers = headers;
            Cookies = cookies;
            Limits  = new XeroLimits(Headers);
            switch (errorCode)
            {
            case 401:
                TokenError = true;
                break;

            case 429:
                LimitReached = true;
                break;
            }
        }
示例#57
0
 public IEnumerable <IBinding> Resolve(Multimap <Type, IBinding> bindings, Type service)
 {
     return(this.proxyStore.GetProxies(service));
 }
        public virtual PriceCalculationContext CreatePriceCalculationContext(
            IEnumerable <Product> products = null,
            Customer customer  = null,
            int?storeId        = null,
            bool includeHidden = true)
        {
            customer ??= _workContext.CurrentCustomer;
            storeId ??= _storeContext.CurrentStore.Id;

            async Task <Multimap <int, ProductVariantAttribute> > attributesFactory(int[] ids)
            {
                var attributes = await _db.ProductVariantAttributes
                                 .AsNoTracking()
                                 .Include(x => x.ProductAttribute)
                                 .Include(x => x.ProductVariantAttributeValues)
                                 .Where(x => ids.Contains(x.ProductId))
                                 .OrderBy(x => x.ProductId)
                                 .ThenBy(x => x.DisplayOrder)
                                 .ToListAsync();

                return(attributes.ToMultimap(x => x.ProductId, x => x));
            }

            async Task <Multimap <int, ProductVariantAttributeCombination> > attributeCombinationsFactory(int[] ids)
            {
                var attributeCombinations = await _db.ProductVariantAttributeCombinations
                                            .AsNoTracking()
                                            .Where(x => ids.Contains(x.ProductId))
                                            .OrderBy(x => x.ProductId)
                                            .ToListAsync();

                return(attributeCombinations.ToMultimap(x => x.ProductId, x => x));
            }

            async Task <Multimap <int, TierPrice> > tierPriceFactory(int[] ids)
            {
                var tierPrices = await _db.TierPrices
                                 .AsNoTracking()
                                 .Include(x => x.CustomerRole)
                                 .Where(x => ids.Contains(x.ProductId) && (x.StoreId == 0 || x.StoreId == storeId.Value))
                                 .ToListAsync();

                return(tierPrices
                       // Sorting locally is most likely faster.
                       .OrderBy(x => x.ProductId)
                       .ThenBy(x => x.Quantity)
                       .FilterForCustomer(customer)
                       .ToMultimap(x => x.ProductId, x => x));
            }

            async Task <Multimap <int, ProductCategory> > productCategoriesFactory(int[] ids)
            {
                var productCategories = await _categoryService.GetProductCategoriesByProductIdsAsync(ids, includeHidden);

                return(productCategories.ToMultimap(x => x.ProductId, x => x));
            }

            async Task <Multimap <int, ProductManufacturer> > productManufacturersFactory(int[] ids)
            {
                var productManufacturers = await _manufacturerService.GetProductManufacturersByProductIdsAsync(ids, includeHidden);

                return(productManufacturers.ToMultimap(x => x.ProductId, x => x));
            }

            async Task <Multimap <int, Discount> > appliedDiscountsFactory(int[] ids)
            {
                var discounts = await _db.Products
                                .AsNoTracking()
                                .Include(x => x.AppliedDiscounts)
                                .ThenInclude(x => x.RuleSets)
                                .Where(x => ids.Contains(x.Id))
                                .Select(x => new
                {
                    ProductId = x.Id,
                    Discounts = x.AppliedDiscounts
                })
                                .ToListAsync();

                var map = new Multimap <int, Discount>();

                discounts.Each(x => map.AddRange(x.ProductId, x.Discounts));

                return(map);
            }

            async Task <Multimap <int, ProductBundleItem> > productBundleItemsFactory(int[] ids)
            {
                var bundleItemsQuery = _db.ProductBundleItem
                                       .AsNoTracking()
                                       .Include(x => x.Product)
                                       .Include(x => x.BundleProduct);

                var query =
                    from pbi in bundleItemsQuery
                    join p in _db.Products.AsNoTracking() on pbi.ProductId equals p.Id
                    where ids.Contains(pbi.BundleProductId) && (includeHidden || (pbi.Published && p.Published))
                    orderby pbi.DisplayOrder
                    select pbi;

                var bundleItems = await query.ToListAsync();

                return(bundleItems.ToMultimap(x => x.BundleProductId, x => x));
            }

            async Task <Multimap <int, Product> > associatedProductsFactory(int[] ids)
            {
                var associatedProducts = await _db.Products
                                         .AsNoTracking()
                                         .ApplyAssociatedProductsFilter(ids, includeHidden)
                                         .ToListAsync();

                return(associatedProducts.ToMultimap(x => x.ParentGroupedProductId, x => x));
            }

            var context = new PriceCalculationContext(products)
            {
                AttributesFactory            = attributesFactory,
                AttributeCombinationsFactory = attributeCombinationsFactory,
                TierPricesFactory            = tierPriceFactory,
                ProductCategoriesFactory     = productCategoriesFactory,
                ProductManufacturersFactory  = productManufacturersFactory,
                AppliedDiscountsFactory      = appliedDiscountsFactory,
                ProductBundleItemsFactory    = productBundleItemsFactory,
                AssociatedProductsFactory    = associatedProductsFactory
            };

            return(context);
        }
 /// <summary>
 /// Returns a stream over all the entries in the multimap.
 /// <para>
 /// This will typically create a stream with duplicate keys.
 ///
 /// </para>
 /// </summary>
 /// @param <K>  the key type </param>
 /// @param <V>  the value type </param>
 /// <param name="multimap">  the multimap to wrap </param>
 /// <returns> a stream over the entries in the multimap </returns>
 public static MapStream <K, V> of <K, V>(Multimap <K, V> multimap)
 {
     return(new MapStream <K, V>(multimap.entries().stream()));
 }