コード例 #1
0
        /// <summary>
        /// Создает обертку
        /// </summary>
        /// <param name="c"></param>
        public ComponentDefinitionWrapper(IComponentDefinition c)
        {
            Name = c.Name;
            var impltype = c.Implementation == null
                                               ? c.ImplementationType
                                               : c.Implementation.GetType();

            ImplAssembly = impltype.Assembly.GetName().Name;
            ImplNs       = impltype.Namespace;
            ImplType     = impltype.Name;

            ServiceAssembly = c.ServiceType.Assembly.GetName().Name;
            ServiceNs       = c.ServiceType.Namespace;
            ServiceType     = c.ServiceType.Name;
            Lifestyle       = c.Lifestyle;
            Tag             = c.Tag;
            Role            = c.Role;
            Priority        = c.Priority;
            ActivationCount = c.ActivationCount;
            CreationCount   = c.CreationCount;
            Parameters      = c.Parameters;
            Help            = c.Help;
            Id = c.ContainerId;
            if (null != c.Source)
            {
                FileName = Path.GetFileName(c.Source.Attribute("_file").Value);
                Line     = c.Source.Attribute("_line").Value;
            }
        }
コード例 #2
0
ファイル: Container.cs プロジェクト: Qorpent/qorpent.sys
        /// <summary>
        ///     Отменяет регистрацию компонента
        /// </summary>
        /// <param name="component"> компонент, который должен быть убран из контейнера </param>
        /// <remarks>
        ///     <note>Очевидно что, такой метод обязан присутствовать в интерфейсе контейнера, однако его использование в задачах помимо тестирования,
        ///         обозначает недостатки архитектуры приложения, так как в нормальном варианте использования контейнер меняет свое поведение по принципу наращивания
        ///         обслуживаемых классов и компонентов, тогда как удаление части компонент может привести к неожиданным эффектам в случае кэширования более
        ///         ранеей выдвачи клиентской стороной</note>
        /// </remarks>
        public void Unregister(IComponentDefinition component)
        {
            lock (this) {
                if (null == component)
                {
                    return;
                }
                if (!Components.Contains(component))
                {
                    return;
                }
                Components.Remove(component);
                ByTypeCache[component.ServiceType].Remove(component);
                if (component.Name.IsNotEmpty())
                {
                    ByNameCache[component.Name].Remove(component);
                }
                foreach (var componentDefinition in OutgoingCache.ToArray())
                {
                    if (Equals(componentDefinition.Value, component))
                    {
                        DropObject(componentDefinition.Key);
                        OutgoingCache.Remove(componentDefinition.Key);
                    }
                }
                if (Lifestyle.PerThread == component.Lifestyle)
                {
                    foreach (var threadCache in ThreadOutgoingCache.ToArray())
                    {
                        foreach (var componentDefinition in threadCache.Value.ToArray())
                        {
                            if (Equals(componentDefinition.Value, component))
                            {
                                DropObject(componentDefinition.Key);
                                OutgoingCache.Remove(componentDefinition.Key);
                            }
                        }
                    }
                }
                if (Lifestyle.Pooled == component.Lifestyle)
                {
                    if (Pool.ContainsKey(component))
                    {
                        foreach (var obj in Pool[component])
                        {
                            DropObject(obj);
                        }
                        Pool.Remove(component);
                    }
                }

                // hook for extensions - UnRegisterComponent extensions can do something after it's
                // native unregistration
                ProcessExtensions(new ContainerContext {
                    Operation = ContainerOperation.UnregisterComponent, Component = component
                });
            }
        }
コード例 #3
0
ファイル: Container.cs プロジェクト: Qorpent/qorpent.sys
        private void ProcessExplicitInjections(IComponentDefinition component, object result)
        {
            var ca = result as IContainerBound;

            if (null != ca)
            {
                ca.SetContainerContext(this, component);
            }
        }
コード例 #4
0
ファイル: SoapRecorder.cs プロジェクト: julienblin/Remora
        public override void EndAsyncProcess(IRemoraOperation operation, IComponentDefinition componentDefinition,
                                             Action callback)
        {
            if (operation.Kind == RemoraOperationKind.Soap)
            {
                EndRecordSoapOperation(operation, componentDefinition);
            }

            callback();
        }
コード例 #5
0
ファイル: Container.cs プロジェクト: Qorpent/qorpent.sys
 private void ProcessParametersInjection(object result, IComponentDefinition component)
 {
     if (component.Parameters.IsNotEmpty())
     {
         foreach (var parameter in component.Parameters)
         {
             //applys parameters in very save mode
             result.SetValue(parameter.Key, parameter.Value, ignoreNotFound: true, publicOnly: false,
                             ignoreTypeConversionError: true);
         }
     }
 }
コード例 #6
0
ファイル: Tracer.cs プロジェクト: julienblin/Remora
 public override void EndAsyncProcess(IRemoraOperation operation, IComponentDefinition componentDefinition,
                                      Action callback)
 {
     try
     {
         TraceOperation(operation, componentDefinition);
     }
     catch (Exception ex)
     {
         Logger.WarnFormat(ex, "There has been an error while tracing operation {0}.", operation);
     }
     callback();
 }
コード例 #7
0
ファイル: Container.cs プロジェクト: Qorpent/qorpent.sys
        /// <summary>
        ///     Проверяет наличие в реестре компонента по внутренней логике сравнения
        /// </summary>
        /// <param name="component"> </param>
        /// <returns> </returns>
        protected bool ComponentExists(IComponentDefinition component)
        {
            var existed = FindComponent(component.ServiceType, component.Name);

            if (null == existed)
            {
                return(false);
            }
            if (component.ServiceType != existed.ServiceType)
            {
                return(false);                //был найден унаследованный тип
            }
            if (component.Name != existed.Name)
            {
                return(false);                //при поиске без  имени был найден именованный компонент
            }
            if (component.Lifestyle != existed.Lifestyle)
            {
                return(false);
            }
            if (component.Priority != existed.Priority)
            {
                return(false);
            }
            if (component.ImplementationType != existed.ImplementationType)
            {
                return(false);
            }
            if (component.Implementation != existed.Implementation)
            {
                return(false);
            }
            if (component.Parameters.Count != existed.Parameters.Count)
            {
                return(false);
            }
            foreach (var p in component.Parameters)
            {
                if (!existed.Parameters.ContainsKey(p.Key))
                {
                    return(false);
                }
                if (p.Value != existed.Parameters[p.Key])
                {
                    return(false);
                }
            }
            return(true);
        }
コード例 #8
0
ファイル: SoapRecorder.cs プロジェクト: julienblin/Remora
        public override void BeginAsyncProcess(IRemoraOperation operation, IComponentDefinition componentDefinition,
                                               Action<bool> callback)
        {
            if (operation.Kind == RemoraOperationKind.Soap)
            {
                RecordSoapOperation(operation);
            }
            else
            {
                Logger.WarnFormat("Unable to record operation {0} because it appears to not be a soap request.",
                                  operation);
            }

            callback(true);
        }
コード例 #9
0
 /// <summary>
 ///     Unregesters component
 /// </summary>
 /// <param name="component"> </param>
 public void Unregister(IComponentDefinition component)
 {
     if (component == null)
     {
         return;                    // hack:
     }
     if (!_typemap.ContainsKey(component.ServiceType))
     {
         return;
     }
     //do not unregister not component's types
     if (!(_typemap[component.ServiceType] == component.ImplementationType))
     {
         return;
     }
     _typemap.Remove(component.ServiceType);
 }
コード例 #10
0
ファイル: Tracer.cs プロジェクト: julienblin/Remora
        public override void BeginAsyncProcess(IRemoraOperation operation, IComponentDefinition componentDefinition,
                                               Action<bool> callback)
        {
            var category = GetCategory(componentDefinition);
            var executionPropertyKey = GetStopwatchExecutionPropertyKey(category);
            if (operation.ExecutionProperties.ContainsKey(executionPropertyKey))
            {
                Logger.WarnFormat(
                    "There may exists two tracer with the same category ({0}) in the same pipeline. Results may be inacurate.",
                    category);
            }

            var stopwatch = new Stopwatch();
            stopwatch.Start();
            operation.ExecutionProperties[executionPropertyKey] = stopwatch;
            callback(true);
        }
コード例 #11
0
ファイル: SoapPlayer.cs プロジェクト: julienblin/Remora
        public override void BeginAsyncProcess(IRemoraOperation operation, IComponentDefinition componentDefinition,
                                               Action<bool> callback)
        {
            if (operation == null) throw new ArgumentNullException("operation");
            if (componentDefinition == null) throw new ArgumentNullException("componentDefinition");
            if (callback == null) throw new ArgumentNullException("callback");
            Contract.EndContractBlock();

            switch (operation.Kind)
            {
                case RemoraOperationKind.Soap:
                    PlaySoapOperation(operation, componentDefinition);
                    break;
                default:
                    throw new SoapPlayerException(
                        string.Format("Unable to playback operation {0} because it is not a soap operation.", operation));
            }
            callback(false);
        }
コード例 #12
0
ファイル: Container.cs プロジェクト: Qorpent/qorpent.sys
        /// <summary>
        ///     comparising method for components - find most preferable component in set
        /// </summary>
        /// <param name="a"> A. </param>
        /// <param name="b"> The b. </param>
        /// <returns> </returns>
        /// <remarks>
        /// </remarks>
        protected internal int CompareComponents(IComponentDefinition a, IComponentDefinition b)
        {
            var ap = a.Priority;
            var bp = b.Priority;

            if (ap == -1)
            {
                ap = 10000;
            }
            if (bp == -1)
            {
                bp = 10000;
            }
            var result = ap.CompareTo(bp);             // if priority not equal- less - first

            if (0 == result)
            {
                result = -a.ContainerId.CompareTo(b.ContainerId);                  //otherwise last (by containerId) is in priority
            }
            return(result);
        }
コード例 #13
0
ファイル: Container.cs プロジェクト: Qorpent/qorpent.sys
        /// <summary>
        ///     creates new instance of component's object, IContainerBound.SetContainerContext called
        /// </summary>
        /// <param name="component"> The component. </param>
        /// <param name="arguments"> аргументы для конструктора, если <c>null</c> , то будет использован конструктор по умолчанию </param>
        /// <returns> </returns>
        /// <remarks>
        /// </remarks>
        protected internal object CreateInstance(IComponentDefinition component, object[] arguments)
        {
            try {
                object result = Activator.CreateInstance(component.ImplementationType,
                                                         BindingFlags.Instance | BindingFlags.CreateInstance | BindingFlags.Public |
                                                         BindingFlags.NonPublic,
                                                         null,
                                                         arguments, CultureInfo.InvariantCulture);

                component.CreationCount++;
                ProcessAttributedInjections(result);
                ProcessParametersInjection(result, component);
                ProcessExplicitInjections(component, result);
                var context = new ContainerContext
                {
                    Component = component,
                    Operation = ContainerOperation.AfterCreate,
                    Object    = result,
                };
                ProcessExtensions(context);
                var o = context.Object as IContainerBound;
                if (o != null)
                {
                    o.OnContainerCreateInstanceFinished();
                }
                return(context.Object);
            }
            catch (ContainerException ex) {
                Log.Error("CreateInstance of" + component, ex);
                throw;
            }
            catch (Exception ex) {
                Log.Error("CreateInstance of" + component, ex);
                throw new ContainerException("CreateInstance " + component, ex);
            }
        }
コード例 #14
0
 /// <summary>
 ///     Конвертирует строку с описанием сборки или типа в перечисление типов расширений
 /// </summary>
 /// <param name="extensionDescriptor"></param>
 /// <returns></returns>
 private IEnumerable <Type> GetExtensionTypes(string extensionDescriptor)
 {
     if (extensionDescriptor.IsLiteral(EscapingType.JsonLiteral))
     {
         IComponentDefinition pkg = Container.FindComponent(typeof(IBSharpBuilderExtension), extensionDescriptor + ".bsbext");
         if (null != pkg)
         {
             yield return(pkg.ImplementationType);
         }
         else
         {
             throw new Exception("cannot find IBSharpBuilderExtension for " + extensionDescriptor + ".bsbext");
         }
     }
     else
     {
         if (extensionDescriptor.Contains(","))
         {
             yield return(Type.GetType(extensionDescriptor));
         }
         else
         {
             Assembly assembly = Assembly.Load(extensionDescriptor);
             foreach (Type t in assembly.GetTypes())
             {
                 if (typeof(IBSharpBuilderExtension).IsAssignableFrom(t))
                 {
                     if (!t.IsAbstract)
                     {
                         yield return(t);
                     }
                 }
             }
         }
     }
 }
コード例 #15
0
ファイル: Tracer.cs プロジェクト: julienblin/Remora
        private void TraceOperation(IRemoraOperation operation, IComponentDefinition componentDefinition)
        {
            var category = GetCategory(componentDefinition);

            if (!componentDefinition.Properties.ContainsKey("directory"))
            {
                Logger.WarnFormat(
                    "Unable to trace operation {0}: no directory has been provided. You must use the directory attribute in the component configuration.",
                    operation);
                return;
            }
            var directoryPath = componentDefinition.Properties["directory"];

            if (!Directory.Exists(directoryPath))
            {
                try
                {
                    Directory.CreateDirectory(directoryPath);
                }
                catch (Exception ex)
                {
                    Logger.WarnFormat(ex,
                                      "Unable to trace operation {0}: the directory {1} does not exists and there has been an error when creating it.",
                                      operation, directoryPath);
                    return;
                }
            }

            var fileName = Path.Combine(directoryPath,
                                        string.Format("{0}-{1}-{2}.xml",
                                                      DateTime.UtcNow.ToString("s").MakeValidFileName(),
                                                      category.MakeValidFileName(), operation.OperationId));

            if (Logger.IsDebugEnabled)
                Logger.DebugFormat("Operation {0}: saving trace ({1}) in {2}...", operation, category, fileName);

            var serializableOperation = new SerializableOperation(operation);

            var stopwatchExecutionProperty = GetStopwatchExecutionPropertyKey(category);
            if (operation.ExecutionProperties.ContainsKey(stopwatchExecutionProperty))
            {
                var stopwatch = (Stopwatch) operation.ExecutionProperties[stopwatchExecutionProperty];
                stopwatch.Stop();
                serializableOperation.ElapsedMilliseconds = stopwatch.ElapsedMilliseconds;
            }

            using (var writeStream = File.OpenWrite(fileName))
            {
                serializableOperation.Serialize(writeStream);
            }

            if (Logger.IsDebugEnabled)
                Logger.DebugFormat("Operation {0}: successfully traced ({1}) in {1}.", operation, category, fileName);
        }
コード例 #16
0
 /// <summary>
 ///     Register new component
 /// </summary>
 /// <param name="component"> </param>
 public void Register(IComponentDefinition component)
 {
     _typemap[component.ServiceType] = component.ImplementationType;
 }
コード例 #17
0
 public void SetContainerContext(IContainer container, IComponentDefinition component) {
     this.Container = container;
 }
コード例 #18
0
ファイル: Sender.cs プロジェクト: julienblin/Remora
        public override void BeginAsyncProcess(IRemoraOperation operation, IComponentDefinition componentDefinition,
                                               Action<bool> callback)
        {
            if (Logger.IsDebugEnabled)
                Logger.DebugFormat("Preparing to send {0}...", operation);

            if (operation.Request.Uri == null)
            {
                throw new UnknownDestinationException(
                    string.Format(
                        "Unable to send {0}: no destination uri is defined. Either use a rewrite attribute on the pipeline or create a custom IPipelineComponent that will determine the destination uri.",
                        operation));
            }

            if (!HttpSchemeRx.IsMatch(operation.Request.Uri.Scheme))
            {
                throw new InvalidDestinationUriException(
                    string.Format(
                        "The destination uri for {0} is not a valid uri: {1}. Remora supports only http(s) destinations.",
                        operation, operation.Request.Uri));
            }

            var webRequest = (HttpWebRequest) WebRequest.Create(operation.Request.Uri);

            if ((operation.ExecutingPipeline != null)
                && (operation.ExecutingPipeline.Definition != null)
                && (!string.IsNullOrEmpty(operation.ExecutingPipeline.Definition.ClientCertificateFilePath))
                )
            {
                ManageCertificate(webRequest, operation.ExecutingPipeline.Definition.ClientCertificateFilePath,
                                  operation.ExecutingPipeline.Definition.ClientCertificatePassword);
            }

            webRequest.Method = operation.Request.Method ?? "POST";
            SetHttpHeaders(operation, webRequest);

            if (webRequest.Method.ToLowerInvariant() != "get")
            {
                WriteData(operation, webRequest);
            }
            else
            {
                webRequest.ContentLength = 0;
            }

            webRequest.BeginGetResponse((result) =>
                                            {
                                                webRequest = (HttpWebRequest) result.AsyncState;
                                                try
                                                {
                                                    var response = (HttpWebResponse) webRequest.EndGetResponse(result);
                                                    ReadResponse(operation, response, componentDefinition);
                                                    if (Logger.IsDebugEnabled)
                                                        Logger.DebugFormat(
                                                            "Successfully received response from {0} for {1}.",
                                                            webRequest.RequestUri, operation);
                                                }
                                                catch (WebException webEx)
                                                {
                                                    if (webEx.Status == WebExceptionStatus.ProtocolError)
                                                    {
                                                        ReadResponse(operation, (HttpWebResponse) webEx.Response,
                                                                     componentDefinition);
                                                        if (Logger.IsDebugEnabled)
                                                            Logger.DebugFormat(
                                                                "Successfully received response from {0} for {1}.",
                                                                webRequest.RequestUri, operation);
                                                    }
                                                    else
                                                    {
                                                        var message =
                                                            string.Format(
                                                                "There has been an error while sending {0} to {1}.",
                                                                operation, webRequest.RequestUri);
                                                        Logger.Error(message, webEx);
                                                        operation.Exception = new SendException(message, webEx);
                                                    }
                                                }
                                                catch (Exception ex)
                                                {
                                                    var message =
                                                        string.Format(
                                                            "There has been an error while sending {0} to {1}.",
                                                            operation, webRequest.RequestUri);
                                                    Logger.Error(message, ex);
                                                    operation.Exception = new SendException(message, ex);
                                                }
                                                finally
                                                {
                                                    callback(false);
                                                }
                                            }, webRequest);
        }
コード例 #19
0
ファイル: Tracer.cs プロジェクト: julienblin/Remora
 private static string GetCategory(IComponentDefinition componentDefinition)
 {
     return componentDefinition.Properties.ContainsKey("category")
                ? componentDefinition.Properties["category"]
                : "default";
 }
コード例 #20
0
 public void SetContainerContext(IContainer container, IComponentDefinition component)
 {
     ContainerBoundTest   = component.Parameters.GetValue <int>("cbt", -1);
     ContainerBoundCalled = true;
 }
コード例 #21
0
ファイル: Container.cs プロジェクト: Qorpent/qorpent.sys
        /// <summary>
        ///     Регистрирует новый компонент в контейнере
        /// </summary>
        public void Register(IComponentDefinition component)
        {
            lock (this) {
#if PARANOID
                if (component.ServiceType == typeof(IRoleResolver))
                {
                    if (component.ImplementationType != typeof(DefaultRoleResolver))
                    {
                        throw new ParanoidException(ParanoidState.InvalidRoleResolver);
                    }
                }

                if (component.ServiceType == typeof(IPrincipalSource))
                {
                    if (component.ImplementationType != typeof(DefaultPrincipalSource))
                    {
                        throw new ParanoidException(ParanoidState.InvalidPrincipalSource);
                    }
                }
                                #endif

                Log.Debug("Start register " + component, this);
                // redirect logic for container extensions - they are processed on their own manner
                // and container extensions don't trigger RegisterComponent event
                if (component.Lifestyle == Lifestyle.ContainerExtension)
                {
                    if (null == _extensions.FirstOrDefault(x => x.GetType() == component.ImplementationType))
                    {
                        RegisterExtension((IContainerExtension)Activator.CreateInstance(component.ImplementationType));
                    }
                    return;
                }
                // hook for extensions - RegisterComponent extensions can replace/update/Prepare component to be registered
                // it can be used only BEFORE native registration due to index integrity
                component =
                    ProcessExtensions(new ContainerContext
                {
                    Operation = ContainerOperation.BeforeRegisterComponent, Component = component
                }).Component;

                //no need double registration
                if (ComponentExists(component))
                {
                    return;
                }
                component.ContainerId = CurrentComponentId++;
                Components.Add(component);
                if (!ByTypeCache.ContainsKey(component.ServiceType))
                {
                    ByTypeCache[component.ServiceType] = new List <IComponentDefinition>();
                }
                ByTypeCache[component.ServiceType].Add(component);
                ByTypeCache[component.ServiceType].Sort(CompareComponents);
                if (component.Name.IsNotEmpty())
                {
                    if (!ByNameCache.ContainsKey(component.Name))
                    {
                        ByNameCache[component.Name] = new List <IComponentDefinition>();
                    }
                    ByNameCache[component.Name].Add(component);
                    ByNameCache[component.Name].Sort(CompareComponents);
                }

                ProcessExtensions(new ContainerContext
                {
                    Operation = ContainerOperation.AfterRegisterComponent, Component = component
                });
                Log.Debug("Registered " + component, this);
            }
        }
コード例 #22
0
ファイル: SoapPlayer.cs プロジェクト: julienblin/Remora
        private bool MockMatch(SerializableOperation serializableOperation, XDocument requestDoc,
                               IComponentDefinition componentDefinition)
        {
            var refDoc = XDocument.Parse(serializableOperation.Request.Content).Normalize();

            var refBody = _soapTransformer.GetBody(refDoc);
            var currentBody = _soapTransformer.GetBody(requestDoc);

            return XNode.DeepEquals(refBody, currentBody);
        }
コード例 #23
0
		/// <summary>
		/// 	called on object after creation in IoC with current component context
		/// 	object can perform container bound logic here
		/// </summary>
		/// <param name="container"> The container. </param>
		/// <param name="component"> The component. </param>
		/// <remarks>
		/// </remarks>
		public override void SetContainerContext(IContainer container, IComponentDefinition component) {
			base.SetContainerContext(container, component);
			container.RegisterExtension(new LogManagerContainerExtension(this));
		}
コード例 #24
0
 /// <summary>
 ///     called on object after creation in IoC with current component context
 ///     object can perform container bound logic here
 /// </summary>
 /// <param name="container"> The container. </param>
 /// <param name="component"> The component. </param>
 /// <remarks>
 /// </remarks>
 public override void SetContainerContext(IContainer container, IComponentDefinition component)
 {
     base.SetContainerContext(container, component);
     container.RegisterExtension(new LogManagerContainerExtension(this));
 }
コード例 #25
0
 public PipelineDefinition()
 {
     ComponentDefinitions = new IComponentDefinition[0];
     Properties = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);
 }
コード例 #26
0
ファイル: Sender.cs プロジェクト: julienblin/Remora
        protected virtual void ReadResponse(IRemoraOperation operation, HttpWebResponse response,
                                            IComponentDefinition componentDefinition)
        {
            operation.Response.StatusCode = (int) response.StatusCode;
            operation.Response.Uri = response.ResponseUri;

            foreach (var header in response.Headers.AllKeys)
            {
                operation.Response.HttpHeaders.Add(header, response.Headers[header]);
            }

            using (var stream = response.GetResponseStream())
            {
                operation.Response.Data = stream.ReadFully(_config.MaxMessageSize);
            }

            ReadEncoding(operation, response, componentDefinition);
        }
コード例 #27
0
ファイル: SoapRecorder.cs プロジェクト: julienblin/Remora
        private void EndRecordSoapOperation(IRemoraOperation operation, IComponentDefinition componentDefinition)
        {
            if (!operation.ExecutionProperties.ContainsKey(SoapActionKey))
                return;

            var soapActionName = (string) operation.ExecutionProperties[SoapActionKey];

            if (!componentDefinition.Properties.ContainsKey("directory"))
            {
                Logger.WarnFormat(
                    "Unable to record operation {0}: no directory has been provided. You must use the directory attribute in the component configuration.",
                    operation);
                return;
            }
            var directoryPath = componentDefinition.Properties["directory"];

            if (!Directory.Exists(directoryPath))
            {
                try
                {
                    Directory.CreateDirectory(directoryPath);
                }
                catch (Exception ex)
                {
                    Logger.WarnFormat(ex,
                                      "Unable to record operation {0}: the directory {1} does not exists and there has been an error when creating it.",
                                      operation, directoryPath);
                    return;
                }
            }

            var randomAppendToFileName = Path.GetFileNameWithoutExtension(Path.GetRandomFileName());
            var fileName = Path.Combine(directoryPath,
                                        string.Format("{0}.{1}.xml", soapActionName.MakeValidFileName(),
                                                      randomAppendToFileName));

            if (Logger.IsDebugEnabled)
                Logger.DebugFormat("Operation {0}: saving record for {1} in {2}...", operation, soapActionName, fileName);

            var serializableOperation = new SerializableOperation(operation);

            try
            {
                using (var writeStream = File.OpenWrite(fileName))
                {
                    serializableOperation.Serialize(writeStream);
                }

                if (Logger.IsDebugEnabled)
                    Logger.DebugFormat("Operation {0}: successfully recorded in {1}.", operation, fileName);
            }
            catch (Exception ex)
            {
                Logger.WarnFormat(ex, "There has been an error while saving record file {0} for operation {1}.",
                                  fileName, operation);
            }
        }
コード例 #28
0
        public void Configure(IComponentDefinition component, AttributeSet attributes)
        {
            if (ReferenceEquals(component, null))
            {
                return;
            }

            var validationErrros = _attributeMatrix.Validate <IComponentDefinition>(attributes);

            if (validationErrros != null)
            {
                var message = "There are invalid attributes on component of type " + component.GetType().DisplayName();

                if (attributes.IsComponent != null && string.IsNullOrEmpty(attributes.IsComponent.Name))
                {
                    message += " called '" + attributes.IsComponent.Name + "'.";
                }

                foreach (var error in validationErrros)
                {
                    message += Environment.NewLine + error;
                }

                throw new ComponentBuilderException(message);
            }

            if (!ReferenceEquals(attributes.IsComponent, null))
            {
                component.Name(attributes.IsComponent.Name);
            }

            if (!ReferenceEquals(attributes.DeployCsss, null))
            {
                foreach (var css in attributes.DeployCsss.OrderBy(c => c.Order))
                {
                    component.DeployCss(css.CssSelector, css.CssStyle);
                }
            }

            if (!ReferenceEquals(attributes.DeployFunctions, null))
            {
                foreach (var function in attributes.DeployFunctions)
                {
                    component.DeployFunction(
                        function.ReturnType,
                        function.FunctionName,
                        function.Parameters,
                        function.Body,
                        function.IsPublic);
                }
            }

            if (!ReferenceEquals(attributes.NeedsDatas, null))
            {
                foreach (var dataNeed in attributes.NeedsDatas)
                {
                    if (!string.IsNullOrEmpty(dataNeed.DataProviderName))
                    {
                        component.DataProvider(dataNeed.DataProviderName);
                    }
                    if (dataNeed.DataType != null)
                    {
                        component.BindTo(dataNeed.DataType, dataNeed.Scope);
                    }
                }
            }

            if (!ReferenceEquals(attributes.PartOf, null))
            {
                component.PartOf(attributes.PartOf.PackageName);
            }

            if (!ReferenceEquals(attributes.DeployedAs, null))
            {
                component
                .DeployIn(attributes.DeployedAs.ModuleName)
                .AssetDeployment(attributes.DeployedAs.Deployment);
            }

            if (!ReferenceEquals(attributes.NeedsComponents, null))
            {
                foreach (var need in attributes.NeedsComponents)
                {
                    component.NeedsComponent(need.ComponentName);
                }
            }

            if (!ReferenceEquals(attributes.RenderHtmls, null))
            {
                foreach (var html in attributes.RenderHtmls.OrderBy(h => h.Order))
                {
                    component.Render(html.TextName, html.Html);
                }
            }
        }
コード例 #29
0
 public void SetContainerContext(IContainer container, IComponentDefinition component)
 {
 }
コード例 #30
0
ファイル: SoapPlayer.cs プロジェクト: julienblin/Remora
        private void PlaySoapOperation(IRemoraOperation operation, IComponentDefinition componentDefinition)
        {
            if (Logger.IsDebugEnabled)
                Logger.DebugFormat("Trying to reply with a mock for {0}...", operation);

            if (!componentDefinition.Properties.ContainsKey("directory"))
            {
                throw new SoapPlayerException(
                    "Unable to playback because no directory has been provided. Please specify a source directory in the component definition.");
            }
            var directoryPath = componentDefinition.Properties["directory"];

            if (!operation.Request.HttpHeaders.ContainsKey("SOAPAction"))
            {
                throw new SoapPlayerException(
                    string.Format("Unable to playback operation {0} because it doesn't have a SOAPAction header.",
                                  operation));
            }

            var soapAction = operation.Request.HttpHeaders["SOAPAction"];
            IEnumerable<string> candidateFiles;
            try
            {
                candidateFiles = Directory.EnumerateFiles(directoryPath, soapAction.MakeValidFileName() + ".*");
            }
            catch (Exception ex)
            {
                throw new SoapPlayerException(
                    string.Format("There has been an error while enumerating files in {0}", directoryPath), ex);
            }

            var requestDoc = _soapTransformer.LoadSoapDocument(operation.Request).Normalize();

            foreach (var candidateFile in candidateFiles)
            {
                try
                {
                    if (Logger.IsDebugEnabled)
                        Logger.DebugFormat("Opening file {0}...", candidateFile);

                    SerializableOperation serializableOperation;
                    using (var readStream = File.OpenRead(candidateFile))
                    {
                        serializableOperation = SerializableOperation.Deserialize(readStream);
                        if (MockMatch(serializableOperation, requestDoc, componentDefinition))
                        {
                            if (Logger.IsInfoEnabled)
                                Logger.InfoFormat("Found appropriate mock for {0}: {1}.", operation, candidateFile);

                            operation.Response.ContentEncoding =
                                Encoding.GetEncoding(serializableOperation.Response.ContentEncoding);
                            foreach (var header in serializableOperation.Response.Headers)
                            {
                                operation.Response.HttpHeaders.Add(header.Name, header.Value);
                            }
                            operation.Response.StatusCode = serializableOperation.Response.StatusCode;
                            operation.Response.Data = serializableOperation.Response.GetData();
                            return;
                        }
                    }
                }
                catch (Exception ex)
                {
                    throw new SoapPlayerException(string.Format("Error while opening mock file {0}.", candidateFile), ex);
                }
            }
            throw new SoapPlayerException(
                string.Format("Unable to find appropriate mock for operation {0} in directory {1}.", operation,
                              directoryPath));
        }
コード例 #31
0
ファイル: ServiceBase.cs プロジェクト: Qorpent/qorpent.sys
 /// <summary>
 ///     Вызывается в момент создания экземпляра после применения стандартных инъекций.
 /// </summary>
 /// <param name="container"> Контейнер, создающий объект </param>
 /// <param name="component"> Компонент, описывающий объект </param>
 /// <remarks>
 ///     Стандартная реализация контейнера <see href="Qorpent.IoC~Qorpent.IoC.Container.html" /> автоматически
 ///     выполняет инъекции зависимоостей на основе параметров <see cref="IComponentDefinition.Parameters" /> и на освное <see
 ///      cref="InjectAttribute" />,
 ///     данный метод в базовой реализации устанавливает свойства  <see cref="SourceContainer" /> и <see cref="Component" />,
 ///     при перекрытии вы можете расширить логику собственным кодом связывания экземпляра с создавшим его контейнером и компонентом
 /// </remarks>
 public virtual void SetContainerContext(IContainer container, IComponentDefinition component)
 {
     SourceContainer = container;
     Component       = component;
 }
コード例 #32
0
ファイル: Sender.cs プロジェクト: julienblin/Remora
        protected virtual void ReadEncoding(IRemoraOperation operation, HttpWebResponse response,
                                            IComponentDefinition componentDefinition)
        {
            if (Logger.IsDebugEnabled)
                Logger.DebugFormat("Determining encoding for response from {0} for operation {1}...",
                                   response.ResponseUri, operation);

            if ((operation.ExecutingPipeline != null)
                && (operation.ExecutingPipeline.Definition != null)
                && (operation.ExecutingPipeline.Definition.Properties.ContainsKey("forceResponseEncoding"))
                )
            {
                try
                {
                    operation.Response.ContentEncoding =
                        Encoding.GetEncoding(operation.ExecutingPipeline.Definition.Properties["forceResponseEncoding"]);
                    if (Logger.IsDebugEnabled)
                        Logger.DebugFormat("Operation {0}: encoding forced to {1}.", operation,
                                           operation.Response.ContentEncoding);
                }
                catch (ArgumentException ex)
                {
                    Logger.ErrorFormat(ex,
                                       "There has been an error while loading encoding defined in forceResponseEncoding property: {0}",
                                       operation.ExecutingPipeline.Definition.Properties["forceResponseEncoding"]);
                    throw;
                }
            }
            else
            {
                var encoding = Encoding.UTF8; // default;
                if (!string.IsNullOrEmpty(response.CharacterSet))
                {
                    try
                    {
                        encoding = Encoding.GetEncoding(response.CharacterSet);

                        if (Logger.IsDebugEnabled)
                            Logger.DebugFormat("Operation {0}: loaded encoding {1} from character set: {2}", operation,
                                               encoding.EncodingName, response.CharacterSet);
                    }
                    catch (ArgumentException ex)
                    {
                        Logger.WarnFormat(ex, "Operation {0}: unable to load a proper encoding for character set {1}",
                                          operation, response.CharacterSet);
                    }
                }
                else
                {
                    if (Logger.IsDebugEnabled)
                        Logger.DebugFormat("Operation {0}: using default encoding {0}", operation, encoding.EncodingName);
                }

                operation.Response.ContentEncoding = encoding;
            }
        }