コード例 #1
0
 private void VerifyResultExists(RewriteContext context)
 {
     if ((String.Compare(context.Location, ContextFacade.GetRawUrl()) != 0) && ((int)context.StatusCode < 300))
     {
         Uri uri = new Uri(ContextFacade.GetRequestUrl(), context.Location);
         if (uri.Host == ContextFacade.GetRequestUrl().Host)
         {
             string filename = ContextFacade.MapPath(uri.AbsolutePath);
             if (!File.Exists(filename))
             {
                 _configuration.Logger.Debug(MessageProvider.FormatString(Message.ResultNotFound, filename));
                 context.StatusCode = HttpStatusCode.NotFound;
             }
             else
             {
                 HandleDefaultDocument(context);
             }
         }
     }
 }
コード例 #2
0
        private static void ReadRegisterTransform(XmlNode node, IRewriterConfiguration config)
        {
            if (node.ChildNodes.Count > 0)
            {
                throw new ConfigurationErrorsException(MessageProvider.FormatString(Message.ElementNoElements, Constants.ElementRegister), node);
            }

            string type = node.GetRequiredAttribute(Constants.AttrTransform);

            // Transform type specified.
            // Create an instance and add it as the mapper handler for this map.
            IRewriteTransform transform = TypeHelper.Activate(type, null) as IRewriteTransform;

            if (transform == null)
            {
                throw new ConfigurationErrorsException(MessageProvider.FormatString(Message.InvalidTypeSpecified, type, typeof(IRewriteTransform)), node);
            }

            config.TransformFactory.Add(transform);
        }
コード例 #3
0
ファイル: RewriterEngine.cs プロジェクト: jre08/YAFNET
        private void ProcessRules(IRewriteContext context, IList <IRewriteAction> rewriteRules, int restarts)
        {
            foreach (var action in rewriteRules)
            {
                // If the rule is conditional, ensure the conditions are met.
                var condition = action as IRewriteCondition;
                if (condition == null || condition.IsMatch(context))
                {
                    // Execute the action.
                    var processing = action.Execute(context);

                    // If the action is Stop, then break out of the processing loop
                    if (processing == RewriteProcessing.StopProcessing)
                    {
                        this._configuration.Logger.Debug(MessageProvider.FormatString(Message.StoppingBecauseOfRule));

                        // Exit the loop.
                        break;
                    }

                    // If the action is Restart, then start again.
                    if (processing == RewriteProcessing.RestartProcessing)
                    {
                        this._configuration.Logger.Debug(MessageProvider.FormatString(Message.RestartingBecauseOfRule));

                        // Increment the number of restarts and check that we have not exceeded our max.
                        restarts++;
                        if (restarts > MaxRestarts)
                        {
                            throw new InvalidOperationException(MessageProvider.FormatString(Message.TooManyRestarts));
                        }

                        // Restart again from the first rule by calling this method recursively.
                        this.ProcessRules(context, rewriteRules, restarts);

                        // Exit the loop.
                        break;
                    }
                }
            }
        }
コード例 #4
0
        private static void ReadRule(XmlNode node, RewriterConfiguration config)
        {
            var parsed  = false;
            var parsers = config.ActionParserFactory.GetParsers(node.LocalName);

            if (parsers != null)
            {
                foreach (IRewriteActionParser parser in parsers)
                {
                    if (!parser.AllowsNestedActions && node.ChildNodes.Count > 0)
                    {
                        throw new ConfigurationErrorsException(
                                  MessageProvider.FormatString(Message.ElementNoElements, parser.Name),
                                  node);
                    }

                    if (!parser.AllowsAttributes && node.Attributes.Count > 0)
                    {
                        throw new ConfigurationErrorsException(
                                  MessageProvider.FormatString(Message.ElementNoAttributes, parser.Name),
                                  node);
                    }

                    var rule = parser.Parse(node, config);
                    if (rule != null)
                    {
                        config.Rules.Add(rule);
                        parsed = true;
                        break;
                    }
                }
            }

            if (!parsed)
            {
                // No parsers recognised to handle this node.
                throw new ConfigurationErrorsException(
                          MessageProvider.FormatString(Message.ElementNotAllowed, node.LocalName),
                          node);
            }
        }
コード例 #5
0
        private bool EndGame()
        {
            MessageProvider.Separator();
            MessageProvider.EndGame();
            var answer = Console.ReadKey();

            MessageProvider.Separator();

            if ("yY".Contains(answer.KeyChar))
            {
                return(true);
            }
            else if ("nN".Contains(answer.KeyChar))
            {
                return(false);
            }
            else
            {
                return(EndGame());
            }
        }
コード例 #6
0
        public static List <MessageTarget> Disconnect(this MessageProvider user)
        {
            user.IsActive = false;

            return(new List <MessageTarget>
            {
                new MessageTarget
                {
                    Targets = new List <MessageProvider> {
                        user
                    },
                    Message = "Successfully disconnected"
                },
                new MessageTarget
                {
                    Targets = Users.GetAllUsersExceptOne(user),
                    //Targets = Users.Where(x => x.Id != user.Id).ToList(),
                    Message = $"{user.Name} disconnected"
                }
            });
        }
コード例 #7
0
        /// <summary>
        /// Gets a required attribute from an XML node.
        /// Throws an error if the required attribute is missing.
        /// Throws an error if the required attribute is empty (blank) and allowBlank is set to false.
        /// or empty (blank).
        /// </summary>
        /// <param name="node">The XML node</param>
        /// <param name="attributeName">The XML attribute name</param>
        /// <param name="allowBlank">Blank (empty) values okay?</param>
        /// <returns>The attribute value</returns>
        public static string GetRequiredAttribute(this XmlNode node, string attributeName, bool allowBlank)
        {
            if (node == null)
            {
                throw new ArgumentNullException("node");
            }

            XmlNode attribute = node.Attributes.GetNamedItem(attributeName);

            if (attribute == null)
            {
                throw new ConfigurationErrorsException(MessageProvider.FormatString(Message.AttributeRequired, attributeName), node);
            }

            if (attribute.Value.Length == 0 && !allowBlank)
            {
                throw new ConfigurationErrorsException(MessageProvider.FormatString(Message.AttributeCannotBeBlank, attributeName), node);
            }

            return(attribute.Value);
        }
コード例 #8
0
ファイル: DiagnosticInfo.cs プロジェクト: BSData/phalanx
    protected object[] GetArgumentsToUse(IFormatProvider?formatProvider)
    {
        object[]? argumentsToUse = null;
        for (var i = 0; i < Arguments.Length; i++)
        {
            if (Arguments[i] is DiagnosticInfo embedded)
            {
                argumentsToUse    = InitializeArgumentListIfNeeded(argumentsToUse);
                argumentsToUse[i] = embedded.GetMessage(formatProvider);
                continue;
            }

            if (Arguments[i] is ISymbol symbol)
            {
                argumentsToUse    = InitializeArgumentListIfNeeded(argumentsToUse);
                argumentsToUse[i] = MessageProvider.GetErrorDisplayString(symbol);
            }
        }

        return(argumentsToUse ?? Arguments);
    }
コード例 #9
0
        private VirtualizingList <MessageModel> InvokeLoadMsg()
        {
            var watcher = new Stopwatch();

            watcher.Start();
            //邮件总数
            var count = DbOperator.GetMessageCount(_dbHelper);

            //获取邮件
            var mailProvider = new MessageProvider(count, 1000)
            {
                DbHelper = _dbHelper
            };

            var list = new VirtualizingList <MessageModel>(mailProvider, 100, 1000);

            watcher.Stop();
            TotalTime = watcher.ElapsedMilliseconds.ToString(CultureInfo.InvariantCulture);

            return(list);
        }
コード例 #10
0
        private static void ReadRegisterParser(XmlNode node, IRewriterConfiguration config)
        {
            if (node.ChildNodes.Count > 0)
            {
                throw new ConfigurationErrorsException(MessageProvider.FormatString(Message.ElementNoElements, Constants.ElementRegister), node);
            }

            var type = node.GetRequiredAttribute(Constants.AttrParser);

            var parser = TypeHelper.Activate(type, null);

            if (parser is IRewriteActionParser actionParser)
            {
                config.ActionParserFactory.Add(actionParser);
            }

            if (parser is IRewriteConditionParser conditionParser)
            {
                config.ConditionParserPipeline.Add(conditionParser);
            }
        }
コード例 #11
0
        /// <summary>
        /// Includes implicit, explicit project references
        /// listed in the Dependencies section of the lock
        /// file.
        /// </summary>
        ///
        /// <exception cref="SwitcherException"/>
        ///
        /// <remarks>
        /// Implicit dependencies mean transitive.
        /// </remarks>
        public virtual void SwitchPkgDependency(IProjectReference reference, LockFileTargetLibrary library, string absolutePath)
        {
            /*
             * References can be represented by several values in
             * an ItemGroup, for example, when included using the
             * Condition attribute.
             */

            ICollection <ProjectItem> items = reference.MsbProject.GetItemsByEvaluatedInclude(library.Name);

            // Implicit.
            if (!items.Any())
            {
                base.AddReference(reference, Type, absolutePath, new Dictionary <string, string>(2)
                {
                    { "Name", library.Name }
                });
            }
            // Explicit.
            else
            {
                /*
                 * Re-creating an item can lead to the loss
                 * of user metadata; in order to avoid this,
                 * the item is redefined.
                 */

                foreach (ProjectItem item in items)
                {
                    item.ItemType = Type.ToString();

                    item.SetMetadataValue("Temp", item.EvaluatedInclude);
                    item.SetMetadataValue("Name", item.EvaluatedInclude);

                    item.UnevaluatedInclude = absolutePath;
                }

                MessageProvider.AddMessage(reference.MsbProject.FullPath, $"Dependency: {library.Name } has been switched. Type: { Type }", MessageCategory.ME);
            }
        }
コード例 #12
0
        internal AssemblyData ResolveMissingAssembly(
            AssemblyIdentity referenceIdentity,
            PortableExecutableReference peReference,
            MetadataImportOptions importOptions,
            DiagnosticBag diagnostics)
        {
            var metadata = GetMetadata(peReference, MessageProvider, Location.None, diagnostics);

            Debug.Assert(metadata != null || diagnostics.HasAnyErrors());

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

            var assemblyMetadata = metadata as AssemblyMetadata;

            if (assemblyMetadata?.IsValidAssembly() != true)
            {
                diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_MetadataFileNotAssembly, Location.None, peReference.Display));
                return(null);
            }

            var assembly = assemblyMetadata.GetAssembly();

            // Allow reference and definition identities to differ in version, but not other properties:
            if (IdentityComparer.Compare(referenceIdentity, assembly.Identity) == AssemblyIdentityComparer.ComparisonResult.NotEquivalent)
            {
                return(null);
            }

            return(CreateAssemblyDataForFile(
                       assembly,
                       assemblyMetadata.CachedSymbols,
                       peReference.DocumentationProvider,
                       SimpleAssemblyName,
                       importOptions,
                       peReference.Properties.EmbedInteropTypes));
        }
コード例 #13
0
        private static void ReadErrorHandler(XmlNode node, RewriterConfiguration config)
        {
            XmlNode codeNode = node.Attributes[Constants.AttrCode];

            if (codeNode == null)
            {
                throw new ConfigurationErrorsException(
                          MessageProvider.FormatString(Message.AttributeRequired, Constants.AttrCode),
                          node);
            }

            XmlNode typeNode = node.Attributes[Constants.AttrType];
            XmlNode urlNode  = node.Attributes[Constants.AttrUrl];

            if (typeNode == null && urlNode == null)
            {
                throw new ConfigurationErrorsException(
                          MessageProvider.FormatString(Message.AttributeRequired, Constants.AttrUrl),
                          node);
            }

            IRewriteErrorHandler handler = null;

            if (typeNode != null)
            {
                // <error-handler code="500" url="/oops.aspx" />
                handler = TypeHelper.Activate(typeNode.Value, null) as IRewriteErrorHandler;
                if (handler == null)
                {
                    throw new ConfigurationErrorsException(MessageProvider.FormatString(Message.InvalidTypeSpecified));
                }
            }
            else
            {
                handler = new DefaultErrorHandler(urlNode.Value);
            }

            config.ErrorHandlers.Add(Convert.ToInt32(codeNode.Value), handler);
        }
コード例 #14
0
    protected void SubmitButton_Click(object sender, EventArgs e)
    {
        Guid?         toUserId = null;
        StringBuilder sb       = new StringBuilder();

        foreach (ListItem item in UserList.Items)
        {
            if (item.Selected)
            {
                if (!toUserId.HasValue)
                {
                    toUserId = new Guid(item.Value);
                }
                else
                {
                    sb.AppendFormat(", {0}", item.Text);
                }
            }
        }

        UserList.ClearSelection();

        if (sb.Length > 0)
        {
            sb.Remove(0, 2);
            sb.Insert(0, "This message additionally were sent to:<br />");
            if (!string.IsNullOrEmpty(MessageTextBox.Text))
            {
                sb.Insert(0, "<br /><br />--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------<br />");
            }
        }
        sb.Insert(0, MessageTextBox.Text);

        MessageProvider.InsertMessage(MessageList1.ParentMessageId, MessageList1.LocalObjectType, MessageList1.LocalObjectId, UserContext.Current.UserId, toUserId, "Tkt Response", sb.ToString());

        MessageList1.DataBind();

        MessageTextBox.Text = string.Empty;
    }
コード例 #15
0
        public static List <MessageTarget> NotifyUnsubscribe(this MessageProvider user, MessageProvider publisher, string channelName)
        {
            var targets = publisher.Subscribers.GetAllUsersExceptOne(user);

            var result = new List <MessageTarget>
            {
                new MessageTarget
                {
                    Message = $"{user.Name} unsubscribed to {channelName}",
                    Targets = targets
                },
                new MessageTarget
                {
                    Message = $"{user.Name} unsubscribed to your channel",
                    Targets = new List <MessageProvider> {
                        publisher
                    }
                }
            };

            return(result);
        }
コード例 #16
0
        private void Spin()
        {
            MessageProvider.EnterStake();
            var stakeAmount = GetStakeAmount();

            MessageProvider.Separator();

            var winningAmount = 0.0m;
            var rotationCount = 4;

            while (rotationCount > 0)
            {
                RotateSymbols(stakeAmount, ref winningAmount);
                rotationCount--;
            }

            _player.CalculateBalance(stakeAmount, winningAmount);
            MessageProvider.Separator();
            MessageProvider.ProfitAmount(winningAmount);
            MessageProvider.CurrentBalance(_player.Balance);
            MessageProvider.Separator();
        }
コード例 #17
0
        /// <summary>
        /// Instantiiert SectionBase im 184 Byte TS-Packet Modus.
        /// </summary>
        /// <param name="pid">pid der TS-Packets</param>
        /// <param name="allowedTables">Byte-Array mit den erlaubten Table-IDs</param>
        public SectionBase(int pid, byte[] allowedTables)
        {
            _SectionData = new byte[4096];
            _DoCrc       = false; // wird später anhand table-ID ermittelt.
            _Pid         = pid;

            if (allowedTables == null)
            {
                switch (_Pid)
                {
                case 0x00:     // PAT
                    _AllowedTables = new byte[] { 0x00 };
                    break;

                case 0x01:     // CAT
                    _AllowedTables = new byte[] { 0x01 };
                    break;

                case 0x10:     // NIT / ST
                    _AllowedTables = new byte[] { 0x40, 0x41 };
                    break;

                case 0x11:     // SDT/BAT/ST
                    _AllowedTables = new byte[] { 0x42, 0x46, 0x4a };
                    break;
                }
            }
            else
            {
                _AllowedTables = allowedTables;
            }

            if (allowedTables == null || allowedTables.Length == 0)
            {
                throw new Exception(MessageProvider.FormatMessage(Message.SectionBaseTableReqd));
            }

            Reset();
        }
コード例 #18
0
ファイル: IniFile.cs プロジェクト: t5b6de/dvbapiNET_public
        private void Load()
        {
            string[] lines = File.ReadAllLines(_Fi.FullName);

            int i = 0;

            string curSection = "";

            foreach (string l in lines)
            {
                if (string.IsNullOrWhiteSpace(l) || l[0] == '#' || l[0] == ';') // Kommentar oder Leerzeile.
                {
                    continue;
                }

                if (l.Length < 3)
                {
                    throw new Exception(MessageProvider.FormatMessage(Message.IniFileParseEx, i + 1));
                }

                if (l[0] == '[' && l[l.Length - 1] == ']' && l.Length > 2) // Section Zeile
                {
                    curSection = l.Substring(1, l.Length - 2);
                }
                else
                {
                    string[] parts = l.Split("=".ToCharArray(), 2);

                    if (parts.Length < 2)
                    {
                        throw new Exception(MessageProvider.FormatMessage(Message.IniFileParseEx, i + 1));
                    }

                    SetValue(curSection, parts[0], parts[1]);
                }

                i++;
            }
        }
コード例 #19
0
        public void ThrowsWrongTypeException()
        {
            var msg = JsonConvert.SerializeObject(new Message <MoveResponsePayload>
            {
                SenderId    = Common.Consts.GameMasterId,
                RecipientId = _id,
                Type        = Common.Consts.MoveResponse,
                Payload     = new MoveResponsePayload
                {
                    DistanceToPiece = 1,
                    TimeStamp       = 1234
                }
            });

            _communicator.Setup(x => x.Receive()).Returns(msg);

            var system = new MessageProvider(_playerState, _communicator.Object);

            Assert.Throws <WrongPayloadException>(() => system.Receive <ActionValidPayload>());
            Assert.Throws <WrongPayloadException>(() => system.Receive <ActionInvalidPayload>());
            Assert.Throws <WrongPayloadException>(() => system.Receive <DiscoveryResponsePayload>());
        }
コード例 #20
0
        public void ThrowsActionInvalidException()
        {
            var msg = new Message <ActionInvalidPayload>
            {
                SenderId    = Common.Consts.GameMasterId,
                RecipientId = _id,
                Type        = Common.Consts.ActionInvalid,
                Payload     = new ActionInvalidPayload
                {
                    Reason = "asdf"
                }
            };
            var serializedMsg = JsonConvert.SerializeObject(msg);

            _communicator.Setup(x => x.Receive()).Returns(serializedMsg);


            var system = new MessageProvider(_playerState, _communicator.Object);


            Assert.Throws <ActionInvalidException>(() => system.Receive <ActionValidPayload>());
        }
コード例 #21
0
 public static void RegisterDefaultErrors(MessageProvider provider)
 {
     if (provider != null)
     {
         provider.Register("initializer/create/failed", "cant create instance: {0} from declaration: {1}, exception: {2}");
         provider.Register("initializer/instance/type", "instance: {0} is not of type: {1}");
         provider.Register("initializer/instance/noproperty", "property {0} not found on {1} type={2}.");
         provider.Register("initializer/resource/notfound", "no resource with key: {0}");
         provider.Register("initializer/arg/nullorempty", "the given value is null or empty: {0}");
         provider.Register("initializer/format/chained", "chained expressions not supported: {1}");
         provider.Register("initializer/contentmethod/notfound", "no add method on: {0} on object: {1}");
         provider.Register("initializer/contentproperty/unexpected", "unexpected error instance: {0} no contentsource.");
         provider.Register("initializer/extension/notfound", "no extension with name: {0}");
         provider.Register("initializer/extension/failed", "extension: {0} failed.");
         provider.Register("initializer/element/nokeyattribute", "no key attribute on: {0}");
         provider.Register("initializer/element/nocontent", "{0} doesnt supoort content");
         provider.Register("initializer/declaration/nonamespace", "no namespace on: {0}");
         provider.Register("initializer/declaration/novalue", "no value on: {0}");
         provider.Register("initializer/declaration/notfound", "no namespace declaration found with prefix: {0}");
         provider.Register("initializer/savechangetype/failed", "cant change: {0} to type: {1}.{2}");
     }
 }
コード例 #22
0
        private void ProcessRules(RewriteContext context)
        {
            const int MaxRestart = 10; // Controls the number of restarts so we don't get into an infinite loop

            IList rewriteRules = _configuration.Rules;
            int   restarts     = 0;

            for (int i = 0; i < rewriteRules.Count; i++)
            {
                // If the rule is conditional, ensure the conditions are met.
                IRewriteCondition condition = rewriteRules[i] as IRewriteCondition;
                if (condition == null || condition.IsMatch(context))
                {
                    // Execute the action.
                    IRewriteAction    action     = rewriteRules[i] as IRewriteAction;
                    RewriteProcessing processing = action.Execute(context);

                    // If the action is Stop, then break out of the processing loop
                    if (processing == RewriteProcessing.StopProcessing)
                    {
                        _configuration.Logger.Debug(MessageProvider.FormatString(Message.StoppingBecauseOfRule));
                        break;
                    }
                    else if (processing == RewriteProcessing.RestartProcessing)
                    {
                        _configuration.Logger.Debug(MessageProvider.FormatString(Message.RestartingBecauseOfRule));

                        // Restart from the first rule.
                        i = 0;

                        if (++restarts > MaxRestart)
                        {
                            throw new InvalidOperationException(MessageProvider.FormatString(Message.TooManyRestarts));
                        }
                    }
                }
            }
        }
コード例 #23
0
        /// <summary>
        /// Parses the node.
        /// </summary>
        /// <param name="node">The node to parse.</param>
        /// <param name="config">The rewriter configuration.</param>
        /// <returns>The parsed action, or null if no action parsed.</returns>
        public override IRewriteAction Parse(XmlNode node, RewriterConfiguration config)
        {
            if (node == null)
            {
                throw new ArgumentNullException("node");
            }
            if (config == null)
            {
                throw new ArgumentNullException("config");
            }

            string to = node.GetRequiredAttribute(Constants.AttrTo, true);

            XmlNode processingNode = node.Attributes[Constants.AttrProcessing];

            RewriteProcessing processing = RewriteProcessing.ContinueProcessing;

            if (processingNode != null)
            {
                if (processingNode.Value == Constants.AttrValueRestart)
                {
                    processing = RewriteProcessing.RestartProcessing;
                }
                else if (processingNode.Value == Constants.AttrValueStop)
                {
                    processing = RewriteProcessing.StopProcessing;
                }
                else if (processingNode.Value != Constants.AttrValueContinue)
                {
                    throw new ConfigurationErrorsException(MessageProvider.FormatString(Message.ValueOfProcessingAttribute, processingNode.Value, Constants.AttrValueContinue, Constants.AttrValueRestart, Constants.AttrValueStop), node);
                }
            }

            RewriteAction action = new RewriteAction(to, processing);

            ParseConditions(node, action.Conditions, false, config);
            return(action);
        }
コード例 #24
0
        public async ValueTask <FlushResult> SendMessageAsync <T>(T message)
        {
            if (!MessageProvider.ContainsMessage <T>())
            {
                throw new ArgumentException(nameof(message));
            }
            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }

            var stream = new MemoryStream();
            var writer = new BinaryWriter(stream);

            MessageSerializer.Serialize(message, writer);

            var payload = stream.GetBuffer();
            var result  = await SendAsync(new Frame <NetworkMetadata>(payload,
                                                                      new NetworkMetadata(payload.Length, MessageProvider.GetId <T>())));

            Console.WriteLine($"{typeof(T).Name} successfully sent !");
            return(result);
        }
コード例 #25
0
 public static void PrintImmediately(string creditText, int seconds, bool mute, bool setMessage, bool devOnly)
 {
     if (devOnly && !RandomizerSettings.Dev)
     {
         return;
     }
     MessageProvider.SetMessage(creditText);
     if (mute)
     {
         CachedVolume = Math.Max(GameSettings.Instance.SoundEffectsVolume, CachedVolume);
         GameSettings.Instance.SoundEffectsVolume = 0f;
     }
     UI.Hints.Show(Randomizer.MessageProvider, HintLayer.GameSaved, (float)seconds);
     if (mute)
     {
         ResetVolume = 3;
     }
     if (setMessage)
     {
         Message            = creditText;
         LastMessageCredits = true;
     }
 }
コード例 #26
0
        private static void ReadMapping(XmlNode node, RewriterConfiguration config)
        {
            // Name attribute.
            XmlNode nameNode = node.Attributes[Constants.AttrName];

            // Mapper type not specified.  Load in the hash map.
            StringDictionary map = new StringDictionary();

            foreach (XmlNode mapNode in node.ChildNodes)
            {
                if (mapNode.NodeType == XmlNodeType.Element)
                {
                    if (mapNode.LocalName == Constants.ElementMap)
                    {
                        XmlNode fromValueNode = mapNode.Attributes[Constants.AttrFrom];
                        if (fromValueNode == null)
                        {
                            throw new ConfigurationErrorsException(MessageProvider.FormatString(Message.AttributeRequired, Constants.AttrFrom), node);
                        }

                        XmlNode toValueNode = mapNode.Attributes[Constants.AttrTo];
                        if (toValueNode == null)
                        {
                            throw new ConfigurationErrorsException(MessageProvider.FormatString(Message.AttributeRequired, Constants.AttrTo), node);
                        }

                        map.Add(fromValueNode.Value, toValueNode.Value);
                    }
                    else
                    {
                        throw new ConfigurationErrorsException(MessageProvider.FormatString(Message.ElementNotAllowed, mapNode.LocalName), node);
                    }
                }
            }

            config.TransformFactory.AddTransform(new StaticMappingTransform(nameNode.Value, map));
        }
コード例 #27
0
        private static void ReadErrorHandler(XmlNode node, IRewriterConfiguration config)
        {
            var code = node.GetRequiredAttribute(Constants.AttrCode);

            XmlNode typeNode = node.Attributes[Constants.AttrType];
            XmlNode urlNode  = node.Attributes[Constants.AttrUrl];

            if (typeNode == null && urlNode == null)
            {
                throw new ConfigurationErrorsException(MessageProvider.FormatString(Message.AttributeRequired, Constants.AttrUrl), node);
            }

            IRewriteErrorHandler handler = null;

            if (typeNode != null)
            {
                // <error-handler code="500" url="/oops.aspx" />
                handler = TypeHelper.Activate(typeNode.Value, null) as IRewriteErrorHandler;
                if (handler == null)
                {
                    throw new ConfigurationErrorsException(MessageProvider.FormatString(Message.InvalidTypeSpecified, typeNode.Value, typeof(IRewriteErrorHandler)), node);
                }
            }
            else
            {
                handler = new DefaultErrorHandler(urlNode.Value);
            }

            int statusCode;

            if (!int.TryParse(code, out statusCode))
            {
                throw new ConfigurationErrorsException(MessageProvider.FormatString(Message.InvalidHttpStatusCode, code), node);
            }

            config.ErrorHandlers.Add(statusCode, handler);
        }
コード例 #28
0
        /// <summary>
        /// Default constructor.
        /// </summary>
        internal RewriterConfiguration()
        {
            _xPoweredBy = MessageProvider.FormatString(Message.ProductName, Assembly.GetExecutingAssembly().GetName().Version.ToString(3));

            _actionParserFactory = new ActionParserFactory();
            _actionParserFactory.AddParser(new IfConditionActionParser());
            _actionParserFactory.AddParser(new UnlessConditionActionParser());
            _actionParserFactory.AddParser(new AddHeaderActionParser());
            _actionParserFactory.AddParser(new SetCookieActionParser());
            _actionParserFactory.AddParser(new SetPropertyActionParser());
            _actionParserFactory.AddParser(new RewriteActionParser());
            _actionParserFactory.AddParser(new RedirectActionParser());
            _actionParserFactory.AddParser(new SetStatusActionParser());
            _actionParserFactory.AddParser(new ForbiddenActionParser());
            _actionParserFactory.AddParser(new GoneActionParser());
            _actionParserFactory.AddParser(new NotAllowedActionParser());
            _actionParserFactory.AddParser(new NotFoundActionParser());
            _actionParserFactory.AddParser(new NotImplementedActionParser());

            _conditionParserPipeline = new ConditionParserPipeline();
            _conditionParserPipeline.AddParser(new AddressConditionParser());
            _conditionParserPipeline.AddParser(new HeaderMatchConditionParser());
            _conditionParserPipeline.AddParser(new MethodConditionParser());
            _conditionParserPipeline.AddParser(new PropertyMatchConditionParser());
            _conditionParserPipeline.AddParser(new ExistsConditionParser());
            _conditionParserPipeline.AddParser(new UrlMatchConditionParser());

            _transformFactory = new TransformFactory();
            _transformFactory.AddTransform(new DecodeTransform());
            _transformFactory.AddTransform(new EncodeTransform());
            _transformFactory.AddTransform(new LowerTransform());
            _transformFactory.AddTransform(new UpperTransform());
            _transformFactory.AddTransform(new Base64Transform());
            _transformFactory.AddTransform(new Base64DecodeTransform());

            _defaultDocuments = new StringCollection();
        }
コード例 #29
0
        private void MessageProvider_MessageReceived(object sender, MessageReceivedEventArgs args)
        {
            var message = args.Message;

            // debug game
            if (message is PingMessage)
            {
                MessageProvider.SendMessage(new PongMessage());
                return;
            }

            SecurityActivity activity = null;

            // load from database if it was too big to distribute
            if (message is BigActivityMessage bigActivityMessage)
            {
                activity = DataHandler.LoadBigSecurityActivity(bigActivityMessage.DatabaseId);
                if (activity == null)
                {
                    SnTrace.Security.WriteError("Cannot load body of a BigActivity. Id: {0}", bigActivityMessage.DatabaseId);
                }
            }

            // trying to interpret
            if (activity == null)
            {
                activity = message as SecurityActivity;
            }

            // Apply if everything is good
            if (activity != null)
            {
                activity.FromReceiver = true;
                activity.Context      = GeneralSecurityContext;
                activity.Execute(GeneralSecurityContext, false);
            }
        }
コード例 #30
0
        public void Start()
        {
            GeneralSecurityContext = null;

            // The message provider must receive ongoing activities at this time.
            StartedAt = DateTime.UtcNow;

            var uncompleted = DataHandler.LoadCompletionState(out var lastActivityIdFromDb);

            PermissionTypeBase.InferForcedRelations();

            using (var op = SnTrace.Security.StartOperation("Security initial loading."))
            {
                var cache = new SecurityCache(DataHandler);
                cache.Initialize();
                Cache         = cache;
                op.Successful = true;
            }

            EntityManager             = new SecurityEntityManager(Cache, DataHandler, MissingEntityHandler);
            Cache.EntityManager       = EntityManager; // Property injection
            DataHandler.EntityManager = EntityManager; // Property injection

            PermissionQuery        = new PermissionQuery(EntityManager, Cache);
            CommunicationMonitor   = new CommunicationMonitor(DataHandler, Options.Create(MessagingOptions));
            GeneralSecurityContext = new SecurityContext(SystemUser, this);

            SecurityActivityQueue = new SecurityActivityQueue(this, CommunicationMonitor, DataHandler, ActivityHistory);
            SecurityActivityQueue.Startup(uncompleted, lastActivityIdFromDb);
            ActivityHistory.SecurityActivityQueue = SecurityActivityQueue; // Property injection

            MessageProvider.MessageReceived += MessageProvider_MessageReceived;
            MessageProvider.Initialize();
            MessageProvider.Start(StartedAt);

            _killed = false;
        }
コード例 #31
0
ファイル: DataManager.cs プロジェクト: madfrog54321/Timer
        public static void Main()
        {
            _messageProvider = new BasicMessageProvider();//enable basic message provider

            //open settings
            _settings = Settings.Load();
            _competition = Competition.Load();

            //start wpf application thread
            var application = new App();
            application.Exit += Application_Exit;
            application.InitializeComponent();
            application.Run();
        }
コード例 #32
0
    public void SendMessage(MessageProvider.SendMessageEnum sendLocalMessage, 
        MessageProvider.SendMessageEnum sendEmail)
    {
        bool res = false;

        try
        {
            var o1 = new Message();
            form2obj(o1);
            MessageProvider.SendMessage(Utility.String2List(o1.ToUser, ";"), o1,
                sendLocalMessage, sendEmail);
            res = true;
        }
        catch (Exception e1)
        {
            this.lastMessage = Utility.GetLabel("RECORD_ERR_MSG") + "<br />" + e1.ToString();
        }
        finally
        {
        }
        if (this.MessageSent != null)
            this.MessageSent(this,
                new Message.MessageEventArgs(0, "send", this.LastMessage, res));
    }