Beispiel #1
0
        public static byte[] ConvertStringCollectionToByte(System.Collections.Specialized.StringCollection stringCollection)
        {
            string[] stringArray = new string[stringCollection.Count];
            stringCollection.CopyTo(stringArray, 0);

            return(stringArray.Select(byte.Parse).ToArray());
        }
        static string[] _ToArray(System.Collections.Specialized.StringCollection refs)
        {
            var result = new string[refs.Count];

            refs.CopyTo(result, 0);
            return(result);
        }
Beispiel #3
0
        public ServiceMain()
        {
            InitializeComponent();
            _logFile             = new Logging();
            _logFile.logFileName = "EventLog";
            _logFile.WriteToLog("EventLog has been created.");

            string minuteDisplay;
            int    timerIntervalMinutes = Properties.Settings.Default.TimerIntervalMinutes;

            minuteDisplay = timerIntervalMinutes == 1 ? " minute." : " minutes.";

            _timerIntervalMilliseconds = 1000 * 60 * timerIntervalMinutes;
            _logFile.WriteToLog("Timer interval set to " + timerIntervalMinutes.ToString() + minuteDisplay);

            System.Collections.Specialized.StringCollection sc = new System.Collections.Specialized.StringCollection();
            sc = Properties.Settings.Default.ScanDirectories;
            string[] scanDir = new string[sc.Count];

            //Copies all rows from string collection
            sc.CopyTo(scanDir, 0);

            string dirDisplay;

            dirDisplay = sc.Count == 1 ? "directory" : "directories";
            _logFile.WriteToLog("The following source " + dirDisplay + " will be scanned:");
            foreach (string dirName in scanDir)
            {
                _logFile.WriteToLog("--> " + dirName);
            }

            //jvc
            string failedDir = Properties.Settings.Default.FailedDirectory;

            _logFile.WriteToLog("FailedDirectory=" + failedDir);

            string outputDir         = Properties.Settings.Default.OutputDirectory;
            string processedDir      = Properties.Settings.Default.ProcessedDirectory;
            string validFileExt      = Properties.Settings.Default.ValidFileExt;
            bool   isDebugLogEnabled = Properties.Settings.Default.DebugLogEnabled;

            //_logFile.WriteToLog("OutputDirectory=" + outputDir);
            _logFile.WriteToLog("ProcessedDirectory=" + processedDir);
            _logFile.WriteToLog("ValidFileExt=" + validFileExt);
            _logFile.WriteToLog("DebugLogEnabled=" + isDebugLogEnabled);

            _logFile.WriteToLog("Creating DirectoryPoller...");
            _dirProcessor = new DirectoryProcessor(scanDir, validFileExt, outputDir, processedDir, failedDir, _logFile);
            _dirProcessor._isDebugLogEnabled = isDebugLogEnabled;
            _dirProcessor._EventLog          = _logFile;
            _logFile.WriteToLog("DirectoryPoller was successfully created.");

            this.timerMain.Interval = _timerIntervalMilliseconds;
            //this.timerMain.Elapsed += new System.Timers.ElapsedEventHandler(timerMain_Elapsed);

            // If the timer is declared in a long-running method, use
            // KeepAlive to prevent garbage collection from occurring
            // before the method ends.
            GC.KeepAlive(timerMain);
        }
        public TestDirProcMain()
        {
            InitializeComponent();
            _EventLog = new Logging();
            _EventLog.logFileName = "EventLog";
            _EventLog.WriteToLog("EventLog has been created.");

            _validExtList =  Properties.Settings.Default.ValidFileExt.Split(',').ToList<string>();
            System.Collections.Specialized.StringCollection sc = new System.Collections.Specialized.StringCollection();
            sc = Properties.Settings.Default.ScanDirectories;
            if (sc.Count > 0)
            {
                _scanDirs = new string[sc.Count];
                sc.CopyTo(_scanDirs, 0);
            }
            else
            {
                _scanDirs = new string[1];
                _scanDirs[0] = Properties.Settings.Default.ScanDirectory;
            }
            
            tbRootDir.Text = initTestDirectory(_scanDirs[0], "Scan");
            tbOuputDir.Text = initTestDirectory(Properties.Settings.Default.OutputDirectory,"Output");
            tbFailedDir.Text = initTestDirectory(Properties.Settings.Default.FailedDirectory,"Failed");;
            tbProcessedDir.Text = initTestDirectory(Properties.Settings.Default.ProcessedDirectory, "Processed"); ;
            tbFileName.Text = Properties.Settings.Default.TestFileName;
           
        }
        /// ---------------------------------------------------------------------------------------
        /// <summary>
        ///     指定した検索パターンに一致するファイルを最下層まで検索しすべて返します。</summary>
        /// <param name="stRootPath">
        ///     検索を開始する最上層のディレクトリへのパス。</param>
        /// <param name="stPattern">
        ///     パス内のファイル名と対応させる検索文字列。</param>
        /// <returns>
        ///     検索パターンに一致したすべてのファイルパス。</returns>
        /// ---------------------------------------------------------------------------------------
        public static string[] GetFilesMostDeep(string stRootPath, string stPattern)
        {
            System.Collections.Specialized.StringCollection hStringCollection = (
                new System.Collections.Specialized.StringCollection()
                );

            // このディレクトリ内のすべてのファイルを検索する
            foreach (string stFilePath in Directory.GetFiles(stRootPath, stPattern))
            {
                hStringCollection.Add(stFilePath);
            }

            // このディレクトリ内のすべてのサブディレクトリを検索する (再帰)
            foreach (string stDirPath in Directory.GetDirectories(stRootPath))
            {
                string[] stFilePaths = GetFilesMostDeep(stDirPath, stPattern);

                // 条件に合致したファイルがあった場合は、ArrayList に加える
                if (stFilePaths != null)
                {
                    hStringCollection.AddRange(stFilePaths);
                }
            }

            // StringCollection を 1 次元の String 配列にして返す
            string[] stReturns = new string[hStringCollection.Count];
            hStringCollection.CopyTo(stReturns, 0);

            return(stReturns);
        }
Beispiel #6
0
        private void DeleteFiles(bool silent)
        {
            System.Collections.Specialized.StringCollection files = new System.Collections.Specialized.StringCollection();
            IEnumerable <IBrowserItem> itemset = getComponent <IBrowser>().CurSelItems;

            foreach (IBrowserItem item in itemset)
            {
                files.Add(item.FullPath);
            }

            ShellLib.ShellFileOperation fo = new ShellLib.ShellFileOperation();

            string[] filearray = new string[files.Count];
            files.CopyTo(filearray, 0);
            fo.Operation   = ShellLib.ShellFileOperation.FileOperations.FO_DELETE;
            fo.OwnerWindow = m_windowhandle;
            fo.SourceFiles = filearray;

            fo.OperationFlags = ShellLib.ShellFileOperation.ShellFileOperationFlags.FOF_NO_CONNECTED_ELEMENTS
                                | ShellLib.ShellFileOperation.ShellFileOperationFlags.FOF_WANTNUKEWARNING;

            if (silent)
            {
                fo.OperationFlags = fo.OperationFlags | ShellLib.ShellFileOperation.ShellFileOperationFlags.FOF_NOCONFIRMATION;
            }

            bool retVal = fo.DoOperation();

            getComponent <IBrowser>().Refresh();

            if (retVal == false)
            {
                throw new Exception("Shell File Operation Failed");
            }
        }
Beispiel #7
0
        public string[] GetAllSubDirectories(string stRootPath)
        {
            System.Collections.Specialized.StringCollection hStringCollection = (
                new System.Collections.Specialized.StringCollection()
                );

            hStringCollection.Add(stRootPath);

            try
            {
                // このディレクトリ内のすべてのサブディレクトリを検索する (再帰)
                foreach (string stDirPath in System.IO.Directory.GetDirectories(stRootPath))
                {
                    string[] stFilePathes = GetAllSubDirectories(stDirPath);

                    // 条件に合致したファイルがあった場合は、ArrayList に加える
                    if (stFilePathes != null)
                    {
                        hStringCollection.AddRange(stFilePathes);
                    }
                }
            }
            catch (Exception)
            {
            }

            // StringCollection を 1 次元の String 配列にして返す
            string[] stReturns = new string[hStringCollection.Count];
            hStringCollection.CopyTo(stReturns, 0);

            return(stReturns);
        }
Beispiel #8
0
        public CB_Filecs()
        {
            InitializeComponent();

            System.Collections.Specialized.StringCollection listFile = null;
            listFile = Clipboard.GetFileDropList();
            //  Console.WriteLine(listFile.ToString());
            if (listFile.Count != 0)
            {
                this.Show();
                string[] array = new string[1000];

                listFile.CopyTo(array, 0);
                //   listFile.CopyTo(array, 1);
                int n = listFile.Count;
                for (int i = 0; i < n; i++)
                {
                    listBox1.Items.Add(array[i]);
                }
            }
            else
            {
                MessageBox.Show("No file in Clipboard");
            }
        }
Beispiel #9
0
        public ServiceMain()
        {
            InitializeComponent();
            _logFile = new Logging();
            _logFile.logFileName = "EventLog";
            _logFile.WriteToLog("EventLog has been created.");

            string minuteDisplay;
            int timerIntervalMinutes = Properties.Settings.Default.TimerIntervalMinutes;
            minuteDisplay = timerIntervalMinutes == 1 ? " minute." : " minutes.";

            _timerIntervalMilliseconds = 1000 * 60 * timerIntervalMinutes;
            _logFile.WriteToLog("Timer interval set to " + timerIntervalMinutes.ToString() + minuteDisplay);

            System.Collections.Specialized.StringCollection sc = new System.Collections.Specialized.StringCollection();
            sc = Properties.Settings.Default.ScanDirectories;
            string[] scanDir = new string[sc.Count];

            //Copies all rows from string collection
            sc.CopyTo(scanDir, 0);

            string dirDisplay;
            dirDisplay = sc.Count == 1 ? "directory" : "directories";
            _logFile.WriteToLog("The following source " + dirDisplay + " will be scanned:");
            foreach (string dirName in scanDir)
            {
                _logFile.WriteToLog("--> " + dirName);
            }

            //jvc
            string failedDir = Properties.Settings.Default.FailedDirectory;
            _logFile.WriteToLog("FailedDirectory=" + failedDir);

            string outputDir = Properties.Settings.Default.OutputDirectory;
            string processedDir = Properties.Settings.Default.ProcessedDirectory;
            string validFileExt = Properties.Settings.Default.ValidFileExt;
            bool isDebugLogEnabled = Properties.Settings.Default.DebugLogEnabled;

            //_logFile.WriteToLog("OutputDirectory=" + outputDir);
            _logFile.WriteToLog("ProcessedDirectory=" + processedDir);
            _logFile.WriteToLog("ValidFileExt=" + validFileExt);
            _logFile.WriteToLog("DebugLogEnabled=" + isDebugLogEnabled);

            _logFile.WriteToLog("Creating DirectoryPoller...");
            _dirProcessor = new DirectoryProcessor(scanDir, validFileExt, outputDir, processedDir, failedDir, _logFile);
            _dirProcessor._isDebugLogEnabled = isDebugLogEnabled;
            _dirProcessor._EventLog = _logFile;
            _logFile.WriteToLog("DirectoryPoller was successfully created.");

            this.timerMain.Interval = _timerIntervalMilliseconds;
            //this.timerMain.Elapsed += new System.Timers.ElapsedEventHandler(timerMain_Elapsed);

            // If the timer is declared in a long-running method, use
            // KeepAlive to prevent garbage collection from occurring
            // before the method ends.
            GC.KeepAlive(timerMain);
        }
Beispiel #10
0
        // Formats a string so that no line will have more than maxLen characters.
        // Input strings may not contain a \r or \n. To format multi-line strings call
        // FormatMultiLineMaxChars
        public static string[] FormatSingleLineMaxChars(int maxLen, string sLine)
        {
            System.Diagnostics.Debug.Assert(maxLen > 0, "Max must be at least 1");
            System.Diagnostics.Debug.Assert(-1 == sLine.IndexOf('\r'));
            System.Diagnostics.Debug.Assert(-1 == sLine.IndexOf('\n'));

            if (maxLen <= 0)
            {
                return(null);
            }
            if (0 == sLine.Length)
            {
                return new String[] { "" }
            }
            ;

            int currentStart = 0;
            int currentEnd;

            System.Collections.Specialized.StringCollection txt = new System.Collections.Specialized.StringCollection();

            while (currentStart < sLine.Length)
            {
                if (currentStart + maxLen < sLine.Length)
                {
                    currentEnd = Math.Min(currentStart + maxLen, sLine.Length - 1);

                    int spaceIdx = sLine.LastIndexOf(" ", currentEnd, currentEnd - currentStart);

                    if (-1 == spaceIdx)
                    {
                        txt.Add(sLine.Substring(currentStart, currentEnd - currentStart));
                        currentStart += maxLen;
                    }
                    else
                    {
                        txt.Add(sLine.Substring(currentStart, spaceIdx - currentStart));
                        currentStart = spaceIdx + 1;
                    }
                }
                else
                {
                    txt.Add(sLine.Substring(currentStart));
                    currentStart += maxLen;
                }
            }

            string[] lines = new string[txt.Count];
            txt.CopyTo(lines, 0);
            return(lines);
        }
Beispiel #11
0
        // Splits a string containing new lines (assumed to be \n or \r\n) and passes each
        // line to FormatSingleLineMaxChars and returns the resulting string array
        public static string[] FormatMultiLineMaxChars(int maxLen, string sLine)
        {
            System.Diagnostics.Debug.Assert(maxLen > 0, "Max must be at least 1");
            if (maxLen <= 0)
            {
                return(null);
            }

            string[] lines = sLine.Replace("\r", "").Split(new char[] { '\n' });
            System.Collections.Specialized.StringCollection formattedLines = new System.Collections.Specialized.StringCollection();

            foreach (string line in lines)
            {
                formattedLines.AddRange(FormatSingleLineMaxChars(maxLen, line));
            }

            string[] multi = new string[formattedLines.Count];
            formattedLines.CopyTo(multi, 0);
            return(multi);
        }
Beispiel #12
0
        public static string[] GetStringsFromClassConstants(System.Type type)
        {
            ArrayList constants = new ArrayList();

            System.Reflection.FieldInfo[] fieldInfos = type.GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.FlattenHierarchy);
            foreach (System.Reflection.FieldInfo fi in fieldInfos)
            {
                if (fi.IsLiteral && !fi.IsInitOnly)
                {
                    constants.Add(fi);
                }
            }
            System.Collections.Specialized.StringCollection ConstantsStringArray = new System.Collections.Specialized.StringCollection();
            foreach (System.Reflection.FieldInfo fi in (System.Reflection.FieldInfo[])constants.ToArray(typeof(System.Reflection.FieldInfo)))
            {
                ConstantsStringArray.Add(System.Convert.ToString(fi.GetValue(null)));
            }

            string[] retVal = new string[ConstantsStringArray.Count - 1 + 1];
            ConstantsStringArray.CopyTo(retVal, 0);
            return(retVal);
        }
Beispiel #13
0
        // Create a new ildocument for the given module.
        public ILDocument(string pathModule)
        {
            // ILDasm the file to produce a textual IL file.
            //   /linenum  tells ildasm to preserve line-number information. This is needed so that we don't lose
            // the source-info when we round-trip the il.

            string pathTempIl = Path.GetTempFileName();

            // We need to invoke ildasm, which is in the sdk.
            string pathIldasm = Program.SdkDir + @"\Bin\ildasm.exe";

            // We'd like to use File.Exists to make sure ildasm is available, but that function appears broken.
            // It doesn't allow spaces in the filenam, even if quoted. Perhaps just a beta 1 bug.

            Console.WriteLine("Invoking ildasm on file '{0}' to temp file '{1}'", pathModule, pathTempIl);
            Util.Run(pathIldasm, "\"" + pathModule + "\" /linenum /out=\"" + pathTempIl + "\"");


            // Now read the temporary file into a string list.
            StringCollection temp = new StringCollection();

            using (TextReader reader = new StreamReader(new FileStream(pathTempIl, FileMode.Open)))
            {
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    // Remove .maxstack since the inline IL will very likely increase stack size.
                    if (line.Trim().StartsWith(".maxstack"))
                    {
                        line = "// removed .maxstack declaration";
                    }

                    temp.Add(line);
                }
            }
            m_lines = new string[temp.Count];
            temp.CopyTo(m_lines, 0);
        }
Beispiel #14
0
        private string[] DoNickComplete(string word)
        {
            System.Collections.Specialized.StringCollection sc = new System.Collections.Specialized.StringCollection();

            foreach (ChanUser cu in lstUsers.Items)
            {
                if (cu.Nick.ToLower().StartsWith(word.ToLower()))
                {
                    sc.Add(cu.Nick);
                }
            }

            foreach (TreeNode tn in Obsidian.mainForm.tvcWindows.Nodes)
            {
                if (tn.Text.ToLower().StartsWith(word.ToLower()))
                {
                    sc.Add(tn.Text);
                }

                /* fix: go through channel window nodes, query nodes, etc. */
                foreach (TreeNode tn2 in tn.Nodes)
                {
                    foreach (TreeNode tn3 in tn2.Nodes)
                    {
                        if (tn3.Text.ToLower().StartsWith(word.ToLower()))
                        {
                            sc.Add(tn3.Text);
                        }
                    }
                }
            }

            string[] a = new string[sc.Count];
            sc.CopyTo(a, 0);
            return(a);
        }
Beispiel #15
0
        public ChangeKeybindForm()
        {
            InitializeComponent();

            textBox1.KeyDown += textBox1_KeyDown;
            textBox1.KeyUp   += textBox1_KeyUp;

            // Set keybind text to saved keybind data
            System.Collections.Specialized.StringCollection saved = Properties.Settings.Default.Keybind;
            string[] savedKeybinds = new string[saved.Count];
            saved.CopyTo(savedKeybinds, 0);
            string keybindInputText = "";

            for (int i = 0; i < savedKeybinds.Length; i++)
            {
                keybindInputText += savedKeybinds[i];

                if (i < savedKeybinds.Length - 1)
                {
                    keybindInputText += " + ";
                }
            }
            textBox1.Text = keybindInputText;
        }
        /// <summary>
        /// Load the addins to the FrontEnd
        /// </summary>
        /// <param name="ownerOfAddIn">Who will own this addin</param>
        /// <param name="objectAdapter">Some ice stuff</param>
        /// <param name="modulesManager">Modules Manager</param>
        /// <param name="displayer">Displayer of the properties (if an Add-in has a property)</param>
        private static void loadAddIns(IOwnerOfAddIn ownerOfAddIn,
            Ice.ObjectAdapter objectAdapter,
            Ferda.ModulesManager.ModulesManager modulesManager, Properties.IOtherObjectDisplayer displayer)
        {
            System.Collections.Specialized.StringCollection proxies
                = new System.Collections.Specialized.StringCollection();

            foreach(string file in System.IO.Directory.GetFiles("AddIns"))
            {
                if(System.IO.Path.GetExtension(file) == ".dll")
                {
                    string path = "Ferda.FrontEnd.AddIns." +
                        System.IO.Path.GetFileNameWithoutExtension(file) +
                        ".Main";

                    //tohle se nezvladne
                    Assembly asembly =
                        System.Reflection.Assembly.LoadFile(System.IO.Path.GetFullPath(file));

                    IAddInMain addInMain = (IAddInMain)asembly.CreateInstance(path);

                    //adding the properties displayer if it is a addin capable of
                    //displaying properties
                    if (addInMain is Properties.IPropertyProvider)
                    {
                        Properties.IPropertyProvider prov = addInMain as
                            Properties.IPropertyProvider;

                        prov.Displayer = displayer;
                    }

                    addInMain.OwnerOfAddIn = ownerOfAddIn;
                    addInMain.ObjectAdapter = objectAdapter;
                    proxies.AddRange(addInMain.ObjectProxiesToAdd);
                    addIns.Add(addInMain);
                }
            }
            int count = proxies.Count;
            string[] newServices = new string[count];
            if(count > 0)
            {
                proxies.CopyTo(newServices, 0);
            }
            modulesManager.AddModuleServices(newServices);
        }
Beispiel #17
0
        void Paste()
        {
            IDataObject obj = Clipboard.GetDataObject();

            int          dropeffect = 0;
            MemoryStream stream     = (System.IO.MemoryStream)obj.GetData("Preferred DropEffect");

            if (stream != null)
            {
                BinaryReader reader = new BinaryReader(stream);
                dropeffect = reader.ReadInt32();
            }

            System.Collections.Specialized.StringCollection files = Clipboard.GetFileDropList();
            ShellLib.ShellFileOperation fo = new ShellLib.ShellFileOperation();

            string[] filearray = new string[files.Count];
            files.CopyTo(filearray, 0);

            if ((DragDropEffects.Move & (DragDropEffects)dropeffect) == DragDropEffects.Move)
            {
                fo.Operation = ShellLib.ShellFileOperation.FileOperations.FO_MOVE;
            }
            else
            {
                fo.Operation = ShellLib.ShellFileOperation.FileOperations.FO_COPY;
            }

            fo.OwnerWindow = m_windowhandle;
            fo.SourceFiles = filearray;

            /*            if (filearray.Length == 0)
             *          {
             *              string[] destarray = new string[files.Count];
             *              for (int i = 0; i < files.Count; i++)
             *              {
             *                  string filename = files[i].Substring(files[i].LastIndexOf('\\'));
             *                  destarray[i] = Browser.CurrentDir.FullName + filename;
             *              }
             *              fo.DestFiles = destarray;
             *          }
             *          else*/
            {
                fo.OperationFlags = ShellLib.ShellFileOperation.ShellFileOperationFlags.FOF_ALLOWUNDO
                                    | ShellLib.ShellFileOperation.ShellFileOperationFlags.FOF_RENAMEONCOLLISION
                                    | ShellLib.ShellFileOperation.ShellFileOperationFlags.FOF_NO_CONNECTED_ELEMENTS
                                    | ShellLib.ShellFileOperation.ShellFileOperationFlags.FOF_WANTNUKEWARNING;

                fo.DestFiles = new string[] { getComponent <IBrowser>().CurrentDir.FullName };
            }

            try
            {
                bool retVal = fo.DoOperation();
                if (retVal == false)
                {
                    MessageBox.Show("Error Occurs");
                }
            }
            catch (Exception EE)
            {
                MessageBox.Show(EE.Message);
            }
        }
        /// <summary>
        /// Prevents a default instance of the <see cref="CLAutoThumbnailer"/> class from being created.
        /// </summary>
        /// <param name="args">Command line arguments.</param>
        /// <param name="baseDir">If created via command file the directory of the command file,
        /// otherwise <c>null</c>.</param>
        /// <exception cref="NDesk.Options.OptionException">Thrown when option error occurs.</exception>
        CLAutoThumbnailer(string[] args, string baseDir)
        {
            InitializeThumbnailSettings ();
            InitializeVideoRE ();

            System.Collections.Specialized.StringCollection fixedArgs =
                new System.Collections.Specialized.StringCollection ();
            foreach (string arg in args)
                {
                if (arg.EndsWith("\""))
                    {
                    fixedArgs.Add(arg.Remove(arg.Length-1));
                    }
                else
                    fixedArgs.Add(arg);
                }

            String[] fixedArgsArray = new String[fixedArgs.Count];
            fixedArgs.CopyTo(fixedArgsArray, 0);
            double doubleInterval = -1;

            _oset = new NDesk.Options.OptionSet () {
                { "d|directory=",
                  "{DIRECTORY} to process. Generate thumbnails for\n" +
                   "files with the following extensions:\n" +
                   _videoExtensions,
                  v => _directoryArg = v },
                { "exts=",
                  "add/remove video {EXTENSIONS} " +
                  "(\"[+]ext1, -ext2\")",
                    v =>
                    {
                    string[] exts = _commaRE.Split(v);
                    foreach (string ext in exts)
                        {
                        string s = ext.Trim().ToLower();
                        bool addExt = true;
                        if (s[0] == '-')
                            {
                            s = s.Substring(1);
                            addExt = false;
                            }
                        else if (s[0] == '+')
                            {
                            s = s.Substring (1);
                            }
                        if (addExt)
                            {
                            if (_videoExts.Contains (s))
                                THelper.Error ("Error: '{0}' is already in valid video extensions list.", s);
                            else
                                {
                                THelper.Information ("'{0}' added to valid video extensions list.", s);
                                _videoExts.Add (s);
                                _videoExtsChanged = true;
                                }
                            }
                        else
                            {
                            if (!_videoExts.Contains (s))
                                THelper.Error ("Error: '{0}' isn't in valid video extensions list.", s);
                            else
                                {
                                THelper.Information ("'{0}' removed from valid video extensions list.", s);
                                _videoExts.Remove (s);
                                _videoExtsChanged = true;
                                }
                            }
                        }
                    if (_videoExtsChanged)
                        {
                        System.Collections.ArrayList temp = System.Collections.ArrayList.Adapter(_videoExts);
                        temp.Sort ();
                        _videoExts = new System.Collections.Specialized.StringCollection ();
                        _videoExts.AddRange ((String[]) temp.ToArray(typeof(string)));
                        }
                    } },

                { "minsize=",
                   String.Format("Minimum {{FILESIZE}} of video files (0 to disable) [{0} ({1})]",
                                  _minFileSize, ThumbnailCreator.GetFileSizeString(_minFileSize)),
                    (long v) =>
                        {
                        if (v < 0)
                            v = 0;
                        _minFileSize = v;
                        } },

                { "m|cmddir=",
                   "create initial command file for {DIRECTORY}",
                   v => _cmdDirectory = v },

                { "s|start=",
                  String.Format(@"start {{TIME}} in h:mm:ss [{0}]",
                                _tnSettings.Start.ToString(@"h\:mm\:ss")),
                  (TimeSpan v) => _tnSettings.Start = v },
                { "e|end=",
                  String.Format(@"end {{TIME}} in h:mm:ss [{0}{1}]",
                                _tnSettings.End.TotalSeconds < 0 ? "-" : "",
                                _tnSettings.End.ToString(@"h\:mm\:ss")),
                  (TimeSpan v) => _tnSettings.End = v },

                { "v|overview",
                  String.Format("create Overview page (-v- disables) [{0}]",
                                _createOverview),
                  v => _createOverview = v != null },
                { "n=",
                  String.Format("Overview page desired # of {{ROWS or COLUMNS}} [{0}]",
                                _tnSettings.OverviewThumbs),
                  (int v) =>
                      {
                      if (v < 1)
                          v = 1;
                      _tnSettings.OverviewThumbs = v;
                      } },
                { "c|columns=",
                  String.Format("Overview page actual # of {{COLUMNS}} [{0}]",
                                _tnSettings.OverviewColumns),
                  (int v) =>
                      {
                      if (v < 1)
                          v = 1;
                      _tnSettings.OverviewColumns = v;
                      } },
                { "r|rows=",
                  String.Format("Overview page actual # of {{ROWS}} [{0}]",
                                _tnSettings.OverviewRows),
                  (int v) =>
                      {
                      if (v < 1)
                          v = 1;
                      _tnSettings.OverviewRows = v;
                      } },

                { "i|interval=",
                   String.Format("Detail page thumbnail interval {{SECONDS}} [{0:F2}]",
                                 _tnSettings.Interval.TotalSeconds),
                    (double v) =>
                        {
                        if (v != 0.0 && v < 1.0 / 30.0)
                            v = 1.0 / 30.0;
                        doubleInterval = v;
                        } },
                { "autointerval",
                   String.Format("use automatic interval based on duration [{0}]",
                                 _autoInterval),
                   v => _autoInterval = v != null },
                { "autointervals=",
                   String.Format("automatic interval {{SPECIFICATION}}\n" +
                                 "( <min1=secs1, <min2=secs2, <min3=secs3, secs4 )\n" +
                                 "[ {0} ]",
                                 _intervalsStr),
                   v => {
                        _intervalsStr = v;
                        InitializeAutoIntervals (_intervalsStr);
                        } },

                { "N=",
                  String.Format("Detail page desired # of {{ROWS or COLUMNS}} [{0}]",
                                _tnSettings.DetailThumbs),
                  (int v) =>
                      {
                      if (v < 1)
                          v = 1;
                      _tnSettings.DetailThumbs = v;
                      } },
                { "C|Columns=",
                  String.Format("Detail page actual # of {{COLUMNS}} [{0}]",
                                _tnSettings.DetailColumns),
                  (int v) =>
                      {
                      if (v < 1)
                          v = 1;
                      _tnSettings.DetailColumns = v;
                      } },
                { "R|Rows=",
                  String.Format("Detail page actual # of {{ROWS}} [{0}]",
                                _tnSettings.DetailRows),
                  (int v) =>
                      {
                      if (v < 1)
                          v = 1;
                      _tnSettings.DetailRows = v;
                      } },
                { "dfts",
                  String.Format("add Detail page filename timestamps\n" +
                                "(--dfts- disables) [{0}]",
                                _tnSettings.DetailFileTimestamps),
                  v => _tnSettings.DetailFileTimestamps = v != null },

                { "y|layout=",
                  String.Format("layout {{MODE}}\n(0=Auto,1=Actual,2=Row Priority,3=Column Priority) [{0}]",
                  _tnSettings.LayoutMode),
                  (int v) =>
                      {
                      if (v < 0 || v > 3)
                          v = 0;
                      _tnSettings.LayoutMode = (ThumbnailSettings.LayoutModes) v;
                      } },
                { "othres=",
                  String.Format("video aspect ratio {{THRESHOLD}} for\n" +
                                "Auto Layout of Overview Page [{0:F2}]",
                                _tnSettings.OverviewThreshold),
                  (double v) =>
                      {
                      if (v != 0.0 && v < 0.2)
                          v = 0.2;
                      if (v > 4.0)
                          v = 4.0;

                      _tnSettings.OverviewThreshold = v;
                      } },
                { "dthres=",
                  String.Format("video aspect ratio {{THRESHOLD}} for\n" +
                                "Auto Layout of Detail Pages [{0:F2}]",
                                _tnSettings.DetailThreshold),
                  (double v) =>
                      {
                      if (v != 0.0 && v < 0.2)
                          if (v < 0.2)
                          v = 0.2;
                      if (v > 4.0)
                          v = 4.0;

                      _tnSettings.DetailThreshold = v;
                      } },
                { "rcopt",
                  String.Format("do row/column optimizations\n" +
                                "(--rcopt- disables) [{0}]",
                  _tnSettings.RCOptimization),
                  v => _tnSettings.RCOptimization = v != null },
                { "maxoptsteps=",
                  String.Format("max # of row/column optimization {{STEPS}}\n" +
                                "(0=unlimited) [{0}]",
                  _tnSettings.MaxOptimizationSteps),
                  (int v) =>
                      {
                      if (v < 0)
                          v = 0;
                      _tnSettings.MaxOptimizationSteps = v;
                      } },
                { "wthres=",
                  String.Format("width {{THRESHOLD}} for adding columns (0.1 - 1.0) [{0:F2}]",
                                _tnSettings.WidthThreshold),
                  (double v) =>
                      {
                      if (v < 0.1)
                          v = 0.1;
                      if (v > 1.0)
                          v = 1.0;

                      _tnSettings.WidthThreshold = v;
                      } },
                { "hthres=",
                  String.Format("height {{THRESHOLD}} for adding rows (0.1 - 1.0)\n[{0:F2}]",
                                _tnSettings.HeightThreshold),
                  (double v) =>
                      {
                      if (v < 0.1)
                          v = 0.1;
                      if (v > 1.0)
                          v = 1.0;

                      _tnSettings.HeightThreshold = v;
                      } },
                { "mincols=",
                  String.Format("minimum # of {{COLUMNS}} [{0}]",
                                _tnSettings.MinColumns),
                  (int v) =>
                      {
                      if (v < 1)
                          v = 1;
                      _tnSettings.MinColumns = v;
                      } },
                { "minrows=",
                  String.Format("minimum # of {{ROWS}} [{0}]",
                                _tnSettings.MinRows),
                  (int v) =>
                      {
                      if (v < 1)
                          v = 1;
                      _tnSettings.MinRows = v;
                      } },

                { "p|crop=", "crop {ASPECT RATIO}",
                    (double v) =>
                        {
                        if (v < 0.2)
                            v = 0.2;
                        if (v > 4.0)
                            v = 4.0;
                        _cropAspect = v;
                        } },
                { "rect=", "source {RECTANGLE} ( X,Y+WxH )",
                    v =>
                    {
                    System.Text.RegularExpressions.Match m = _rectRE.Match (v);
                    if (!m.Success)
                        throw new NDesk.Options.OptionException (
                            "Need to specify X,Y+WxH for --rect option.",
                            "--rect");
                    _srcRect = new System.Drawing.Rectangle (Int32.Parse (m.Groups["x"].Value),
                                                             Int32.Parse (m.Groups["y"].Value),
                                                             Int32.Parse (m.Groups["w"].Value),
                                                             Int32.Parse (m.Groups["h"].Value));
                    } },

                { "t|stretch=", "stretch {ASPECT RATIO}",
                    (double v) =>
                        {
                        if (v < 0.2)
                            v = 0.2;
                        if (v > 4.0)
                            v = 4.0;
                        _stretchAspect = v;
                        } },
                { "aar",
                  String.Format("do auto aspect ratio adjustment\n" +
                                "(--aar- disables) [{0}]",
                                _autoAspectRatio),
                  v => _autoAspectRatio = v != null },

                { "o|outdir=",  "Output {DIRECTORY}",
                    v => _outputDirectory = v },
                { "subdir=",
                  String.Format("Output sub-directory {{NAME}} [\"{0}\"]",
                                _tnSettings.SubDirectory),
                    v =>
                        {
                        if (v=="" || !_subdirRE.IsMatch(v))
                            throw new NDesk.Options.OptionException (
                                "Subdirectory name can only contain alphanumerics, '_', and '-'.",
                                "--subdir");
                        _tnSettings.SubDirectory = v;
                        } },
                { "name=",  "Display {NAME}",
                    v => _displayFilename = v },

                { "l|label=",
                  String.Format("timestamp label {{POSITION}}\n(0=Off,1=LR,2=LL,3=UR,4=UL) [{0}]",
                  _tnSettings.LabelPosition),
                  (int v) =>
                      {
                      if (v < 0 || v > 4)
                          v = 1;
                      _tnSettings.LabelPosition = (ThumbnailSettings.LabelPositions) v;
                      } },
                { "ms",
                  String.Format("show non-zero millisecond display in timestamps [{0}]",
                                _tnSettings.AlwaysShowMilliseconds),
                  v => _tnSettings.AlwaysShowMilliseconds = v != null },

                { "f|scalefactor=",
                  String.Format("page {{SCALE FACTOR}} [{0:F2}]",
                  _tnSettings.ScaleFactor),
                  (double v) =>
                      {
                      if (v < 0.25)
                          v = 0.25;
                      if (v > 3.0)
                          v = 3.0;
                      _tnSettings.ScaleFactor = v;
                      } },
                { "w|width=",
                  String.Format("page width {{PIXELS}} [{0}]",
                  _tnSettings.Width),
                  (int v) =>
                      {
                      if (v < 100)
                          v = 100;

                      _tnSettings.Width = v;
                      } },
                { "h|height=",
                  String.Format("page height {{PIXELS}} [{0}]",
                  _tnSettings.Height),
                  (int v) =>
                      {
                      if (v < 100)
                          v = 100;

                      _tnSettings.Height = v;
                      } },
                { "margin=",
                  String.Format("margin between thumbnails {{PIXELS}} [{0}]",
                  _tnSettings.Margin),
                  (int v) =>
                      {
                      if (v < 0)
                          v = 0;
                      _tnSettings.Margin = v;
                      } },
                { "border=",
                  String.Format("thumbnail border width {{PIXELS}} [{0}]",
                  _tnSettings.Border),
                  (int v) =>
                      {
                      if (v < 0)
                          v = 0;
                      _tnSettings.Border = v;
                      } },

                { "save", "save current settings as defaults",
                   v => _saveSettings = v != null },
                { "reset", "reset settings to initial defaults",
                   v => _resetSettings = v != null },

                { "dumpcr:", "dump # columns/rows diagnostic plot to {FILE}",
                   v =>
                       {
                       _dumpCRs = true;
                       if (v != null)
                           {
                           _dumpFilename = v;
                           if (_dumpFilename.Contains ("|"))
                               {
                               string[] parts = _dumpFilename.Split (new char[] { '|' }, 2);
                               _dumpFilename = parts[1];
                               string flag = parts[0].Trim ().ToLower ();
                               if (flag.StartsWith ("nothr"))
                                   _dumpThresholds = false;
                               }
                           }
                       } },

                { "debug:",
                   String.Format("show debugging information"),
                   v =>
                       {
                       if (v == null)
                           _debug = DebugModes.ShowDebuggingMessages;
                       else
                           {
                           int debug = Int32.Parse (v);
                           if (debug < 0)
                               {
                               debug = -debug;
                               THelper.SetLoggerLevel("mainlogger",
                                                      System.Diagnostics.SourceLevels.Information);
                               }
                           else
                               {
                               THelper.SetConsoleLevel (System.Diagnostics.SourceLevels.Verbose);
                               }
                           _debug = (DebugModes) debug;
                           }
                       } },

                { "?|help",  "show this message and exit",
                    v => _show_help = v != null },
                { "version",  "show version and exit",
                    v => _show_version = v != null },

            #if false
                { "x|maxmulti=", "max # of multi-page {ROWS}",
                    (int v) => _tnSettings.MaxMultiRows = v },
                { "n|minoverview=", "minimum # of overview {ROWS}",
                    (int v) => _tnSettings.MinOverviewRows = v },
               NDesk.Options.Option rectOption = _oset.Add(
                    );
            #endif
                };

            List<string> extra;
            extra = _oset.Parse (fixedArgsArray);
            if (_show_help && baseDir != null)
                {
                ShowHelp (_oset);
                return;
                }

            if (_debug == DebugModes.ShowDebuggingMessages && baseDir != null)
                {
                THelper.Information ("Displaying debugging information.");
                }

            if (extra.Count > 0)
                {
                _filename = extra[0];
                }

            if (_filename != null)
                {
                if (baseDir != null)
                    {
                    if (!System.IO.Path.IsPathRooted (_filename))
                        _filename = System.IO.Path.Combine (baseDir, _filename);
                    }

                _fileList = CreateFileList (_filename);
                if (_fileList == null)
                    {
                    THelper.Critical ("\"" + _filename + "\" doesn't exist.");
                    _filename = null;
                    return;
                    }
                if (_fileList.Count == 0)
                    {
                    THelper.Critical ("\"" + _filename + "\" doesn't match any files.");
                    _filename = null;
                    _fileList = null;
                    return;
                    }
                }

            if (_directoryArg != null)
                {
                if (baseDir != null)
                    {
                    if (!System.IO.Path.IsPathRooted(_directoryArg))
                        _directoryArg = System.IO.Path.Combine(baseDir, _directoryArg);
                    }

                if (!System.IO.Directory.Exists(_directoryArg))
                    {
                    _directoryArg = null;
                    THelper.Critical ("\"" + _directoryArg + "\" doesn't exist.");
                    return;
                    }
                }

            if (doubleInterval != -1)
                {
                int intervalSeconds = (int) Math.Truncate (doubleInterval);
                int intervalMilliseconds = 0;
                double fractSeconds = Math.Abs (doubleInterval - (double) intervalSeconds);
                if (fractSeconds >= 0.001)
                    intervalMilliseconds = (int) (1000 * fractSeconds);

                _tnSettings.Interval = new TimeSpan (0, 0, 0,
                                                    intervalSeconds, intervalMilliseconds);
                }

            if (_tnSettings.OverviewThreshold == 0.0)
                _tnSettings.OverviewThreshold = _tnSettings.AspectRatio * _tnSettings.LayoutThresholdAdjustment;
            if (_tnSettings.DetailThreshold == 0.0)
                _tnSettings.DetailThreshold = _tnSettings.AspectRatio * _tnSettings.LayoutThresholdAdjustment;
        }
        static string[] GetArgs(string s)
        {
            System.Collections.Specialized.StringCollection scArgs =
                new System.Collections.Specialized.StringCollection ();
            StringBuilder arg = new StringBuilder ();

            bool seenQuote = false;
            foreach (char c in s)
                {
                if (char.IsWhiteSpace (c))
                    {
                    if (seenQuote)
                        arg.Append (c);
                    else
                        {
                        if (arg.Length > 0)
                            scArgs.Add (arg.ToString ());
                        arg.Clear ();
                        }
                    }
                else
                    {
                    if (c == '"')
                        {
                        seenQuote = !seenQuote;
                        }
                    else
                        {
                        arg.Append (c);
                        }
                    }
                }

            if (arg.Length > 0)
                scArgs.Add (arg.ToString ());

            String[] args = new String[scArgs.Count];
            scArgs.CopyTo (args, 0);

            return args;
        }
Beispiel #20
0
        private string[] DoNickComplete(string word)
        {
            System.Collections.Specialized.StringCollection sc = new System.Collections.Specialized.StringCollection();

            foreach (ChanUser cu in lstUsers.Items)
            {
                if (cu.Nick.ToLower().StartsWith(word.ToLower()))
                {
                    sc.Add(cu.Nick);
                }
            }

            foreach (TreeNode tn in Obsidian.mainForm.tvcWindows.Nodes)
            {
                if (tn.Text.ToLower().StartsWith(word.ToLower()))
                {
                    sc.Add(tn.Text);
                }

                /* fix: go through channel window nodes, query nodes, etc. */
                foreach (TreeNode tn2 in tn.Nodes)
                {
                    foreach (TreeNode tn3 in tn2.Nodes)
                    {
                        if (tn3.Text.ToLower().StartsWith(word.ToLower()))
                        {
                            sc.Add(tn3.Text);
                        }
                    }
                }
            }

            string[] a = new string[sc.Count];
            sc.CopyTo(a, 0);
            return a;
        }
Beispiel #21
0
            private static KeyValuePair <bool, object> RunCSharpCode(string CSharpCode, ulong currentGuild, ulong currentChannel, bool ShowErrors, string StringParameter)
            {
                try
                {
                    #region Encapsulate Code into a single Method
                    string Code =
                        "using System;" + Environment.NewLine +
                        "using System.IO;" + Environment.NewLine +
                        "using System.Text;" + Environment.NewLine +
                        "using System.Collections;" + Environment.NewLine +
                        "using System.Linq;" + Environment.NewLine +
                        "using System.Diagnostics;" + Environment.NewLine +
                        "using System.Xml;" + Environment.NewLine +
                        "using System.Reflection;" + Environment.NewLine +
                        "using System.Collections.Generic;" + Environment.NewLine +
                        "using System.Web;" + Environment.NewLine +
                        "using System.Threading.Tasks;" + Environment.NewLine +
                        "using Newtonsoft.Json;" + Environment.NewLine +
                        "using GafBot;" + Environment.NewLine +
                        "using GafBot.MessageSystem;" + Environment.NewLine +
                        "using GafBot.Osu;" + Environment.NewLine +
                        "using GafBot.Osu.Api;" + Environment.NewLine +

                        "public class UserClass" + Environment.NewLine +
                        "{" + Environment.NewLine +
                        "public object UserMethod( string StringParameter )" + Environment.NewLine +
                        "{" + Environment.NewLine +
                        "object Result = null;" + Environment.NewLine +
                        "var dclient = Coding.Methods.GetClient();" + Environment.NewLine +
                        Environment.NewLine +
                        Environment.NewLine +

                        CSharpCode +

                        Environment.NewLine +
                        Environment.NewLine +
                        "return Result;" + Environment.NewLine +
                        "}" + Environment.NewLine +
                        "}";
                    #endregion

                    #region Compile the Dll to Memory

                    #region Make Reference List
                    Assembly[] FullAssemblyList = AppDomain.CurrentDomain.GetAssemblies();

                    System.Collections.Specialized.StringCollection ReferencedAssemblies_sc = new System.Collections.Specialized.StringCollection();

                    foreach (Assembly ThisAssebly in FullAssemblyList)
                    {
                        try
                        {
                            if (ThisAssebly is System.Reflection.Emit.AssemblyBuilder)
                            {
                                // Skip dynamic assemblies
                                continue;
                            }

                            ReferencedAssemblies_sc.Add(ThisAssebly.Location);
                        }
                        catch (NotSupportedException)
                        {
                            // Skip other dynamic assemblies
                            continue;
                        }
                    }

                    string[] ReferencedAssemblies = new string[ReferencedAssemblies_sc.Count];
                    ReferencedAssemblies_sc.CopyTo(ReferencedAssemblies, 0);
                    #endregion

                    Microsoft.CSharp.CSharpCodeProvider codeProvider = new Microsoft.CSharp.CSharpCodeProvider();
#pragma warning disable CS0618 // Type or member is obsolete
                    System.CodeDom.Compiler.ICodeCompiler CSharpCompiler = codeProvider.CreateCompiler();
#pragma warning restore CS0618 // Type or member is obsolete
                    System.CodeDom.Compiler.CompilerParameters parameters = new System.CodeDom.Compiler.CompilerParameters(ReferencedAssemblies)
                    {
                        GenerateExecutable      = false,
                        GenerateInMemory        = true,
                        IncludeDebugInformation = false,
                        OutputAssembly          = "ScreenFunction"
                    };
                    System.CodeDom.Compiler.CompilerResults CompileResult = CSharpCompiler.CompileAssemblyFromSource(parameters, Code);
                    #endregion

                    if (CompileResult.Errors.HasErrors == false)
                    { // Successful Compile
                        #region Run "UserMethod" from "UserClass"
                        System.Type UserClass = CompileResult.CompiledAssembly.GetType("UserClass");
                        object      Instance  = Activator.CreateInstance(UserClass, false);
                        return(new KeyValuePair <bool, object>(true, UserClass.GetMethod("UserMethod").Invoke(Instance, new object[] { StringParameter })));

                        #endregion
                    }
                    else // Failed Compile
                    {
                        if (ShowErrors)
                        {
                            #region Show Errors
                            StringBuilder ErrorText = new StringBuilder();

                            foreach (System.CodeDom.Compiler.CompilerError Error in CompileResult.Errors)
                            {
                                ErrorText.Append("Line " + (Error.Line - 1) +
                                                 " (" + Error.ErrorText + ")" +
                                                 Environment.NewLine);
                            }

                            Logger.Log("Compiler: " + ErrorText.ToString(), LogLevel.Trace);
                            #endregion
                        }
                    }
                }
                catch (Exception E)
                {
                    if (ShowErrors)
                    {
                        return(new KeyValuePair <bool, object>(false, E));
                    }
                }

                return(new KeyValuePair <bool, object>(false, null));
            }
 /// <summary>
 ///
 /// </summary>
 /// <param name="aDataObject"></param>
 /// <param name="aProps"></param>
 public CantUpdateNotLoadedPropertiesException(ICSSoft.STORMNET.DataObject aDataObject, System.Collections.Specialized.StringCollection aProps)
 {
     dobject = aDataObject;
     props   = new string[aProps.Count];
     aProps.CopyTo(props, 0);
 }
        // Splits a string containing new lines (assumed to be \n or \r\n) and passes each
        // line to FormatSingleLineMaxChars and returns the resulting string array
        public static string[] FormatMultiLineMaxChars( int maxLen, string sLine )
        {
            System.Diagnostics.Debug.Assert( maxLen > 0, "Max must be at least 1" );
              if(  maxLen <= 0 ) return null;

              string[] lines = sLine.Replace( "\r", "" ).Split( new char[]{'\n'} );
              System.Collections.Specialized.StringCollection formattedLines = new System.Collections.Specialized.StringCollection();

              foreach( string line in lines )
            formattedLines.AddRange( FormatSingleLineMaxChars( maxLen, line ) );

              string[] multi = new string[ formattedLines.Count ];
              formattedLines.CopyTo( multi, 0 );
              return multi;
        }
Beispiel #24
0
 private void addFiles(System.Collections.Specialized.StringCollection collection)
 {
     string[] files = new string[collection.Count];
     collection.CopyTo(files, 0);
     addFiles(files);
 }
 public void Populate(System.Collections.Specialized.StringCollection filenames)
 {
     string[] strings = new string[filenames.Count];
     filenames.CopyTo(strings, 0);
     Populate(strings);
 }
Beispiel #26
0
        /// <summary>
        ///   Creates a relative path from one file or folder to another.
        /// </summary>
        /// <param name = "fromDirectory">
        ///   Contains the directory that defines the 
        ///   start of the relative path.
        /// </param>
        /// <param name = "toPath">
        ///   Contains the path that defines the
        ///   endpoint of the relative path.
        /// </param>
        /// <returns>
        ///   The relative path from the start
        ///   directory to the end path.
        /// </returns>
        /// <exception cref = "ArgumentNullException"></exception>
        public static string RelativePathTo(string fromDirectory, string toPath)
        {
            if (fromDirectory == null)
            throw new ArgumentNullException("fromDirectory");

              if (toPath == null)
            throw new ArgumentNullException("toPath");

              bool isRooted = Path.IsPathRooted(fromDirectory) && Path.IsPathRooted(toPath);

              if (isRooted)
              {
            bool isDifferentRoot = String.Compare(Path.GetPathRoot(fromDirectory), Path.GetPathRoot(toPath), true) != 0;

            if (isDifferentRoot)
              return toPath;
              }

              StringCollection relativePath = new StringCollection();
              string[] fromDirectories = fromDirectory.Split(Path.DirectorySeparatorChar);

              string[] toDirectories = toPath.Split(Path.DirectorySeparatorChar);

              int length = Math.Min(fromDirectories.Length, toDirectories.Length);

              int lastCommonRoot = -1;

              // find common root
              for (int x = 0; x < length; x++)
              {
            if (String.Compare(fromDirectories[x], toDirectories[x], true) != 0)
              break;

            lastCommonRoot = x;
              }

              if (lastCommonRoot == -1)
            return toPath;

              // add relative folders in from path
              for (int x = lastCommonRoot + 1; x < fromDirectories.Length; x++)
            if (fromDirectories[x].Length > 0)
              relativePath.Add("..");

              // add to folders to path
              for (int x = lastCommonRoot + 1; x < toDirectories.Length; x++)
            relativePath.Add(toDirectories[x]);

              // create relative path
              string[] relativeParts = new string[relativePath.Count];
              relativePath.CopyTo(relativeParts, 0);

              string newPath = String.Join(Path.DirectorySeparatorChar.ToString(), relativeParts);

              return newPath;
        }
Beispiel #27
0
        private void DeleteFiles()
        {
            System.Collections.Specialized.StringCollection files = new System.Collections.Specialized.StringCollection();
            IEnumerable<IBrowserItem> itemset = Browser.CurSelItems;

            foreach (IBrowserItem item in itemset)
            {
                files.Add(item.FullPath);
            }

            ShellLib.ShellFileOperation fo = new ShellLib.ShellFileOperation();

            string[] filearray = new string[files.Count];
            files.CopyTo(filearray, 0);
            fo.Operation = ShellLib.ShellFileOperation.FileOperations.FO_DELETE;
            fo.OwnerWindow = Program.form.Handle;
            fo.SourceFiles = filearray;

            fo.OperationFlags = ShellLib.ShellFileOperation.ShellFileOperationFlags.FOF_NO_CONNECTED_ELEMENTS
                | ShellLib.ShellFileOperation.ShellFileOperationFlags.FOF_WANTNUKEWARNING;

            bool retVal = fo.DoOperation();

            Browser.Refresh();

            if (retVal == false)
            {
                throw new Exception("Shell File Operation Failed");
            }
        }
        // Formats a string so that no line will have more than maxLen characters.
        // Input strings may not contain a \r or \n. To format multi-line strings call
        // FormatMultiLineMaxChars
        public static string[] FormatSingleLineMaxChars( int maxLen, string sLine )
        {
            System.Diagnostics.Debug.Assert( maxLen > 0, "Max must be at least 1" );
              System.Diagnostics.Debug.Assert( -1 == sLine.IndexOf( '\r' ) );
              System.Diagnostics.Debug.Assert( -1 == sLine.IndexOf( '\n' ) );

              if(  maxLen <= 0 ) return null;
              if( 0 == sLine.Length ) return new String[]{""};

              int currentStart = 0;
              int currentEnd;
              System.Collections.Specialized.StringCollection txt = new System.Collections.Specialized.StringCollection();

              while(  currentStart < sLine.Length  ) {
            if(  currentStart + maxLen < sLine.Length  ) {
              currentEnd = Math.Min(  currentStart + maxLen,  sLine.Length - 1  );

              int spaceIdx = sLine.LastIndexOf(  " ",  currentEnd,  currentEnd - currentStart  );

              if(  -1 == spaceIdx  ) {
            txt.Add(  sLine.Substring( currentStart, currentEnd - currentStart )  );
            currentStart += maxLen;
              }
              else {
            txt.Add(  sLine.Substring( currentStart, spaceIdx - currentStart )  );
            currentStart = spaceIdx + 1;
              }
            }
            else {
              txt.Add(  sLine.Substring( currentStart )  );
              currentStart += maxLen;
            }
              }

              string[] lines = new string[ txt.Count ];
              txt.CopyTo( lines, 0 );
              return lines;
        }