/// <summary>
		/// Creates a new instance, using the init parameters of a <see cref="StatefulService"/>
		/// </summary>
		/// <param name="receiver">(Required) Processes incoming messages.</param>
		/// <param name="context">(Optional) The context that was used to init the Reliable Service that uses this listener.</param>
		/// <param name="serviceBusQueueName">The name of the monitored Service Bus Queue</param>
		/// <param name="serviceBusSendConnectionString">(Optional) A Service Bus connection string that can be used for Sending messages. 
		/// (Returned as Service Endpoint.) When not supplied, an App.config appSettings value with key 'Microsoft.ServiceBus.ConnectionString.Receive'
		///  is used.</param>
		/// <param name="serviceBusReceiveConnectionString">(Optional) A Service Bus connection string that can be used for Receiving messages. 
		///  When not supplied, an App.config appSettings value with key 'Microsoft.ServiceBus.ConnectionString.Receive'
		///  is used.</param>
		public ServiceBusQueueCommunicationListener(IServiceBusMessageReceiver receiver, ServiceContext context, string serviceBusQueueName, string serviceBusSendConnectionString = null, string serviceBusReceiveConnectionString = null)
			: base(receiver, context, serviceBusSendConnectionString, serviceBusReceiveConnectionString)
		{
			if (string.IsNullOrWhiteSpace(serviceBusQueueName)) throw new ArgumentOutOfRangeException(nameof(serviceBusQueueName));

			ServiceBusQueueName = serviceBusQueueName;
		}
コード例 #2
0
 public void CreateServiceContext()
 {
     var services = new ServiceContext();
     _projectService = new ProjectService();
     services.Add(_projectService);
     services.ServiceManager.StartServices();
 }
コード例 #3
0
ファイル: SettingsServiceTests.cs プロジェクト: alfeg/nunit
 public void CreateServiceContext()
 {
     var services = new ServiceContext();
     _settingsService = new SettingsService(false);
     services.Add(_settingsService);
     services.ServiceManager.StartServices();
 }
コード例 #4
0
	static void Main(string[] args)
	{
		var ctx = new ServiceContext();
		var service = new AgentService();
		service.Launch(12000);
		ctx.Run();
	}
 public WebHostCommunicationListener(ServiceContext serviceContext, string appPath, string endpointName, Func<string, ServiceCancellation, IWebHost> build)
 {
     this.serviceContext = serviceContext;
     this.endpointName = endpointName;
     this.build = build;
     this.appPath = appPath;
 }
コード例 #6
0
        public static void SetConfigurationValue(ServiceContext context, string package, string section, string name, string value)
        {
            MockCodePackageActivationContext mockContext = context.CodePackageActivationContext as MockCodePackageActivationContext;
            if (mockContext == null)
            {
                throw new ArgumentException("MockCodePackageActivationContext expected");
            }

            ConfigurationPackage config;
            if (!mockContext.GetConfigurationPackageNames().Contains(package))
            {
                config = CreateConfigurationPackage();
                mockContext.AddConfigurationPackage(package, config);
            }
            else
            {
                config = mockContext.GetConfigurationPackageObject(package);
            }

            System.Fabric.Description.ConfigurationSettings settings = config.Settings;
            if (!settings.Sections.Contains(section))
            {
                ConfigurationSection newSection = (ConfigurationSection)Activator.CreateInstance(typeof(ConfigurationSection), nonPublic: true);
                typeof(ConfigurationSection).GetProperty("Name").SetValue(newSection, section);
                settings.Sections.Add(newSection);
            }

            var s = settings.Sections[section];

            ConfigurationProperty p = (ConfigurationProperty) Activator.CreateInstance(typeof(ConfigurationProperty), nonPublic: true);
            typeof(ConfigurationProperty).GetProperty("Name").SetValue(p, name);
            typeof(ConfigurationProperty).GetProperty("Value").SetValue(p, value);

            s.Parameters.Add(p);
        }
コード例 #7
0
        internal InstitutionModel GetInstitutionDetails(InstitutionModel institutionModel)
        {
            try
            {
                //Demo purposes only.  The OAuth tokens returned by the SAML assertion are valid for 1 hour and do not need to be requested before each API call.
                SamlRequestValidator validator = new SamlRequestValidator(AggCatAppSettings.Certificate,
                                                                          AggCatAppSettings.ConsumerKey,
                                                                          AggCatAppSettings.ConsumerSecret,
                                                                          AggCatAppSettings.SamlIdentityProviderId,
                                                                          AggCatAppSettings.CustomerId);
                ServiceContext ctx = new ServiceContext(validator);
                AggregationCategorizationService svc = new AggregationCategorizationService(ctx);
                institutionModel.InstitutionDetail = svc.GetInstitutionDetails(institutionModel.InstitutionId);
                institutionModel.Success = true;
                institutionModel.Error = null;
            }
            catch (AggregationCategorizationException ex)
            {
                institutionModel.InstitutionDetail = null;
                institutionModel.Success = false;
                institutionModel.Error = ex.ToString();
            }

            return institutionModel;
        }
コード例 #8
0
        public void ConvertEngineResultToXml()
        {
            ServiceContext services = new ServiceContext();
            services.Add(new ExtensionService());
            ResultService resultService = new ResultService();
            services.Add(resultService);
            services.ServiceManager.StartServices();

            StringBuilder sb = new StringBuilder();
            using (StringWriter writer = new StringWriter(sb))
            {
                var nunit2Writer = resultService.GetResultWriter("nunit2", null);
                Assert.NotNull(nunit2Writer, "Unable to get nunit2 result writer");
                nunit2Writer.WriteResultFile(EngineResult.Xml, writer);
            }

            _doc = new XmlDocument();
            _doc.LoadXml(sb.ToString());

            _topNode = _doc.SelectSingleNode("/test-results");
            Assert.NotNull(_topNode, "Test-results element not found");

            _envNode = _topNode.SelectSingleNode("environment");
            Assert.NotNull(_envNode, "Environment element not found");

            _cultureNode = _topNode.SelectSingleNode("culture-info");
            Assert.NotNull(_topNode, "CultureInfo element not found");

            _fixtureNode = _topNode.SelectSingleNode("descendant::test-suite[@name='MockTestFixture']");
            Assert.NotNull(_fixtureNode, "MockTestFixture element not found");
        }
コード例 #9
0
 public WebSocketApp(IVisualObjectsBox visualObjectBox, string appRoot, string webSocketRoot, ServiceContext initParams)
 {
     this.visualObjectBox = visualObjectBox;
     this.appRoot = string.IsNullOrWhiteSpace(appRoot) ? string.Empty : appRoot.TrimEnd('/') + '/';
     this.webSocketRoot = string.IsNullOrWhiteSpace(webSocketRoot) ? string.Empty : webSocketRoot.TrimEnd('/') + '/';
     this.serviceContext = initParams;
 }
コード例 #10
0
 public void CreateServiceContext()
 {
     var services = new ServiceContext();
     _runtimeService = new RuntimeFrameworkService();
     services.Add(_runtimeService);
     services.ServiceManager.StartServices();
 }
コード例 #11
0
 public void SetUp()
 {
     var services = new ServiceContext();
     services.Add(new Services.SettingsService());
     recentFiles = new RecentFilesService();
     services.Add(recentFiles);
 }
コード例 #12
0
        /// <summary>
        /// Run the sample.
        /// </summary>
        /// <param name="serverConfig">configuration for the server.</param>
        /// <param name="promptToDelete">
        /// whether or not to prompt the user to delete created records.
        /// </param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptToDelete)
        {
            using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,
                                                                     serverConfig.Credentials, serverConfig.DeviceCredentials))
            {
                using (_context = new ServiceContext(_serviceProxy))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    // This statments checks whether Standard Email templates are present
                    var emailTemplateId = (
                                       from emailTemplate in _context.TemplateSet
                                       where emailTemplate.Title == "Contact Reconnect"
                                       select emailTemplate.Id
                                      ).FirstOrDefault();             
                           
                    if (emailTemplateId != Guid.Empty)
                    {
                        CreateRequiredRecords();

                        // Perform the bulk delete.  If you want to perform a recurring delete
                        // operation, then leave this as it is.  Otherwise, pass in false as the
                        // first parameter.
                        PerformBulkDelete(true, promptToDelete);
                    }
                    else
                    {
                        throw new ArgumentException("Standard Email Templates are missing");
                    }
                }
            }
        }
コード例 #13
0
 public void CreateServiceContext()
 {
     var services = new ServiceContext();
     _factory = new CoreTestRunnerFactory();
     services.Add(_factory);
     services.ServiceManager.StartServices();
 }
コード例 #14
0
        public static AggregationCategorizationService GetService(Cache cache, String userId)
        {

            try
            {
                if (cache["AggCatService_" + userId] == null)
                {
                    string certificateFile = System.Configuration.ConfigurationManager.AppSettings["PrivateKeyPath"];
                    string password = System.Configuration.ConfigurationManager.AppSettings["PrivateKeyPassword"];
                    X509Certificate2 certificate = new X509Certificate2(certificateFile, password);

                    string consumerKey = System.Configuration.ConfigurationManager.AppSettings["ConsumerKey"];
                    string consumerSecret = System.Configuration.ConfigurationManager.AppSettings["ConsumerSecret"];
                    string issuerId = System.Configuration.ConfigurationManager.AppSettings["SAMLIdentityProviderID"];

                    SamlRequestValidator samlValidator = new SamlRequestValidator(certificate, consumerKey, consumerSecret, issuerId, userId);

                    ServiceContext ctx = new ServiceContext(samlValidator);
                    cache.Add("AggCatService_" + userId, new AggregationCategorizationService(ctx), null, DateTime.Now.AddMinutes(50),
                              Cache.NoSlidingExpiration, CacheItemPriority.High, null);
                }
                return (AggregationCategorizationService)cache["AggCatService_" + userId];
            }
            catch (Exception ex)
            {
                throw new Exception("Unable to create AggCatService: " + ex.Message);
            }
        }
コード例 #15
0
        public OwinCommunicationListener(Action<IAppBuilder> startup, ServiceContext serviceContext, ServiceEventSource eventSource, string endpointName, string appRoot)
        {
            if (startup == null)
            {
                throw new ArgumentNullException(nameof(startup));
            }

            if (serviceContext == null)
            {
                throw new ArgumentNullException(nameof(serviceContext));
            }

            if (endpointName == null)
            {
                throw new ArgumentNullException(nameof(endpointName));
            }

            if (eventSource == null)
            {
                throw new ArgumentNullException(nameof(eventSource));
            }

            this.startup = startup;
            this.serviceContext = serviceContext;
            this.endpointName = endpointName;
            this.eventSource = eventSource;
            this.appRoot = appRoot;
        }
コード例 #16
0
        private ICommunicationListener CreateInternalListener(ServiceContext context)
        {
            // Partition replica's URL is the node's IP, port, PartitionId, ReplicaId, Guid
            EndpointResourceDescription internalEndpoint = context.CodePackageActivationContext.GetEndpoint("ProcessingServiceEndpoint");

            // Multiple replicas of this service may be hosted on the same machine,
            // so this address needs to be unique to the replica which is why we have partition ID + replica ID in the URL.
            // HttpListener can listen on multiple addresses on the same port as long as the URL prefix is unique.
            // The extra GUID is there for an advanced case where secondary replicas also listen for read-only requests.
            // When that's the case, we want to make sure that a new unique address is used when transitioning from primary to secondary
            // to force clients to re-resolve the address.
            // '+' is used as the address here so that the replica listens on all available hosts (IP, FQDM, localhost, etc.)
            
            string uriPrefix = String.Format(
                "{0}://+:{1}/{2}/{3}-{4}/",
                internalEndpoint.Protocol,
                internalEndpoint.Port,
                context.PartitionId,
                context.ReplicaOrInstanceId,
                Guid.NewGuid());

            string nodeIP = FabricRuntime.GetNodeContext().IPAddressOrFQDN;

            // The published URL is slightly different from the listening URL prefix.
            // The listening URL is given to HttpListener.
            // The published URL is the URL that is published to the Service Fabric Naming Service,
            // which is used for service discovery. Clients will ask for this address through that discovery service.
            // The address that clients get needs to have the actual IP or FQDN of the node in order to connect,
            // so we need to replace '+' with the node's IP or FQDN.
            string uriPublished = uriPrefix.Replace("+", nodeIP);
            return new HttpCommunicationListener(uriPrefix, uriPublished, this.ProcessInternalRequest);
        }
コード例 #17
0
ファイル: DomainManagerTests.cs プロジェクト: nahugrau/nunit
 public void CreateDomainManager()
 {
     var context = new ServiceContext();
     _domainManager = new DomainManager();
     context.Add(_domainManager);
     context.ServiceManager.StartServices();
 }
コード例 #18
0
        /// <summary>
        /// Initializes a new instance of the <see cref="OrleansCommunicationListener" /> class.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="configuration">The configuration.</param>
        public OrleansCommunicationListener(ServiceContext context, ClusterConfiguration configuration)
        {
            this.configuration = configuration;
            if (this.configuration == null)
            {
                this.configuration = new ClusterConfiguration();
                this.configuration.StandardLoad();
            }

            this.SiloName = Regex.Replace(context.ServiceName.PathAndQuery.Trim('/'), "[^a-zA-Z0-9_]", "_") + "_" +
                            context.ReplicaOrInstanceId.ToString("X");

            // Gather configuration from Service Fabric.
            var activation = context.CodePackageActivationContext;
            var endpoints = activation.GetEndpoints();
            var siloEndpoint = GetEndpoint(endpoints, "OrleansSiloEndpoint");
            var gatewayEndpoint = GetEndpoint(endpoints, "OrleansProxyEndpoint");

            // Set the endpoints according to Service Fabric configuration.
            var nodeConfig = this.configuration.Defaults;
            if (string.IsNullOrWhiteSpace(nodeConfig.HostNameOrIPAddress))
            {
                nodeConfig.HostNameOrIPAddress = context.NodeContext.IPAddressOrFQDN;
            }

            nodeConfig.Port = siloEndpoint.Port;
            nodeConfig.ProxyGatewayEndpoint = new IPEndPoint(nodeConfig.Endpoint.Address, gatewayEndpoint.Port);
        }
コード例 #19
0
        public InstitutionModel GetDefaultInstitutions()
        {
            InstitutionModel model = new InstitutionModel();

            //Demo purposes only.  The OAuth tokens returned by the SAML assertion are valid for 1 hour and do not need to be requested before each API call.
            SamlRequestValidator validator = new SamlRequestValidator(AggCatAppSettings.Certificate,
                                                                      AggCatAppSettings.ConsumerKey,
                                                                      AggCatAppSettings.ConsumerSecret,
                                                                      AggCatAppSettings.SamlIdentityProviderId,
                                                                      AggCatAppSettings.CustomerId);
            ServiceContext ctx = new ServiceContext(validator);
            AggregationCategorizationService svc = new AggregationCategorizationService(ctx);
            try
            {
                List<Institution> institutions = svc.GetInstitutions().institution.ToList<Institution>();
                model.Institutions = institutions;
                model.Error = null;
                model.Success = true;
            }
            catch (AggregationCategorizationException ex)
            {
                model.Institutions = null;
                model.Error = ex.ToString();
                model.Success = false;
            }

            return model;
        }
コード例 #20
0
ファイル: RecentFilesTests.cs プロジェクト: alfeg/nunit
 public void SetUp()
 {
     var services = new ServiceContext();
     services.Add(new FakeSettingsService());
     _recentFiles = new RecentFilesService();
     services.Add(_recentFiles);
     services.ServiceManager.StartServices();
 }
コード例 #21
0
	static void Main(string[] args)
	{
		var ctx = new ServiceContext();
		var service = new MailService();
		ctx.LaunchCmdline(typeof(ICmdline), service);
		service.Launch(8090);
		ctx.Run();
	}
コード例 #22
0
 public void CreateDriverFactory()
 {
     var serviceContext = new ServiceContext();
     serviceContext.Add(new ExtensionService());
     _driverService = new DriverService();
     serviceContext.Add(_driverService);
     serviceContext.ServiceManager.StartServices();
 }
 public OwinCommunicationListener(
     string appRoot, IOwinAppBuilder startup, ServiceContext serviceContext, CommonServiceEventSource eventSource)
 {
     this.startup = startup;
     this.appRoot = appRoot;
     this.serviceContext = serviceContext;
     this.eventSource = eventSource;
 }
コード例 #24
0
ファイル: ResultServiceTests.cs プロジェクト: alfeg/nunit
 public void CreateService()
 {
     var services = new ServiceContext();
     services.Add(new ExtensionService());
     _resultService = new ResultService();
     services.Add(_resultService);
     services.ServiceManager.StartServices();
 }
コード例 #25
0
 public void CreateServiceContext()
 {
     _services = new ServiceContext();
     _services.Add(new ProjectService());
     _factory = new DefaultTestRunnerFactory();
     _services.Add(_factory);
     _services.ServiceManager.StartServices();
 }
コード例 #26
0
        public AbstractTestRunner(ServiceContext services, TestPackage package)
        {
            this.Services = services;
            this.TestPackage = package;
            TestRunnerFactory = Services.GetService<ITestRunnerFactory>();
#if NUNIT_ENGINE
            ProjectService = Services.GetService<IProjectService>();
#endif
        }
コード例 #27
0
        /// <summary>
        /// Page Load Event, pulls Customer data from QuickBooks using SDK and Binds it to Grid
        /// </summary>
        /// <param name="sender">Sender of the event.</param>
        /// <param name="e">Event Args.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (HttpContext.Current.Session.Keys.Count > 0)
            {
                realmId = HttpContext.Current.Session["realm"].ToString();
                accessToken = HttpContext.Current.Session["accessToken"].ToString();
                accessTokenSecret = HttpContext.Current.Session["accessTokenSecret"].ToString();
                consumerKey = ConfigurationManager.AppSettings["consumerKey"].ToString(CultureInfo.InvariantCulture);
                consumerSecret = ConfigurationManager.AppSettings["consumerSecret"];
                dataSourcetype = HttpContext.Current.Session["dataSource"].ToString().ToLower() == "qbd" ? IntuitServicesType.QBD : IntuitServicesType.QBO;

                OAuthRequestValidator oauthValidator =  new OAuthRequestValidator(accessToken, accessTokenSecret, consumerKey, consumerSecret);
                ServiceContext context = new ServiceContext(oauthValidator, realmId, dataSourcetype);
                DataServices commonService = new DataServices(context);

                try
                {
                    switch(dataSourcetype)
                    {
                        case IntuitServicesType.QBD:
                            var qbdCustomerQuery = new Intuit.Ipp.Data.Qbd.CustomerQuery();
                            qbdCustomerQuery.ItemElementName = Intuit.Ipp.Data.Qbd.ItemChoiceType4.StartPage;
                            qbdCustomerQuery.Item = "1";
                            qbdCustomerQuery.ChunkSize = "10";
                            var qbdCustomers = qbdCustomerQuery.ExecuteQuery<Intuit.Ipp.Data.Qbd.Customer>(context).ToList();
                            grdQuickBooksCustomers.DataSource = qbdCustomers;
                            break;
                        case IntuitServicesType.QBO:
                            var qboCustomer = new Intuit.Ipp.Data.Qbo.Customer();
                            var qboCustomers = commonService.FindAll(qboCustomer, 1, 10).ToList();
                            grdQuickBooksCustomers.DataSource = qboCustomers;
                            break;
                    }

                    grdQuickBooksCustomers.DataBind();

                    if (grdQuickBooksCustomers.Rows.Count > 0)
                    {
                        GridLocation.Visible = true;
                        MessageLocation.Visible = false;
                    }
                    else
                    {
                        GridLocation.Visible = false;
                        MessageLocation.Visible = true;
                    }
                }
                catch (Intuit.Ipp.Exception.InvalidTokenException)
                {
                    //Remove the Oauth access token from the OauthAccessTokenStorage.xml
                    OauthAccessTokenStorageHelper.RemoveInvalidOauthAccessToken(Session["FriendlyEmail"].ToString(), Page);

                    Session["show"] = true;
                    Response.Redirect("~/Default.aspx");
                }
            }
        }
コード例 #28
0
ファイル: TestAgencyTests.cs プロジェクト: alfeg/nunit
 public void CreateServiceContext()
 {
     var services = new ServiceContext();
     services.Add(new FakeRuntimeService());
     // Use a different URI to avoid conflicting with the "real" TestAgency
     _testAgency = new TestAgency("TestAgencyTest", 0);
     services.Add(_testAgency);
     services.ServiceManager.StartServices();
 }
コード例 #29
0
        public void CreateDomainManagerAndDomain()
        {
            var context = new ServiceContext();
            _domainManager = new DomainManager();
            context.Add(_domainManager);
            context.ServiceManager.StartServices();

            _domain = _domainManager.CreateDomain(new TestPackage(MockAssembly.AssemblyPath));
        }
コード例 #30
0
        /// <summary>
        /// Page Load Event, pulls Customer data from QuickBooks using SDK and Binds it to Grid
        /// </summary>
        /// <param name="sender">Sender of the event.</param>
        /// <param name="e">Event Args.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (HttpContext.Current.Session.Keys.Count > 0)
            {
                String realmId = HttpContext.Current.Session["realm"].ToString();
                String accessToken = HttpContext.Current.Session["accessToken"].ToString();
                String accessTokenSecret = HttpContext.Current.Session["accessTokenSecret"].ToString();
                String consumerKey = ConfigurationManager.AppSettings["consumerKey"].ToString(CultureInfo.InvariantCulture);
                String consumerSecret = ConfigurationManager.AppSettings["consumerSecret"].ToString(CultureInfo.InvariantCulture);
                IntuitServicesType intuitServiceType = (IntuitServicesType)HttpContext.Current.Session["intuitServiceType"];

                OAuthRequestValidator oauthValidator = new OAuthRequestValidator(accessToken, accessTokenSecret, consumerKey, consumerSecret);
                ServiceContext context = new ServiceContext(oauthValidator, realmId, intuitServiceType);
                DataServices commonService = new DataServices(context);

                try
                {
                    switch(intuitServiceType )
                    {
                        case IntuitServicesType.QBO:
                            Intuit.Ipp.Data.Qbo.Customer qboCustomer = new Intuit.Ipp.Data.Qbo.Customer();
                            IEnumerable<Intuit.Ipp.Data.Qbo.Customer> qboCustomers =  commonService.FindAll(qboCustomer, 1, 10) as IEnumerable<Intuit.Ipp.Data.Qbo.Customer>;
                            grdQuickBooksCustomers.DataSource = qboCustomers;
                            break;
                        case IntuitServicesType.QBD:
                            //FindAll() is a GET operation for QBD, so we need to use the respective Query object instead to POST the start page and records per page (ChunkSize).
                            Intuit.Ipp.Data.Qbd.CustomerQuery qbdCustomerQuery = new Intuit.Ipp.Data.Qbd.CustomerQuery();
                            qbdCustomerQuery.ItemElementName = Intuit.Ipp.Data.Qbd.ItemChoiceType4.StartPage;
                            qbdCustomerQuery.Item = "1";
                            qbdCustomerQuery.ChunkSize = "10";
                            IEnumerable<Intuit.Ipp.Data.Qbd.Customer> qbdCustomers = qbdCustomerQuery.ExecuteQuery<Intuit.Ipp.Data.Qbd.Customer>(context) as IEnumerable<Intuit.Ipp.Data.Qbd.Customer>;
                            grdQuickBooksCustomers.DataSource = qbdCustomers;
                            break;
                        default:
                            throw new Exception("Data Source not defined.");
                    }

                    grdQuickBooksCustomers.DataBind();
                    if (grdQuickBooksCustomers.Rows.Count > 0)
                    {
                        GridLocation.Visible = true;
                        MessageLocation.Visible = false;
                    }
                    else
                    {
                        GridLocation.Visible = false;
                        MessageLocation.Visible = true;
                    }
                }
                catch
                {
                    throw;
                }
            }
        }
コード例 #31
0
 public EntregaObraClienteTermoRepository(ServiceContext serviceContext) : base(serviceContext)
 {
 }
コード例 #32
0
        /// <summary>
        /// Verifies the service implementation feature.
        /// </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 the service implementation feature 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    svcStatus = ServiceStatus.GetInstance();
            string entityTypeShortName;
            var    propTypes = new string[2] {
                "Edm.Date", "Edm.DateTimeOffset"
            };
            var propNames = MetadataHelper.GetPropertyNames(propTypes, out entityTypeShortName);

            if (null == propNames || !propNames.Any())
            {
                return(passed);
            }

            string propName     = propNames[0];
            var    entitySetUrl = entityTypeShortName.GetAccessEntitySetURL();

            if (string.IsNullOrEmpty(entitySetUrl))
            {
                return(passed);
            }

            string url  = svcStatus.RootURL.TrimEnd('/') + "/" + entitySetUrl;
            var    resp = WebHelper.Get(new Uri(url), string.Empty, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, svcStatus.DefaultHeaders);

            if (null != resp && HttpStatusCode.OK == resp.StatusCode)
            {
                var settings = new JsonSerializerSettings();
                settings.DateParseHandling = DateParseHandling.None;
                JObject jObj    = JsonConvert.DeserializeObject(resp.ResponsePayload, settings) as JObject;
                JArray  jArr    = jObj.GetValue(Constants.Value) as JArray;
                var     entity  = jArr.First as JObject;
                var     propVal = entity[propName].ToString();
                int     index   = propVal.IndexOf('-');
                propVal = propVal.Substring(0, index);
                url     = string.Format("{0}?$filter=year({1}) eq {2}", url, propName, propVal);
                resp    = WebHelper.Get(new Uri(url), string.Empty, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, svcStatus.DefaultHeaders);
                var detail = new ExtensionRuleResultDetail(this.Name, url, HttpMethod.Get, string.Empty);
                info = new ExtensionRuleViolationInfo(new Uri(url), string.Empty, detail);
                if (null != resp && HttpStatusCode.OK == resp.StatusCode)
                {
                    jObj = JsonConvert.DeserializeObject(resp.ResponsePayload, settings) as JObject;
                    jArr = jObj.GetValue(Constants.Value) as JArray;
                    foreach (JObject et in jArr)
                    {
                        passed = et[propName].ToString().Substring(0, index) == propVal;
                    }
                }
                else
                {
                    passed = false;
                }
            }

            return(passed);
        }
コード例 #33
0
        /// <summary>
        /// Verifies the extension 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");
            }

            bool?passed = null;

            info = null;

            JObject entry;

            context.ResponsePayload.TryToJObject(out entry);

            List <string> expandProps = ODataUriAnalyzer.GetQueryOptionValsFromUrl(context.Destination.ToString(), @"expand");

            if (entry != null && entry.Type == JTokenType.Object && expandProps.Count > 0)
            {
                var props = entry.Children();

                foreach (JProperty prop in props)
                {
                    if (expandProps.Contains(prop.Name))
                    {
                        passed = null;

                        if (prop.Value.Type == JTokenType.Object)
                        {
                            JObject jObj = prop.Value as JObject;
                            JsonParserHelper.ClearPropertiesList();

                            if (JsonParserHelper.GetSpecifiedPropertiesFromEntryPayload(jObj, Constants.OdataV4JsonIdentity).Count > 0)
                            {
                                passed = true;
                                break;
                            }
                            else
                            {
                                passed = false;
                            }
                        }
                        else if (prop.Value.Type == JTokenType.Array)
                        {
                            JArray jArr = prop.Value as JArray;

                            if (JsonParserHelper.GetSpecifiedPropertiesFromFeedPayload(jArr, Constants.OdataV4JsonIdentity).Count > 0)
                            {
                                passed = true;
                                break;
                            }
                            else
                            {
                                passed = false;
                            }
                        }
                    }
                }

                if (passed == false)
                {
                    info = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, context.ResponsePayload);
                }
            }

            return(passed);
        }
コード例 #34
0
 public ServiceItemsController(ServiceContext context)
 {
     _context = context;
 }
        /// <summary>
        /// Verifies the service implementation feature.
        /// </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 the service implementation feature 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    svcStatus = ServiceStatus.GetInstance();
            string entityTypeShortName;
            var    propNames = MetadataHelper.GetPropertyNames("Edm.String", out entityTypeShortName);

            if (null == propNames || !propNames.Any())
            {
                return(passed);
            }

            string propName     = propNames[0];
            var    entitySetUrl = entityTypeShortName.GetAccessEntitySetURL();

            if (string.IsNullOrEmpty(entitySetUrl))
            {
                return(passed);
            }

            string url  = svcStatus.RootURL.TrimEnd('/') + "/" + entitySetUrl;
            var    resp = WebHelper.Get(new Uri(url), string.Empty, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, svcStatus.DefaultHeaders);

            if (null != resp && HttpStatusCode.OK == resp.StatusCode)
            {
                JObject jObj    = JObject.Parse(resp.ResponsePayload);
                JArray  jArr    = jObj.GetValue("value") as JArray;
                var     entity  = jArr.First as JObject;
                var     propVal = entity[propName].ToString();
                url  = string.Format("{0}?$search={1}", url, propVal);
                resp = WebHelper.Get(new Uri(url), string.Empty, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, svcStatus.DefaultHeaders);
                var detail = new ExtensionRuleResultDetail("ServiceImpl_SystemQueryOptionSearch", url, HttpMethod.Get, string.Empty);
                detail.URI                = url;
                detail.ResponsePayload    = resp.ResponsePayload;
                detail.ResponseHeaders    = resp.ResponseHeaders;
                detail.HTTPMethod         = "GET";
                detail.ResponseStatusCode = resp.StatusCode.ToString();

                info = new ExtensionRuleViolationInfo(new Uri(url), string.Empty, detail);
                if (null != resp && HttpStatusCode.OK == resp.StatusCode)
                {
                    jObj = JObject.Parse(resp.ResponsePayload);
                    jArr = jObj.GetValue("value") as JArray;
                    if (null == jArr || !jArr.Any())
                    {
                        return(false);
                    }

                    entity = jArr.First as JObject;
                    passed = propVal == entity[propName].ToString();
                }
                else
                {
                    passed = false;
                }
            }
            else
            {
                return(passed);
            }

            return(passed);
        }
コード例 #36
0
 public OwinCommunicationListener(Action <IAppBuilder> startup, ServiceContext serviceContext, ServiceEventSource eventSource, string endpointName)
     : this(startup, serviceContext, eventSource, endpointName, null)
 {
 }
コード例 #37
0
 public ItemChecklistEntregaRepository(ServiceContext serviceContext) : base(serviceContext)
 {
 }
コード例 #38
0
 /// <summary>
 /// Construct a RemoteTestAgent
 /// </summary>
 public RemoteTestAgent(Guid agentId, ITestAgency agency, ServiceContext services)
     : base(agentId, agency, services)
 {
 }
コード例 #39
0
 public BaseRepository(ServiceContext serviceContext)
 {
     dbContext = serviceContext;
 }
        /// <summary>
        /// Verifies the service implementation feature.
        /// </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 the service implementation feature 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    svcStatus = ServiceStatus.GetInstance();
            string entityTypeShortName;
            var    props = MetadataHelper.GetProperties("Edm.GeographyPoint", 1, out entityTypeShortName);

            if (null == props || !props.Any())
            {
                return(passed);
            }

            string propName     = props[0].PropertyName;
            string srid         = props[0].SRID;
            var    entitySetUrl = entityTypeShortName.GetAccessEntitySetURL();

            if (string.IsNullOrEmpty(entitySetUrl))
            {
                return(passed);
            }

            string url    = svcStatus.RootURL.TrimEnd('/') + "/" + entitySetUrl;
            var    resp   = WebHelper.Get(new Uri(url), string.Empty, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, svcStatus.DefaultHeaders);
            var    detail = new ExtensionRuleResultDetail(this.Name, url, HttpMethod.Get, string.Empty);

            detail.URI                = url;
            detail.ResponsePayload    = resp.ResponsePayload;
            detail.ResponseHeaders    = resp.ResponseHeaders;
            detail.HTTPMethod         = "GET";
            detail.ResponseStatusCode = resp.StatusCode.ToString();
            info = new ExtensionRuleViolationInfo(new Uri(url), string.Empty, detail);
            if (null != resp && HttpStatusCode.OK == resp.StatusCode)
            {
                JObject jObj   = JObject.Parse(resp.ResponsePayload);
                JArray  jArr   = jObj.GetValue(Constants.Value) as JArray;
                var     entity = jArr.First as JObject;

                if (entity[propName] == null)
                {
                    detail.ErrorMessage = propName + "is null";
                    passed = false;
                    return(passed);
                }
                try
                {
                    var test = entity[propName]["coordinates"] as JArray;
                }
                catch (Exception ex2)
                {
                    detail.ErrorMessage = propName + " coordinates is null or missing.  Review for format and include the coordinate attribute.  This is the call that is failing:  var propVal = entity[propName][\"coordinates\"] as JArray;";
                    passed = false;
                    return(passed);
                }
                var propVal = entity[propName]["coordinates"] as JArray;
                var pt      = new Point(Convert.ToDouble(propVal[0]), Convert.ToDouble(propVal[1]));
                var pts     = new Point[4]
                {
                    pt + new Point(1.0, 0.0),
                    pt + new Point(-1.0, 0.0),
                    pt + new Point(0.0, 1.0),
                    pt + new Point(0.0, -1.0)
                };
                url  = string.Format("{0}?$filter=geo.intersects({1}, geography'POLYGON(({2}, {3}, {4}, {5}, {6}))')", url, propName, pts[0], pts[1], pts[2], pts[3], pts[0]);
                resp = WebHelper.Get(new Uri(url), string.Empty, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, svcStatus.DefaultHeaders);
                var detail1 = new ExtensionRuleResultDetail(this.Name, url, HttpMethod.Get, string.Empty);
                detail1.URI                = url;
                detail1.ResponsePayload    = resp.ResponsePayload;
                detail1.ResponseHeaders    = resp.ResponseHeaders;
                detail1.HTTPMethod         = "GET";
                detail1.ResponseStatusCode = resp.StatusCode.ToString();
                if (info == null)
                {
                    info = new ExtensionRuleViolationInfo(new Uri(url), string.Empty, detail1);
                }
                else
                {
                    info.AddDetail(detail1);
                }
                if (null != resp && HttpStatusCode.OK == resp.StatusCode)
                {
                    jObj = JObject.Parse(resp.ResponsePayload);
                    jArr = jObj.GetValue(Constants.Value) as JArray;
                    foreach (JObject et in jArr)
                    {
                        passed = this.IsIntersects(propName, new Polygon(pts), et);
                        if (passed == false)
                        {
                            detail1.ErrorMessage = "The polygon doe not intersect";
                            break;
                        }
                    }
                }
                else
                {
                    detail1.ErrorMessage = "The server returned an error response:  " + detail.ResponseStatusCode;
                    passed = false;
                }
            }

            return(passed);
        }
コード例 #41
0
 public ContentTypeTreeController(UmbracoTreeSearcher treeSearcher, IGlobalSettings globalSettings, IUmbracoContextAccessor umbracoContextAccessor, ISqlContext sqlContext, ServiceContext services, AppCaches appCaches, IProfilingLogger logger, IRuntimeState runtimeState, UmbracoHelper umbracoHelper) : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoHelper)
 {
     _treeSearcher = treeSearcher;
 }
コード例 #42
0
        /// <summary>
        /// Verify Metadata.Core.2014
        /// </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;

            // Adding all AtomPub mappings to a list
            List <string> atomPubMapping = new List <string>(new string[]
            {
                "SyndicationAuthorName",
                "SyndicationAuthorEmail",
                "SyndicationAuthorUri",
                "SyndicationPublished",
                "SyndicationRights",
                "SyndicationTitle",
                "SyndicationUpdated",
                "SyndicationContributorName",
                "SyndicationContributorEmail",
                "SyndicationContributorUri",
                "SyndicationSource",
                "SyndicationSummary"
            });

            // Load MetadataDocument into XMLDOM
            XmlDocument xmlDoc = new XmlDocument();

            xmlDoc.LoadXml(context.MetadataDocument);

            // Find all nodes
            XmlNodeList xmlNodeList = xmlDoc.SelectNodes("//*[@*[name()='m:FC_TargetPath']]");

            if (xmlNodeList.Count != 0)
            {
                foreach (XmlNode node in xmlNodeList)
                {
                    if (atomPubMapping.Exists(item => item == node.Attributes["m:FC_TargetPath"].Value))
                    {
                        if (node.ParentNode.Name.Equals("EntityType", StringComparison.OrdinalIgnoreCase))
                        {
                            if (node.ParentNode.Attributes["m:FC_NsPrefix"] != null)
                            {
                                passed = false;
                                break;
                            }
                            else
                            {
                                passed = true;
                            }
                        }
                        else if (node.ParentNode.Name.Equals("Schema", StringComparison.OrdinalIgnoreCase))
                        {
                            if (node.Attributes["m:FC_NsPrefix"] != null)
                            {
                                passed = false;
                            }
                            else
                            {
                                passed = true;
                            }
                        }
                    }
                }
            }

            info = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, context.ResponsePayload);

            return(passed);
        }
コード例 #43
0
 public void CreateServiceContext()
 {
     _services = new ServiceContext();
 }
コード例 #44
0
        /// <summary>
        /// Verifies the extension 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");
            }

            bool?passed = null;

            info = null;
            ServiceStatus serviceStatus    = ServiceStatus.GetInstance();
            TermDocuments termDocs         = TermDocuments.GetInstance();
            DataFactory   dFactory         = DataFactory.Instance();
            var           detail1          = new ExtensionRuleResultDetail(this.Name);
            var           detail2          = new ExtensionRuleResultDetail(this.Name);
            var           detail3          = new ExtensionRuleResultDetail(this.Name);
            var           detail4          = new ExtensionRuleResultDetail(this.Name);
            List <string> keyPropertyTypes = new List <string>()
            {
                "Edm.Int32", "Edm.Int16", "Edm.Int64", "Edm.Guid", "Edm.String"
            };
            List <string> norPropertyTypes = new List <string>()
            {
                "Edm.String"
            };
            List <EntityTypeElement> entityTypeElements = MetadataHelper.GetEntityTypes(serviceStatus.MetadataDocument, 1, keyPropertyTypes, norPropertyTypes, NavigationRoughType.CollectionValued).ToList();

            if (null == entityTypeElements || 0 == entityTypeElements.Count())
            {
                detail1.ErrorMessage = "It expects an entity type with Int32 key property and containing a string property to Patch/Post, but there is no this entity type in metadata so can not verify this rule.";
                info = new ExtensionRuleViolationInfo(new Uri(serviceStatus.RootURL), serviceStatus.ServiceDocument, detail1);

                return(passed);
            }

            foreach (var et in entityTypeElements)
            {
                string navigPropName = null;
                string navigPropRelatedEntitySetUrl      = null;
                string navigPropRelatedEntityTypeKeyName = null;
                var    matchEntity = et.EntitySetName.GetRestrictions(serviceStatus.MetadataDocument, termDocs.VocCapabilitiesDoc,
                                                                      new List <Func <string, string, string, List <NormalProperty>, List <NavigProperty>, bool> >()
                {
                    AnnotationsHelper.GetDeleteRestrictions, AnnotationsHelper.GetInsertRestrictions, AnnotationsHelper.GetUpdateRestrictions
                });

                if (string.IsNullOrEmpty(matchEntity.Item1) ||
                    matchEntity.Item2 == null || !matchEntity.Item2.Any() ||
                    matchEntity.Item3 == null || !matchEntity.Item3.Any())
                {
                    continue;
                }

                foreach (var np in matchEntity.Item3)
                {
                    navigPropName = np.NavigationPropertyName;
                    string navigEntityTypeShortName     = np.NavigationPropertyType.RemoveCollectionFlag().GetLastSegment();
                    List <NormalProperty> navigKeyProps = MetadataHelper.GetKeyProperties(serviceStatus.MetadataDocument, navigEntityTypeShortName).ToList();

                    if (navigKeyProps.Count == 1 && keyPropertyTypes.Contains(navigKeyProps[0].PropertyType))
                    {
                        navigPropRelatedEntitySetUrl      = navigEntityTypeShortName.MapEntityTypeShortNameToEntitySetURL();
                        navigPropRelatedEntityTypeKeyName = navigKeyProps[0].PropertyName;

                        break;
                    }
                }

                if (!string.IsNullOrEmpty(navigPropRelatedEntityTypeKeyName) && !string.IsNullOrEmpty(navigPropRelatedEntitySetUrl))
                {
                    string entitySetUrl    = et.EntitySetName.MapEntitySetNameToEntitySetURL();
                    string url             = serviceStatus.RootURL.TrimEnd('/') + @"/" + entitySetUrl;
                    var    additionalInfos = new List <AdditionalInfo>();
                    var    reqData         = dFactory.ConstructInsertedEntityData(et.EntitySetName, et.EntityTypeShortName, null, out additionalInfos);
                    string reqDataStr      = reqData.ToString();
                    bool   isMediaType     = !string.IsNullOrEmpty(additionalInfos.Last().ODataMediaEtag);
                    var    resp            = WebHelper.CreateEntity(url, context.RequestHeaders, reqData, isMediaType, ref additionalInfos);
                    detail1 = new ExtensionRuleResultDetail(this.Name, url, HttpMethod.Post, string.Empty, resp, string.Empty, reqDataStr);

                    if (null != resp && HttpStatusCode.Created == resp.StatusCode)
                    {
                        string  entityId  = additionalInfos.Last().EntityId;
                        bool    hasEtag   = additionalInfos.Last().HasEtag;
                        JObject newEntity = JObject.Parse(resp.ResponsePayload);
                        url                        = serviceStatus.RootURL.TrimEnd('/') + @"/" + navigPropRelatedEntitySetUrl;
                        resp                       = WebHelper.Get(new Uri(url), Constants.V4AcceptHeaderJsonFullMetadata, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, serviceStatus.DefaultHeaders);
                        detail2                    = new ExtensionRuleResultDetail(this.Name, url, HttpMethod.Get, StringHelper.MergeHeaders(Constants.V4AcceptHeaderJsonFullMetadata, serviceStatus.DefaultHeaders), resp);
                        detail2.URI                = url;
                        detail2.ResponsePayload    = resp.ResponsePayload;
                        detail2.ResponseHeaders    = resp.ResponseHeaders;
                        detail2.HTTPMethod         = "GET";
                        detail2.ResponseStatusCode = resp.StatusCode.ToString();

                        if (resp.StatusCode == HttpStatusCode.OK)
                        {
                            JObject feed;
                            resp.ResponsePayload.TryToJObject(out feed);
                            var entities = JsonParserHelper.GetEntries(feed);

                            if (entities.Count > 0 && entities[0][Constants.V4OdataId] != null)
                            {
                                reqDataStr = @"{""" + Constants.V4OdataId + @""" : """ + entities[0][Constants.V4OdataId].ToString() + @"""}";
                                url        = string.Format("{0}/{1}/$ref", entityId.TrimEnd('/'), navigPropName.TrimEnd('/'));

                                // Verify to send a POST Http request and response with a 204 No Content status code.
                                resp    = WebHelper.CreateEntity(url, reqDataStr);
                                detail3 = new ExtensionRuleResultDetail(this.Name, url, HttpMethod.Post, string.Empty, resp, string.Empty, reqDataStr);

                                if (null != resp && resp.StatusCode == HttpStatusCode.NoContent)
                                {
                                    if (resp.ResponseHeaders.Contains("OData-EntityId"))
                                    {
                                        // Verify to send a PATCH Http request and response with a 204 No Content status code.
                                        List <string> norPropertyNames = et.NormalProperties
                                                                         .Where(np => norPropertyTypes.Contains(np.PropertyType) && !np.IsKey)
                                                                         .Select(np => np.PropertyName).ToList();
                                        if (!norPropertyNames.Any())
                                        {
                                            detail3.ErrorMessage = "The entity-type does not contain any properties can be updated.";
                                            info = new ExtensionRuleViolationInfo(new Uri(url), resp.ResponsePayload, detail3);

                                            return(passed);
                                        }

                                        reqData = dFactory.ConstructUpdatedEntityData(newEntity, norPropertyNames);
                                        resp    = WebHelper.UpdateEntity(entityId, context.RequestHeaders, reqDataStr, HttpMethod.Patch, hasEtag);
                                        detail4 = new ExtensionRuleResultDetail(this.Name, url, HttpMethod.Patch, string.Empty, resp, string.Empty, reqDataStr);

                                        if (HttpStatusCode.NoContent == resp.StatusCode)
                                        {
                                            if (resp.ResponseHeaders.Contains("OData-EntityId"))
                                            {
                                                passed = true;
                                            }
                                            else
                                            {
                                                passed = false;
                                                detail4.ErrorMessage = "The response headers does not contain OData-EntityId header for above patch request.";
                                            }
                                        }
                                        else
                                        {
                                            passed = false;
                                            detail4.ErrorMessage = "Patch HTTP request failed.";
                                        }
                                    }
                                    else
                                    {
                                        passed = false;
                                        detail3.ErrorMessage = "The response headers does not contain OData-EntityId header for above POST request.";
                                    }
                                }
                                else
                                {
                                    passed = false;
                                    detail3.ErrorMessage = "POST HTTP request failed for above URI.";
                                }
                            }
                        }

                        // Restore the service.
                        var resps = WebHelper.DeleteEntities(context.RequestHeaders, additionalInfos);
                    }
                    else
                    {
                        passed = false;
                        detail1.ErrorMessage = "Created the new entity failed for above URI.";
                    }

                    break;
                }
            }

            var details = new List <ExtensionRuleResultDetail>()
            {
                detail1, detail2, detail3, detail4
            }.RemoveNullableDetails();

            info = new ExtensionRuleViolationInfo(new Uri(serviceStatus.RootURL), serviceStatus.ServiceDocument, details);

            return(passed);
        }
コード例 #45
0
 public UsersController(IGlobalSettings globalSettings, IUmbracoContextAccessor umbracoContextAccessor, ISqlContext sqlContext, ServiceContext services, AppCaches appCaches, IProfilingLogger logger, IRuntimeState runtimeState, UmbracoHelper umbracoHelper)
     : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoHelper)
 {
 }
コード例 #46
0
        /// <summary>
        /// Verify Metadata.Core.4328
        /// </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;
            var    metadata = XElement.Parse(context.MetadataDocument);
            string xPath    = "//*[local-name()='NavigationPropertyBinding']";
            var    navigationPropertyBindingElems = metadata.XPathSelectElements(xPath, ODataNamespaceManager.Instance);

            if (null == navigationPropertyBindingElems && !navigationPropertyBindingElems.Any())
            {
                return(passed);
            }

            navigationPropertyBindingElems = navigationPropertyBindingElems
                                             .Where(npElem => null != npElem.Attribute("Path"))
                                             .Select(npElem => npElem);
            if (null == navigationPropertyBindingElems && !navigationPropertyBindingElems.Any())
            {
                return(passed);
            }

            foreach (var navigationPropertyBindingElem in navigationPropertyBindingElems)
            {
                string pathAttribVal          = navigationPropertyBindingElem.GetAttributeValue("Path");
                int    slashIndex             = pathAttribVal.LastIndexOf('/');
                string navigationPropertyName = pathAttribVal.Remove(0, slashIndex + 1);
                string nTypeShortName         = string.Empty;
                if (slashIndex != -1)
                {
                    nTypeShortName = pathAttribVal.Substring(0, slashIndex).GetLastSegment();
                    if (nTypeShortName.IsSpecifiedComplexTypeShortNameExist())
                    {
                        nTypeShortName = null;
                    }
                }

                var parentElement = navigationPropertyBindingElem.Parent;
                if (null == parentElement)
                {
                    return(passed);
                }

                string entityTypeShortName = string.Empty;
                if ("EntitySet" == parentElement.Name.LocalName && null != parentElement.Attribute("EntityType"))
                {
                    entityTypeShortName = parentElement.GetAttributeValue("EntityType").GetLastSegment();
                    if (slashIndex == -1)
                    {
                        nTypeShortName = entityTypeShortName;
                    }
                }
                else if ("Singleton" == parentElement.Name.LocalName && null != parentElement.Attribute("Type"))
                {
                    entityTypeShortName = parentElement.GetAttributeValue("Type").GetLastSegment();
                    if (slashIndex == -1)
                    {
                        nTypeShortName = entityTypeShortName;
                    }
                }

                if (!entityTypeShortName.IsSpecifiedEntityTypeShortNameExist())
                {
                    return(null);
                }

                var navigTreeNode = NavigateTreeNode.Parse(entityTypeShortName);
                var node          = navigTreeNode.Search(navigationPropertyName, nTypeShortName);
                if (null != node)
                {
                    if ((node.Data.Path + "/" + node.Data.Name).EndsWith(pathAttribVal))
                    {
                        passed = true;
                    }
                    else
                    {
                        passed = false;
                        break;
                    }
                }
            }

            info = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, context.ResponsePayload);

            return(passed);
        }
コード例 #47
0
        /// <summary>
        /// Verify Metadata.Core.4103
        /// </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;

            // Load MetadataDocument into XMLDOM
            XmlDocument xmlDoc = new XmlDocument();

            xmlDoc.LoadXml(context.MetadataDocument);

            string      xpath = "//*[local-name()='NavigationProperty']";
            XmlNodeList navPropertyNodeList = xmlDoc.SelectNodes(xpath);

            foreach (XmlNode navProp in navPropertyNodeList)
            {
                if (navProp.Attributes["Type"] != null)
                {
                    string navPropTypeName = navProp.Attributes["Type"].Value;
                    if (navPropTypeName.Contains("Collection("))
                    {
                        navPropTypeName = navPropTypeName.Substring(11, navPropTypeName.Length - 12);
                    }

                    // 1. See whether the navigation type is of Edm.EntityType.
                    if (navPropTypeName.Equals("Edm.EntityType"))
                    {
                        passed = true;
                        continue;
                    }

                    // 2. See whether the navigation type can resolve to an entity type defined in the metadata document.
                    string navPropTypeSimpleName = navPropTypeName.GetLastSegment();
                    string navPropTypePrefix     = navPropTypeName.Substring(0, navPropTypeName.IndexOf(navPropTypeSimpleName) - 1);

                    bool isTypeDefinedInDoc = IsEntityTypeDefinedInDoc(navPropTypeName, context.MetadataDocument);

                    if (isTypeDefinedInDoc)
                    {
                        passed = true;
                        continue;
                    }

                    // 3. See whether the navigation type can resolve to an entity type defined in one of the referenced data model.
                    string docString = MetadataHelper.GetReferenceDocByDefinedType(navPropTypeName, context);

                    if (!string.IsNullOrEmpty(docString))
                    {
                        isTypeDefinedInDoc = false;
                        isTypeDefinedInDoc = IsEntityTypeDefinedInDoc(navPropTypeName, docString);

                        if (isTypeDefinedInDoc)
                        {
                            passed = true;
                        }
                    }
                }

                // If the navigation type cannot resolve to an in-scope entity type, this navigation property failed in this rule.
                if (passed != true)
                {
                    passed = false;
                    info   = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, context.ResponsePayload);
                    break;
                }
            }

            return(passed);
        }
コード例 #48
0
 public AreaRepository(ServiceContext context) : base(context)
 {
     _serviceContext = context;
 }
コード例 #49
0
        public List<ShowImageDto> GetImageInfos([FromUri] int themeID, [FromUri] int year, [FromUri] int month, [FromUri] int userID)
        {
            try
            {
                if (!JustToken.TokenCheck())
                {
                    return null;
                }

                var hasTheme = themeID != 0;
                var hasYear = year != 0;
                var hasMonth = month != 0;

                using (var context = new ServiceContext())
                {
                    var imageList = new List<Image>();

                    //1
                    if (!hasTheme && !hasYear && !hasMonth)
                    {
                        LogHelper.Error("[ShowImage]:!hasTheme && !hasYear && !hasMonth");
                        imageList = null;
                    }

                    //2
                    if (hasTheme && hasYear && hasMonth)
                    {

                        var imageListEntity = context.Image.Where(t => t.ThemeID == themeID && t.Year == year && t.Month == month).ToList();

                        if (imageListEntity == null)
                        {
                            return null;
                        }

                        imageList = imageListEntity.OrderBy(i => i.Updatetime).ToList();
                    }

                    //3
                    if (hasTheme && !hasYear && !hasMonth)
                    {

                        var imageListEntity = context.Image.Where(t => t.ThemeID == themeID).ToList();

                        if (imageListEntity == null)
                        {
                            return null;
                        }

                        imageList = imageListEntity.OrderBy(i => i.Year).ThenBy(i => i.Month).ThenBy(i => i.Updatetime).ToList();
                    }

                    //4
                    if (hasTheme && !hasYear && hasMonth)
                    {

                        var imageListEntity = context.Image.Where(t => t.ThemeID == themeID && t.Month == month).ToList();

                        if (imageListEntity == null)
                        {
                            return null;
                        }
                        imageList = imageListEntity.OrderBy(i => i.Year).ThenBy(i => i.Updatetime).ToList();
                    }

                    //5
                    if (hasTheme && hasYear && !hasMonth)
                    {

                        var imageListEntity = context.Image.Where(t => t.ThemeID == themeID && t.Year == year).ToList();

                        if (imageListEntity == null)
                        {
                            return null;
                        }
                        imageList = imageListEntity.OrderBy(i => i.Month).ThenBy(i => i.Updatetime).ToList();
                    }

                    //6
                    if (!hasTheme && hasYear && hasMonth)
                    {

                        var imageListEntity = context.Image.Where(t => t.UserID == userID && t.Year == year && t.Month == month).ToList();

                        if (imageListEntity == null)
                        {
                            return null;
                        }
                        imageList = imageListEntity.OrderBy(i => i.Updatetime).ToList();
                    }

                    //7
                    if (!hasTheme && hasYear && !hasMonth)
                    {

                        var imageListEntity = context.Image.Where(t => t.UserID == userID && t.Year == year).ToList();

                        if (imageListEntity == null)
                        {
                            return null;
                        }
                        imageList = imageListEntity.OrderBy(i => i.Month).ThenBy(i => i.Updatetime).ToList();
                    }

                    //8
                    if (!hasTheme && !hasYear && hasMonth)
                    {

                        var imageListEntity = context.Image.Where(t => t.UserID == userID && t.Month == month).ToList();

                        if (imageListEntity == null)
                        {
                            return null;
                        }
                        imageList = imageListEntity.OrderBy(i => i.Year).ThenBy(i => i.Updatetime).ToList();
                    }

                    var showImageDtoList = new List<ShowImageDto>();
                    foreach (var image in imageList)
                    {
                        showImageDtoList.Add(ShowImageDto.Map(image));
                    }
                    return showImageDtoList;
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error("[ShowImage]:" + ex.ToString());
                return null;
            }
        }
コード例 #50
0
        /// <summary>
        /// Verify Entry.Common.4402
        /// </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;
            JObject allobject;

            context.ResponsePayload.TryToJObject(out allobject);

            // Whether odata.type value is namespace- or alias-qualified the instance's type
            bool isNamespaceValue = false;
            bool isAliasValue     = false;

            // Use the XPath query language to access the metadata document and get all Namespace value.
            string        xpath = @"//*[local-name()='DataServices']/*[local-name()='Schema']";
            List <string> appropriateNamespace = MetadataHelper.GetPropertyValues(context, xpath, "Namespace");

            // Get Alias value.
            List <string> appropriateAlias = MetadataHelper.GetPropertyValues(context, xpath, "Alias");

            // If PayloadType is Feed, verify as below, else is Entry.
            if (context.PayloadType.Equals(RuleEngine.PayloadType.Feed))
            {
                var entries = JsonParserHelper.GetEntries(allobject);
                foreach (JObject entry in entries)
                {
                    var jProps = entry.Children();
                    foreach (JProperty jProp in jProps)
                    {
                        // Whether the property name contains odata.type.
                        if (jProp.Name.Contains(Constants.OdataType))
                        {
                            // Whether the property is built-in primitive types.
                            bool isBuiltInPrimitiveType = JsonSchemaHelper.IsBuiltInPrimitiveTypes(jProp, context);

                            if (isBuiltInPrimitiveType)
                            {
                                if (appropriateNamespace.Count != 0)
                                {
                                    // Verify the annoatation contains the namespace-qualified.
                                    foreach (string currentvalue in appropriateNamespace)
                                    {
                                        if (jProp.Name.Contains(currentvalue))
                                        {
                                            isNamespaceValue = true;
                                        }
                                        else
                                        {
                                            isNamespaceValue = false;
                                        }
                                    }
                                }

                                if (appropriateAlias.Count != 0)
                                {
                                    // Verify the annoatation contains the alias-qualified.
                                    foreach (string currentvalue in appropriateAlias)
                                    {
                                        if (jProp.Name.Contains(currentvalue))
                                        {
                                            isAliasValue = true;
                                        }
                                        else
                                        {
                                            isAliasValue = false;
                                        }
                                    }
                                }

                                // odata.type annotation is the unqualified name of the primitive type means it does not contain the namespace-qualified or alias-qualified type.
                                if (!isAliasValue && !isNamespaceValue)
                                {
                                    passed = true;
                                    continue;
                                }
                                else
                                {
                                    passed = false;
                                    info   = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, context.ResponsePayload);
                                    break;
                                }
                            }
                        }
                    }
                }
            }
            else
            {
                var jProps = allobject.Children();

                foreach (JProperty jProp in jProps)
                {
                    // Whether the property name contains odata.type.
                    if (jProp.Name.Contains(Constants.OdataType))
                    {
                        // Whether the property is built-in primitive types.
                        bool isBuiltInPrimitiveType = JsonSchemaHelper.IsBuiltInPrimitiveTypes(jProp, context);

                        if (isBuiltInPrimitiveType)
                        {
                            if (appropriateNamespace.Count != 0)
                            {
                                // Verify the annoatation contains the namespace-qualified.
                                foreach (string currentvalue in appropriateNamespace)
                                {
                                    if (jProp.Name.Contains(currentvalue))
                                    {
                                        isNamespaceValue = true;
                                    }
                                    else
                                    {
                                        isNamespaceValue = false;
                                    }
                                }
                            }

                            if (appropriateAlias.Count != 0)
                            {
                                // Verify the annoatation contains the alias-qualified.
                                foreach (string currentvalue in appropriateAlias)
                                {
                                    if (jProp.Name.Contains(currentvalue))
                                    {
                                        isAliasValue = true;
                                    }
                                    else
                                    {
                                        isAliasValue = false;
                                    }
                                }
                            }

                            // odata.type annotation is the unqualified name of the primitive type means it does not contain the namespace-qualified or alias-qualified type.
                            if (!isAliasValue && !isNamespaceValue)
                            {
                                passed = true;
                                continue;
                            }
                            else
                            {
                                passed = false;
                                info   = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, context.ResponsePayload);
                                break;
                            }
                        }
                    }
                }
            }

            return(passed);
        }
コード例 #51
0
 public EfRepository(ServiceContext dbContext, AppIdentityDbContext identityContext)
 {
     _dbContext       = dbContext;
     _identityContext = identityContext;
 }
コード例 #52
0
 public ApplicationContext(DatabaseContext dbContext, ServiceContext serviceContext, CacheHelper cache)
     : this(dbContext, serviceContext, cache,
            new ProfilingLogger(LoggerResolver.Current.Logger, ProfilerResolver.Current.Profiler))
 {
 }
コード例 #53
0
        /// <summary>
        /// Verifies the extension 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");
            }

            bool?passed = null;

            info = null;

            JObject entry;

            context.ResponsePayload.TryToJObject(out entry);

            if (entry != null && entry.Type == JTokenType.Object && context.OdataMetadataType == ODataMetadataType.MinOnly)
            {
                JsonParserHelper.ClearProperyValsList();
                List <JToken> odataMetadataVals = JsonParserHelper.GetSpecifiedPropertyValsFromEntryPayload(entry, Constants.OdataV4JsonIdentity, MatchType.Equal);

                JsonParserHelper.ClearProperyValsList();
                List <JToken> navigationLinkVals = JsonParserHelper.GetSpecifiedPropertyValsFromEntryPayload(entry, Constants.OdataNavigationLinkPropertyNameSuffix, MatchType.Contained);

                string url = string.Empty;

                if (odataMetadataVals.Count == 1)
                {
                    string odataMetadataValStr = odataMetadataVals[0].ToString().Trim('"');
                    int    index = odataMetadataValStr.IndexOf(Constants.Metadata);
                    url = odataMetadataValStr.Remove(index, odataMetadataValStr.Length - index);

                    foreach (var navigationLinkVal in navigationLinkVals)
                    {
                        if (Uri.IsWellFormedUriString(navigationLinkVal.ToString().Trim('"'), UriKind.Relative))
                        {
                            url += navigationLinkVal.ToString().Trim('"');
                        }
                        else
                        {
                            url = navigationLinkVal.ToString().Trim('"');
                        }

                        Uri uri = new Uri(url, UriKind.RelativeOrAbsolute);

                        // Send a request with "application/json;odata=minimalmetadata" in Accept header.
                        string   acceptHeader = Constants.V4AcceptHeaderJsonMinimalMetadata;
                        Response response     = WebHelper.Get(uri, acceptHeader, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, context.RequestHeaders);

                        // If response's status code is not equal to 200, it will indicate the url cannot be computed.
                        if (response.StatusCode != HttpStatusCode.OK)
                        {
                            passed = true;
                        }
                        else
                        {
                            passed = false;
                            info   = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, context.ResponsePayload);
                            break;
                        }
                    }
                }
            }

            return(passed);
        }
コード例 #54
0
 protected ListenerPrimary(ServiceContext serviceContext) : base(serviceContext)
 {
 }
コード例 #55
0
 internal static Uri GetChatDataServiceName(ServiceContext context)
 {
     return(new Uri($"{context.CodePackageActivationContext.ApplicationName}/Chat.Data"));
 }
コード例 #56
0
        /// <summary>
        /// Verify EntityReference.Core.4606
        /// </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;

            XmlDocument payload = new XmlDocument();

            payload.LoadXml(context.ResponsePayload);
            string xPath = @"//*[local-name()='ref']";

            XmlNodeList elems = payload.SelectNodes(xPath, ODataNamespaceManager.Instance);

            if (null != elems && elems.Count > 0)
            {
                passed = true;

                foreach (XmlNode elem in elems)
                {
                    string idVal = elem.Attributes["id"].Value;

                    if (!Uri.IsWellFormedUriString(idVal, UriKind.Absolute))
                    {
                        if (Uri.IsWellFormedUriString(idVal, UriKind.Relative))
                        {
                            idVal = idVal.TrimStart('#');
                            idVal = context.ServiceBaseUri + idVal;
                        }
                        else
                        {
                            passed = false;
                            info   = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, context.ResponsePayload);
                            break;
                        }
                    }

                    var resp = WebHelper.Get(new Uri(idVal), Constants.AcceptHeaderAtom, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, context.RequestHeaders);

                    if (null != resp && HttpStatusCode.OK == resp.StatusCode)
                    {
                        payload.LoadXml(resp.ResponsePayload);
                        if (null != payload && "entry" == payload.DocumentElement.Name)
                        {
                            xPath = @"/*/*[local-name()='id']";
                            XmlNode idElem = payload.SelectSingleNode(xPath, ODataNamespaceManager.Instance);
                            string  idURL  = idElem.InnerXml.ToString();

                            if (Uri.IsWellFormedUriString(idURL, UriKind.Relative))
                            {
                                idURL = idURL.TrimStart('#');
                                idURL = context.ServiceBaseUri + idURL;
                            }

                            if (idVal != idURL)
                            {
                                passed = false;
                                info   = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, context.ResponsePayload);
                                break;
                            }
                        }
                    }
                }
            }

            return(passed);
        }
コード例 #57
0
        /// <summary>
        /// Verifies the extension 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");
            }

            bool? passed = null;
            info = null;
            ServiceStatus serviceStatus = ServiceStatus.GetInstance();
            TermDocuments termDocs = TermDocuments.GetInstance();
            DataFactory dFactory = DataFactory.Instance();
            var detail1 = new ExtensionRuleResultDetail(this.Name);
            var detail2 = new ExtensionRuleResultDetail(this.Name);
            var detail3 = new ExtensionRuleResultDetail(this.Name);
            var detail4 = new ExtensionRuleResultDetail(this.Name);
            Dictionary<string, Dictionary<KeyValuePair<string, string>, List<string>>> entityTypeInfos;
            if (!MetadataHelper.GetEntityTypesWithComplexProperty(serviceStatus.MetadataDocument, "Edm.String", out entityTypeInfos))
            {
                detail1.ErrorMessage = "To verify this rule it expects complex type containing a property with string type, but there is no this complex type in metadata so cannot verify this rule.";
                info = new ExtensionRuleViolationInfo(new Uri(serviceStatus.RootURL), serviceStatus.ServiceDocument, detail1);

                return passed;
            }

            var entityTypeInfo = new KeyValuePair<string, Dictionary<KeyValuePair<string, string>, List<string>>>();
            string entitySetName = string.Empty;
            foreach (var etInfo in entityTypeInfos)
            {
                entitySetName = etInfo.Key.MapEntityTypeShortNameToEntitySetName();
                var funcs = new List<Func<string, string, string, List<NormalProperty>, List<NavigProperty>, bool>>() 
                {
                    AnnotationsHelper.GetInsertRestrictions, AnnotationsHelper.GetUpdateRestrictions, AnnotationsHelper.GetDeleteRestrictions
                };

                var restrictions = entitySetName.GetRestrictions(serviceStatus.MetadataDocument, termDocs.VocCapabilitiesDoc, funcs);
                if (!string.IsNullOrEmpty(restrictions.Item1) ||
                    null != restrictions.Item2 || restrictions.Item2.Any() ||
                    null != restrictions.Item3 || restrictions.Item3.Any())
                {
                    entityTypeInfo = etInfo;

                    break;
                }
            }

            if (string.IsNullOrEmpty(entitySetName) ||
                string.IsNullOrEmpty(entityTypeInfo.Key) ||
                null == entityTypeInfo.Value ||
                !entityTypeInfo.Value.Any())
            {
                detail1.ErrorMessage = "Cannot find the entity-set which support insert, updata, delete restrictions at the same time.";
                info = new ExtensionRuleViolationInfo(new Uri(serviceStatus.RootURL), serviceStatus.ServiceDocument, detail1);

                return passed;
            }

            string entityTypeShortName = entityTypeInfo.Key;
            string entitySetUrl = entitySetName.MapEntitySetNameToEntitySetURL();
            string complexPropName = entityTypeInfo.Value.Keys.First().Key;
            string complexPropType = entityTypeInfo.Value.Keys.First().Value;
            string propertyNameWithSpecifiedType = entityTypeInfo.Value[new KeyValuePair<string, string>(complexPropName, complexPropType)].First();

            // Create a entity
            string url = serviceStatus.RootURL.TrimEnd('/') + @"/" + entitySetUrl;
            var additionalInfos = new List<AdditionalInfo>();
            var reqData = dFactory.ConstructInsertedEntityData(entitySetName, entityTypeShortName, null, out additionalInfos);
            reqData = dFactory.ReconstructNullableComplexData(reqData, new List<string>() { complexPropName });
            string reqDataStr = reqData.ToString();
            bool isMediaType = !string.IsNullOrEmpty(additionalInfos.Last().ODataMediaEtag);
            var resp = WebHelper.CreateEntity(url, context.RequestHeaders, reqData, isMediaType, ref additionalInfos);
            detail1 = new ExtensionRuleResultDetail(this.Name, url, HttpMethod.Post, string.Empty, resp, string.Empty, reqDataStr);
            if (resp.StatusCode == HttpStatusCode.Created)
            {
                var entityId = additionalInfos.Last().EntityId;
                var hasEtag = additionalInfos.Last().HasEtag;

                // Get a complex property except key property
                string complexProUrl = entityId + @"/" + complexPropName;
                resp = WebHelper.Get(new Uri(complexProUrl), Constants.AcceptHeaderJson, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, serviceStatus.DefaultHeaders);
                detail2 = new ExtensionRuleResultDetail(this.Name, complexProUrl, HttpMethod.Get, StringHelper.MergeHeaders(Constants.AcceptHeaderJson, serviceStatus.DefaultHeaders), resp);

                if (resp.StatusCode == HttpStatusCode.OK)
                {
                    JObject jo;
                    resp.ResponsePayload.TryToJObject(out jo);
                    //string newComplexProperty = VerificationHelper.ConstructUpdatedEntityData(jo, new List<string>() { propertyNameWithSpecifiedType }, out hasEtag);
                    string newComplexProperty = dFactory.ConstructUpdatedEntityData(jo, new List<string>() { propertyNameWithSpecifiedType }).ToString();

                    // Update the complex property
                    resp = WebHelper.UpdateEntity(complexProUrl, context.RequestHeaders, newComplexProperty, HttpMethod.Patch, hasEtag);
                    detail3 = new ExtensionRuleResultDetail(this.Name, complexProUrl, HttpMethod.Patch, string.Empty, resp, string.Empty, newComplexProperty);
                    if (resp.StatusCode == HttpStatusCode.NoContent)
                    {
                        // Check whether the complex property is updated to new value
                        if (WebHelper.GetContent(complexProUrl, context.RequestHeaders, out resp))
                        {
                            detail4 = new ExtensionRuleResultDetail(this.Name, complexProUrl, HttpMethod.Get, string.Empty, resp);
                            resp.ResponsePayload.TryToJObject(out jo);

                            if (jo != null && jo[propertyNameWithSpecifiedType] != null && jo[propertyNameWithSpecifiedType].Value<string>().Equals(Constants.UpdateData))
                            {
                                passed = true;
                            }
                            else if (jo == null)
                            {
                                passed = false;
                                detail4.ErrorMessage = "Can not get complex property after Patch it. ";
                            }
                            else if (jo != null && jo[propertyNameWithSpecifiedType] == null)
                            {
                                passed = false;
                                detail4.ErrorMessage = string.Format("Can not get the value of {0} property in complex property {1}. ", propertyNameWithSpecifiedType, complexProUrl);
                            }
                            else if (jo != null && jo[propertyNameWithSpecifiedType] != null && !jo[propertyNameWithSpecifiedType].Value<string>().Equals(Constants.UpdateData))
                            {
                                passed = false;
                                detail4.ErrorMessage = string.Format("The value of {0} property in complex is not updated by {1}. ", propertyNameWithSpecifiedType, complexProUrl);
                            }
                        }
                    }
                    else
                    {
                        passed = false;
                        detail3.ErrorMessage = "Update complex property in the created entity failed. ";
                    }
                }
                else if (resp.StatusCode == HttpStatusCode.NoContent)
                {
                    detail2.ErrorMessage = "The value of property with complex type is null.";
                }
                else
                {
                    passed = false;
                    detail2.ErrorMessage = "Get complex property in the created entity failed. ";
                }
                // Delete the entity
                var resps = WebHelper.DeleteEntities(context.RequestHeaders, additionalInfos);
            }
            else
            {
                passed = false;
                detail1.ErrorMessage = "Created the new entity failed for above URI. ";
            }

            var details = new List<ExtensionRuleResultDetail>() { detail1, detail2, detail3, detail4 }.RemoveNullableDetails();
            info = new ExtensionRuleViolationInfo(new Uri(serviceStatus.RootURL), serviceStatus.ServiceDocument, details);

            return passed;
        }
コード例 #58
0
 public PlansQuery(ServiceContext serviceContext)
 {
     _serviceContext = serviceContext;
 }
コード例 #59
0
        public void SetUp()
        {
            // annoying, but content type wants short string helper ;(
            SettingsForTests.Reset();

            // well, this is also annoying, but...
            // validating a value is performed by its data editor,
            // based upon the configuration in the data type, so we
            // need to be able to retrieve them all...

            Current.Reset();

            var configs = new Configs();

            configs.Add(SettingsForTests.GetDefaultGlobalSettings);
            configs.Add(SettingsForTests.GetDefaultUmbracoSettings);

            var factory = Mock.Of <IFactory>();

            Current.Factory = factory;

            var dataEditors = new DataEditorCollection(new IDataEditor[]
            {
                new DataEditor(Mock.Of <ILogger>())
                {
                    Alias = "editor", ExplicitValueEditor = new DataValueEditor("view")
                }
            });
            var propertyEditors = new PropertyEditorCollection(dataEditors);

            var dataType = Mock.Of <IDataType>();

            Mock.Get(dataType)
            .Setup(x => x.Configuration)
            .Returns(null);

            var dataTypeService = Mock.Of <IDataTypeService>();

            Mock.Get(dataTypeService)
            .Setup(x => x.GetDataType(It.IsAny <int>()))
            .Returns <int>(x => dataType);

            var serviceContext = ServiceContext.CreatePartial(
                dataTypeService: dataTypeService,
                localizedTextService: Mock.Of <ILocalizedTextService>());

            Mock.Get(factory)
            .Setup(x => x.GetInstance(It.IsAny <Type>()))
            .Returns <Type>(x =>
            {
                if (x == typeof(Configs))
                {
                    return(configs);
                }
                if (x == typeof(PropertyEditorCollection))
                {
                    return(propertyEditors);
                }
                if (x == typeof(ServiceContext))
                {
                    return(serviceContext);
                }
                if (x == typeof(ILocalizedTextService))
                {
                    return(serviceContext.LocalizationService);
                }
                throw new NotSupportedException(x.FullName);
            });
        }
コード例 #60
0
        /// <summary>
        /// Verify Common.Core.4628
        /// </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;

            // Single primitive individual property is not allowed to have instance annotation.
            if (VerificationHelper.IsIndividualPropertySinglePrimitiveType(context.ResponsePayload, context.PayloadType))
            {
                return(null);
            }

            XmlDocument xmlDoc = new XmlDocument();

            // Test Data
            // Url:http://services.odata.org/V4/OData/OData.svc/Products(0)/Description?$format=xml or http://services.odata.org/V4/OData/OData.svc/Persons(0)?$format=atom
            // xmlDoc.LoadXml("<?xml version=\"1.0\" encoding=\"utf-8\"?><m:value m:context=\"http://services.odata.org/V4/OData/OData.svc/$metadata#Products(0)/Description\" xmlns:atom=\"http://www.w3.org/2005/Atom\"  xmlns:d=\"http://docs.oasis-open.org/odata/ns/data\" xmlns:georss=\"http://www.georss.org/georss\" xmlns:gml=\"http://www.opengis.net/gml\" xmlns:m=\"http://docs.oasis-open.org/odata/ns/metadata\">Whole grain bread <m:annotation atom:term=\"com.contoso.address\" m:type=\"#ODataDemo.Address\"><d:Street>2817 Milton Dr.</d:Street><d:City>Albuquerque</d:City><d:State>NM</d:State><d:ZipCode>87110</d:ZipCode><d:Country>USA</d:Country></m:annotation></m:value>");
            xmlDoc.LoadXml(context.ResponsePayload);

            XmlNodeList annotationElements = xmlDoc.SelectNodes(@"//*[local-name()='annotation']", ODataNamespaceManager.Instance);

            passed = true;

            foreach (XmlNode annotatEle in annotationElements)
            {
                bool isStructuredValue = false;

                if (annotatEle.ChildNodes != null && annotatEle.ChildNodes.Count > 1)
                {
                    isStructuredValue = true;

                    foreach (XmlNode ele in annotatEle.ChildNodes)
                    {
                        if (!ele.NamespaceURI.Equals(Constants.V4NSData))
                        {
                            isStructuredValue = false;
                            break;
                        }
                    }
                }

                if (!isStructuredValue)
                {
                    continue;
                }

                bool hasType = annotatEle.Attributes["type", Constants.NSMetadata] != null;

                if (hasType == false)
                {
                    passed = false;
                    break;
                }
            }

            info = new ExtensionRuleViolationInfo(passed == true ? null : this.ErrorMessage, context.Destination, context.ResponsePayload);

            return(passed);
        }