/// <summary>
 /// Adds diagnostics from useSiteDiagnostics into diagnostics and returns True if there were any errors.
 /// </summary>
 internal static bool Add(
     this DiagnosticBag diagnostics,
     CSharpSyntaxNode node,
     HashSet<DiagnosticInfo> useSiteDiagnostics)
 {
     return !useSiteDiagnostics.IsNullOrEmpty() && diagnostics.Add(node.Location, useSiteDiagnostics);
 }
Beispiel #2
0
        private ImmutableArray <NamedTypeSymbol> MakeAcyclicInterfaces(ConsList <TypeSymbol> basesBeingResolved, DiagnosticBag diagnostics)
        {
            var typeKind = this.TypeKind;

            if (typeKind == TypeKind.Enum)
            {
                Debug.Assert(GetDeclaredInterfaces(basesBeingResolved: null).IsEmpty, "Computation skipped for enums");
                return(ImmutableArray <NamedTypeSymbol> .Empty);
            }

            var  declaredInterfaces = GetDeclaredInterfaces(basesBeingResolved: basesBeingResolved);
            bool isInterface        = (typeKind == TypeKind.Interface);

            ArrayBuilder <NamedTypeSymbol> result = isInterface ? ArrayBuilder <NamedTypeSymbol> .GetInstance() : null;

            foreach (var t in declaredInterfaces)
            {
                if (isInterface)
                {
                    if (BaseTypeAnalysis.TypeDependsOn(depends: t, on: this))
                    {
                        result.Add(new ExtendedErrorTypeSymbol(t, LookupResultKind.NotReferencable,
                                                               diagnostics.Add(ErrorCode.ERR_CycleInInterfaceInheritance, Locations[0], this, t)));
                        continue;
                    }
                    else
                    {
                        result.Add(t);
                    }
                }

                HashSet <DiagnosticInfo> useSiteDiagnostics = null;

                if (t.DeclaringCompilation != this.DeclaringCompilation)
                {
                    t.AddUseSiteDiagnostics(ref useSiteDiagnostics);

                    foreach (var @interface in t.AllInterfacesNoUseSiteDiagnostics)
                    {
                        if (@interface.DeclaringCompilation != this.DeclaringCompilation)
                        {
                            @interface.AddUseSiteDiagnostics(ref useSiteDiagnostics);
                        }
                    }
                }

                if (!useSiteDiagnostics.IsNullOrEmpty())
                {
                    diagnostics.Add(Locations[0], useSiteDiagnostics);
                }
            }

            return(isInterface ? result.ToImmutableAndFree() : declaredInterfaces);
        }
        public BoundExpression Convert(TypeSymbol type, BoundExpression arg)
        {
            HashSet <DiagnosticInfo> useSiteDiagnostics = null;
            Conversion c = Compilation.Conversions.ClassifyConversionFromExpression(arg, type, ref useSiteDiagnostics);

            Debug.Assert(useSiteDiagnostics.IsNullOrEmpty());

            // If this happens, we should probably check if the method has ObsoleteAttribute.
            Debug.Assert((object)c.Method == null, "Why are we synthesizing a user-defined conversion after initial binding?");

            return(Convert(type, arg, c));
        }
Beispiel #4
0
        async Task LoadAllReferencedLoggers(
            List <string> apisToExtract,
            ExtractorParameters extractorParameters)
        {
            var serviceDiagnostics = await this.diagnosticClient.GetAllAsync(extractorParameters);

            foreach (var serviceDiagnostic in serviceDiagnostics)
            {
                string loggerId = serviceDiagnostic.Properties.LoggerId;

                var serviceDiagnosticsKey = ParameterNamingHelper.GenerateValidParameterName(serviceDiagnostic.Name, ParameterPrefix.Diagnostic);

                if (!this.Cache.ServiceLevelDiagnosticLoggerBindings.ContainsKey(serviceDiagnosticsKey))
                {
                    this.Cache.ServiceLevelDiagnosticLoggerBindings.Add(serviceDiagnosticsKey, loggerId);
                }
            }

            if (apisToExtract.IsNullOrEmpty())
            {
                this.logger.LogWarning("No apis to extract are passed to {0}", nameof(LoggerExtractor));
                return;
            }

            foreach (string curApiName in apisToExtract)
            {
                var diagnostics = await this.diagnosticClient.GetApiDiagnosticsAsync(curApiName, extractorParameters);

                if (diagnostics.IsNullOrEmpty())
                {
                    this.logger.LogWarning("No diagnostics found for '{0}' api", curApiName);
                    continue;
                }

                var diagnosticLoggerBindings = new HashSet <DiagnosticLoggerBinding>();
                foreach (var diagnostic in diagnostics)
                {
                    diagnosticLoggerBindings.Add(new DiagnosticLoggerBinding
                    {
                        DiagnosticName = ParameterNamingHelper.GenerateValidParameterName(diagnostic.Name, ParameterPrefix.Diagnostic),
                        LoggerId       = diagnostic.Properties.LoggerId
                    });
                }

                if (!diagnosticLoggerBindings.IsNullOrEmpty())
                {
                    this.Cache.ApiDiagnosticLoggerBindings.Add(
                        ParameterNamingHelper.GenerateValidParameterName(curApiName, ParameterPrefix.Api),
                        diagnosticLoggerBindings);
                }
            }
        }
Beispiel #5
0
        public static bool ContainsAttribute([NotNull] this IAttributesOwnerDeclaration declaration, IEnumerable <string> attributeNames)
        {
            var clrTypeNames = new HashSet <ClrTypeName>(attributeNames.Select(x => new ClrTypeName(x)));

            if (clrTypeNames.IsNullOrEmpty())
            {
                return(false);
            }
            return(declaration
                   .AttributesEnumerable
                   .Select(attribute => attribute.Name.Reference.Resolve().DeclaredElement)
                   .OfType <IClass>()
                   .Select(attributeClass => attributeClass.GetClrName())
                   .Any(clrTypeNames.Contains));
        }
        public bool Has(Texture2D tex, HashSet <EAtlasType> types)
        {
            foreach (var v in FloorVariations)
            {
                v.Has(tex, types);
            }
            foreach (var v in WallVariations)
            {
                v.Has(tex, types);
            }

            Edge.Has(tex, types);
            DiagEdge.Has(tex, types);

            return(!types.IsNullOrEmpty());
        }
Beispiel #7
0
        /// <summary>
        /// Create properties
        /// </summary>
        /// <param name="typeBuilder">type builder</param>
        /// <param name="interfaceType">type of the interface to implement</param>
        public static void CreateProperties(TypeBuilder typeBuilder, Type interfaceType)
        {
            // build field for each property and implement these properties
            var propertyInformationCollection = new HashSet <PropertyInfo>();

            GetProperties(interfaceType, propertyInformationCollection);
            if (!propertyInformationCollection.IsNullOrEmpty())
            {
                foreach (var propertyInformation in propertyInformationCollection)
                {
                    var name         = propertyInformation.Name;
                    var fieldName    = CreateName(name);
                    var fieldBuilder = typeBuilder.DefineField(
                        fieldName,
                        propertyInformation.PropertyType,
                        FieldAttributes.Private);
                    var propertyBuilder = typeBuilder.DefineProperty(
                        name,
                        PropertyAttributes.HasDefault,
                        propertyInformation.PropertyType,
                        Type.EmptyTypes);

                    if (propertyInformation.CanRead)
                    {
                        var getMethodReference = propertyInformation.GetGetMethod();
                        var getMethodBuilder   = CreatePropertyMethod(typeBuilder, getMethodReference);
                        var getIlGenerator     = getMethodBuilder.GetILGenerator();
                        getIlGenerator.Emit(OpCodes.Ldarg_0);
                        getIlGenerator.Emit(OpCodes.Ldfld, fieldBuilder);
                        getIlGenerator.Emit(OpCodes.Ret);
                        propertyBuilder.SetGetMethod(getMethodBuilder);
                    }

                    if (propertyInformation.CanWrite)
                    {
                        var setMethodReference = propertyInformation.GetSetMethod();
                        var setMethodBuilder   = CreatePropertyMethod(typeBuilder, setMethodReference);
                        var setIlGenerator     = setMethodBuilder.GetILGenerator();
                        setIlGenerator.Emit(OpCodes.Ldarg_0);
                        setIlGenerator.Emit(OpCodes.Ldarg_1);
                        setIlGenerator.Emit(OpCodes.Stfld, fieldBuilder);
                        setIlGenerator.Emit(OpCodes.Ret);
                        propertyBuilder.SetSetMethod(setMethodBuilder);
                    }
                }
            }
        }
        /// <summary>
        /// This method loads the child products into the checklist for display in the Sale message
        /// </summary>
        /// <param name="childProductsBelongingToUserFrom"></param>
        /// <returns></returns>
        private ICollection <CheckBoxItem> loadChildProductsIntoCheckItems(HashSet <ProductChild> childProductsBelongingToUserFrom)
        {
            List <CheckBoxItem> lst = new List <CheckBoxItem>();

            if (childProductsBelongingToUserFrom.IsNullOrEmpty())
            {
                return(lst);
            }

            foreach (ProductChild productChild in childProductsBelongingToUserFrom)
            {
                CheckBoxItem chkBx = new CheckBoxItem(productChild);
                lst.Add(chkBx);
            }

            return(lst);
        }
Beispiel #9
0
        internal void FinishDataReaderMap <TModel>(IDictionary <string, string> bindings, HashSet <string> ignoreMembers, bool useStandardCodeStyleForMembers)
            where TModel : class, new()
        {
            if (!bindings.IsNullOrEmpty())
            {
                CasheDataReaderProvider <TModel> .SetBindingsConfiguration(bindings);
            }

            if (!ignoreMembers.IsNullOrEmpty())
            {
                CasheDataReaderProvider <TModel> .SetBindingsConfiguration(ignoreMembers);
            }

            if (useStandardCodeStyleForMembers)
            {
                CasheDataReaderProvider <TModel> .UseStandardCodeStyleForMembers(true);
            }
        }
        private BoundExpression ConvertIndex(BoundExpression expr, TypeSymbol oldType, TypeSymbol newType)
        {
            HashSet <DiagnosticInfo> useSiteDiagnostics = null;
            var kind = _bound.Compilation.Conversions.ClassifyConversionFromType(oldType, newType, ref useSiteDiagnostics).Kind;

            Debug.Assert(useSiteDiagnostics.IsNullOrEmpty());
            switch (kind)
            {
            case ConversionKind.Identity:
                return(expr);

            case ConversionKind.ExplicitNumeric:
                return(Convert(expr, newType, true));

            default:
                return(Convert(expr, _int32Type, false));
            }
        }
Beispiel #11
0
        internal static List <GUID> FilterReferencesForAsset(IDependencyData dependencyData, GUID asset, List <ObjectIdentifier> references, HashSet <ObjectIdentifier> previousSceneObjects = null)
        {
            var referencedAssets = new HashSet <AssetLoadInfo>();
            var referencesPruned = new List <ObjectIdentifier>(references.Count);

            // Remove Default Resources and Includes for Assets assigned to Bundles
            foreach (ObjectIdentifier reference in references)
            {
                if (reference.filePath.Equals(CommonStrings.UnityDefaultResourcePath, StringComparison.OrdinalIgnoreCase))
                {
                    continue;
                }
                if (dependencyData.AssetInfo.TryGetValue(reference.guid, out AssetLoadInfo referenceInfo))
                {
                    referencedAssets.Add(referenceInfo);
                    continue;
                }
                referencesPruned.Add(reference);
            }
            references.Clear();
            references.AddRange(referencesPruned);

            var referencedAssetsGuids = new List <GUID>(referencedAssets.Count);

            // Remove References also included by non-circular Referenced Assets
            // Remove References also included by circular Referenced Assets if Asset's GUID is higher than Referenced Asset's GUID
            foreach (AssetLoadInfo referencedAsset in referencedAssets)
            {
                var  refObjectIdLookup = new HashSet <ObjectIdentifier>(referencedAsset.referencedObjects);
                bool circularRef       = refObjectIdLookup.Select(x => x.guid).Contains(asset);
                if (!circularRef || (circularRef && asset > referencedAsset.asset || asset == referencedAsset.asset))
                {
                    references.RemoveAll(refObjectIdLookup.Contains);
                }
                referencedAssetsGuids.Add(referencedAsset.asset);
            }

            // Special path for scenes, they can use data from previous sharedAssets in the same bundle
            if (!previousSceneObjects.IsNullOrEmpty())
            {
                references.RemoveAll(previousSceneObjects.Contains);
            }
            return(referencedAssetsGuids);
        }
        private ImmutableArray <NamedTypeSymbol> MakeAcyclicInterfaces(ConsList <Symbol> basesBeingResolved, DiagnosticBag diagnostics)
        {
            // NOTE: this is mostly copied from SourceNamedTypeSymbol_Bases.
            var declaredInterfaces = GetDeclaredInterfaces(basesBeingResolved: basesBeingResolved);

            var result = ArrayBuilder <NamedTypeSymbol> .GetInstance();

            foreach (var t in declaredInterfaces)
            {
                if (BaseTypeAnalysis.InterfaceDependsOn(depends: t, on: this))
                {
                    result.Add(new ExtendedErrorTypeSymbol(t, LookupResultKind.NotReferencable,
                                                           diagnostics.Add(ErrorCode.ERR_CycleInInterfaceInheritance, Locations[0], this, t)));
                    continue;
                }
                else
                {
                    result.Add(t);
                }

                HashSet <DiagnosticInfo> useSiteDiagnostics = null;

                if (t.DeclaringCompilation != DeclaringCompilation)
                {
                    t.AddUseSiteDiagnostics(ref useSiteDiagnostics);

                    foreach (var @interface in t.AllInterfacesNoUseSiteDiagnostics)
                    {
                        if (@interface.DeclaringCompilation != DeclaringCompilation)
                        {
                            @interface.AddUseSiteDiagnostics(ref useSiteDiagnostics);
                        }
                    }
                }

                if (!useSiteDiagnostics.IsNullOrEmpty())
                {
                    diagnostics.Add(Locations[0], useSiteDiagnostics);
                }
            }

            return(result.ToImmutableAndFree());
        }
Beispiel #13
0
        private void addFeatureToEveryProductWithMenuPath2(MenuPath2 menuPath2, MenuFeature menuFeature)
        {
            //Now add the feature to every product that has menu1 as its path.
            //first find all the menuMains that contain MenuPath1
            if (menuPath2.MenuPathMains.IsNullOrEmpty())
            {
                return;
            }

            List <MenuPathMain> menuPathMainList = menuPath2.MenuPathMains.ToList();
            //Now get all the products that have theseMenuPaths as their path.
            HashSet <Product> productHashList = new HashSet <Product>();

            foreach (var menuPathMain in menuPathMainList)
            {
                if (!menuPathMain.Products_Fixed.IsNullOrEmpty())
                {
                    List <Product> menuPathMainProductList = menuPathMain.Products_Fixed.ToList();
                    foreach (var prod in menuPathMainProductList)
                    {
                        productHashList.Add(prod);
                    }
                }
            }

            if (productHashList.IsNullOrEmpty())
            {
                return;
            }

            foreach (var prod2 in productHashList)
            {
                ProductFeature pf = new ProductFeature();
                pf.ProductId     = prod2.Id;
                pf.Product       = prod2;
                pf.MenuFeatureId = menuFeature.Id;
                pf.MenuFeature   = menuFeature;
                pf.Name          = menuFeature.Name;

                ProductFeatureBiz.CreateAndSave(pf);
            }
            SaveChanges();
        }
        public BoundReturnStatement Return(BoundExpression expression = null)
        {
            if (expression != null)
            {
                // If necessary, add a conversion on the return expression.
                HashSet <DiagnosticInfo> useSiteDiagnostics = null;
                var conversion = Compilation.Conversions.ClassifyConversion(expression.Type, CurrentMethod.ReturnType, ref useSiteDiagnostics);
                Debug.Assert(useSiteDiagnostics.IsNullOrEmpty());
                Debug.Assert(conversion.Kind != ConversionKind.NoConversion);
                if (conversion.Kind != ConversionKind.Identity)
                {
                    expression = BoundConversion.Synthesized(Syntax, expression, conversion, false, false, ConstantValue.NotAvailable, CurrentMethod.ReturnType);
                }
            }

            return(new BoundReturnStatement(Syntax, expression)
            {
                WasCompilerGenerated = true
            });
        }
    void ClearIfNecessary()
    {
        if (mBasicEdges == null)
        {
            mBasicEdges = new List <BasicEdge>();
        }
        else
        {
            mBasicEdges.Clear();
        }
        if (!mVertices.IsNullOrEmpty())
        {
            mVertices.Clear();
        }
        if (!mEdges.IsNullOrEmpty())
        {
            mEdges.Clear();
        }

        mCentroid = Vector3.zero;
    }
Beispiel #16
0
        public ActionResult ResetPasswordSetNew(Lite <ResetPasswordRequestEntity> rpr)
        {
            using (AuthLogic.Disable())
            {
                ResetPasswordRequestEntity request = rpr.Retrieve();

                var user = request.User;

                var context = user.ApplyChanges(this, UserMapping.ChangePassword, "").Validate();


                HashSet <string> errorNpk  = null;
                HashSet <string> errorNpbk = null;
                context.Errors.TryGetValue(UserMapping.NewPasswordKey, out errorNpk);
                context.Errors.TryGetValue(UserMapping.NewPasswordBisKey, out errorNpbk);

                if (!errorNpk.IsNullOrEmpty() || !errorNpbk.IsNullOrEmpty())
                {
                    ViewData["Title"] = AuthMessage.ChangePassword.NiceToString();
                    ModelState.FromContext(context);
                    return(ResetPasswordSetNewError(request.Id, ""));
                }

                string errorPasswordValidation = UserEntity.OnValidatePassword(Request.Params[UserMapping.NewPasswordKey]);
                if (errorPasswordValidation.HasText())
                {
                    return(ResetPasswordSetNewError(request.Id, errorPasswordValidation));
                }


                using (OperationLogic.AllowSave <UserEntity>())
                {
                    context.Value.Save();
                }
                //remove pending requests
                Database.Query <ResetPasswordRequestEntity>().Where(r => r.User.Email == user.Email && r.Code == request.Code).UnsafeDelete();
            }

            return(RedirectToAction("ResetPasswordSuccess"));
        }
Beispiel #17
0
        public static bool Add(
            this DiagnosticBag diagnostics,
            Location location,
            HashSet <DiagnosticInfo> useSiteDiagnostics)
        {
            if (useSiteDiagnostics.IsNullOrEmpty())
            {
                return(false);
            }

            bool haveErrors = false;

            foreach (var info in useSiteDiagnostics)
            {
                if (info.Severity == DiagnosticSeverity.Error)
                {
                    haveErrors = true;
                }
                diagnostics.Add(info.ToDiagnostic(location));
            }
            return(haveErrors);
        }
        public static string GenerateConstructTarget(IRelationDomain targetDomain, bool useMetamodelInterface)
        {
            StringBuilder stringBuilder = new StringBuilder();
            ISet <string> postPonedSets = new HashSet <string>();

            List <IObjectTemplateExp> objectTemplates = QvtModelExplorer.FindAllObjectTemplates(targetDomain).Where(o => !o.IsAntiTemplate()).ToList();

            foreach (IObjectTemplateExp objectTemplate in objectTemplates)
            {
                IVariable variable = objectTemplate.BindsTo;
                stringBuilder.AppendLine("\n// Contructing " + variable.Name);

                foreach (IPropertyTemplateItem propertyTemplateItem in objectTemplate.Part)
                {
                    string             setStatement           = GenerateSetValue(propertyTemplateItem, variable.Name, (IRelation)targetDomain.Rule, useMetamodelInterface);
                    IVariableExp       targetVariableValue    = propertyTemplateItem.Value as IVariableExp;
                    IObjectTemplateExp targetObjTemplateValue = objectTemplates.FirstOrDefault(o => o.BindsTo == targetVariableValue?.ReferredVariable);
                    bool ok = targetObjTemplateValue == null || objectTemplates.IndexOf(targetObjTemplateValue) < objectTemplates.IndexOf(objectTemplate);

                    if (ok)
                    {
                        stringBuilder.AppendLine(setStatement);
                    }
                    else
                    {
                        postPonedSets.Add(setStatement);
                    }
                }
            }
            if (!postPonedSets.IsNullOrEmpty())
            {
                stringBuilder.AppendLine("// Setting cycling properties");
                foreach (string setStatement in postPonedSets)
                {
                    stringBuilder.AppendLine(setStatement);
                }
            }
            return(stringBuilder.ToString());
        }
Beispiel #19
0
        private List <MenuFeature> getAllMenuFeaturesAsPerProductsMenuPath(IProduct iproduct)
        {
            Product product = iproduct as Product;

            product.IsNullThrowException("Product is null");

            if (product.MenuPathMains.IsNullOrEmpty())
            {
                return(null);
            }

            List <MenuPathMain> menuPathList = product.MenuPathMains.Where(x => x.MetaData.IsDeleted == false).ToList();

            menuPathList.IsNullOrEmptyThrowException("menuPathList is empty");

            HashSet <MenuFeature> menuFeaturesAsPerMenuPaths = new HashSet <MenuFeature>();

            foreach (MenuPathMain mp in menuPathList)
            {
                HashSet <MenuFeature> currCollection = getAllCurrentFeaturesFor(mp);

                if (currCollection.IsNullOrEmpty())
                {
                    continue;
                }

                foreach (MenuFeature mf in currCollection)
                {
                    try
                    {
                        menuFeaturesAsPerMenuPaths.Add(mf);
                    }
                    catch
                    {
                    }
                }
            }
            return(menuFeaturesAsPerMenuPaths.ToList());
        }
Beispiel #20
0
        /// <summary>
        /// Appends diagnostics from useSiteDiagnostics into diagnostics and returns True if there were any errors.
        /// </summary>
        internal static bool AppendUseSiteDiagnostics(
            SyntaxNode node,
            HashSet <DiagnosticInfo> useSiteDiagnostics,
            DiagnosticBag diagnostics)
        {
            if (useSiteDiagnostics.IsNullOrEmpty())
            {
                return(false);
            }

            bool haveErrors = false;

            foreach (var info in useSiteDiagnostics)
            {
                if (info.Severity == DiagnosticSeverity.Error)
                {
                    haveErrors = true;
                }

                Error(diagnostics, info, node);
            }

            return(haveErrors);
        }
        internal static bool Add(
            this DiagnosticBag diagnostics,
            Location location,
            HashSet<DiagnosticInfo> useSiteDiagnostics)
        {
            if (useSiteDiagnostics.IsNullOrEmpty())
            {
                return false;
            }

            bool haveErrors = false;

            foreach (var info in useSiteDiagnostics)
            {
                if (info.Severity == DiagnosticSeverity.Error)
                {
                    haveErrors = true;
                }

                diagnostics.Add(new CSDiagnostic(info, location));
            }

            return haveErrors;
        }
Beispiel #22
0
        public static int LongestContainedRange(List <int> array)
        {
            // unprocessedEntries records the existence of each entry in A.
            var unprocessedEntries = new HashSet <int>(array);

            var maxIntervalSize = 0;

            while (!unprocessedEntries.IsNullOrEmpty())
            {
                using var enumerator = unprocessedEntries.GetEnumerator();
                enumerator.MoveNext();
                var a = enumerator.Current;

                unprocessedEntries.Remove(a);

                // Finds the lower bound of the largest range containing a.
                var lowerBound = a - 1;
                while (unprocessedEntries.Contains(lowerBound))
                {
                    unprocessedEntries.Remove(lowerBound);
                    --lowerBound;
                }

                // Finds the upper bound of the largest range containing a.
                var upperBound = a + 1;
                while (unprocessedEntries.Contains(upperBound))
                {
                    unprocessedEntries.Remove(upperBound);
                    ++upperBound;
                }

                maxIntervalSize = Math.Max(upperBound - lowerBound - 1, maxIntervalSize);
            }

            return(maxIntervalSize);
        }
Beispiel #23
0
        public static T ItemAtIndexLinear <T>(this HashSet <T> set, int index)
        {
            if (set.IsNullOrEmpty() || index >= set.Count)
            {
                return(default(T));
            }

            T   result = default(T);
            int seeker = 0;

            set.ForEach(item =>
            {
                if (seeker == index)
                {
                    result = item;
                    return(true);
                }

                seeker++;
                return(false);
            });

            return(result);
        }
        /// <summary>
        /// Appends diagnostics from useSiteDiagnostics into diagnostics and returns True if there were any errors.
        /// </summary>
        internal static bool AppendUseSiteDiagnostics(
            SyntaxNode node,
            HashSet<DiagnosticInfo> useSiteDiagnostics,
            DiagnosticBag diagnostics)
        {
            if (useSiteDiagnostics.IsNullOrEmpty())
            {
                return false;
            }

            bool haveErrors = false;

            foreach (var info in useSiteDiagnostics)
            {
                if (info.Severity == DiagnosticSeverity.Error)
                {
                    haveErrors = true;
                }

                Error(diagnostics, info, node);
            }

            return haveErrors;
        }
Beispiel #25
0
        private static async Task RefreshTopics()
        {
            await IgnoreErrorsAsync(async() =>
            {
                var topics = new HashSet <string>();
                await ServerConnection.ExecuteNonQuery("DELETE FROM topic");
                foreach (var topic in await ServerConnection.QueryStringList("SELECT DISTINCT topics FROM query WHERE topics IS NOT NULL AND topics != ''"))
                {
                    topics.UnionWith(topic.Split(TopicSeparator, StringSplitOptions.RemoveEmptyEntries));
                }
                if (topics.IsNullOrEmpty())
                {
                    return;
                }

                string sql = "";
                foreach (var topic in topics)
                {
                    sql += $"INSERT INTO topic (name) VALUES ('{topic}');";
                }

                await ServerConnection.ExecuteNonQuery(sql);
            });
        }
Beispiel #26
0
        private NamedTypeSymbol MakeAcyclicBaseType(DiagnosticBag diagnostics)
        {
            var             typeKind    = this.TypeKind;
            var             compilation = this.DeclaringCompilation;
            NamedTypeSymbol declaredBase;

            if (typeKind == TypeKind.Enum)
            {
                Debug.Assert((object)GetDeclaredBaseType(basesBeingResolved: null) == null, "Computation skipped for enums");
                declaredBase = compilation.GetSpecialType(SpecialType.System_Enum);
            }
            else
            {
                declaredBase = GetDeclaredBaseType(basesBeingResolved: null);
            }

            if ((object)declaredBase == null)
            {
                switch (typeKind)
                {
                case TypeKind.Class:

                    if (this.SpecialType == SpecialType.System_Object)
                    {
                        return(null);
                    }

                    declaredBase = compilation.GetSpecialType(SpecialType.System_Object);
                    break;

                case TypeKind.Struct:
                case TypeKind.Interface:
                    return(null);

                case TypeKind.Delegate:
                    declaredBase = compilation.GetSpecialType(SpecialType.System_MulticastDelegate);
                    break;

                default:
                    throw ExceptionUtilities.UnexpectedValue(typeKind);
                }
            }

            if (BaseTypeAnalysis.ClassDependsOn(declaredBase, this))
            {
                return(new ExtendedErrorTypeSymbol(declaredBase, LookupResultKind.NotReferencable,
                                                   diagnostics.Add(ErrorCode.ERR_CircularBase, Locations[0], declaredBase, this)));
            }

            this.SetKnownToHaveNoDeclaredBaseCycles();

            HashSet <DiagnosticInfo> useSiteDiagnostics = null;
            NamedTypeSymbol          current            = declaredBase;

            do
            {
                if (current.DeclaringCompilation == this.DeclaringCompilation)
                {
                    break;
                }

                current.AddUseSiteDiagnostics(ref useSiteDiagnostics);
                current = current.BaseTypeNoUseSiteDiagnostics;
            }while ((object)current != null);

            if (!useSiteDiagnostics.IsNullOrEmpty())
            {
                diagnostics.Add(FindBaseRefSyntax(declaredBase) ?? Locations[0], useSiteDiagnostics);
            }

            return(declaredBase);
        }
    /// <summary>
    /// Performs when action executing.
    /// </summary>
    /// <param name="context"></param>
    /// <param name="next"></param>
    public virtual async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
        if (!context.ModelState.IsValid)
        {
            var httpContext = context.HttpContext;

            IEnumerable <ModelError> modelErrors = context.ModelState.Values.SelectMany(v => v.Errors);

            var errors = new HashSet <string> {
            };

            foreach (var item in modelErrors)
            {
                errors.Add(item.ErrorMessage);
            }


            var properties       = GetProperties(DisabledProperties);
            var nestedProperties = GetProperties(DisabledNestedProperties);

            if (!nestedProperties.IsNullOrEmpty())
            {
                foreach (var nestedProp in nestedProperties)
                {
                    var assembly = Assembly.GetAssembly(AssemblyTypeForNestedProps);

                    var dtoType = assembly?.GetExportedTypes()?.ToList()?.FirstOrDefault(i => i.FullName.Contains(DTOFolderAssemblyName) &&
                                                                                         (i.Name == $"{nestedProp}DTO" ||
                                                                                          i.Name == $"{nestedProp.Remove(nestedProp.Length - 1, 1)}DTO"));
                    if (dtoType != null)
                    {
                        var dtoProps = dtoType.GetProperties().ToList();

                        dtoProps.RemoveAll(i => i.Name.Contains("Id"));

                        foreach (var entityProp in dtoProps)
                        {
                            if (entityProp.CustomAttributes.Count() != 0)
                            {
                                if (httpContext.Items[entityProp.Name] != null)
                                {
                                    errors.Remove(httpContext.Items[entityProp.Name].ToString());
                                }
                            }
                        }
                    }
                }
            }

            if (!properties.IsNullOrEmpty())
            {
                foreach (var prop in properties)
                {
                    if (httpContext.Items[prop] != null)
                    {
                        errors.Remove(httpContext.Items[prop].ToString());
                    }
                }
            }

            if (!errors.IsNullOrEmpty())
            {
                throw new MilvaUserFriendlyException(string.Join("~", errors));
            }
        }

        await next();
    }
Beispiel #28
0
        private static bool AppendUseSiteDiagnostics(
            HashSet<DiagnosticInfo> useSiteDiagnostics,
            TypeParameterSymbol typeParameter,
            ref ArrayBuilder<TypeParameterDiagnosticInfo> useSiteDiagnosticsBuilder)
        {
            if (useSiteDiagnostics.IsNullOrEmpty())
            {
                return false;
            }

            if (useSiteDiagnosticsBuilder == null)
            {
                useSiteDiagnosticsBuilder = new ArrayBuilder<TypeParameterDiagnosticInfo>();
            }

            bool hasErrors = false;

            foreach (var info in useSiteDiagnostics)
            {
                if (info.Severity == DiagnosticSeverity.Error)
                {
                    hasErrors = true;
                }

                useSiteDiagnosticsBuilder.Add(new TypeParameterDiagnosticInfo(typeParameter, info));
            }

            return hasErrors;
        }
        /// <summary>
        /// Select from DOM using index. First non-class/tag/id selector will result in this being passed off to GetMatches
        /// </summary>
        /// <param name="document"></param>
        /// <returns></returns>
        public IEnumerable <IDomObject> Select(IDomDocument document, IEnumerable <IDomObject> context)
        {
            if (Selectors == null)
            {
                throw new ArgumentException("No selectors provided.");
            }
            if (Selectors.Count == 0)
            {
                yield break;
            }
            Document = document;
            IEnumerable <IDomObject> lastResult      = null;
            HashSet <IDomObject>     output          = new HashSet <IDomObject>();
            IEnumerable <IDomObject> selectionSource = context;

            // Disable the index if there is no context (e.g. disconnected elements)
            bool useIndex = context.IsNullOrEmpty() || !context.First().IsDisconnected;

            // Copy the list because it may change during the process
            ActiveSelectors = new List <Selector>(Selectors);

            for (activeSelectorId = 0; activeSelectorId < ActiveSelectors.Count; activeSelectorId++)
            {
                var            selector       = ActiveSelectors[activeSelectorId];
                CombinatorType combinatorType = selector.CombinatorType;
                SelectorType   selectorType   = selector.SelectorType;
                TraversalType  traversalType  = selector.TraversalType;

                // Determine what kind of combining method we will use with previous selection results

                if (activeSelectorId != 0)
                {
                    switch (combinatorType)
                    {
                    case CombinatorType.Cumulative:
                        // do nothing
                        break;

                    case CombinatorType.Root:
                        selectionSource = context;
                        if (lastResult != null)
                        {
                            output.AddRange(lastResult);
                            lastResult = null;
                        }
                        break;

                    case CombinatorType.Chained:
                        selectionSource = lastResult;
                        lastResult      = null;
                        break;
                        // default (chained): leave lastresult alone
                    }
                }

                HashSet <IDomObject>     tempResult    = null;
                IEnumerable <IDomObject> interimResult = null;

                string key = "";
                if (useIndex && !selector.NoIndex)
                {
#if DEBUG_PATH
                    if (type.HasFlag(SelectorType.Attribute))
                    {
                        key   = "!" + selector.AttributeName;
                        type &= ~SelectorType.Attribute;
                        if (selector.AttributeValue != null)
                        {
                            InsertAttributeValueSelector(selector);
                        }
                    }
                    else if (type.HasFlag(SelectorType.Tag))
                    {
                        key   = "+" + selector.Tag;
                        type &= ~SelectorType.Tag;
                    }
                    else if (type.HasFlag(SelectorType.ID))
                    {
                        key   = "#" + selector.ID;
                        type &= ~SelectorType.ID;
                    }
                    else if (type.HasFlag(SelectorType.Class))
                    {
                        key   = "." + selector.Class;
                        type &= ~SelectorType.Class;
                    }
#else
                    if (selectorType.HasFlag(SelectorType.Attribute))
                    {
                        key           = "!" + (char)DomData.TokenID(selector.AttributeName);
                        selectorType &= ~SelectorType.Attribute;
                        if (selector.AttributeValue != null)
                        {
                            InsertAttributeValueSelector(selector);
                        }
                    }
                    else if (selectorType.HasFlag(SelectorType.Tag))
                    {
                        key           = "+" + (char)DomData.TokenID(selector.Tag, true);
                        selectorType &= ~SelectorType.Tag;
                    }
                    else if (selectorType.HasFlag(SelectorType.ID))
                    {
                        key           = "#" + (char)DomData.TokenID(selector.ID);
                        selectorType &= ~SelectorType.ID;
                    }
                    else if (selectorType.HasFlag(SelectorType.Class))
                    {
                        key           = "." + (char)DomData.TokenID(selector.Class);
                        selectorType &= ~SelectorType.Class;
                    }
#endif
                }

                // If part of the selector was indexed, key will not be empty. Return initial set from the
                // index. If any selectors remain after this they will be searched the hard way.

                if (key != String.Empty)
                {
                    int  depth       = 0;
                    bool descendants = true;

                    switch (traversalType)
                    {
                    case TraversalType.Child:
                        depth       = selector.ChildDepth;;
                        descendants = false;
                        break;

                    case TraversalType.Filter:
                        depth       = 0;
                        descendants = false;
                        break;

                    case TraversalType.Descendent:
                        depth       = 1;
                        descendants = true;
                        break;
                    }

                    if (selectionSource == null)
                    {
                        interimResult = document.QueryIndex(key + DomData.indexSeparator, depth, descendants);
                    }
                    else
                    {
                        interimResult = new HashSet <IDomObject>();
                        foreach (IDomObject obj in selectionSource)
                        {
                            ((HashSet <IDomObject>)interimResult)
                            .AddRange(document.QueryIndex(key + DomData.indexSeparator + obj.Path,
                                                          depth, descendants));
                        }
                    }
                }
                else if (selectorType.HasFlag(SelectorType.Elements))
                {
                    selectorType &= ~SelectorType.Elements;
                    HashSet <IDomObject> source = new HashSet <IDomObject>(selectionSource);
                    interimResult = new HashSet <IDomObject>();

                    foreach (IDomObject obj in selectionSource)
                    {
                        key = DomData.indexSeparator + obj.Path;
                        HashSet <IDomObject> srcKeys = new HashSet <IDomObject>(document.QueryIndex(key));
                        foreach (IDomObject match in selector.SelectElements)
                        {
                            if (srcKeys.Contains(match))
                            {
                                ((HashSet <IDomObject>)interimResult).Add(match);
                            }
                        }
                    }
                }
                // TODO - GetMatch should work if passed with no selectors (returning nothing), now it returns everything
                // 12/10/11 - this todo is not verified, much has changed since it was written. TODO confirm this and
                // fix if needed. If having the conversation with self again, remove comments and forget it. This is
                // an example of why comments can do more harm than good.

                if ((selectorType & ~(SelectorType.SubSelectorNot | SelectorType.SubSelectorHas)) != 0)
                {
                    IEnumerable <IDomObject> finalSelectWithin =
                        interimResult
                        ?? (combinatorType == CombinatorType.Chained ? lastResult : null)
                        ?? selectionSource
                        ?? document.ChildElements;

                    // if there are no temporary results (b/c there was no indexed selector) then use the whole set
                    interimResult = GetMatches(finalSelectWithin, selector);
                }

                // Deal with subselectors: has() and not() test for the presence of a selector within the children of
                // an element. This is essentially similar to the manual selection above.

                if (selectorType.HasFlag(SelectorType.SubSelectorHas) ||
                    selectorType.HasFlag(SelectorType.SubSelectorNot))
                {
                    bool isHasSelector = selectorType.HasFlag(SelectorType.SubSelectorHas);

                    IEnumerable <IDomObject> subSelectWithin = interimResult
                                                               ?? (combinatorType == CombinatorType.Chained ? lastResult : null)
                                                               ?? selectionSource;

                    // subselects are a filter. start a new interim result.

                    HashSet <IDomObject> filteredResults = new HashSet <IDomObject>();

                    foreach (IDomObject obj in subSelectWithin)
                    {
                        bool match = true;
                        foreach (var sub in selector.SubSelectors)
                        {
                            List <IDomObject> listOfOne = new List <IDomObject>();
                            listOfOne.Add(obj);

                            bool has = !sub.Select(document, listOfOne).IsNullOrEmpty();

                            match &= isHasSelector == has;
                        }
                        if (match)
                        {
                            filteredResults.Add(obj);
                        }
                    }
                    interimResult = filteredResults;
                }
                tempResult = new HashSet <IDomObject>();
                if (lastResult != null)
                {
                    tempResult.AddRange(lastResult);
                }
                if (interimResult != null)
                {
                    tempResult.AddRange(interimResult);
                }
                lastResult = tempResult;
            }


            if (lastResult != null)
            {
                output.AddRange(lastResult);
            }

            if (output.IsNullOrEmpty())
            {
                yield break;
            }
            else
            {
                // Selectors always return in DOM order. Selections may end up in a different order but
                // we always sort here.

                foreach (IDomObject item in output.OrderBy(item => item.Path, StringComparer.Ordinal))
                {
                    yield return(item);
                }
            }
            ActiveSelectors.Clear();
        }
Beispiel #30
0
        private BoundForEachStatement BindForEachPartsWorker(DiagnosticBag diagnostics, Binder originalBinder)
        {
            BoundExpression collectionExpr = this.Next.BindValue(_syntax.Expression, diagnostics, BindValueKind.RValue); //bind with next to avoid seeing iteration variable

            ForEachEnumeratorInfo.Builder builder = new ForEachEnumeratorInfo.Builder();
            TypeSymbol inferredType;
            bool       hasErrors = !GetEnumeratorInfoAndInferCollectionElementType(ref builder, ref collectionExpr, diagnostics, out inferredType);

            // These should only occur when special types are missing or malformed.
            hasErrors = hasErrors ||
                        (object)builder.GetEnumeratorMethod == null ||
                        (object)builder.MoveNextMethod == null ||
                        (object)builder.CurrentPropertyGetter == null;

            // Check for local variable conflicts in the *enclosing* binder; obviously the *current*
            // binder has a local that matches!
            var hasNameConflicts = this.ValidateDeclarationNameConflictsInScope(IterationVariable, diagnostics);

            // If the type in syntax is "var", then the type should be set explicitly so that the
            // Type property doesn't fail.

            TypeSyntax typeSyntax = _syntax.Type;

            bool        isVar;
            AliasSymbol alias;
            TypeSymbol  declType = BindType(typeSyntax, diagnostics, out isVar, out alias);

            TypeSymbol iterationVariableType;

            if (isVar)
            {
                iterationVariableType = inferredType ?? CreateErrorType("var");
            }
            else
            {
                Debug.Assert((object)declType != null);
                iterationVariableType = declType;
            }


            BoundTypeExpression boundIterationVariableType = new BoundTypeExpression(typeSyntax, alias, iterationVariableType);

            this.IterationVariable.SetTypeSymbol(iterationVariableType);

            BoundStatement body = originalBinder.BindPossibleEmbeddedStatement(_syntax.Statement, diagnostics);

            hasErrors = hasErrors || iterationVariableType.IsErrorType();

            // Skip the conversion checks and array/enumerator differentiation if we know we have an error (except local name conflicts).
            if (hasErrors)
            {
                return(new BoundForEachStatement(
                           _syntax,
                           null, // can't be sure that it's complete
                           default(Conversion),
                           boundIterationVariableType,
                           this.IterationVariable,
                           collectionExpr,
                           body,
                           CheckOverflowAtRuntime,
                           this.BreakLabel,
                           this.ContinueLabel,
                           hasErrors));
            }

            hasErrors |= hasNameConflicts;

            var foreachKeyword = _syntax.ForEachKeyword;

            ReportDiagnosticsIfObsolete(diagnostics, builder.GetEnumeratorMethod, foreachKeyword, hasBaseReceiver: false);
            ReportDiagnosticsIfObsolete(diagnostics, builder.MoveNextMethod, foreachKeyword, hasBaseReceiver: false);
            ReportDiagnosticsIfObsolete(diagnostics, builder.CurrentPropertyGetter, foreachKeyword, hasBaseReceiver: false);
            ReportDiagnosticsIfObsolete(diagnostics, builder.CurrentPropertyGetter.AssociatedSymbol, foreachKeyword, hasBaseReceiver: false);

            // We want to convert from inferredType in the array/string case and builder.ElementType in the enumerator case,
            // but it turns out that these are equivalent (when both are available).

            HashSet <DiagnosticInfo> useSiteDiagnostics = null;
            Conversion elementConversion = this.Conversions.ClassifyConversionForCast(inferredType, iterationVariableType, ref useSiteDiagnostics);

            if (!elementConversion.IsValid)
            {
                ImmutableArray <MethodSymbol> originalUserDefinedConversions = elementConversion.OriginalUserDefinedConversions;
                if (originalUserDefinedConversions.Length > 1)
                {
                    diagnostics.Add(ErrorCode.ERR_AmbigUDConv, _syntax.ForEachKeyword.GetLocation(), originalUserDefinedConversions[0], originalUserDefinedConversions[1], inferredType, iterationVariableType);
                }
                else
                {
                    SymbolDistinguisher distinguisher = new SymbolDistinguisher(this.Compilation, inferredType, iterationVariableType);
                    diagnostics.Add(ErrorCode.ERR_NoExplicitConv, _syntax.ForEachKeyword.GetLocation(), distinguisher.First, distinguisher.Second);
                }
                hasErrors = true;
            }
            else
            {
                ReportDiagnosticsIfObsolete(diagnostics, elementConversion, _syntax.ForEachKeyword, hasBaseReceiver: false);
            }

            // Spec (§8.8.4):
            // If the type X of expression is dynamic then there is an implicit conversion from >>expression<< (not the type of the expression)
            // to the System.Collections.IEnumerable interface (§6.1.8).
            builder.CollectionConversion = this.Conversions.ClassifyConversionFromExpression(collectionExpr, builder.CollectionType, ref useSiteDiagnostics);
            builder.CurrentConversion    = this.Conversions.ClassifyConversion(builder.CurrentPropertyGetter.ReturnType, builder.ElementType, ref useSiteDiagnostics);

            builder.EnumeratorConversion = this.Conversions.ClassifyConversion(builder.GetEnumeratorMethod.ReturnType, GetSpecialType(SpecialType.System_Object, diagnostics, _syntax), ref useSiteDiagnostics);

            diagnostics.Add(_syntax.ForEachKeyword.GetLocation(), useSiteDiagnostics);

            // Due to the way we extracted the various types, these conversions should always be possible.
            // CAVEAT: if we're iterating over an array of pointers, the current conversion will fail since we
            // can't convert from object to a pointer type.  Similarly, if we're iterating over an array of
            // Nullable<Error>, the current conversion will fail because we don't know if an ErrorType is a
            // value type.  This doesn't matter in practice, since we won't actually use the enumerator pattern
            // when we lower the loop.
            Debug.Assert(builder.CollectionConversion.IsValid);
            Debug.Assert(builder.CurrentConversion.IsValid ||
                         (builder.ElementType.IsPointerType() && collectionExpr.Type.IsArray()) ||
                         (builder.ElementType.IsNullableType() && builder.ElementType.GetMemberTypeArgumentsNoUseSiteDiagnostics().Single().IsErrorType() && collectionExpr.Type.IsArray()));
            Debug.Assert(builder.EnumeratorConversion.IsValid ||
                         this.Compilation.GetSpecialType(SpecialType.System_Object).TypeKind == TypeKind.Error ||
                         !useSiteDiagnostics.IsNullOrEmpty(),
                         "Conversions to object succeed unless there's a problem with the object type or the source type");

            // If user-defined conversions could occur here, we would need to check for ObsoleteAttribute.
            Debug.Assert((object)builder.CollectionConversion.Method == null,
                         "Conversion from collection expression to collection type should not be user-defined");
            Debug.Assert((object)builder.CurrentConversion.Method == null,
                         "Conversion from Current property type to element type should not be user-defined");
            Debug.Assert((object)builder.EnumeratorConversion.Method == null,
                         "Conversion from GetEnumerator return type to System.Object should not be user-defined");

            // We're wrapping the collection expression in a (non-synthesized) conversion so that its converted
            // type (i.e. builder.CollectionType) will be available in the binding API.
            BoundConversion convertedCollectionExpression = new BoundConversion(
                collectionExpr.Syntax,
                collectionExpr,
                builder.CollectionConversion,
                CheckOverflowAtRuntime,
                false,
                ConstantValue.NotAvailable,
                builder.CollectionType);

            return(new BoundForEachStatement(
                       _syntax,
                       builder.Build(this.Flags),
                       elementConversion,
                       boundIterationVariableType,
                       this.IterationVariable,
                       convertedCollectionExpression,
                       body,
                       CheckOverflowAtRuntime,
                       this.BreakLabel,
                       this.ContinueLabel,
                       hasErrors));
        }
Beispiel #31
0
        public void IsNullOrEmpty_EmptyCollectionGiven_ShouldReturnTrue()
        {
            ICollection <int> input = new HashSet <int>();

            Assert.True(input.IsNullOrEmpty());
        }
Beispiel #32
0
    /// <summary>
    /// Performs when action executing.
    /// </summary>
    /// <param name="context"></param>
    public override void OnActionExecuting(ActionExecutingContext context)
    {
        async Task <ActionExecutingContext> RewriteResponseAsync(string message)
        {
            var validationResponse = new ExceptionResponse
            {
                Success    = false,
                Message    = message,
                StatusCode = MilvaStatusCodes.Status600Exception,
                Result     = new object(),
                ErrorCodes = new List <int>()
            };
            var json = JsonConvert.SerializeObject(validationResponse);

            context.HttpContext.Response.ContentType = "application/json";
            context.HttpContext.Items.Add(new KeyValuePair <object, object>("StatusCode", MilvaStatusCodes.Status600Exception));
            context.HttpContext.Response.StatusCode = MilvaStatusCodes.Status200OK;
            await context.HttpContext.Response.WriteAsync(json).ConfigureAwait(false);

            context.Result = new OkResult();

            return(context);
        };

        if (!context.ModelState.IsValid)
        {
            var httpContext = context.HttpContext;

            IEnumerable <ModelError> modelErrors = context.ModelState.Values.SelectMany(v => v.Errors);

            var errors = new HashSet <string> {
            };

            foreach (var item in modelErrors)
            {
                errors.Add(item.ErrorMessage);
            }

            var properties       = GetProperties(DisabledProperties);
            var nestedProperties = GetProperties(DisabledNestedProperties);

            if (!nestedProperties.IsNullOrEmpty())
            {
                foreach (var nestedProp in nestedProperties)
                {
                    var assembly = Assembly.GetAssembly(AssemblyTypeForNestedProps);

                    var dtoType = assembly?.GetExportedTypes()?.ToList()?.FirstOrDefault(i => i.FullName.Contains(DTOFolderAssemblyName) &&
                                                                                         (i.Name == $"{nestedProp}DTO" ||
                                                                                          i.Name == $"{nestedProp.Remove(nestedProp.Length - 1, 1)}DTO"));
                    if (dtoType != null)
                    {
                        var dtoProps = dtoType.GetProperties().ToList();

                        dtoProps.RemoveAll(i => i.Name.Contains("Id"));

                        foreach (var entityProp in dtoProps)
                        {
                            if (entityProp.CustomAttributes.Count() != 0)
                            {
                                if (httpContext.Items[entityProp.Name] != null)
                                {
                                    errors.Remove(httpContext.Items[entityProp.Name].ToString());
                                    httpContext.Items.Remove(entityProp.Name);
                                }
                            }
                        }
                    }
                }
            }

            if (!properties.IsNullOrEmpty())
            {
                foreach (var prop in properties)
                {
                    if (httpContext.Items[prop] != null)
                    {
                        errors.Remove(httpContext.Items[prop].ToString());
                        httpContext.Items.Remove(prop);
                    }
                }
            }

            if (!errors.IsNullOrEmpty())
            {
                base.OnActionExecuting(RewriteResponseAsync(string.Join("~", errors)).Result);
            }
        }
    }
        private List <string> joinCurrPicsAndPictureAddresses(List <string> pictureAddresses, List <string> currPcs)
        {
            if (!currPcs.IsNullOrEmpty())
            {
                currPcs.Remove(UploadedFile.DefaultBlankPictureLocation());
            }

            if (!pictureAddresses.IsNullOrEmpty())
            {
                pictureAddresses.Remove(UploadedFile.DefaultBlankPictureLocation());
            }

            if (currPcs.IsNullOrEmpty())
            {
                if (pictureAddresses.IsNullOrEmpty())
                {
                }
                else
                {
                    pictureAddresses = pictureAddresses.Concat(currPcs).ToList();
                }
            }
            else
            {
                if (pictureAddresses.IsNullOrEmpty())
                {
                    pictureAddresses = currPcs;
                }
                else
                {
                    //remove currPcs from pictureAddress
                    //remove duplicates from CurrPic
                    int returnNoOfPictures = MenuPath1.MaxNumberOfPicturesInMenu() + 1;
                    currPcs = new HashSet <string>(currPcs).ToList();

                    if (!currPcs.IsNullOrEmpty())
                    {
                        foreach (string currPic in currPcs)
                        {
                            pictureAddresses.Remove(currPic);
                        }
                    }

                    if (pictureAddresses.IsNullOrEmpty())
                    {
                        return(currPcs);
                    }

                    //now currPcs has its own pics
                    //and picture address has its own


                    if (currPcs.Count >= returnNoOfPictures)
                    {
                        return(currPcs.GetRange(0, returnNoOfPictures));
                    }
                    else
                    {
                        int noOfPicsRequried = returnNoOfPictures - currPcs.Count;

                        //if there are more pics in picture address than required....
                        if (pictureAddresses.Count >= noOfPicsRequried)
                        {
                            pictureAddresses = getRandomPictures(pictureAddresses);
                            pictureAddresses = pictureAddresses.GetRange(0, noOfPicsRequried);
                        }

                        pictureAddresses = pictureAddresses.Concat(currPcs).ToList();
                        pictureAddresses = new HashSet <string>(pictureAddresses).ToList();
                    }
                }
            }

            return(pictureAddresses);
        }
Beispiel #34
0
        internal static BoundCall GenerateObjectConstructorInitializer(MethodSymbol constructor, DiagnosticBag diagnostics)
        {
            NamedTypeSymbol objectType = constructor.ContainingType.BaseTypeNoUseSiteDiagnostics;

            Debug.Assert(objectType.SpecialType == SpecialType.System_Object);
            MethodSymbol     objectConstructor = null;
            LookupResultKind resultKind        = LookupResultKind.Viable;

            foreach (MethodSymbol objectCtor in objectType.InstanceConstructors)
            {
                if (objectCtor.ParameterCount == 0)
                {
                    objectConstructor = objectCtor;
                    break;
                }
            }

            // UNDONE: If this happens then something is deeply wrong. Should we give a better error?
            if ((object)objectConstructor == null)
            {
                diagnostics.Add(ErrorCode.ERR_BadCtorArgCount, constructor.Locations[0], objectType, /*desired param count*/ 0);
                return(null);
            }

            // UNDONE: If this happens then something is deeply wrong. Should we give a better error?
            bool hasErrors = false;
            HashSet <DiagnosticInfo> useSiteDiagnostics = null;

            if (!AccessCheck.IsSymbolAccessible(objectConstructor, constructor.ContainingType, ref useSiteDiagnostics))
            {
                diagnostics.Add(ErrorCode.ERR_BadAccess, constructor.Locations[0], objectConstructor);
                resultKind = LookupResultKind.Inaccessible;
                hasErrors  = true;
            }

            if (!useSiteDiagnostics.IsNullOrEmpty())
            {
                diagnostics.Add(constructor.Locations.IsEmpty ? NoLocation.Singleton : constructor.Locations[0], useSiteDiagnostics);
            }

            CSharpSyntaxNode syntax = constructor.GetNonNullSyntaxNode();

            BoundExpression receiver = new BoundThisReference(syntax, constructor.ContainingType)
            {
                WasCompilerGenerated = true
            };

            return(new BoundCall(
                       syntax: syntax,
                       receiverOpt: receiver,
                       method: objectConstructor,
                       arguments: ImmutableArray <BoundExpression> .Empty,
                       argumentNamesOpt: ImmutableArray <string> .Empty,
                       argumentRefKindsOpt: ImmutableArray <RefKind> .Empty,
                       isDelegateCall: false,
                       expanded: false,
                       invokedAsExtensionMethod: false,
                       argsToParamsOpt: ImmutableArray <int> .Empty,
                       resultKind: resultKind,
                       type: objectType,
                       hasErrors: hasErrors)
            {
                WasCompilerGenerated = true
            });
        }
        /// <summary>
        /// Select from DOM using index. First non-class/tag/id selector will result in this being passed off to GetMatches
        /// </summary>
        /// <param name="document"></param>
        /// <returns></returns>
        public IEnumerable<IDomObject> Select(IDomDocument document, IEnumerable<IDomObject> context)
        {
            if (Selectors == null )
            {
                throw new ArgumentException("No selectors provided.");
            }
            if (Selectors.Count == 0)
            {
                yield break;
            }
            Document = document;
            IEnumerable<IDomObject> lastResult = null;
            HashSet<IDomObject> output = new HashSet<IDomObject>();
            IEnumerable<IDomObject> selectionSource = context;

            // Disable the index if there is no context (e.g. disconnected elements)
            bool useIndex = context.IsNullOrEmpty() || !context.First().IsDisconnected;

            // Copy the list because it may change during the process
            ActiveSelectors = new List<Selector>(Selectors);

            for (activeSelectorId = 0; activeSelectorId < ActiveSelectors.Count; activeSelectorId++)
            {
                var selector = ActiveSelectors[activeSelectorId];
                CombinatorType combinatorType = selector.CombinatorType;
                SelectorType selectorType = selector.SelectorType;
                TraversalType traversalType = selector.TraversalType;

                // Determine what kind of combining method we will use with previous selection results

                if (activeSelectorId != 0)
                {
                    switch (combinatorType)
                    {
                        case CombinatorType.Cumulative:
                            // do nothing
                            break;
                        case CombinatorType.Root:
                            selectionSource = context;
                            if (lastResult != null)
                            {
                                output.AddRange(lastResult);
                                lastResult = null;
                            }
                            break;
                        case CombinatorType.Chained:
                            selectionSource = lastResult;
                            lastResult = null;
                            break;
                        // default (chained): leave lastresult alone
                    }
                }

                HashSet<IDomObject> tempResult = null;
                IEnumerable<IDomObject> interimResult = null;

                string key = "";
                if (useIndex && !selector.NoIndex)
                {

            #if DEBUG_PATH

                    if (type.HasFlag(SelectorType.Attribute))
                    {
                        key = "!" + selector.AttributeName;
                        type &= ~SelectorType.Attribute;
                        if (selector.AttributeValue != null)
                        {
                            InsertAttributeValueSelector(selector);
                        }
                    }
                    else if (type.HasFlag(SelectorType.Tag))
                    {
                        key = "+"+selector.Tag;
                        type &= ~SelectorType.Tag;
                    }
                    else if (type.HasFlag(SelectorType.ID))
                    {
                        key = "#" + selector.ID;
                        type &= ~SelectorType.ID;
                    }
                    else if (type.HasFlag(SelectorType.Class))
                    {
                        key = "." + selector.Class;
                        type &= ~SelectorType.Class;
                    }

            #else
                    if (selectorType.HasFlag(SelectorType.Attribute))
                    {
                        key = "!" + (char)DomData.TokenID(selector.AttributeName);
                        selectorType &= ~SelectorType.Attribute;
                        if (selector.AttributeValue != null)
                        {
                            InsertAttributeValueSelector(selector);
                        }
                    }
                    else if (selectorType.HasFlag(SelectorType.Tag))
                    {
                        key = "+" + (char)DomData.TokenID(selector.Tag, true);
                        selectorType &= ~SelectorType.Tag;
                    }
                    else if (selectorType.HasFlag(SelectorType.ID))
                    {
                        key = "#" + (char)DomData.TokenID(selector.ID);
                        selectorType &= ~SelectorType.ID;
                    }
                    else if (selectorType.HasFlag(SelectorType.Class))
                    {
                        key = "." + (char)DomData.TokenID(selector.Class);
                        selectorType &= ~SelectorType.Class;
                    }
            #endif
                }

                // If part of the selector was indexed, key will not be empty. Return initial set from the
                // index. If any selectors remain after this they will be searched the hard way.

                if (key != String.Empty)
                {
                    int depth = 0;
                    bool descendants = true;

                    switch (traversalType)
                    {
                        case TraversalType.Child:
                            depth = selector.ChildDepth; ;
                            descendants = false;
                            break;
                        case TraversalType.Filter:
                            depth = 0;
                            descendants = false;
                            break;
                        case TraversalType.Descendent:
                            depth = 1;
                            descendants = true;
                            break;
                    }

                    if (selectionSource == null)
                    {
                        interimResult = document.QueryIndex(key + DomData.indexSeparator, depth, descendants);
                    }
                    else
                    {
                        interimResult = new HashSet<IDomObject>();
                        foreach (IDomObject obj in selectionSource)
                        {
                            ((HashSet<IDomObject>)interimResult)
                                .AddRange(document.QueryIndex(key + DomData.indexSeparator + obj.Path,
                                    depth, descendants));
                        }
                    }
                }
                else if (selectorType.HasFlag(SelectorType.Elements))
                {
                    selectorType &= ~SelectorType.Elements;
                    HashSet<IDomObject> source = new HashSet<IDomObject>(selectionSource);
                    interimResult = new HashSet<IDomObject>();

                    foreach (IDomObject obj in selectionSource)
                    {
                        key = DomData.indexSeparator + obj.Path;
                        HashSet<IDomObject> srcKeys = new HashSet<IDomObject>(document.QueryIndex(key));
                        foreach (IDomObject match in selector.SelectElements)
                        {
                            if (srcKeys.Contains(match))
                            {
                                ((HashSet<IDomObject>)interimResult).Add(match);
                            }
                        }
                    }
                }
                // TODO - GetMatch should work if passed with no selectors (returning nothing), now it returns everything
                // 12/10/11 - this todo is not verified, much has changed since it was written. TODO confirm this and
                // fix if needed. If having the conversation with self again, remove comments and forget it. This is
                // an example of why comments can do more harm than good.

                if ((selectorType & ~(SelectorType.SubSelectorNot | SelectorType.SubSelectorHas)) != 0)
                {
                    IEnumerable<IDomObject> finalSelectWithin =
                        interimResult
                        ?? (combinatorType == CombinatorType.Chained ? lastResult : null)
                        ?? selectionSource
                        ?? document.ChildElements;

                    // if there are no temporary results (b/c there was no indexed selector) then use the whole set
                    interimResult = GetMatches(finalSelectWithin, selector);

                }

                // Deal with subselectors: has() and not() test for the presence of a selector within the children of
                // an element. This is essentially similar to the manual selection above.

                if (selectorType.HasFlag(SelectorType.SubSelectorHas)
                    || selectorType.HasFlag(SelectorType.SubSelectorNot))
                {
                    bool isHasSelector = selectorType.HasFlag(SelectorType.SubSelectorHas);

                    IEnumerable<IDomObject> subSelectWithin = interimResult
                        ?? (combinatorType == CombinatorType.Chained ? lastResult : null)
                        ?? selectionSource;

                    // subselects are a filter. start a new interim result.

                    HashSet<IDomObject> filteredResults = new HashSet<IDomObject>();

                    foreach (IDomObject obj in subSelectWithin)
                    {
                        bool match = true;
                        foreach (var sub in selector.SubSelectors)
                        {
                            List<IDomObject> listOfOne = new List<IDomObject>();
                            listOfOne.Add(obj);

                            bool has = !sub.Select(document, listOfOne).IsNullOrEmpty();

                            match &= isHasSelector == has;
                        }
                        if (match)
                        {
                            filteredResults.Add(obj);
                        }
                    }
                    interimResult = filteredResults;
                }
                tempResult = new HashSet<IDomObject>();
                if (lastResult != null)
                {
                    tempResult.AddRange(lastResult);
                }
                if (interimResult != null)
                {
                    tempResult.AddRange(interimResult);
                }
                lastResult = tempResult;
            }

            if (lastResult != null)
            {
                output.AddRange(lastResult);
            }

            if (output.IsNullOrEmpty())
            {
                yield break;
            }
            else
            {
                // Selectors always return in DOM order. Selections may end up in a different order but
                // we always sort here.

                foreach (IDomObject item in output.OrderBy(item => item.Path, StringComparer.Ordinal))
                {
                    yield return item;
                }
            }
            ActiveSelectors.Clear();
        }