public void GenerateModel_writes_errors_if_any_returned_from_model_generation()
        {
            var modelGenCache = new ModelGenErrorCache();
            var mockPackage = new Mock<IEdmPackage>();
            mockPackage.Setup(p => p.ModelGenErrorCache).Returns(modelGenCache);

            PackageManager.Package = mockPackage.Object;
            var mockHostContext = new Mock<ModelBuilderEngineHostContext>();
            var mockModelBuilderSettings = CreateMockModelBuilderSettings();
            var mockModelBuilderEngine = new Mock<ModelBuilderEngine> { CallBase = true };

            var error = new EdmSchemaError("testError", 42, EdmSchemaErrorSeverity.Warning);

            mockModelBuilderEngine
                .Setup(m => m.GenerateModels(It.IsAny<string>(), It.IsAny<ModelBuilderSettings>(), It.IsAny<List<EdmSchemaError>>()))
                .Callback(
                    (string storeModelNamespace, ModelBuilderSettings settings, List<EdmSchemaError> errors) => errors.Add(error))
                .Returns(new DbModel(new DbProviderInfo("System.Data.SqlClient", "2008"), Mock.Of<DbProviderManifest>()));

            mockModelBuilderEngine.Object.GenerateModel(mockModelBuilderSettings.Object, Mock.Of<IVsUtils>(), mockHostContext.Object);

            mockModelBuilderEngine
                .Verify(m => m.GenerateModels(
                    It.IsAny<string>(), It.IsAny<ModelBuilderSettings>(), It.IsAny<List<EdmSchemaError>>()), Times.Once());

            mockHostContext.Verify(h => h.LogMessage(It.IsAny<string>()), Times.Exactly(3));
            mockHostContext
                .Verify(h => h.LogMessage(It.IsRegex(Resources.Engine_ModelGenErrors.Substring(1, 20))), Times.Once());
            mockHostContext
                .Verify(h => h.LogMessage(It.IsRegex(Resources.Engine_ModelGenException)), Times.Never());

            Assert.Same(error, modelGenCache.GetErrors(mockModelBuilderSettings.Object.ModelPath).Single());
        }
Beispiel #2
0
        public void EdmSchemaError_stores_passed_arguments()
        {
            var schemaError = new EdmSchemaError("message", 100, EdmSchemaErrorSeverity.Error);

            Assert.Equal("message", schemaError.Message);
            Assert.Equal(100, schemaError.ErrorCode);
            Assert.Equal(EdmSchemaErrorSeverity.Error, schemaError.Severity);
        }
        public void Can_add_get_error()
        {
            var mappingContext = new SimpleMappingContext(new EdmModel(DataSpace.SSpace), true);
            Assert.Empty(mappingContext.Errors);

            var error = new EdmSchemaError("bar", 0xF00, EdmSchemaErrorSeverity.Warning);
            mappingContext.Errors.Add(error);

            Assert.Same(error, mappingContext.Errors.Single());
        }
        public void GenerateModel_combines_store_model_and_mapping_errors()
        {
            var storeModelError = new EdmSchemaError("storeError", 42, EdmSchemaErrorSeverity.Error);
            var errorMetadataProperty =
                MetadataProperty.Create(
                    MetadataItemHelper.SchemaErrorsMetadataPropertyName,
                    TypeUsage.CreateDefaultTypeUsage(
                        PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.String).GetCollectionType()),
                    new List<EdmSchemaError> { storeModelError });

            var entityType =
                EntityType.Create(
                    "foo", "bar", DataSpace.SSpace, new string[0], new EdmMember[0],
                    new[] { errorMetadataProperty });

            var storeModel = new EdmModel(DataSpace.SSpace);
            storeModel.AddItem(entityType);

            var mappingContext = new SimpleMappingContext(storeModel, true);
            mappingContext.AddMapping(
                storeModel.Containers.Single(),
                EntityContainer.Create("C", DataSpace.CSpace, null, null, null));
            mappingContext.Errors.Add(new EdmSchemaError("mappingError", 911, EdmSchemaErrorSeverity.Warning));

            var mockModelGenerator = new Mock<ModelGenerator>(new ModelBuilderSettings(), "storeNamespace");
            mockModelGenerator
                .Setup(g => g.CreateStoreModel())
                .Returns(() => storeModel);

            mockModelGenerator
                .Setup(g => g.CreateMappingContext(It.IsAny<EdmModel>()))
                .Returns(() => mappingContext);

            var errors = new List<EdmSchemaError>();
            mockModelGenerator.Object.GenerateModel(errors);
            Assert.Equal(new[] { storeModelError, mappingContext.Errors.Single() }, errors);
        }
        internal bool ValidateTypeConditions(bool validateAmbiguity, IList<EdmSchemaError> errors, string sourceLocation)
        {
            // Verify that all types can be produced
            KeyToListMap<EntityType, LineInfo> unreachableEntityTypes;
            KeyToListMap<EntityType, LineInfo> unreachableIsTypeOfs;
            GetUnreachableTypes(validateAmbiguity, out unreachableEntityTypes, out unreachableIsTypeOfs);

            var valid = true;
            foreach (var unreachableEntityType in unreachableEntityTypes.KeyValuePairs)
            {
                var lineInfo = unreachableEntityType.Value.First();
                var lines = StringUtil.ToCommaSeparatedString(unreachableEntityType.Value.Select(li => li.LineNumber));
                var error = new EdmSchemaError(
                    Strings.Mapping_FunctionImport_UnreachableType(unreachableEntityType.Key.FullName, lines),
                    (int)StorageMappingErrorCode.MappingFunctionImportAmbiguousTypeConditions,
                    EdmSchemaErrorSeverity.Error,
                    sourceLocation,
                    lineInfo.LineNumber,
                    lineInfo.LinePosition);
                errors.Add(error);
                valid = false;
            }
            foreach (var unreachableIsTypeOf in unreachableIsTypeOfs.KeyValuePairs)
            {
                var lineInfo = unreachableIsTypeOf.Value.First();
                var lines = StringUtil.ToCommaSeparatedString(unreachableIsTypeOf.Value.Select(li => li.LineNumber));
                var isTypeOfDescription = StorageMslConstructs.IsTypeOf + unreachableIsTypeOf.Key.FullName
                                          + StorageMslConstructs.IsTypeOfTerminal;
                var error = new EdmSchemaError(
                    Strings.Mapping_FunctionImport_UnreachableIsTypeOf(isTypeOfDescription, lines),
                    (int)StorageMappingErrorCode.MappingFunctionImportAmbiguousTypeConditions,
                    EdmSchemaErrorSeverity.Error,
                    sourceLocation,
                    lineInfo.LineNumber,
                    lineInfo.LinePosition);
                errors.Add(error);
                valid = false;
            }

            return valid;
        }
        // effects: Given a container, ensures that all entity/association
        // sets in container on the C-side have been mapped
        private static ErrorLog EnsureAllCSpaceContainerSetsAreMapped(
            IEnumerable<Cell> cells,
            EntityContainerMapping containerMapping)
        {
            var mappedExtents = new Set<EntitySetBase>();
            string mslFileLocation = null;
            EntityContainer container = null;
            // Determine the container and name of the file while determining
            // the set of mapped extents in the cells
            foreach (var cell in cells)
            {
                mappedExtents.Add(cell.CQuery.Extent);
                mslFileLocation = cell.CellLabel.SourceLocation;
                // All cells are from the same container
                container = cell.CQuery.Extent.EntityContainer;
            }
            Debug.Assert(container != null);

            var missingExtents = new List<EntitySetBase>();
            // Go through all the extents in the container and determine
            // extents that are missing
            foreach (var extent in container.BaseEntitySets)
            {
                if (mappedExtents.Contains(extent) == false
                    && !(containerMapping.HasQueryViewForSetMap(extent.Name)))
                {
                    var associationSet = extent as AssociationSet;
                    if (associationSet == null
                        || !associationSet.ElementType.IsForeignKey)
                    {
                        missingExtents.Add(extent);
                    }
                }
            }
            var errorLog = new ErrorLog();
            // If any extent is not mapped, add an error
            if (missingExtents.Count > 0)
            {
                var extentBuilder = new StringBuilder();
                var isFirst = true;
                foreach (var extent in missingExtents)
                {
                    if (isFirst == false)
                    {
                        extentBuilder.Append(", ");
                    }
                    isFirst = false;
                    extentBuilder.Append(extent.Name);
                }
                var message = Strings.ViewGen_Missing_Set_Mapping(extentBuilder);
                // Find the cell with smallest line number - so that we can
                // point to the beginning of the file
                var lowestLineNum = -1;
                Cell smallestCell = null;
                foreach (var cell in cells)
                {
                    if (lowestLineNum == -1
                        || cell.CellLabel.StartLineNumber < lowestLineNum)
                    {
                        smallestCell = cell;
                        lowestLineNum = cell.CellLabel.StartLineNumber;
                    }
                }
                Debug.Assert(smallestCell != null && lowestLineNum >= 0);
                var edmSchemaError = new EdmSchemaError(
                    message, (int)ViewGenErrorCode.MissingExtentMapping,
                    EdmSchemaErrorSeverity.Error, containerMapping.SourceLocation, containerMapping.StartLineNumber,
                    containerMapping.StartLinePosition, null);
                var record = new ErrorLog.Record(edmSchemaError);
                errorLog.AddEntry(record);
            }
            return errorLog;
        }
 /// <summary>
 /// 
 /// </summary>
 /// <param name="errorCode"></param>
 /// <param name="severity"></param>
 /// <param name="source"></param>
 /// <param name="lineNumber"></param>
 /// <param name="linePosition"></param>
 /// <param name="message"></param>
 private void AddError(
     ErrorCode errorCode, EdmSchemaErrorSeverity severity, string sourceLocation, int lineNumber, int linePosition, object message)
 {
     EdmSchemaError error = null;
     var messageString = message as string;
     if (messageString != null)
     {
         error = new EdmSchemaError(messageString, (int)errorCode, severity, sourceLocation, lineNumber, linePosition);
     }
     else
     {
         var ex = message as Exception;
         if (ex != null)
         {
             error = new EdmSchemaError(ex.Message, (int)errorCode, severity, sourceLocation, lineNumber, linePosition, ex);
         }
         else
         {
             error = new EdmSchemaError(message.ToString(), (int)errorCode, severity, sourceLocation, lineNumber, linePosition);
         }
     }
     Schema.AddError(error);
 }
Beispiel #8
0
 internal void AddError(EdmSchemaError error)
 {
     _errors.Add(error);
 }
Beispiel #9
0
            private void Init(
                ViewGenErrorCode errorCode, string message,
                IEnumerable<Cell> sourceCells, string debugMessage)
            {
                m_sourceCells = new List<Cell>(sourceCells);

                Debug.Assert(m_sourceCells.Count > 0, "Error record must have at least one cell");

                // For certain foreign key messages, we may need the SSDL line numbers and file names
                var label = m_sourceCells[0].CellLabel;
                var sourceLocation = label.SourceLocation;
                var lineNumber = label.StartLineNumber;
                var columnNumber = label.StartLinePosition;

                var userMessage = InternalToString(message, debugMessage, m_sourceCells, errorCode, false);
                m_debugMessage = InternalToString(message, debugMessage, m_sourceCells, errorCode, true);
                m_mappingError = new EdmSchemaError(
                    userMessage, (int)errorCode, EdmSchemaErrorSeverity.Error, sourceLocation,
                    lineNumber, columnNumber);
            }
Beispiel #10
0
 //There are cases when we want to create a ViewGen error that is not specific to any mapping fragment
 //In this case, it is better to just create the EdmSchemaError directly and hold on to it.
 internal Record(EdmSchemaError error)
 {
     m_debugMessage = error.ToString();
     m_mappingError = error;
 }
        private bool TryConvertToPropertyMappings(
            StructuralType structuralType,
            RowType cTypeTvfElementType,
            RowType sTypeTvfElementType,
            EdmFunction functionImport,
            FunctionImportStructuralTypeMappingKB functionImportKB,
            IXmlLineInfo navLineInfo,
            out List<PropertyMapping> propertyMappings)
        {
            propertyMappings = new List<PropertyMapping>();

            // Gather and validate structuralType property mappings.
            var errorFound = false;
            foreach (EdmProperty property in TypeHelpers.GetAllStructuralMembers(structuralType))
            {
                // Only scalar property mappings are supported at the moment.
                if (!Helper.IsScalarType(property.TypeUsage.EdmType))
                {
                    var error = new EdmSchemaError(
                        Strings.Mapping_Invalid_CSide_ScalarProperty(property.Name),
                        (int)MappingErrorCode.InvalidTypeInScalarProperty,
                        EdmSchemaErrorSeverity.Error,
                        m_sourceLocation, navLineInfo.LineNumber, navLineInfo.LinePosition);
                    m_parsingErrors.Add(error);
                    errorFound = true;
                    continue;
                }

                string columnName = null;
                IXmlLineInfo columnMappingLineInfo = null;
                FunctionImportReturnTypeStructuralTypeColumnRenameMapping columnRenameMapping;
                bool explicitPropertyMapping;
                if (functionImportKB.ReturnTypeColumnsRenameMapping.TryGetValue(property.Name, out columnRenameMapping))
                {
                    explicitPropertyMapping = true;
                    columnName = columnRenameMapping.GetRename(structuralType, out columnMappingLineInfo);
                }
                else
                {
                    explicitPropertyMapping = false;
                    columnName = property.Name;
                }
                columnMappingLineInfo = columnMappingLineInfo != null && columnMappingLineInfo.HasLineInfo()
                                            ? columnMappingLineInfo
                                            : navLineInfo;

                EdmProperty column;
                if (sTypeTvfElementType.Properties.TryGetValue(columnName, false, out column))
                {
                    Debug.Assert(cTypeTvfElementType.Properties.Contains(columnName), "cTypeTvfElementType.Properties.Contains(columnName)");
                    var cTypeColumn = cTypeTvfElementType.Properties[columnName];
                    if (ValidateFunctionImportMappingResultTypeCompatibility(property.TypeUsage, cTypeColumn.TypeUsage))
                    {
                        propertyMappings.Add(new ScalarPropertyMapping(property, column));
                    }
                    else
                    {
                        var error = new EdmSchemaError(
                            GetInvalidMemberMappingErrorMessage(property, column),
                            (int)MappingErrorCode.IncompatibleMemberMapping,
                            EdmSchemaErrorSeverity.Error,
                            m_sourceLocation, columnMappingLineInfo.LineNumber, columnMappingLineInfo.LinePosition);
                        m_parsingErrors.Add(error);
                        errorFound = true;
                    }
                }
                else
                {
                    if (explicitPropertyMapping)
                    {
                        AddToSchemaErrorsWithMemberInfo(
                            Strings.Mapping_InvalidContent_Column, columnName,
                            MappingErrorCode.InvalidStorageMember,
                            m_sourceLocation, columnMappingLineInfo, m_parsingErrors);
                        errorFound = true;
                    }
                    else
                    {
                        var error = new EdmSchemaError(
                            Strings.Mapping_FunctionImport_PropertyNotMapped(
                                property.Name, structuralType.FullName, functionImport.Identity),
                            (int)MappingErrorCode.MappingFunctionImportReturnTypePropertyNotMapped,
                            EdmSchemaErrorSeverity.Error,
                            m_sourceLocation, columnMappingLineInfo.LineNumber, columnMappingLineInfo.LinePosition);
                        m_parsingErrors.Add(error);
                        errorFound = true;
                    }
                }
            }

            // Make sure that propertyMappings is in the order of properties of the structuredType.
            // The rest of the code depends on it.
            Debug.Assert(
                errorFound ||
                TypeHelpers.GetAllStructuralMembers(structuralType).Count == propertyMappings.Count &&
                TypeHelpers.GetAllStructuralMembers(structuralType).Cast<EdmMember>().Zip(propertyMappings)
                           .All(ppm => ppm.Key.EdmEquals(ppm.Value.Property)),
                "propertyMappings order does not correspond to the order of properties in the structuredType.");

            return !errorFound;
        }
        private EFObject EdmSchemaError2EFObject(EdmSchemaError error, EFArtifact defaultArtifactForError)
        {
            EFArtifact a = null;
            if (error.SchemaLocation != null)
            {
                a = _modelManager.GetArtifact(Utils.FileName2Uri(error.SchemaLocation));
            }

            if (a == null)
            {
                a = defaultArtifactForError;
            }

            return a.FindEFObjectForLineAndColumn(error.Line, error.Column);
        }
 private static ErrorInfo.Severity GetErrorInfoSeverity(EdmSchemaError error)
 {
     switch (error.Severity)
     {
         case EdmSchemaErrorSeverity.Error:
             return ErrorInfo.Severity.ERROR;
         case EdmSchemaErrorSeverity.Warning:
             return ErrorInfo.Severity.WARNING;
         default:
             Debug.Fail("Unexpected value for EdmSchemaErrorSeverity");
             return ErrorInfo.Severity.ERROR;
     }
 }
        /// <summary>
        ///     Creates generated view object for the combination of the <paramref name="setMapping" />.Set and the
        ///     <paramref
        ///         name="type" />
        ///     .
        ///     This constructor is used for user-defined query views only.
        /// </summary>
        internal static bool TryParseUserSpecifiedView(
            StorageSetMapping setMapping,
            EntityTypeBase type,
            string eSQL,
            bool includeSubtypes,
            StorageMappingItemCollection mappingItemCollection,
            ConfigViewGenerator config,
            /*out*/ IList<EdmSchemaError> errors,
            out GeneratedView generatedView)
        {
            var failed = false;

            DbQueryCommandTree commandTree;
            DiscriminatorMap discriminatorMap;
            Exception parserException;
            if (
                !TryParseView(
                    eSQL, true, setMapping.Set, mappingItemCollection, config, out commandTree, out discriminatorMap, out parserException))
            {
                var error = new EdmSchemaError(
                    Strings.Mapping_Invalid_QueryView2(setMapping.Set.Name, parserException.Message),
                    (int)StorageMappingErrorCode.InvalidQueryView, EdmSchemaErrorSeverity.Error,
                    setMapping.EntityContainerMapping.SourceLocation, setMapping.StartLineNumber, setMapping.StartLinePosition,
                    parserException);
                errors.Add(error);
                failed = true;
            }
            else
            {
                Debug.Assert(commandTree != null, "commandTree not set after parsing the view");

                // Verify that all expressions appearing in the view are supported.
                foreach (var error in ViewValidator.ValidateQueryView(commandTree, setMapping, type, includeSubtypes))
                {
                    errors.Add(error);
                    failed = true;
                }

                // Verify that the result type of the query view is assignable to the element type of the entityset
                var queryResultType = (commandTree.Query.ResultType.EdmType) as CollectionType;
                if ((queryResultType == null)
                    || (!setMapping.Set.ElementType.IsAssignableFrom(queryResultType.TypeUsage.EdmType)))
                {
                    var error = new EdmSchemaError(
                        Strings.Mapping_Invalid_QueryView_Type(setMapping.Set.Name),
                        (int)StorageMappingErrorCode.InvalidQueryViewResultType, EdmSchemaErrorSeverity.Error,
                        setMapping.EntityContainerMapping.SourceLocation, setMapping.StartLineNumber, setMapping.StartLinePosition);
                    errors.Add(error);
                    failed = true;
                }
            }

            if (!failed)
            {
                generatedView = new GeneratedView(setMapping.Set, type, commandTree, eSQL, discriminatorMap, mappingItemCollection, config);
                return true;
            }
            else
            {
                generatedView = null;
                return false;
            }
        }
        public void CollectStoreModelErrors_returns_errors_from_function_return_rowtypes()
        {
            var edmSchemaError = new EdmSchemaError("msg", 42, EdmSchemaErrorSeverity.Error);
            var errorMetadataProperty =
                MetadataProperty.Create(
                    MetadataItemHelper.SchemaErrorsMetadataPropertyName,
                    TypeUsage.CreateDefaultTypeUsage(
                        PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.String).GetCollectionType()),
                    new List<EdmSchemaError> { edmSchemaError });

            var rowType = RowType.Create(new EdmProperty[0], new[] { errorMetadataProperty });

            var function =
                EdmFunction.Create(
                    "foo",
                    "bar",
                    DataSpace.SSpace,
                    new EdmFunctionPayload
                        {
                            ReturnParameters =
                                new[]
                                    {
                                        FunctionParameter.Create(
                                            "ReturnType",
                                            rowType,
                                            ParameterMode.ReturnValue)
                                    }
                        },
                    null);

            var model = new EdmModel(DataSpace.SSpace);
            model.AddItem(function);

            var schemaErrors = ModelGenerator.CollectStoreModelErrors(model);

            Assert.NotNull(schemaErrors);
            Assert.Equal(1, schemaErrors.Count);
            Assert.Same(edmSchemaError, schemaErrors.Single());
        }
        public void CollectStoreModelErrors_returns_errors_on_model_items()
        {
            var edmSchemaError = new EdmSchemaError("msg", 42, EdmSchemaErrorSeverity.Error);
            var errorMetadataProperty =
                MetadataProperty.Create(
                    MetadataItemHelper.SchemaErrorsMetadataPropertyName,
                    TypeUsage.CreateDefaultTypeUsage(
                        PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.String).GetCollectionType()),
                    new List<EdmSchemaError> { edmSchemaError });

            var entityType =
                EntityType.Create(
                    "foo", "bar", DataSpace.SSpace, new string[0], new EdmMember[0],
                    new[] { errorMetadataProperty });

            var model = new EdmModel(DataSpace.SSpace);
            model.AddItem(entityType);

            var schemaErrors = ModelGenerator.CollectStoreModelErrors(model);

            Assert.NotNull(schemaErrors);
            Assert.Equal(1, schemaErrors.Count);
            Assert.Same(edmSchemaError, schemaErrors.Single());
        }