public EntityDescriptor Generate(string wsfedEndpoint)
        {
            var tokenServiceDescriptor = GetTokenServiceDescriptor(wsfedEndpoint);

            var id = new EntityId(_options.IssuerUri);
            var entity = new EntityDescriptor(id);
            entity.SigningCredentials = new X509SigningCredentials(_options.SigningCertificate);
            entity.RoleDescriptors.Add(tokenServiceDescriptor);

            return entity;
        }
        public ActionResult Generate()
        {
            var wsFederationEndpoint = new EndpointAddress(Request.ToApplicationUri() + "Issue/WSFederation");
            var wsTrustEndpoint = new EndpointAddress(new Uri(Request.ToApplicationUri() + "Issue/WSTrust/Message/Windows"), null, null, CreateMetadataReader(new Uri(Request.ToApplicationUri() + "Issue/WSTrust/mex")), null);
            var metadata = new EntityDescriptor
            {
                EntityId = new EntityId(Request.ToApplicationUri()),
                RoleDescriptors =
                {
                    new SecurityTokenServiceDescriptor {
                        ServiceDisplayName = Configuration.IssuerName,
                        Contacts = {
                            new ContactPerson {
                                 Type = ContactType.Support,
                                 Company = "Contoso Bank",
                                 EmailAddresses = { "*****@*****.**" },
                                 TelephoneNumbers = { "+1 (416) 555-1212" }
                            }
                        },
                        ClaimTypesOffered =
                        {
                            DisplayClaim.CreateDisplayClaimFromClaimType(ClaimTypes.Name),
                            DisplayClaim.CreateDisplayClaimFromClaimType(ClaimTypes.Email),
                        },
                        ProtocolsSupported = { new Uri(WSFederationMetadataConstants.Namespace) },
                        TokenTypesOffered = { new Uri(SecurityTokenTypes.OasisWssSaml11TokenProfile11), new Uri(SecurityTokenTypes.OasisWssSaml2TokenProfile11) },
                        PassiveRequestorEndpoints = { wsFederationEndpoint },
                        SecurityTokenServiceEndpoints = { wsTrustEndpoint },
                        Keys = { new KeyDescriptor(
                                    new SecurityKeyIdentifier(
                                        new X509SecurityToken(Configuration.TokenSigningCertificate).CreateKeyIdentifierClause<X509RawDataKeyIdentifierClause>())) { Use = KeyType.Signing } }
                    },
                },
                SigningCredentials = new X509SigningCredentials(Configuration.TokenSigningCertificate)
            };

            using (var stream = new MemoryStream())
            using (var streamReader = new StreamReader(stream))
            {
                var serializer = new MetadataSerializer();
                serializer.WriteMetadata(stream, metadata);
                stream.Position = 0;
                var result = new ContentResult
                {
                    Content = streamReader.ReadToEnd(),
                    ContentEncoding = Encoding.Unicode,
                    ContentType = System.Net.Mime.MediaTypeNames.Text.Xml
                };
                return result;
            }
        }
        public void Metadata()
        {
            var config = new SimpleSecurityTokenServiceConfiguration();   

            // Entity
            var ent = new EntityDescriptor();
            ent.Contacts.Add(new ContactPerson(ContactType.Technical) { GivenName = "Sandra", Surname = "Fernandes" });
            ent.EntityId = new EntityId(config.TokenIssuerName);
            ent.SigningCredentials = config.SigningCredentials;

            // Role: Security Token Service
            var role = new SecurityTokenServiceDescriptor();
            var endpoints = new EndpointAddress[] {
                new EndpointAddress("https://idp.prompt11.local:10443/Federation/Issue"),                
            };
            foreach (var ep in endpoints)
            {
                role.SecurityTokenServiceEndpoints.Add(ep);
                role.PassiveRequestorEndpoints.Add(ep);
            }

            role.ServiceDescription = "My Service";
            role.ServiceDisplayName = "My Service Description";
            role.ProtocolsSupported.Add(new Uri("http://docs.oasis-open.org/wsfed/federation/200706"));
            role.ValidUntil = DateTime.Now.AddDays(1);
            role.ClaimTypesOffered.Add(new DisplayClaim(Microsoft.IdentityModel.Claims.ClaimTypes.Role));
            role.ClaimTypesOffered.Add(new DisplayClaim(Microsoft.IdentityModel.Claims.ClaimTypes.Name));

            role.Keys.Add(
                new KeyDescriptor()
                {
                    KeyInfo =
                        new SecurityKeyIdentifier(
                            new X509RawDataKeyIdentifierClause((config.SigningCredentials as X509SigningCredentials).Certificate)
                        ),
                    Use = KeyType.Signing
                }
            );

            ent.RoleDescriptors.Add(role);

            // Serialize
            var serializer = new MetadataSerializer();
            var xe = new XDocument();
            var writer = xe.CreateWriter();
            serializer.WriteMetadata(writer, ent);
            writer.Close();
            Response.ContentType = "text/xml";
            Response.Write(xe.ToString(SaveOptions.DisableFormatting));     
        }
Exemple #4
0
 private static void ReadMetadata(XmlElement xmlElement)
 {
     if (EntitiesDescriptor.IsValid(xmlElement)) {
         Console.Error.WriteLine("Reading SAML entities descriptor metadata");
         EntitiesDescriptor entitiesDescriptor = new EntitiesDescriptor(xmlElement);
         Console.WriteLine(entitiesDescriptor.ToXml().OuterXml);
     } else if (EntityDescriptor.IsValid(xmlElement)) {
         Console.Error.WriteLine("Reading SAML entity descriptor metadata");
         EntityDescriptor entityDescriptor = new EntityDescriptor(xmlElement);
         Console.WriteLine(entityDescriptor.ToXml().OuterXml);
     } else {
         throw new ArgumentException("Expecting entities descriptor or entity descriptor");
     }
 }
        public string Generate()
        {
            var tokenServiceDescriptor = GetTokenServiceDescriptor();
            var id = new EntityId(_configurationRepository.Configuration.IssuerUri);
            var entity = new EntityDescriptor(id);
            entity.SigningCredentials = new X509SigningCredentials(_configurationRepository.SigningCertificate.Certificate);
            entity.RoleDescriptors.Add(tokenServiceDescriptor);

            var ser = new MetadataSerializer();
            var sb = new StringBuilder(512);

            ser.WriteMetadata(XmlWriter.Create(new StringWriter(sb), new XmlWriterSettings { OmitXmlDeclaration = true }), entity);
            return sb.ToString();
        }
 private EntityDescriptor GenerateEntities()
 {
     var sts = new SecurityTokenServiceDescriptor();
     FillOfferedClaimTypes(sts.ClaimTypesOffered);
     FillEndpoints(sts);
     FillSupportedProtocols(sts);
     FillSigningKey(sts);
     var entity = new EntityDescriptor(new EntityId(string.Format("https://{0}", Request.Url.GetLeftPart(UriPartial.Authority))))
     {
         SigningCredentials = this.SigningCredentials
     };
     entity.RoleDescriptors.Add(sts);
     return entity;
 }
Exemple #7
0
        /// <summary>
        /// Generate a sample MetadataBase.
        /// </summary>
        /// <remarks>
        /// In a production system this would be generated from the STS configuration.
        /// </remarks>
        public static MetadataBase GetFederationMetadata()
        {
            string endpointId = "http://localhost:61754/";
            EntityDescriptor metadata = new EntityDescriptor();
            metadata.EntityId = new EntityId(endpointId);

            // Define the signing key
            string signingCertificateName = WebConfigurationManager.AppSettings["SigningCertificateName"];
            X509Certificate2 cert = CertificateUtil.GetCertificate(StoreName.My, StoreLocation.LocalMachine, signingCertificateName);
            metadata.SigningCredentials = new X509SigningCredentials(cert);

            // Create role descriptor for security token service
            SecurityTokenServiceDescriptor stsRole = new SecurityTokenServiceDescriptor();
            stsRole.ProtocolsSupported.Add(new Uri(WSFederationMetadataConstants.Namespace));
            metadata.RoleDescriptors.Add(stsRole);

            // Add a contact name
            ContactPerson person = new ContactPerson(ContactType.Administrative);
            person.GivenName = "contactName";
            stsRole.Contacts.Add(person);

            // Include key identifier for signing key in metadata
            SecurityKeyIdentifierClause clause = new X509RawDataKeyIdentifierClause(cert);
            SecurityKeyIdentifier ski = new SecurityKeyIdentifier(clause);
            KeyDescriptor signingKey = new KeyDescriptor(ski);
            signingKey.Use = KeyType.Signing;
            stsRole.Keys.Add(signingKey);

            // Add endpoints
            string activeSTSUrl = "http://localhost:61754/";
            EndpointAddress endpointAddress = new EndpointAddress(new Uri(activeSTSUrl),
                                                                   null,
                                                                   null, GetMetadataReader(activeSTSUrl), null);
            stsRole.SecurityTokenServiceEndpoints.Add(endpointAddress);

            // Add a collection of offered claims
            // NOTE: In this sample, these claims must match the claims actually generated in CustomSecurityTokenService.GetOutputClaimsIdentity.
            //       In a production system, there would be some common data store that both use
            stsRole.ClaimTypesOffered.Add(new DisplayClaim(ClaimTypes.Name, "Name", "The name of the subject."));
            stsRole.ClaimTypesOffered.Add(new DisplayClaim(ClaimTypes.Role, "Role", "The role of the subject."));
            // Add a special claim for the QuoteService
            stsRole.ClaimTypesOffered.Add(new DisplayClaim(QuotationClassClaimType, "QuotationClass", "Class of quotation desired."));

            return metadata;
        }
        public byte[] GetFederationMetadata(Uri passiveSignInUrl, Uri identifier, X509Certificate2 signingCertificate)
        {
            var credentials = new X509SigningCredentials(signingCertificate);

            // Figure out the hostname exposed from Azure and what port the service is listening on
            EndpointAddress realm = new EndpointAddress(identifier);
            EndpointAddress passiveEndpoint = new EndpointAddress(passiveSignInUrl);

            // Create metadata document for relying party
            EntityDescriptor entity = new EntityDescriptor(new EntityId(realm.Uri.AbsoluteUri));
            SecurityTokenServiceDescriptor sts = new SecurityTokenServiceDescriptor();
            entity.RoleDescriptors.Add(sts);

            // Add STS's signing key
            KeyDescriptor signingKey = new KeyDescriptor(credentials.SigningKeyIdentifier);
            signingKey.Use = KeyType.Signing;
            sts.Keys.Add(signingKey);

            // Add offered claim types
            sts.ClaimTypesOffered.Add(new DisplayClaim(ClaimTypes.AuthenticationMethod));
            sts.ClaimTypesOffered.Add(new DisplayClaim(ClaimTypes.AuthenticationInstant));
            sts.ClaimTypesOffered.Add(new DisplayClaim(ClaimTypes.Name));

            // Add passive federation endpoint
            sts.PassiveRequestorEndpoints.Add(passiveEndpoint);

            // Add supported protocols
            sts.ProtocolsSupported.Add(new Uri(WSFederationConstants.Namespace));

            // Add passive STS endpoint
            sts.SecurityTokenServiceEndpoints.Add(passiveEndpoint);

            // Set credentials with which to sign the metadata
            entity.SigningCredentials = credentials;

            // Serialize the metadata and convert it to an XElement
            MetadataSerializer serializer = new MetadataSerializer();
            MemoryStream stream = new MemoryStream();
            serializer.WriteMetadata(stream, entity);
            stream.Flush();

            return stream.ToArray();
        }
        private static void CreateIdentityProviderMetadata(SamlSpData samlSpData, string fileName, Encoding encoding)
        {
            Constants.NameIdType nidFmt = samlSpData.NameIdType;

            MetadataSerializer serializer = new MetadataSerializer();
            ServiceProviderSingleSignOnDescriptor item = new ServiceProviderSingleSignOnDescriptor();

            EntityDescriptor metadata = new EntityDescriptor();
            metadata.EntityId = new EntityId(samlSpData.EntityId);

            //using 2.0
            if (Constants.NameIdType.Saml20 == nidFmt)
                item.NameIdentifierFormats.Add(Saml2Constants.NameIdentifierFormats.Transient);

            //using 1.1
            if (Constants.NameIdType.Saml11 == nidFmt)
                item.NameIdentifierFormats.Add(Saml2Constants.NameIdentifierFormats.Unspecified);

            item.ProtocolsSupported.Add(new Uri(Constants.Saml20Protocol));
            IndexedProtocolEndpoint ipEndpoint = new IndexedProtocolEndpoint()
                {
                    IsDefault=true,
                    Binding=new Uri(samlSpData.BindingType),
                    Location=new Uri(samlSpData.BindingLocation)
                };

            item.AssertionConsumerService.Add(0, ipEndpoint);

            metadata.RoleDescriptors.Add(item);

            metadata.Contacts.Add(new ContactPerson(ContactType.Technical)
            {
                Company = samlSpData.MainContact.Company,
                GivenName = samlSpData.MainContact.GivenName,
                Surname = samlSpData.MainContact.SurName,
                EmailAddresses = { samlSpData.MainContact.Email },
                TelephoneNumbers = { samlSpData.MainContact.Phone }
            });

            XmlTextWriter writer = new XmlTextWriter(fileName, encoding);
            serializer.WriteMetadata(writer, metadata);
            writer.Close();
        }
        private static EntityDescriptor ExtractEntityDescriptor(string fromXml, string forEntityId = null)
        {
            // extract entity descriptor from xml
            if (string.IsNullOrWhiteSpace(fromXml)) throw new ArgumentNullException("fromXml");

            // load xml into a document
            var xmlDocument = new XmlDocument();
            xmlDocument.LoadXml(fromXml);

            // xml may only be a single entity descriptor
            if (EntityDescriptor.IsValid(xmlDocument.DocumentElement))
            {
                // create a new entity descriptor
                var entityDescriptor = new EntityDescriptor(xmlDocument.DocumentElement);

                // entity descriptor is only valid when forEntityId argument has no value
                // or when the forEntityId argument has value and matches the entity descriptor
                if (string.IsNullOrWhiteSpace(forEntityId) // entityID match not enforced
                    || forEntityId.Equals(entityDescriptor.EntityID.URI, // entityID match enforced
                        StringComparison.OrdinalIgnoreCase))
                    return entityDescriptor;

                // forEntityId argument has value, and does not match entity descriptor
                return null;
            }

            // xml may be a n entities descriptor container
            if (EntitiesDescriptor.IsValid(xmlDocument.DocumentElement))
            {
                // create a new entities descriptor
                var entitiesDescriptor = new EntitiesDescriptor(xmlDocument.DocumentElement);

                // when forEntityId is specified, return specific entity descriptor
                // when forEntityId is not specified, return the first entity descriptor
                return (!string.IsNullOrWhiteSpace(forEntityId))
                    ? entitiesDescriptor.GetEntityDescriptor(forEntityId)
                    : entitiesDescriptor.EntityDescriptors.FirstOrDefault();
            }

            return null;
        }
Exemple #11
0
        // Creates an IdP entity descriptor
        private static EntityDescriptor CreateIDPEntityDescriptor()
        {
            EntityDescriptor entityDescriptor = new EntityDescriptor();
            entityDescriptor.EntityID = new EntityIDType("http://www.idp.com");
            entityDescriptor.IDPSSODescriptors.Add(CreateIDPSSODescriptor());

            Organization organization = new Organization();
            organization.OrganizationNames.Add(new OrganizationName("IdP", "en"));
            organization.OrganizationDisplayNames.Add(new OrganizationDisplayName("IdP", "en"));
            organization.OrganizationURLs.Add(new OrganizationURL("www.idp.com", "en"));
            entityDescriptor.Organization = organization;

            ContactPerson contactPerson = new ContactPerson();
            contactPerson.ContactTypeValue = "technical";
            contactPerson.GivenName = "Joe";
            contactPerson.Surname = "User";
            contactPerson.EmailAddresses.Add("*****@*****.**");
            entityDescriptor.ContactPeople.Add(contactPerson);

            return entityDescriptor;
        }
 public ActionResult Index()
 {
     var entityDescriptor = new EntityDescriptor(new EndpointReference("http://udv.itfoxtec.com/webapptest"), CertificateUtil.Load("~/App_Data/webapptest_certificate.pfx"));
     entityDescriptor.ValidUntil = 365;
     //entityDescriptor.SPSsoDescriptor = new SPSsoDescriptor(CertificateUtil.Load("~/App_Data/webapptest_certificate.pfx"), CertificateUtil.Load("~/App_Data/webapptest_encryptioncertificate.pfx")) 
     entityDescriptor.SPSsoDescriptor = new SPSsoDescriptor(CertificateUtil.Load("~/App_Data/webapptest_certificate.pfx")) 
     {
         WantAssertionsSigned = true,
         SingleLogoutService = new SingleLogoutService(ProtocolBindings.HttpRedirect, new EndpointAddress("https://udv.itfoxtec.com/webapptest/Auth/SingleLogout"), new EndpointAddress("https://udv.itfoxtec.com/webapptest/LoggedOut")),
         NameIDFormat = NameIdentifierFormats.X509SubjectName,
         AssertionConsumerService = new AssertionConsumerService(ProtocolBindings.HttpPost, new EndpointAddress("https://udv.itfoxtec.com/webapptest/Auth/AssertionConsumerService")),
         AttributeConsumingService = new AttributeConsumingService(new ServiceName("Some SP", "da"), CreateRequestedAttributes()),
     };
     entityDescriptor.ContactPerson = new ContactPerson(ContactTypes.Administrative)
     {
         Company = "Some Company",
         GivenName = "Some Given Name",
         SurName = "Some Sur Name",
         EmailAddress = "*****@*****.**",
         TelephoneNumber = "11111111",
     };
     return new Saml2Metadata(entityDescriptor).CreateMetadata().ToActionResult();
 }
 public EntityModelBuilder(EntityDescriptor descriptor, EntityModelBuilderConfiguration configuration)
 {
     Descriptor    = descriptor;
     Configuration = configuration;
 }
Exemple #14
0
        public void AtomParserLinkRelTest()
        {
            const string atomPayloadTemplate =
                @"HTTP/1.1 200 OK
Content-Type: application/atom+xml

<feed xmlns:d='http://docs.oasis-open.org/odata/ns/data' xmlns:m='http://docs.oasis-open.org/odata/ns/metadata' xmlns='http://www.w3.org/2005/Atom'>
  <title type='text'>ASet</title>
  <id>http://host/ASet</id>
  <updated>2010-09-01T23:36:00Z</updated>
  <link rel='self' title='ASet' href='ASet' />
  <entry>
    <id>http://host/ASet(1)</id>
    <title type='text'></title>
    <updated>2010-09-01T23:36:00Z</updated>
    <author>
      <name />
    </author>
    <link rel='{0}' title='EntityA' href='ASet(1)' />
    <link rel='{1}' title='EntityA' href='ASet(1)' />
    <link rel='{2}' title='EntityA' href='ASet(1)/$value' />
    <category term='NamespaceName.EntityA' scheme='http://docs.oasis-open.org/odata/ns/scheme' />
    <content type='CustomType/CustomSubType' src='ASet(1)/$value' />
    <m:properties>
      <d:ID m:type='Edm.Int32'>1</d:ID>
    </m:properties>
  </entry>
</feed>";

            string[] selfLinkRefs      = { "self", "http://www.iana.org/assignments/relation/self" };
            string[] editLinkRefs      = { "edit", "http://www.iana.org/assignments/relation/edit" };
            string[] editMediaLinkRefs = { "edit-media", "http://www.iana.org/assignments/relation/edit-media" };

            PlaybackServiceDefinition playbackService = new PlaybackServiceDefinition();

            using (TestWebRequest request = playbackService.CreateForInProcessWcf())
            {
                request.ServiceType        = typeof(PlaybackService);
                request.ForceVerboseErrors = true;
                request.StartService();

                TestUtil.RunCombinations(selfLinkRefs, editLinkRefs, editMediaLinkRefs, (self, edit, editMedia) =>
                {
                    DataServiceContext ctx = new DataServiceContext(request.ServiceRoot);
                    ctx.EnableAtom         = true;

                    string atomPayload = string.Format(atomPayloadTemplate, self, edit, editMedia);
                    playbackService.OverridingPlayback = atomPayload;

                    foreach (var item in ctx.CreateQuery <EntityA>("ASet"))
                    {
                        Assert.IsNotNull(item, "item");
                    }

                    EntityDescriptor entity = ctx.Entities.Single();

                    Assert.AreEqual(ctx.BaseUri + "/ASet(1)", entity.SelfLink.OriginalString);
                    Assert.AreEqual(ctx.BaseUri + "/ASet(1)", entity.EditLink.OriginalString);
                    Assert.AreEqual(ctx.BaseUri + "/ASet(1)/$value", entity.ReadStreamUri.OriginalString);
                    Assert.AreEqual(ctx.BaseUri + "/ASet(1)/$value", entity.EditStreamUri.OriginalString);
                });
            }
        }
Exemple #15
0
 void Awake()
 {
     ownerDescriptor = GetComponent<EntityDescriptor>();
     controller = GetComponent<CharacterController>();
 }
        static void CreatePassiveStsMetadata(StsData data, string fileName, Encoding encoding)
        {
            MetadataSerializer serializer = new MetadataSerializer();
            SecurityTokenServiceDescriptor item = new SecurityTokenServiceDescriptor();
            EntityDescriptor metadata = new EntityDescriptor();
            metadata.EntityId = new EntityId(data.EntityId);

            X509Certificate2 certificate = CertificateHelper.RetrieveCertificate(data.SigninCertificateCn);

            metadata.SigningCredentials = new X509SigningCredentials(certificate);
            KeyDescriptor descriptor3 = new KeyDescriptor(new SecurityKeyIdentifier(new SecurityKeyIdentifierClause[] { new X509SecurityToken(certificate).CreateKeyIdentifierClause<X509RawDataKeyIdentifierClause>() }));
            descriptor3.Use = KeyType.Signing;
            item.Keys.Add(descriptor3);

            if (data.Claims != null)
            {
                foreach (var claim in data.Claims)
                {
                    DisplayClaim dc = new DisplayClaim(claim.ClaimType, claim.DisplayTag, claim.Description)
                    {
                        Optional = claim.Optional
                    };

                    item.ClaimTypesOffered.Add(dc);
                }
            }

            item.PassiveRequestorEndpoints.Add(new EndpointAddress( new Uri(data.PassiveRequestorEndpoint).AbsoluteUri));

            if (data.Protocols != null)
            {
                foreach (Protocol protocol in data.Protocols)
                {
                    item.ProtocolsSupported.Add(new Uri(protocol.ProtocolNamespace));
                }
            }

            item.SecurityTokenServiceEndpoints.Add(new EndpointAddress( new Uri(data.ActiveStsEndpoint).AbsoluteUri));
            item.Contacts.Add(new ContactPerson(ContactType.Technical)
            {
                Company = data.MainContact.Company,
                GivenName = data.MainContact.GivenName,
                Surname = data.MainContact.SurName,
                EmailAddresses = { data.MainContact.Email },
                TelephoneNumbers = { data.MainContact.Phone }
            });

            metadata.RoleDescriptors.Add(item);

            XmlTextWriter writer = new XmlTextWriter(fileName, Encoding.UTF8);
            serializer.WriteMetadata(writer, metadata);
            writer.Close();
        }
 /// <param name="entityDescriptor">[Required] The EntitiesDescriptor element contains the metadata for an optionally named group of SAML entities.</param>
 public Saml2Metadata(EntityDescriptor entityDescriptor)
 {
     EntityDescriptor = entityDescriptor;
 }
 /// <summary>
 /// Creates Saml2 metadata Xml Document.
 /// </summary>
 public Saml2Metadata CreateMetadata()
 {
     XmlDocument = EntityDescriptor.ToXmlDocument();
     return(this);
 }
 /// <summary>
 /// If overridden, returns the sql builder associated with the optional entity descriptor and entity mapping.
 /// Note: Any or all the parameters can be <c>NULL</c>
 /// </summary>
 protected virtual ISqlBuilder GetSqlBuilder(EntityDescriptor entityDescriptor, EntityMapping entityMapping)
 {
     return(null);
 }
Exemple #20
0
        private static void SaveMetadata(EntityDescriptor entityDescriptor)
        {
            Console.WriteLine("Saving SAML metadata to {0}.", metadataFileName);

            XmlDocument xmlDocument = entityDescriptor.ToXml().OwnerDocument;

            using (XmlTextWriter xmlTextWriter = new XmlTextWriter(metadataFileName, null)) {
                xmlTextWriter.Formatting = Formatting.Indented;
                xmlDocument.Save(xmlTextWriter);
            }
        }
Exemple #21
0
        private void RunPositiveFunctionTest(ODataFormat format, TestCase testCase)
        {
            // All of the functions tests use the PlaybackService since the WCF Data Services server doesn't support functions
            // The PlaybackService itself will not automatically turn Metadata into an absolute URI, so set that to false on all tests.
            // The tests also use absolute URIs for Target, so suppress that as well.
            testCase.AddBaseUriToMetadata = false;
            testCase.AddBaseUriToTarget   = false;

            using (TestWebRequest request = TestWebRequest.CreateForInProcessWcf())
                using (PlaybackService.ProcessRequestOverride.Restore())
                {
                    request.ServiceType = typeof(AstoriaUnitTests.Stubs.PlaybackService);
                    request.StartService();

                    var payloadBuilder = testCase.ResponsePayloadBuilder;
                    PlaybackService.ProcessRequestOverride.Value = (req) =>
                    {
                        string contentType;
                        if (format == ODataFormat.Json)
                        {
                            contentType             = UnitTestsUtil.JsonLightMimeType;
                            payloadBuilder.Metadata = request.BaseUri + "/$metadata#TestService.CustomerEntities/$entity";
                        }
                        else
                        {
                            contentType = UnitTestsUtil.AtomFormat;
                        }

                        req.SetResponseStreamAsText(PayloadGenerator.Generate(payloadBuilder, format));
                        req.ResponseHeaders.Add("Content-Type", contentType);
                        req.SetResponseStatusCode(200);
                        return(req);
                    };

                    testCase.AddBaseUriStringToExpectedDescriptors(request.ServiceRoot.OriginalString, format);

                    Uri uri = new Uri(request.ServiceRoot + "/" + testCase.RequestUriString);
                    DataServiceContext ctx = new DataServiceContext(request.ServiceRoot, ODataProtocolVersion.V4);
                    //ctx.EnableAtom = true;

                    if (format == ODataFormat.Json)
                    {
                        string serviceEdmx = GetServiceEdmxWithOperations(payloadBuilder);
                        JsonLightTestUtil.ConfigureContextForJsonLight(ctx, serviceEdmx);
                    }

                    QueryOperationResponse <CustomerEntity> qor = (QueryOperationResponse <CustomerEntity>)ctx.Execute <CustomerEntity>(uri);
                    Assert.IsNotNull(qor);
                    Assert.IsNull(qor.Error);

                    IEnumerator <CustomerEntity> entities = qor.GetEnumerator();

                    int expectedDescriptorsPerEntity = 0;

                    while (entities.MoveNext())
                    {
                        CustomerEntity   c  = entities.Current;
                        EntityDescriptor ed = ctx.GetEntityDescriptor(c);
                        IEnumerable <OperationDescriptor> actualDescriptors = ed.OperationDescriptors;
                        TestEquality(actualDescriptors, testCase.GetExpectedDescriptors(format)[expectedDescriptorsPerEntity++]);
                    }
                }
        }
Exemple #22
0
 /// <summary>
 /// If overriden, returns the sql builder associated with the optional entity descriptor and entity mapping.
 /// Note: Any or all the parameters can be <c>NULL</c>
 /// </summary>
 protected override ISqlBuilder GetSqlBuilder(EntityDescriptor entityDescriptor, EntityMapping entityMapping)
 {
     return(((entityDescriptor as EntityDescriptor <TEntity>) ?? OrmConfiguration.GetEntityDescriptor <TEntity>())
            .GetSqlStatements(entityMapping)
            .SqlBuilder);
 }
Exemple #23
0
        Action <IDatabase, DbCommand, TEntity> IOperationBuilder <Action <IDatabase, DbCommand, TEntity> > .BuildInvoker(EntityDescriptor descriptor)
        {
            Initialize(descriptor);

            var memberBinder    = CreateParameterBinder(_members, BuildSetParameter);
            var conditionBinder = CreateParameterBinder(_keys, BuildConditionParameter);

            return((db, command, entity) =>
            {
                memberBinder(db, command, entity);
                conditionBinder(db, command, entity);
                db.ExecuteNonQuery(command);
            });
        }
Exemple #24
0
        Func <IDatabase, DbCommand> IOperationBuilder <Action <IDatabase, DbCommand, TEntity> > .BuildCommandProvider(EntityDescriptor descriptor)
        {
            Initialize(descriptor);

            var sql = new StringBuilder("UPDATE ")
                      .Append(string.IsNullOrEmpty(_descriptor.Schema) ? null : (Quote(_descriptor.Schema) + '.'))
                      .AppendLine(Quote(_descriptor.Name))
                      .Append(" SET ")
                      .AppendJoin(", ", _members.Select((_, i) => Quote(_.Name) + " = " + BuildSetParameter(i)))
                      .AppendLine()
                      .Append(" WHERE ")
                      .AppendJoin(", ", _keys.Select((_, i) => Quote(_.Name) + " = " + BuildConditionParameter(i)))
                      .ToString();

            return(db => db.GetSqlStringCommand(sql));
        }
Exemple #25
0
        public void AtomParserNavigationLinkTypeTest()
        {
            const string atomPayloadTemplate =
                @"HTTP/1.1 200 OK
Content-Type: application/atom+xml

<feed xmlns:d='http://docs.oasis-open.org/odata/ns/data' xmlns:m='http://docs.oasis-open.org/odata/ns/metadata' xmlns='http://www.w3.org/2005/Atom'>
  <title type='text'>ASet</title>
  <id>http://host/ASet</id>
  <updated>2010-09-01T23:36:00Z</updated>
  <link rel='self' title='ASet' href='ASet' />
  <entry>
    <id>http://host/ASet(1)</id>
    <title type='text'></title>
    <updated>2010-09-01T23:36:00Z</updated>
    <author>
      <name />
    </author>
    <link rel='http://docs.oasis-open.org/odata/ns/related/{0}' title='{0}' href='ASet' type='{1}'>{2}</link>
    <category term='NamespaceName.EntityA' scheme='http://docs.oasis-open.org/odata/ns/scheme' />
    <content type='CustomType/CustomSubType' src='ASet(1)/$value' />
    <m:properties>
      <d:ID m:type='Edm.Int32'>1</d:ID>
    </m:properties>
  </entry>
</feed>";

            var linkTypes = new[]
            {
                new
                {
                    LinkType             = "application/atom+xml;type=entry",
                    ExpectedErrorMessage = new Func <bool, bool?, string>((collection, expandedFeed) =>
                    {
                        // If the link type is entry:
                        // - For collection property, it must fail since the type must match the model
                        // - If the link is expanded the payload must match the model
                        if (collection && expandedFeed == false)
                        {
                            return(ODataLibResourceUtil.GetString("ODataAtomReader_ExpandedEntryInFeedNavigationLink"));
                        }
                        if (collection && expandedFeed == true)
                        {
                            return(ODataLibResourceUtil.GetString("ODataAtomReader_ExpandedFeedInEntryNavigationLink"));
                        }
                        if (collection)
                        {
                            return(ODataLibResourceUtil.GetString("ODataAtomReader_DeferredEntryInFeedNavigationLink"));
                        }
                        if (!collection && expandedFeed == true)
                        {
                            return(ODataLibResourceUtil.GetString("ODataAtomReader_ExpandedFeedInEntryNavigationLink"));
                        }
                        return(null);
                    }),
                    RecognizedLinkType = true,
                },
                new
                {
                    LinkType             = "application/atom+xml;type=feed",
                    ExpectedErrorMessage = new Func <bool, bool?, string>((collection, expandedFeed) =>
                    {
                        // If the link type is feed:
                        // - If the link is not expanded the type must match the model
                        // - If the link is expanded the expanded payload must match the model as well.
                        if (!collection)
                        {
                            return(ODataLibResourceUtil.GetString("ODataAtomReader_FeedNavigationLinkForResourceReferenceProperty", "Singleton"));
                        }
                        if (collection && expandedFeed == false)
                        {
                            return(ODataLibResourceUtil.GetString("ODataAtomReader_ExpandedEntryInFeedNavigationLink"));
                        }
                        return(null);
                    }),
                    RecognizedLinkType = true,
                },
                new
                {
                    LinkType = "application/atom+xml",
                    // Breaking change: we are not recognizing links even when type is missing
                    // If the link has no type, client doesn't recognize this as a nav. prop.
                    ExpectedErrorMessage = new Func <bool, bool?, string>((collection, expandedFeed) =>
                    {
                        if (!collection && expandedFeed == true)
                        {
                            return(ODataLibResourceUtil.GetString("ODataAtomReader_ExpandedFeedInEntryNavigationLink"));
                        }
                        if (collection && expandedFeed == false)
                        {
                            return(ODataLibResourceUtil.GetString("ODataAtomReader_ExpandedEntryInFeedNavigationLink"));
                        }
                        return(null);
                    }),
                    RecognizedLinkType = true,
                },
                new
                {
                    LinkType = "application/atom+xml;type=test",
                    // Breaking change: we are not recognizing links even when type is wrong
                    // If the link has wrong type, client doesn't recognize this as a nav. prop.
                    ExpectedErrorMessage = new Func <bool, bool?, string>((collection, expandedFeed) =>
                    {
                        if (!collection && expandedFeed == true)
                        {
                            return(ODataLibResourceUtil.GetString("ODataAtomReader_ExpandedFeedInEntryNavigationLink"));
                        }
                        if (collection && expandedFeed == false)
                        {
                            return(ODataLibResourceUtil.GetString("ODataAtomReader_ExpandedEntryInFeedNavigationLink"));
                        }
                        return(null);
                    }),
                    RecognizedLinkType = true,
                },
            };

            string deferredLinkBody  = string.Empty;
            string expandedFeedBody  = "<m:inline><feed/></m:inline>";
            string expandedEntryBody = "<m:inline><entry><id>http://host/ASet</id></entry></m:inline>";

            PlaybackServiceDefinition playbackService = new PlaybackServiceDefinition();

            using (TestWebRequest request = playbackService.CreateForInProcessWcf())
            {
                request.ServiceType        = typeof(PlaybackService);
                request.ForceVerboseErrors = true;
                request.StartService();

                TestUtil.RunCombinations(
                    new string[] { "Singleton", "Collection" },
                    new bool?[] { null, false, true },
                    linkTypes,
                    (propertyName, expandedFeed, linkType) =>
                {
                    DataServiceContext ctx = new DataServiceContext(request.ServiceRoot);
                    ctx.EnableAtom         = true;

                    string linkBody    = expandedFeed.HasValue ? (expandedFeed == true ? expandedFeedBody : expandedEntryBody) : deferredLinkBody;
                    string atomPayload = string.Format(atomPayloadTemplate, propertyName, linkType.LinkType, linkBody);
                    playbackService.OverridingPlayback = atomPayload;

                    Exception exception = TestUtil.RunCatching(() => ctx.CreateQuery <EntityWithNavigationProperties>("ASet").AsEnumerable().Count());

                    string expectedExceptionMessage = linkType.ExpectedErrorMessage(propertyName == "Collection", expandedFeed);

                    if (exception == null)
                    {
                        Assert.IsNull(expectedExceptionMessage, "The test case was expected to fail.");
                        EntityDescriptor entity = ctx.Entities.Single(e => e.Identity == new Uri("http://host/ASet(1)"));
                        if (linkType.RecognizedLinkType)
                        {
                            Assert.AreEqual(ctx.BaseUri + "/ASet", entity.LinkInfos.Single(li => li.Name == propertyName).NavigationLink.OriginalString);
                        }
                        else
                        {
                            Assert.AreEqual(0, entity.LinkInfos.Count, "The link should not have been recognized as a navigation link.");
                        }
                    }
                    else
                    {
                        Assert.IsNotNull(expectedExceptionMessage, "The test case was expected to succeed.");
                        Assert.AreEqual(expectedExceptionMessage, exception.Message, "Unexpected error.");
                    }
                });
            }
        }
Exemple #26
0
        // Reads an entity descriptor
        private static void ReadEntityDescriptor(EntityDescriptor entityDescriptor)
        {
            foreach (IDPSSODescriptor idpSSODescriptor in entityDescriptor.IDPSSODescriptors) {
                foreach (EndpointType singleSignOnService in idpSSODescriptor.SingleSignOnServices) {
                    Console.WriteLine("Binding: " + singleSignOnService.Binding);
                    Console.WriteLine("Location: " + singleSignOnService.Location);
                }

                ReadX509Certificates(idpSSODescriptor);
            }

            foreach (SPSSODescriptor spSSODescriptor in entityDescriptor.SPSSODescriptors) {
                foreach (EndpointType assertionConsumerService in spSSODescriptor.AssertionConsumerServices) {
                    Console.WriteLine("Binding: " + assertionConsumerService.Binding);
                    Console.WriteLine("Location: " + assertionConsumerService.Location);
                }

                ReadX509Certificates(spSSODescriptor);
            }

            foreach (OrganizationDisplayName organizationDisplayName in entityDescriptor.Organization.OrganizationDisplayNames) {
                Console.WriteLine("Organization: " + organizationDisplayName.Name);
            }
        }
        private static void QueryEntityInstance(DataServiceContextWrapper <DefaultContainer> contextWrapper)
        {
            contextWrapper.Context.IgnoreMissingProperties = true;

            contextWrapper.Configurations.ResponsePipeline
            .OnEntryEnded(PipelineEventsTestsHelper.AddRemovePropertySpecialEmployeeEntry_Reading)
            .OnEntityMaterialized(PipelineEventsTestsHelper.AddEnumPropertySpecialEmployeeEntity_Materialized)
            .OnEntityMaterialized(PipelineEventsTestsHelper.ModifyPropertyValueCustomerEntity_Materialized);

            var specialEmployee =
                contextWrapper.CreateQuery <Person>("Person").Where(p => p.PersonId == -10).Single() as SpecialEmployee;
            EntityDescriptor descriptor = contextWrapper.GetEntityDescriptor(specialEmployee);

            Assert.AreEqual("AddRemovePropertySpecialEmployeeEntry_Reading", specialEmployee.CarsLicensePlate,
                            "Unexpected CarsLicensePlate");
            Assert.AreEqual(1, specialEmployee.BonusLevel, "Unexpected BonusLevel");

            specialEmployee = contextWrapper.Execute <SpecialEmployee>(new Uri("Person(-10)", UriKind.Relative)).Single();
            Assert.AreEqual("AddRemovePropertySpecialEmployeeEntry_Reading", specialEmployee.CarsLicensePlate,
                            "Unexpected CarsLicensePlate");
            Assert.AreEqual(1, specialEmployee.BonusLevel, "Unexpected BonusLevel");

            DataServiceRequest[] requests = new DataServiceRequest[]
            {
                contextWrapper.CreateQuery <Person>("Person"),
                contextWrapper.CreateQuery <Customer>("Customer"),
            };

            DataServiceResponse responses = contextWrapper.ExecuteBatch(requests);
            bool personVerified           = false;
            bool customerVerified         = false;

            foreach (QueryOperationResponse response in responses)
            {
                foreach (object p in response)
                {
                    var      specialEmployee1 = p as SpecialEmployee;
                    Customer c = p as Customer;
                    if (specialEmployee1 != null)
                    {
                        Assert.AreEqual("AddRemovePropertySpecialEmployeeEntry_Reading", specialEmployee1.CarsLicensePlate,
                                        "Unexpected CarsLicensePlate");
                        Assert.AreEqual(1, specialEmployee1.BonusLevel, "Unexpected BonusLevel");
                        personVerified = true;
                    }

                    if (c != null)
                    {
                        Assert.IsTrue(c.Name.EndsWith("ModifyPropertyValueCustomerEntity_Materialized"),
                                      "Unexpected primitive property");
                        Assert.IsTrue(c.Auditing.ModifiedBy.Equals("ModifyPropertyValueCustomerEntity_Materialized"),
                                      "Unexpected complex property");
                        Assert.IsTrue(c.PrimaryContactInfo.EmailBag.Contains("ModifyPropertyValueCustomerEntity_Materialized"),
                                      "Unexpected collection property");
                        customerVerified = true;
                    }
                }
            }

            Assert.IsTrue(personVerified && customerVerified, "Some inner request does not completed correctly");
        }
Exemple #28
0
 /// <summary>
 /// Creates the materializer entry for LoadProperty scenario.
 /// </summary>
 /// <param name="descriptor">The entity descriptor.</param>
 /// <param name="format">The format the entry was read in.</param>
 /// <param name="isTracking">True if the contents of the entry will be tracked in the context, otherwise False.</param>
 /// <returns>A new materializer entry.</returns>
 public static MaterializerEntry CreateEntryForLoadProperty(EntityDescriptor descriptor, ODataFormat format, bool isTracking)
 {
     return(new MaterializerEntry(descriptor, format, isTracking));
 }
 public PostgreSqlBuilder(EntityDescriptor entityDescriptor, EntityMapping entityMapping)
     : base(entityDescriptor, entityMapping, SqlDialect.PostgreSql)
 {
 }
Exemple #30
0
 public BulkCopyReader(EntityDescriptor entityDescriptor, IEnumerable collection)
 {
     Columns     = entityDescriptor.Columns.Where(c => !c.SkipOnInsert).ToArray();
     _collection = collection;
     _enumerator = _collection.GetEnumerator();
 }
 /* Returns a float indicating how well a can hear b. */
 public static float CompareAudibility(EntityDescriptor a, EntityDescriptor b)
 {
     return 1 / Vector3.Distance(a.gameObject.transform.position, b.gameObject.transform.position);
 }
Exemple #32
0
 // Use this for initialization
 void Start()
 {
     descriptor = GetComponent<EntityDescriptor>();
     animator = GetComponent<Animator>();
 }
            public EntityStates GetEntityState(object entity)
            {
                EntityDescriptor descriptor = this.TableServiceContext.GetEntityDescriptor(entity);

                return((descriptor == null) ? EntityStates.Detached : descriptor.State);
            }
 /// <param name="entityDescriptor">[Required] The EntitiesDescriptor element contains the metadata for an optionally named group of SAML entities.</param>
 public Saml2Metadata(EntityDescriptor entityDescriptor)
 {
     EntityDescriptor = entityDescriptor;
 }
Exemple #35
0
 /// <summary>
 /// Where Constructor
 /// </summary>
 /// <param name="entityDescriptor">Entity Descriptor instance</param>
 /// <param name="referObject">Refered Object instance</param>
 public DeleteImpl(EntityDescriptor entityDescriptor, Object referObject)
 {
     this.entityDescriptor = entityDescriptor;
     this.referObject      = referObject;
 }
        private static void CreateIdentityProviderMetadata(SamlIdpData idpData, string fileName, Encoding encoding)
        {
            if ( string.IsNullOrEmpty(idpData.SigninCertificateCn))
                throw new ApplicationException("no CN for a Certificate supplied");

            string signingCertificateSubjectName = idpData.SigninCertificateCn;

            Constants.NameIdType nidFmt = idpData.NameIdType;

            MetadataSerializer serializer = new MetadataSerializer();
            IdentityProviderSingleSignOnDescriptor item = new IdentityProviderSingleSignOnDescriptor();

            EntityDescriptor metadata = new EntityDescriptor();
            metadata.EntityId = new EntityId(idpData.EntityId);

            X509Certificate2 certificate = CertificateHelper.RetrieveCertificate(signingCertificateSubjectName);
            KeyDescriptor descriptor = new KeyDescriptor(
                new SecurityKeyIdentifier(
                    new SecurityKeyIdentifierClause[]
                    {
                        new X509SecurityToken(certificate).CreateKeyIdentifierClause<X509RawDataKeyIdentifierClause>()
                    }));

            descriptor.Use = KeyType.Signing;
            item.Keys.Add(descriptor);

            //using 2.0
            if (Constants.NameIdType.Saml20 == nidFmt)
                item.NameIdentifierFormats.Add(Saml2Constants.NameIdentifierFormats.Transient);

            //using 1.1
            if (Constants.NameIdType.Saml11 == nidFmt)
                item.NameIdentifierFormats.Add(Saml2Constants.NameIdentifierFormats.Unspecified);

            foreach (var attributeName in idpData.AttributeNames)
            {
                Saml2Attribute at1 = new Saml2Attribute(attributeName.Name)
                {
                    NameFormat = new Uri(Constants.Saml20AttributeNameFormat)
                };
                item.SupportedAttributes.Add(at1);
            }

            item.ProtocolsSupported.Add(new Uri(Constants.Saml20Protocol));
            item.SingleSignOnServices.Add(new ProtocolEndpoint(new Uri(idpData.BindingType), new Uri(idpData.BindingLocation)));

            metadata.RoleDescriptors.Add(item);

            metadata.Contacts.Add(new ContactPerson(ContactType.Technical)
            {
                Company = idpData.MainContact.Company,
                GivenName = idpData.MainContact.GivenName,
                Surname = idpData.MainContact.SurName,
                EmailAddresses = { idpData.MainContact.Email },
                TelephoneNumbers = { idpData.MainContact.Phone }
            });

            XmlTextWriter writer = new XmlTextWriter(fileName, encoding);
            serializer.WriteMetadata(writer, metadata);
            writer.Close();
        }
 public MetadataActionResult(EntityDescriptor metadata)
 {
     this.metadata = metadata;
 }
Exemple #38
0
        protected internal static string GetTableName(ISqlBuilder sqlBuilder, BulkCopyOptions options, EntityDescriptor descriptor)
        {
            var databaseName = options.DatabaseName ?? descriptor.DatabaseName;
            var schemaName   = options.SchemaName ?? descriptor.SchemaName;
            var tableName    = options.TableName ?? descriptor.TableName;

            return(sqlBuilder.BuildTableName(
                       new StringBuilder(),
                       databaseName == null ? null : sqlBuilder.Convert(databaseName, ConvertType.NameToDatabase).ToString(),
                       schemaName == null ? null : sqlBuilder.Convert(schemaName, ConvertType.NameToOwner).ToString(),
                       tableName == null ? null : sqlBuilder.Convert(tableName, ConvertType.NameToQueryTable).ToString())
                   .ToString());
        }
 public MetadataResult(EntityDescriptor entity)
 {
     _entity = entity;
 }
Exemple #40
0
        public void AtomParserDuplicateTest_AfterODataLibIntegration()
        {
            // BUG:
            // The following breaking changes are taken in WCF DS client. Once "ODataLib - WCF DS client" integration is complete, enable the asserts in this test.
            // Current ODataLib behavior for WCF DS client is the following.
            // (a) Read the first entry/category element with a valid scheme even if it does not have a term attribute.
            // (b) Throw if there are duplicate entry/link/m:inline elements
            // (c) For m:properties:
            //      For entry/content/m:properties, the first m:properties in each of the entry/content elements is taken and merged.
            //      For entry/m:properties, all duplicates are read and merged.
            // (d) Relationship links are V3 feature. So, we will change WCF DS client do disallow duplicates.
            // (e) Named streams are V3 feature. If we see two different mime types when processing two named streams with the same name but are read and edit links respectively, we will throw.
            // (f) Named streams are V3 feature. If we see named stream duplicates, we will throw.

            const string atomPayloadTemplate =
                @"HTTP/1.1 200 OK
Content-Type: application/atom+xml

<feed xmlns:d='http://docs.oasis-open.org/odata/ns/data' xmlns:m='http://docs.oasis-open.org/odata/ns/metadata' xmlns='http://www.w3.org/2005/Atom'>
  <m:count>3</m:count>
  <title type='text'>ASet</title>
  <id>http://host/ASet</id>
  <updated>2010-09-01T23:36:00Z</updated>
  <link rel='self' title='ASet' href='ASet' />
  <entry>
    <id>http://host/ASet(2)</id>
    <id>http://host/ASet(1)</id>
    <title type='text'></title>
    <updated>2010-09-01T23:36:00Z</updated>
    <author>
      <name />
    </author>
    {0}
  </entry>
</feed>";
            var tests = new[]
            {
                new
                {
                    Type    = "AssociationLinks",
                    Payload = @"
    <link rel='http://docs.oasis-open.org/odata/ns/relatedlinks/NavProp' href='http://odata.org/link1' type='application/xml'/>
    <link rel='http://docs.oasis-open.org/odata/ns/relatedlinks/NavProp' href='http://odata.org/link2' type='application/xml'/>"
                },
                new
                {
                    Type    = "NavigationLinks",
                    Payload = @"
    <link rel='http://docs.oasis-open.org/odata/ns/related/RelProp' href='http://odata.org/link3' type='application/atom+xml;type=entry'/>
    <link rel='http://docs.oasis-open.org/odata/ns/related/RelProp' href='http://odata.org/link4' type='application/atom+xml;type=entry'/>"
                },
                new
                {
                    // mime types differ for the same stream. This is not allowed.
                    Type    = "NamedStreams",
                    Payload = @"
    <link rel='http://docs.oasis-open.org/odata/ns/mediaresource/NamedStream' href='http://odata.org/readlink' type='mime/type1'/>
    <link rel='http://docs.oasis-open.org/odata/ns/edit-media/NamedStream' href='http://odata.org/editlink' type='mime/type2'/>"
                },
                new
                {
                    Type    = "MediaResourceStreams",
                    Payload = @"
    <link rel='http://docs.oasis-open.org/odata/ns/mediaresource/MediaResourceStreamDup' href='http://odata.org/readlink1' type='mime/type3'/>
    <link rel='http://docs.oasis-open.org/odata/ns/mediaresource/MediaResourceStreamDup' href='http://odata.org/readlink2' type='mime/type4'/>"
                },
                new
                {
                    Type    = "EditMedialinks",
                    Payload = @"
    <link rel='http://docs.oasis-open.org/odata/ns/edit-media/EditMediaStreamDup' href='http://odata.org/editlink1' type='mime/type5'/>
    <link rel='http://docs.oasis-open.org/odata/ns/edit-media/EditMediaStreamDup' href='http://odata.org/editlink2' type='mime/type6'/>"
                },
                new
                {
                    Type    = "Content",
                    Payload = @"    
          <content type='application/xml' >
             <m:properties>
                <d:ID m:type='Edm.Int32'>1</d:ID>
             </m:properties>
          </content>
          <content src='http://odata.org'/>"
                },
                new
                {
                    Type    = "Properties",
                    Payload = @"
    <link rel='http://docs.oasis-open.org/odata/ns/related/B' type='application/atom+xml;type=entry' title='B' href='Customer(1)/B'>
      <m:inline>
        <entry>
          <id>http://host/BSet(1)</id>
          <content type='application/xml' >
             <m:properties>
                <d:ID m:type='Edm.Int32'>1</d:ID>
                <d:Prop1 m:type='Edm.Int32'>1</d:Prop1>
             </m:properties>
             <m:properties>
                <d:Prop1 m:type='Edm.Int32'>2</d:Prop1>
             </m:properties>
          </content>
          <content type='application/xml' >
             <m:properties>
                <d:ID m:type='Edm.Int32'>2</d:ID>
                <d:Prop1 m:type='Edm.Int32'>3</d:Prop1>
             </m:properties>
             <m:properties>
                <d:Prop1 m:type='Edm.Int32'>4</d:Prop1>
             </m:properties>
          </content>
        </entry>      
      </m:inline>
    </link>
    <m:properties>
        <d:ID m:type='Edm.Int32'>1</d:ID>
        <d:Prop1 m:type='Edm.Int32'>1</d:Prop1>
    </m:properties>
    <m:properties>
        <d:Prop1 m:type='Edm.Int32'>2</d:Prop1>
    </m:properties>"
                },
                new
                {
                    Type    = "TypeScheme",
                    Payload = @"
    <category scheme='http://docs.oasis-open.org/odata/ns/scheme' />
    <category scheme='http://docs.oasis-open.org/odata/ns/scheme' term='NamespaceName.EntityB' />"
                },
                new
                {
                    Type    = "InlineElements",
                    Payload = @"
      <link rel='http://docs.oasis-open.org/odata/ns/related/B' type='application/atom+xml;type=entry' title='B' href='Customer(1)/B'>
      <m:inline>
        <entry>
          <id>http://host/BSet(2)</id>
          <content type='application/xml' >
             <m:properties>
                <d:ID m:type='Edm.Int32'>2</d:ID>
                <d:Prop1 m:type='Edm.Int32'>5</d:Prop1>
             </m:properties>
             <m:properties>
                <d:Prop1 m:type='Edm.Int32'>6</d:Prop1>
             </m:properties>
          </content>
        </entry>
      </m:inline>
      <m:inline/>
      </link>"
                },
            };

            string[] shouldFailTests = new string[] { "AssociationLinks", "NamedStreams", "Content", "MediaResourceStreams", "EditMedialinks", "InlineElements", "Properties" };
            string[] shouldPassTests = new string[] { "NavigationLinks", "TypeScheme" };

            PlaybackServiceDefinition playbackService = new PlaybackServiceDefinition();

            using (TestWebRequest request = playbackService.CreateForInProcessWcf())
            {
                request.ServiceType        = typeof(PlaybackService);
                request.ForceVerboseErrors = true;
                request.StartService();

                TestUtil.RunCombinations(tests, (test) =>
                {
                    DataServiceContext ctx = new DataServiceContext(request.ServiceRoot, ODataProtocolVersion.V4);
                    ctx.EnableAtom         = true;

                    playbackService.OverridingPlayback = string.Format(atomPayloadTemplate, test.Payload);
                    EntityA entity = null;
                    Exception ex   = TestUtil.RunCatching(() => entity = ctx.CreateQuery <EntityA>("ASet").FirstOrDefault());

                    if (shouldFailTests.Contains(test.Type))
                    {
                        Assert.IsNotNull(ex, test.Type + " expects an exception but got none.");
                    }
                    else
                    {
                        Assert.IsNull(ex, test.Type + " expects to pass but got an exception: " + ex);
                    }

                    // Duplicate navigation links are allowed.
                    if (test.Type == "NavigationLinks")
                    {
                        EntityDescriptor descriptor = ctx.Entities.First();
                        Assert.AreEqual(1, descriptor.LinkInfos.Count());
                        Assert.AreEqual("http://odata.org/link4", descriptor.LinkInfos[0].NavigationLink.AbsoluteUri);
                    }

                    // Read the first entry/category element with a valid scheme even if the term attribute is not present.
                    if (test.Type == "TypeScheme")
                    {
                        EntityDescriptor descriptor = ctx.Entities.First();
                        Assert.AreEqual(null, descriptor.ServerTypeName);
                    }
                });
            }
        }
 /*
     Returns a float indicating the level of danger for a to interact with b. The
    	value has no meaning aside from comparison purposes.
 */
 public static float CompareDanger(EntityDescriptor a, EntityDescriptor b)
 {
     return b.hp - a.hp;
 }
 // Use this for initialization
 void Start()
 {
     descriptor = memoizer.GetMemoizedComponent<EntityDescriptor>(gameObject);
     movement = memoizer.GetMemoizedComponent<MovementCC>(gameObject);
     animator = memoizer.GetMemoizedComponent<Animator>(unit);
 }
 public MetadataResult(EntityDescriptor entity)
 {
     _entity = entity;
 }
Exemple #44
0
 /// <summary>
 /// Where Constructor
 /// </summary>
 /// <param name="entityDescriptor">Entity Descriptor instance</param>
 public DeleteImpl(EntityDescriptor entityDescriptor)
 {
     this.entityDescriptor = entityDescriptor;
 }