public void Insert(string inputString, int insertPosition)
 {
     char[] inputCharArray = inputString.ToCharArray();
     LinkedList<char> newLinkedList = new LinkedList<char>();
     int total = inputCharArray.Length + linkedList.Count;
     List<char> charList = new List<char>();
     foreach(char c in linkedList)
     {
         charList.Add(c);
     }
     int baseIndexCounter = 0;
     for (int index = 0; index < total; index++)
     {
         if(index == insertPosition)
         {
             foreach(char nextChar in inputCharArray)
             {
                 newLinkedList.AddLast(nextChar);
                 index++;
             }
         }
         newLinkedList.AddLast(charList[baseIndexCounter]);
         baseIndexCounter++;
     }
     linkedList = newLinkedList;
     PrintEachItem();
 }
 public void Remove(int startIndex, int numCharsToRemove)
 {
     LinkedList<char> newLinkedList = new LinkedList<char>();
     int total = linkedList.Count;
     int baseIndexCount = 0;
     List<char> charList = new List<char>();
     foreach (char c in linkedList)
     {
         charList.Add(c);
     }
     for (int index = 0; index < total; index++)
     {
         if (index == startIndex)
         {
             for (int count = 0; count < numCharsToRemove; count++)
             {
                 index++;
             }
         }
         newLinkedList.AddLast(charList[index]);
         baseIndexCount++;
     }
     linkedList = newLinkedList;
     PrintEachItem();
 }
示例#3
0
        public List<string> FindAllSumPath(TreeNode<int> root, int sum)
        {
            List<string> results = new List<string>();

            Stack<int> stack = new Stack<int>();

            FindAllSumPathRecursive(root, results, stack, sum, 0);

            return results;
        }
        public EventProcessor(NotificationQueue q, DbStatusObject dbStatusObj, string dbPath)
        {
            queue = q;
            conn = new SQLiteConnection(dbPath);
            //@"Data Source=" + System.Environment.GetEnvironmentVariable("windir") + "\\system\\AccessTrackerDB");

            TrimOpenAccessTimer = new System.Timers.Timer(1000 * 60 * TRIM_OPEN_ACCESS_INTERVAL); //Interval specified in milliseconds
            killedProcessList = new List<Win32ProcessInfo>();
            procDeleteWatcher = new ProcessDeleteWatcherAsync(killedProcessList);
            dbStatus = dbStatusObj;
        }
示例#5
0
        public List<string> CombinationSum(int[] input, int sum)
        {
            if (input == null || input.Length == 0)
            {
                throw new NullReferenceException("input is null");
            }

            List<string> results = new List<string>();

            GenerateSum(results, input, string.Empty, sum);

            return results;
        }
示例#6
0
        static void Main(string[] args)
        {
            // TestMoveBit();

            // Test1();

            // Test List<T>
            ArrayList myArrayList = new ArrayList();
            myArrayList.Add(3);
            List<int> myInt = new List<int>();
            myInt.Add(3);

            Console.ReadKey();
        }
示例#7
0
        //Cities data
        public static List<Cities> CityData()
        {
            var seattle = new Cities();
            List<Cities> cities = new List<Cities>();

            seattle.CityName = "Seattle, WA";
            seattle.CityPopulation = 652405;

            var redmond = new Cities();
            redmond.CityName = "Redmond, WA";
            redmond.CityPopulation = 57530;

            var spokane = new Cities();
            spokane.CityName = "Spokane, WA";
            spokane.CityPopulation = 208916;

            var bellevue = new Cities();
            bellevue.CityName = "Bellevue, MO";
            bellevue.CityPopulation = 200123;

            var everette = new Cities();
            everette.CityName = "Everette, WA";
            everette.CityPopulation = 133992;

            var olympia = new Cities();
            olympia.CityName = "Olympia, WA";
            olympia.CityPopulation = 48338;

            var tacoma = new Cities();
            tacoma.CityName = "Tacoma, WA";
            tacoma.CityPopulation = 133992;

            var ellensburge = new Cities();
            ellensburge.CityName = "Ellensburge, WA";
            ellensburge.CityPopulation = 18111;

            cities.Add(seattle);
            cities.Add(redmond);
            cities.Add(spokane);
            cities.Add(bellevue);
            cities.Add(everette);
            cities.Add(olympia);
            cities.Add(tacoma);
            cities.Add(ellensburge);

            return cities;
        }
        //        public static void Main(){ genericList(); }
        private static void genericList()
        {
            List<string> strs = new List<string>();

            strs.Add("one");
            strs.Add("two");
            strs.Add("three");
            strs.Add("four");

            //all in one
            for(int i=0; i<strs.Count; i++){
                con.Write( strs[i] + "." );
            }

            //foreach
            foreach(string str in strs){
                Console.Write(str + ",");
            }
        }
示例#9
0
        private void FindAllSumPathRecursive(TreeNode<int> node, List<string> results, Stack<int> stack, int sum, int currentSum)
        {
            if (node == null)
            {
                return;
            }

            if (node.LeftNode == null && node.RightNode == null)
            {
                if (currentSum + node.Value == sum)
                {
                    int[] array = new int[stack.Count];
                    stack.CopyTo(array, 0);
                    results.Add(node.Value + " " + string.Join(" ", array));
                }

                return;
            }

            stack.Push(node.Value);

            FindAllSumPathRecursive(node.LeftNode, results, stack, sum, currentSum + node.Value);

            FindAllSumPathRecursive(node.RightNode, results, stack, sum, currentSum + node.Value);

            stack.Pop();
        }
        public static BinarySearchTree<EventEntry> getEventsForFilters(List<InternalFilter> allFilters, Byte requestedDataType, 
            IPAddress reqIP, ref String lastTime, string dbPath)
        {
            SQLiteConnection conn = null;
            BinarySearchTree<EventEntry> resultTree = null;

            try
            {
                using (conn = new SQLiteConnection(dbPath))
                {
                    conn.Open();
                    using (SQLiteCommand myCommand = new SQLiteCommand())
                    {
                        string query = getQueryForFilters(myCommand, allFilters, requestedDataType, reqIP, lastTime);
                        if (query == null)
                        {
                            CLogger.WriteLog(ELogLevel.ERROR, "Null query returned");
                            return null;
                        }

                        myCommand.CommandText = query;
                        myCommand.Connection = conn;

                        SQLiteDataReader reader = myCommand.ExecuteReader();
                        resultTree = new BinarySearchTree<EventEntry>();
                        EventEntry entry;
                        bool firstRecord = true;

                        if (reader.HasRows)
                        {
                            while (reader.Read())
                            {
                                entry = new EventEntry();
                                try
                                {
                                    entry.timestamp = DateTime.Parse(reader.GetString(0));
                                    if (firstRecord == true)
                                    {
                                        if (requestedDataType == Common.INITIAL || requestedDataType == Common.UPDATE)
                                        {
                                            lastTime = reader.GetString(0);
                                            OperatingSystem osInfo = Environment.OSVersion;
                                            if (osInfo.Version.Major == 5) /* WIN_SERVER_2003 */
                                                lastTime += ".000";
                                        }
                                        else
                                        {
                                            lastTime = Common.DEFAULT;
                                        }
                                        firstRecord = false;
                                    }

                                }
                                catch (Exception ex)
                                {
                                    CLogger.WriteLog(ELogLevel.ERROR, ex.Message + "\n" + ex.StackTrace);
                                    entry.timestamp = new DateTime();
                                }
                                entry.fileName = reader.GetString(1);
                                entry.userName = reader.GetString(2);
                                entry.action = reader.GetString(3);
                                entry.fileType = reader.GetString(4);
                                entry.result = reader.GetString(5);
                                entry.Machine = System.Environment.MachineName;
                                resultTree.Add(entry);
                            }
                        }
                        else //if(reader.HasRoes)
                        {
                            if (requestedDataType == Common.INITIAL)
                            {
                                CLogger.WriteLog(ELogLevel.DEBUG, " Data Type is Initial, so setting Time to Default ");
                                lastTime = Common.DEFAULT;
                            }
                        }
                        conn.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                CLogger.WriteLog(ELogLevel.ERROR, ex.Message + "\n" + ex.StackTrace);
                //throw(ex);
            }
            finally
            {
                if (conn != null)
                    ((IDisposable)conn).Dispose();
            }

            return resultTree;
        }
示例#11
0
文件: Program.cs 项目: Miltt/Console
        private static string Output(List list)
        {            
            Node iterator = list.FirstNode;
            string values = String.Empty;

            while (iterator != null)
            {
                values += iterator.Data;
                iterator = iterator.Next;                
            }

            return values;
        }
示例#12
0
        private void GetParentheses(List<string> results, string oneResult, int number, int leftNumber, int rightNumber)
        {
            if (leftNumber == number && rightNumber == number)
            {
                results.Add(oneResult);
                return;
            }

            if (leftNumber < number)
            {
                oneResult += "(";
                GetParentheses(results, oneResult, number, leftNumber + 1, rightNumber);
            }

            if (rightNumber < number && rightNumber < number)
            {
                oneResult += ")";
                GetParentheses(results, oneResult, number, leftNumber, rightNumber + 1);
            }
        }
示例#13
0
        private void RestoreUtil(string s, string resultstr, int start, int count, List<string> results)
        {
            int maxlen = 3;

            if (count == 3)
            {
                string ip = s.Substring(start, s.Length - start);

                if (IsValid(ip))
                {
                    resultstr +=  ip;
                    results.Add(resultstr);
                }

                return;
            }

            for (int i = 0; i < maxlen; i++)
            {
                string ip = s.Substring(start, i + 1);
                if (IsValid(ip))
                {
                    //resultstr += ip + ".";
                    RestoreUtil(s, resultstr + ip + ".", start + i + 1, count + 1, results);
                    //resultstr = resultstr.Remove(resultstr.Length - ip.Length);
                }
            }
        }
 public char[] GetAllChars()
 {
     char[] allCharacters = new char[Length()];
     List<Node> allNodes = new List<Node>();
     Node cur = head;
     while (cur.next != null)
     {
         allNodes.Add(cur);
         cur = cur.next;
     }
     allNodes.Add(cur);
     for (int i = 0; i < allCharacters.Length; i++)
     {
         allCharacters[i] = allNodes[i].data;
     }
     return allCharacters;
 }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="allFilters"></param>
        /// <param name="requestedDataType"></param>
        /// <param name="lastTime"></param>
        /// <returns></returns>
        private static string getQueryForFilters(
            SQLiteCommand myCommand, List<InternalFilter> allFilters, Byte requestedDataType, 
            IPAddress reqIP, String lastTime)
        {
            string searchBox1 = "";
            string searchBox2 = "";

            DateTime date1 = DateTime.MinValue;
            DateTime date2 = DateTime.MinValue;
            string dateQuery = "";
            int dateCount = 0;

            /*
            string machine = "";
            string machineQuery = "";
            int machineCount = 0;
            */

            string filename = "";
            int filenameCount = 0;
            string filenameQuery = "";

            string user = "";
            int userCount = 0;
            string userQuery = "";

            string action = "";
            string actionQuery = "";
            int actionCount = 0;

            string queryCategory = "";
            string queryCategoryQuery = "";
            int queryCategoryCount = 0;

            string result = "";

            //pattern to trim trailing OR's from the query
            char[] trimOR = { ' ', 'O', 'R' };

            /**
             * Iterate over each of the selected filter. Populate the corresponding vars with their vals. Generate the query as per the filter
             * criteria and then fire the query to get only the required items from the db.
            */
            int emptyFilter = 0;
            foreach (InternalFilter f in allFilters)
            {
                if (!f.Empty())
                {
                    searchBox1 = f.Search1;
                    searchBox2 = f.Search2;

                    //check if category and searchbox1 contains a value
                    if ((f.Category == null) || (searchBox1.Equals("")))
                    {
                        CLogger.WriteLog(ELogLevel.ERROR, "Search parameters insufficient");
                        throw new Exception("Search parameters insufficient");
                    }

                    // Handle * for some sensible cases like: machine, user, filename
                    if (f.Category.Equals("Time") || f.Category.Equals("TimeWritten"))
                    {
                        //code to get date 1 and date2
                        if (searchBox1.EndsWith(":"))
                        {
                            searchBox1 = searchBox1.Substring(0, 10);
                        }
                        if (searchBox2.EndsWith(":"))
                        {
                            searchBox2 = searchBox2.Substring(0, 10);
                        }

                        DateTime start;
                        try
                        {
                            start = DateTime.Parse(searchBox1);
                        }
                        catch (FormatException ex)
                        {
                            CLogger.WriteLog(ELogLevel.ERROR, ex.Message + " Start Date");
                            return null;
                        }

                        DateTime end;
                        try
                        {
                            end = DateTime.Parse(searchBox2);
                        }
                        catch (FormatException ex)
                        {
                            CLogger.WriteLog(ELogLevel.ERROR, ex.Message + " End Date");
                            end = start;
                        }

                        if (start.CompareTo(end) > 0)
                        {
                            DateTime tmp = start;
                            start = end;
                            end = tmp;
                        }

                        //TODO: this is not 24 hour conversion. check how this can be done.
                        //date1 = start.ToString("G", DateTimeFormatInfo.InvariantInfo);
                        //date2 = end.ToString("G", DateTimeFormatInfo.InvariantInfo);
                        date1 = start;
                        date2 = end;

                        dateQuery += " (timestamp between @date1" + dateCount + " AND @date2" + dateCount + ") OR ";
                        myCommand.Parameters.AddWithValue("@date1" + dateCount, date1);
                        myCommand.Parameters.AddWithValue("@date2" + dateCount, date2);
                        ++dateCount;

                        continue;
                    }

                    /*
                    if ("Machine".Equals(f.Category))
                    {
                        machine = f.Search1;
                        if (!"".Equals(machine))
                        {
                            if (machine.EndsWith("*") || machine.StartsWith("*"))
                            {
                                machine = machine.Replace("*", "%");
                                machineQuery += "machine like @machine" + machineCount + " OR ";
                            }
                            else
                            {
                                machineQuery += "machine = @machine" + machineCount + " OR ";
                            }
                            myCommand.Parameters.AddWithValue("@machine" + machineCount, machine);
                            ++machineCount;
                        }
                        continue;
                    }*/

                    if (f.Category.Equals("Object Name"))
                    {
                        searchBox1 = searchBox1.ToLower();
                        filename = searchBox1;

                        if (!"".Equals(filename))
                        {
                            if (filename.EndsWith("*") || filename.StartsWith("*"))
                            {
                                filename = filename.Replace("*", "%");
                                filenameQuery += "filename like @filename" + filenameCount + " OR ";
                            }
                            else
                            {
                                filename = "%" + filename + "%";
                                filenameQuery += "filename like @filename" + filenameCount + " OR ";
                            }
                            myCommand.Parameters.AddWithValue("@filename" + filenameCount, filename);
                            ++filenameCount;
                        }
                        continue;
                    }

                    if (f.Category.Equals("User"))
                    {
                        user = searchBox1;

                        if (!"".Equals(user))
                        {
                            if (user.EndsWith("*") || user.StartsWith("*"))
                            {
                                user = user.Replace("*", "%");
                                userQuery += "user like @user" + userCount + " OR ";

                            }
                            else
                            {
                                user = "******" + user;
                                userQuery += "user like @user" + userCount + " OR ";
                                //userQuery += "user = @user" + userCount + " OR ";
                            }
                            myCommand.Parameters.AddWithValue("@user" + userCount, user);
                            ++userCount;
                        }
                        continue;
                    }

                    if ("Action".Equals(f.Category))
                    {
                        action = searchBox1;

                        if (!"".Equals(action))
                        {
                            if (action.EndsWith("*") || action.StartsWith("*"))
                            {
                                action = action.Replace("*", "%");
                                actionQuery += "action like @action" + actionCount + " OR ";
                            }
                            else
                            {
                                actionQuery += "action = @action" + actionCount + " OR ";
                            }
                            myCommand.Parameters.AddWithValue("@action" + actionCount, action);
                            ++actionCount;
                        }
                        continue;
                    }

                    if ("Category".Equals(f.Category))
                    {
                        queryCategory = searchBox1;
                        queryCategoryQuery += "filetype = @category" + queryCategoryCount + " OR ";
                        myCommand.Parameters.AddWithValue("@category" + queryCategoryCount, queryCategory);
                        ++queryCategoryCount;
                        continue;
                    }

                    if ("Result".Equals(f.Category))
                    {
                        result = searchBox1;
                        continue;
                    }
                }

                else
                {
                    emptyFilter++;
                }
            }

            string query;

            if ((allFilters.Count - emptyFilter) == 0)
            {
                if (requestedDataType == Common.UPDATE)
                {
                    //lastTime is in format
                    if (lastTime == Common.DEFAULT)
                    {
                        query = @"select distinct timestamp, filename, user, action, filetype, result from FAM
                                order by timestamp desc limit " + Common.MAX_NUM;
                    }
                    else
                    {
                        query = @"select distinct timestamp, filename, user, action, filetype, result from FAM
                                where timestamp > @TS order by timestamp desc";
                        SQLiteParameter param = myCommand.CreateParameter();
                        param.ParameterName = "@TS";
                        param.DbType = DbType.DateTime;
                        try
                        {
                            CLogger.WriteLog(ELogLevel.DEBUG, " Last Time is " + lastTime);
                            param.Value = DateTime.Parse(lastTime);
                        }
                        catch (Exception ex)
                        {
                            CLogger.WriteLog(ELogLevel.ERROR, ex.Message + "\n" + ex.StackTrace);
                            return null;
                        }
                        myCommand.Parameters.Add(param);
                    }
                }
                else
                {
                    query = @"select distinct timestamp, filename, user, action, filetype, result from FAM
                    order by timestamp desc limit " + Common.MAX_NUM;
                }
            }
            else
            {
                query = @"select distinct timestamp, filename, user, action, filetype, result from FAM where ";

                if (!date1.Equals(DateTime.MinValue) && !date2.Equals(DateTime.MinValue))
                {
                    dateQuery = dateQuery.TrimEnd(trimOR);
                    query += " (" + dateQuery + ") AND ";
                }

                /*
                if (!"".Equals(machine))
                {
                    machineQuery = machineQuery.TrimEnd(trimOR);
                    query += " (" + machineQuery + ") AND ";
                }
                */

                if (!"".Equals(filename))
                {
                    filenameQuery = filenameQuery.TrimEnd(trimOR);
                    query += " (" + filenameQuery + ") AND ";
                }

                if (!"".Equals(user))
                {
                    userQuery = userQuery.TrimEnd(trimOR);
                    query += " (" + userQuery + ") AND ";
                }

                if (!"".Equals(action))
                {
                    actionQuery = actionQuery.TrimEnd(trimOR);
                    query += " (" + actionQuery + ") AND ";
                }

                if (!"".Equals(queryCategory))
                {
                    queryCategoryQuery = queryCategoryQuery.TrimEnd(trimOR);
                    query += " (" + queryCategoryQuery + ") AND ";
                }

                if (!"".Equals(result))
                {
                    query += "result = @result AND ";
                    myCommand.Parameters.AddWithValue("@result", result);

                }

                char[] trim = { ' ', 'A', 'N', 'D' };
                query = query.TrimEnd(trim);
            }

            CLogger.WriteLog(ELogLevel.INFO, "Client: " + reqIP + " Query: " + query);
            return query;
        }
示例#16
0
        static void Main()
        {
            var start = new Point(9, 3);
            var end = new Point(1, 8);
            Func<Point, char> getCell = GetCell(MAZE);
            Func<Point, IEnumerable<Point>> getNeighbours = GetNeighbours(getCell);
            Func<Point, Point, int> getCost = (from, to) => getCell(to) == '@' ? 4:1 ;
            Func<Point, int> manhattanHeuristic = (to) => Math.Abs(to.X - end.X) + Math.Abs(to.Y - end.Y);
            Func<Point, double> manhattanHeuristicD = (to) => Math.Abs(to.X - end.X) + Math.Abs(to.Y - end.Y);

            var millisecondsTimeout = 100;

            var algorithms = new Dictionary<int, Tuple<string, Func<IEnumerable<Point>>, Func<IEnumerable<Point>>>>
            {
                {1, "Depth First Search", () =>  DepthFirstSearch.Explore(start, getNeighbours),()=>DepthFirstSearch.FindPath(start,getNeighbours,p => p.Equals(end) ) },
                {2, "Breadth First Search", () =>  BreadthFirstSearch.Explore(start, getNeighbours) ,()=>BreadthFirstSearch.FindPath(start,getNeighbours,p => p.Equals(end) )},
                {3, "Dijkstra", () =>  Dijkstra.Explore(start, getNeighbours,getCost ) ,()=>Dijkstra.FindPath(start,getNeighbours,getCost,p => p.Equals(end) )},
                {4, "Greedy Best-First Search (with manhattan)", () => GreedyBestFirstSearch.Explore(start, getNeighbours, manhattanHeuristic),()=>GreedyBestFirstSearch.FindPath(start,getNeighbours,manhattanHeuristic,p => p.Equals(end) )},
                {5, "A* (with manhattan)", () => AStar.Explore(start, getNeighbours,getCost, manhattanHeuristicD),()=>AStar.FindPath(start,getNeighbours,getCost,manhattanHeuristicD,p => p.Equals(end) )},
            };

            int choice = 0;
            while (choice != 10)
            {
                Console.Clear();
                Console.WriteLine("Choose traversal algorithm :");

                foreach (var algorithm in algorithms)
                {
                    Console.WriteLine($"\t{algorithm.Key} - {algorithm.Value.Item1}");
                }

                while (choice == 0)
                {
                    int.TryParse(Console.ReadLine(), out choice);
                }
                var currentMaze = MAZE;

                var result = algorithms[choice].Item2();
                var path = algorithms[choice].Item3().ToList();

                var visited = new List<Point>();

                foreach (var item in result)
                {

                    visited.Add(item);
                    var lines = currentMaze.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
                    var line = lines[item.Y].ToCharArray();
                    line[item.X] = '*';
                    lines[item.Y] = new string(line);
                    currentMaze = string.Join(Environment.NewLine, lines);
                    DisplayMaze(currentMaze, visited.Count, 0,0, algorithms[choice].Item1);

                    Thread.Sleep(millisecondsTimeout);
                    if (item == end) break;

                }

                foreach (var item in path)
                {
                    var lines = currentMaze.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
                    var line = lines[item.Y].ToCharArray();
                    line[item.X] = '+';
                    lines[item.Y] = new string(line);
                    currentMaze = string.Join(Environment.NewLine, lines);
                }

                var pathcost = path.Aggregate(0, (current, point) => current + getCost(Point.Empty, point));

                DisplayMaze(currentMaze, visited.Count(), path.Count(),pathcost, algorithms[choice].Item1);

                choice = 0;
                Console.WriteLine();
                Console.WriteLine($"Press any key to reset");
                Console.Read();
            }
        }
        /// <summary>
        /// Is used to send a request to ther server - just calls the clientfunction.
        /// </summary>
        /// <param name="list">A list of internal filters</param>
        public void ClientSendRequest(List<InternalFilter> list, Byte updateType)
        {
            if (this.InvokeRequired) {
            ClientSendRequestDelegate d=new ClientSendRequestDelegate(ClientSendRequest);

                this.Invoke(d,new object[] {list,updateType});
            }
            else
            {
                lastRequestType = updateType;
                BinarySearchTree<EventEntry> bst;
                if (isLocalConn == true)
                    bst = DBSendRequest(list, updateType);
                else
                {
                    bst = client.ClientSendRequest(list, updateType);
                    temDBUsagePercent = client.getDbUsage;
                    if (client.getDbUsage <= 100)
                        dbProgressBar.Value = temDBUsagePercent;
                    else dbProgressBar.Value = 100;
                    tempAvailableDBSize = client.getAvaiableDBSize / 1048576;
                    tempAvailableDiskSpace = client.getAvaiableDiskSpace;

                    availablediskSpaceLabel.Text = "Available diskspace: " + tempAvailableDiskSpace + " MB";
                    if (client.getAvaiableDBSize >= 0)
                    {
                        if (tempAvailableDBSize != 0)
                        {
                            progressbarAfterLabel.Text = "" + temDBUsagePercent + "% (" + tempAvailableDBSize + " MB left)";

                        }
                        else if ((client.getAvaiableDBSize / 1024) != 0)
                        {
                            progressbarAfterLabel.Text = "" + temDBUsagePercent + "% (" + (client.getAvaiableDBSize / 1024) + " KB left)";
                        }
                        else
                        {
                            progressbarAfterLabel.Text = "" + temDBUsagePercent + "% (" + client.getAvaiableDBSize + " Bytes left)";
                        }
                    }else progressbarAfterLabel.Text = "100% (0 Bytes left)";
                    if (tempAvailableDBSize >= tempAvailableDiskSpace)
                    {
                        MessageBox.Show("The space left for the Audit Report database is less than the disk space. Please configure the settings on the server for the database properly.", "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }

                    if (temDBUsagePercent>=100)
                    {
                        MessageBox.Show("The database is 100% full. The Audit Report Server therefore stopped logging. Please backup the Audit Report database in order to see new log entries.", "Audit Report database is full", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        secondWarning = true;
                        firstWarning = true;
                    }
                    else if (temDBUsagePercent == 99)
                    {
                        MessageBox.Show("The database is 99% full. The Audit Report Server will stop logging at 100%. Please backup the Audit Report database.", "Audit Report database is almost full", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        secondWarning = true;
                        firstWarning = true;
                    }
                    else if (temDBUsagePercent >= 90 && secondWarning == false)
                    {
                        MessageBox.Show("The Audit Report database is "+ temDBUsagePercent+"% full. Please back it up as soon as possible.", "audit Report database is almost full", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        secondWarning = true;
                        firstWarning = true;
                    }

                    else if (temDBUsagePercent >= 70 && firstWarning == false)
                    {
                        MessageBox.Show("The Audit Report database is " + temDBUsagePercent + "% full. Please back it up soon.", "Audit Report database is getting full", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        firstWarning = true;
                    }

                }
                if (bst != null)
                {
                    if (updateType == Common.INITIAL || updateType == Common.CUSTOM)
                    {

                        setEvents(bst);
                    }
                    else
                    {
                        mergeEvents(bst);

                    }
                    SetDataForColumns();
                }
            }
        }
示例#18
0
        /// <summary>
        /// Is used to send a request to ther server.
        /// </summary>
        /// <param name="list">A list of internal filters</param>
        /// <param name="allOrUpdate">
        /// If set to ALL, gets the MAX_NUM most recent messages
        /// If set to UPDATE, gets the most recent messages from the last timestamp
        /// </param>
        public BinarySearchTree<EventEntry> ClientSendRequest(List<InternalFilter> list, Byte updateType)
        {
            Socket sock = clientSocket;
            BinarySearchTree<EventEntry> bst = null;

            try
            {
                if (isConnected())
                {
                    #region send request to server

                    BinaryFormatter bf = new BinaryFormatter();
                    MemoryStream ms = new MemoryStream();
                    ASCIIEncoding asen = new ASCIIEncoding();

                    if (Monitor.TryEnter(this, 600 * 1000))
                    {
                        try
                        {
                            byte[] strTime;
                            if (updateType == Common.UPDATE)
                            {
                                strTime = asen.GetBytes(lastTimeReceived);
                            }
                            else
                            {
                                strTime = asen.GetBytes(Common.DEFAULT);
                            }
                            ms.Write(strTime, 0, Common.TIMELENGTH);

                            bf.Serialize(ms, list);
                            byte[] payload = ms.GetBuffer();
                            int payloadLength = payload.Length;

                            //make sure that we are sending 32 bytes regardless of the length of the actual data to be sent.
                            //this is to make sure that server will read 32 bytes on 1st read he will get the data we want it to get.
                            // Adding an additional 1 byte denote message type ALL, UPDATE, CUSTOM
                            int headerLength = 33;

                            byte[] header = new byte[headerLength];
                            header[0] = updateType;
                            byte[] msg = asen.GetBytes("" + payloadLength);
                            Buffer.BlockCopy(msg, 0, header, 1, msg.Length);

                            sock.Send(header, header.Length, 0);

                            //since we have sent the length of data 1st we can send exactly that much data and server is expected to read that amt only.
                            sock.Send(payload, payload.Length, 0);

                    #endregion

                            #region read answer from server

                            byte[] bb = new byte[32];

                            // make sure the we have read 32 bytes of data.
                            int received = 0;
                            do
                            {
                                received += sock.Receive(bb, received, bb.Length - received, 0);

                            } while (received < bb.Length);

                            string rcv = "";

                            for (int i = 0; i < received; i++)
                            {
                                if (bb[i] != 0)
                                    rcv += Convert.ToChar(bb[i]);
                            }

                            int length = Int32.Parse(rcv);

                            bb = new byte[length];

                            //make sure that we have read bb.lenght amount of data.
                            received = 0;
                            do
                            {
                                received += sock.Receive(bb, received, bb.Length - received, 0);

                            } while (received < bb.Length);

                            if (updateType == Common.INITIAL || updateType == Common.UPDATE)
                            {
                                lastTimeReceived = asen.GetString(bb, 0, Common.TIMELENGTH);
                            }

                            dbUsage = bb[Common.TIMELENGTH];
                            availableDBSize = BitConverter.ToInt64(bb, Common.TIMELENGTH + 1);
                            availableDiskSpace = BitConverter.ToInt32(bb, Common.TIMELENGTH + 9);

                            bf = new BinaryFormatter();
                            ms = new MemoryStream(bb, Common.TIMELENGTH + 13, bb.Length - (Common.TIMELENGTH + 13));
                            bst = (BinarySearchTree<EventEntry>)bf.Deserialize(ms);

                        }
                        finally
                        {
                            Monitor.Exit(this);
                        }
                            #endregion
                    }
                    else
                    {
                        MessageBox.Show("Request timed out");
                    }
                }
                else
                {
                    MessageBox.Show("Connection reset by the server");
                }
            }
            catch (System.Runtime.Serialization.SerializationException)
            {
                //needed because when an updated by the client is performed and the db is empty a SerializationException is thrown.
            }
            catch (Exception Se)
            {
                string s = Se.Message;
                MessageBox.Show(s);
             }

            return bst;
        }
        /// <summary>
        /// this method creates a list of internal filters (without the GUI part)
        /// </summary>
        /// <returns>List of simplyfied filters</returns>
        public List<InternalFilter> ConvertFiltersToInternal()
        {
            List<InternalFilter> list = new List<InternalFilter>();

            foreach (Filter f in allFilter)
            {
                if (f.GetCategory() != null)
                {
                    list.Add(new InternalFilter(f.GetCategory(), f.GetSearch1(), f.GetSearch2()));
                   }
            }

            return list;
        }
示例#20
0
        public List<string> RestoreIPAddress(string s)
        {
            if (s == null || s.Length == 0)
            {
                return null;
            }

            List<string> results = new List<string>();

            RestoreUtil(s, string.Empty, 0, 0, results);

            return results;
        }
示例#21
0
        private void GenerateSum(List<string> results, int[] input, string s, int sum)
        {
            for (int i = 0; i < input.Length; i++)
            {
                if (s.Length > 0 && input[i] < (s[s.Length - 1] - '0'))
                {
                    continue;
                }

                if (sum - input[i] == 0)
                {
                    s += " " + input[i].ToString();
                    results.Add(s);
                    return;
                }
                else if (sum - input[i] > 0)
                {
                    s += " " + input[i].ToString();
                    GenerateSum(results, input, s, sum - input[i]);
                }
                else
                {
                    s = String.Empty;
                    return;
                }
            }
        }
示例#22
0
文件: Program.cs 项目: Miltt/Console
        static void Main(string[] args)
        {
            List linked = new List();
            linked.AddFirst("a");
            linked.AddFirst("b");
            linked.AddLast("c");
            linked.AddAfter(linked.FirstNode, "u");
            linked.AddBefore(linked.LastNode, "p");                               
            linked.Remove(linked.FindFirst("b"));                       
            linked.Reverse();

            Console.WriteLine(Output(linked));
            Console.WriteLine("Press any key...");
            Console.ReadKey();
        }
        private BinarySearchTree<EventEntry> DBSendRequest(List<InternalFilter> list, Byte updateType)
        {
            IPHostEntry IPHost = Dns.GetHostEntry("localhost");
            IPAddress[] addr = IPHost.AddressList;
            BinarySearchTree<EventEntry> tree;

            tree = QueryProcessor.getEventsForFilters(list, updateType, addr[0], ref lastTimeReceived, dbConnString);

            if (tree == null) {
                MessageBox.Show("No data found...","",MessageBoxButtons.OK,MessageBoxIcon.Error);
                con.Enabled = true;
                con.Visible = true;
              //  con.setLocalDBMessage = "Invalid or empty Audit Report database was selected.";
                con.Focus();
                this.Dispose();
            }
            return tree;
        }
示例#24
0
        public List<string> GenerateParentheses(int number)
        {
            List<string> results = new List<string>();

            GetParentheses(results, "", number, 0, 0);

            return results;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void TrimOpenAccessTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            CLogger.WriteLog(ELogLevel.INFO, "In Timer fired");

            Win32ProcessInfo procInfo;
            try
            {
                Process[] explorerProcList = Process.GetProcessesByName("explorer.exe");
                Process explorerInfo;
                DateTime timestamp = DateTime.Now;
                timestamp = timestamp.AddMinutes(-TRIM_OPEN_ACCESS_INTERVAL);

                for (int i = 0; i < explorerProcList.Length; i++)
                {
                    explorerInfo = explorerProcList[i];
                    procInfo = new Win32ProcessInfo();
                    procInfo.processID = explorerInfo.Id;
                    procInfo.timeStamp = timestamp;
                    lock(killedProcessList)
                    {
                        killedProcessList.Add(procInfo);
                    }
                }
            }
            catch (Exception exc)
            {
                CLogger.WriteLog(ELogLevel.INFO, "Exception occurred while opening explorer.exe but its ok to proceed." +
                                                    " System error: " +exc.Message);
            }

            /* Get the list of processes killed from table
             * Delete the entries from OPENACCESS with those pids which have entries older by
             * TRIM_OPEN_ACCESS_INTERVAL minutes */

            // Make a copy of the killedProcessList
            List<Win32ProcessInfo> currentList;
            lock (killedProcessList)
            {
                currentList = new List<Win32ProcessInfo>(killedProcessList);
                killedProcessList.Clear();
            }

            try
            {
                for (int i = currentList.Count; i > 0; i--)
                {
                    procInfo = currentList[i-1];

                    DateTime timeStamp = DateTime.Now;
                    timeStamp = timeStamp.AddMinutes(-TRIM_OPEN_ACCESS_INTERVAL);

                    if (timeStamp >= procInfo.timeStamp)
                    {
                        using (SQLiteCommand cmd = new SQLiteCommand())
                        {
                            cmd.Connection = conn;
                            cmd.CommandText = "DELETE FROM OPENACCESS WHERE pid =" + procInfo.processID +
                                            " AND timestamp <= @TS";

                            SQLiteParameter param = cmd.CreateParameter();
                            param.ParameterName = "@TS";
                            param.DbType = DbType.DateTime;
                            param.Value = procInfo.timeStamp;
                            cmd.Parameters.Add(param);

                            int rowsAffected = cmd.ExecuteNonQuery();
                            CLogger.WriteLog(ELogLevel.DEBUG, "Removed pid: " + procInfo.processID);
                            currentList.RemoveAt(i-1);
                        }
                    }
                }

                /* Add the remaining elements in the current list to the killedProcessList
                 * which might have changed when were deleting the records
                 *
                 */
                lock (killedProcessList)
                {
                    killedProcessList.AddRange(currentList);
                }
            }
            catch (Exception exc)
            {
                CLogger.WriteLog(ELogLevel.ERROR, exc.Message + "\n" + exc.StackTrace);
            }
        }
示例#26
-1
        private List<string> Perm(string a, string c)
        {
            if (c.Length == 1)
            {
                return new List<string>() {a + c};
            }

            List<string> tempResults = new List<string>();
            for (int i = 0; i < c.Length; i++)
            {
                string temp = c;
                tempResults.AddRange(Perm(c.Substring(i, 1), temp.Remove(i, 1)));
            }

            List<string> results = new List<string>();

            tempResults.ForEach(i => results.Add(a + i));

            return results;
        }
示例#27
-3
        public List<string> PermutationDFS(string input)
        {
            List<string> results = new List<string>();

            for (int i = 0; i < input.Length; i++)
            {
                string temp = input;
                results.AddRange(Perm(input.Substring(i, 1), temp.Remove(i, 1)));
            }

            return results;
        }
示例#28
-5
        public static List<int> MergeTwoSortedList(List<int> list1, List<int> list2)
        {
            if(list1 == null || list1.Count == 0)
            {
                return (list2 == null || list2.Count == 0) ?  new List<int>() : list2;
            }
            else if (list2 == null || list2.Count == 0)
            {
                return (list1 == null || list1.Count == 0) ? new List<int>() : list1;
            }

            List<int> newList = new List<int>();

            int index1 = 0, index2 = 0;

            while (index1 < list1.Count && index2 < list2.Count)
            {
                newList.Add((list1[index1] <= list2[index2]) ? list1[index1++] : list2[index2++]);
            }

            if (index1 >= list1.Count)
            {
                newList.AddRange(list2.GetRange(index2, list2.Count-index2));
            }
            else
            {
                newList.AddRange(list1.GetRange(index1, list1.Count - index1));
            }

            return newList;
        }