예제 #1
0
파일: Form1.cs 프로젝트: nzldvd90/MidTermAP
        private void btnInterpretate_Click(object sender, EventArgs e)
        {
            try
            {

                Stopwatch timer = new Stopwatch();
                RegularExpression r;

                timer.Reset();
                timer.Start();
                r = new RegularExpression(txtRegEx.Text);
                timer.Stop();
                ReportResult("Parsing '" + txtRegEx.Text + "'", "SUCCESS", r.IsCompiled, timer);

                timer.Reset();
                timer.Start();
                bool result = r.IsMatch(txtInput.Text);
                timer.Stop();
                ReportResult("Matching '" + txtInput.Text + "'", result.ToString(), r.IsCompiled, timer);

                ReportData("Original Expression:\t" + r.OriginalExpression + "\r\nInfix Expression:\t" + r.FormattedExpression + "\r\nPostfix string:\t" + r.PostfixExpression + "\r\n\r\nNon Deterministic Automata has\t\t" + r.NDStateCount + " states.\r\nDeterministic Automata has\t\t" + r.DStateCount + " states.\r\nOptimized Deterministic Automata has\t" + r.OptimizedDStateCount + " states.");

                automataViewer1.Initialize(r);
            }
            catch (RegularExpressionParser.RegularExpressionParserException exc)
            {
                ReportError("PARSER ERROR", exc.ToString());
            }
            catch (Exception exc)
            {
                ReportError("EXCEPTION", exc.ToString());
            }
        }
예제 #2
0
        internal TokenInfo(RegularExpression definition, Lexicon lexicon, Lexer state, Token tag)
        {
            Lexicon = lexicon;
            Definition = definition;
            State = state;

            Tag = tag;
        }
예제 #3
0
        public static RegularExpression Derive(RegularExpression re, char a)
        {
            RegularExpression r, s;
            if (re.IsEmptyWord)
            {
                return CreateEmptySet();
            }
            else if (re.Value == a.ToString())
            {
                return new RegularExpression();
            }
            else if (re.Value.Length == 1 && !(re.Value == a.ToString()))
            {
                return CreateEmptySet();
            }
            else if (re.Value.Equals(RegularExpression.EMPTY_SET))
            {
                return CreateEmptySet();
            }
            else if (re.IsConcatenation)
            {
                re.GetConcatSubExpressions(out r, out s);
                return Derive(r, a).Concatenate(s).Union(v(r).Concatenate(Derive(s, a)));
            }
            else if (re.IsKleene)
            {
                string expUnderStar;
                if (re.Value[0] == '(')
                {
                    expUnderStar = re.Value.Substring(1, re.Value.Length - 3);
                }
                else
                {
                    expUnderStar = re.Value[0].ToString();
                }
                return Derive(new RegularExpression(expUnderStar), a).Concatenate(new RegularExpression(re.Value));
            }
            else if (re.IsPlus)
            {
                string expUnderPlus;
                if (re.Value[0] == '(')
                {
                    expUnderPlus = re.Value.Substring(1, re.Value.Length - 4);
                }
                else
                {
                    expUnderPlus = re.Value[0].ToString();
                }
                return Derive(new RegularExpression(expUnderPlus), a).Concatenate(new RegularExpression("(" + expUnderPlus + ")" + "*"));
            }
            else if (re.IsUnion)
            {
                re.GetUnionSubExpressions(out r, out s);
                return Derive(r, a).Union(Derive(s, a));
            }

            return null; //indicates error
        }
예제 #4
0
파일: Lexicon.cs 프로젝트: destinyclown/VBF
        internal TokenInfo AddToken(RegularExpression definition, Lexer state, int indexInState, string description)
        {
            int index = m_tokenList.Count;
            Token tag = new Token(index, description ?? definition.ToString(), state.Index);
            TokenInfo token = new TokenInfo(definition, this, state, tag);
            m_tokenList.Add(token);

            return token;
        }
예제 #5
0
파일: Lexer.cs 프로젝트: destinyclown/VBF
        public Token DefineToken(RegularExpression regex, string description)
        {
            CodeContract.RequiresArgumentNotNull(regex, "regex");

            int indexInState = m_tokens.Count;

            TokenInfo token = Lexicon.AddToken(regex, this, indexInState, description);
            m_tokens.Add(token);

            return token.Tag;
        }
예제 #6
0
파일: DFA.cs 프로젝트: pmichna/Finite
 public DFA(RegularExpression re)
 {
     States = new List<State>();
     InitState = new State(re, DFABuilder.IsExpressionFinal(re));
     InitState.QLabel = "q0";
     Transitions = new List<Transition>();
     States.Add(InitState);
     Alphabet = new HashSet<char>();
     foreach (char c in re.Value)
     {
         if (Char.IsLetter(c))
             Alphabet.Add(c);
     }
 }
예제 #7
0
 public static bool hasIgnoreCase(Hashtable table, String str)
 {
     RegularExpression rexp = null;
     if ((rexp = (RegularExpression) table[str]) != null &&
         !rexp.TokenProductionContext.IgnoreCase)
         return false;
     foreach (RegularExpression regularExpression in table.Values) {
         rexp = regularExpression;
         if (rexp.TokenProductionContext.IgnoreCase) {
             other = rexp;
             return true;
         }
     }
     return false;
 }
예제 #8
0
 public static bool hasIgnoreCase(IDictionary<string, RegularExpression> table, String str)
 {
     RegularExpression rexp;
     if (table.TryGetValue(str, out rexp) &&
         !rexp.TokenProductionContext.IgnoreCase)
         return false;
     foreach (var regularExpression in table.Values) {
         rexp = regularExpression;
         if (rexp.TokenProductionContext.IgnoreCase) {
             other = rexp;
             return true;
         }
     }
     return false;
 }
예제 #9
0
        public void ParseTest10()
        {
            var parser = new RegexParser();
            string pattern = ".*a.*";

            // Expected regular expression
            var anyCharacterBlock = new AnyCharacterBlock();
            var zeroOrOneBlock = new ZeroOrMoreBlock(anyCharacterBlock);
            var textBlock = new TextBlock("a");
            var groupBlock = new AndGroupBlock(new RegexBlock[] { zeroOrOneBlock, textBlock, zeroOrOneBlock });

            var expected = new RegularExpression(groupBlock);

            var actual = parser.Parse(pattern);
            Assert.IsTrue(expected.Equals(actual), "Pattern was parsed incorrectly");
        }
 public static void add_inline_regexpr(RegularExpression r)
 {
     if (!(r is REndOfFile)) {
         TokenProduction p = new TokenProduction();
         p.IsExplicit = false;
         p.LexStates = new String[] {"DEFAULT"};
         p.Kind = TokenProduction.TOKEN;
         RegExprSpec res = new RegExprSpec();
         res.RegularExpression = r;
         res.RegularExpression.TokenProductionContext = p;
         res.Action = new Action();
         res.NextState = null;
         res.NextStateToken = null;
         p.RegexSpecs.Add(res);
         CSharpCCGlobals.rexprlist.Add(p);
     }
 }
예제 #11
0
        public void ParseTest1()
        {
            var parser = new RegexParser();
            string pattern = "a+b+";

            // Expected regular expression
            var aBlock = new TextBlock("a");
            var bBlock = new TextBlock("b");
            var plusBlock1 = new OneOrMoreBlock(aBlock);
            var plusBlock2 = new OneOrMoreBlock(bBlock);

            var groupBlock = new AndGroupBlock(new RegexBlock[] { plusBlock1, plusBlock2 });

            var expected = new RegularExpression(groupBlock);

            var actual = parser.Parse(pattern);
            Assert.IsTrue(expected.Equals(actual), "Pattern was parsed incorrectly");
        }
예제 #12
0
        public void ParseTest11()
        {
            var parser = new RegexParser();
            string pattern = @".+(.)(.)(.)(.)\4\3\2\1.*";

            // Expected regular expression
            var anyCharacterBlock = new AnyCharacterBlock();
            var oneOrMoreBlock = new OneOrMoreBlock(anyCharacterBlock);
            var zeroOrOneBlock = new ZeroOrMoreBlock(anyCharacterBlock);
            var andGroupBlock = new AndGroupBlock(new [] { anyCharacterBlock });
            var b4 = new BackreferenceBlock(4);
            var b3 = new BackreferenceBlock(3);
            var b2 = new BackreferenceBlock(2);
            var b1 = new BackreferenceBlock(1);
            var groupBlock = new AndGroupBlock(new RegexBlock[] { oneOrMoreBlock, andGroupBlock, andGroupBlock, andGroupBlock, andGroupBlock, b4, b3, b2, b1, zeroOrOneBlock });

            var expected = new RegularExpression(groupBlock);

            var actual = parser.Parse(pattern);
            Assert.IsTrue(expected.Equals(actual), "Pattern was parsed incorrectly");
        }
예제 #13
0
 public void Initialize(RegularExpression regEx)
 {
     _automata = new Dictionary<string, string>();
     finalStates.Clear();
     foreach (var st in regEx.ParserAutomata.States)
     {
         foreach (var to in st.Transitions)
         {
             string key = st.ID + ":" + to.NextState.ID;
             string val = "";
             if(_automata.ContainsKey(key)){
                 val = _automata[key];
                 _automata.Remove(key);
             }
             if(val!="") val+=":";
             val += to.MatchedChar;
             _automata.Add(key,val);
         }
         if (st.IsFinal) finalStates.Add(st.ID);
     }
     stateCount = regEx.ParserAutomata.States.Length;
     this.Invalidate();
 }
예제 #14
0
파일: Form1.cs 프로젝트: nzldvd90/MidTermAP
        private void button2_Click(object sender, EventArgs e)
        {
            try
            {

                Stopwatch timer = new Stopwatch();
                RegularExpression r;

                // performance test of parsing RegEx
                timer.Reset();
                timer.Start();
                r = new RegularExpression(txtRegEx.Text);
                timer.Stop();

                ReportData("Original Expression:\t" + r.OriginalExpression + "\r\nInfix Expression:\t" + r.FormattedExpression + "\r\nPostfix string:\t" + r.PostfixExpression + "\r\n\r\nNon Deterministic Automata has\t\t" + r.NDStateCount + " states.\r\nDeterministic Automata has\t\t" + r.DStateCount + " states.\r\nOptimized Deterministic Automata has\t" + r.OptimizedDStateCount + " states.");
                ReportResult("Parsing '" + txtRegEx.Text + "'", "SUCCESS", r.IsCompiled, timer);

                // performance test of compile MyRegEx class
                timer.Reset();
                timer.Start();
                string classString = r.Compile();
                timer.Stop();

                ReportData("GENERATED c# CLASS SOURCE:\r\n" + classString);

                ReportResult("Compile RegEx as C# class", "SUCCESS", r.IsCompiled, timer);

                // performance test of IsMatch call
                bool result = r.IsMatch(txtInput.Text, timer);
                //bool result = r.IsMatch(pigreco, timer);

                ReportResult("Match('" + txtInput.Text + "')", result.ToString(), r.IsCompiled, timer);

                automataViewer1.Initialize(r);
            }
            catch (RegularExpressionParser.RegularExpressionParserException ex)
            {
                ReportError("PARSING ERROR", ex.ErrorCode.ToString());
            }
            catch (Exception exc)
            {
                ReportError("EXCEPTION", exc.ToString());
            }
        }
예제 #15
0
        public void RegularExpressionRuleIsValid()
        {
            string regularExpressionText = RegularExpressionConstants.Name;
            string target = "Matt Valencia";
            RegularExpression rule = new RegularExpression("RegularExpressionIsValid", "The RegularExpression does not match.", target, regularExpressionText);
            Result result = rule.Execute();

            Assert.IsTrue(result.IsValid);
            Assert.IsNotNullOrEmpty(result.Message);
            Assert.IsNotNull(result.RulePolicy);
            Assert.AreEqual(result.RulePolicy.Severity, Severity.Exception);
        }
예제 #16
0
 public virtual void Exit(RegularExpression/*!*/ node) { }
예제 #17
0
 public virtual bool Enter(RegularExpression/*!*/ node) { return true; }
예제 #18
0
 public static bool IsExpressionFinal(RegularExpression re)
 {
     string str1 = v(re).Value;
     string str2 = RegularExpression.EMPTY_WORD.ToString();
     if (str1 == str2)
     {
         return true;
     }
     return false;
 }
예제 #19
0
 public KleeneStar(RegularExpression a)
 {
     _a = a;
 }
예제 #20
0
        //helper function
        private static RegularExpression v(RegularExpression re)
        {
            RegularExpression r, s;

            if (re.IsEmptyWord)
            {
                return new RegularExpression();
            }
            else if ((!re.IsEmptyWord && re.Value.Length == 1) || re.IsEmptySet)
            {
                return CreateEmptySet();
            }
            else if (re.IsConcatenation)
            {
                re.GetConcatSubExpressions(out r, out s);
                if (v(r).IsEmptyWord && v(s).IsEmptyWord)
                    return new RegularExpression();
            }
            else if (re.IsUnion)
            {
                re.GetUnionSubExpressions(out r, out s);
                if (v(r).IsEmptyWord || v(s).IsEmptyWord)
                    return new RegularExpression();
            }
            else if (re.IsKleene)
            {
                return new RegularExpression();
            }
            return CreateEmptySet();
        }
예제 #21
0
 public override bool Enter(RegularExpression/*!*/ node) {
     if (node.Pattern.Count == 1) {
         var literal = node.Pattern[0] as StringLiteral;
         if (literal != null) {
             _regexLog.WriteLine("/{0}/{{{1}}}", literal.Value, node.Options);
         }
     }
     return true;
 }
예제 #22
0
파일: State.cs 프로젝트: pmichna/Finite
 public State(RegularExpression re, bool isFinal)
 {
     RegexLabel = re.Value;
     IsFinal = isFinal;
 }
예제 #23
0
 public static void reInit()
 {
     ostr = null;
     staticString = null;
     tokMgrClassName = null;
     allTpsForState = new Dictionary<string, IList<TokenProduction>>();
     lexStateIndex = 0;
     kinds = null;
     maxOrdinal = 1;
     lexStateSuffix = null;
     newLexState = null;
     lexStates = null;
     ignoreCase = null;
     actions = null;
     initStates = new Dictionary<string, NfaState>();
     stateSetSize = 0;
     maxLexStates = 0;
     lexStateName = null;
     singlesToSkip = null;
     toSkip = null;
     toSpecial = null;
     toMore = null;
     toToken = null;
     defaultLexState = 0;
     rexprs = null;
     maxLongsReqd = null;
     initMatch = null;
     canMatchAnyChar = null;
     hasEmptyMatch = false;
     canLoop = null;
     stateHasActions = null;
     hasLoop = false;
     canReachOnMore = null;
     hasNfa = null;
     mixed = null;
     initialState = null;
     curKind = 0;
     hasSkipActions = false;
     hasMoreActions = false;
     hasTokenActions = false;
     hasSpecial = false;
     hasSkip = false;
     hasMore = false;
     curRE = null;
 }
예제 #24
0
 public IEnumerable<int> GetPositions(RegularExpression expression)
 {
     var enumerable = Visit(expression) as IEnumerable<int>;
     Contract.Assert(enumerable != null);
     return enumerable;
 }
예제 #25
0
		public ROneOrMore(Token token, RegularExpression expression) {
			Column = token.beginColumn;
			Line = token.beginLine;
			RegularExpression = expression;
		}
예제 #26
0
        public static void start()
        {
            if (!Options.getBuildTokenManager() ||
                Options.getUserTokenManager() ||
                CSharpCCErrors.ErrorCount > 0)
                return;

            keepLineCol = Options.getKeepLineColumn();
            List<RegularExpression> choices = new List<RegularExpression>();
            IEnumerator e;
            TokenProduction tp;
            int i, j;

            staticString = (Options.getStatic() ? "static " : "");
            tokMgrClassName = CSharpCCGlobals.cu_name + "TokenManager";

            PrintClassHead();
            BuildLexStatesTable();

            e = allTpsForState.Keys.GetEnumerator();

            bool ignoring = false;

            while (e.MoveNext()) {
                NfaState.ReInit();
                RStringLiteral.ReInit();

                String key = (String) e.Current;

                lexStateIndex = GetIndex(key);
                lexStateSuffix = "_" + lexStateIndex;
                IList<TokenProduction> allTps = allTpsForState[key];
                initStates[key] = initialState = new NfaState();
                ignoring = false;

                singlesToSkip[lexStateIndex] = new NfaState();
                singlesToSkip[lexStateIndex].dummy = true;

                if (key.Equals("DEFAULT"))
                    defaultLexState = lexStateIndex;

                for (i = 0; i < allTps.Count; i++) {
                    tp = allTps[i];
                    int kind = tp.Kind;
                    bool ignore = tp.IgnoreCase;
                    IList<RegExprSpec> rexps = tp.RegexSpecs;

                    if (i == 0)
                        ignoring = ignore;

                    for (j = 0; j < rexps.Count; j++) {
                        RegExprSpec respec = rexps[j];
                        curRE = respec.RegularExpression;

                        rexprs[curKind = curRE.Ordinal] = curRE;
                        lexStates[curRE.Ordinal] = lexStateIndex;
                        ignoreCase[curRE.Ordinal] = ignore;

                        if (curRE.IsPrivate) {
                            kinds[curRE.Ordinal] = -1;
                            continue;
                        }

                        if (curRE is RStringLiteral &&
                            !((RStringLiteral) curRE).Image.Equals("")) {
                            ((RStringLiteral) curRE).GenerateDfa(ostr, curRE.Ordinal);
                            if (i != 0 && !mixed[lexStateIndex] && ignoring != ignore)
                                mixed[lexStateIndex] = true;
                        } else if (curRE.CanMatchAnyChar) {
                            if (canMatchAnyChar[lexStateIndex] == -1 ||
                                canMatchAnyChar[lexStateIndex] > curRE.Ordinal)
                                canMatchAnyChar[lexStateIndex] = curRE.Ordinal;
                        } else {
                            Nfa temp;

                            if (curRE is RChoice)
                                choices.Add(curRE);

                            temp = curRE.GenerateNfa(ignore);
                            temp.End.isFinal = true;
                            temp.End.kind = curRE.Ordinal;
                            initialState.AddMove(temp.Start);
                        }

                        if (kinds.Length < curRE.Ordinal) {
                            int[] tmp = new int[curRE.Ordinal + 1];

                            Array.Copy(kinds, 0, tmp, 0, kinds.Length);
                            kinds = tmp;
                        }
                        //System.out.println("   ordina : " + curRE.ordinal);

                        kinds[curRE.Ordinal] = kind;

                        if (respec.NextState != null &&
                            !respec.NextState.Equals(lexStateName[lexStateIndex]))
                            newLexState[curRE.Ordinal] = respec.NextState;

                        if (respec.Action != null && respec.Action.ActionTokens != null &&
                            respec.Action.ActionTokens.Count > 0)
                            actions[curRE.Ordinal] = respec.Action;

                        switch (kind) {
                            case TokenProduction.SPECIAL:
                                hasSkipActions |= (actions[curRE.Ordinal] != null) ||
                                                  (newLexState[curRE.Ordinal] != null);
                                hasSpecial = true;
                                toSpecial[curRE.Ordinal/64] |= 1L << (curRE.Ordinal%64);
                                toSkip[curRE.Ordinal/64] |= 1L << (curRE.Ordinal%64);
                                break;
                            case TokenProduction.SKIP:
                                hasSkipActions |= (actions[curRE.Ordinal] != null);
                                hasSkip = true;
                                toSkip[curRE.Ordinal/64] |= 1L << (curRE.Ordinal%64);
                                break;
                            case TokenProduction.MORE:
                                hasMoreActions |= (actions[curRE.Ordinal] != null);
                                hasMore = true;
                                toMore[curRE.Ordinal/64] |= 1L << (curRE.Ordinal%64);

                                if (newLexState[curRE.Ordinal] != null)
                                    canReachOnMore[GetIndex(newLexState[curRE.Ordinal])] = true;
                                else
                                    canReachOnMore[lexStateIndex] = true;

                                break;
                            case TokenProduction.TOKEN:
                                hasTokenActions |= (actions[curRE.Ordinal] != null);
                                toToken[curRE.Ordinal/64] |= 1L << (curRE.Ordinal%64);
                                break;
                        }
                    }
                }

                // Generate a static block for initializing the nfa transitions
                NfaState.ComputeClosures();

                for (i = 0; i < initialState.epsilonMoves.Count; i++)
                    initialState.epsilonMoves[i].GenerateCode();

                if (hasNfa[lexStateIndex] = (NfaState.generatedStates != 0)) {
                    initialState.GenerateCode();
                    initialState.GenerateInitMoves(ostr);
                }

                if (initialState.kind != Int32.MaxValue && initialState.kind != 0) {
                    if ((toSkip[initialState.kind/64] & (1L << initialState.kind)) != 0L ||
                        (toSpecial[initialState.kind/64] & (1L << initialState.kind)) != 0L)
                        hasSkipActions = true;
                    else if ((toMore[initialState.kind/64] & (1L << initialState.kind)) != 0L)
                        hasMoreActions = true;
                    else
                        hasTokenActions = true;

                    if (initMatch[lexStateIndex] == 0 ||
                        initMatch[lexStateIndex] > initialState.kind) {
                        initMatch[lexStateIndex] = initialState.kind;
                        hasEmptyMatch = true;
                    }
                } else if (initMatch[lexStateIndex] == 0)
                    initMatch[lexStateIndex] = Int32.MaxValue;

                RStringLiteral.FillSubString();

                if (hasNfa[lexStateIndex] && !mixed[lexStateIndex])
                    RStringLiteral.GenerateNfaStartStates(ostr, initialState);

                RStringLiteral.DumpDfaCode(ostr);

                if (hasNfa[lexStateIndex])
                    NfaState.DumpMoveNfa(ostr);

                if (stateSetSize < NfaState.generatedStates)
                    stateSetSize = NfaState.generatedStates;
            }

            for (i = 0; i < choices.Count; i++)
                ((RChoice) choices[i]).CheckUnmatchability();

            NfaState.DumpStateSets(ostr);
            CheckEmptyStringMatch();
            NfaState.DumpNonAsciiMoveMethods(ostr);
            RStringLiteral.DumpStrLiteralImages(ostr);
            DumpStaticVarDeclarations();
            DumpFillToken();
            DumpGetNextToken();

            if (Options.getDebugTokenManager()) {
                NfaState.DumpStatesForKind(ostr);
                DumpDebugMethods();
            }

            if (hasLoop) {
                ostr.WriteLine("{0}int[] ccEmptyLineNo = new int[{1}];", staticString, maxLexStates);
                ostr.WriteLine("{0}int[] ccEmptyColNo = new int[{1}];", staticString, maxLexStates);
                ostr.WriteLine("{0}bool[] ccBeenHere = new bool[{1}];", staticString, maxLexStates);
            }

            if (hasSkipActions)
                DumpSkipActions();
            if (hasMoreActions)
                DumpMoreActions();
            if (hasTokenActions)
                DumpTokenActions();

            NfaState.PrintBoilerPlate(ostr);
            ostr.WriteLine( /*{*/ "}");

            if (namespaceInserted)
                ostr.WriteLine("}");

            ostr.Close();
        }
예제 #27
0
파일: Form1.cs 프로젝트: nzldvd90/MidTermAP
        private void btnStartTest_Click(object sender, EventArgs e)
        {
            pnlTestResult.Visible = true;
            btnStartTest.Enabled = false;
            int numberOfTries = 100;
            long[] TicksIntepreted = null;
            long[] TicksCompiled = null;

            try
            {
                RegularExpression rIntepreted = new RegularExpression("([1-9][0-9]*|0)(,[0-9]*[1-9])?");
                RegularExpression rCompiled = new RegularExpression("([1-9][0-9]*|0)(,[0-9]*[1-9])?");
                string classString = rCompiled.Compile();
                progressBar1.Maximum = numberOfTries - 1;

                TicksIntepreted = new long[numberOfTries];
                TicksCompiled = new long[numberOfTries];

                Stopwatch timer = new Stopwatch();

                for (int i = 0; i < numberOfTries; i++)
                {

                    timer.Reset();
                    timer.Start();
                    //bool result = rIntepreted.IsMatch(txtInput.Text);
                    bool result = rIntepreted.IsMatch(pigreco);
                    timer.Stop();
                    TicksIntepreted[i] = timer.ElapsedTicks;

                    timer.Reset();
                    timer.Start();
                    //result = rCompiled.IsMatch(txtInput.Text, timer);
                    result = rCompiled.IsMatch(pigreco, timer);
                    timer.Stop();
                    TicksCompiled[i] = timer.ElapsedTicks;

                    // performance test of parsing RegEx
                    timer.Start();
                    timer.Stop();

                    progressBar1.Value = i;
                }

                DisplayTestResults(TicksIntepreted, TicksCompiled);
            }
            catch (RegularExpressionParser.RegularExpressionParserException ex)
            {
                ReportError("PARSING ERROR", ex.ErrorCode.ToString());
            }
            catch (Exception exc)
            {
                ReportError("EXCEPTION", exc.ToString());
            }
            finally
            {
                btnStartTest.Enabled = true;
            }
        }
        /// <summary>
        /// Import the given questions into the DB
        /// </summary>
        public void ImportQuestions(NSurveyQuestion importQuestions, int userId)
        {

            SqlConnection sqlConnection = new SqlConnection(DbConnection.NewDbConnectionString);
            sqlConnection.Open();
            SqlTransaction sqlTransaction = sqlConnection.BeginTransaction();
            SqlCommand insertCommand = new AnswerType().GetInsertAnswerTypeCommand(sqlConnection, sqlTransaction, userId);
            SqlCommand command2 = new RegularExpression().GetInsertRegularExpressionCommand(sqlConnection, sqlTransaction, userId);
            SqlCommand insertQuestionCommand = this.GetInsertQuestionCommand(sqlConnection, sqlTransaction);
            SqlCommand insertChildQuestionCommand = this.GetInsertChildQuestionCommand(sqlConnection, sqlTransaction);
            SqlCommand insertAnswerCommand = new Answer().GetInsertAnswerCommand(sqlConnection, sqlTransaction);
            SqlCommand insertAnswerConnectionCommand = new Answer().GetInsertAnswerConnectionCommand(sqlConnection, sqlTransaction);
            SqlCommand insertAnswerPropertyCommand = new Answer().GetInsertAnswerPropertyCommand(sqlConnection, sqlTransaction);
            SqlCommand command8 = this.GetInsertQuestionSectionCommand(sqlConnection, sqlTransaction, "");
            SqlCommand insertQuestionSectionGridAnswersCommand = this.GetInsertQuestionSectionGridAnswersCommand(sqlConnection, sqlTransaction);
            try
            {
                // Add Question groups so we can attach them to questions
                int surveyId = importQuestions.Question.First().SurveyId;
                // Add Question groups so we can attach them to questions

                string defaultLang = null;

                var groups = new QuestionGroups();
                var existingGroups = groups.GetAll(defaultLang).QuestionGroups;
                foreach (var qgrp in importQuestions.QuestionGroups
                    .OrderBy(x => x.IsParentGroupIdNull() ? 0 : 1)) //Load parent groups first
                {
                    var grpHere = existingGroups.FirstOrDefault(x => x.GroupName == qgrp.GroupName);

                    int groupIdHere;
                    if (grpHere == null)
                    {
                        int? parentGroupId = null;
                        if (!qgrp.IsParentGroupIdNull()) //Has Parent Group
                        {
                            var pgrp = importQuestions.QuestionGroups.SingleOrDefault(x => x.ID == qgrp.ParentGroupId);
                            if (pgrp != null)
                            {
                                var exPar = groups.GetAll(defaultLang).QuestionGroups
                                      .FirstOrDefault(x => x.GroupName == pgrp.GroupName);
                                if (exPar != null) parentGroupId = exPar.ID;
                            }
                        }
                        groups.AddNewGroup(qgrp.GroupName, parentGroupId, defaultLang);

                        var grt = groups.GetAll(defaultLang).QuestionGroups
                            .FirstOrDefault(x => x.GroupName == qgrp.GroupName);
                        groupIdHere = grt.ID;
                    }
                    else
                    {
                        groupIdHere = grpHere.ID;
                    }
                    importQuestions.Question
                          .Where(x => x.QuestionGroupId == qgrp.OldId)
                          .ToList().ForEach(x => x.QuestionGroupId = groupIdHere);

                }

                DbConnection.db.UpdateDataSet(importQuestions, "AnswerType", insertCommand, new SqlCommand(), insertCommand, UpdateBehavior.Transactional);
                DbConnection.db.UpdateDataSet(importQuestions, "RegularExpression", command2, new SqlCommand(), command2, UpdateBehavior.Transactional);
                DbConnection.db.UpdateDataSet(importQuestions, "Question", insertQuestionCommand, new SqlCommand(), insertQuestionCommand, UpdateBehavior.Transactional);
                DbConnection.db.UpdateDataSet(importQuestions, "Answer", insertAnswerCommand, new SqlCommand(), insertAnswerCommand, UpdateBehavior.Transactional);
                DbConnection.db.UpdateDataSet(importQuestions, "AnswerConnection", insertAnswerConnectionCommand, new SqlCommand(), insertAnswerConnectionCommand, UpdateBehavior.Transactional);
                DbConnection.db.UpdateDataSet(importQuestions, "ChildQuestion", insertChildQuestionCommand, new SqlCommand(), insertChildQuestionCommand, UpdateBehavior.Transactional);
                DbConnection.db.UpdateDataSet(importQuestions, "AnswerProperty", insertAnswerPropertyCommand, new SqlCommand(), insertAnswerPropertyCommand, UpdateBehavior.Transactional);
                DbConnection.db.UpdateDataSet(importQuestions, "QuestionSectionOption", command8, new SqlCommand(), command8, UpdateBehavior.Transactional);
                DbConnection.db.UpdateDataSet(importQuestions, "QuestionSectionGridAnswer", insertQuestionSectionGridAnswersCommand, new SqlCommand(), insertQuestionSectionGridAnswersCommand, UpdateBehavior.Transactional);
                var multiLanguage = new MultiLanguage();
                int newQuestionId = importQuestions.Question[0].QuestionId;
                foreach (var langText in importQuestions.MultiLanguageText)
                {
                    var localGroups = groups.GetAll(defaultLang).QuestionGroups;
                    //Process Survey level
                    if (langText.LanguageMessageTypeId == 10)
                    {
                        var impGrp = importQuestions.QuestionGroups.SingleOrDefault(x => x.OldId == langText.LanguageItemId);
                        if (impGrp != null)
                        {
                            var localGrp = localGroups.SingleOrDefault(x => x.GroupName == impGrp.GroupName);
                            try
                            {
                                if (localGrp != null)
                                    multiLanguage.AddMultiLanguageText(localGrp.ID, langText.LanguageCode, langText.LanguageMessageTypeId, langText.ItemText);
                            }
                            catch (Exception ex) { }
                        }
                    }

                    if (langText.LanguageMessageTypeId == 3 || langText.LanguageMessageTypeId == 11 || langText.LanguageMessageTypeId == 12)
                        multiLanguage.AddMultiLanguageText(newQuestionId
                            , langText.LanguageCode, langText.LanguageMessageTypeId, langText.ItemText);

                    if (langText.LanguageMessageTypeId == 1 || langText.LanguageMessageTypeId == 2 || langText.LanguageMessageTypeId == 13)
                        multiLanguage.AddMultiLanguageText(importQuestions.Answer.Single(x => x.OldId == langText.LanguageItemId).AnswerId
                            , langText.LanguageCode, langText.LanguageMessageTypeId, langText.ItemText);

                }
                sqlTransaction.Commit();
                sqlConnection.Close();
            }
            catch (Exception exception)
            {
                sqlTransaction.Rollback();
                throw exception;
            }
        }
예제 #29
0
 public RegularExpressionCondition(RegularExpression/*!*/ regex)
     : base(regex.Location)
 {
     Assert.NotNull(regex);
     _regex = regex;
 }
예제 #30
0
파일: parser.cs 프로젝트: nlhepler/mono
		public RegularExpression ParseRegularExpression (string pattern, RegexOptions options) {
			this.pattern = pattern;
			this.ptr = 0;

			caps.Clear ();
			refs.Clear ();
			this.num_groups = 0;

			try {
				RegularExpression re = new RegularExpression ();
				ParseGroup (re, options, null);
				ResolveReferences ();

				re.GroupCount = num_groups;
				
				return re;
			}
			catch (IndexOutOfRangeException) {
				throw NewParseException ("Unexpected end of pattern.");
			}
		}