/// <summary>
        /// Called during the authorization process before a service method or behavior is executed.
        /// </summary>
        /// <param name="serviceContext">The service context.</param>
        /// <param name="behaviorContext">The "method authorizing" behavior context.</param>
        /// <returns>A service method action.</returns>
        public override BehaviorMethodAction OnMethodAuthorizing(IServiceContext serviceContext, MethodAuthorizingContext behaviorContext)
        {
            if (serviceContext == null)
            {
                throw new ArgumentNullException("serviceContext");
            }

            string userId, signatureHash;
            DateTime timestamp;

            if (!TryGetRequestedSignature(serviceContext.Request, out userId, out signatureHash, out timestamp) ||
                String.IsNullOrWhiteSpace(userId) ||
                String.IsNullOrWhiteSpace(signatureHash))
            {
                serviceContext.Response.SetStatus(HttpStatusCode.Unauthorized, Global.Unauthorized);
                return BehaviorMethodAction.Stop;
            }

            if (!IsRequestedSignatureValid(serviceContext, signatureHash, timestamp))
            {
                serviceContext.Response.SetStatus(HttpStatusCode.Unauthorized, Global.Unauthorized);
                return BehaviorMethodAction.Stop;
            }

            string hashedServerSignature = HashSignature(serviceContext.Request, userId, GenerateServerSignature(serviceContext, userId, timestamp));

            return signatureHash == hashedServerSignature ? BehaviorMethodAction.Execute : BehaviorMethodAction.Stop;
        }
예제 #2
0
        /// <summary>
        /// Deserializes HTTP message body data into an object instance of the provided type.
        /// </summary>
        /// <param name="context">The service context.</param>
        /// <param name="objectType">The object type.</param>
        /// <returns>The deserialized object.</returns>
        /// <exception cref="HttpResponseException">If the object cannot be deserialized.</exception>
        public virtual object FormatRequest(IServiceContext context, Type objectType)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            if (objectType == null)
            {
                throw new ArgumentNullException("objectType");
            }

            if (objectType == typeof(object))
            {
                using (var streamReader = new StreamReader(context.Request.Body, context.Request.Headers.ContentCharsetEncoding))
                {
                    return new DynamicXDocument(streamReader.ReadToEnd());
                }
            }

            if (context.Request.Body.CanSeek)
            {
                context.Request.Body.Seek(0, SeekOrigin.Begin);
            }

            var reader = XmlReader.Create(new StreamReader(context.Request.Body, context.Request.Headers.ContentCharsetEncoding));

            return XmlSerializerRegistry.Get(objectType).Deserialize(reader);
        }
        public void Init(IServiceContext context)
        {
            Context = context;
            host = context.GetPlugin<WemosPlugin>();

            InitLastValues();
        }
        private static dynamic PopulateDynamicObject(IServiceContext context)
        {
            dynamic instance = new DynamicResult();

            foreach (string key in context.Request.QueryString.Keys)
            {
                IList<string> values = context.Request.QueryString.GetValues(key);
                string propertyName = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(key);

                try
                {
                    if (values.Count == 1)
                    {
                        instance.Add(propertyName, values[0]);
                    }
                    else
                    {
                        instance.Add(propertyName, values);
                    }
                }
                catch (ArgumentException)
                {
                    throw new HttpResponseException(HttpStatusCode.BadRequest, Global.InvalidDynamicPropertyName);
                }
            }

            return instance;
        }
예제 #5
0
        /// <summary>
        /// Called during the authorization process before a service method or behavior is executed.
        /// </summary>
        /// <param name="serviceContext">The service context.</param>
        /// <param name="behaviorContext">The "method authorizing" behavior context.</param>
        /// <returns>A service method action.</returns>
        public override BehaviorMethodAction OnMethodAuthorizing(IServiceContext serviceContext, MethodAuthorizingContext behaviorContext)
        {
            if (serviceContext == null)
            {
                throw new ArgumentNullException("serviceContext");
            }

            if (serviceContext.Cache == null)
            {
                throw new InvalidOperationException(Resources.Global.UnableToInitializeCache);
            }

            string remoteAddress = serviceContext.Request.ServerVariables.RemoteAddress;

            if (String.IsNullOrEmpty(remoteAddress))
            {
                return BehaviorMethodAction.Execute;
            }

            string cacheKey = String.Concat("throttle-", serviceContext.Request.Url.GetLeftPart(UriPartial.Path), "-", remoteAddress);

            if (serviceContext.Cache.Contains(cacheKey))
            {
                SetStatus((HttpStatusCode) 429, Resources.Global.TooManyRequests);
                return BehaviorMethodAction.Stop;
            }

            serviceContext.Cache.Add(cacheKey, true, DateTime.Now.AddMilliseconds(m_delayInMilliseconds), CachePriority.Low);
            return BehaviorMethodAction.Execute;
        }
예제 #6
0
        /// <summary>
        /// Called before a service method is executed.
        /// </summary>
        /// <param name="serviceContext">The service context.</param>
        /// <param name="behaviorContext">The "method executing" behavior context.</param>
        /// <returns>A service method action.</returns>
        public override BehaviorMethodAction OnMethodExecuting(IServiceContext serviceContext, MethodExecutingContext behaviorContext)
        {
            if (serviceContext == null)
            {
                throw new ArgumentNullException("serviceContext");
            }

            if (behaviorContext == null)
            {
                throw new ArgumentNullException("behaviorContext");
            }

            if (behaviorContext.Resource == null || m_validator == null)
            {
                return BehaviorMethodAction.Execute;
            }

            IReadOnlyCollection<ValidationError> validationErrors;

            if (!m_validator.IsValid(behaviorContext.Resource, out validationErrors))
            {
                serviceContext.GetHttpContext().Items[ResourceValidator.ValidationErrorKey] = new ResourceState(validationErrors);
            }

            return BehaviorMethodAction.Execute;
        }
        /// <summary>
        /// Called during the authorization process before a service method or behavior is executed.
        /// </summary>
        /// <param name="serviceContext">The service context.</param>
        /// <param name="behaviorContext">The "method authorizing" behavior context.</param>
        /// <returns>A service method action.</returns>
        public override BehaviorMethodAction OnMethodAuthorizing(IServiceContext serviceContext, MethodAuthorizingContext behaviorContext)
        {
            if (serviceContext == null)
            {
                throw new ArgumentNullException("serviceContext");
            }

            if (RequiresSsl && AuthorizeConnection(serviceContext.Request) == BehaviorMethodAction.Stop)
            {
                SetStatusDescription(Resources.Global.HttpsRequiredStatusDescription);
                return BehaviorMethodAction.Stop;
            }

            AuthorizationHeader header;

            if (!AuthorizationHeaderParser.TryParse(serviceContext.Request.Headers.Authorization, serviceContext.Request.Headers.ContentCharsetEncoding, out header) ||
                !AuthenticationType.Equals(header.AuthenticationType, StringComparison.OrdinalIgnoreCase))
            {
                serviceContext.Response.SetStatus(HttpStatusCode.Unauthorized, Resources.Global.Unauthorized);
                GenerateAuthenticationHeader(serviceContext);
                return BehaviorMethodAction.Stop;
            }

            Credentials credentials = m_authorizationManager.GetCredentials(header.UserName);

            if (credentials == null || !String.Equals(header.Password, credentials.Password, StringComparison.Ordinal))
            {
                GenerateAuthenticationHeader(serviceContext);
                return BehaviorMethodAction.Stop;
            }

            serviceContext.User = new GenericPrincipal(new GenericIdentity(header.UserName, AuthenticationType), credentials.GetRoles());
            return BehaviorMethodAction.Execute;
        }
예제 #8
0
        public DfsContext(IDfsConfiguration dfsConfiguration)
        {
            this.dfsConfiguration = dfsConfiguration;
            serviceFactory = ServiceFactory.Instance;

            var contextFactory = ContextFactory.Instance;
            serviceContext = contextFactory.NewContext();

            var repositoryIdentity = new RepositoryIdentity(dfsConfiguration.Repository, dfsConfiguration.UserName, dfsConfiguration.Password, string.Empty);
            serviceContext.AddIdentity(repositoryIdentity);

            var contentTransferProfile = new ContentTransferProfile
            {
                TransferMode = ContentTransferMode.MTOM
            };
            serviceContext.SetProfile(contentTransferProfile);

            // Setting the filter to ALL can cause errors if the DataObject
            // passed to the operation contains system properties, so to be safe 
            // set the filter to ALL_NON_SYSTEM unless you explicitly want to update
            // a system property
            var propertyProfile = new PropertyProfile
            {
                FilterMode = PropertyFilterMode.ALL_NON_SYSTEM
            };
            serviceContext.SetProfile(propertyProfile);

            serviceContext.SetRuntimeProperty("USER_TRANSACTION_HINT", "TRANSACTION_REQUIRED");
        }
예제 #9
0
        private static object BindObject(string name, Type objectType, IServiceContext context)
        {
            string uriValue = context.Request.QueryString.TryGet(name);
            object changedValue;

            return SafeConvert.TryChangeType(uriValue, objectType, out changedValue) ? changedValue : null;
        }
예제 #10
0
        public void Initialize()
        {
            m_context = MockContextManager.GenerateContext();

            MockContextManager.SetQuery("callback", "callback");
            MockContextManager.SetHeader("X-Requested-With", "XMLHttpRequest");
        }
예제 #11
0
        /// <summary>
        /// Executes the result against the provided service context.
        /// </summary>
        /// <param name="context">The service context.</param>
        public virtual void Execute(IServiceContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            if (Code == HttpStatusCode.NoContent)
            {
                context.Response.Output.Clear();
            }

            foreach (var header in ResponseHeaders)
            {
                context.Response.SetHeader(header.Key, header.Value);
            }

            if (!String.IsNullOrWhiteSpace(Description))
            {
                context.Response.SetStatus(Code, Description);
            }
            else
            {
                context.Response.SetStatus(Code);
            }
        }
        internal RegistrationManager(
            IRegistrationContext registrationContext, 
            IModuleManager moduleManager,
            IPublicRegistrationService publicRegistrationService, 
            ISdkInformation sdkInformation,
            IEnvironmentInformation environmentInformation, 
            IServiceContext serviceContext,
            ISecureRegistrationService secureRegistrationService, 
            IConfigurationManager configurationManager,
            IEventBus eventBus, 
            IRefreshToken tokenRefresher, 
            ILogger logger,
			IJsonSerialiser serialiser)
        {
            _registrationContext = registrationContext;
            _moduleManager = moduleManager;
            _publicRegistrationService = publicRegistrationService;
            _sdkInformation = sdkInformation;
            _environmentInformation = environmentInformation;
            _serviceContext = serviceContext;
            _secureRegistrationService = secureRegistrationService;
            _configurationManager = configurationManager;
            _eventBus = eventBus;
            _tokenRefresher = tokenRefresher;
            _logger = logger;
			_serialiser = serialiser;
        }
예제 #13
0
        /// <summary>
        /// Deserializes HTTP message body data into an object instance of the provided type.
        /// </summary>
        /// <param name="context">The service context.</param>
        /// <param name="objectType">The object type.</param>
        /// <returns>The deserialized object.</returns>
        /// <exception cref="HttpResponseException">If the object cannot be deserialized.</exception>
        public virtual object FormatRequest(IServiceContext context, Type objectType)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            if (objectType == null)
            {
                throw new ArgumentNullException("objectType");
            }

            if (context.Request.Body.CanSeek)
            {
                context.Request.Body.Seek(0, SeekOrigin.Begin);
            }

            var streamReader = new StreamReader(context.Request.Body, context.Request.Headers.ContentCharsetEncoding);
            var serializer = JsonSerializerFactory.Create();
            var reader = new JsonTextReader(streamReader);

            if (objectType == typeof(object))
            {
                return serializer.Deserialize(reader);
            }

            return serializer.Deserialize(reader, objectType);
        }
예제 #14
0
        /// <summary>
        /// Executes the result against the provided service context.
        /// </summary>
        /// <param name="context">The service context.</param>
        public virtual void Execute(IServiceContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            if (Content == null)
            {
                return;
            }

            if (ClearOutput)
            {
                context.Response.Output.Clear();
            }

            SetContentType(context);
            context.Response.SetCharsetEncoding(context.Request.Headers.AcceptCharsetEncoding);
            
            OutputCompressionManager.FilterResponse(context);

            context.Response.Output.Write(Content);

            LogResponse();
        }
예제 #15
0
        /// <summary>
        /// Called during the authorization process before a service method or behavior is executed.
        /// </summary>
        /// <param name="serviceContext">The service context.</param>
        /// <param name="behaviorContext">The "method authorizing" behavior context.</param>
        /// <returns>A service method action.</returns>
        public override BehaviorMethodAction OnMethodAuthorizing(IServiceContext serviceContext, MethodAuthorizingContext behaviorContext)
        {
            if (serviceContext == null)
            {
                throw new ArgumentNullException("serviceContext");
            }

            var ranges = IPAddressRange.GetConfiguredRanges(m_sectionName).ToList();

            if (ranges.Count == 0)
            {
                return BehaviorMethodAction.Stop;
            }

            bool isAllowed = false;

            foreach (var range in ranges)
            {
                if (range.IsInRange(serviceContext.GetHttpContext().Request.UserHostAddress))
                {
                    isAllowed = true;
                    break;
                }
            }

            return isAllowed ? BehaviorMethodAction.Execute : BehaviorMethodAction.Stop;
        }
예제 #16
0
        private object BindObject(string name, Type objectType, IServiceContext context)
        {
            string value = context.Request.Headers.TryGet(GetHeaderName(name));
            object changedValue;

            return SafeConvert.TryChangeType(value, objectType, out changedValue) ? changedValue : null;
        }
        /// <summary>
        /// Performs a query on a collection and returns the resulting collection of
        /// objects.
        /// </summary>
        /// <param name="context">The service context.</param>
        /// <param name="collection">The collection to perform the query on.</param>
        /// <returns>The resulting collection.</returns>
        public virtual IEnumerable PerformQuery(IServiceContext context, IQueryable collection)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

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

            NameValueCollection queryString = context.Request.QueryString.ToNameValueCollection();
            TrySetMaxQueryResults(context, queryString);

            int count;

            List<object> filteredCollection = TryConvertToFilteredCollection(collection, queryString, out count);
            object filteredObject = filteredCollection.FirstOrDefault(o => o != null);
            Type objectType = filteredObject != null ? filteredObject.GetType() : typeof(object);

            if (Attribute.IsDefined(objectType, typeof(CompilerGeneratedAttribute), false))
            {
                throw new HttpResponseException(HttpStatusCode.InternalServerError, Global.UnsupportedObjectTypeForOData);
            }

            Tuple<int, int> range = GetContentRanges(queryString, count);

            TrySetContentRange(context, filteredCollection, range);

            return GenerateFilteredCollection(filteredCollection, objectType);
        }
예제 #18
0
        /// <summary>
        /// Called before a service method is executed.
        /// </summary>
        /// <param name="serviceContext">The service context.</param>
        /// <param name="behaviorContext">The "method executing" behavior context.</param>
        /// <returns>A service method action.</returns>
        public override BehaviorMethodAction OnMethodExecuting(IServiceContext serviceContext, MethodExecutingContext behaviorContext)
        {
            serviceContext.Request.ResourceBag.LoggingEnabled = true;
            serviceContext.Response.Output.WriteFormat("Action '{0}' executing", behaviorContext.GetMethodName()).WriteLine(2);

            return BehaviorMethodAction.Execute;
        }
예제 #19
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MerchelloHelper"/> class.
        /// </summary>
        /// <param name="serviceContext">
        /// The service context.
        /// </param>
        public MerchelloHelper(IServiceContext serviceContext)
        {
            Mandate.ParameterNotNull(serviceContext, "ServiceContext cannot be null");

            _queryProvider = new Lazy<ICachedQueryProvider>(() => new CachedQueryProvider(serviceContext));
            _validationHelper = new Lazy<IValidationHelper>(() => new ValidationHelper());
        }
예제 #20
0
        public async Task Execute(IResult result, IServiceContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            if (result == null)
            {
                return;
            }

            var asyncResult = result as IResultAsync;

            if (asyncResult != null)
            {
                await asyncResult.ExecuteAsync(context, context.Response.GetCancellationToken());
            }
            else
            {
                result.Execute(context);
            }

            TryDisposeResult(result);
        }
예제 #21
0
        private static object BindObject(string name, Type objectType, IServiceContext context)
        {
            string value = context.GetHttpContext().Request.Form.Get(name);
            object changedValue;

            return SafeConvert.TryChangeType(value, objectType, out changedValue) ? changedValue : null;
        }
예제 #22
0
        /// <summary>
        /// Binds data from an HTTP body key value pair to a service method parameter.
        /// </summary>
        /// <param name="name">The service method parameter name.</param>
        /// <param name="objectType">The binded object type.</param>
        /// <param name="context">The service context.</param>
        /// <returns>The object instance with the data or null.</returns>
        public override object Bind(string name, Type objectType, IServiceContext context)
        {
            if (String.IsNullOrEmpty(name))
            {
                throw new ArgumentNullException("name");
            }

            if (objectType == null)
            {
                throw new ArgumentNullException("objectType");
            }

            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            if (context.Request.Headers.ContentType == null || context.Request.Headers.ContentType.IndexOf(FormDataMediaType, StringComparison.OrdinalIgnoreCase) < 0)
            {
                throw new HttpResponseException(HttpStatusCode.InternalServerError, Resources.Global.UnsupportedFormData);
            }

            if (!String.IsNullOrWhiteSpace(Name))
            {
                name = Name.Trim();
            }

            return objectType.IsArray ? BindArray(name, objectType, context) : BindObject(name, objectType, context);
        }
        protected override string GenerateServerSignature(IServiceContext context, string userId, DateTime timespan)
        {
            string urlPaRT = context.Request.Url.GetLeftPart(UriPartial.Path).TrimEnd(' ', '/', '?', '#').ToLowerInvariant();
            string dateTimePart = timespan.ToString("yyyyMMddhhmmss");
            const string salt = "HM@CS1G";

            return urlPaRT + dateTimePart + userId + salt;
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="ServiceBehaviorInvoker"/> class.
        /// </summary>
        /// <param name="context">The service context.</param>
        public ServiceBehaviorInvoker(IServiceContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            m_context = context;
        }
예제 #25
0
        internal GatewayContext(IServiceContext serviceContext, IGatewayProviderResolver resolver)
        {
            Mandate.ParameterNotNull(serviceContext, "serviceContext");
            Mandate.ParameterNotNull(resolver, "resolver");
            _gatewayProviderService = serviceContext.GatewayProviderService;
            _resolver = resolver;

            BuildGatewayContext(serviceContext.GatewayProviderService, serviceContext.StoreSettingService);
        }
예제 #26
0
        public ServiceContextHandler(IServiceContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            Context = context;
        }
예제 #27
0
        internal MerchelloContext(IServiceContext serviceContext, CacheHelper cache, bool isUnitTest)
        {
            Mandate.ParameterNotNull(serviceContext, "serviceContext");
            Mandate.ParameterNotNull(cache, "cache");

            _services = serviceContext;
            Cache = cache;

            BuildMerchelloContext(isUnitTest);
        }
예제 #28
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MerchelloContext"/> class.
        /// </summary>
        /// <param name="serviceContext">
        /// The service context.
        /// </param>
        /// <param name="gatewayContext">
        /// The gateway context.
        /// </param>
        /// <param name="cache">
        /// The cache.
        /// </param>
        internal MerchelloContext(IServiceContext serviceContext, IGatewayContext gatewayContext, CacheHelper cache)
        {
            Mandate.ParameterNotNull(serviceContext, "serviceContext");
            Mandate.ParameterNotNull(gatewayContext, "gatewayContext");
            Mandate.ParameterNotNull(cache, "cache");

            _services = serviceContext;
            _gateways = gatewayContext;
            Cache = cache;
        }
예제 #29
0
        /// <summary>
        /// Executes the result against the provided service context.
        /// </summary>
        /// <param name="context">The service context.</param>
        public virtual void Execute(IServiceContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            if (String.IsNullOrEmpty(ContentType))
            {
                ContentType = "application/json";
            }
            else if (context.Request.Headers.AcceptVersion > 0 && ContentType.IndexOf("version=", StringComparison.OrdinalIgnoreCase) < 0)
            {
                ContentType += String.Format(CultureInfo.InvariantCulture, "; version={0}", context.Request.Headers.AcceptVersion);
            }

            if (!String.IsNullOrEmpty(Callback) && !methodNamePattern.IsMatch(Callback))
            {
                throw new HttpResponseException(HttpStatusCode.BadRequest, Global.InvalidJsonPCallback);
            }

            context.Response.Output.Clear();
            context.Response.SetHeader(context.Response.HeaderNames.ContentType, ContentType);
            context.Response.SetCharsetEncoding(context.Request.Headers.AcceptCharsetEncoding);

            var serializer = JsonSerializerFactory.Create();

            if (context.Request.IsAjax && Rest.Configuration.Options.JsonSettings.LowerPropertiesForAjax)
            {
                serializer.ContractResolver = contractResolver;
            }

            if (ReturnedType == null && Content != null)
            {
                ReturnedType = Content.GetType();
            }

            if (!NonGenericCollectionValidator.ValidateType(ReturnedType))
            {
                throw new HttpResponseException(HttpStatusCode.InternalServerError, Global.NonGenericResultCollections);
            }

            if (ReturnedType != null && ReturnedType.IsGenericType && SerializeAsSpecializedCollection(context, serializer))
            {
                return;
            }

            OutputCompressionManager.FilterResponse(context);

            TryAddCallbackStart(context.Response.Output.Writer);
            serializer.Serialize(context.Response.Output.Writer, WrapContent ? new { d = Content } : Content);
            TryAddCallbackEnd(context.Response.Output.Writer);

            LogResponse(Content);
        }
        /// <summary>
        /// Called before a service method is executed.
        /// </summary>
        /// <param name="serviceContext">The service context.</param>
        /// <param name="behaviorContext">The "method executing" behavior context.</param>
        /// <returns>A service method action.</returns>
        public override BehaviorMethodAction OnMethodExecuting(IServiceContext serviceContext, MethodExecutingContext behaviorContext)
        {
            if (serviceContext == null)
            {
                throw new ArgumentNullException("serviceContext");
            }

            serviceContext.GetHttpContext().Items[ServiceCallConstants.MaxQueryResults] = AllowOverride ? (MaxResults * -1) : MaxResults;

            return BehaviorMethodAction.Execute;
        }
예제 #31
0
 IExecuteActivityScopeProvider <TActivity, TArguments> CreateExecuteActivityScopeProvider <TActivity, TArguments>(IServiceContext context)
     where TActivity : class, ExecuteActivity <TArguments>
     where TArguments : class
 {
     return(new LamarExecuteActivityScopeProvider <TActivity, TArguments>(context.GetRequiredService <IContainer>()));
 }
예제 #32
0
 /** <inheritdoc /> */
 public void Init(IServiceContext context)
 {
     // No-op.
 }
예제 #33
0
 ICompensateActivityScopeProvider <TActivity, TLog> CreateCompensateActivityScopeProvider <TActivity, TLog>(IServiceContext context)
     where TActivity : class, CompensateActivity <TLog>
     where TLog : class
 {
     return(new LamarCompensateActivityScopeProvider <TActivity, TLog>(context.GetRequiredService <IContainer>()));
 }
예제 #34
0
 /// <summary>
 /// Defines the actions to take when the service is first executed
 /// </summary>
 /// <param name="context"></param>
 public void Execute(IServiceContext context)
 {
     Log.LogInformation("Executing TRex Service 'SurveyedSurfaceService'");
 }
예제 #35
0
 public DiscordarNoticia(IUnitOfWork uow, IServiceContext serviceContext, ILogTransacaoRepository logTransacaoRepository, IOpiniaoRepository opiniaoRepository)
     : base(uow, serviceContext, logTransacaoRepository)
 {
     Uow = uow;
     _opiniaoRepository = opiniaoRepository;
 }
예제 #36
0
 public BaseViewModel(DT data, IServiceContext serviceContext)
     : base(serviceContext)
 {
     SetData(data);
 }
예제 #37
0
 public SearchRepository(IServiceContext serviceContext)
 {
     _serviceContext = serviceContext;
 }
예제 #38
0
 public AdaptorClientHost(IServiceContext serviceContext, IInstanceContext instanceContext)
 {
     this.serviceContext  = serviceContext;
     this.instanceContext = instanceContext;
     this.serviceHosts    = serviceContext.ServiceHosts;
 }
예제 #39
0
 public EpisodeStateDownloaded(IServiceContext serviceContext)
     : base(serviceContext)
 {
 }
예제 #40
0
 public ZeusPlus([Import] IServiceContext context)
 {
     Context        = context;
     AbilityFactory = context.AbilityFactory;
 }
예제 #41
0
 public LoggedService(IServiceContext context)
 {
     Service = new DefaultService(context);
     Log     = context.Logger;
 }
예제 #42
0
 /// <summary>
 /// Cancels this instance.
 /// <para/>
 /// Note that Ignite cannot guarantee that the service exits from <see cref="IService.Execute"/>
 /// method whenever <see cref="IService.Cancel"/> is called. It is up to the user to
 /// make sure that the service code properly reacts to cancellations.
 /// </summary>
 /// <param name="context">Service execution context.</param>
 public void Cancel(IServiceContext context)
 {
     Console.WriteLine("Service cancelled: " + context.Name);
 }
예제 #43
0
        public virtual void Execute(object parameter)
        {
            IServiceContext childContext = BeanContext.CreateService(CreateModuleType);

            bool success = false;

            try
            {
                EventHandler eventHandler = new EventHandler(delegate(Object sender, EventArgs e)
                {
                    ChildWindow childWindow = childContext.GetService <ChildWindow>(PopupWindowBean);

                    bool?dialogResult = childWindow.DialogResult;
                    if (!dialogResult.HasValue || !dialogResult.Value)
                    {
                        return;
                    }

                    IModelSingleContainer <T> singleContainer = childContext.GetService <IModelSingleContainer <T> >();
                    T newItem = singleContainer.Value;
                    if (parameter is IGenericViewModel <T> )
                    {
                        ((IGenericViewModel <T>)parameter).InsertAt(0, newItem);
                    }
                    else if (parameter is IModelMultiContainer <T> )
                    {
                        ((IModelMultiContainer <T>)parameter).Values.Insert(0, newItem);
                    }
                    else if (parameter is IModelSingleContainer <T> )
                    {
                        ((IModelSingleContainer <T>)parameter).Value = newItem;
                    }
                    else if (parameter is IList <T> )
                    {
                        ((IList <T>)parameter).Insert(0, newItem);
                    }
                    else if (parameter is T)
                    {
                        parameter = newItem;
                    }
                    else
                    {
                        String errorString = "parameter for create command can not hold an item of type " + newItem.GetType().ToString();
                        Log.Error(errorString);
                        throw new ArgumentException(errorString);
                    }
                });
                childContext.Link(eventHandler).To(PopupWindowBean, ChildWindowEvents.Closed);
                success = true;
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                throw;
            }
            finally
            {
                if (!success)
                {
                    childContext.Dispose();
                }
            }
        }
예제 #44
0
 public static User GetUser(IServiceContext serviceContext, string token)
 {
     return(serviceContext.Cache.Get <User>(prefix + token));
 }
예제 #45
0
        public virtual Object PostProcessBean(IBeanContextFactory beanContextFactory, IServiceContext beanContext, IBeanConfiguration beanConfiguration, Type beanType, Object targetBean, ISet <Type> requestedTypes)
        {
            if (!typeof(FrameworkElement).IsAssignableFrom(beanType))
            {
                // Handle only FrameworkElements
                return(targetBean);
            }
            if (beanType.IsAssignableFrom(typeof(UserControl)))
            {
                // Ignore all instances which are base types of UserControl
                return(targetBean);
            }

            ISet <Object> alreadyHandledBeans = factoryToAlreadyHandledNames[beanContextFactory];

            if (alreadyHandledBeans == null)
            {
                alreadyHandledBeans = new IdentityHashSet <Object>();
                factoryToAlreadyHandledNames[beanContextFactory] = alreadyHandledBeans;
            }
            if (alreadyHandledBeans.Contains(targetBean))
            {
                //Do not yet add the Bean to the list.
                return(targetBean);
            }

            FrameworkElement frameworkElement          = (FrameworkElement)targetBean;
            MethodInfo       initializeComponentMethod = beanType.GetMethod("InitializeComponent");

            if (initializeComponentMethod != null)
            {
                IServiceContext oldCurrentBeanContext = XamlBeanProvider.CurrentBeanContext;
                try
                {
                    XamlBeanProvider.CurrentBeanContext = beanContext;
                    initializeComponentMethod.Invoke(targetBean, null);
                }
                catch (Exception e)
                {
                    throw new Exception("InitializeComponent of \"" + frameworkElement.Name + "\" (" + beanType.FullName + ") failed.", e);
                }
                finally
                {
                    XamlBeanProvider.CurrentBeanContext = oldCurrentBeanContext;
                }
            }

            if (!typeof(UIElement).IsAssignableFrom(beanType))
            {
                return(targetBean);
            }

            ISet <Object> unnamedBeans = new IdentityHashSet <Object>();
            IDictionary <String, Object> namedBeans = new Dictionary <String, Object>();

            CollectChildBeans((UIElement)targetBean, unnamedBeans, namedBeans, alreadyHandledBeans);

            foreach (Object unnamedBean in unnamedBeans)
            {
                IBeanConfiguration nestedBeanConfiguration = beanContextFactory.RegisterWithLifecycle(unnamedBean);
                if (unnamedBean is ISelfRegisteringControlBean)
                {
                    ((ISelfRegisteringControlBean)unnamedBean).RegisterSelf(nestedBeanConfiguration, beanContext, beanContextFactory);
                }
            }
            foreach (KeyValuePair <String, Object> namedBean in namedBeans)
            {
                Object             currentNamedBean        = namedBean.Value;
                IBeanConfiguration nestedBeanConfiguration = beanContextFactory.RegisterWithLifecycle(namedBean.Key, currentNamedBean);
                if (currentNamedBean is ISelfRegisteringControlBean)
                {
                    ((ISelfRegisteringControlBean)currentNamedBean).RegisterSelf(nestedBeanConfiguration, beanContext, beanContextFactory);
                }
            }
            if (targetBean is ISelfRegisteringControlBean)
            {
                ((ISelfRegisteringControlBean)targetBean).RegisterSelf(beanConfiguration, beanContext, beanContextFactory);
            }
            return(targetBean);
        }
예제 #46
0
 public PodcastSummaryViewModel(Podcast podcast, IServiceContext serviceContext)
     : base(podcast, serviceContext)
 {
     podcast.Episodes.CollectionChanged += OnEpisodesChanged;
 }
 protected KeyPressOrbwalkingModeAsync(IServiceContext context, Key key)
     : base(context)
 {
     this.Input = context.Input;
     this.Key   = key;
 }
 public InativarPublicacao(IUnitOfWork uow, IServiceContext serviceContext, ILogTransacaoRepository logTransacaoRepository, IPublicacaoRepository publicacaoRepository)
     : base(uow, serviceContext, logTransacaoRepository)
 {
     _publicacaoRepository = publicacaoRepository;
 }
예제 #49
0
 protected LoggedServiceBase(IServiceContext context, IService service)
 {
     Log     = context.LogServiceMethod;
     Service = service;
 }
예제 #50
0
 public EarthSpiritCrappa([Import] IServiceContext context)
 {
     Context = context;
 }
예제 #51
0
 public IoCEndpoint(IServiceContext serviceContext)
 {
     _serviceContext = serviceContext;
     _loggerFactory  = _serviceContext.Resolve <Func <string, ILogger> >();
     _loggerFactory("Custom Origin").Information("Invoke constructor for endpoint IoC");
 }
 public static void CompensateActivityHost <TActivity, TLog>(this IReceiveEndpointConfigurator configurator, IServiceContext context,
                                                             Action <ICompensateActivityConfigurator <TActivity, TLog> > configure = null)
     where TActivity : class, CompensateActivity <TLog>
     where TLog : class
 {
     CompensateActivityHost(configurator, context.GetInstance <IContainer>(), configure);
 }
예제 #53
0
 public Service(IServiceContext context)
 {
     Context = context;
 }
 /// <summary>
 /// Registers a saga using the container that has the repository resolved from the container
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="configurator"></param>
 /// <param name="context"></param>
 /// <param name="configure"></param>
 /// <returns></returns>
 public static void Saga <T>(this IReceiveEndpointConfigurator configurator, IServiceContext context, Action <ISagaConfigurator <T> > configure = null)
     where T : class, ISaga
 {
     Saga(configurator, context.GetInstance <IContainer>(), configure);
 }
예제 #55
0
 public Container(IServiceContext serviceContext)
 {
     this.serviceContext = serviceContext;
 }
예제 #56
0
 /// <summary>
 /// Defines the actions to take if the service is cancelled
 /// </summary>
 /// <param name="context"></param>
 public void Cancel(IServiceContext context)
 {
 }
예제 #57
0
 public GroupPageViewModel(PodcastGroup group, IServiceContext serviceContext)
     : base(group, serviceContext)
 {
 }
예제 #58
0
 public static void PutUser(IServiceContext serviceContext, User user, string token)
 {
     serviceContext.Cache.Store(prefix + token, user, userSessionTimeout);
 }
예제 #59
0
 protected static Criterion[] ThroughCriterionConverter(
     IServiceContext ctx, Criterion criterion)
 {
     return(new Criterion[] { criterion });
 }
예제 #60
0
 /// <summary>
 /// Starts execution of this service. This method is automatically invoked whenever an instance of the service
 /// is deployed on an Ignite node. Note that service is considered deployed even after it exits the Execute
 /// method and can be cancelled (or undeployed) only by calling any of the Cancel methods on
 /// <see cref="IServices"/> API. Also note that service is not required to exit from Execute method until
 /// Cancel method was called.
 /// </summary>
 /// <param name="context">Service execution context.</param>
 public void Execute(IServiceContext context)
 {
     Console.WriteLine("Service started: " + context.Name);
 }