Example #1
0
        public float main_calculator(string ss)
        {
            TOkenizer      obj1   = new TOkenizer(ss);
            Stack <float>  nstack = new Stack <float>();
            Stack <string> ostack = new Stack <string>();

            while (obj1.is_finished())
            {
                Token _res = obj1.getToken();
                if (_res.Type == TokenType.enumeric)
                {
                    number_value = _res.Value;
                    if (!obj1.is_finished())
                    {
                        nstack.Push(float.Parse(number_value));
                        break;
                    }
                    _res = obj1.getToken();
                    while (_res.Type == TokenType.enumeric)
                    {
                        number_value += _res.Value;
                        if (!obj1.is_finished())
                        {
                            break;
                        }
                        _res = obj1.getToken();
                    }
                    nstack.Push(float.Parse(number_value));
                }

                if (ostack.Count() == 0 && obj1.is_finished())
                {
                    ostack.Push(_res.Value);
                }
                else if (ostack.Count() != 0 && obj1.is_finished())
                {
                    string char_pop = ostack.Peek();
                    int    com_res  = compare_chars(_res.Value, char_pop);
                    if (com_res == 1)
                    {
                        ostack.Push(_res.Value);
                    }
                    else
                    {
                        char_pop = ostack.Pop();
                        while (compare_chars(_res.Value, char_pop) != 1 || ostack.Count() != 0)
                        {
                            number1 = nstack.Pop();
                            number2 = nstack.Pop();
                            nstack.Push(calcalator(char_pop));
                            if (ostack.Count() == 0)
                            {
                                break;
                            }
                            char_pop = ostack.Pop();
                        }
                        ostack.Push(_res.Value);
                    }
                }
            }
            while (ostack.Count() != 0)
            {
                string char_pop = ostack.Pop();
                number1 = nstack.Pop();
                number2 = nstack.Pop();
                nstack.Push(calcalator(char_pop));
                result = calcalator(char_pop);
            }
            return(result);
        }
Example #2
0
        private bool finished;                  //Totuusarvo onko algoritmi valmis.

        public Dijkstra(int[,] matriisi, int s, int target)
        {
            start    = s;
            Matriisi = matriisi;
            //Alustetaan kaikki taulukot.
            visited  = new int[(int)Math.Sqrt(matriisi.Length)];
            distance = new int[visited.Length];
            via      = new int[visited.Length];
            inde     = new List <int>();
            path     = new Stack <int>();
            finished = false;
            for (int i = 0; i < distance.Length; i++)
            {
                //Alustetaan alla olevien taulukoiden erikoisarvot.
                distance[i] = int.MaxValue;
                visited[i]  = -1;
                via[i]      = -1;
            }
            inde.Clear();
            current = start;
            int[] tdistance = new int[visited.Length];
            int   round     = 0;

            //Aloitetaan algoritmi.
            while (finished != true)
            {
                if (current == start)       //Jos tarkasteltava piste on aloituspiste niin sen etäisyys asetetaan nollaksi.
                {
                    distance[current] = 0;
                    via[current]      = -1;
                }
                for (int i = 0; i < distance.Length; i++)
                {
                    if (Matriisi[current, i] != 0 && Matriisi[current, i] + distance[current] < distance[i])
                    {                          //Jos tarkasteltavan pisteen ja i:n väli on 0 välissä ei ole linkkiä.
                                               //Jos tarkasteltavan pisteen ja i:n väli on < kuin niinden välinen etäisyys asetetaan uusi etäisyys.
                        distance[i] = distance[current] + Matriisi[current, i];
                        via[i]      = current; //asetetaan perittävä piste
                    }
                }
                tdistance = (int[])distance.Clone();       //Kloonataan etäisyyslista.
                Array.Sort(tdistance);                     //Väliaikainen etäisyyslista lajitellaan.
                visited[round] = current;                  //Vierailtujenlistaan lisätään tarkasteltu piste.
                for (int i = 0; i < tdistance.Length; i++) //Silmukka, jossa katsotaan väliaikaislistan pituus.
                {
                    inde.Clear();                          //Tyhjennetään inde-lista.
                    int former = current;                  //Asetetaan muutosmuuttuja
                    for (int j = 0; j < distance.Length; j++)
                    {
                        if (distance[j] == tdistance[i]) //Tarkastellaan lyhimmästä pisimpään järjestyksessä, mikä seuraavan tarkastelupisteen tulee olla.
                        {
                            inde.Add(j);                 //Lisätään kandidaatit listaan inde
                        }
                    }
                    foreach (int value in inde)         //Käydään läpi inde lista
                    {
                        if (tdistance[i] >= distance[current] && Array.IndexOf(visited, value) == -1 && value != -1)
                        //Jos väliaikaisetäisyys on >= tarkasteltava etäisyys JA vierailtujentaulukosta ei löydy kyseistä inde-listassa olevaa arvoa JA arvo != -1
                        {
                            current = value;    //Asetetaan uudeksi tarkasteltavaksi pisteeksi inde-listan tämänhetkinen arvo.
                            break;
                        }
                    }
                    if (former != current)
                    {
                        break;
                    }                                   //Jos muutosmuuttujan ja tarkasteltavan pisteen välillä on ero on tarkasteltava piste vaihtunut.
                }
                if (Array.IndexOf(visited, -1) == -1)
                {
                    finished = true;
                }                                                          //Jos vierailtujen lista on täynnä on algoritmi valmis.
                round++;
            }
            Console.WriteLine("Vertex:  Distance:   Via:"); //Tulostetaan selvästi luettava lista.
            Console.WriteLine("---------------------------");
            for (int i = 0; i < visited.Length; i++)
            {
                Console.Write(" {0}         ", i);
                Console.Write("{0}          ", distance[i]);
                if (via[i] == -1)
                {
                    Console.WriteLine(" ");
                }
                else
                {
                    Console.WriteLine(via[i]);
                }
                Console.WriteLine("---------------------------");
            }
            while (true) //Tulostetaan polku lähtöpisteestä päätepisteeseen.
            {
                path.Push(target);
                if (target == start)
                {
                    break;
                }
                target = via[target];
            }
            while (path.Count() != 0)
            {
                Console.Write("{0}, ", path.Pop());
            }
        }
Example #3
0
        public void DFS(List<DirectedNode> nodelist, int goalNodeid)
        {
            Stack<DirectedNode> stack = new Stack<DirectedNode>();
            stack.Push(nodelist[0]);
            DirectedNode frontiernode;
            int[] adjlist;

            while (stack.Count() != 0)
            {
                frontiernode = stack.Pop();
                adjlist = frontiernode.adjnodes;

                if (adjlist == null) { continue; }

                foreach (int i in adjlist)
                {
                    stack.Push(nodelist[i]);

                    node previousnode = nodelist[nodelist[i].PreviousNodeid];
                    float edgeweight = ConsoleApplication1.Driver.distance(frontiernode, nodelist[i]);
                    float newdistance = frontiernode.ShortestDistanceTo + edgeweight;

                    if (nodelist[i].ShortestDistanceTo == 0)
                    {
                        nodelist[i].ShortestDistanceTo = newdistance;
                        nodelist[i].PreviousNodeid = frontiernode.id;
                    }
                    else if (newdistance < nodelist[i].ShortestDistanceTo)
                    {
                        nodelist[i].ShortestDistanceTo = newdistance;
                        nodelist[i].PreviousNodeid = frontiernode.id;
                    }
                    else { }
                }
            }
            int prevNodeId = goalNodeid - 1;
            Console.Write("Path: " + prevNodeId);
            while (prevNodeId != 0)
            {
                Console.Write(" <- " + nodelist[prevNodeId].PreviousNodeid);
                prevNodeId = nodelist[prevNodeId].PreviousNodeid;
            }
            Console.Write("\nDistance: " + nodelist[goalNodeid - 1].ShortestDistanceTo);
        }
        static void Main(string[] args)
        {
            Dictionary <string, int> myDictionary = new Dictionary <string, int>();
            Queue <string>           myQueue      = new Queue <string>();
            Stack <string>           stkMyStack   = new Stack <string>();
            bool error      = true;
            int  menuchoice = 0;

            /****************************************************************************************************************************/
            /****************************************************************************************************************************/
            /*************************************                 MAIN MENU                *********************************************/
            /****************************************************************************************************************************/
            /****************************************************************************************************************************/
            /****************************************************************************************************************************/
            while (menuchoice != 4)
            {
                Console.WriteLine("MENU");
                Console.WriteLine("Please enter the number that you want to do:");
                Console.WriteLine("1. Stack");
                Console.WriteLine("2. Queue");
                Console.WriteLine("3. Dicitonary");
                Console.WriteLine("4. Exit");
                error = true;
                while (error == true)
                {
                    try
                    {
                        menuchoice = int.Parse(Console.ReadLine());
                        error      = false;
                    }
                    catch
                    {
                        Console.WriteLine("Invalid Entry");
                        Console.WriteLine("Please enter a number between 1-4");
                    }
                }
                switch (menuchoice)
                {
                case 1:
                    /****************************************************************************************************************************/
                    /*************************************                 STACK MENU              *********************************************/
                    /****************************************************************************************************************************/
                    /****************************************************************************************************************************/

                    while (menuchoice != 7)
                    {
                        menuchoice = 0;
                        Console.WriteLine("STACK MENU");
                        Console.WriteLine("Please enter the number that you want to do:");
                        Console.WriteLine("1. Add one item to Stack");
                        Console.WriteLine("2. Add Huge List of Items to Stack");
                        Console.WriteLine("3. Display Stack");
                        Console.WriteLine("4. Delete from Stack");
                        Console.WriteLine("5. Clear Stack");
                        Console.WriteLine("6. Search Stack");
                        Console.WriteLine("7. Return to Main Menu");
                        error = true;
                        while (error == true)
                        {
                            try
                            {
                                menuchoice = int.Parse(Console.ReadLine());
                                error      = false;
                            }
                            catch
                            {
                                Console.WriteLine("Invalid Entry");
                                Console.WriteLine("Please enter a number between 1-4");
                            }
                        }
                        switch (menuchoice)
                        {
                        case 1:
                            Console.WriteLine("Adding one item......");
                            Console.Write("Please add one item");
                            string sMyString = Console.ReadLine();
                            stkMyStack.Push(sMyString);
                            break;

                        case 2:
                            Console.WriteLine("Adding Huge List of Items......");

                            for (int i = 0; i < 2000; i++)
                            {
                                string sNewEntry = ("New Entry " + i);
                                stkMyStack.Push(sNewEntry);
                            }
                            break;

                        case 3:
                            Console.WriteLine("Display........");
                            for (int iCount = 0; iCount < stkMyStack.Count(); iCount++)
                            {
                                Console.WriteLine(stkMyStack.ElementAt(iCount));
                            }
                            break;

                        case 4:
                            Console.WriteLine("Delete.........");
                            Stack <string> stkDelStack = new Stack <string>();
                            Console.Write("Please enter which item you would like to delete: ");
                            string sItem = Console.ReadLine();

                            while (sItem != stkMyStack.Peek())
                            {
                                stkDelStack.Push(stkMyStack.Pop());
                            }
                            stkMyStack.Pop();
                            for (int iCounter = 0; iCounter < stkDelStack.Count(); iCounter++)
                            {
                                stkMyStack.Push(stkDelStack.Pop());
                            }
                            break;

                        case 5:
                            Console.WriteLine("Clear........");
                            stkMyStack.Clear();
                            break;

                        case 6:
                            Console.WriteLine("Search........");
                            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
                            Console.WriteLine("Please enter an item you would like to search for: ");
                            string sSearch = Console.ReadLine();
                            sw.Start();
                            for (int i = 0; i < stkMyStack.Count(); i++)
                            {
                                if (stkMyStack.ElementAt(i).Equals(sSearch))
                                {
                                    Console.WriteLine(stkMyStack.ElementAt(i));
                                    sw.Stop();
                                    Console.WriteLine("It took " + sw.Elapsed + " seconds to complete this search.");
                                }
                                else
                                {
                                    Console.WriteLine("We could not find that item.");
                                }
                            }

                            break;

                        case 7:
                            Console.WriteLine("Going back to Main Menu.......");
                            break;          //go to main menu

                        default:
                            Console.WriteLine("Sorry, invalid selection");
                            break;
                        }
                    }
                    break;

                /****************************************************************************************************************************/
                /*************************************                 QUEUE MENU              *********************************************/
                /****************************************************************************************************************************/
                /****************************************************************************************************************************/
                case 2:
                    while (menuchoice != 7)
                    {
                        menuchoice = 0;
                        Console.WriteLine("QUEUE MENU");
                        Console.WriteLine("Please enter the number that you want to do:");
                        Console.WriteLine("1. Add one item to Queue");
                        Console.WriteLine("2. Add Huge List of Items to Queue");
                        Console.WriteLine("3. Display Queue");
                        Console.WriteLine("4. Delete from Queue");
                        Console.WriteLine("5. Clear Queue");
                        Console.WriteLine("6. Search Queue");
                        Console.WriteLine("7. Return to Main Menu");
                        error = true;
                        while (error == true)
                        {
                            try
                            {
                                menuchoice = int.Parse(Console.ReadLine());
                                error      = false;
                            }
                            catch
                            {
                                Console.WriteLine("Invalid Entry");
                                Console.WriteLine("Please enter a number between 1-4");
                            }
                        }
                        switch (menuchoice)
                        {
                        case 1:
                            //Add one item to Queue
                            Console.WriteLine("Enter a name or something.");
                            string iInput = Console.ReadLine();
                            myQueue.Enqueue(iInput);
                            break;

                        case 2:
                            //Add Huge List of Items to Queue
                            myQueue.Clear();
                            int iCount = 0;
                            while (iCount < 2000)
                            {
                                myQueue.Enqueue("New Entry " + iCount);
                                iCount++;
                            }
                            break;

                        case 3:
                            //Display Queue
                            foreach (string value in myQueue)
                            {
                                Console.WriteLine(value);
                            }
                            break;

                        case 4:
                            //Delete from Queue
                            Console.WriteLine("Which queue item do you want to delete?");
                            int iQueueDelete = 0;
                            try
                            {
                                iQueueDelete = int.Parse(Console.ReadLine());
                            }
                            catch
                            {
                                Console.WriteLine("Invalid Entry");
                                Console.WriteLine("Please enter a number from your queue.");
                            }
                            List <string> listOfWhatWontBeDeletedFromQueue = new List <string>();
                            int           iListCount = 1;
                            while (iListCount < iQueueDelete)
                            {
                                listOfWhatWontBeDeletedFromQueue.Add(myQueue.Dequeue());
                                iListCount++;
                            }
                            myQueue.Dequeue();
                            foreach (string value in listOfWhatWontBeDeletedFromQueue)
                            {
                                myQueue.Enqueue(value);
                            }
                            break;

                        case 5:
                            //Clear Queue
                            myQueue.Clear();
                            break;

                        case 6:
                            //Search Queue
                            Console.WriteLine("What item would you like to see if the queue contains?");
                            string iQueueSearch             = Console.ReadLine();
                            System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
                            sw.Start();
                            if (myQueue.Contains(iQueueSearch))
                            {
                                Console.WriteLine("Yes, the queue had that.");
                            }
                            else
                            {
                                Console.WriteLine("No, the queue didn't have that.");
                            }
                            sw.Start();
                            Console.WriteLine("It took " + sw.ElapsedMilliseconds + " milliseconds to figure that out.");
                            break;

                        case 7:
                            //Return to Main Menu
                            break;

                        default:
                            Console.WriteLine("Sorry, invalid selection");
                            break;
                        }
                    }
                    break;

                case 3:
                    /****************************************************************************************************************************/
                    /*************************************                 DICTIONARY MENU              *****************************************/
                    /****************************************************************************************************************************/
                    /****************************************************************************************************************************/
                    while (menuchoice != 7)
                    {
                        //Declare variables
                        string sUserResponse;
                        int    iUserResponse;
                        int    iCount   = 0;
                        int    iCounter = 0;



                        menuchoice = 0;
                        Console.WriteLine("DICTIONARY MENU");
                        Console.WriteLine("Please enter the number that you want to do:");
                        Console.WriteLine("1. Add one item to Dictionary");
                        Console.WriteLine("2. Add Huge List of Items to Dictionary");
                        Console.WriteLine("3. Display Dictionary");
                        Console.WriteLine("4. Delete from Dictionary");
                        Console.WriteLine("5. Clear Dictionary");
                        Console.WriteLine("6. Search Dictionary");
                        Console.WriteLine("7. Return to Main Menu");
                        error = true;
                        while (error == true)
                        {
                            try
                            {
                                menuchoice = int.Parse(Console.ReadLine());
                                error      = false;
                            }
                            catch
                            {
                                Console.WriteLine("Invalid Entry");
                                Console.WriteLine("Please enter a number between 1-4");
                            }
                        }
                        switch (menuchoice)
                        {
                        case 1:
                            //Prompt user for them to enter in a string and record the response
                            Console.WriteLine("\nPlease enter a string");
                            sUserResponse = Console.ReadLine();

                            //Add the response to the myDictionary object along with a value
                            myDictionary.Add(sUserResponse, iCount++);
                            break;

                        case 2:
                            //Clear all of the contents of the dictionary
                            myDictionary.Clear();

                            //Load up each dictionary item up to 2000
                            for (iCount = 0; iCount <= 2000; iCount++)
                            {
                                myDictionary.Add("New Entry " + iCount, iCount);
                            }

                            //Reset the iCount back to 0
                            iCount = 0;
                            break;

                        case 3:
                            //Display the contents of the dictionary
                            Console.WriteLine("\nThis is the contents of the Dictionary");

                            foreach (KeyValuePair <string, int> entry in myDictionary)
                            {
                                Console.WriteLine(entry.Key.PadRight(20, ' ') + entry.Value);
                            }
                            Console.WriteLine();
                            break;

                        case 4:
                            //Prompt for user input of what they want to delete from the dictionary
                            Console.WriteLine("\nWhat would you like to Delete from the Dictionary? \nHere is the List: \n");

                            //Display the dictionary so they can see their options
                            foreach (KeyValuePair <string, int> entry in myDictionary)
                            {
                                Console.WriteLine(entry.Key);
                            }

                            //Record the user response and then delete the request item from the Dictionary
                            Console.WriteLine();
                            sUserResponse = Console.ReadLine();

                            myDictionary.Remove(sUserResponse);

                            break;

                        case 5:
                            //Clear the whole dictionary
                            myDictionary.Clear();
                            break;

                        case 6:
                            //Prompt the user for what string they want to look for.
                            Console.WriteLine("\nPlease enter the string you are searching for: ");
                            sUserResponse = Console.ReadLine();

                            //Display the results of the search
                            if (myDictionary.ContainsKey(sUserResponse))
                            {
                                Console.WriteLine("\nYou found " + sUserResponse + "! Here is the value: " + myDictionary[sUserResponse] + "\n");
                            }
                            else
                            {
                                Console.WriteLine("\nString not found!");
                            }
                            break;

                        case 7:
                            Console.WriteLine("Going back to Main Menu.......");
                            break;  //go to main menu

                        default:
                            Console.WriteLine("Sorry, invalid selection");
                            break;
                        }
                    }
                    break;

                case 4:
                    break;      //end

                default:
                    Console.WriteLine("Sorry, invalid selection");
                    break;
                }
            }
        }
        public static SanitizeResult sanitizer(String html, Regex allowedTags, Regex forbiddenTags, bool isConsiderAllowedTag = false)
        {
            SanitizeResult ret      = new SanitizeResult();
            Stack <String> openTags = new Stack <string>();

            if (String.IsNullOrEmpty(html))
            {
                return(ret);
            }


            List <String> tokens = tokenize(html);

            // -------------------   LOOP for every token --------------------------
            for (int i = 0; i < tokens.Count; i++)
            {
                String token           = tokens[i];
                bool   isAcceptedToken = false;

                Match startMatcher = tagStartPattern.Match(token);
                Match endMatcher   = tagClosePattern.Match(token);

                //--------------------------------------------------------------------------------  COMMENT    <!-- ......... -->
                if (commentPattern.Match(token).Success)
                {
                    ret.val = ret.val + token + (token.EndsWith("-->") ? "" : "-->");
                    ret.invalidTags.Add(token + (token.EndsWith("-->") ? "" : "-->"));
                    continue;

                    //--------------------------------------------------------------------------------  OPEN TAG    <tag .........>
                }
                else if (startMatcher.Success)
                {
                    //tag name extraction
                    String tag = startMatcher.Groups[1].Value.ToLower();

                    //-----------------------------------------------------  FORBIDDEN TAG   <script .........>
                    if (forbiddenTags.Match(tag).Success)
                    {
                        ret.invalidTags.Add("<" + tag + ">");
                        continue;

                        // --------------------------------------------------  WELL KNOWN TAG
                    }
                    else if (allowedTags.Match(tag).Success)
                    {
                        if (!isConsiderAllowedTag)
                        {
                            ret.invalidTags.Add("<" + tag + ">");
                            continue;
                        }

                        String cleanToken = "<" + tag;
                        String tokenBody  = startMatcher.Groups[2].Value;

                        //first test table consistency
                        //table tbody tfoot thead th tr td
                        if ("thead".Equals(tag) || "tbody".Equals(tag) || "tfoot".Equals(tag) || "tr".Equals(tag))
                        {
                            if (openTags.Select(t => t == "table").Count() <= 0)
                            {
                                ret.invalidTags.Add("<" + tag + ">");
                                continue;
                            }
                        }
                        else if ("td".Equals(tag) || "th".Equals(tag))
                        {
                            if (openTags.Count(t => t == "tr") <= 0)
                            {
                                ret.invalidTags.Add("<" + tag + ">");
                                continue;
                            }
                        }

                        // then test properties
                        //Match attributes = attributesPattern.Match(tokenBody);
                        var attributes = attributesPattern.Matches(tokenBody);

                        bool foundURL = false; // URL flag

                        foreach (Match attribute in attributes)
                        //while (attributes.find())
                        {
                            String attr = attribute.Groups[1].Value.ToLower();
                            String val  = attribute.Groups[2].Value;

                            if (val.Contains("&{"))
                            {
                                ret.invalidTags.Add(attr + " " + val);
                            }
                            // we will accept href in case of <A>
                            else if ("a".Equals(tag) && "href".Equals(attr))
                            {    // <a href="......">
                                try
                                {
                                    var url = new Uri(val);

                                    if (url.Scheme == Uri.UriSchemeHttp || url.Scheme == Uri.UriSchemeHttps || url.Scheme == Uri.UriSchemeMailto)
                                    {
                                        foundURL = true;
                                    }
                                    else
                                    {
                                        ret.invalidTags.Add(attr + " " + val);
                                        val = "";
                                    }
                                }
                                catch
                                {
                                    ret.invalidTags.Add(attr + " " + val);
                                    val = "";
                                }
                            }
                            else if ((tag == "img" || tag == "embed") && "src".Equals(attr))
                            { // <img src="......">
                                try
                                {
                                    var url = new Uri(val);

                                    if (url.Scheme == Uri.UriSchemeHttp || url.Scheme == Uri.UriSchemeHttps)
                                    {
                                        foundURL = true;
                                    }
                                    else
                                    {
                                        ret.invalidTags.Add(attr + " " + val);
                                        val = "";
                                    }
                                }
                                catch
                                {
                                    ret.invalidTags.Add(attr + " " + val);
                                    val = "";
                                }
                            }
                            else if ("href".Equals(attr) || "src".Equals(attr))
                            { // <tag src/href="......">   skipped
                                ret.invalidTags.Add(tag + " " + attr + " " + val);
                                continue;
                            }
                            else if (attr == "width" || attr == "height")
                            { // <tag width/height="......">
                                Regex r = new Regex("\\d+%|\\d+$");
                                if (!r.Match(val.ToLower()).Success)
                                { // test numeric values
                                    ret.invalidTags.Add(tag + " " + attr + " " + val);
                                    continue;
                                }
                            }
                            else if ("style".Equals(attr))
                            { // <tag style="......">
                                // then test properties
                                var    styles     = stylePattern.Matches(val);
                                String cleanStyle = "";

                                foreach (Match style in styles)
                                //while (styles.find())
                                {
                                    String styleName  = style.Groups[1].Value.ToLower();
                                    String styleValue = style.Groups[2].Value;

                                    // suppress invalid styles values
                                    if (forbiddenStylePattern.Match(styleValue).Success)
                                    {
                                        ret.invalidTags.Add(tag + " " + attr + " " + styleValue);
                                        continue;
                                    }

                                    // check if valid url
                                    Match urlStyleMatcher = urlStylePattern.Match(styleValue);
                                    if (urlStyleMatcher.Success)
                                    {
                                        try
                                        {
                                            String url = urlStyleMatcher.Groups[1].Value;
                                            var    uri = new Uri(url);

                                            if (!(uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps))
                                            {
                                                ret.invalidTags.Add(tag + " " + attr + " " + styleValue);
                                                continue;
                                            }
                                        }
                                        catch
                                        {
                                            ret.invalidTags.Add(tag + " " + attr + " " + styleValue);
                                            continue;
                                        }
                                    }

                                    cleanStyle = cleanStyle + styleName + ":" + encode(styleValue) + ";";
                                }
                                val = cleanStyle;
                            }
                            else if (attr.StartsWith("on"))
                            {  // skip all javascript events
                                ret.invalidTags.Add(tag + " " + attr + " " + val);
                                continue;
                            }
                            else
                            {  // by default encode all properies
                                val = encode(val);
                            }

                            cleanToken = cleanToken + " " + attr + "=\"" + val + "\"";
                        }
                        cleanToken = cleanToken + ">";

                        isAcceptedToken = true;

                        // for <img> and <a>
                        if ((tag == "a" || tag == "img" || tag == "embed") && !foundURL)
                        {
                            isAcceptedToken = false;
                            cleanToken      = "";
                        }

                        token = cleanToken;

                        // push the tag if require closure and it is accepted (otherwise is encoded)
                        if (isAcceptedToken && !(standAloneTags.Match(tag).Success || selfClosed.Match(tag).Success))
                        {
                            openTags.Push(tag);
                        }

                        // --------------------------------------------------------------------------------  UNKNOWN TAG
                    }
                    else
                    {
                        //ret.invalidTags.Add(token);
                        //ret.val = ret.val + token;
                        continue;
                    }

                    // --------------------------------------------------------------------------------  CLOSE TAG </tag>
                }
                else if (endMatcher.Success)
                {
                    String tag = endMatcher.Groups[1].Value.ToLower();

                    //is self closing
                    if (selfClosed.Match(tag).Success)
                    {
                        ret.invalidTags.Add(token);
                        continue;
                    }
                    if (forbiddenTags.Match(tag).Success)
                    {
                        ret.invalidTags.Add("/" + tag);
                        continue;
                    }
                    if (!allowedTags.Match(tag).Success)
                    {
                        //ret.invalidTags.Add(token);
                        //ret.val = ret.val + token;
                        continue;
                    }
                    else
                    {
                        String cleanToken = "";

                        // check tag position in the stack

                        int  pos   = -1;
                        bool found = false;

                        foreach (var item in openTags)
                        {
                            pos++;
                            if (item == tag)
                            {
                                found = true;
                                break;
                            }
                        }

                        // if found on top ok
                        if (found)
                        {
                            for (int k = 0; k <= pos; k++)
                            {
                                //pop all elements before tag and close it
                                String poppedTag = openTags.Pop();
                                cleanToken      = cleanToken + "</" + poppedTag + ">";
                                isAcceptedToken = true;
                            }
                        }

                        token = cleanToken;
                    }
                }

                ret.val = ret.val + token;

                if (isAcceptedToken)
                {
                    ret.html = ret.html + token;
                    //ret.text = ret.text + " ";
                }
                else
                {
                    String sanToken = htmlEncodeApexesAndTags(token);
                    ret.html = ret.html + sanToken;
                    ret.text = ret.text + htmlEncodeApexesAndTags(removeLineFeed(token));
                }
            }

            // must close remaining tags
            while (openTags.Count() > 0)
            {
                //pop all elements before tag and close it
                String poppedTag = openTags.Pop();
                ret.html = ret.html + "</" + poppedTag + ">";
                ret.val  = ret.val + "</" + poppedTag + ">";
            }

            //set boolean value
            ret.isValid = ret.invalidTags.Count == 0;

            return(ret);
        }
Example #6
0
        private String[] Parse(String s)
        {
            String[]       s1 = new String[s.Length];
            Stack <String> st = new Stack <String>();
            int            i  = 0;

            s = s.Replace("ln", "l");
            s = s.Replace("cos", "c");
            s = s.Replace("sin", "s");
            int t = 0;

            for (int j = 0; j < s.Length; j++)
            {
                String c = s[j] + "";
                if (functionCheek(c))
                {
                    t = 1;
                }
                if (numberCheek(c))
                {
                    s1[i] = c;
                    while (s.Length > j + 1 && numberCheek(s[j + 1] + ""))
                    {
                        j++;
                        s1[i] += s[j];
                    }
                    i++;
                }
                else
                if (operatorCheek(c))
                {
                    while (!(st.Count() == 0))
                    {
                        if (priority(st.Peek()) >= priority(c))
                        {
                            s1[i] = st.Peek();
                            st.Pop();
                            i++;
                        }
                        else
                        {
                            break;
                        }
                    }
                    st.Push(c);
                }
                else
                if ((c == "(" || functionCheek(c)) && t == 1)
                {
                    st.Push(c);
                }
                else
                if (c == ")" && t == 1)
                {
                    while (st.Peek() != "(")
                    {
                        s1[i] = st.Peek();
                        st.Pop();
                        i++;
                    }
                    st.Pop();

                    if (functionCheek(st.Peek()))
                    {
                        s1[i] = st.Peek();
                        st.Pop();
                        i++;
                    }
                    t = 0;
                }
                else
                if (c == "(")
                {
                    st.Push(c);
                }
                else
                if (c == ")")
                {
                    while (st.Peek() != "(")
                    {
                        s1[i] = st.Peek();
                        st.Pop();
                        i++;
                    }
                    st.Pop();
                }
            }
            while (!(st.Count() == 0))
            {
                s1[i] = st.Peek();
                st.Pop();
                i++;
            }

            return(s1);
        }