/// <summary>
        /// Creates a new instance of <see cref="GenerateAssemblersParams"/>.
        /// </summary>
        /// <param name="targetProject">Project where the Assemblers are going to be generated.</param>
        /// <param name="targetProjectFolder">Project folder where Assemblers are going to be generated.
        /// Null value indicates to generate at project level.</param>
        /// <param name="sourceFileHeaderComment">Source File Header Comment (optional).</param>
        /// <param name="useProjectDefaultNamespace">Indicates if Target Project default namespace is going to be used.</param>
        /// <param name="sourceNamespace">Namespace used for the Assemblers.</param>
        /// <param name="classIdentifierUse">Indicates use of identifier in class names.</param>
        /// <param name="classIdentifierWord">Identifier to use in class names.</param>
        /// <param name="sourceFileGenerationType">Specifies the Source File Generation Type desired.</param>
        /// <param name="sourceFileName">Source File Name to use if the Source File Generation Type is OneSourceFile.</param>
        /// <param name="isServiceReady">Specifies if the DTOs are Service-Ready (this means if they can be serialized or not).</param>
        /// <param name="dtosNamespace">DTO's namespace.</param>
        /// <param name="dtosTargetProject">DTO's target Project.</param>
        /// <param name="edmxProjectItem">EDMX ProjectItem.</param>
        public GenerateAssemblersParams(Project targetProject, ProjectItem targetProjectFolder,
                                        string sourceFileHeaderComment, bool useProjectDefaultNamespace, string sourceNamespace,
                                        ClassIdentifierUse classIdentifierUse, string classIdentifierWord,
                                        SourceFileGenerationType sourceFileGenerationType, string sourceFileName, bool isServiceReady,
                                        string dtosNamespace, Project dtosTargetProject, ProjectItem edmxProjectItem)
        {
            this.TargetProject       = targetProject;
            this.TargetProjectFolder = targetProjectFolder;

            // Indicate target type
            this.TargetType = (this.TargetProjectFolder == null ? TargetType.Project : TargetType.ProjectFolder);

            this.SourceFileHeaderComment    = sourceFileHeaderComment;
            this.UseProjectDefaultNamespace = useProjectDefaultNamespace;
            this.SourceNamespace            = sourceNamespace;

            this.ClassIdentifierUse  = classIdentifierUse;
            this.ClassIdentifierWord = classIdentifierWord;

            if (this.ClassIdentifierUse == ClassIdentifierUse.None)
            {
                this.ClassIdentifierWord = string.Empty;
            }

            this.SourceFileGenerationType = sourceFileGenerationType;
            this.SourceFileName           = sourceFileName;
            this.IsServiceReady           = isServiceReady;
            this.DTOsNamespace            = dtosNamespace;
            this.DTOsTargetProject        = dtosTargetProject;
            this.EDMXProject = edmxProjectItem.ContainingProject;

            this.EntitiesNamespace = EdmxHelper.GetEntitiesNamespace(edmxProjectItem);
        }
Exemplo n.º 2
0
        /// <summary>
        /// Verifies the semantic rule
        /// </summary>
        /// <param name="context">The Interop service context</param>
        /// <param name="info">out parameter to return violation information when rule does not pass</param>
        /// <returns>true if rule passes; false otherwise</returns>
        public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            info = null;
            bool?passed = null;

            var     edmxHelper = new EdmxHelper(XElement.Parse(context.MetadataDocument));
            var     segments   = ResourcePathHelper.GetPathSegments(context);
            UriType uriType;
            var     target = edmxHelper.GetTargetType(segments, out uriType);

            if (uriType == UriType.URI3)
            {
                ComplexType complexType = (ComplexType)((EdmProperty)target).TypeUsage.EdmType;
                XElement    payload     = XElement.Parse(context.ResponsePayload);
                passed = VerifyComplexType(payload, complexType, context.Destination, out info);
            }
            else if (uriType == UriType.URI4 || uriType == UriType.URI5)
            {
                PrimitiveType propertyType = (PrimitiveType)((EdmProperty)target).TypeUsage.EdmType;
                XElement      property     = XElement.Parse(context.ResponsePayload);
                passed = VerifyValueByPrimitiveType(property.Value, propertyType.FullName);
                if (!passed.Value)
                {
                    passed = false;
                    info   = new ExtensionRuleViolationInfo("invalid formatted value for type " + propertyType.FullName, context.Destination, property.Value);
                }
            }

            return(passed);
        }
Exemplo n.º 3
0
        /// <summary>
        /// Verifies the semantic rule
        /// </summary>
        /// <param name="context">The Interop service context</param>
        /// <param name="info">out parameter to return violation information when rule does not pass</param>
        /// <returns>true if rule passes; false otherwise</returns>
        public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            info = null;
            bool?passed = true;

            var edmxHelper = new EdmxHelper(XElement.Parse(context.MetadataDocument));

            XElement payload = XElement.Parse(context.ResponsePayload);

            // for each property as XML element value, make sure it has either custom XML namnespace or the default one - in other word, it is not null or empty
            string xpath   = "//m:properties/../..";
            var    entries = payload.XPathSelectElements(xpath, ODataNamespaceManager.Instance);

            foreach (var entry in entries)
            {
                if (!VerifyEntry(entry, edmxHelper, context.Destination, out info))
                {
                    passed = false;
                    break;
                }
            }

            return(passed);
        }
        /// <summary>
        /// Verify the rule
        /// </summary>
        /// <param name="context">Service context</param>
        /// <param name="info">out paramater to return violation information when rule fail</param>
        /// <returns>true if rule passes; false otherwise</returns>
        public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            bool?passed = null;

            info = null;

            var    qs      = HttpUtility.ParseQueryString(context.Destination.Query);
            string qExpand = qs["$expand"];

            if (!string.IsNullOrEmpty(qExpand))
            {
                JObject jo      = JObject.Parse(context.ResponsePayload);
                var     version = JsonParserHelper.GetPayloadODataVersion(jo);

                var        edmxHelper = new EdmxHelper(XElement.Parse(context.MetadataDocument));
                EntityType et;
                edmxHelper.TryGetItem(context.EntityTypeFullName, out et);

                var branches = ResourcePathHelper.GetBranchedSegments(qExpand);
                foreach (var paths in branches)
                {
                    var    navStack           = ODataUriAnalyzer.GetNavigationStack(et, paths).ToArray();
                    bool[] targetIsCollection = (from n in navStack select n.RelationshipMultiplicity == RelationshipMultiplicity.Many).ToArray();

                    // to verify each single entity type expanded along the navigation path to have proper properties
                    TestResult result = null;
                    for (int i = 0; i < paths.Length; i++)
                    {
                        string jSchema = null;

                        if (!targetIsCollection[i])
                        {
                            var    etShort = navStack[i].GetEntityType().FullName.GetLastSegment();
                            string jsET    = JsonSchemaHelper.GetSchemaForEntityType(etShort, context.MetadataDocument);
                            string jsCore  = string.Format(@"""{0}"" : {1}", paths[i], jsET);
                            jSchema = JsonSchemaHelper.GetJsonSchema(paths, i, version, jsCore, targetIsCollection);

                            passed = JsonParserHelper.ValidateJson(jSchema, context.ResponsePayload, out result);
                            if (!passed.Value)
                            {
                                break;
                            }
                        }
                    }

                    if (!passed.Value)
                    {
                        info = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, context.ResponsePayload, result != null ? result.LineNumberInError : -1);
                        break;
                    }
                }
            }

            return(passed);
        }
        /// <summary>
        /// Verify the code rule
        /// </summary>
        /// <param name="context">Service context</param>
        /// <param name="info">out paramater to return violation information when rule fail</param>
        /// <returns>true if rule passes; false otherwise</returns>
        public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            bool?passed = null;

            info = null;

            var     segments   = ResourcePathHelper.GetPathSegments(context).ToArray();
            var     edmxHelper = new EdmxHelper(XElement.Parse(context.MetadataDocument));
            UriType uriType;
            var     target = edmxHelper.GetTargetType(segments, out uriType);

            if (uriType == UriType.URI4 || uriType == UriType.URI5)
            {
                string  property = segments.LastOrDefault(s => !s.StartsWith("$"));
                JObject jo       = JObject.Parse(context.ResponsePayload);
                var     version  = JsonParserHelper.GetPayloadODataVersion(jo);

                string     coreSchema = string.Format(fmtCore, property);
                string     jSchema    = JsonSchemaHelper.WrapJsonSchema(coreSchema, version);
                TestResult testResult;
                passed = JsonParserHelper.ValidateJson(jSchema, context.ResponsePayload, out testResult);
                if (passed.HasValue && !passed.Value)
                {
                    info = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, context.ResponsePayload, testResult != null ? testResult.LineNumberInError : -1);
                }
            }

            return(passed);
        }
        /// <summary>
        /// Verify the code rule
        /// </summary>
        /// <param name="context">Service context</param>
        /// <param name="info">out paramater to return violation information when rule fail</param>
        /// <returns>true if rule passes; false otherwise</returns>
        public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            bool?passed = null;

            info = null;

            var     edmxHelper = new EdmxHelper(XElement.Parse(context.MetadataDocument));
            var     segments   = ResourcePathHelper.GetPathSegments(context);
            UriType uriType;
            var     target = edmxHelper.GetTargetType(segments, out uriType);

            // to check this rule only when returned resource is a ComplexType
            if (uriType == UriType.URI3 || uriType == UriType.URI12)
            {
                JObject    jo      = JObject.Parse(context.ResponsePayload);
                var        version = JsonParserHelper.GetPayloadODataVersion(jo);
                string     name    = (uriType == UriType.URI3) ? ((EdmProperty)target).Name : ((ComplexType)target).Name;
                string     jsCore  = string.Format(fmtoreSchema, name);
                string     jSchema = JsonSchemaHelper.WrapJsonSchema(jsCore, version);
                TestResult testResult;
                passed = JsonParserHelper.ValidateJson(jSchema, context.ResponsePayload, out testResult);
                if (passed.HasValue && !passed.Value)
                {
                    info = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, context.ResponsePayload, testResult != null ? testResult.LineNumberInError : -1);
                }
            }

            return(passed);
        }
Exemplo n.º 7
0
        /// <summary>
        /// Creates an instance of <see cref="DTOEntity"/>.
        /// </summary>
        /// <param name="typeNode">Type node.</param>
        /// <param name="genParams">Parameters for the generation of DTOs.</param>
        /// <param name="navigations">Entity navigations available.</param>
        public DTOEntity(XElement typeNode, GenerateDTOsParams genParams, List <EntityNavigation> navigations)
            : base(typeNode, genParams)
        {
            // Define Class Base Type (if exists)
            string entityBaseType = EdmxHelper.GetEntityBaseType(typeNode);

            if (string.IsNullOrWhiteSpace(entityBaseType) == false)
            {
                // Check if base type is going to be generated
                if (genParams.TypesToGenerateFilter.Contains(entityBaseType) == true)
                {
                    this.NameBaseDTO = Utils.ConstructDTOName(entityBaseType, genParams);
                }
            }

            #region Set IsAbstract

            if (typeNode.Attribute(EdmxNodeAttributes.EntityType_Abstract) != null)
            {
                string abstractValue = typeNode.Attribute(EdmxNodeAttributes.EntityType_Abstract).Value.ToLower();
                this.IsAbstract = (abstractValue == Resources.XmlBoolTrue);
            }

            #endregion Set IsAbstract

            #region Set Navigation Properties

            if (navigations != null)
            {
                IEnumerable <EntityNavigation> myNavigations = navigations.Where(a => a.DTOName == this.NameDTO);

                foreach (EntityNavigation entityNav in myNavigations)
                {
                    foreach (EntityNavigationProperty navProperty in entityNav.NavigationProperties)
                    {
                        // Add property only if target type is going to be generated
                        if (genParams.TypesToGenerateFilter.Contains(navProperty.EntityTargetName) == true)
                        {
                            if (genParams.AssociationType == AssociationType.KeyProperty &&
                                this.Properties.Exists(p => p.PropertyName == navProperty.Name))
                            {
                                VisualStudioHelper.AddToErrorList(TaskErrorCategory.Warning,
                                                                  string.Format(Resources.Warning_PropertyNameConflict, this.Name, navProperty.Name, navProperty.EntityTargetName),
                                                                  genParams.TargetProject, null, null, null);
                            }
                            else
                            {
                                this.Properties.Add(new DTOClassProperty(
                                                        entityNav.NavigationPropertyNameEDMX, navProperty, genParams.DTOsServiceReady));
                            }
                        }
                    }
                }
            }

            #endregion Set Association Properties
        }
        /// <summary>
        /// Gets the raw value of the property of the entry
        /// </summary>
        /// <param name="context">The context object which directly or indirectly points to an entry </param>
        /// <param name="property">The property name</param>
        /// <returns>The raw value returned from the remote service</returns>
        private static string GetRawValueOfProperty(ServiceContext context, string property, ServiceContext ctx)
        {
            var edmxHelper = new EdmxHelper(XElement.Parse(context.MetadataDocument));
            var segments   = ResourcePathHelper.GetPathSegments(context);
            var segs       = ResourcePathHelper.GetEntryUriSegments(segments.Take(segments.Count() - 1), edmxHelper);
            Uri uriEntry   = new Uri(context.ServiceBaseUri, string.Join("/", segs) + "/");

            return(GetProperty(uriEntry, property, ctx));
        }
Exemplo n.º 9
0
        /// <summary>
        /// Verifies the semantic rule
        /// </summary>
        /// <param name="context">The Interop service context</param>
        /// <param name="info">out parameter to return violation information when rule does not pass</param>
        /// <returns>true if rule passes; false otherwise</returns>
        public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            info = null;
            bool passed = true;

            // if query option of $expand is present, rule shall be verified
            // get the leftmost navigation property of expand query option
            var    qs      = HttpUtility.ParseQueryString(context.Destination.Query);
            string qExpand = qs["$expand"];

            if (!string.IsNullOrEmpty(qExpand))
            {
                var        edmxHelper = new EdmxHelper(XElement.Parse(context.MetadataDocument));
                EntityType et;
                edmxHelper.TryGetItem(context.EntityTypeFullName, out et);

                var     segments = ResourcePathHelper.GetPathSegments(context);
                UriType uriType;
                var     target = edmxHelper.GetTargetType(segments, out uriType);
                bool    isColletcionResource = uriType == UriType.URI1 || uriType == UriType.URI_CollEt;

                var branches = ResourcePathHelper.GetBranchedSegments(qExpand);
                foreach (var paths in branches)
                {
                    var    navStack           = ODataUriAnalyzer.GetNavigationStack(et, paths).ToArray();
                    bool[] targetIsCollection = (from n in navStack select n.RelationshipMultiplicity == RelationshipMultiplicity.Many).ToArray();

                    string rngCore = @"<ref name=""anyContent"" />";
                    for (int i = paths.Length - 1; i >= 0; i--)
                    {
                        rngCore = targetIsCollection[i] ? GetRngOfInlineFeed(paths[i], rngCore) : GetRngOfInlineEntry(paths[i], rngCore);
                    }

                    // construct the desired srng schema and verify
                    string rngSchema = isColletcionResource
                        ? string.Format(formatRngOfColl, rngCore, RngCommonPattern.CommonPatterns)
                        : string.Format(formatRngSingle, rngCore, RngCommonPattern.CommonPatterns);

                    RngVerifier verifier = new RngVerifier(rngSchema);
                    TestResult  result;
                    passed = verifier.Verify(context, out result);
                    if (!passed)
                    {
                        info = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, context.ResponsePayload, result.LineNumberInError);
                        break;
                    }
                }
            }

            return(passed);
        }
Exemplo n.º 10
0
        /// <summary>
        /// Verify the code rule
        /// </summary>
        /// <param name="context">Service context</param>
        /// <param name="info">out paramater to return violation information when rule fail</param>
        /// <returns>true if rule passes; false otherwise</returns>
        public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            bool?passed = null;

            info = null;

            var     segments   = ResourcePathHelper.GetPathSegments(context).ToArray();
            var     edmxHelper = new EdmxHelper(XElement.Parse(context.MetadataDocument));
            UriType uriType;
            var     target = edmxHelper.GetTargetType(segments, out uriType);

            if (uriType == UriType.URI4 || uriType == UriType.URI5)
            {
                passed = false;
                string  targetType = ((EdmProperty)target).TypeUsage.EdmType.FullName;
                string  property   = segments.LastOrDefault(s => !s.StartsWith("$"));
                JObject jo         = JObject.Parse(context.ResponsePayload);
                var     inner      = jo.ReachInnerToken();
                if (inner.Type == JTokenType.Object)
                {
                    JObject innerObj = (JObject)inner;
                    if (innerObj.Properties() != null && innerObj.Properties().Count() == 1)
                    {
                        var    value        = innerObj.Properties().First().Value;
                        string valueLiteral = value.ToString();

                        IEdmType type = EdmTypeManager.GetEdmType(targetType);

                        bool isValidJsonData = type.IsGoodInJsonWith(valueLiteral);
                        if (isValidJsonData)
                        {
                            passed = true;
                        }
                        else
                        {
                            // target type may allow null
                            //TODO: allow null only when the target type is nullable
                            passed = valueLiteral.Equals("null", StringComparison.Ordinal);
                        }
                    }
                }
            }

            if (passed.HasValue && !passed.Value)
            {
                info = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, context.ResponsePayload, -1);
            }

            return(passed);
        }
        protected virtual void UpdateDesignerInfo(EdmxHelper edmxHelper, ModelBuilderSettings settings)
        {
            Debug.Assert(edmxHelper != null);

            edmxHelper.UpdateDesignerOptionProperty(
                OptionsDesignerInfo.AttributeEnablePluralization, settings.UsePluralizationService);
            edmxHelper.UpdateDesignerOptionProperty(
                OptionsDesignerInfo.AttributeIncludeForeignKeysInModel, settings.IncludeForeignKeysInModel);
            edmxHelper.UpdateDesignerOptionProperty(
                OptionsDesignerInfo.AttributeUseLegacyProvider, settings.UseLegacyProvider);
        }
        // internal virtual to allow mocking
        protected override void ProcessModel(DbModel model, string storeModelNamespace, ModelBuilderSettings settings, 
            ModelBuilderEngineHostContext hostContext, List<EdmSchemaError> errors)
        {
            Edmx = XDocument.Parse(_initialModelContentsFactory.GetInitialModelContents(settings.TargetSchemaVersion));

            var edmxHelper = new EdmxHelper(Edmx);

            edmxHelper.UpdateEdmxFromModel(model, storeModelNamespace, settings.ModelNamespace, errors);

            // load extensions that want to update model after the wizard has run. 
            hostContext.DispatchToModelGenerationExtensions();

            UpdateDesignerInfo(edmxHelper, settings);
        }
Exemplo n.º 13
0
        /// <summary>
        /// Verify the code rule
        /// </summary>
        /// <param name="context">Service context</param>
        /// <param name="info">out paramater to return violation information when rule fail</param>
        /// <returns>true if rule passes; false otherwise</returns>
        public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            bool?passed = null;

            info = null;

            var segments = ResourcePathHelper.GetPathSegments(context).ToArray();

            if (segments.Length > 0)
            {
                string lastSeg = segments[segments.Length - 1];
                if (lastSeg.Equals("$value", StringComparison.Ordinal))
                {
                    var     edmxHelper = new EdmxHelper(XElement.Parse(context.MetadataDocument));
                    UriType uriType;
                    var     target = edmxHelper.GetTargetType(segments, out uriType);
                    if (uriType == UriType.URI4 || uriType == UriType.URI5)
                    {
                        string targetType = ((EdmProperty)target).TypeUsage.EdmType.FullName;
                        if (!string.IsNullOrEmpty(targetType))
                        {
                            // do the validation here
                            IEdmType type = EdmTypeManager.GetEdmType(targetType);
                            if (type != null)
                            {
                                passed = type.IsGoodWith(context.ResponsePayload);
                                if (passed.HasValue && !passed.Value)
                                {
                                    info = new ExtensionRuleViolationInfo("pattern not matched", context.Destination, context.ResponsePayload, 1);
                                }
                            }
                            else
                            {
                                // type unknown
                                info   = new ExtensionRuleViolationInfo("unrecognized Edm type", context.Destination, targetType, 1);
                                passed = false;
                            }
                        }
                    }
                }
            }

            return(passed);
        }
Exemplo n.º 14
0
        /// <summary>
        /// Creates a new instance of <see cref="GenerateDTOsParams"/>.
        /// </summary>
        /// <param name="targetProject">Project where the DTOs are going to be generated.</param>
        /// <param name="targetProjectFolder">Project folder where DTO's are going to be generated.
        /// Null value indicates to generate at project level.</param>
        /// <param name="entitySource">Entity source (can be a Project or a ProjectItem representing an EDMX).</param>
        /// <param name="typesToGenerateFilter">Types from which to generate the DTOs.</param>
        /// <param name="generateAllTypes">Indicates if all types must be generated.</param>
        /// <param name="generateAllComplexTypes">Indicates if all complex types must be generated.</param>
        /// <param name="generateAllEntityTypes">Indicates if all complex types must be generated.</param>
        /// <param name="sourceFileHeaderComment">Source File Header Comment (optional).</param>
        /// <param name="useProjectDefaultNamespace">Indicates if Target Project default namespace is going to be used.</param>
        /// <param name="sourceNamespace">Namespace used for the DTOs.</param>
        /// <param name="dtosServiceReady">Specifies if the DTOs are Service-Ready (this means if they can be serialized or not).</param>
        /// <param name="classIdentifierUse">Indicates use of identifier in class names.</param>
        /// <param name="classIdentifierWord">Identifier to use in class names.</param>
        /// <param name="sourceFileGenerationType">Specifies the Source File Generation Type desired.</param>
        /// <param name="sourceFileName">Source File Name to use if the Source File Generation Type is OneSourceFile.</param>
        /// <param name="associationType">Class Association Type desired.</param>
        /// <param name="generateDTOConstructors">Indicates if DTO's Constructor methods should be created.</param>
        public GenerateDTOsParams(Project targetProject, ProjectItem targetProjectFolder, dynamic entitySource,
                                  List <string> typesToGenerateFilter, bool generateAllTypes, bool generateAllComplexTypes,
                                  bool generateAllEntityTypes, string sourceFileHeaderComment, bool useProjectDefaultNamespace,
                                  string sourceNamespace, bool dtosServiceReady, ClassIdentifierUse classIdentifierUse,
                                  string classIdentifierWord, SourceFileGenerationType sourceFileGenerationType, string sourceFileName,
                                  AssociationType associationType, bool generateDTOConstructors)
        {
            this.TargetProject       = targetProject;
            this.TargetProjectFolder = targetProjectFolder;

            this.TargetType = (this.TargetProjectFolder == null ? TargetType.Project : TargetType.ProjectFolder);

            this.EDMXProject = (entitySource is ProjectItem ? entitySource.ContainingProject : null);

            // TODO: ffernandez, use EntitySource (enum), add new property for the type and for Project
            this.EDMXProjectItem = entitySource;

            this.EDMXDocument = EdmxHelper.GetEdmxDocument(this.EDMXProjectItem);

            // TODO: ffernandez, review Project case
            this.EntitiesNamespace = EdmxHelper.GetEntitiesNamespace(entitySource);

            this.TypesToGenerateFilter   = typesToGenerateFilter;
            this.GenerateAllTypes        = generateAllTypes;
            this.GenerateAllComplexTypes = generateAllComplexTypes;
            this.GenerateAllEntityTypes  = generateAllEntityTypes;

            this.SourceFileHeaderComment    = sourceFileHeaderComment;
            this.UseProjectDefaultNamespace = useProjectDefaultNamespace;
            this.SourceNamespace            = sourceNamespace;
            this.DTOsServiceReady           = dtosServiceReady;

            this.ClassIdentifierUse  = classIdentifierUse;
            this.ClassIdentifierWord = classIdentifierWord;

            if (this.ClassIdentifierUse == ClassIdentifierUse.None)
            {
                this.ClassIdentifierWord = string.Empty;
            }

            this.SourceFileGenerationType = sourceFileGenerationType;
            this.SourceFileName           = sourceFileName;
            this.AssociationType          = associationType;
            this.GenerateDTOConstructors  = generateDTOConstructors;
        }
Exemplo n.º 15
0
        private bool VerifyEntry(XElement entry, EdmxHelper edmxHelper, Uri uriTarget, out ExtensionRuleViolationInfo info)
        {
            bool result = true;

            info = null;

            var category = entry.XPathSelectElement("./*[local-name()='category']");

            if (category != null)
            {
                string categoryTerm;
                categoryTerm = category.GetAttributeValue("term");
                if (!string.IsNullOrEmpty(categoryTerm))
                {
                    EntityType entityType;
                    if (edmxHelper.TryGetItem(categoryTerm, out entityType))
                    {
                        var properties = entry.XPathSelectElements("./*/m:properties/*", ODataNamespaceManager.Instance);
                        foreach (var property in properties)
                        {
                            var propertyName = property.Name.LocalName;

                            var metaProperty = from p in entityType.Properties where p.Name == propertyName select p;
                            if (metaProperty != null && metaProperty.Any())
                            {
                                var propertyType = metaProperty.First().TypeUsage.EdmType;
                                if (propertyType.BuiltInTypeKind == BuiltInTypeKind.PrimitiveType)
                                {
                                    if (!VerifyValueByPrimitiveType(property.Value, propertyType.FullName))
                                    {
                                        info   = new ExtensionRuleViolationInfo("invalid formatted value for type " + propertyType.FullName, uriTarget, property.Value);
                                        result = false;
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }

            return(result);
        }
        /// <summary>
        /// Verify the code rule
        /// </summary>
        /// <param name="context">Service context</param>
        /// <param name="info">out paramater to return violation information when rule fail</param>
        /// <returns>true if rule passes; false otherwise</returns>
        public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            bool passed = true;

            info = null;

            // to check this rule only when request URI if os URI7, and about set of links (not single link)
            bool isCheckingTarget = false;
            bool isNullable       = false;

            var     edmxHelper = new EdmxHelper(XElement.Parse(context.MetadataDocument));
            var     segments   = ResourcePathHelper.GetPathSegments(context);
            UriType uriType;
            var     target = edmxHelper.GetTargetType(segments, out uriType);

            if (uriType == UriType.URI7)
            {
                // safe to convert since s must be a RelationshipEndMember
                var targetRelationEndMember = (RelationshipEndMember)target;
                isCheckingTarget = targetRelationEndMember.RelationshipMultiplicity == RelationshipMultiplicity.One ||
                                   targetRelationEndMember.RelationshipMultiplicity == RelationshipMultiplicity.ZeroOrOne;
                isNullable = targetRelationEndMember.RelationshipMultiplicity == RelationshipMultiplicity.ZeroOrOne;
            }

            if (isCheckingTarget)
            {
                string      rngSchema = string.Format(isNullable ? rngFormat_nullable : rngFormat_one, RngCommonPattern.CommonPatterns);
                RngVerifier verifier  = new RngVerifier(rngSchema);
                TestResult  result;
                passed = verifier.Verify(context, out result);
                if (!passed)
                {
                    info = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, context.ResponsePayload, result.LineNumberInError);
                }
            }

            return(passed);
        }
Exemplo n.º 17
0
        /// <summary>
        /// Gets the Keys of an Entity.
        /// </summary>
        /// <param name="entityNodeKeysOwner">EntityType node to get the keys from.</param>
        /// <param name="entityNodeToSetKeys">EntityType node to set the keys.</param>
        /// <param name="entityNodeElements">EntityType nodes.</param>
        /// <param name="genParams">Parameters for the generation of DTOs.</param>
        /// <returns></returns>
        private static List <EntityKeyProperty> GetEntityKeys(XElement entityNodeKeysOwner, XElement entityNodeToSetKeys,
                                                              IEnumerable <XElement> entityNodeElements, GenerateDTOsParams genParams)
        {
            LogManager.LogMethodStart();

            var result = new List <EntityKeyProperty>();

            IEnumerable <XElement> propertyRefNodeElements = entityNodeKeysOwner.DescendantsCSDL(EdmxNodes.PropertyRef);

            IEnumerable <XElement> propertyNodeElements = entityNodeKeysOwner.DescendantsCSDL(EdmxNodes.Property);

            foreach (var propertyRefNode in propertyRefNodeElements)
            {
                result.Add(new EntityKeyProperty(entityNodeToSetKeys, propertyRefNode,
                                                 propertyNodeElements, genParams));
            }

            // Does this Entity have a Base Type ?
            string entityBaseType = EdmxHelper.GetEntityBaseType(entityNodeKeysOwner);

            if (entityBaseType != null)
            {
                // Find the Base Type node
                XElement entityBaseTypeNode = entityNodeElements.FirstOrDefault(
                    e => e.Attribute(EdmxNodeAttributes.EntityType_Name).Value == entityBaseType);

                if (entityBaseTypeNode == null)
                {
                    throw new ApplicationException(string.Format(Resources.Error_BaseTypeNotFound,
                                                                 entityNodeKeysOwner.Attribute(EdmxNodeAttributes.EntityType_Name).Value, entityBaseType));
                }

                // Add the Entity Base Type keys to the resulting keys
                result.AddRange(DTOGenerator.GetEntityKeys(entityBaseTypeNode, entityNodeToSetKeys,
                                                           entityNodeElements, genParams));
            }

            LogManager.LogMethodEnd();

            return(result);
        }
Exemplo n.º 18
0
        /// <summary>
        /// Verify the code rule
        /// </summary>
        /// <param name="context">Service context</param>
        /// <param name="info">out paramater to return violation information when rule fail</param>
        /// <returns>true if rule passes; false otherwise</returns>
        public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            bool?passed = null;

            info = null;

            var     edmxHelper = new EdmxHelper(XElement.Parse(context.MetadataDocument));
            var     segments   = ResourcePathHelper.GetPathSegments(context).ToArray();
            UriType uriType;
            var     target = edmxHelper.GetTargetType(segments, out uriType);

            if (segments.Length > 0)
            {
                string lastSeg = segments[segments.Length - 1];
                if (lastSeg.Equals("$value", StringComparison.Ordinal) && uriType != UriType.URI17)
                {
                    string targetType = ((EdmProperty)target).TypeUsage.EdmType.FullName;

                    // to ignore the case of Edm.Binary
                    if (!targetType.Equals("Edm.Binary", StringComparison.Ordinal))
                    {
                        var ct = context.ResponseHttpHeaders.GetContentTypeValue();
                        HttpHeaderRegexVerifier verifier = new HttpHeaderRegexVerifier("Content-Type", "\\s*text/plain\\b.*");
                        TestResult tr;
                        passed = verifier.Verify(context, out tr);
                        if (passed.HasValue && !passed.Value)
                        {
                            info = new ExtensionRuleViolationInfo("unexpected Content-Type header value", context.Destination, ct);
                        }
                    }
                }
            }

            return(passed);
        }
Exemplo n.º 19
0
        /// <summary>
        /// Verifies the semantic rule
        /// </summary>
        /// <param name="context">The Interop service context</param>
        /// <param name="info">out parameter to return violation information when rule does not pass</param>
        /// <returns>true if rule passes; false otherwise</returns>
        public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            info = null;
            bool?passed = null;

            //success is implied; otherwise OData error payload would have been received
            //apply rule when URI path points to a single entity, properties of an entity or Media Resource
            var     edmxHelper = new EdmxHelper(XElement.Parse(context.MetadataDocument));
            var     segments   = ResourcePathHelper.GetPathSegments(context);
            UriType uriType;
            var     target = edmxHelper.GetTargetType(segments, out uriType);
            bool    IsUriPathApplicable = uriType == UriType.URI2 ||
                                          uriType == UriType.URI3 ||
                                          uriType == UriType.URI4 ||
                                          uriType == UriType.URI5 ||
                                          uriType == UriType.URI10 ||
                                          uriType == UriType.URI17;

            if (IsUriPathApplicable)
            {
                string entityName          = ResourcePathHelper.GetEntityName(context);
                string concurrencyProperty = ResourcePathHelper.GetConcurrencyProperty(XElement.Parse(context.MetadataDocument), entityName);
                if (concurrencyProperty != null)
                {
                    //to check the existence of ETag header
                    var etagInHeader = context.ResponseHttpHeaders.GetHeaderValue("ETag");
                    passed = etagInHeader != null;
                    if (!passed.Value)
                    {
                        info = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, string.Empty);
                    }
                }
            }
            return(passed);
        }
Exemplo n.º 20
0
        /// <summary>
        /// Gets the Associations of the provided EDMX Document.
        /// </summary>
        /// <param name="genParams">Parameters for the generation of DTOs.</param>
        /// <returns></returns>
        private static List <EntityAssociation> GetEntitiesAssociations(GenerateDTOsParams genParams)
        {
            LogManager.LogMethodStart();

            IEnumerable <XElement> associationNodeElements =
                EdmxHelper.GetAssociationNodes(genParams.EDMXDocument);

            var result = new List <EntityAssociation>();

            foreach (XElement associationNodeElement in associationNodeElements)
            {
                result.Add(new EntityAssociation(associationNodeElement,
                                                 EntityAssociationEnd.First, genParams));

                result.Add(new EntityAssociation(associationNodeElement,
                                                 EntityAssociationEnd.Second, genParams));
            }

            LogManager.LogMethodEnd();

            return(result);
        }
        /// <summary>
        /// Verify the code rule
        /// </summary>
        /// <param name="context">Service context</param>
        /// <param name="info">out paramater to return violation information when rule fail</param>
        /// <returns>true if rule passes; false otherwise</returns>
        public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            bool?passed = null;

            info = null;

            var     edmxHelper = new EdmxHelper(XElement.Parse(context.MetadataDocument));
            var     segments   = ResourcePathHelper.GetPathSegments(context);
            UriType uriType;
            var     target = edmxHelper.GetTargetType(segments, out uriType);

            if (uriType == UriType.URI3)
            {
                XElement meta       = XElement.Parse(context.MetadataDocument);
                string   targetType = ((EdmProperty)target).TypeUsage.EdmType.FullName;

                var complexType = ResourcePathHelper.GetComplexType(targetType, meta);
                if (complexType != null)
                {
                    XElement    payload  = XElement.Parse(context.ResponsePayload);
                    string      schema   = GetRngSchema(ResourcePathHelper.GetBaseName(targetType), payload.Name.NamespaceName);
                    RngVerifier verifier = new RngVerifier(schema);
                    TestResult  result;
                    passed = verifier.Verify(context, out result);
                    if (passed.HasValue && !passed.Value)
                    {
                        info = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, context.ResponsePayload, result.LineNumberInError);
                    }
                }
            }

            return(passed);
        }
Exemplo n.º 22
0
        /// <summary>
        /// Verify rule logic
        /// </summary>
        /// <param name="context">Service context</param>
        /// <param name="info">out parameter to return violation information when rule fail</param>
        /// <returns>true if rule passes; false otherwise</returns>
        public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            bool?passed = null;

            info = null;

            // get the list of navigation properties of the interesting entity type
            var        edmxHelper = new EdmxHelper(XElement.Parse(context.MetadataDocument));
            EntityType et;

            edmxHelper.TryGetItem(context.EntityTypeFullName, out et);
            var navProps = et.NavigationProperties.Select(x => x.Name);

            // find out the data service namespace; falling back the implcit one if none exists
            string dsns = ResourcePathHelper.GetDataServiceNamespace(XElement.Parse(context.ResponsePayload));

            // get the relaxNG schema and verify the payload
            var rngNavLinks = navProps.Select(x => string.Format(tmplRngNavLink, dsns, x));
            var rng         = string.Format(tmplRngSchema, string.Join(string.Empty, rngNavLinks), RngCommonPattern.CommonPatterns);

            RngVerifier verifier = new RngVerifier(rng);
            TestResult  result;

            passed = verifier.Verify(context, out result);

            if (!passed.Value)
            {
                info = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, context.ResponsePayload, result.LineNumberInError);
            }

            return(passed);
        }
        /// <summary>
        /// Verify the code rule
        /// </summary>
        /// <param name="context">Service context</param>
        /// <param name="info">out paramater to return violation information when rule fail</param>
        /// <returns>true if rule passes; false otherwise</returns>
        public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            bool?passed = null;

            info = null;

            var     edmxHelper = new EdmxHelper(XElement.Parse(context.MetadataDocument));
            var     segments   = ResourcePathHelper.GetPathSegments(context);
            UriType uriType;
            var     target = edmxHelper.GetTargetType(segments, out uriType);

            // to check this rule only when returned resource is a ComplexType
            if (uriType == UriType.URI3 || uriType == UriType.URI12)
            {
                JObject jo      = JObject.Parse(context.ResponsePayload);
                var     version = JsonParserHelper.GetPayloadODataVersion(jo);

                ComplexType ct      = (uriType == UriType.URI12) ? (ComplexType)target : (ComplexType)((EdmProperty)target).TypeUsage.EdmType;
                var         props   = from p in ct.Properties select p.Name;
                var         jsProps = props.Select(x => string.Format(@"""{0}"" : {{""required"" : false }}", x));
                string      jsCore  = string.Format(fmtCoreSchema, ct.Name, string.Join(",", jsProps.ToArray()));
                string      jSchema = JsonSchemaHelper.WrapJsonSchema(jsCore, version);
                TestResult  result;
                passed = JsonParserHelper.ValidateJson(jSchema, context.ResponsePayload, out result);
                if (passed.HasValue && !passed.Value)
                {
                    info = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, context.ResponsePayload, result != null ? result.LineNumberInError : -1);
                }
            }

            return(passed);
        }
Exemplo n.º 24
0
        /// <summary>
        /// Gets the enum types available.
        /// </summary>
        /// <param name="parameters">Parameters for the generation of DTOs.</param>
        /// <returns></returns>
        private static List <EnumType> GetEnumTypes(GenerateDTOsParams parameters)
        {
            var enums = new List <EnumType>();

            foreach (XElement xEnum in EdmxHelper.GetEnumTypeNodes(parameters.EDMXDocument))
            {
                var enumType = new EnumType();
                enumType.Name = xEnum.Attribute(EdmxNodeAttributes.EntityType_Name).Value;

                XAttribute attrExternalType = xEnum.Attribute(EdmxNodeAttributes.EnumType_ExternalTypeName);
                if (attrExternalType != null)
                {
                    enumType.ExternalTypeName = attrExternalType.Value;

                    VisualStudioHelper.AddToErrorList(TaskErrorCategory.Warning,
                                                      string.Format(Resources.Warning_ManuallyAddReferenceForEnum, enumType.ExternalTypeName),
                                                      parameters.TargetProject, null, null, null);
                }

                enums.Add(enumType);
            }

            return(enums);
        }
Exemplo n.º 25
0
        /// <summary>
        /// Verify the code rule
        /// </summary>
        /// <param name="context">Service context</param>
        /// <param name="info">out paramater to return violation information when rule fail</param>
        /// <returns>true if rule passes; false otherwise</returns>
        public override bool? Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            bool? passed = null;
            info = null;

            var edmxHelper = new EdmxHelper(XElement.Parse(context.MetadataDocument));
            var segments = ResourcePathHelper.GetPathSegments(context);
            UriType uriType;
            var target = edmxHelper.GetTargetType(segments, out uriType);
            if (uriType == UriType.URI3)
            {
                XElement meta = XElement.Parse(context.MetadataDocument);
                string targetType = ((EdmProperty)target).TypeUsage.EdmType.FullName;

                var complexType = ResourcePathHelper.GetComplexType(targetType, meta);
                if (complexType != null)
                {
                    XElement payload = XElement.Parse(context.ResponsePayload);
                    string schema = GetRngSchema(ResourcePathHelper.GetBaseName(targetType), payload.Name.NamespaceName);
                    RngVerifier verifier = new RngVerifier(schema);
                    TestResult result;
                    passed = verifier.Verify(context, out result);
                    if (passed.HasValue && !passed.Value)
                    {
                        info = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, context.ResponsePayload, result.LineNumberInError);
                    }
                }
            }

            return passed;
        }
 /// <summary>
 /// Gets the short name of the entity for the context
 /// </summary>
 /// <param name="context">The context object which directly or indirectly points to an entry</param>
 /// <returns>The short name of entity</returns>
 public static string GetEntityName(ServiceContext context)
 {
     string entityName = context.EntityTypeShortName;
     if (string.IsNullOrEmpty(entityName))
     {
         var edmxHelper = new EdmxHelper(XElement.Parse(context.MetadataDocument));
         var segments = ResourcePathHelper.GetPathSegments(context);
         var segsToEntity = GetEntryUriSegments(segments.Take(segments.Count() - 1), edmxHelper);
         UriType uriType;
         var target = edmxHelper.GetTargetType(segsToEntity, out uriType);
         entityName = ((EntityType)target).Name;
     }
     return entityName;
 }
        /// <summary>
        /// Verifies the semantic rule
        /// </summary>
        /// <param name="context">The Interop service context</param>
        /// <param name="info">out parameter to return violation information when rule does not pass</param>
        /// <returns>true if rule passes; false otherwise</returns>
        public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            info = null;
            bool?passed = null;

            //to apply rule when payload has ETag header
            var etagInHeader = context.ResponseHttpHeaders.GetHeaderValue("ETag");

            if (etagInHeader != null)
            {
                var    valueInHeader = GetETagValueCore(etagInHeader.Trim());
                string entityName    = ResourcePathHelper.GetEntityName(context);

                string concurrencyProperty = ResourcePathHelper.GetConcurrencyProperty(XElement.Parse(context.MetadataDocument), entityName);
                if (concurrencyProperty != null)
                {
                    string valueInEntry = null;

                    //to get the concurrency token for the entity
                    switch (context.PayloadFormat)
                    {
                    case RuleEngine.PayloadFormat.Atom:
                    case RuleEngine.PayloadFormat.Xml:
                        valueInEntry = GetProperty(XElement.Parse(context.ResponsePayload), concurrencyProperty);
                        if (valueInEntry == null)
                        {
                            valueInEntry = GetRawValueOfProperty(context, concurrencyProperty, context);
                        }
                        break;

                    case RuleEngine.PayloadFormat.Json:
                        JObject jo = JObject.Parse(context.ResponsePayload);
                        valueInEntry = GetProperty(jo, concurrencyProperty);
                        if (valueInEntry == null)
                        {
                            valueInEntry = GetRawValueOfProperty(context, concurrencyProperty, context);
                        }
                        break;

                    case RuleEngine.PayloadFormat.Other:
                    {
                        var edmxHelper          = new EdmxHelper(XElement.Parse(context.MetadataDocument));
                        var segments            = ResourcePathHelper.GetPathSegments(context);
                        var segs                = ResourcePathHelper.GetEntryUriSegments(segments.Take(segments.Count() - 1), edmxHelper);
                        Uri uriEntry            = new Uri(context.ServiceBaseUri, string.Join("/", segs) + "/");
                        Uri uriConcurrencyValue = new Uri(uriEntry, concurrencyProperty + "/$value");
                        if (context.Destination == uriConcurrencyValue)
                        {
                            valueInEntry = context.ResponsePayload;
                        }
                        else
                        {
                            valueInEntry = GetProperty(uriEntry, concurrencyProperty, context);
                        }
                    }
                    break;
                    }

                    if (valueInEntry != null)
                    {
                        passed = valueInEntry == valueInHeader;
                    }
                }
            }

            if (passed.HasValue && !passed.Value)
            {
                info = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, etagInHeader);
            }

            return(passed);
        }
Exemplo n.º 28
0
        /// <summary>
        /// Verify the code rule
        /// </summary>
        /// <param name="context">Service context</param>
        /// <param name="info">out paramater to return violation information when rule fail</param>
        /// <returns>true if rule passes; false otherwise</returns>
        public override bool? Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            bool? passed = null;
            info = null;

            var segments = ResourcePathHelper.GetPathSegments(context).ToArray();
            var edmxHelper = new EdmxHelper(XElement.Parse(context.MetadataDocument));
            UriType uriType;
            var target = edmxHelper.GetTargetType(segments, out uriType);
            if (uriType == UriType.URI4 || uriType == UriType.URI5)
            {
                string property = segments.LastOrDefault(s => !s.StartsWith("$"));
                JObject jo = JObject.Parse(context.ResponsePayload);
                var version = JsonParserHelper.GetPayloadODataVersion(jo);

                string coreSchema = string.Format(fmtCore, property);
                string jSchema = JsonSchemaHelper.WrapJsonSchema(coreSchema, version);
                TestResult testResult;
                passed = JsonParserHelper.ValidateJson(jSchema, context.ResponsePayload, out testResult);
                if (passed.HasValue && !passed.Value)
                {
                    info = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, context.ResponsePayload, testResult != null ? testResult.LineNumberInError : -1);
                }
            }

            return passed;
        }
        /// <summary>
        /// Gets the segments pointing to an entry based
        /// </summary>
        /// <param name="segments">The segments pointing to derived resources of the entry</param>
        /// <param name="edmxHelper">The EdmxHelper instance</param>
        /// <returns>The segments pointing to the entry</returns>
        public static IEnumerable<string> GetEntryUriSegments(IEnumerable<string> segments, EdmxHelper edmxHelper)
        {
            if (!segments.Any())
            {
                return segments;
            }

            UriType uriType;
            var target = edmxHelper.GetTargetType(segments, out uriType);
            if (uriType == UriType.URI2)
            {
                return segments;
            }

            return GetEntryUriSegments(segments.Take(segments.Count() - 1), edmxHelper);
        }
Exemplo n.º 30
0
 /// <summary>
 /// Gets the raw value of the property of the entry
 /// </summary>
 /// <param name="context">The context object which directly or indirectly points to an entry </param>
 /// <param name="property">The property name</param>
 /// <returns>The raw value returned from the remote service</returns>
 private static string GetRawValueOfProperty(ServiceContext context, string property, ServiceContext ctx)
 {
     var edmxHelper = new EdmxHelper(XElement.Parse(context.MetadataDocument));
     var segments = ResourcePathHelper.GetPathSegments(context);
     var segs = ResourcePathHelper.GetEntryUriSegments(segments.Take(segments.Count() - 1), edmxHelper);
     Uri uriEntry = new Uri(context.ServiceBaseUri, string.Join("/", segs) + "/");
     return GetProperty(uriEntry, property, ctx);
 }
Exemplo n.º 31
0
        /// <summary>
        /// Creates an instance of <see cref="EntityNavigation"/>.
        /// </summary>
        /// <param name="genParams">Parameters for the generation of DTOs.</param>
        public EntityNavigation(XElement navigationNode, List <EntityAssociation> entitiesAssociations,
                                List <EntityKeyProperty> entitiesKeys, GenerateDTOsParams genParams)
        {
            // Set DTO Name
            string entityName = navigationNode.Parent.Attribute(EdmxNodeAttributes.EntityType_Name).Value;

            this.DTOName = Utils.ConstructDTOName(entityName, genParams);

            // Get the To Role End name
            string toRole = navigationNode.Attribute(EdmxNodeAttributes.NavigationProperty_ToRole).Value;

            // Get the Association Name
            string associationName = EdmxHelper.GetNavigationAssociationName(navigationNode);

            this.NavigationProperties = new List <EntityNavigationProperty>();

            // Find the Association
            EntityAssociation association = (
                from a in entitiesAssociations
                where (a.AssociationName == associationName) && (a.EndRoleName == toRole)
                select a
                ).FirstOrDefault();

            // Find the DTO associated keys
            IEnumerable <EntityKeyProperty> dtoToKeys = entitiesKeys.Where(k => k.DTOName == association.DTOName);

            // Get the base Property Name
            this.NavigationPropertyNameEDMX = navigationNode.Attribute(EdmxNodeAttributes.NavigationProperty_Name).Value;
            string propertyName = PropertyHelper.GetPropertyName(this.NavigationPropertyNameEDMX, entityName);

            // Set association type desired, can change if requirements are not met
            AssociationType associationTypeDesired = genParams.AssociationType;

            if (association.EndMultiplicity == EntityAssociationMultiplicity.Many)
            {
                if ((associationTypeDesired != AssociationType.ClassType) &&
                    (dtoToKeys.Count() != 1))
                {
                    // TODO: ffernandez, indicate Project-ProjectItem-Line-Column
                    VisualStudioHelper.AddToErrorList(TaskErrorCategory.Warning,
                                                      string.Format(Resources.Warning_CannotCreateNavPropManyKeyProp, this.DTOName, association.DTOName),
                                                      null, null, null, null);

                    associationTypeDesired = AssociationType.ClassType;
                }

                bool isList = true;

                if (associationTypeDesired == AssociationType.ClassType)
                {
                    // List<T> Type
                    string type = string.Format(Resources.CSharpTypeListT, association.DTOName);

                    this.NavigationProperties.Add(new EntityNavigationProperty(type, propertyName, isList,
                                                                               association.DTOName, association.EntityName, association.DTOName));
                }
                else
                {
                    // AssociationTypeEnum.KeyProperty
                    EntityKeyProperty dtoToKey = dtoToKeys.First();

                    // List<T> Type
                    string type = string.Format(Resources.CSharpTypeListT, dtoToKey.Type);

                    propertyName += (Resources.NameSeparator + dtoToKey.Name);

                    this.NavigationProperties.Add(new EntityNavigationProperty(type, propertyName, isList,
                                                                               dtoToKey.Type, association.EntityName, association.DTOName));
                }
            }
            else
            {
                // EntityAssociationMultiplicityEnum.One
                // EntityAssociationMultiplicityEnum.ZeroOrOne
                bool   isList = false;
                string listOf = null;

                if (associationTypeDesired == AssociationType.ClassType)
                {
                    this.NavigationProperties.Add(new EntityNavigationProperty(association.DTOName, propertyName, isList,
                                                                               listOf, association.EntityName, association.DTOName));
                }
                else
                {
                    // AssociationTypeEnum.KeyProperty

                    foreach (EntityKeyProperty dtoToKey in dtoToKeys)
                    {
                        string propName = (propertyName + Resources.NameSeparator + dtoToKey.Name);

                        this.NavigationProperties.Add(new EntityNavigationProperty(dtoToKey.Type, propName, isList,
                                                                                   listOf, association.EntityName, association.DTOName));
                    }
                }
            }
        }
Exemplo n.º 32
0
        /// <summary>
        /// Verify the rule
        /// </summary>
        /// <param name="context">Service context</param>
        /// <param name="info">out paramater to return violation information when rule fail</param>
        /// <returns>true if rule passes; false otherwise</returns>
        public override bool? Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            bool? passed = null;
            info = null;

            var qs = HttpUtility.ParseQueryString(context.Destination.Query);
            string qExpand = qs["$expand"];
            if (!string.IsNullOrEmpty(qExpand))
            {
                JObject jo = JObject.Parse(context.ResponsePayload);
                var version = JsonParserHelper.GetPayloadODataVersion(jo);

                var edmxHelper = new EdmxHelper(XElement.Parse(context.MetadataDocument));
                EntityType et;
                edmxHelper.TryGetItem(context.EntityTypeFullName, out et);

                var branches = ResourcePathHelper.GetBranchedSegments(qExpand);
                foreach (var paths in branches)
                {
                    var navStack = ODataUriAnalyzer.GetNavigationStack(et, paths).ToArray();
                    bool[] targetIsCollection = (from n in navStack select n.RelationshipMultiplicity == RelationshipMultiplicity.Many).ToArray();

                    // to verify each single entity type expanded along the navigation path to have proper properties
                    TestResult result = null;
                    for (int i = 0; i < paths.Length; i++)
                    {
                        string jSchema = null;

                        if (!targetIsCollection[i])
                        {
                            var etShort = navStack[i].GetEntityType().FullName.GetLastSegment();
                            string jsET = JsonSchemaHelper.GetSchemaForEntityType(etShort, context.MetadataDocument);
                            string jsCore = string.Format(@"""{0}"" : {1}", paths[i], jsET);
                            jSchema = JsonSchemaHelper.GetJsonSchema(paths, i, version, jsCore, targetIsCollection);

                            passed = JsonParserHelper.ValidateJson(jSchema, context.ResponsePayload, out result);
                            if (!passed.Value)
                            {
                                break;
                            }
                        }
                    }

                    if (!passed.Value)
                    {
                        info = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, context.ResponsePayload, result != null ? result.LineNumberInError : -1);
                        break;
                    }
                }
            }

            return passed;
        }
Exemplo n.º 33
0
        /// <summary>
        /// Verify the code rule
        /// </summary>
        /// <param name="context">Service context</param>
        /// <param name="info">out paramater to return violation information when rule fail</param>
        /// <returns>true if rule passes; false otherwise</returns>
        public override bool? Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            bool? passed = null;
            info = null;

            var edmxHelper = new EdmxHelper(XElement.Parse(context.MetadataDocument));
            var segments = ResourcePathHelper.GetPathSegments(context);
            UriType uriType;
            var target = edmxHelper.GetTargetType(segments, out uriType);

            // to check this rule only when returned resource is a ComplexType
            if (uriType == UriType.URI3 || uriType == UriType.URI12)
            {
                JObject jo = JObject.Parse(context.ResponsePayload);
                var version = JsonParserHelper.GetPayloadODataVersion(jo);

                ComplexType ct = (uriType == UriType.URI12) ? (ComplexType)target : (ComplexType)((EdmProperty)target).TypeUsage.EdmType;
                var props = from p in ct.Properties select p.Name;
                var jsProps = props.Select(x => string.Format(@"""{0}"" : {{""required"" : false }}", x));
                string jsCore = string.Format(fmtCoreSchema, ct.Name, string.Join(",", jsProps.ToArray()));
                string jSchema = JsonSchemaHelper.WrapJsonSchema(jsCore, version);
                TestResult result;
                passed = JsonParserHelper.ValidateJson(jSchema, context.ResponsePayload, out result);
                if (passed.HasValue && !passed.Value)
                {
                    info = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, context.ResponsePayload, result != null ? result.LineNumberInError : -1);
                }
            }

            return passed;
        }
 internal void UpdateDesignerInfoInvoker(EdmxHelper edmxHelper, ModelBuilderSettings settings)
 {
     UpdateDesignerInfo(edmxHelper, settings);
 }
Exemplo n.º 35
0
        /// <summary>
        /// Verifies the semantic rule
        /// </summary>
        /// <param name="context">The Interop service context</param>
        /// <param name="info">out parameter to return violation information when rule does not pass</param>
        /// <returns>true if rule passes; false otherwise</returns>
        public override bool? Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            info = null;
            bool? passed = null;

            //to apply rule when payload has ETag header
            var etagInHeader = context.ResponseHttpHeaders.GetHeaderValue("ETag");
            if (etagInHeader != null)
            {
                var valueInHeader = GetETagValueCore(etagInHeader.Trim());
                string entityName = ResourcePathHelper.GetEntityName(context);

                string concurrencyProperty = ResourcePathHelper.GetConcurrencyProperty(XElement.Parse(context.MetadataDocument), entityName);
                if (concurrencyProperty != null)
                {
                    string valueInEntry = null;

                    //to get the concurrency token for the entity
                    switch (context.PayloadFormat)
                    {
                        case RuleEngine.PayloadFormat.Atom:
                        case RuleEngine.PayloadFormat.Xml:
                            valueInEntry = GetProperty(XElement.Parse(context.ResponsePayload), concurrencyProperty);
                            if (valueInEntry == null)
                            {
                                valueInEntry = GetRawValueOfProperty(context, concurrencyProperty, context);
                            }
                            break;
                        case RuleEngine.PayloadFormat.Json:
                            JObject jo = JObject.Parse(context.ResponsePayload);
                            valueInEntry = GetProperty(jo, concurrencyProperty);
                            if (valueInEntry == null)
                            {
                                valueInEntry = GetRawValueOfProperty(context, concurrencyProperty, context);
                            }
                            break;
                        case RuleEngine.PayloadFormat.Other:
                            {
                                var edmxHelper = new EdmxHelper(XElement.Parse(context.MetadataDocument));
                                var segments = ResourcePathHelper.GetPathSegments(context);
                                var segs = ResourcePathHelper.GetEntryUriSegments(segments.Take(segments.Count() - 1), edmxHelper);
                                Uri uriEntry = new Uri(context.ServiceBaseUri, string.Join("/", segs) + "/");
                                Uri uriConcurrencyValue = new Uri(uriEntry, concurrencyProperty + "/$value");
                                if (context.Destination == uriConcurrencyValue)
                                {
                                    valueInEntry = context.ResponsePayload;
                                }
                                else
                                {
                                    valueInEntry = GetProperty(uriEntry, concurrencyProperty, context);
                                }
                            }
                            break;
                    }

                    if (valueInEntry != null)
                    {
                        passed = valueInEntry == valueInHeader;
                    }
                }
            }

            if (passed.HasValue && !passed.Value)
            {
                info = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, etagInHeader);
            }

            return passed;
        }
Exemplo n.º 36
0
        /// <summary>
        /// Gets the objects that represents the DTOs that needs to be generated from the received EDMX Document.
        /// </summary>
        /// <param name="parameters">Parameters for the generation of DTOs.</param>
        /// <returns></returns>
        private static List <DTOEntity> GetEntityDTOs(GenerateDTOsParams parameters)
        {
            LogManager.LogMethodStart();

            // Variables
            string typeName        = null;
            bool   generateType    = false;
            var    complexTypeDTOs = new List <DTOEntity>();
            var    entityTypeDTOs  = new List <DTOEntity>();

            // Get the DTOs for the ComplexType nodes
            foreach (XElement complexType in EdmxHelper.GetComplexTypeNodes(parameters.EDMXDocument))
            {
                typeName = complexType.Attribute(EdmxNodeAttributes.EntityType_Name).Value;

                generateType = parameters.TypesToGenerateFilter.Contains(typeName);

                if (generateType == true)
                {
                    List <EntityNavigation> entityNavigations = null;

                    complexTypeDTOs.Add(new DTOEntity(complexType, parameters, entityNavigations));
                }
            }

            // Set the Complex Types available
            PropertyHelper.SetComplexTypes(complexTypeDTOs);

            // Get Navigation Properties
            List <EntityNavigation> entitiesNavigations = DTOGenerator.GetEntitiesNavigations(parameters);

            // Get the DTOs for the EntityType nodes
            foreach (XElement entityTypeNode in EdmxHelper.GetEntityTypeNodes(parameters.EDMXDocument))
            {
                typeName = entityTypeNode.Attribute(EdmxNodeAttributes.EntityType_Name).Value;

                generateType = parameters.TypesToGenerateFilter.Contains(typeName);

                if (generateType == true)
                {
                    entityTypeDTOs.Add(new DTOEntity(entityTypeNode, parameters, entitiesNavigations));
                }
            }

            foreach (DTOEntity dto in entityTypeDTOs)
            {
                // Set Know Types of DTO
                dto.SetKnownTypes(entityTypeDTOs, parameters.DTOsServiceReady);

                // Set DTOs childs of DTO
                dto.SetChilds(entityTypeDTOs);

                // Set reference to DTO Base Class
                dto.SetDTOBase(entityTypeDTOs);

                // Set Navigation Target DTO references
                foreach (DTOClassProperty dtoProperty in dto.Properties.Where(p => p.IsNavigation == true))
                {
                    DTOEntity dtoTarget = entityTypeDTOs.FirstOrDefault(e => e.NameDTO == dtoProperty.NavigatesToDTOName);

                    if (dtoTarget != null)
                    {
                        dtoProperty.SetNavigatesToDTOReference(dtoTarget);
                    }
                }
            }

            // Get the final result
            var result = new List <DTOEntity>();

            result.AddRange(complexTypeDTOs);
            result.AddRange(entityTypeDTOs);

            LogManager.LogMethodEnd();

            return(result);
        }
 protected override void UpdateDesignerInfo(EdmxHelper edmxHelper, ModelBuilderSettings settings)
 {
     // in the update model case, there is no need to fix up the designer info
     // since it would only be applied to the temporary artifact and then ignored
 }
Exemplo n.º 38
0
        /// <summary>
        /// Verify the code rule
        /// </summary>
        /// <param name="context">Service context</param>
        /// <param name="info">out paramater to return violation information when rule fail</param>
        /// <returns>true if rule passes; false otherwise</returns>
        public override bool? Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            bool passed = true;
            info = null;

            // to check this rule only when request URI if os URI7, and about set of links (not single link)
            bool isCheckingTarget = false;

            var edmxHelper = new EdmxHelper(XElement.Parse(context.MetadataDocument));
            var segments = ResourcePathHelper.GetPathSegments(context);
            UriType uriType;
            var target = edmxHelper.GetTargetType(segments, out uriType);

            if (uriType == UriType.URI7)
            {
                // safe to convert since s must be a RelationshipEndMember
                var targetRelationEndMember = (RelationshipEndMember)target;
                isCheckingTarget = targetRelationEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many;
            }

            if (isCheckingTarget)
            {
                string rngSchema = string.Format(rngFormat, RngCommonPattern.CommonPatterns);
                RngVerifier verifier = new RngVerifier(rngSchema);
                TestResult result;
                passed = verifier.Verify(context, out result);
                if (!passed)
                {
                    info = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, context.ResponsePayload, result.LineNumberInError);
                }
            }

            return passed;
        }
Exemplo n.º 39
0
        /// <summary>
        /// Verify rule logic
        /// </summary>
        /// <param name="context">Service context</param>
        /// <param name="info">out parameter to return violation information when rule fail</param>
        /// <returns>true if rule passes; false otherwise</returns>
        public override bool? Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            bool? passed = null;
            info = null;

            // get the list of navigation properties of the interesting entity type
            var edmxHelper = new EdmxHelper(XElement.Parse(context.MetadataDocument));
            EntityType et;
            edmxHelper.TryGetItem(context.EntityTypeFullName, out et);
            var navProps = et.NavigationProperties.Select(x => x.Name);

            // find out the data service namespace; falling back the implcit one if none exists
            string dsns = ResourcePathHelper.GetDataServiceNamespace(XElement.Parse(context.ResponsePayload));

            // get the relaxNG schema and verify the payload
            var rngNavLinks = navProps.Select(x => string.Format(tmplRngNavLink, dsns, x));
            var rng = string.Format(tmplRngSchema, string.Join(string.Empty, rngNavLinks), RngCommonPattern.CommonPatterns);

            RngVerifier verifier = new RngVerifier(rng);
            TestResult result;
            passed = verifier.Verify(context, out result);

            if (!passed.Value)
            {
                info = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, context.ResponsePayload, result.LineNumberInError);
            }

            return passed;
        }
Exemplo n.º 40
0
        /// <summary>
        /// Verifies the semantic rule
        /// </summary>
        /// <param name="context">The Interop service context</param>
        /// <param name="info">out parameter to return violation information when rule does not pass</param>
        /// <returns>true if rule passes; false otherwise</returns>
        public override bool? Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            info = null;
            bool? passed = null;

            //success is implied; otherwise OData error payload would have been received
            //apply rule when URI path points to a single entity, properties of an entity or Media Resource
            var edmxHelper = new EdmxHelper(XElement.Parse(context.MetadataDocument));
            var segments = ResourcePathHelper.GetPathSegments(context);
            UriType uriType;
            var target = edmxHelper.GetTargetType(segments, out uriType);
            bool IsUriPathApplicable = uriType == UriType.URI2
                || uriType == UriType.URI3
                || uriType == UriType.URI4
                || uriType == UriType.URI5
                || uriType == UriType.URI10
                || uriType == UriType.URI17;
            if (IsUriPathApplicable)
            {
                string entityName = ResourcePathHelper.GetEntityName(context);
                string concurrencyProperty = ResourcePathHelper.GetConcurrencyProperty(XElement.Parse(context.MetadataDocument), entityName);
                if (concurrencyProperty != null)
                {
                    //to check the existence of ETag header
                    var etagInHeader = context.ResponseHttpHeaders.GetHeaderValue("ETag");
                    passed = etagInHeader != null;
                    if (!passed.Value)
                    {
                        info = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, string.Empty);
                    }
                }
            }
            return passed;
        }
Exemplo n.º 41
0
        /// <summary>
        /// Verify the code rule
        /// </summary>
        /// <param name="context">Service context</param>
        /// <param name="info">out paramater to return violation information when rule fail</param>
        /// <returns>true if rule passes; false otherwise</returns>
        public override bool? Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            bool? passed = null;
            info = null;

            var edmxHelper = new EdmxHelper(XElement.Parse(context.MetadataDocument));
            var segments = ResourcePathHelper.GetPathSegments(context);
            UriType uriType;
            var target = edmxHelper.GetTargetType(segments, out uriType);

            // to check this rule only when returned resource is collection of ComplexType
            if (uriType == UriType.URI11)
            {
                JObject jo = JObject.Parse(context.ResponsePayload);
                var version = JsonParserHelper.GetPayloadODataVersion(jo);

                string jSchema = JsonSchemaHelper.WrapJsonSchema(coreSchema, version);
                TestResult testResult;
                passed = JsonParserHelper.ValidateJson(jSchema, context.ResponsePayload, out testResult);
                if (passed.HasValue && !passed.Value)
                {
                    info = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, context.ResponsePayload, testResult != null ? testResult.LineNumberInError : -1);
                }
            }

            return passed;
        }
Exemplo n.º 42
0
        /// <summary>
        /// Verifies the semantic rule
        /// </summary>
        /// <param name="context">The Interop service context</param>
        /// <param name="info">out parameter to return violation information when rule does not pass</param>
        /// <returns>true if rule passes; false otherwise</returns>
        public override bool? Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            info = null;
            bool? passed = null;

            var edmxHelper = new EdmxHelper(XElement.Parse(context.MetadataDocument));
            var segments = ResourcePathHelper.GetPathSegments(context);
            UriType uriType;
            var target = edmxHelper.GetTargetType(segments, out uriType);

            if (uriType == UriType.URI3)
            {
                ComplexType complexType = (ComplexType)((EdmProperty)target).TypeUsage.EdmType;
                XElement payload = XElement.Parse(context.ResponsePayload);
                passed = VerifyComplexType(payload, complexType, context.Destination, out info);
            }
            else if (uriType == UriType.URI4 || uriType == UriType.URI5)
            {
                PrimitiveType propertyType = (PrimitiveType)((EdmProperty)target).TypeUsage.EdmType;
                XElement property = XElement.Parse(context.ResponsePayload);
                passed = VerifyValueByPrimitiveType(property.Value, propertyType.FullName);
                if (!passed.Value)
                {
                    passed = false;
                    info = new ExtensionRuleViolationInfo("invalid formatted value for type " + propertyType.FullName, context.Destination, property.Value);
                }
            }

            return passed;
        }
Exemplo n.º 43
0
        /// <summary>
        /// Verify the code rule
        /// </summary>
        /// <param name="context">Service context</param>
        /// <param name="info">out paramater to return violation information when rule fail</param>
        /// <returns>true if rule passes; false otherwise</returns>
        public override bool? Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            bool? passed = null;
            info = null;

            var segments = ResourcePathHelper.GetPathSegments(context).ToArray();
            var edmxHelper = new EdmxHelper(XElement.Parse(context.MetadataDocument));
            UriType uriType;
            var target = edmxHelper.GetTargetType(segments, out uriType);
            if (uriType == UriType.URI4 || uriType == UriType.URI5)
            {
                passed = false;
                string targetType = ((EdmProperty)target).TypeUsage.EdmType.FullName;
                string property = segments.LastOrDefault(s => !s.StartsWith("$"));
                JObject jo = JObject.Parse(context.ResponsePayload);
                var inner = jo.ReachInnerToken();
                if (inner.Type == JTokenType.Object)
                {
                    JObject innerObj = (JObject)inner;
                    if (innerObj.Properties() != null && innerObj.Properties().Count() == 1)
                    {
                        var value = innerObj.Properties().First().Value;
                        string valueLiteral = value.ToString();

                        IEdmType type = EdmTypeManager.GetEdmType(targetType);

                        bool isValidJsonData = type.IsGoodInJsonWith(valueLiteral);
                        if (isValidJsonData)
                        {
                            passed = true;
                        }
                        else
                        {
                            // target type may allow null
                            //TODO: allow null only when the target type is nullable
                            passed = valueLiteral.Equals("null", StringComparison.Ordinal);
                        }
                    }
                }
            }

            if (passed.HasValue && !passed.Value)
            {
                info = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, context.ResponsePayload, -1);
            }

            return passed;
        }
Exemplo n.º 44
0
        /// <summary>
        /// Verifies the semantic rule
        /// </summary>
        /// <param name="context">The Interop service context</param>
        /// <param name="info">out parameter to return violation information when rule does not pass</param>
        /// <returns>true if rule passes; false otherwise</returns>
        public override bool? Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            info = null;
            bool? passed = true;

            var edmxHelper = new EdmxHelper(XElement.Parse(context.MetadataDocument));

            XElement payload = XElement.Parse(context.ResponsePayload);

            // for each property as XML element value, make sure it has either custom XML namnespace or the default one - in other word, it is not null or empty
            string xpath = "//m:properties/../..";
            var entries = payload.XPathSelectElements(xpath, ODataNamespaceManager.Instance);
            foreach (var entry in entries)
            {
                if (!VerifyEntry(entry, edmxHelper, context.Destination, out info))
                {
                    passed = false;
                    break;
                }
            }

            return passed;
        }
Exemplo n.º 45
0
        private bool VerifyEntry(XElement entry, EdmxHelper edmxHelper, Uri uriTarget, out ExtensionRuleViolationInfo info)
        {
            bool result = true;
            info = null;

            var category = entry.XPathSelectElement("./*[local-name()='category']");
            if (category != null)
            {
                string categoryTerm;
                categoryTerm = category.GetAttributeValue("term");
                if (!string.IsNullOrEmpty(categoryTerm))
                {
                    EntityType entityType;
                    if (edmxHelper.TryGetItem(categoryTerm, out entityType))
                    {
                        var properties = entry.XPathSelectElements("./*/m:properties/*", ODataNamespaceManager.Instance);
                        foreach (var property in properties)
                        {
                            var propertyName = property.Name.LocalName;

                            var metaProperty = from p in entityType.Properties where p.Name == propertyName select p;
                            if (metaProperty != null && metaProperty.Any())
                            {
                                var propertyType = metaProperty.First().TypeUsage.EdmType;
                                if (propertyType.BuiltInTypeKind == BuiltInTypeKind.PrimitiveType)
                                {
                                    if (!VerifyValueByPrimitiveType(property.Value, propertyType.FullName))
                                    {
                                        info = new ExtensionRuleViolationInfo("invalid formatted value for type " + propertyType.FullName, uriTarget, property.Value);
                                        result = false;
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }

            return result;
        }
Exemplo n.º 46
0
        /// <summary>
        /// Verifies the semantic rule
        /// </summary>
        /// <param name="context">The Interop service context</param>
        /// <param name="info">out parameter to return violation information when rule does not pass</param>
        /// <returns>true if rule passes; false otherwise</returns>
        public override bool? Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            info = null;
            bool passed = true;

            // if query option of $expand is present, rule shall be verified
            // get the leftmost navigation property of expand query option
            var qs = HttpUtility.ParseQueryString(context.Destination.Query);
            string qExpand = qs["$expand"];

            if (!string.IsNullOrEmpty(qExpand))
            {
                var edmxHelper = new EdmxHelper(XElement.Parse(context.MetadataDocument));
                EntityType et;
                edmxHelper.TryGetItem(context.EntityTypeFullName, out et);

                var segments = ResourcePathHelper.GetPathSegments(context);
                UriType uriType;
                var target = edmxHelper.GetTargetType(segments, out uriType);
                bool isColletcionResource = uriType == UriType.URI1 || uriType == UriType.URI_CollEt;

                var branches = ResourcePathHelper.GetBranchedSegments(qExpand);
                foreach (var paths in branches)
                {
                    var navStack = ODataUriAnalyzer.GetNavigationStack(et, paths).ToArray();
                    bool[] targetIsCollection = (from n in navStack select n.RelationshipMultiplicity == RelationshipMultiplicity.Many).ToArray();

                    string rngCore = @"<ref name=""anyContent"" />";
                    for (int i = paths.Length - 1; i >= 0; i--)
                    {
                        rngCore = targetIsCollection[i] ? GetRngOfInlineFeed(paths[i], rngCore) : GetRngOfInlineEntry(paths[i], rngCore);
                    }

                    // construct the desired srng schema and verify
                    string rngSchema = isColletcionResource
                        ? string.Format(formatRngOfColl, rngCore, RngCommonPattern.CommonPatterns)
                        : string.Format(formatRngSingle, rngCore, RngCommonPattern.CommonPatterns);

                    RngVerifier verifier = new RngVerifier(rngSchema);
                    TestResult result;
                    passed = verifier.Verify(context, out result);
                    if (!passed)
                    {
                        info = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, context.ResponsePayload, result.LineNumberInError);
                        break;
                    }
                }
            }

            return passed;
        }