public void TestMatchObject() {
            var o = new Match() as object;

            Assert.IsTrue(o.IsPropertyMatch<Match, string>("Prop1", mm => mm.Prop1));
            Assert.IsTrue(o.IsPropertyMatch<Match, int>("Prop2", mm => mm.Prop2));
            Assert.IsTrue(o.IsPropertyMatch<Match, Match>("Prop3", mm => mm.Prop3));
            Assert.IsTrue(o.IsPropertyMatch<Match, int?>("Prop4", mm => mm.Prop4));

            Assert.IsFalse(o.IsPropertyMatch<Match, string>("Prop2", mm => mm.Prop1));
            Assert.IsFalse(o.IsPropertyMatch<Match, int>("Something", mm => mm.Prop2));
            Assert.IsFalse(o.IsPropertyMatch<Match, int>("", mm => mm.Prop2));
            Assert.IsFalse(o.IsPropertyMatch<Match, int>(null, mm => mm.Prop2));

            var oo = new Object();

            Assert.IsFalse(oo.IsPropertyMatch<Match, string>("Prop1", mm => mm.Prop1));
            Assert.IsFalse(oo.IsPropertyMatch<Match, int>("Prop2", mm => mm.Prop2));
            Assert.IsFalse(oo.IsPropertyMatch<Match, Match>("Prop3", mm => mm.Prop3));
            Assert.IsFalse(oo.IsPropertyMatch<Match, int?>("Prop4", mm => mm.Prop4));

            Assert.IsFalse(oo.IsPropertyMatch<Match, string>("Prop2", mm => mm.Prop1));
            Assert.IsFalse(oo.IsPropertyMatch<Match, int>("Something", mm => mm.Prop2));
            Assert.IsFalse(oo.IsPropertyMatch<Match, int>("", mm => mm.Prop2));
            Assert.IsFalse(oo.IsPropertyMatch<Match, int>(null, mm => mm.Prop2));
        }
Example #2
0
        public override CompetitorRanks GenerateResult(MatchStrategy matchStrategy, List<Competitor> competitors)
        {
            List<Match> matches = new List<Match>();

            if (competitors.Count % 2 != 0)
                throw new ArgumentException("Collection count must be even.", "competitors");

            // generate the results for the competitors
            // note that the competitors are paired in this round by the order they're in in the List object
            // pairing first with last, second with second-to-last, etc.
            for (int index = 0; index < competitors.Count / 2; index++)
            {
                int mirrorIndex = competitors.Count - (index + 1);

                Competitor competitorA = competitors[index];
                Competitor competitorB = competitors[mirrorIndex];

                Match match = new Match(matchStrategy, WinsToClinchMatch);
                match.Run(competitorA, competitorB);
                matches.Add(match);
            }

            Matches = matches;

            CompetitorPoints tournamentRoundPoints = AccumulateMatchPoints(matches);
            return tournamentRoundPoints.GetCompetitorRanks();
        }
 /// <summary>
 /// Returns a boolean representation of the value associated with the 
 /// IsMobile property.
 /// </summary>
 /// <param name="match">a Match object</param>
 /// <returns>
 /// A boolean representation of the value for IsMobile
 /// </returns>        
 public static bool getIsMobileBool(Match match)
 {
     if (match["IsMobile"].ToString() == "True")
         return true;
     else
         return false;
 }
Example #4
0
        public void ICanCreateAMatch()
        {
            var match = new Match(7, 501);

            Assert.AreEqual(7, match.BestOfLegs);
            Assert.AreEqual(501, match.LegStartScore);
        }
Example #5
0
        public override void Apply(Match match)
        {
            if (!this.IsValid(match))
            {
                return;
            }

            match.PendingDecisions.Dequeue();

            if (this._stocks.Count>0)
            {
                Console.WriteLine("   [{0}] Purchasing stock in: ",match.Players[this._playerIndex].Member.Name);

                foreach (var stock in _stocks)
                {
                    match.Players[_playerIndex].AddStock(stock.Key, stock.Value);

                    var price = Engine.GetStockPrice(stock.Key, match);
                    Console.WriteLine("      - {1}x {0} - spending {2:C}", stock.Key, stock.Value, stock.Value * price);
                    match.Players[_playerIndex].Money -= stock.Value * price;
                    match.AvailableStock[stock.Key] -= stock.Value;
                }
            }
            else
            {
                Console.WriteLine("   No active chains to purchase stock in");
            }
            if (match.PendingDecisions.Count == 0)
                match.CurrentPhase = MatchPhase.DrawingTile;
        }
Example #6
0
        /**
        *   Generates a label with text, a picturebox and another label.
        *   @parentPanel The panel that should add the created panel to it's controls.
        *   @team The team object containing data that'll be displayed such as the teams name and logo.
        *   @match The match object containing data that should be displayed.
        **/
        private void generateLabel(Panel parentPanel, Team team, Match match)
        {
            int _teamScore;
            if (match._team1 == team) {
                _teamScore = match._team1Score;
            } else {
                _teamScore = match._team2score;
            }

            Label labelname = new System.Windows.Forms.Label();
            labelname.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Pixel, ((byte)(0)));
            labelname.Name = team._name;
            labelname.Size = new System.Drawing.Size(250, 15);
            labelname.Dock = System.Windows.Forms.DockStyle.Top;
            labelname.Text = String.Format("{0}", team._name);
            labelname.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(207)))), ((int)(((byte)(207)))), ((int)(((byte)(207)))));

            PictureBox pb = new PictureBox();
            pb.Size = new System.Drawing.Size(15, 15);
            pb.Dock = DockStyle.Right;
            pb.Image = team.getTeamLogo();

            Label score = new Label();
            score.Text = _teamScore.ToString();
            score.Dock = DockStyle.Right;
            score.Size = new System.Drawing.Size(15, 15);

            labelname.Controls.Add(score);
            labelname.Controls.Add(pb);
            parentPanel.Controls.Add(labelname);
        }
Example #7
0
        public override bool IsValid(Match match)
        {
            var nextDecision = match.PendingDecisions.First();

            return nextDecision.PlayerIndex == this._playerIndex
                && nextDecision.Type == DecisionType.ChooseMergeOrder;
        }
Example #8
0
		public override bool DoMatch(INode other, Match match)
		{
			if (other == null || other.IsNull)
				return this.MinCount <= 0;
			else
				return this.MaxCount >= 1 && childNode.DoMatch(other, match);
		}
 public override IEnumerable<Tuple<ShapeNode, ShapeNode>> Apply(Match<Word, ShapeNode> match, Word output)
 {
     FeatureStruct fs = _simpleCtxt.FeatureStruct.DeepClone();
     fs.ReplaceVariables(match.VariableBindings);
     ShapeNode newNode = output.Shape.Add(fs);
     return Tuple.Create((ShapeNode) null, newNode).ToEnumerable();
 }
Example #10
0
 public MatchEditor(Match m, Player[] playerList)
 {
     this.oldMatch = m;
     this.thisMatch = m.Clone();
     this.players = playerList;
     InitializeComponent();
 }
Example #11
0
        /// <summary>
        /// Extracts the matches of this pattern from <paramref name="source" />.
        /// </summary>
        /// <param name="fileName">The name of the file associated with <paramref name="source" />.</param>
        /// <param name="source">The source string</param>
        /// <returns>
        /// A collection of found matches.
        /// </returns>
        public MatchCollection Extract(string fileName, string source)
        {
            MatchCollection resultMatches = new MatchCollection();
            LineCounter lineCounter = new LineCounter(source);

            RegexMatch regexMatch = scanner.Match(source);
            while (regexMatch.Success)
            {
                Match match = new Match();
                match["Path"] = Path.GetDirectoryName(fileName);
                match["File"] = Path.GetFileName(fileName);
                match["LineNumber"] = lineCounter.CountTo(regexMatch.Index).InvariantToString();
                foreach (string groupName in scanner.GetGroupNames())
                {
                    // ignore default-names like '0', '1' ... as produced
                    // by the Regex class
                    if (Char.IsLetter(groupName[0]) || (groupName[0] == '_'))
                    {
                        match[groupName] = ConcatenateCaptures(regexMatch.Groups[groupName]);
                    }
                }
                resultMatches.Add(match);
                regexMatch = regexMatch.NextMatch();
            }
            return resultMatches;
        }
Example #12
0
 public Goal(int id, int minutes, Match match, Player player)
 {
     Id = id;
     Minutes = minutes;
     Match = match;
     Player = player;
 }
Example #13
0
 public Goal(int id, int minutes, Match match, int idPlayer)
 {
     Id = id;
     Minutes = minutes;
     Match = match;
     Player = createPlayer(idPlayer);
 }
Example #14
0
 public void selectChoice(Match.RPS choice)
 {
     if(currentMatch != null)
     {
         currentMatch.setPlayerChoice(this, choice);
     }
 }
        public void TranslationCandidatesDefaultValue_Match()
        {
            Match match;

            match = new Match();
            Assert.IsFalse(match.HasReferenceTranslation, "HasReferenceTranslation is incorrect.");
            Assert.IsNull(match.Id, "Id is incorrect.");
            Assert.IsNull(match.MatchQuality, "MatchQuality is incorrect.");
            Assert.IsNull(match.MatchSuitability, "MatchSuitability is incorrect.");
            Assert.IsNull(match.Metadata, "Metadata is incorrect.");
            Assert.IsNull(match.Origin, "Origin is incorrect.");
            Assert.IsNull(match.OriginalData, "OriginalData is incorrect.");
            Assert.IsNull(match.Similarity, "Similarity is incorrect.");
            Assert.IsNull(match.Source, "Source is incorrect.");
            Assert.IsNull(match.SourceReference, "SourceReference is incorrect.");
            Assert.IsNull(match.SubType, "SubType is incorrect.");
            Assert.IsNull(match.Target, "Target is incorrect.");
            Assert.AreEqual(MatchType.TranslationMemory, match.Type, "Type is incorrect.");

            match = new Match("sourcereference");
            Assert.IsFalse(match.HasReferenceTranslation, "HasReferenceTranslation is incorrect.");
            Assert.IsNull(match.Id, "Id is incorrect.");
            Assert.IsNull(match.MatchQuality, "MatchQuality is incorrect.");
            Assert.IsNull(match.MatchSuitability, "MatchSuitability is incorrect.");
            Assert.IsNull(match.Metadata, "Metadata is incorrect.");
            Assert.IsNull(match.Origin, "Origin is incorrect.");
            Assert.IsNull(match.OriginalData, "OriginalData is incorrect.");
            Assert.IsNull(match.Similarity, "Similarity is incorrect.");
            Assert.IsNull(match.Source, "Source is incorrect.");
            Assert.AreEqual("sourcereference", match.SourceReference, "SourceReference is incorrect.");
            Assert.IsNull(match.SubType, "SubType is incorrect.");
            Assert.IsNull(match.Target, "Target is incorrect.");
            Assert.AreEqual(MatchType.TranslationMemory, match.Type, "Type is incorrect.");
        }
 public PointTotal(Match m, bool home)
 {
     if (home)
        this.points = (m.HomeGoals);
     else
         this.points = (m.AwayGoals);
 }
    public override void ProcessRequest(HttpContext context, Match match)
    {
        context.Response.Cache.SetCacheability(HttpCacheability.NoCache);

        try
        {
            PccConfig.LoadConfig("pcc.config");
            string searchTermsId = GetStringFromUrl(context, match, "SearchTermsId");
            // make sure target directory exists
            String targetDir = System.IO.Path.GetDirectoryName(PccConfig.SearchTermsPath);
            if (!System.IO.Directory.Exists(targetDir))
            {
                context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                context.Response.Write("SearchTermsPath does not exist or is not configured correctly in pcc.config");
                context.Response.ContentType = "text/plain";
                return;
            }
            string searchTermsFileName = Path.Combine(targetDir, searchTermsId);
            using (FileStream searchStream = new FileStream(searchTermsFileName, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                searchStream.CopyTo(context.Response.OutputStream);
            }

            context.Response.ContentType = "application/json;charset=utf-8";
            context.Response.StatusCode = (int)HttpStatusCode.OK;
        }
        catch(Exception e)
        {
            context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
            context.Response.Write(e.Message);
            context.Response.ContentType = "text/plain";
            return;
        }
    }
Example #18
0
    public void ShouldBeUsableToSearchForMatches(Cloud cloud)
    {
        Login2NewUsers(cloud, (gamer1, gamer2) => {
            string queryStr = "public:true AND owner_id:" + gamer1.GamerId;
            Match[] matches = new Match[2];

            gamer1.Matches.Create(maxPlayers: 2)
            .Then(match1 => {
                Bundle matchProp = Bundle.CreateObject("public", true, "owner_id", gamer1.GamerId);
                matches[0] = match1;
                // Index the match
                return cloud.Index("matches").IndexObject(match1.MatchId, matchProp, Bundle.Empty);
            })
            .Then(indexResult => {
                // Create another match
                return gamer1.Matches.Create(maxPlayers: 2);
            })
            .Then(match2 => {
                // Index it
                matches[1] = match2;
                return cloud.Index("matches").IndexObject(match2.MatchId, Bundle.CreateObject("public", false), Bundle.Empty);
            })
            .Then(indexResult2 => {
                // Check that we can find match1 by looking for public matches
                return cloud.Index("matches").Search(queryStr);
            })
            .Then(found => {
                Assert(found.Hits.Count == 1, "Should find one match");
                Assert(found.Hits[0].ObjectId == matches[0].MatchId, "Should find one match");
            })
            .CompleteTestIfSuccessful();
        });
    }
        public string Get()
        {
            using (var DBContext = new HeartstatDBDataContext())
            {
                for(int i = 0; i < 10; i++){

                Match seedMatch = new Match
                {
                    User = "******"+i.ToString(),
                    UserClass = "Druid",
                    SubClass = "Ramp",
                    OpponentClass = "Warlock",
                    OpponentSubClass = "Zoo",
                    MatchResult = false,
                    PlayerRank = 18,
                    Season = 5,
                    Created = DateTime.Now,
                    Comment = "Paska peli",
                    UserId = "1111-1111111-1111-111"
                };
                DBContext.Matches.InsertOnSubmit(seedMatch);
                }
                try
                {
                    DBContext.SubmitChanges();
                    return "Database seed completed";
                }
                catch (Exception ex)
                {
                    return ex.Message;
                }

            }
        }
Example #20
0
        static Match FindContainingAllTokensInOrder(string s, int startIndex, int endIndex, string[] tokens)
        {
            int firstTokenStart;
            int lastTokenEnd;

            if (tokens.Length == 0)
            {
                return null;
            }
            firstTokenStart = s.IndexOf(tokens[0], startIndex, endIndex - startIndex);
            if (firstTokenStart == -1)
            {
                return null;
            }

            lastTokenEnd = firstTokenStart + tokens[0].Length;
            for (int i = 1; i < tokens.Length; i++)
            {
                lastTokenEnd = s.IndexOf(tokens[i], lastTokenEnd, endIndex - lastTokenEnd);
                if (lastTokenEnd == -1)
                {
                    return null;
                }
                lastTokenEnd += tokens[i].Length;
            }

            Match ret = new Match();
            ret.Index = firstTokenStart;
            ret.EndIndex = lastTokenEnd;
            return ret;
        }
Example #21
0
		public override bool DoMatch(INode other, Match match)
		{
			var last = match.Get (referencedGroupName).Last ();
			if (last == null && other == null)
				return true;
			return last.IsMatch(other);
		}
        private bool IsUnapplicationNonvacuous(Match<Word, ShapeNode> match, IEnumerable<FeatureStruct> rhsAntiFSs)
        {
            int i = 0;
            foreach (FeatureStruct fs in rhsAntiFSs)
            {
                ShapeNode node = match.GroupCaptures["target" + i].Span.GetStart(match.Matcher.Direction);
                foreach (SymbolicFeature sf in fs.Features.OfType<SymbolicFeature>())
                {
                    SymbolicFeatureValue sfv = fs.GetValue(sf);
                    SymbolicFeatureValue nodeSfv;
                    if (node.Annotation.FeatureStruct.TryGetValue(sf, out nodeSfv))
                    {
                        if (sfv.IsVariable)
                        {
                            SymbolicFeatureValue varSfv;
                            if (!match.VariableBindings.TryGetValue(sfv.VariableName, out varSfv) || !nodeSfv.IsSupersetOf(varSfv, !sfv.Agree))
                                return true;
                        }
                        else if (!nodeSfv.IsSupersetOf(sfv))
                        {
                            return true;
                        }
                    }
                }
                i++;
            }

            return false;
        }
        public override int PointsEarned(MatchResult outcome, Match MatchOfWeek)
        {
            int Multiple = outcome.Match == MatchOfWeek ? 2 : 1;

            if (outcome.Winner != null && !outcome.Winner.Equals(Winner))
                return 0;

            //Is a stoppage!
            if (outcome.ResultType.HasRounds)
            {
                if (outcome.Round == Round)
                {
                    return ((3 + 5) * Multiple);
                }
                else if (outcome.Round <= Round + 1 && outcome.Round >= Round - 1)
                {
                    return ((3 + 3) * Multiple);
                }
                else if (outcome.Round <= Round + 2 && outcome.Round >= Round - 2)
                {
                    return ((3 + 1) * Multiple);
                }
                else
                {
                    return (3 * Multiple);
                }
            }

            return 0;
        }
Example #24
0
        private static void ReplaceMatch(Match scMatch, int monitorHeight, string scConfigContent, string scFolderPath, string fileName)
        {
            if (scMatch.Success)
            {
                string fullString = scMatch.Captures[0].Value;

                string variablesName = scMatch.Groups[1].Captures[0].Value;
                string delimiter = scMatch.Groups[2].Captures[0].Value;
                string valueEnclosingCharacter = scMatch.Groups[3].Captures[0].Value;
                int configHeight = int.Parse(scMatch.Groups[4].Captures[0].Value);

                if (configHeight != monitorHeight)
                {
                    Console.WriteLine("Current Height: {0}", configHeight);
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.WriteLine("Changing to {0}", monitorHeight);
                    scConfigContent = scConfigContent.Replace(fullString, string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}{3}{2}", variablesName, delimiter, valueEnclosingCharacter, monitorHeight));
                    Console.ForegroundColor = ConsoleColor.Green;
                    WriteAllText(scFolderPath, fileName, scConfigContent);
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("Everthing is already goooood to gooo!!!");
                }
            }
            else
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Something bad happened to the config file... go check it!");
                Console.ReadLine();
            }
        }
Example #25
0
        /// <summary>
        ///   Clusters Two INodes together, sets new root/parent/left and right edges
        /// </summary>
        /// <param name="left"> Node on the left </param>
        /// <param name="right"> Node on the Right </param>
        /// <param name="match"> Inverted or Not Inverted </param>
        /// <param name="matchData"> Optional MatchData variable, store clustering information </param>
        public Cluster(INode left, INode right, Match match = Match.NonInverted, MatchData matchData = null)
        {
            if (match == Match.Impossible)
            {
                throw new ArgumentException("Match is apparently impossible why are you trying?");
            }

            // Now Build the new nodes
            _left = left;
            _right = right;
            _matchData = matchData;
            _size = left.Size() + right.Size();
            _leftedge = left.LeftEdge();
            _rightedge = right.RightEdge();

            // Set the parents accordingly
            left.Parent(this);
            right.Parent(this);
            _parent = null;

            // change the roots
            _left.Root(this);
            _right.Root(this);

            // Update Count
            Id = _count++;
        }
        public MatchCollectionTest()
        {
            Match<char> match;

             try
             {
            match = new Match<char> ("0123456789".ToListCursor (), 0, 10, true);
             }
             catch (Exception e)
             {
            Assert.Inconclusive (e.ToString ());
            throw;
             }
             m_allDigitsMatch = match;

             try
             {
            match = new Match<char> ("0123456789".ToListCursor (), 0, 0, false);
             }
             catch (Exception e)
             {
            Assert.Inconclusive (e.ToString ());
            throw;
             }
             m_noDigitsMatch = match;
        }
        public Match CreateMatch(DateTime matchDate, TimeSpan time, Venue venue, CompetitionMatchType matchType,
            Competition competition, Team homeTeam, Team awayTeam)
        {
            if (homeTeam.GetType() == awayTeam.GetType())
            {
                Match match = new Match();

                match.MatchDate = matchDate;
                match.MatchTime = time;
                match.Venue = venue;
                match.CompetitionMatchType = matchType;
                match.Competition = competition;
                match.HomeTeam = homeTeam;
                match.AwayTeam = awayTeam;

                context.Matches.Add(match);
                context.SaveChanges();

                return match;
            }
            else
            {
                return null;
            }
        }
 /// <summary>  
 /// 将Json序列化的时间由/Date(....)转为字符串
 /// </summary>
 private string ConvertJsonDateToDateString(Match m)
 {
     string result = string.Empty;
     DateTime dt = new DateTime(1970, 1, 1);
     dt = dt.AddMilliseconds(long.Parse(m.Groups[1].Value)).ToLocalTime();
     return dt.ToString(FormateStr);
 }
Example #29
0
 public void ICannotAdd2PlayersToAMatchWithTheSameName()
 {
     var match = new Match(7, 501);
     var player = new Player("Andy");
     match.AddPlayer(player);
     match.AddPlayer(player);
 }
Example #30
0
		public override bool DoMatch(INode other, Match match)
		{
			if (other == null || other.IsNull)
				return true;
			else
				return childNode.DoMatch(other, match);
		}
Example #31
0
        public static bool IsPhone(string inputData)
        {
            Match m = RegPhone.Match(inputData);

            return(m.Success);
        }
        public static void Main(string[] args)
        {
            string tainted_2 = null;
            string tainted_3 = null;


            Process process = new Process();

            process.StartInfo.FileName               = "/bin/bash";
            process.StartInfo.Arguments              = "-c 'cat /tmp/tainted.txt'";
            process.StartInfo.UseShellExecute        = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.Start();

            using (StreamReader reader = process.StandardOutput) {
                tainted_2 = reader.ReadToEnd();
                process.WaitForExit();
                process.Close();
            }

            tainted_3 = tainted_2;

            if ((4 + 2 >= 42))
            {
                string pattern = @"/^[0-9]*$/";
                Regex  r       = new Regex(pattern);
                Match  m       = r.Match(tainted_2);
                if (!m.Success)
                {
                    tainted_3 = "";
                }
                else
                {
                    tainted_3 = tainted_2;
                }
            }
            else if (!(4 + 2 >= 42))
            {
                {}
            }

            //flaw

            string query = "SELECT * FROM '" + tainted_3 + "'";


            string        connectionString = @"server=localhost;uid=sql_user;password=sql_password;database=dbname";
            SqlConnection dbConnection     = null;

            try {
                dbConnection = new SqlConnection(connectionString);
                dbConnection.Open();
                SqlCommand cmd = dbConnection.CreateCommand();
                cmd.CommandText = query;
                SqlDataReader reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    Console.WriteLine(reader.ToString());
                }
                dbConnection.Close();
            } catch (Exception e) {
                Console.WriteLine(e.ToString());
            }
        }
Example #33
0
        protected override bool DoMatch(AstNode other, Match match)
        {
            CommentStatement o = other as CommentStatement;

            return(o != null && MatchString(comment, o.comment));
        }
Example #34
0
 public RegexMatchResult(Match match) : base(match.Value)
 {
     Match = match;
 }
Example #35
0
        /// <summary>
        /// 判断订单是否规范
        /// </summary>
        /// <param name="order">待判断订单</param>
        /// <param name="errorMsg">错误信息</param>
        /// <returns>是否规范</returns>
        public static bool isNormative(PeriodicalOrder order, ref List <string> errorMsg)
        {
            List <string> errorList = new List <string>();

            if (order.BookSellerId <= 0)
            {
                errorList.Add("BookSellerId Error");
            }
            if (order.OrdererId <= 0)
            {
                errorList.Add("OrdererId Error");
            }
            Match matchISBN = Regex.Match(order.ISBN, @"^(\d{10})$");

            if (!matchISBN.Success)
            {
                errorList.Add("ISBN Error");
            }
            Match matchDocumentType = Regex.Match(order.DocumentType, @"^(期刊|专著)$");

            if (!matchDocumentType.Success)
            {
                errorList.Add("DocumentType Error");
            }
            Match matchPublishCycle = Regex.Match(order.PublishCycle, @"^(周刊|半月刊|月刊|季刊|年刊)$");

            if (!matchPublishCycle.Success)
            {
                errorList.Add("PublishCycle Error");
            }
            Match matchOfficialTitle = Regex.Match(order.OfficialTitle, @"^(.*)$");

            if (!matchOfficialTitle.Success)
            {
                errorList.Add("OfficialTitle Error");
            }
            Match matchSupplementTitle = Regex.Match(order.SupplementTitle, @"^(.*)$");

            if (!matchSupplementTitle.Success)
            {
                errorList.Add("SupplementTitle Error");
            }
            if (order.PublishingHouseId <= 0)
            {
                errorList.Add("PublishingHouseId Error");
            }
            if (Math.Sign(order.OrderPrice) != 1)
            {
                errorList.Add("OrderPrice Error");
            }
            Match matchCurrencyType = Regex.Match(order.CurrencyType, @"^(人民币\(RMB\))|(美元\(USD\))$");

            if (!matchCurrencyType.Success)
            {
                errorList.Add("CurrencyType Error");
            }
            Match matchSize = Regex.Match(order.Size, @"^(A4|A3|16开)$");

            if (!matchSize.Success)
            {
                errorList.Add("Size Error");
            }
            errorMsg = errorList;
            if (errorList.Count > 0)
            {
                return(false);
            }
            return(true);
        }
Example #36
0
        /// <summary>
        /// 是否是浮点数
        /// </summary>
        /// <param name="inputData">输入字符串</param>
        /// <returns></returns>
        public static bool IsDecimal(string inputData)
        {
            Match m = RegDecimal.Match(inputData);

            return(m.Success);
        }
Example #37
0
        /// <summary>
        /// 是否数字字符串 可带正负号
        /// </summary>
        /// <param name="inputData">输入字符串</param>
        /// <returns></returns>
        public static bool IsNumberSign(string inputData)
        {
            Match m = RegNumberSign.Match(inputData);

            return(m.Success);
        }
Example #38
0
        /// <summary>
        /// 检测是否有中文字符
        /// </summary>
        /// <param name="inputData"></param>
        /// <returns></returns>
        public static bool IsHasCHZN(string inputData)
        {
            Match m = RegCHZN.Match(inputData);

            return(m.Success);
        }
Example #39
0
        /// <summary>
        /// Returns true if the text passed is a public message written by a player on the chat
        /// </summary>
        /// <param name="text">text to test</param>
        /// <param name="message">if it's message, this will contain the message</param>
        /// <param name="sender">if it's message, this will contain the player name that sends the message</param>
        /// <returns>Returns true if the text is a chat message</returns>
        protected static bool IsChatMessage(string text, ref string message, ref string sender)
        {
            if (String.IsNullOrEmpty(text))
            {
                return(false);
            }

            text = GetVerbatim(text);

            //User-defined regex for public chat messages
            if (Settings.ChatFormat_Public != null)
            {
                Match regexMatch = Settings.ChatFormat_Public.Match(text);
                if (regexMatch.Success && regexMatch.Groups.Count >= 3)
                {
                    sender  = regexMatch.Groups[1].Value;
                    message = regexMatch.Groups[2].Value;
                    return(IsValidName(sender));
                }
            }

            //Built-in detection routine for public messages
            if (Settings.ChatFormat_Builtins)
            {
                string[] tmp = text.Split(' ');

                //Detect vanilla/factions Messages
                //<Someone> message
                //<*Faction Someone> message
                //<*Faction Someone>: message
                //<*Faction ~Nicknamed>: message
                if (text[0] == '<')
                {
                    try
                    {
                        text = text.Substring(1);
                        string[] tmp2 = text.Split('>');
                        sender  = tmp2[0];
                        message = text.Substring(sender.Length + 2);
                        if (message.Length > 1 && message[0] == ' ')
                        {
                            message = message.Substring(1);
                        }
                        tmp2   = sender.Split(' ');
                        sender = tmp2[tmp2.Length - 1];
                        if (sender[0] == '~')
                        {
                            sender = sender.Substring(1);
                        }
                        return(IsValidName(sender));
                    }
                    catch (IndexOutOfRangeException) { /* Not a vanilla/faction message */ }
                    catch (ArgumentOutOfRangeException) { /* Same here */ }
                }

                //Detect HeroChat Messages
                //Public chat messages
                //[Channel] [Rank] User: Message
                else if (text[0] == '[' && text.Contains(':') && tmp.Length > 2)
                {
                    try
                    {
                        int name_end   = text.IndexOf(':');
                        int name_start = text.Substring(0, name_end).LastIndexOf(']') + 2;
                        sender  = text.Substring(name_start, name_end - name_start);
                        message = text.Substring(name_end + 2);
                        return(IsValidName(sender));
                    }
                    catch (IndexOutOfRangeException) { /* Not a herochat message */ }
                    catch (ArgumentOutOfRangeException) { /* Same here */ }
                }

                //Detect (Unknown Plugin) Messages
                //**Faction<Rank> User : Message
                else if (text[0] == '*' &&
                         text.Length > 1 &&
                         text[1] != ' ' &&
                         text.Contains('<') && text.Contains('>') &&
                         text.Contains(' ') && text.Contains(':') &&
                         text.IndexOf('*') < text.IndexOf('<') &&
                         text.IndexOf('<') < text.IndexOf('>') &&
                         text.IndexOf('>') < text.IndexOf(' ') &&
                         text.IndexOf(' ') < text.IndexOf(':'))
                {
                    try
                    {
                        string prefix    = tmp[0];
                        string user      = tmp[1];
                        string semicolon = tmp[2];
                        if (prefix.All(c => char.IsLetterOrDigit(c) || new char[] { '*', '<', '>', '_' }.Contains(c)) &&
                            semicolon == ":")
                        {
                            message = text.Substring(prefix.Length + user.Length + 4);
                            return(IsValidName(user));
                        }
                    }
                    catch (IndexOutOfRangeException) { /* Not a <unknown plugin> message */ }
                    catch (ArgumentOutOfRangeException) { /* Same here */ }
                }
            }

            return(false);
        }
Example #40
0
        /// <summary>
        /// 是否是浮点数 可带正负号
        /// </summary>
        /// <param name="inputData">输入字符串</param>
        /// <returns></returns>
        public static bool IsEmail(string inputData)
        {
            Match m = RegEmail.Match(inputData);

            return(m.Success);
        }
Example #41
0
        private string Login(string emailAddress, string password)
        {
            try
            {
                Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "Logging into google.com for " + emailAddress + ".", m_username));

                // Fetch GALX
                HttpWebRequest galxRequest = (HttpWebRequest)WebRequest.Create(PRE_LOGIN_URL);
                galxRequest.ConnectionGroupName = "prelogin";
                galxRequest.CookieContainer     = m_cookies;

                HttpWebResponse galxResponse = (HttpWebResponse)galxRequest.GetResponse();
                if (galxResponse.StatusCode != HttpStatusCode.OK)
                {
                    galxResponse.Close();
                    throw new ApplicationException("Load of the Google Voice pre-login page failed with response " + galxResponse.StatusCode + ".");
                }
                else
                {
                    // The pre login URL can redirect to a different URL, such as accounts.google.com, need to use the cookies from that redirect when accessing www.google.com.
                    m_cookies.Add(new Uri(GOOGLE_COM_URL), galxResponse.Cookies);
                    Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "Google Voice pre-login page loaded successfully.", m_username));
                }

                StreamReader galxReader             = new StreamReader(galxResponse.GetResponseStream());
                string       galxResponseFromServer = galxReader.ReadToEnd();
                galxResponse.Close();

                Match galxMatch = Regex.Match(galxResponseFromServer, @"name=""GALX""[^>]+value=""(?<galxvalue>.*?)""");
                if (galxMatch.Success)
                {
                    Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "GALX key " + galxMatch.Result("${galxvalue}") + " successfully retrieved.", m_username));
                }
                else
                {
                    throw new ApplicationException("Could not find GALX key on your Google Voice pre-login page, SMS cannot proceed.");
                }

                Match gxfMatch = Regex.Match(galxResponseFromServer, @"name=""gxf""[^>]+value=""(?<gxfvalue>.*?)""", RegexOptions.IgnoreCase);
                if (gxfMatch.Success)
                {
                    Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "gxf key " + gxfMatch.Result("${gxfvalue}") + " successfully retrieved.", m_username));
                }
                else
                {
                    throw new ApplicationException("Could not find GXF key on your Google Voice pre-login page, callback cannot proceed.");
                }

                // Build login request.
                string         loginData    = "Email=" + Uri.EscapeDataString(emailAddress) + "&Passwd=" + Uri.EscapeDataString(password) + "&GALX=" + Uri.EscapeDataString(galxMatch.Result("${galxvalue}")) + "&gxf=" + Uri.EscapeDataString(gxfMatch.Result("${gxfvalue}"));
                HttpWebRequest loginRequest = (HttpWebRequest)WebRequest.Create(LOGIN_URL);
                loginRequest.CookieContainer     = m_cookies;
                loginRequest.ConnectionGroupName = "login";
                loginRequest.AllowAutoRedirect   = true;
                loginRequest.Method        = "POST";
                loginRequest.ContentType   = "application/x-www-form-urlencoded;charset=utf-8";
                loginRequest.ContentLength = loginData.Length;
                loginRequest.GetRequestStream().Write(Encoding.UTF8.GetBytes(loginData), 0, loginData.Length);
                loginRequest.Timeout = HTTP_REQUEST_TIMEOUT * 1000;

                // Send login request and read response stream.
                HttpWebResponse response = (HttpWebResponse)loginRequest.GetResponse();
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    response.Close();
                    throw new ApplicationException("Login to google.com failed for " + emailAddress + " with response " + response.StatusCode + ".");
                }
                response.Close();

                // We're now logged in. Need to load up the Google Voice page to get the rnr hidden input value which is needed for
                // the HTTP call requests.
                HttpWebRequest rnrRequest = (HttpWebRequest)WebRequest.Create(VOICE_HOME_URL);
                rnrRequest.ConnectionGroupName = "call";
                rnrRequest.CookieContainer     = m_cookies;

                // Send the Google Voice account page request and read response stream.
                response = (HttpWebResponse)rnrRequest.GetResponse();
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    response.Close();
                    throw new ApplicationException("Load of the Google Voice account page failed for " + emailAddress + " with response " + response.StatusCode + ".");
                }
                else
                {
                    Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "Google Voice home page loaded successfully.", m_username));
                }

                StreamReader reader             = new StreamReader(response.GetResponseStream());
                string       responseFromServer = reader.ReadToEnd();
                response.Close();

                // Extract the rnr field from the HTML.
                Match rnrMatch = Regex.Match(responseFromServer, @"name=""_rnr_se"".*?value=""(?<rnrvalue>.*?)""");
                if (rnrMatch.Success)
                {
                    return(rnrMatch.Result("${rnrvalue}"));
                }
                else
                {
                    throw new ApplicationException("Could not find _rnr_se key on your Google Voice account page, SMS cannot proceed.");
                }
            }
            catch (Exception excp)
            {
                logger.Error("Exception GoogleVoiceSMS Login. " + excp.Message);
                throw;
            }
        }
Example #42
0
        private string FirstWordOf(string s)
        {
            Match match = _findFirstWordRegex.Match(s);

            return(match.Value);
        }
Example #43
0
        public String HandlePart(Match m, String part, CellFormatType type, StringBuilder descBuf)
        {
            int  pos     = descBuf.Length;
            char firstCh = part[0];

            switch (firstCh)
            {
            case 'e':
            case 'E':
                // See comment in WriteScientific -- exponent handling is complex.
                // (1) When parsing the format, remove the sign from After the 'e' and
                // Put it before the first digit of the exponent.
                if (exponent == null && specials.Count > 0)
                {
                    exponent = new Special('.', pos);
                    specials.Add(exponent);
                    insertSignForExponent = part[1];
                    return(part.Substring(0, 1));
                }
                break;

            case '0':
            case '?':
            case '#':
                if (insertSignForExponent != '\0')
                {
                    specials.Add(new Special(insertSignForExponent, pos));
                    descBuf.Append(insertSignForExponent);
                    insertSignForExponent = '\0';
                    pos++;
                }
                for (int i = 0; i < part.Length; i++)
                {
                    char ch = part[i];
                    specials.Add(new Special(ch, pos + i));
                }
                break;

            case '.':
                if (decimalPoint == null && specials.Count > 0)
                {
                    decimalPoint = new Special('.', pos);
                    specials.Add(decimalPoint);
                }
                break;

            case '/':
                //!! This assumes there is a numerator and a denominator, but these are actually optional
                if (slash == null && specials.Count > 0)
                {
                    numerator = PreviousNumber();
                    // If the first number in the whole format is the numerator, the
                    // entire number should be printed as an improper fraction
                    improperFraction |= (numerator == FirstDigit(specials));
                    slash             = new Special('.', pos);
                    specials.Add(slash);
                }
                break;

            case '%':
                // don't need to remember because we don't need to do anything with these
                scale *= 100;
                break;

            default:
                return(null);
            }
            return(part);
        }
Example #44
0
        /// <summary>
        /// Returns true if the text passed is a private message sent to the bot
        /// </summary>
        /// <param name="text">text to test</param>
        /// <param name="message">if it's a private message, this will contain the message</param>
        /// <param name="sender">if it's a private message, this will contain the player name that sends the message</param>
        /// <returns>Returns true if the text is a private message</returns>
        protected static bool IsPrivateMessage(string text, ref string message, ref string sender)
        {
            if (String.IsNullOrEmpty(text))
            {
                return(false);
            }

            text = GetVerbatim(text);

            //User-defined regex for private chat messages
            if (Settings.ChatFormat_Private != null)
            {
                Match regexMatch = Settings.ChatFormat_Private.Match(text);
                if (regexMatch.Success && regexMatch.Groups.Count >= 3)
                {
                    sender  = regexMatch.Groups[1].Value;
                    message = regexMatch.Groups[2].Value;
                    return(IsValidName(sender));
                }
            }

            //Built-in detection routine for private messages
            if (Settings.ChatFormat_Builtins)
            {
                string[] tmp = text.Split(' ');
                try
                {
                    //Detect vanilla /tell messages
                    //Someone whispers message (MC 1.5)
                    //Someone whispers to you: message (MC 1.7)
                    if (tmp.Length > 2 && tmp[1] == "whispers")
                    {
                        if (tmp.Length > 4 && tmp[2] == "to" && tmp[3] == "you:")
                        {
                            message = text.Substring(tmp[0].Length + 18); //MC 1.7
                        }
                        else
                        {
                            message = text.Substring(tmp[0].Length + 10);  //MC 1.5
                        }
                        sender = tmp[0];
                        return(IsValidName(sender));
                    }

                    //Detect Essentials (Bukkit) /m messages
                    //[Someone -> me] message
                    //[~Someone -> me] message
                    else if (text[0] == '[' && tmp.Length > 3 && tmp[1] == "->" &&
                             (tmp[2].ToLower() == "me]" || tmp[2].ToLower() == "moi]"))   //'me' is replaced by 'moi' in french servers
                    {
                        message = text.Substring(tmp[0].Length + 4 + tmp[2].Length + 1);
                        sender  = tmp[0].Substring(1);
                        if (sender[0] == '~')
                        {
                            sender = sender.Substring(1);
                        }
                        return(IsValidName(sender));
                    }

                    //Detect Modified server messages. /m
                    //[Someone @ me] message
                    else if (text[0] == '[' && tmp.Length > 3 && tmp[1] == "@" &&
                             (tmp[2].ToLower() == "me]" || tmp[2].ToLower() == "moi]"))   //'me' is replaced by 'moi' in french servers
                    {
                        message = text.Substring(tmp[0].Length + 4 + tmp[2].Length + 0);
                        sender  = tmp[0].Substring(1);
                        if (sender[0] == '~')
                        {
                            sender = sender.Substring(1);
                        }
                        return(IsValidName(sender));
                    }

                    //Detect Essentials (Bukkit) /me messages with some custom prefix
                    //[Prefix] [Someone -> me] message
                    //[Prefix] [~Someone -> me] message
                    else if (text[0] == '[' && tmp[0][tmp[0].Length - 1] == ']' &&
                             tmp[1][0] == '[' && tmp.Length > 4 && tmp[2] == "->" &&
                             (tmp[3].ToLower() == "me]" || tmp[3].ToLower() == "moi]"))
                    {
                        message = text.Substring(tmp[0].Length + 1 + tmp[1].Length + 4 + tmp[3].Length + 1);
                        sender  = tmp[1].Substring(1);
                        if (sender[0] == '~')
                        {
                            sender = sender.Substring(1);
                        }
                        return(IsValidName(sender));
                    }

                    //Detect Essentials (Bukkit) /me messages with some custom rank
                    //[Someone [rank] -> me] message
                    //[~Someone [rank] -> me] message
                    else if (text[0] == '[' && tmp.Length > 3 && tmp[2] == "->" &&
                             (tmp[3].ToLower() == "me]" || tmp[3].ToLower() == "moi]"))
                    {
                        message = text.Substring(tmp[0].Length + 1 + tmp[1].Length + 4 + tmp[2].Length + 1);
                        sender  = tmp[0].Substring(1);
                        if (sender[0] == '~')
                        {
                            sender = sender.Substring(1);
                        }
                        return(IsValidName(sender));
                    }

                    //Detect HeroChat PMsend
                    //From Someone: message
                    else if (text.StartsWith("From "))
                    {
                        sender  = text.Substring(5).Split(':')[0];
                        message = text.Substring(text.IndexOf(':') + 2);
                        return(IsValidName(sender));
                    }
                    else
                    {
                        return(false);
                    }
                }
                catch (IndexOutOfRangeException) { /* Not an expected chat format */ }
                catch (ArgumentOutOfRangeException) { /* Same here */ }
            }

            return(false);
        }
Example #45
0
 public static Order IsLargerThanRE(decimal threshold)
 {
     return(Match.Create <Order>(order => order.MetricTons < threshold, () => Order.IsLargerThanRE(threshold)));
 }
        public static void Main(string[] args)
        {
            string tainted_2 = null;
            string tainted_3 = null;


            Process process = new Process();

            process.StartInfo.FileName               = "/bin/bash";
            process.StartInfo.Arguments              = "-c 'cat /tmp/tainted.txt'";
            process.StartInfo.UseShellExecute        = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.Start();

            using (StreamReader reader = process.StandardOutput) {
                tainted_2 = reader.ReadToEnd();
                process.WaitForExit();
                process.Close();
            }

            tainted_3 = tainted_2;

            if ((Math.Sqrt(42) <= 42))
            {
                {}
            }
            else if (!(Math.Sqrt(42) <= 42))
            {
                string pattern = @"/^[0-9]*$/";
                Regex  r       = new Regex(pattern);
                Match  m       = r.Match(tainted_2);
                if (!m.Success)
                {
                    tainted_3 = "";
                }
                else
                {
                    tainted_3 = tainted_2;
                }
            }

            //flaw

            string query = "SELECT * FROM '" + tainted_3 + "'";


            string           connectionString = "Server=localhost;port=1337;User Id=postgre_user;Password=postgre_password;Database=dbname";
            NpgsqlConnection dbConnection     = null;

            try{
                dbConnection = new NpgsqlConnection(connectionString);
                dbConnection.Open();
                NpgsqlCommand    cmd = new NpgsqlCommand(query, dbConnection);
                NpgsqlDataReader dr  = cmd.ExecuteReader();
                while (dr.Read())
                {
                    Console.Write("{0}\n", dr[0]);
                }
                dbConnection.Close();
            }catch (Exception e) {
                Console.WriteLine(e.ToString());
            }
        }
Example #47
0
 public static Order IsLargeRE()
 {
     return(Match.Create <Order>(order => order.MetricTons >= 1000M, () => Order.IsLargeRE()));
 }
Example #48
0
 public static Order PretendIsAny()
 {
     return(Match.Create <Order>(order => false, () => It.IsAny <Order>()));
 }
Example #49
0
 public static Order IsSmallRE()
 {
     return(Match.Create <Order>(order => order.MetricTons < 1000M, () => Order.IsSmallRE()));
 }
Example #50
0
 public static Order IsLargerThan(decimal threshold)
 {
     return(Match.Create <Order>(order => order.MetricTons > threshold));
 }
Example #51
0
        };                                                                         //if user name is in blacklist, than previous two lines limit is treated as 1

        static void Main(string[] args)
        {
            using (TikSession session = new TikSession(TikConnectorType.Api))
            {
                session.Open(HOST, USER, PASS);

                //load potential login errors
                LogList logItems = new LogList();
                logItems.LoadByTopics("system,error,critical");

                //load actual addresslist
                FirewallAddressListList addrListItems = new FirewallAddressListList();
                addrListItems.LoadByList(DROP_ADDR_LIST);

                //Find all logon erros (possible atack)
                Dictionary <string, Dictionary <string, int> > atacksPerIp = new Dictionary <string, Dictionary <string, int> >(); //<ip, <user, cnt>>
                foreach (Log log in logItems)
                {
                    Match match = loginErrorRegex.Match(log.Message);
                    if (match.Success) //is logon error format
                    {
                        string atackerIp         = match.Groups["IP"].Value;
                        string atackerTechnology = match.Groups["CONN"].Value;
                        string atackerLogin      = match.Groups["USER"].Value;
                        if (!atackerIp.StartsWith(IP_PREFIX_WHITELIST, StringComparison.OrdinalIgnoreCase))      //IP is not in white-list
                        {
                            if (checkedTechnology.Contains(atackerTechnology, StringComparer.OrdinalIgnoreCase)) //technology is in checked list (should be handled)
                            {
                                if (!atacksPerIp.ContainsKey(atackerIp))
                                {
                                    atacksPerIp.Add(atackerIp, new Dictionary <string, int>());
                                }

                                if (!atacksPerIp[atackerIp].ContainsKey(atackerLogin))
                                {
                                    atacksPerIp[atackerIp].Add(atackerLogin, 0);
                                }

                                atacksPerIp[atackerIp][atackerLogin] = atacksPerIp[atackerIp][atackerLogin] + 1;
                            }
                        }
                    }

                    //Disable all atackers
                    foreach (KeyValuePair <string, Dictionary <string, int> > atackFromIp in atacksPerIp)
                    {
                        if (atackFromIp.Value.Keys.Any(login => LOGIN_BLACKLIST.Contains(login)) || //in blacklist
                            atackFromIp.Value.Keys.Count >= CNT_OF_LOGINS_PER_IP_LIMIT ||
                            atackFromIp.Value.Any(p => p.Value >= CNT_OF_ERRORS_PER_LOGIN_LIMIT))
                        {
                            //should be disabled
                            if (!addrListItems.Any(i => i.Address == atackFromIp.Key))
                            {
                                //not already in disabled list
                                addrListItems.Add(new FirewallAddressList()
                                {
                                    Address  = atackFromIp.Key,
                                    Disabled = false,
                                    List     = DROP_ADDR_LIST
                                });
                            }
                        }
                    }

                    if (addrListItems.IsModified)
                    {
                        addrListItems.Save();
                    }
                }
            }
        }
Example #52
0
 public static Order IsLarge()
 {
     return(Match.Create <Order>(order => order.MetricTons >= 1000M));
 }
Example #53
0
 static string MakeSafe(Match m)
 {
   var c = m.Value[0];
   return string.Format("%{0:X}{1:X}", c / 16, c % 16);
 }
Example #54
0
 public static Order IsSmall()
 {
     return(Match.Create <Order>(order => order.MetricTons < 1000M));
 }
Example #55
0
        /// <summary>
        /// Parses a string that represents a date.
        /// </summary>
        /// <param name="date">A string containing the value to be converted.   </param>
        /// <param name="result">A container for a successfully-parsed date.  </param>
        /// <param name="cultureInfo">The culture that should be used to parse the string.</param>
        /// <returns>True if the date string was successfully parsed; otherwise, false.  </returns>
        /// <remarks>
        ///  If the string can be parsed,
        /// the result parameter is set to an CuiDate object corresponding to
        /// the parsed dateString. If the string cannot be parsed, the result parameter is set to DateTime.MinValue.
        /// </remarks>
        public static bool TryParseExact(string date, out CuiDate result, CultureInfo cultureInfo)
        {
            // check for true null
            if (string.IsNullOrEmpty(date))
            {
                result          = new CuiDate();
                result.DateType = DateType.Null;
                return(true);
            }

            // first check for numeric year month as this can be confused as a date
            Regex numericYearMonthRegEx        = new Regex("^(?<Month>0?[1-9]|10|11|12)[-\\s/](?<Year>\\d{4}|\\d{2})$");
            Match numericYearMonthRegExResults = numericYearMonthRegEx.Match(date);

            if (numericYearMonthRegExResults.Success)
            {
                result          = new CuiDate();
                result.DateType = DateType.YearMonth;
                result.Month    = int.Parse(numericYearMonthRegExResults.Groups["Month"].Value, cultureInfo);
                result.Year     = CuiDate.ParseYear(numericYearMonthRegExResults.Groups["Year"].Value, cultureInfo);

                return(true);
            }

            // check to see if approx indicator is present
            bool approxIndicatorPresent = (date.IndexOf(Resources.CuiDateResources.Approximate, StringComparison.CurrentCultureIgnoreCase) >= 0);

            if (approxIndicatorPresent)
            {
                date = date.Replace(Resources.CuiDateResources.Approximate, string.Empty).Trim();
            }

            // try datetime parse with our standard formats
            GlobalizationService gs = new GlobalizationService();

            string[] standardFormats = new string[]
            {
                gs.ShortDatePattern,
                gs.ShortDatePatternWithDayOfWeek,
            };

            DateTime parsedDateTime;

            if (DateTime.TryParseExact(date, standardFormats, cultureInfo, DateTimeStyles.None, out parsedDateTime))
            {
                result          = new CuiDate(parsedDateTime);
                result.DateType = (approxIndicatorPresent ? DateType.Approximate : DateType.Exact);
                return(true);
            }

            // Check if 'date' is a year and a month
            Regex yearMonthRegEx = BuildMonthYearRegEx(cultureInfo);
            Match yearMonthMatch = yearMonthRegEx.Match(date);

            // Regex doesn't take care of year as zero
            if (yearMonthMatch.Success && CuiDate.ParseYear(yearMonthMatch.Groups["Year"].Value, cultureInfo) > 0)
            {
                int month = GetMonthNumberFromMonthName(yearMonthMatch.Groups["Month"].Value, cultureInfo);
                int year  = CuiDate.ParseYear(yearMonthMatch.Groups["Year"].Value, cultureInfo);
                result = new CuiDate(year, month);
                return(true);
            }

            // Check if 'date' is a year
            Regex yearRegEx = new Regex(@"^(\d{4}|\d{2})$");

            // Regex doesn't take care of year as zero
            if (yearRegEx.IsMatch(date) && CuiDate.ParseYear(date, cultureInfo) > 0)
            {
                result = new CuiDate(CuiDate.ParseYear(date, cultureInfo));
                return(true);
            }

            // Check if 'date' is a Null date
            Regex nullDateRegEx = new Regex(@"^Null:(?<Index>-?\d+)$", RegexOptions.IgnoreCase);

            Match match = nullDateRegEx.Match(date);

            if (match.Success)
            {
                // Pull the numeric Index text and see if it is in range
                int nullIndex;

                if (int.TryParse(match.Groups[1].Captures[0].Value, out nullIndex))
                {
                    if (nullIndex >= MinimumNullIndex && nullIndex <= MaximumNullIndex)
                    {
                        result           = new CuiDate();
                        result.NullIndex = nullIndex;
                        result.DateType  = DateType.NullIndex;

                        return(true);
                    }
                }
            }

            // try alternative formats
            string[] alternativeFormats = new string[]
            {
                "d-MMM-yyyy", "d-M-yyyy", "d-MM-yyyy", "d-MMMM-yyyy",
                "d/MMM/yyyy", "d/M/yyyy", "d/MM/yyyy", "d/MMMM/yyyy",
                "d MMM yyyy", "d M yyyy", "d MM yyyy", "d MMMM yyyy",
                "ddd d-MMM-yyyy", "ddd d-M-yyyy", "ddd d-MM-yyyy", "ddd d-MMMM-yyyy",
                "ddd d/MMM/yyyy", "ddd d/M/yyyy", "ddd d/MM/yyyy", "ddd d/MMMM/yyyy",
                "ddd d MMM yyyy", "ddd d M yyyy", "ddd d MM yyyy", "ddd d MMMM yyyy",
                "d-MMM-yy", "d-M-yy", "d-MM-yy", "d-MMMM-yy",
                "d/MMM/yy", "d/M/yy", "d/MM/yy", "d/MMMM/yy",
                "d MMM yy", "d M yy", "d MM yy", "d MMMM yy",
                "ddd d-MMM-yy", "ddd d-M-yy", "ddd d-MM-yy", "ddd d-MMMM-yy",
                "ddd d/MMM/yy", "ddd d/M/yy", "ddd d/MM/yy", "ddd d/MMMM/yy",
                "ddd d MMM yy", "ddd d M yy", "ddd d MM yy", "ddd d MMMM yy"
            };

            if (DateTime.TryParseExact(date, alternativeFormats, cultureInfo, DateTimeStyles.None, out parsedDateTime))
            {
                result          = new CuiDate(parsedDateTime);
                result.DateType = (approxIndicatorPresent ? DateType.Approximate : DateType.Exact);
                return(true);
            }

            // no match
            result = null;
            return(false);
        }
        /// <summary>
        /// Returns beatmapFilter delegate for specified searchWord.
        /// Unimplemented: key/keys/speed/played/unplayed
        ///  </summary>
        /// <param name="searchWord"></param>
        /// <returns></returns>
        private searchFilter GetSearchFilter(string searchWord)
        {
            Match match = regComparison.Match(searchWord);

            if (match.Success)
            {
                string key = match.Groups[1].Value.ToLower();
                string op  = match.Groups[2].Value;
                string val = match.Groups[3].Value.ToLower();
                if (op == @"=")
                {
                    op = @"==";
                }

                double num;

                Match matchNum = regNumber.Match(val);
                if (matchNum.Success)
                {
                    num = Double.Parse(matchNum.Groups[0].Value, nfi);
                    switch (key)
                    {
                    case "star":
                    case "stars":
                        return(delegate(Beatmap b) { return isPatternMatch(Math.Round(GetStars(b), 2), op, num); });

                    case "cs":
                        return(delegate(Beatmap b) { return isPatternMatch(Math.Round((double)b.CircleSize, 1), op, num) && b.PlayMode != PlayMode.OsuMania && b.PlayMode != PlayMode.Taiko; });

                    case "hp":
                        return(delegate(Beatmap b) { return isPatternMatch(Math.Round((double)b.HpDrainRate, 1), op, num); });

                    case "od":
                        return(delegate(Beatmap b) { return isPatternMatch(Math.Round((double)b.OverallDifficulty, 1), op, num); });

                    case "ar":
                        return(delegate(Beatmap b) { return isPatternMatch(Math.Round((double)b.ApproachRate, 1), op, num) && b.PlayMode != PlayMode.OsuMania && b.PlayMode != PlayMode.Taiko; });

                    case "key":
                    case "keys":
                        return(delegate(Beatmap b) { return isPatternMatch(Math.Round((double)b.CircleSize, 1), op, num) && b.PlayMode == PlayMode.OsuMania; });

                    case "speed":
                        return(delegate(Beatmap b) { return RetFalse(); });

                    case "bpm":
                        return(delegate(Beatmap b) { return isPatternMatch(Math.Round(b.MinBpm), op, num); });

                    case "length":
                        return(delegate(Beatmap b) { return isPatternMatch(b.TotalTime / 1000, op, num); });

                    case "drain":
                        return(delegate(Beatmap b) { return isPatternMatch(b.DrainingTime, op, num); });

                    case "played":
                        break;
                    }
                }

                switch (key)
                {
                case "mods":
                    var  splitMods = Regex.Split(val, @"([A-Za-z]{2})").Where(s => !string.IsNullOrEmpty(s)).ToList();
                    Mods mods      = Mods.Omod;
                    foreach (var mod in splitMods)
                    {
                        if (Enum.TryParse(mod, true, out Mods parsedMod))
                        {
                            mods |= parsedMod;
                        }
                    }
                    CurrentMods = mods;
                    return(null);

                case "artist":
                    var artist = val.Replace(SpaceReplacement, " ");
                    return(delegate(Beatmap b) { return isArtistMatch(b, artist); });

                case "title":
                    var title = val.Replace(SpaceReplacement, " ");
                    return(delegate(Beatmap b) { return isTitleMatch(b, title); });

                case "unplayed":
                    if (String.IsNullOrEmpty(val))
                    {
                        return delegate { return RetFalse(); }
                    }
                    ;
                    break;

                case "mode":
                    num             = descriptorToNum(val, ModePairs);
                    CurrentPlayMode = (PlayMode)num;
                    return(delegate(Beatmap b) { return isPatternMatch((double)b.PlayMode, op, num); });

                case "status":
                    num = descriptorToNum(val, StatusPairs);

                    return(delegate(Beatmap b) { return isPatternMatch((double)b.State, op, num); });
                }
            }
            int id;

            if (Int32.TryParse(searchWord, out id))
            {
                if (BeatmapExtensionIsUsed)
                {
                    return(delegate(Beatmap b)
                    {
                        //match mapid and mapset id while input is numbers.
                        if (b.MapId == id)
                        {
                            return true;
                        }
                        if (b.MapSetId == id)
                        {
                            return true;
                        }
                        if (b.ThreadId == id)
                        {
                            return true;
                        }
                        return isWordMatch((BeatmapExtension)b, searchWord);
                    });
                }
                else
                {
                    return(delegate(Beatmap b)
                    {
                        //match mapid and mapset id while input is numbers.
                        if (b.MapId == id)
                        {
                            return true;
                        }
                        if (b.MapSetId == id)
                        {
                            return true;
                        }
                        if (b.ThreadId == id)
                        {
                            return true;
                        }
                        return isWordMatch(b, searchWord);
                    });
                }
            }
            if (BeatmapExtensionIsUsed)
            {
                return delegate(Beatmap b) { return isWordMatch((BeatmapExtension)b, searchWord); }
            }
            ;
            else
            {
                return delegate(Beatmap b) { return isWordMatch(b, searchWord); }
            };
        }
Example #57
0
        /// <summary>
        /// Mail-To-Weblog runs in background thread and this is the thread function.
        /// </summary>
        public void Run()
        {
            IBlogDataService    dataService    = null;
            ILoggingDataService loggingService = null;

            SiteConfig siteConfig = SiteConfig.GetSiteConfig(configPath);

            loggingService = LoggingDataServiceFactory.GetService(logPath);
            dataService    = BlogDataServiceFactory.GetService(contentPath, loggingService);


            ErrorTrace.Trace(System.Diagnostics.TraceLevel.Info, "MailToWeblog thread spinning up");

            loggingService.AddEvent(new EventDataItem(EventCodes.Pop3ServiceStart, "", ""));

            do
            {
                try
                {
                    // reload on every cycle to get the current settings
                    siteConfig     = SiteConfig.GetSiteConfig(configPath);
                    loggingService = LoggingDataServiceFactory.GetService(logPath);
                    dataService    = BlogDataServiceFactory.GetService(contentPath, loggingService);


                    if (siteConfig.EnablePop3 &&
                        siteConfig.Pop3Server != null && siteConfig.Pop3Server.Length > 0 &&
                        siteConfig.Pop3Username != null && siteConfig.Pop3Username.Length > 0)
                    {
                        Pop3 pop3 = new Pop3();


                        try
                        {
                            pop3.host     = siteConfig.Pop3Server;
                            pop3.userName = siteConfig.Pop3Username;
                            pop3.password = siteConfig.Pop3Password;

                            pop3.Connect();
                            pop3.Login();
                            pop3.GetAccountStat();

                            for (int j = pop3.messageCount; j >= 1; j--)
                            {
                                Pop3Message message = pop3.GetMessage(j);

                                string messageFrom;
                                // [email protected] 1-MAR-04
                                // only delete those messages that are processed
                                bool messageWasProcessed = false;

                                // E-Mail addresses look usually like this:
                                // My Name <*****@*****.**> or simply
                                // [email protected]. This block handles
                                // both variants.
                                Regex getEmail   = new Regex(".*\\<(?<email>.*?)\\>.*");
                                Match matchEmail = getEmail.Match(message.from);
                                if (matchEmail.Success)
                                {
                                    messageFrom = matchEmail.Groups["email"].Value;
                                }
                                else
                                {
                                    messageFrom = message.from;
                                }

                                // Only if the subject of the message is prefixed (case-sensitive) with
                                // the configured subject prefix, we accept the message
                                if (message.subject.StartsWith(siteConfig.Pop3SubjectPrefix))
                                {
                                    Entry entry = new Entry();
                                    entry.Initialize();
                                    entry.Title      = message.subject.Substring(siteConfig.Pop3SubjectPrefix.Length);
                                    entry.Categories = "";
                                    entry.Content    = "";
                                    entry.Author     = messageFrom;                                 //store the email, what we have for now...

                                    // Grab the categories. Categories are defined in square brackets
                                    // in the subject line.
                                    Regex categoriesRegex = new Regex("(?<exp>\\[(?<cat>.*?)\\])");
                                    foreach (Match match in categoriesRegex.Matches(entry.Title))
                                    {
                                        entry.Title       = entry.Title.Replace(match.Groups["exp"].Value, "");
                                        entry.Categories += match.Groups["cat"].Value + ";";
                                    }
                                    entry.Title = entry.Title.Trim();

                                    string   categories = "";
                                    string[] splitted   = entry.Categories.Split(';');
                                    for (int i = 0; i < splitted.Length; i++)
                                    {
                                        categories += splitted[i].Trim() + ";";
                                    }
                                    entry.Categories = categories.TrimEnd(';');


                                    entry.CreatedUtc = RFC2822Date.Parse(message.date);

                                    #region PLain Text
                                    // plain text?
                                    if (message.contentType.StartsWith("text/plain"))
                                    {
                                        entry.Content += message.body;
                                    }
                                    #endregion

                                    #region Just HTML
                                    // Luke Latimer 16-FEB-2004 ([email protected])
                                    // HTML only emails were not appearing
                                    else if (message.contentType.StartsWith("text/html"))
                                    {
                                        string messageText = "";

                                        // Note the email may still be encoded
                                        //messageText = QuotedCoding.DecodeOne(message.charset, "Q", message.body);
                                        messageText = message.body;

                                        // Strip the <body> out of the message (using code from below)
                                        Regex bodyExtractor = new Regex("<body.*?>(?<content>.*)</body>", RegexOptions.IgnoreCase | RegexOptions.Singleline);
                                        Match match         = bodyExtractor.Match(messageText);
                                        if (match != null && match.Success && match.Groups["content"] != null)
                                        {
                                            entry.Content += match.Groups["content"].Value;
                                        }
                                        else
                                        {
                                            entry.Content += messageText;
                                        }
                                    }
                                    #endregion

                                    // HTML/Text with attachments ?
                                    else if (
                                        message.contentType.StartsWith("multipart/alternative") ||
                                        message.contentType.StartsWith("multipart/related") ||
                                        message.contentType.StartsWith("multipart/mixed"))
                                    {
                                        Hashtable embeddedFiles = new Hashtable();
                                        ArrayList attachedFiles = new ArrayList();

                                        foreach (Attachment attachment in message.attachments)
                                        {
                                            // just plain text?
                                            if (attachment.contentType.StartsWith("text/plain"))
                                            {
                                                entry.Content += StringOperations.GetString(attachment.data);
                                            }

                                            // Luke Latimer 16-FEB-2004 ([email protected])
                                            // Allow for html-only attachments
                                            else if (attachment.contentType.StartsWith("text/html"))
                                            {
                                                // Strip the <body> out of the message (using code from below)
                                                Regex  bodyExtractor = new Regex("<body.*?>(?<content>.*)</body>", RegexOptions.IgnoreCase | RegexOptions.Singleline);
                                                string htmlString    = StringOperations.GetString(attachment.data);
                                                Match  match         = bodyExtractor.Match(htmlString);

                                                //NOTE: We will BLOW AWAY any previous content in this case.
                                                // This is because most mail clients like Outlook include
                                                // plain, then HTML. We will grab plain, then blow it away if
                                                // HTML is included later.
                                                if (match != null && match.Success && match.Groups["content"] != null)
                                                {
                                                    entry.Content = match.Groups["content"].Value;
                                                }
                                                else
                                                {
                                                    entry.Content = htmlString;
                                                }
                                            }

                                            // or alternative text ?
                                            else if (attachment.contentType.StartsWith("multipart/alternative"))
                                            {
                                                bool   contentSet  = false;
                                                string textContent = null;
                                                foreach (Attachment inner_attachment in attachment.attachments)
                                                {
                                                    // we prefer HTML
                                                    if (inner_attachment.contentType.StartsWith("text/plain"))
                                                    {
                                                        textContent = StringOperations.GetString(inner_attachment.data);
                                                    }
                                                    else if (inner_attachment.contentType.StartsWith("text/html"))
                                                    {
                                                        Regex  bodyExtractor = new Regex("<body.*?>(?<content>.*)</body>", RegexOptions.IgnoreCase | RegexOptions.Singleline);
                                                        string htmlString    = StringOperations.GetString(inner_attachment.data);
                                                        Match  match         = bodyExtractor.Match(htmlString);
                                                        if (match != null && match.Success && match.Groups["content"] != null)
                                                        {
                                                            entry.Content += match.Groups["content"].Value;
                                                        }
                                                        else
                                                        {
                                                            entry.Content += htmlString;
                                                        }
                                                        contentSet = true;
                                                    }
                                                }
                                                if (!contentSet)
                                                {
                                                    entry.Content += textContent;
                                                }
                                            }
                                            // or text with embeddedFiles (in a mixed message only)
                                            else if ((message.contentType.StartsWith("multipart/mixed") || message.contentType.StartsWith("multipart/alternative")) &&
                                                     attachment.contentType.StartsWith("multipart/related"))
                                            {
                                                foreach (Attachment inner_attachment in attachment.attachments)
                                                {
                                                    // just plain text?
                                                    if (inner_attachment.contentType.StartsWith("text/plain"))
                                                    {
                                                        entry.Content += StringOperations.GetString(inner_attachment.data);
                                                    }

                                                    else if (inner_attachment.contentType.StartsWith("text/html"))
                                                    {
                                                        Regex  bodyExtractor = new Regex("<body.*?>(?<content>.*)</body>", RegexOptions.IgnoreCase | RegexOptions.Singleline);
                                                        string htmlString    = StringOperations.GetString(inner_attachment.data);
                                                        Match  match         = bodyExtractor.Match(htmlString);
                                                        if (match != null && match.Success && match.Groups["content"] != null)
                                                        {
                                                            entry.Content += match.Groups["content"].Value;
                                                        }
                                                        else
                                                        {
                                                            entry.Content += htmlString;
                                                        }
                                                    }

                                                    // or alternative text ?
                                                    else if (inner_attachment.contentType.StartsWith("multipart/alternative"))
                                                    {
                                                        bool   contentSet  = false;
                                                        string textContent = null;
                                                        foreach (Attachment inner_inner_attachment in inner_attachment.attachments)
                                                        {
                                                            // we prefer HTML
                                                            if (inner_inner_attachment.contentType.StartsWith("text/plain"))
                                                            {
                                                                textContent = StringOperations.GetString(inner_inner_attachment.data);
                                                            }
                                                            else if (inner_inner_attachment.contentType.StartsWith("text/html"))
                                                            {
                                                                Regex  bodyExtractor = new Regex("<body.*?>(?<content>.*)</body>", RegexOptions.IgnoreCase | RegexOptions.Singleline);
                                                                string htmlString    = StringOperations.GetString(inner_inner_attachment.data);
                                                                Match  match         = bodyExtractor.Match(htmlString);
                                                                if (match != null && match.Success && match.Groups["content"] != null)
                                                                {
                                                                    entry.Content += match.Groups["content"].Value;
                                                                }
                                                                else
                                                                {
                                                                    entry.Content += htmlString;
                                                                }
                                                                contentSet = true;
                                                            }
                                                        }
                                                        if (!contentSet)
                                                        {
                                                            entry.Content += textContent;
                                                        }
                                                    }
                                                    // any other inner_attachment
                                                    else if (inner_attachment.data != null &&
                                                             inner_attachment.fileName != null &&
                                                             inner_attachment.fileName.Length > 0)
                                                    {
                                                        if (inner_attachment.contentID.Length > 0)
                                                        {
                                                            embeddedFiles.Add(inner_attachment.contentID, StoreAttachment(inner_attachment, binariesPath));
                                                        }
                                                        else
                                                        {
                                                            attachedFiles.Add(StoreAttachment(inner_attachment, binariesPath));
                                                        }
                                                    }
                                                }
                                            }
                                            // any other attachment
                                            else if (attachment.data != null &&
                                                     attachment.fileName != null &&
                                                     attachment.fileName.Length > 0)
                                            {
                                                if (attachment.contentID.Length > 0 && message.contentType.StartsWith("multipart/related"))
                                                {
                                                    embeddedFiles.Add(attachment.contentID, StoreAttachment(attachment, binariesPath));
                                                }
                                                else
                                                {
                                                    attachedFiles.Add(StoreAttachment(attachment, binariesPath));
                                                }
                                            }
                                        }


                                        // check for orphaned embeddings
                                        string[] embeddedKeys = new string[embeddedFiles.Keys.Count];
                                        embeddedFiles.Keys.CopyTo(embeddedKeys, 0);
                                        foreach (string key in embeddedKeys)
                                        {
                                            if (entry.Content.IndexOf("cid:" + key.Trim('<', '>')) == -1)
                                            {
                                                object file = embeddedFiles[key];
                                                embeddedFiles.Remove(key);
                                                attachedFiles.Add(file);
                                            }
                                        }


                                        // now fix up the URIs

                                        if (siteConfig.Pop3InlineAttachedPictures)
                                        {
                                            foreach (string fileName in attachedFiles)
                                            {
                                                string fileNameU = fileName.ToUpper();
                                                if (fileNameU.EndsWith(".JPG") || fileNameU.EndsWith(".JPEG") ||
                                                    fileNameU.EndsWith(".GIF") || fileNameU.EndsWith(".PNG") ||
                                                    fileNameU.EndsWith(".BMP"))
                                                {
                                                    bool scalingSucceeded = false;

                                                    if (siteConfig.Pop3InlinedAttachedPicturesThumbHeight > 0)
                                                    {
                                                        try
                                                        {
                                                            string absoluteFileName  = Path.Combine(binariesPath, fileName);
                                                            string thumbBaseFileName = Path.GetFileNameWithoutExtension(fileName) + "-thumb.dasblog.JPG";
                                                            string thumbFileName     = Path.Combine(binariesPath, thumbBaseFileName);
                                                            Bitmap sourceBmp         = new Bitmap(absoluteFileName);
                                                            if (sourceBmp.Height > siteConfig.Pop3InlinedAttachedPicturesThumbHeight)
                                                            {
                                                                Bitmap targetBmp = new Bitmap(sourceBmp, new Size(
                                                                                                  Convert.ToInt32(Math.Round((((double)sourceBmp.Width) * (((double)siteConfig.Pop3InlinedAttachedPicturesThumbHeight) / ((double)sourceBmp.Height))), 0)),
                                                                                                  siteConfig.Pop3InlinedAttachedPicturesThumbHeight));

                                                                ImageCodecInfo    codecInfo     = GetEncoderInfo("image/jpeg");
                                                                Encoder           encoder       = Encoder.Quality;
                                                                EncoderParameters encoderParams = new EncoderParameters(1);
                                                                long             compression    = 75;
                                                                EncoderParameter encoderParam   = new EncoderParameter(encoder, compression);
                                                                encoderParams.Param[0] = encoderParam;
                                                                targetBmp.Save(thumbFileName, codecInfo, encoderParams);

                                                                string absoluteUri      = new Uri(binariesBaseUri, fileName).AbsoluteUri;
                                                                string absoluteThumbUri = new Uri(binariesBaseUri, thumbBaseFileName).AbsoluteUri;
                                                                entry.Content   += String.Format("<div class=\"inlinedMailPictureBox\"><a href=\"{0}\"><img border=\"0\" class=\"inlinedMailPicture\" src=\"{2}\"></a><br /><a class=\"inlinedMailPictureLink\" href=\"{0}\">{1}</a></div>", absoluteUri, fileName, absoluteThumbUri);
                                                                scalingSucceeded = true;
                                                            }
                                                        }
                                                        catch
                                                        {
                                                        }
                                                    }
                                                    if (!scalingSucceeded)
                                                    {
                                                        string absoluteUri = new Uri(binariesBaseUri, fileName).AbsoluteUri;
                                                        entry.Content += String.Format("<div class=\"inlinedMailPictureBox\"><img class=\"inlinedMailPicture\" src=\"{0}\"><br /><a class=\"inlinedMailPictureLink\" href=\"{0}\">{1}</a></div>", absoluteUri, fileName);
                                                    }
                                                }
                                            }
                                        }

                                        if (attachedFiles.Count > 0)
                                        {
                                            entry.Content += "<p>";
                                        }

                                        foreach (string fileName in attachedFiles)
                                        {
                                            string fileNameU = fileName.ToUpper();
                                            if (!siteConfig.Pop3InlineAttachedPictures ||
                                                (!fileNameU.EndsWith(".JPG") && !fileNameU.EndsWith(".JPEG") &&
                                                 !fileNameU.EndsWith(".GIF") && !fileNameU.EndsWith(".PNG") &&
                                                 !fileNameU.EndsWith(".BMP")))
                                            {
                                                string absoluteUri = new Uri(binariesBaseUri, fileName).AbsoluteUri;
                                                entry.Content += String.Format("Download: <a href=\"{0}\">{1}</a><br />", absoluteUri, fileName);
                                            }
                                        }
                                        if (attachedFiles.Count > 0)
                                        {
                                            entry.Content += "</p>";
                                        }

                                        foreach (string key in embeddedFiles.Keys)
                                        {
                                            entry.Content = entry.Content.Replace("cid:" + key.Trim('<', '>'), new Uri(binariesBaseUri, (string)embeddedFiles[key]).AbsoluteUri);
                                        }
                                    }

                                    loggingService.AddEvent(
                                        new EventDataItem(
                                            EventCodes.Pop3EntryReceived, entry.Title,
                                            SiteUtilities.GetPermaLinkUrl(siteConfig, entry.EntryId), messageFrom));

                                    SiteUtilities.SaveEntry(entry, siteConfig, loggingService, dataService);

                                    ErrorTrace.Trace(System.Diagnostics.TraceLevel.Info,
                                                     String.Format("Message stored. From: {0}, Title: {1} as entry {2}",
                                                                   messageFrom, entry.Title, entry.EntryId));

                                    // give the XSS upstreamer a hint that things have changed
//                                    XSSUpstreamer.TriggerUpstreaming();

                                    // [email protected] (01-MAR-04)
                                    messageWasProcessed = true;
                                }
                                else
                                {
                                    // [email protected] (01-MAR-04)
                                    // logging every ignored email is apt
                                    // to fill up the event page very quickly
                                    // especially if only processed emails are
                                    // being deleted
                                    if (siteConfig.Pop3LogIgnoredEmails)
                                    {
                                        loggingService.AddEvent(
                                            new EventDataItem(
                                                EventCodes.Pop3EntryIgnored, message.subject,
                                                null, messageFrom));
                                    }
                                }
                                // [email protected] (01-MAR-04)
                                if (siteConfig.Pop3DeleteAllMessages || messageWasProcessed)
                                {
                                    if (!messageWasProcessed)
                                    {
                                        loggingService.AddEvent(
                                            new EventDataItem(
                                                EventCodes.Pop3EntryDiscarded, message.subject,
                                                null, messageFrom));
                                    }
                                    pop3.DeleteMessage(j);
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            ErrorTrace.Trace(System.Diagnostics.TraceLevel.Error, e);
                            loggingService.AddEvent(
                                new EventDataItem(
                                    EventCodes.Pop3ServerError, e.ToString().Replace("\n", "<br />"), null, null));
                        }
                        finally
                        {
                            pop3.Close();
                        }
                    }

                    Thread.Sleep(TimeSpan.FromSeconds(siteConfig.Pop3Interval));
                }
                catch (ThreadAbortException abortException)
                {
                    ErrorTrace.Trace(System.Diagnostics.TraceLevel.Info, abortException);
                    loggingService.AddEvent(new EventDataItem(EventCodes.Pop3ServiceShutdown, "", ""));
                    break;
                }
                catch (Exception e)
                {
                    // if the siteConfig can't be read, stay running regardless
                    // default wait time is 4 minutes in that case
                    Thread.Sleep(TimeSpan.FromSeconds(240));
                    ErrorTrace.Trace(System.Diagnostics.TraceLevel.Error, e);
                }
            }while (true);
            ErrorTrace.Trace(System.Diagnostics.TraceLevel.Info, "MailToWeblog thread terminating");
            loggingService.AddEvent(new EventDataItem(EventCodes.Pop3ServiceShutdown, "", ""));
        }
Example #58
0
        /// <summary>
        /// Adds a number of months, weeks, days or years to a date.
        /// </summary>
        /// <param name="sourceDate">The date to be added to. </param>
        /// <param name="instruction">Add instructions such as +2w to add 2 weeks or -3m to subtract 3 months. </param>
        /// <remarks>
        /// The operand can be positive or negative; if the operand is not included, it is assumed to be positive.
        /// </remarks>
        /// <exception cref="System.ArgumentNullException">If either argument is null.
        /// </exception>
        /// <exception cref="System.InvalidOperationException">If <see cref="P:Microsoft.Cui.Controls.Common.DateAndTime.CuiDate.DateType">DateType</see>
        /// is null. </exception>
        /// <exception cref="System.ArgumentException">If <see cref="P:Microsoft.Cui.Controls.Common.DateAndTime.CuiDate.DateType">DateType</see>
        /// is <see cref="P:Microsoft.Cui.Controls.Common.DateAndTime.CuiDate.Year">Year</see> and the unit in the instruction is
        /// not DateArithmeticResources.YearsUnit. Or if <see cref="P:Microsoft.Cui.Controls.Common.DateAndTime.CuiDate.DateType">DateType</see>
        /// is YearMonth and the unit in the instruction is
        /// not DateArithmeticResources.YearsUnit or DateArithmeticResources.MonthsUnit. Or if the instruction is not
        /// of the expected format.</exception>
        /// <exception cref="Microsoft.Cui.Controls.Common.DateAndTime.InvalidArithmeticSetException">If the set of letters in
        /// the DateArithmeticResources is not unique or if values are not each a single character long.
        /// </exception>
        /// <returns>A new CuiDate object. </returns>
        public static CuiDate Add(CuiDate sourceDate, string instruction)
        {
            if (instruction == null)
            {
                throw new ArgumentNullException("instruction");
            }

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

            // check the set of resource strings  used by this method are
            // valid
            if (!CheckArithmeticSetResources())
            {
                throw new InvalidArithmeticSetException(Resources.CuiDateResources.ArithmeticSetInvalidResources);
            }

            if (sourceDate.DateType == DateType.NullIndex)
            {
                throw new InvalidOperationException(Resources.CuiDateResources.AddNotAllowedForDateType);
            }

            if (CuiDate.IsAddValid(instruction) == false)
            {
                throw new ArgumentException(Resources.CuiDateResources.AddInstructionInvalidFormat, "instruction");
            }

            Regex shortcut = new Regex(CuiDate.ResolveAddInstructionRegExTokens(), RegexOptions.IgnoreCase);

            Match match = shortcut.Match(instruction.Replace(" ", string.Empty));

            if (match.Success == true)
            {
                // We need to skip the first group because with this RegEx it is always the complete string
                int groupNumber = 0;

                foreach (Group g in match.Groups)
                {
                    if (groupNumber > 0)
                    {
                        foreach (Capture c in g.Captures)
                        {
                            int increment;

                            if (int.TryParse(c.Value.Substring(0, c.Value.Length - 1), out increment))
                            {
                                if (c.Value.EndsWith(Resources.CuiDateResources.MonthsUnit, StringComparison.OrdinalIgnoreCase) == true)
                                {
                                    if (sourceDate.DateType == DateType.Exact || sourceDate.DateType == DateType.Approximate)
                                    {
                                        sourceDate.DateValue = sourceDate.DateValue.AddMonths(increment);
                                    }
                                    else if (sourceDate.DateType == DateType.YearMonth)
                                    {
                                        sourceDate.Year  += increment / 12;
                                        sourceDate.Month += increment % 12;
                                    }
                                    else
                                    {
                                        throw new ArgumentException(
                                                  string.Format(CultureInfo.CurrentCulture, Resources.CuiDateResources.AddInstructionNotAllowedForDateType, "Month", sourceDate.DateType),
                                                  "instruction");
                                    }
                                }
                                else if (c.Value.EndsWith(Resources.CuiDateResources.WeeksUnit, StringComparison.OrdinalIgnoreCase) == true)
                                {
                                    if (sourceDate.DateType == DateType.Exact || sourceDate.DateType == DateType.Approximate)
                                    {
                                        // Add weeks using AddDays and multiplying number of weeks to add by 7
                                        sourceDate.DateValue = sourceDate.DateValue.AddDays(increment * 7);
                                    }
                                    else
                                    {
                                        throw new ArgumentException(
                                                  string.Format(CultureInfo.CurrentCulture, Resources.CuiDateResources.AddInstructionNotAllowedForDateType, "Week", sourceDate.DateType),
                                                  "instruction");
                                    }
                                }
                                else if (c.Value.EndsWith(Resources.CuiDateResources.DaysUnit, StringComparison.OrdinalIgnoreCase) == true)
                                {
                                    if (sourceDate.DateType == DateType.Exact || sourceDate.DateType == DateType.Approximate)
                                    {
                                        sourceDate.DateValue = sourceDate.DateValue.AddDays(increment);
                                    }
                                    else
                                    {
                                        throw new ArgumentException(
                                                  string.Format(CultureInfo.CurrentCulture, Resources.CuiDateResources.AddInstructionNotAllowedForDateType, "Day", sourceDate.DateType),
                                                  "instruction");
                                    }
                                }
                                else if (c.Value.EndsWith(Resources.CuiDateResources.YearsUnit, StringComparison.OrdinalIgnoreCase) == true)
                                {
                                    if (sourceDate.DateType == DateType.Exact || sourceDate.DateType == DateType.Approximate)
                                    {
                                        sourceDate.DateValue = sourceDate.DateValue.AddYears(increment);
                                    }
                                    else if (sourceDate.DateType == DateType.Year || sourceDate.DateType == DateType.YearMonth)
                                    {
                                        sourceDate.Year += increment;
                                    }
                                    else
                                    {
                                        throw new ArgumentException(
                                                  string.Format(CultureInfo.CurrentCulture, Resources.CuiDateResources.AddInstructionNotAllowedForDateType, "Year", sourceDate.DateType),
                                                  "instruction");
                                    }
                                }
                            }
                        }
                    }

                    groupNumber++;
                }
            }

            return(sourceDate);
        }
Example #59
0
        /// <summary>
        /// Evaluates a match.
        /// </summary>
        /// <param name="match">
        /// The match.
        /// </param>
        /// <param name="timeSpan">
        /// The time span.
        /// </param>
        /// <returns>
        /// The evaluate match.
        /// </returns>
        private string EvaluateMatch(Match match, TimeSpan timeSpan)
        {
            switch (match.Value)
            {
            case "DD":
                return(timeSpan.TotalDays.ToString("00"));

            case "D":
                return(timeSpan.TotalDays.ToString("0"));

            case "dd":
                return(timeSpan.Days.ToString("00"));

            case "d":
                return(timeSpan.Days.ToString("0"));

            case "HH":
                return(((int)timeSpan.TotalHours).ToString("00"));

            case "H":
                return(((int)timeSpan.TotalHours).ToString("0"));

            case "hh":
                return(timeSpan.Hours.ToString("00"));

            case "h":
                return(timeSpan.Hours.ToString("0"));

            case "MM":
                return(((int)timeSpan.TotalMinutes).ToString("00"));

            case "M":
                return(((int)timeSpan.TotalMinutes).ToString("0"));

            case "mm":
                return(timeSpan.Minutes.ToString("00"));

            case "m":
                return(timeSpan.Minutes.ToString("0"));

            case "SS":
                return(((int)timeSpan.TotalSeconds).ToString("00"));

            case "S":
                return(((int)timeSpan.TotalSeconds).ToString("0"));

            case "ss":
                return(timeSpan.Seconds.ToString("00"));

            case "s":
                return(timeSpan.Seconds.ToString("0"));

            case "fffffff":
                return((timeSpan.Milliseconds * 10000).ToString("0000000"));

            case "ffffff":
                return((timeSpan.Milliseconds * 1000).ToString("000000"));

            case "fffff":
                return((timeSpan.Milliseconds * 100).ToString("00000"));

            case "ffff":
                return((timeSpan.Milliseconds * 10).ToString("0000"));

            case "fff":
                return(timeSpan.Milliseconds.ToString("000"));

            case "ff":
                return((timeSpan.Milliseconds / 10).ToString("00"));

            case "f":
                return((timeSpan.Milliseconds / 100).ToString("0"));

            default:
                return(match.Value);
            }
        }
        public void DownloadAndSyncDashboard(Session epiSession, CommandLineParams o)
        {
            string file = Path.GetTempFileName();

            using (StreamWriter swLog = new StreamWriter(file))
            {
                swLog.WriteLine("Got in the Function");
                try
                {
                    epiSession["Customizing"] = false;
                    var oTrans             = new ILauncher(epiSession);
                    CustomizationVerify cm = new CustomizationVerify(epiSession);
                    swLog.WriteLine("Customization Verify");
                    string dll = cm.getDllName(o.Key2);
                    swLog.WriteLine("Got Epicor DLL");
                    StringBuilder refds          = new StringBuilder();
                    dynamic       epiBaseForm    = null;
                    dynamic       epiTransaction = null;
                    if (string.IsNullOrEmpty(dll))
                    {
                        dll = "*.UI.*.dll";
                    }


                    Assembly assy = ClientAssemblyRetriever.ForILaunch(oTrans).RetrieveAssembly(dll);
                    swLog.WriteLine("Finding File");
                    string s = "";

                    s = assy.Location;
                    var typeE     = assy.DefinedTypes.Where(r => r.FullName.ToUpper().Contains(o.Key2.ToUpper())).FirstOrDefault();
                    var typeTList = assy.DefinedTypes.Where(r => r.BaseType.Name.Equals("EpiTransaction")).ToList();

                    epiTransaction = new EpiTransaction(oTrans);



                    refds.AppendLine($"<Reference Include=\"{typeE.Assembly.FullName}\">");
                    refds.AppendLine($"<HintPath>{s}</HintPath>");
                    refds.AppendLine($"</Reference>");


                    var     typ      = assy.DefinedTypes.Where(r => r.Name == "Launch").FirstOrDefault();
                    dynamic launcher = Activator.CreateInstance(typ);
                    launcher.Session = epiSession;
                    launcher.GetType().GetMethod("InitializeLaunch", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(launcher, null);

                    epiBaseForm = launcher.GetType().GetField("lForm", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(launcher);
                    swLog.WriteLine("Initialize EpiUI Utils");
                    EpiUIUtils eu = epiBaseForm.GetType().GetField("utils", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(epiBaseForm);
                    eu.GetType().GetField("currentSession", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(eu, epiTransaction.Session);
                    eu.GetType().GetField("customizeName", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(eu, o.Key1);
                    eu.GetType().GetField("baseExtentionName", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(eu, o.Key3.Replace("BaseExtension^", string.Empty));
                    eu.ParentForm = epiBaseForm;
                    swLog.WriteLine("Get composite Customize Data Set");
                    var  mi        = eu.GetType().GetMethod("getCompositeCustomizeDataSet", BindingFlags.Instance | BindingFlags.NonPublic);
                    bool customize = false;
                    mi.Invoke(eu, new object[] { o.Key2, customize, customize, customize });
                    Ice.Adapters.GenXDataAdapter ad = new Ice.Adapters.GenXDataAdapter(epiTransaction);
                    ad.BOConnect();
                    GenXDataImpl i = (GenXDataImpl)ad.BusinessObject;
                    swLog.WriteLine("Customization Get By ID");
                    var             ds     = i.GetByID(o.Company, o.ProductType, o.LayerType, o.CSGCode, o.Key1, o.Key2, o.Key3);
                    string          beName = o.Key3.Replace("BaseExtension^", string.Empty);
                    string          exName = (string)eu.GetType().GetField("extensionName", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(eu);
                    CustomizationDS nds    = new CustomizationDS();


                    if (string.IsNullOrEmpty(o.Company))
                    {
                        eu.CustLayerMan.GetType().GetProperty("RetrieveFromCache", BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic).SetValue(eu.CustLayerMan, false);
                        eu.CustLayerMan.GetType().GetField("custAllCompanies", BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic).SetValue(eu.CustLayerMan, string.IsNullOrEmpty(o.Company));
                        eu.CustLayerMan.GetType().GetField("selectCompCode", BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic).SetValue(eu.CustLayerMan, o.Company);
                        eu.CustLayerMan.GetType().GetField("companyCode", BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic).SetValue(eu.CustLayerMan, o.Company);
                        eu.CustLayerMan.GetType().GetField("loadDeveloperMode", BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic).SetValue(eu.CustLayerMan, string.IsNullOrEmpty(o.Company));

                        bool cancel = false;
                        eu.CustLayerMan.GetType().GetMethod("GetCompositeCustomDataSet", BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic).Invoke(eu.CustLayerMan, new object[] { o.Key2, exName, o.Key1, cancel });
                    }


                    PersonalizeCustomizeManager csm = new PersonalizeCustomizeManager(epiBaseForm, epiTransaction, o.ProductType, o.Company, beName, exName, o.Key1, eu.CustLayerMan, DeveloperLicenseType.Partner, LayerType.Customization);

                    swLog.WriteLine("Init Custom Controls");
                    csm.InitCustomControlsAndProperties(ds, LayerName.CompositeBase, true);
                    CustomScriptManager csmR = csm.CurrentCustomScriptManager;
                    swLog.WriteLine("Generate Refs");
                    List <string> aliases = new List <string>();
                    Match         match   = Regex.Match(csmR.CustomCodeAll, "((?<=extern alias )(.*)*(?=;))");
                    while (match.Success)
                    {
                        aliases.Add(match.Value.Replace("_", ".").ToUpper());
                        match = match.NextMatch();
                    }
                    o.Version = ds.XXXDef[0].SysRevID;
                    GenerateRefs(refds, csmR, o, null);
                    ExportCustmization(nds, ad, o);
                    Resync(o, swLog, refds, ds, nds, csmR);



                    epiBaseForm.Dispose();


                    ad.Dispose();
                    cm = null;
                    eu.CloseCacheRespinSplash();
                    eu.Dispose();
                }
                catch (Exception ee)
                {
                    swLog.WriteLine(ee.ToString());
                }
            }


            //MessageBox.Show(file);
        }