示例#1
0
        public IContextStrategy GetContextStrategy(ContextInformation contextInformation)
        {
            switch (contextInformation.LocationalContext)
            {
            case LocationalContext.Church:
                break;

            case LocationalContext.Government:
                break;

            case LocationalContext.Home:
                break;

            case LocationalContext.Public:
                return(new PublicInteractionStrategy());

            case LocationalContext.Palace:
                break;

            case LocationalContext.Workplace:
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            return(new PublicInteractionStrategy());
        }
示例#2
0
 public BlazorWasmTemplateTest(ProjectFactoryFixture projectFactory, PlaywrightFixture <BlazorServerTemplateTest> browserFixture, ITestOutputHelper output)
     : base(browserFixture)
 {
     ProjectFactory     = projectFactory;
     Output             = output;
     BrowserContextInfo = new ContextInformation(CreateFactory(output));
 }
示例#3
0
        internal static object GetAssociatedSection(ContextInformation evalContext, string sectionPath)
        {
            object section = null;

            if (evalContext == null)
            {
                section = (!(bool)InvokeHelper.InvokeStaticGet(typeof(ServiceHostingEnvironment), "IsHosted") ? ConfigurationManager.GetSection(sectionPath) : Microsoft.ServiceBus.Configuration.ConfigurationHelpers.GetSectionFromWebConfigurationManager(sectionPath));
                if (Microsoft.ServiceBus.Diagnostics.DiagnosticUtility.ShouldTraceVerbose)
                {
                    TraceUtility.TraceEvent(TraceEventType.Verbose, TraceCode.GetConfigurationSection, new StringTraceRecord("ConfigurationSection", sectionPath), null, null);
                }
            }
            else
            {
                section = evalContext.GetSection(sectionPath);
            }
            if (section == null)
            {
                ExceptionUtility exceptionUtility      = Microsoft.ServiceBus.Diagnostics.DiagnosticUtility.ExceptionUtility;
                string           configSectionNotFound = Resources.ConfigSectionNotFound;
                object[]         objArray = new object[] { sectionPath };
                throw exceptionUtility.ThrowHelperError(new ConfigurationErrorsException(Microsoft.ServiceBus.SR.GetString(configSectionNotFound, objArray)));
            }
            return(section);
        }
示例#4
0
        /// <inheritdoc />
        public override Task RunAsync(ContextInformation context)
        {
            // Check that the current block has not been reorged.
            // Catching a reorg at this point will not require a rewind.
            if (context.BlockValidationContext.Block.Header.HashPrevBlock != context.BlockValidationContext.ConsensusTip.HashBlock)
            {
                this.Logger.LogTrace("Reorganization detected.");
                ConsensusErrors.InvalidPrevTip.Throw();
            }

            this.Logger.LogTrace("Validating new block.");

            // Build the next block in the chain of headers. The chain header is most likely already created by
            // one of the peers so after we create a new chained block (mainly for validation)
            // we ask the chain headers for its version (also to prevent memory leaks).
            context.BlockValidationContext.ChainedBlock = new ChainedBlock(context.BlockValidationContext.Block.Header, context.BlockValidationContext.Block.Header.GetHash(), context.BlockValidationContext.ConsensusTip);

            // Liberate from memory the block created above if possible.
            context.BlockValidationContext.ChainedBlock = this.Parent.Chain.GetBlock(context.BlockValidationContext.ChainedBlock.HashBlock) ?? context.BlockValidationContext.ChainedBlock;
            context.SetBestBlock(this.Parent.DateTimeProvider.GetTimeOffset());

            // Calculate the consensus flags and check they are valid.
            context.Flags = this.Parent.NodeDeployments.GetFlags(context.BlockValidationContext.ChainedBlock);

            return(Task.CompletedTask);
        }
示例#5
0
        internal void UpdateEndpointSections(ContextInformation evaluationContext)
        {
            ExtensionElementCollection endpointExtensions = ExtensionsSection.UnsafeLookupCollection(ConfigurationStrings.EndpointExtensions, evaluationContext);

            // Extension collections are additive only (BasicMap) and do not allow for <clear>
            // or <remove> tags, nor do they allow for overriding an entry.  This allows us
            // to optimize this to only walk the binding extension collection if the counts
            // mismatch.
            if (endpointExtensions.Count != this.properties.Count)
            {
                foreach (ExtensionElement endpointExtension in endpointExtensions)
                {
                    if (null != endpointExtension)
                    {
                        if (!this.properties.Contains(endpointExtension.Name))
                        {
                            Type extensionType = Type.GetType(endpointExtension.Type, false);
                            if (extensionType == null)
                            {
                                ConfigurationHelpers.TraceExtensionTypeNotFound(endpointExtension);
                            }
                            else
                            {
                                ConfigurationProperty property = new ConfigurationProperty(endpointExtension.Name,
                                                                                           extensionType,
                                                                                           null,
                                                                                           ConfigurationPropertyOptions.None);

                                this.properties.Add(property);
                            }
                        }
                    }
                }
            }
        }
示例#6
0
        /// <inheritdoc />
        public async Task ExectueAsync(BlockValidationContext blockValidationContext)
        {
            try
            {
                var context = new ContextInformation(blockValidationContext, this.ConsensusParams);
                blockValidationContext.Context = context;

                foreach (var consensusRule in this.consensusRules)
                {
                    var rule = consensusRule.Value;

                    if (context.BlockValidationContext.SkipValidation && rule.CanSkipValidation)
                    {
                        this.logger.LogTrace("Rule {0} skipped for block at height {1}.", nameof(rule), context.BlockValidationContext.ChainedBlock.Height);
                    }
                    else
                    {
                        await rule.RunAsync(context).ConfigureAwait(false);
                    }
                }
            }
            catch (ConsensusErrorException ex)
            {
                blockValidationContext.Error = ex.ConsensusError;
            }

            if (blockValidationContext.Error != null)
            {
                // TODO invoke the error handler rule.
            }
        }
        internal static object UnsafeGetAssociatedSection(ContextInformation evalContext, string sectionPath)
        {
            object retval = null;

            if (evalContext != null)
            {
                retval = UnsafeGetSectionFromContext(evalContext, sectionPath);
            }
            else
            {
                retval = AspNetEnvironment.Current.UnsafeGetConfigurationSection(sectionPath);

                // Trace after call to underlying configuration system to
                // insure that configuration system is initialized
                if (DiagnosticUtility.ShouldTraceVerbose)
                {
                    TraceUtility.TraceEvent(TraceEventType.Verbose, TraceCode.GetConfigurationSection,
                                            SR.GetString(SR.TraceCodeGetConfigurationSection),
                                            new StringTraceRecord("ConfigurationSection", sectionPath), null, null);
                }
            }
            if (retval == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                          new ConfigurationErrorsException(SR.GetString(SR.ConfigSectionNotFound,
                                                                        sectionPath)));
            }

            return(retval);
        }
        void ValidateSection()
        {
            ContextInformation context = ConfigurationHelpers.GetEvaluationContext(this);

            if (context != null)
            {
                foreach (ServiceElement service in this.Services)
                {
                    BehaviorsSection.ValidateServiceBehaviorReference(service.BehaviorConfiguration, context, service);

                    foreach (ServiceEndpointElement endpoint in service.Endpoints)
                    {
                        if (string.IsNullOrEmpty(endpoint.Kind))
                        {
                            if (!string.IsNullOrEmpty(endpoint.EndpointConfiguration))
                            {
                                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ConfigurationErrorsException(SR.GetString(SR.ConfigInvalidAttribute, "endpointConfiguration", "endpoint", "kind")));
                            }
                            if (string.IsNullOrEmpty(endpoint.Binding))
                            {
                                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ConfigurationErrorsException(SR.GetString(SR.RequiredAttributeMissing, "binding", "endpoint")));
                            }
                        }
                        if (string.IsNullOrEmpty(endpoint.Binding) && !string.IsNullOrEmpty(endpoint.BindingConfiguration))
                        {
                            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ConfigurationErrorsException(SR.GetString(SR.ConfigInvalidAttribute, "bindingConfiguration", "endpoint", "binding")));
                        }
                        BehaviorsSection.ValidateEndpointBehaviorReference(endpoint.BehaviorConfiguration, context, endpoint);
                        BindingsSection.ValidateBindingReference(endpoint.Binding, endpoint.BindingConfiguration, context, endpoint);
                        StandardEndpointsSection.ValidateEndpointReference(endpoint.Kind, endpoint.EndpointConfiguration, context, endpoint);
                    }
                }
            }
        }
示例#9
0
		/// <summary>
		/// Performs a Formatting phase.
		/// </summary>
		/// <param name="raw">The raw content to Format.</param>
		/// <param name="context">The Context information.</param>
		/// <param name="phase">The Phase.</param>
		/// <returns>The Formatted content.</returns>
		public string Format(string raw, ContextInformation context, FormattingPhase phase) {
			// Match all <ref>*</ref>
			MatchCollection mc = RefRegex.Matches(raw);

			// No ref-tag found, nothing to do
			if(mc.Count == 0)
			{
				return raw;
			}

			// No references tag
			if(ReferencesRegex.Matches(raw).Count == 0) {
				return raw + "<br/><span style=\"color: #FF0000;\">Reference Error! Missing element &lt;references/&gt;</span>";
			}

			string output = raw;
			string ref_string = "<table class=\"footnotes\">";

			int footnoteCounter = 0;

			// For each <ref>...</ref> replace it with Footnote, append it to ref-section
			foreach(Match m in mc) {
				footnoteCounter++;
				output = ReplaceFirst(output, m.Value, "<a id=\"refnote" + footnoteCounter.ToString() + "\" href=\"#footnote" + footnoteCounter.ToString() + "\"><sup>" + footnoteCounter.ToString() + "</sup></a>");

				ref_string += "<tr><td><a id=\"footnote" + footnoteCounter.ToString() + "\" href=\"#refnote" + footnoteCounter.ToString() + "\"><sup>" + footnoteCounter.ToString() + "</sup></a></td><td>" + RefRemovalRegex.Replace(m.Value, "") + "</td></tr>";
			}
			ref_string += "</table>";

			// Replace <reference/> with ref-section
			output = ReferencesRegex.Replace(output, ref_string);

			return output;
		}
 public static extern Result GetContextInformation(
     [In] IntPtr context,
     [In][MarshalAs(UnmanagedType.U4)] ContextInformation parameterName,
     [In] UIntPtr parameterValueSize,
     [Out] byte[] parameterValue,
     [Out] out UIntPtr parameterValueSizeReturned
     );
示例#11
0
        /// <inheritdoc />
        public override Task RunAsync(ContextInformation context)
        {
            if (context.CheckMerkleRoot)
            {
                Block block = context.BlockValidationContext.Block;

                uint256 hashMerkleRoot2 = BlockMerkleRootRule.BlockMerkleRoot(block, out bool mutated);
                if (block.Header.HashMerkleRoot != hashMerkleRoot2)
                {
                    this.Logger.LogTrace("(-)[BAD_MERKLE_ROOT]");
                    ConsensusErrors.BadMerkleRoot.Throw();
                }

                // Check for merkle tree malleability (CVE-2012-2459): repeating sequences
                // of transactions in a block without affecting the merkle root of a block,
                // while still invalidating it.
                if (mutated)
                {
                    this.Logger.LogTrace("(-)[BAD_TX_DUP]");
                    ConsensusErrors.BadTransactionDuplicate.Throw();
                }
            }

            return(Task.CompletedTask);
        }
        public void CanCheckBlockWithWitness()
        {
            var block = new Block(Encoders.Hex.DecodeData("000000202f6f6a130549473222411b5c6f54150d63b32aadf10e57f7d563cfc7010000001e28204471ef9ef11acd73543894a96a3044932b85e99889e731322a8ec28a9f9ae9fc56ffff011d0011b40202010000000001010000000000000000000000000000000000000000000000000000000000000000ffffffff2c028027266a24aa21a9ed09154465f26a2a4144739eba3e83b3e9ae6a1f69566eae7dc3747d48f1183779010effffffff0250b5062a0100000023210263ed47e995cbbf1bc560101e3b76c6bdb1b094a185450cea533781ce598ff2b6ac0000000000000000266a24aa21a9ed09154465f26a2a4144739eba3e83b3e9ae6a1f69566eae7dc3747d48f1183779012000000000000000000000000000000000000000000000000000000000000000000000000001000000000101cecd90cd38ac6858c47f2fe9f28145d6e18f9c5abc7ef1a41e2f19e6fe0362580100000000ffffffff0130b48d06000000001976a91405481b7f1d90c5a167a15b00e8af76eb6984ea5988ac0247304402206104c335e4adbb920184957f9f710b09de17d015329fde6807b9d321fd2142db02200b24ad996b4aa4ff103000348b5ad690abfd9fddae546af9e568394ed4a83113012103a65786c1a48d4167aca08cf6eb8eed081e13f45c02dc6000fd8f3bb16242579a00000000"));

            var consensusFlags = new ConsensusFlags()
            {
                ScriptFlags   = ScriptVerify.Witness | ScriptVerify.P2SH | ScriptVerify.Standard,
                LockTimeFlags = LockTimeFlags.MedianTimePast,
                EnforceBIP34  = true
            };

            var context = new ContextInformation()
            {
                BestBlock = new ContextBlockInformation()
                {
                    MedianTimePast = DateTimeOffset.Parse("2016-03-31T09:02:19+00:00", CultureInfo.InvariantCulture),
                    Height         = 10111
                },
                NextWorkRequired = block.Header.Bits,
                Time             = DateTimeOffset.UtcNow,
                BlockResult      = new BlockResult {
                    Block = block
                },
                Flags = consensusFlags,
            };

            Network.Main.Consensus.Options = new PowConsensusOptions();
            var validator = new PowConsensusValidator(Network.Main);

            //validator.CheckBlockHeader(context);
            validator.ContextualCheckBlock(context);
            validator.CheckBlock(context);
        }
示例#13
0
        string IFormatterProviderV30.Format(string raw, ContextInformation context, FormattingPhase phase)
        {
            var buffer            = new StringBuilder(raw);
            var anyDiagramsOnPage = false;

            try
            {
                if (context.Page != null)
                {
                    anyDiagramsOnPage = ReplaceTags(context, buffer, context.Page.FullName);
                }
                else
                {
                    return(raw);
                }
            }
            catch (Exception ex)
            {
                LogWarning(string.Format("Exception occurred: {0}", ex.StackTrace));
            }
            if (anyDiagramsOnPage)
            {
                InjectStyleAndScript(buffer);
            }
            return(buffer.ToString());
        }
示例#14
0
        /// <summary>
        /// Performs the Phase 3 of the formatting process.
        /// </summary>
        /// <param name="raw">The raw WikiMarkup to format.</param>
        /// <param name="context">The formatting context.</param>
        /// <param name="current">The current Page, if any.</param>
        /// <returns>The formatted content.</returns>
        public static string FormatWithPhase3(string raw, FormattingContext context, PageInfo current)
        {
            raw = Formatter.FormatPhase3(raw, context, current);

            ContextInformation info = null;
            var username            = SessionFacade.CurrentUsername;

            info = new ContextInformation(false, false, context, current, System.Threading.Thread.CurrentThread.CurrentCulture.Name, HttpContext.Current,
                                          username, SessionFacade.GetCurrentGroupNames());

            // Phase 3
            foreach (IFormatterProviderV30 provider in GetSortedFormatters())
            {
                if (provider.PerformPhase3)
                {
                    try
                    {
                        raw = provider.Format(raw, info, FormattingPhase.Phase3);
                    }
                    catch (Exception ex)
                    {
                        if (!(ex is ThreadAbortException))
                        { // Consider Response.End()
                            Log.LogEntry("Provider " + provider.Information.Name + " failed to perform Phase3 (silently resuming from next provider): " + ex.ToString(), EntryType.Error, Log.SystemUsername);
                        }
                    }
                }
            }

            return(raw);
        }
示例#15
0
        /// <summary>
        /// Performs a Formatting phase.
        /// </summary>
        /// <param name="raw">The raw content to Format.</param>
        /// <param name="context">The Context information.</param>
        /// <param name="phase">The Phase.</param>
        /// <returns>The Formatted content.</returns>
        public string Format(string raw, ContextInformation context, FormattingPhase phase)
        {
            var buffer = new StringBuilder(raw);

            var block = FindAndRemoveFirstOccurrence(buffer);

            if (block.Key != -1)
            {
                string unfuddleTickets = null;
                if (HttpContext.Current != null)
                {
                    unfuddleTickets = HttpContext.Current.Cache["UnfuddleTicketsStore"] as string;
                }

                if (string.IsNullOrEmpty(unfuddleTickets))
                {
                    unfuddleTickets = LoadUnfuddleTicketsFromWeb();
                }

                if (string.IsNullOrEmpty(unfuddleTickets))
                {
                    unfuddleTickets = LoadErrorMessage;
                }

                do
                {
                    buffer.Insert(block.Key, unfuddleTickets);
                    block = FindAndRemoveFirstOccurrence(buffer);
                } while(block.Key != -1);
            }

            return(buffer.ToString());
        }
示例#16
0
        private void ValidateSection()
        {
            ContextInformation evaluationContext = ConfigurationHelpers.GetEvaluationContext(this);

            if (evaluationContext != null)
            {
                foreach (ChannelEndpointElement element in this.Endpoints)
                {
                    if (string.IsNullOrEmpty(element.Kind))
                    {
                        if (!string.IsNullOrEmpty(element.EndpointConfiguration))
                        {
                            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ConfigurationErrorsException(System.ServiceModel.SR.GetString("ConfigInvalidAttribute", new object[] { "endpointConfiguration", "endpoint", "kind" })));
                        }
                        if (string.IsNullOrEmpty(element.Binding))
                        {
                            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ConfigurationErrorsException(System.ServiceModel.SR.GetString("RequiredAttributeMissing", new object[] { "binding", "endpoint" })));
                        }
                        if (string.IsNullOrEmpty(element.Contract))
                        {
                            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ConfigurationErrorsException(System.ServiceModel.SR.GetString("RequiredAttributeMissing", new object[] { "contract", "endpoint" })));
                        }
                    }
                    if (string.IsNullOrEmpty(element.Binding) && !string.IsNullOrEmpty(element.BindingConfiguration))
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ConfigurationErrorsException(System.ServiceModel.SR.GetString("ConfigInvalidAttribute", new object[] { "bindingConfiguration", "endpoint", "binding" })));
                    }
                    BehaviorsSection.ValidateEndpointBehaviorReference(element.BehaviorConfiguration, evaluationContext, element);
                    BindingsSection.ValidateBindingReference(element.Binding, element.BindingConfiguration, evaluationContext, element);
                    StandardEndpointsSection.ValidateEndpointReference(element.Kind, element.EndpointConfiguration, evaluationContext, element);
                }
            }
        }
示例#17
0
    protected override async Task InitializeCoreAsync(TestContext context)
    {
        BrowserManager = await BrowserManager.CreateAsync(_config, LoggerFactory);

        BrowserContextInfo = new ContextInformation(LoggerFactory);
        _output            = new BrowserTestOutputLogger(Logger);
    }
示例#18
0
        /// <summary>
        /// Performs a Formatting phase.
        /// </summary>
        /// <param name="raw">The raw content to Format.</param>
        /// <param name="context">The Context information.</param>
        /// <param name="phase">The Phase.</param>
        /// <returns>The Formatted content.</returns>
        public string Format(string raw, ContextInformation context, FormattingPhase phase)
        {
            string result         = ExtractLocalizedContent(context.Language, raw);     // Try to load localized content
            bool   notLocalized   = false;
            bool   noLocalization = false;

            if (result == null)
            {
                result         = ExtractLocalizedContent(defaultLanguage, raw);         // Load content in the default language
                notLocalized   = true;
                noLocalization = false;
            }
            if (result == null)
            {
                result         = raw;         // The Page is not localized, return all the content
                notLocalized   = false;
                noLocalization = true;
            }
            if (displayWarning && !noLocalization && context.Page != null)
            {
                if (notLocalized)
                {
                    return(NotLocalizedMessage + result);
                }
                else
                {
                    return(StandardMessage + result);
                }
            }
            else
            {
                return(result);
            }
        }
示例#19
0
        /// <inheritdoc />
        public override Task RunAsync(ContextInformation context)
        {
            var options = context.Consensus.Option <PowConsensusOptions>();

            // After the coinbase witness nonce and commitment are verified,
            // we can check if the block weight passes (before we've checked the
            // coinbase witness, it would be possible for the weight to be too
            // large by filling up the coinbase witness, which doesn't change
            // the block hash, so we couldn't mark the block as permanently
            // failed).
            if (GetBlockWeight(context.BlockValidationContext.Block, options) > options.MaxBlockWeight)
            {
                this.Logger.LogTrace("(-)[BAD_BLOCK_WEIGHT]");
                ConsensusErrors.BadBlockWeight.Throw();
            }

            Block block = context.BlockValidationContext.Block;

            // Size limits.
            if ((block.Transactions.Count == 0) || (block.Transactions.Count > options.MaxBlockBaseSize) || (GetSize(block, NetworkOptions.None) > options.MaxBlockBaseSize))
            {
                this.Logger.LogTrace("(-)[BAD_BLOCK_LEN]");
                ConsensusErrors.BadBlockLength.Throw();
            }

            return(Task.CompletedTask);
        }
示例#20
0
        protected override void DeserializeElement(XmlReader reader, bool serializeCollectionKey)
        {
            PartialTrustHelpers.FailIfInPartialTrustOutsideAspNet();

            base.DeserializeElement(reader, serializeCollectionKey);


            // Update paths
            // If we're not running in the context of a web application then skip this setting.
#if MONO_BROKEN_CONFIGURATION_DLL
            try {
                var hack = this.EvaluationContext;
            } catch (ConfigurationErrorsException) {
                this.actualPath = GetConfigurationDirectory();
                return;
            }
#endif
            ContextInformation context    = this.EvaluationContext;
            WebContext         webContext = context.HostingContext as WebContext;
            if (webContext == null)
            {
                return;
            }

            if (this.Href.Length == 0)
            {
                return;
            }

            string tempVirtualPath = webContext.Path;
            string path            = null;

            // If the help page is not in the web app directory hierarchy (the case
            // for those specified in machine.config like DefaultWsdlHelpGenerator.aspx)
            // then we can't construct a true virtual path. This means that certain web
            // form features that rely on relative paths won't work.

            if (tempVirtualPath == null)
            {
                tempVirtualPath = HostingEnvironment.ApplicationVirtualPath;
                if (tempVirtualPath == null)
                {
                    tempVirtualPath = "";
                }
                path = GetConfigurationDirectory();
            }
            else
            {
                path = HostingEnvironment.MapPath(tempVirtualPath);
            }
            if (!tempVirtualPath.EndsWith("/", StringComparison.Ordinal))
            {
                tempVirtualPath += "/";
            }
            CheckIOReadPermission(path, this.Href);
            this.actualPath         = path;
            this.virtualPath        = tempVirtualPath;
            this.needToValidateHref = true;
        }
示例#21
0
        public string Format(string raw, ContextInformation context, FormattingPhase phase)
        {
            var requestedPage = GetRequestedPage(context);

            Log(String.Format("Rendering tab menu, requested page is {0}", requestedPage));

            return(new Formatter(this).FormatMenu(raw, requestedPage));
        }
        internal bool CanAdd(string extensionCollectionName, ContextInformation evaluationContext)
        {
            bool retVal = false;

            ExtensionElementCollection collection = ExtensionsSection.UnsafeLookupCollection(extensionCollectionName, evaluationContext);

            if (null != collection && collection.Count != 0)
            {
                string thisAssemblyQualifiedName = ThisType.AssemblyQualifiedName;
                string thisTypeName = ExtensionElement.GetTypeName(thisAssemblyQualifiedName);
                foreach (ExtensionElement extensionElement in collection)
                {
                    string extensionTypeName = extensionElement.Type;
                    if (extensionTypeName.Equals(thisAssemblyQualifiedName, StringComparison.Ordinal))
                    {
                        retVal = true;
                        break;
                    }

                    if (extensionElement.TypeName.Equals(thisTypeName, StringComparison.Ordinal))
                    {
                        Type extensionType = Type.GetType(extensionTypeName, false);
                        if (extensionType != null && extensionType.Equals(ThisType))
                        {
                            retVal = true;
                            break;
                        }
                    }
                }

                if (!retVal && DiagnosticUtility.ShouldTraceWarning)
                {
                    TraceUtility.TraceEvent(TraceEventType.Warning,
                                            TraceCode.ConfiguredExtensionTypeNotFound,
                                            SR.GetString(SR.TraceCodeConfiguredExtensionTypeNotFound),
                                            this.CreateCanAddRecord(extensionCollectionName), this, null);
                }
            }
            else if (DiagnosticUtility.ShouldTraceWarning)
            {
                int    traceCode;
                string traceDescription;
                if (collection != null && collection.Count == 0)
                {
                    traceCode        = TraceCode.ExtensionCollectionIsEmpty;
                    traceDescription = SR.GetString(SR.TraceCodeExtensionCollectionIsEmpty);
                }
                else
                {
                    traceCode        = TraceCode.ExtensionCollectionDoesNotExist;
                    traceDescription = SR.GetString(SR.TraceCodeExtensionCollectionDoesNotExist);
                }
                TraceUtility.TraceEvent(TraceEventType.Warning,
                                        traceCode, traceDescription, this.CreateCanAddRecord(extensionCollectionName), this, null);
            }

            return(retVal);
        }
示例#23
0
        internal void Validate()
        {
            ContextInformation evaluationContext = ConfigurationHelpers.GetEvaluationContext(this);

            if ((evaluationContext != null) && !string.IsNullOrEmpty(this.Binding))
            {
                BindingsSection.ValidateBindingReference(this.Binding, this.BindingConfiguration, evaluationContext, this);
            }
        }
示例#24
0
        string GetRequestedPage(ContextInformation context)
        {
            var defaultPage = _host.GetSettingValue(SettingName.RootNamespaceDefaultPage);

            if (context.Page == null)
            {
                return(defaultPage);
            }

            return(context.Page.FullName ?? defaultPage);
        }
示例#25
0
        /// <inheritdoc />
        public override Task RunAsync(ContextInformation context)
        {
            DeploymentFlags deploymentFlags = context.Flags;

            if (deploymentFlags.EnforceBIP34)
            {
                return(base.RunAsync(context));
            }

            return(Task.CompletedTask);
        }
示例#26
0
        /// <summary>
        /// Performs the Phases 1 and 2 of the formatting process for Wysiwyg.
        /// </summary>
        /// <param name="wiki">The wiki.</param>
        /// <param name="raw">The raw WikiMarkup to format.</param>
        /// <param name="context">The formatting context.</param>
        /// <returns>The formatted content.</returns>
        public static string FormatForWysiwygWithPhase1And2(string wiki, string raw, FormattingContext context)
        {
            string[]           linkedPages;
            ContextInformation info     = null;
            string             username = SessionFacade.CurrentUsername;

            info = new ContextInformation(false, true, context, null, System.Threading.Thread.CurrentThread.CurrentCulture.Name, HttpContext.Current,
                                          username, SessionFacade.GetCurrentGroupNames(wiki));

            IList <IFormatterProviderV50> providers = GetSortedFormatters(wiki);

            // Phase 1
            foreach (IFormatterProviderV50 provider in providers)
            {
                if (provider.EnablePluginsEditor && provider.PerformPhase1)
                {
                    try
                    {
                        raw = provider.WysiwygFormat(raw, info, FormattingPhase.Phase1);
                    }
                    catch (Exception ex)
                    {
                        if (!(ex is ThreadAbortException))
                        { // Consider Response.End()
                            Log.LogEntry("Provider " + provider.Information.Name + " failed to perform Phase1 for Wysiwyg (silently resuming from next provider): " + ex.ToString(), EntryType.Error, Log.SystemUsername, provider.CurrentWiki);
                        }
                    }
                }
            }

            raw = Formatter.Format(wiki, raw, false, context, null, out linkedPages, true);

            // Phase 2
            foreach (IFormatterProviderV50 provider in providers)
            {
                if (provider.EnablePluginsEditor)
                {
                    try
                    {
                        raw = provider.WysiwygFormat(raw, info, FormattingPhase.Phase2);
                    }
                    catch (Exception ex)
                    {
                        if (!(ex is ThreadAbortException))
                        { // Consider Response.End()
                            Log.LogEntry("Provider " + provider.Information.Name + " failed to perform Phase2 for Wysiwyg (silently resuming from next provider): " + ex.ToString(), EntryType.Error, Log.SystemUsername, provider.CurrentWiki);
                        }
                    }
                }
            }

            return(raw);
        }
示例#27
0
        /// <summary>
        /// Performs the Phases 1 and 2 of the formatting process.
        /// </summary>
        /// <param name="raw">The raw WikiMarkup to format.</param>
        /// <param name="forIndexing">A value indicating whether the formatting is being done for content indexing.</param>
        /// <param name="context">The formatting context.</param>
        /// <param name="current">The current Page, if any.</param>
        /// <param name="linkedPages">The Pages linked by the current Page.</param>
        /// <returns>The formatted content.</returns>
        public static string FormatWithPhase1And2(string raw, bool forIndexing, FormattingContext context, PageInfo current, out string[] linkedPages)
        {
            ContextInformation info     = null;
            string             username = SessionFacade.CurrentUsername;

            info = new ContextInformation(forIndexing, false, context, current, System.Threading.Thread.CurrentThread.CurrentCulture.Name, HttpContext.Current,
                                          username, SessionFacade.GetCurrentGroupNames( ));

            IList <IFormatterProviderV30> providers = GetSortedFormatters( );

            // Phase 1
            foreach (IFormatterProviderV30 provider in providers)
            {
                if (provider.PerformPhase1)
                {
                    try
                    {
                        raw = provider.Format(raw, info, FormattingPhase.Phase1);
                    }
                    catch (Exception ex)
                    {
                        if (!(ex is ThreadAbortException))
                        {                         // Consider Response.End()
                            Log.LogEntry("Provider " + provider.Information.Name + " failed to perform Phase1 (silently resuming from next provider): " + ex, EntryType.Error, Log.SystemUsername);
                        }
                    }
                }
            }

            raw = Formatter.Format(raw, forIndexing, context, current, out linkedPages);

            // Phase 2
            foreach (IFormatterProviderV30 provider in providers)
            {
                if (provider.PerformPhase2)
                {
                    try
                    {
                        raw = provider.Format(raw, info, FormattingPhase.Phase2);
                    }
                    catch (Exception ex)
                    {
                        if (!(ex is ThreadAbortException))
                        {                         // Consider Response.End()
                            Log.LogEntry("Provider " + provider.Information.Name + " failed to perform Phase2 (silently resuming from next provider): " + ex, EntryType.Error, Log.SystemUsername);
                        }
                    }
                }
            }

            return(raw);
        }
        private string GetConfigurationElementName()
        {
            string name = string.Empty;
            ExtensionElementCollection elements = null;
            Type thisType = this.ThisType;
            ContextInformation containingEvaluationContext = this.ContainingEvaluationContext;

            if (containingEvaluationContext == null)
            {
                containingEvaluationContext = ConfigurationHelpers.GetEvaluationContext(this);
            }
            if (string.IsNullOrEmpty(this.extensionCollectionName))
            {
                if (DiagnosticUtility.ShouldTraceWarning)
                {
                    TraceUtility.TraceEvent(TraceEventType.Warning, 0x8001b, System.ServiceModel.SR.GetString("TraceCodeExtensionCollectionNameNotFound"), this, (Exception)null);
                }
                elements = ExtensionsSection.UnsafeLookupAssociatedCollection(this.ThisType, containingEvaluationContext, out this.extensionCollectionName);
            }
            else
            {
                elements = ExtensionsSection.UnsafeLookupCollection(this.extensionCollectionName, containingEvaluationContext);
            }
            if (elements == null)
            {
                if (string.IsNullOrEmpty(this.extensionCollectionName))
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ConfigurationErrorsException(System.ServiceModel.SR.GetString("ConfigNoExtensionCollectionAssociatedWithType", new object[] { thisType.AssemblyQualifiedName }), base.ElementInformation.Source, base.ElementInformation.LineNumber));
                }
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ConfigurationErrorsException(System.ServiceModel.SR.GetString("ConfigExtensionCollectionNotFound", new object[] { this.extensionCollectionName }), base.ElementInformation.Source, base.ElementInformation.LineNumber));
            }
            for (int i = 0; i < elements.Count; i++)
            {
                ExtensionElement element = elements[i];
                if (element.Type.Equals(thisType.AssemblyQualifiedName, StringComparison.Ordinal))
                {
                    name = element.Name;
                    break;
                }
                Type type = Type.GetType(element.Type, false);
                if ((null != type) && thisType.Equals(type))
                {
                    name = element.Name;
                    break;
                }
            }
            if (string.IsNullOrEmpty(name))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ConfigurationErrorsException(System.ServiceModel.SR.GetString("ConfigExtensionTypeNotRegisteredInCollection", new object[] { thisType.AssemblyQualifiedName, this.extensionCollectionName }), base.ElementInformation.Source, base.ElementInformation.LineNumber));
            }
            return(name);
        }
示例#29
0
        /// <summary>
        /// Performs a Formatting phase.
        /// </summary>
        /// <param name="raw">The raw content to Format.</param>
        /// <param name="context">The Context information.</param>
        /// <param name="phase">The Phase.</param>
        /// <returns>The Formatted content.</returns>
        public string Format(string raw, ContextInformation context, FormattingPhase phase)
        {
            // {rating}
            // _backendpage not found -> ignored

            StringBuilder buffer = new StringBuilder(raw);

            try {
                if (context.Context == FormattingContext.PageContent && context.Page != null)
                {
                    if (context.HttpContext.Request["vote"] != null)
                    {
                        AddRating(context.Page.FullName, int.Parse(context.HttpContext.Request["vote"]));
                        System.Web.HttpCookie cookie = new System.Web.HttpCookie("RatingManagerPlugin_" + context.Page.FullName, context.HttpContext.Request["vote"]);
                        cookie.Expires = DateTime.Now.AddYears(10);
                        context.HttpContext.Response.Cookies.Add(cookie);
                        return("");
                    }
                }
                if (context.Page != null)
                {
                    ComputeRating(context, buffer, context.Page.FullName);
                }
                else
                {
                    return(raw);
                }
            }
            catch (Exception ex) {
                LogWarning(string.Format("Exception occurred: {0}", ex.StackTrace));
            }
            if (foundRatings)
            {
                buffer.Append(@"<script type=""text/javascript"" src=""GetFile.aspx?file=" + defaultDirectoryName + jsFileName + @"""></script>");
                buffer.Append(@"<link rel=""StyleSheet"" href=""GetFile.aspx?file=" + defaultDirectoryName + cssFileName + @""" type=""text/css"" />");
                buffer.Append(@"<script type=""text/javascript""> <!--
function GenerateStaticStars(rate, cssClass) {
var string = '';
var i = 0;
for (i=0; i<rate; i++) {
string +='<span class=""static-rating ' + cssClass + '""></span>';
}
for(i=rate; i<5; i++) {
string +='<span class=""static-rating ui-rating-empty""></span>';
}
return string;
}
//--> </script>");
                foundRatings = false;
            }
            return(buffer.ToString());
        }
示例#30
0
    // Show how to use the Configuration object properties
    // to obtain configuration file information.
    static void GetConfigurationInformation()
    {
        try
        {
            // Get the current configuration file.
            System.Configuration.Configuration config =
                ConfigurationManager.OpenExeConfiguration(
                    ConfigurationUserLevel.None) as Configuration;

            Console.WriteLine("Reading configuration information:");

            //<Snippet7>
            ContextInformation evalContext =
                config.EvaluationContext as ContextInformation;
            Console.WriteLine("Machine level: {0}",
                              evalContext.IsMachineLevel.ToString());
            //</Snippet7>

            //<Snippet8>
            string filePath = config.FilePath;
            Console.WriteLine("File path: {0}", filePath);
            //</Snippet8>

            //<Snippet9>
            bool hasFile = config.HasFile;
            Console.WriteLine("Has file: {0}", hasFile.ToString());
            //</Snippet9>


            //<Snippet10>
            ConfigurationSectionGroupCollection
                groups = config.SectionGroups;
            Console.WriteLine("Groups: {0}", groups.Count.ToString());
            foreach (ConfigurationSectionGroup group in groups)
            {
                Console.WriteLine("Group Name: {0}", group.Name);
                // Console.WriteLine("Group Type: {0}", group.Type);
            }
            //</Snippet10>


            //<Snippet11>
            ConfigurationSectionCollection
                sections = config.Sections;
            Console.WriteLine("Sections: {0}", sections.Count.ToString());
            //</Snippet11>
        }
        catch (ConfigurationErrorsException err)
        {
            Console.WriteLine("GetConfigurationInformation: {0}", err.ToString());
        }
    }