GetFileName() private méthode

private GetFileName ( string path ) : string
path string
Résultat string
Exemple #1
0
		public InMemoryFile(string filePath)
		{
			Path = new Path(filePath);
			Name = Path.GetFileName(filePath);
			NameWithoutExtension = Path.GetFileNameWithoutExtension(filePath);

			_LastModifiedTimeUtc = null;
		}
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is string path)
        {
            return(Path.GetFileName(path));
        }

        return(value);
    }
Exemple #3
0
 public FolderVM(ExplorerTreeNodeVM parent, string path)
     : this(parent, path, IOPath.GetFileName(path))
 {
 }
Exemple #4
0
        public void SetUp()
        {
            testDirectory         = TestContext.CurrentContext.TestDirectory;
            tempDirectory         = IOPath.Combine(testDirectory, "temp", TestContext.CurrentContext.Test.Name);
            intermediateDirectory = IOPath.Combine(tempDirectory, "obj", "Debug", TargetFramework);
            Directory.CreateDirectory(tempDirectory);

            //copy _Directory.Build.[props|targets] in test/
            var props   = IOPath.Combine(testDirectory, "..", "..", "..", "MSBuild", "_Directory.Build.props");
            var targets = IOPath.Combine(testDirectory, "..", "..", "..", "MSBuild", "_Directory.Build.targets");

            if (!File.Exists(props))
            {
                //NOTE: VSTS may be running tests in a staging directory, so we can use an environment variable to find the source
                //https://docs.microsoft.com/en-us/vsts/build-release/concepts/definitions/build/variables?view=vsts&tabs=batch#buildsourcesdirectory
                var sourcesDirectory = Environment.GetEnvironmentVariable("BUILD_SOURCESDIRECTORY");
                if (!string.IsNullOrEmpty(sourcesDirectory))
                {
                    props   = IOPath.Combine(sourcesDirectory, "Microsoft.Maui.Controls.Xaml.UnitTests", "MSBuild", "_Directory.Build.props");
                    targets = IOPath.Combine(sourcesDirectory, "Microsoft.Maui.Controls.Xaml.UnitTests", "MSBuild", "_Directory.Build.targets");

                    if (!File.Exists(props))
                    {
                        Assert.Fail("Unable to find _Directory.Build.props at path: " + props);
                    }
                }
                else
                {
                    Assert.Fail("Unable to find _Directory.Build.props at path: " + props);
                }

                Directory.CreateDirectory(IOPath.Combine(testDirectory, "..", "..", "..", "..", ".nuspec"));
                foreach (var file in Directory.GetFiles(IOPath.Combine(sourcesDirectory, ".nuspec"), "*.targets"))
                {
                    File.Copy(file, IOPath.Combine(testDirectory, "..", "..", "..", "..", ".nuspec", IOPath.GetFileName(file)), true);
                }
                foreach (var file in Directory.GetFiles(IOPath.Combine(sourcesDirectory, ".nuspec"), "*.props"))
                {
                    File.Copy(file, IOPath.Combine(testDirectory, "..", "..", "..", "..", ".nuspec", IOPath.GetFileName(file)), true);
                }
                File.Copy(IOPath.Combine(sourcesDirectory, "Directory.Build.props"), IOPath.Combine(testDirectory, "..", "..", "..", "..", "Directory.Build.props"), true);
            }

            File.Copy(props, IOPath.Combine(tempDirectory, "Directory.Build.props"), true);
            File.Copy(targets, IOPath.Combine(tempDirectory, "Directory.Build.targets"), true);
        }
Exemple #5
0
        private void mnuNewCritter_Click(object sender, EventArgs e)
        {
            Character objCharacter = new Character();
            string    settingsPath = Path.Combine(Application.StartupPath, "settings");

            string[] settingsFiles = Directory.GetFiles(settingsPath, "*.xml");

            if (settingsFiles.Length > 1)
            {
                Cursor = Cursors.WaitCursor;
                frmSelectSetting frmPickSetting = new frmSelectSetting();
                frmPickSetting.ShowDialog(this);
                Cursor = Cursors.Default;

                if (frmPickSetting.DialogResult == DialogResult.Cancel)
                {
                    return;
                }

                objCharacter.SettingsFile = frmPickSetting.SettingsFile;
            }
            else
            {
                string strSettingsFile = settingsFiles[0];
                objCharacter.SettingsFile = Path.GetFileName(strSettingsFile);
            }

            Cursor = Cursors.WaitCursor;

            // Override the defaults for the setting.
            objCharacter.IgnoreRules = true;
            objCharacter.IsCritter   = true;
            objCharacter.Created     = true;
            objCharacter.BuildMethod = CharacterBuildMethod.Karma;
            objCharacter.BuildPoints = 0;

            // Show the Metatype selection window.
            frmKarmaMetatype frmSelectMetatype = new frmKarmaMetatype(objCharacter, "critters.xml");

            frmSelectMetatype.ShowDialog();
            Cursor = Cursors.Default;

            if (frmSelectMetatype.DialogResult == DialogResult.Cancel)
            {
                return;
            }
            Cursor = Cursors.WaitCursor;

            // Add the Unarmed Attack Weapon to the character.
            XmlDocument objXmlDocument = XmlManager.Load("weapons.xml");
            XmlNode     objXmlWeapon   = objXmlDocument.SelectSingleNode("/chummer/weapons/weapon[name = \"Unarmed Attack\"]");

            if (objXmlWeapon != null)
            {
                List <Weapon> lstWeapons = new List <Weapon>();
                Weapon        objWeapon  = new Weapon(objCharacter);
                objWeapon.Create(objXmlWeapon, lstWeapons);
                objWeapon.ParentID = Guid.NewGuid().ToString("D"); // Unarmed Attack can never be removed
                objCharacter.Weapons.Add(objWeapon);
                foreach (Weapon objLoopWeapon in lstWeapons)
                {
                    objCharacter.Weapons.Add(objLoopWeapon);
                }
            }

            frmCareer frmNewCharacter = new frmCareer(objCharacter)
            {
                MdiParent   = this,
                WindowState = FormWindowState.Maximized
            };

            frmNewCharacter.Show();

            objCharacter.CharacterNameChanged += objCharacter_CharacterNameChanged;
            Cursor = Cursors.Default;
        }
Exemple #6
0
 private IReadOnlyList <string> GetGraphQLConfigFiles(
     GeneratorExecutionContext context) =>
 context.AdditionalFiles
 .Select(t => t.Path)
 .Where(t => IOPath.GetFileName(t).EqualsOrdinal(".graphqlrc.json"))
 .ToList();
Exemple #7
0
        /// <summary>Loads all non-runtime plugins.</summary>
        /// <returns>Whether loading all plugins was successful.</returns>
        internal static bool LoadPlugins()
        {
            UnloadPlugins();
            string folder = Program.FileSystem.GetDataFolder("Plugins");

            string[] files = {};
            try
            {
                files = Directory.GetFiles(folder);
            }
            catch
            {
                // ignored
            }

            List <ContentLoadingPlugin> list = new List <ContentLoadingPlugin>();
            StringBuilder builder            = new StringBuilder();

            foreach (string file in files)
            {
                if (file.EndsWith(".dll", StringComparison.OrdinalIgnoreCase))
                {
                                        #if !DEBUG
                    try {
                                                #endif
                    ContentLoadingPlugin plugin = new ContentLoadingPlugin(file);
                    Assembly assembly;
                    Type[] types;
                    try
                    {
                        assembly = Assembly.LoadFile(file);
                        types    = assembly.GetTypes();
                    }
#pragma warning disable 168
                    catch (Exception ex)
#pragma warning restore 168
                    {
#if !DEBUG
                        if ((ex is ReflectionTypeLoadException))
                        {
                            /*
                             * This is actually a .Net assembly, it just failed to load a reference
                             * Probably built against a newer API version.
                             */

                            builder.Append("Plugin ").Append(Path.GetFileName(file)).AppendLine(" failed to load. \n \n Please check that you are using the most recent version of OpenBVE.");
                        }
                        else
                        {
                            builder.Append("Plugin ").Append(Path.GetFileName(file)).AppendLine(" is not a .Net assembly.");
                        }
#endif
                        continue;
                    }
                    bool iruntime = false;
                    foreach (Type type in types)
                    {
                        if (type.FullName == null)
                        {
                            continue;
                        }
                        if (type.IsSubclassOf(typeof(OpenBveApi.Textures.TextureInterface)))
                        {
                            plugin.Texture = (OpenBveApi.Textures.TextureInterface)assembly.CreateInstance(type.FullName);
                        }
                        if (type.IsSubclassOf(typeof(OpenBveApi.Sounds.SoundInterface)))
                        {
                            plugin.Sound = (OpenBveApi.Sounds.SoundInterface)assembly.CreateInstance(type.FullName);
                        }
                        if (type.IsSubclassOf(typeof(OpenBveApi.Objects.ObjectInterface)))
                        {
                            plugin.Object = (OpenBveApi.Objects.ObjectInterface)assembly.CreateInstance(type.FullName);
                        }
                        if (type.IsSubclassOf(typeof(OpenBveApi.Routes.RouteInterface)))
                        {
                            plugin.Route = (OpenBveApi.Routes.RouteInterface)assembly.CreateInstance(type.FullName);
                        }
                        if (typeof(OpenBveApi.Runtime.IRuntime).IsAssignableFrom(type))
                        {
                            iruntime = true;
                        }
                    }
                    if (plugin.Texture != null | plugin.Sound != null | plugin.Object != null | plugin.Route != null)
                    {
                        plugin.Load(Program.CurrentHost, Program.FileSystem, Interface.CurrentOptions, Program.Renderer);
                        list.Add(plugin);
                    }
                    else if (!iruntime)
                    {
                        builder.Append("Plugin ").Append(Path.GetFileName(file)).AppendLine(" does not implement compatible interfaces.");
                        builder.AppendLine();
                    }
                                                #if !DEBUG
                }
                catch (Exception ex) {
                    builder.Append("Could not load plugin ").Append(Path.GetFileName(file)).AppendLine(":").AppendLine(ex.Message);
                    builder.AppendLine();
                }
                                        #endif
                }
            }
            Program.CurrentHost.Plugins = list.ToArray();
            if (Program.CurrentHost.Plugins.Length == 0)
            {
                MessageBox.Show("No available content loading plugins were found." + Environment.NewLine +
                                " Please re-download openBVE.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Hand);
                return(false);
            }
            string message = builder.ToString().Trim(new char[] { });
            if (message.Length != 0)
            {
                return(MessageBox.Show(message, Application.ProductName, MessageBoxButtons.OKCancel, MessageBoxIcon.Hand, MessageBoxDefaultButton.Button2) == DialogResult.OK);
            }
            else
            {
                return(true);
            }
        }
Exemple #8
0
        /// <summary>
        /// permet de séparer les pages du document source
        /// vers le répertoire temporaire
        /// <param name="file">fichier source</param>
        /// <param name="copy">true:copie false:déplace</param>
        /// </summary>
        public static void SplitPdf(string file, bool copy)
        {
            try
            {
                var srcDoc = file;

                //ouverture du fichier
                PdfSharpDocument inputDocument = PdfSharpReader.Open(srcDoc, PdfDocumentOpenMode.Import);

                string name = Path.GetFileNameWithoutExtension(file);
                if (inputDocument.PageCount > 1)
                {
                    for (int idx = 0; idx < inputDocument.PageCount; idx++)
                    {
                        //nouveau document
                        PdfSharpDocument outputDocument = new PdfSharpDocument();
                        outputDocument.Version      = inputDocument.Version;
                        outputDocument.Info.Title   = $"Page {idx + 1} of {inputDocument.Info.Title}";
                        outputDocument.Info.Creator = inputDocument.Info.Creator;

                        //ajout de la page et sauvegarde
                        outputDocument.AddPage(inputDocument.Pages[idx]);
                        var temp = Path.Combine(ServiceCfg.TempFolder, Path.GetFileNameWithoutExtension(file));
                        CheckFolder(temp, true);
                        outputDocument.Save(Path.Combine(temp, $"{name}__p{idx + 1}.pdf"));
                        outputDocument.Close();
                    }
                }
                else
                {
                    //nouveau document
                    PdfSharpDocument outputDocument = new PdfSharpDocument();
                    outputDocument.Version      = inputDocument.Version;
                    outputDocument.Info.Title   = inputDocument.Info.Title;
                    outputDocument.Info.Creator = inputDocument.Info.Creator;

                    //ajout de la page et sauvegarde
                    outputDocument.AddPage(inputDocument.Pages[0]);
                    var temp = Path.Combine(ServiceCfg.TempFolder, Path.GetFileNameWithoutExtension(file));
                    CheckFolder(temp, true);
                    outputDocument.Save(Path.Combine(temp, $"{name}.pdf"));
                    outputDocument.Close();
                }

                if (CheckFolder(ServiceCfg.OutputFolderPath, false))
                {
                    var pathbckup = Path.Combine(ServiceCfg.OutputFolderPath, "original\\");
                    var filebck   = Path.Combine(pathbckup, Path.GetFileName(file));
                    if (CheckFolder(pathbckup, true))
                    {
                        if (File.Exists(filebck))
                        {
                            filebck = Path.Combine(pathbckup, $"{Path.GetFileNameWithoutExtension(file)}_[ALT-{DateTime.Now.ToString("yyyyMMddHHmmss")}]{Path.GetExtension(file)}");
                        }
                        if (copy)
                        {
                            File.Copy(srcDoc, filebck);
                        }
                        else
                        {
                            File.Move(srcDoc, filebck);
                        }
                        //on garde le chemin du fichier d'origine
                        DataManager.SetDicoValue(LogTableParam.Source, filebck);
                    }
                }
            }
            catch (Exception e)
            {
                ServiceCfg.Log.Error($"PdfManager.SplitPdf : {file}{Environment.NewLine}", e);
                throw new Exception($"PdfManager.SplitPdf : {file}{Environment.NewLine}", e);
            }
        }
        private static bool IsValidPath(string path)
        {
            var fileName = Path.GetFileName(path);

            return(fileName != null && fileName.StartsWith(PHmiConstants.PHmiIoDevicePrefix));
        }
Exemple #10
0
        private void CopyFile(string filePath, string directoryPath)
        {
            var fileName = Path.GetFileName(filePath);

            File.Copy(filePath, Path.Combine(directoryPath, fileName), true);
        }
Exemple #11
0
        public void ClearLocalRepo()
        {
            var folder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "ForguncyCollaboration", Path.GetFileName(TempFolder));

            Directory.Delete(folder, true);
        }
Exemple #12
0
        private async void Button_Create_Click(object sender, RoutedEventArgs e)
        {
            tmpInfo.Title   = textboxTitle.Text;
            tmpInfo.Author  = textboxAuthor.Text;
            tmpInfo.Desc    = textboxDesc.Text;
            tmpInfo.Contact = textboxWebsite.Text;
            tmpInfo.License = textboxLicense.Text;
            //tmpInfo.Type = (SetupDesktop.WallpaperType)comboBoxType.SelectedItem;
            tmpInfo.Type      = wallpaperTypes[comboBoxType.SelectedIndex].Type;
            tmpInfo.Arguments = textboxArgs.Text;

            if (folderContents.Count == 0 || String.IsNullOrWhiteSpace(tmpInfo.FileName))
            {
                MessageBox.Show(Properties.Resources.txtMsgSelectWallpaperFile);
                return;
            }

            if (String.IsNullOrEmpty(tmpInfo.Title) || String.IsNullOrEmpty(tmpInfo.Desc) || String.IsNullOrEmpty(tmpInfo.Author)
                )    //|| String.IsNullOrEmpty(tmpInfo.contact) )
            {
                MessageBox.Show(Properties.Resources.txtMsgFillAllFields);
                return;
            }

            /*
             * //Optional
             * if( !File.Exists(tmpInfo.Thumbnail) || !File.Exists(tmpInfo.Preview) )
             * {
             *  MessageBox.Show(Properties.Resources.txtSelectPreviewThumb);
             *  return;
             * }
             */

            SaveFileDialog saveFileDialog1 = new SaveFileDialog
            {
                Title           = "Select location to save the file",
                Filter          = "Lively/zip file|*.zip",
                OverwritePrompt = true
            };

            if (saveFileDialog1.ShowDialog() == true)
            {
                if (!String.IsNullOrEmpty(saveFileDialog1.FileName))
                {
                    //to write to Livelyinfo.json file only, tmp object.
                    SaveData.LivelyInfo tmp = new SaveData.LivelyInfo(tmpInfo);
                    tmp.FileName  = Path.GetFileName(tmp.FileName);
                    tmp.Preview   = Path.GetFileName(tmp.Preview);
                    tmp.Thumbnail = Path.GetFileName(tmp.Thumbnail);

                    SaveData.SaveWallpaperMetaData(tmp, Path.Combine(App.pathData, "tmpdata"));

                    /*
                     * //if previous livelyinfo.json file(s) exists in wallpaper directory, remove all of them.
                     * folderContents.RemoveAll(x => Path.GetFileName(x).Equals(Path.GetFileName(folderContents[folderContents.Count - 1]),
                     *                  StringComparison.InvariantCultureIgnoreCase));
                     */
                    folderContents.Add(Path.Combine(App.pathData, "tmpdata", "LivelyInfo.json"));

                    //btnCreateWallpaer.IsEnabled = false;
                    await CreateZipFile(saveFileDialog1.FileName, folderContents);

                    string folderPath = System.IO.Path.GetDirectoryName(saveFileDialog1.FileName);
                    if (Directory.Exists(folderPath))
                    {
                        ProcessStartInfo startInfo = new ProcessStartInfo
                        {
                            Arguments = folderPath,
                            FileName  = "explorer.exe"
                        };
                        Process.Start(startInfo);
                    }

                    //clearing temp files if any.
                    FileOperations.EmptyDirectory(Path.Combine(App.pathData, "SaveData", "wptmp"));
                    //this.NavigationService.GoBack(); //won't work, since prev is window, not page.
                    var wnd = Window.GetWindow(this);
                    wnd.Close();
                }
            }
            else
            {
                return;
            }
        }
Exemple #13
0
        private void StartRenderButton_Click(object sender, RoutedEventArgs e)
        {
            if (videoPath.Text == "")
            {
                MessageBox.Show("Please specify a destination path");
                return;
            }

            if (renderer.renderer == null)
            {
                MessageBox.Show("No renderer is selected");
                return;
            }

            if (File.Exists(videoPath.Text))
            {
                if (MessageBox.Show("Are you sure you want to override " + Path.GetFileName(videoPath.Text), "Override", MessageBoxButton.YesNo) == MessageBoxResult.No)
                {
                    return;
                }
            }
            if (File.Exists(alphaPath.Text))
            {
                if (MessageBox.Show("Are you sure you want to override " + Path.GetFileName(alphaPath.Text), "Override", MessageBoxButton.YesNo) == MessageBoxResult.No)
                {
                    return;
                }
            }

            settings.realtimePlayback = false;
            settings.playbackEnabled  = false;
            settings.playSound        = true;

            settings.running            = true;
            settings.width              = (int)viewWidth.Value * (int)SSAAFactor.Value;
            settings.height             = (int)viewHeight.Value * (int)SSAAFactor.Value;
            settings.downscale          = (int)SSAAFactor.Value;
            settings.fps                = (int)viewFps.Value;
            settings.ffRender           = true;
            settings.ffPath             = videoPath.Text;
            settings.renderSecondsDelay = (double)secondsDelay.Value;

            settings.Paused          = false;
            previewPaused.IsChecked  = false;
            settings.tempoMultiplier = 1;
            tempoSlider.Value        = 0;

            settings.ffmpegDebug = (bool)ffdebug.IsChecked;

            settings.useBitrate = (bool)bitrateOption.IsChecked;
            if (settings.useBitrate)
            {
                settings.bitrate = (int)bitrate.Value;
            }
            else
            {
                settings.crf       = (int)crfFactor.Value;
                settings.crfPreset = (string)((ComboBoxItem)crfPreset.SelectedItem).Content;
            }

            settings.includeAudio      = (bool)includeAudio.IsChecked;
            settings.audioPath         = audioPath.Text;
            settings.ffRenderMask      = (bool)includeAlpha.IsChecked;
            settings.ffMaskPath        = alphaPath.Text;
            renderThread               = Task.Factory.StartNew(RunRenderWindow);
            Resources["notPreviewing"] = false;
            Resources["notRendering"]  = false;
        }
Exemple #14
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            // Open file system to select file(s)
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
            dlg.Multiselect = true;


            Nullable <bool> result = dlg.ShowDialog();  // Display OpenFileDialog by calling ShowDialog method

            byte[] rawData;
            List <Tuple <string, byte[]> > dataList = new List <Tuple <string, byte[]> >();
            string ext      = "";
            string filename = "";

            // Add all files selected into the the db. If multiple files added, project destination is the same.
            foreach (String file in dlg.FileNames)
            {
                // Get the selected file name and display in a TextBox
                if (result.HasValue == true && result.Value == true)
                {
                    rawData = File.ReadAllBytes(file);
                    dataList.Add(Tuple.Create(file, rawData));
                    ext      = Path.GetExtension(file);
                    filename = file;
                }
            }

            AnalysisMsgPrompt a = new AnalysisMsgPrompt(new DataGridLoader(), null);



            if (a.ShowDialog() == true)
            {
                dgl.loadSpeakers(a.PID);
                rowS = dgl.getCollection("S");
                foreach (var elem in rowS.ToList())
                {
                    ((dynamic)rowS).Add((Speaker)elem);
                }


                foreach (var dataItem in dataList)
                {
                    var comm = new MySqlCommand();
                    filename = Path.GetFileName(dataItem.Item1);

                    using (DBConnection db = new DBConnection())
                    {
                        comm.CommandText = "INSERT INTO Analysis (AID, Description, FileData, FileType) VALUES(@AID, @Desc, @FileAsBlob, @FileType)";
                        comm.Parameters.AddWithValue("@AID", filename);
                        if (a.Desc.Equals(""))
                        {
                            comm.Parameters.AddWithValue("@Desc", "No description");
                        }
                        else
                        {
                            //Add to analysis table
                            comm.CommandText = "create table if not exists analysis (AID varchar(150) primary key, File mediumblob, Description varchar(500))";
                            comm.ExecuteNonQuery();

                            comm.CommandText = "INSERT INTO analysis (AID, File, Description) VALUES(@AID, @FileAsBlob, @Desc)";
                            comm.Parameters.AddWithValue("@AID", dataItem.Item1);
                            comm.Parameters.AddWithValue("@FileAsBlob", dataItem.Item2);
                            if (a.Desc.Equals(""))
                            {
                                comm.Parameters.AddWithValue("@Desc", "No description");
                            }
                            else
                            {
                                comm.Parameters.AddWithValue("@Desc", a.Desc);
                            }
                            comm.ExecuteNonQuery();

                            //Add to the mapping table(to link with speaker)
                            List <Row> startsWithAge = rowS.Where(s => ((Speaker)s).SpeakerName.StartsWith(a.Age)).ToList();

                            MessageBox.Show(a.Age);
                            foreach (var row in rowS)
                            {
                                //comm.CommandText = "create table if not exists files2analysis (AID varchar(150) primary key, ID varchar(150) primary key)";
                                //comm.ExecuteNonQuery();
                                if (((Speaker)row).SpeakerName.StartsWith(a.Age))
                                {
                                    db.insertIntoDB(comm);
                                }


                                comm.CommandText = "INSERT IGNORE INTO files2analysis (ID, AID) VALUES (@ID2, @AID2)";
                                comm.Parameters.Clear();
                                comm.Parameters.AddWithValue("@ID2", ((Speaker)row).ID);
                                comm.Parameters.AddWithValue("@AID2", dataItem.Item1);
                                comm.ExecuteNonQuery();
                            }


                            HashSet <Tuple <String, String> > uniqueAnalysis = new HashSet <Tuple <String, String> >();
                            HashSet <Tuple <String, String> > uniqueRowName  = new HashSet <Tuple <String, String> >();
                            string previous = "";
                            foreach (var row in rowS)
                            {
                                if (!((Speaker)row).Name.Equals(previous))
                                {
                                    previous = ((Speaker)row).Name;
                                    uniqueAnalysis.Add(Tuple.Create(((Speaker)row).Name, ((Speaker)row).ID));
                                }
                            }
                            foreach (var uRow in uniqueAnalysis)
                            {
                                if ((uRow.Item1.StartsWith(a.Age)))
                                {
                                    comm.CommandText = "INSERT IGNORE INTO File2Analysis (File_FID, Analysis_AID) VALUES (@FileID, @AID)";
                                    comm.Parameters.Clear();
                                    comm.Parameters.AddWithValue("@FileID", uRow.Item2);
                                    comm.Parameters.AddWithValue("@AID", filename);
                                    db.insertIntoDB(comm);
                                }
                            }
                        }
                    }
                }
            }
        }
Exemple #15
0
        internal static Task <Tuple <string, bool> > GetFileForUriAsync(Context context, Uri uri, bool isPhoto, bool saveToAlbum)
        {
            var tcs = new TaskCompletionSource <Tuple <string, bool> >();

            if (uri.Scheme == "file")
            {
                tcs.SetResult(new Tuple <string, bool>(new System.Uri(uri.ToString()).LocalPath, false));
            }
            else if (uri.Scheme == "content")
            {
                Task.Factory.StartNew(() =>
                {
                    ICursor cursor = null;
                    try
                    {
                        string[] proj = null;
                        if ((int)Build.VERSION.SdkInt >= 22)
                        {
                            proj = new[] { MediaStore.MediaColumns.Data }
                        }
                        ;

                        cursor = context.ContentResolver.Query(uri, proj, null, null, null);
                        if (cursor == null || !cursor.MoveToNext())
                        {
                            tcs.SetResult(new Tuple <string, bool>(null, false));
                        }
                        else
                        {
                            var column         = cursor.GetColumnIndex(MediaStore.MediaColumns.Data);
                            string contentPath = null;

                            if (column != -1)
                            {
                                contentPath = cursor.GetString(column);
                            }



                            // If they don't follow the "rules", try to copy the file locally
                            if (contentPath == null || !contentPath.StartsWith("file", StringComparison.InvariantCultureIgnoreCase))
                            {
                                string fileName = null;
                                try
                                {
                                    fileName = Path.GetFileName(contentPath);
                                }
                                catch (Exception ex)
                                {
                                    System.Diagnostics.Debug.WriteLine("Unable to get file path name, using new unique " + ex);
                                }


                                var outputPath = GetOutputMediaFile(context, "temp", fileName, isPhoto, false);

                                try
                                {
                                    using (var input = context.ContentResolver.OpenInputStream(uri))
                                        using (var output = File.Create(outputPath.Path))
                                            input.CopyTo(output);

                                    contentPath = outputPath.Path;
                                }
                                catch (Java.IO.FileNotFoundException fnfEx)
                                {
                                    // If there's no data associated with the uri, we don't know
                                    // how to open this. contentPath will be null which will trigger
                                    // MediaFileNotFoundException.
                                    System.Diagnostics.Debug.WriteLine("Unable to save picked file from disk " + fnfEx);
                                }
                            }

                            tcs.SetResult(new Tuple <string, bool>(contentPath, false));
                        }
                    }
                    finally
                    {
                        if (cursor != null)
                        {
                            cursor.Close();
                            cursor.Dispose();
                        }
                    }
                }, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default);
            }
            else
            {
                tcs.SetResult(new Tuple <string, bool>(null, false));
            }

            return(tcs.Task);
        }
Exemple #16
0
        //Browse for project icon
        private void Button_Click_4(object sender, RoutedEventArgs e)
        {
            OpenFileDialog fileDialog = new OpenFileDialog();

            fileDialog.Filter = "Icons (*.ico) | *.ico";
            if (fileDialog.ShowDialog() == true)
            {
                if (!File.Exists(Path.Combine(CurrentSolution.WorkingDirectoryPath, "img", Path.GetFileName(fileDialog.FileName))))
                {
                    File.Copy(fileDialog.FileName, Path.Combine(CurrentSolution.WorkingDirectoryPath, "img", Path.GetFileName(fileDialog.FileName)));
                }
                CurrentSolution.IconFileName = Path.GetFileName(fileDialog.FileName);
                IconNameText.Text            = Path.GetFileName(fileDialog.FileName);
                IconPreviewImage.Source      = new BitmapImage(new Uri(Path.Combine(CurrentSolution.WorkingDirectoryPath, "img", Path.GetFileName(fileDialog.FileName))));
                CurrentSolution.RebuildCSProjFile();
                CurrentSolution.Save();
            }
        }
 private void RemoveSelectedButton_Click(object sender, RoutedEventArgs e)
 {
     for (int i = 0; i < FilesToAddList.SelectedItems.Count; i++)
     {
         if (FilesToAddalways.Contains(FilesToAddList.SelectedItems[i]))
         {
             string filename = FilesToAddList.SelectedItems[i] as string;
             if (string.IsNullOrEmpty(filename))
             {
                 filename = "null";
             }
             MessageBox.Show(string.Format("{0}: {1}", Translations.GetTranslatedString("cantRemoveDefaultFile"), Path.GetFileName(filename)));
         }
         else
         {
             FilesToAddList.Items.Remove(FilesToAddList.SelectedItems[i]);
             i--;
         }
     }
 }
Exemple #18
0
        /// <summary>
        /// recouvre le fichier modèle avec le contenu des fichiers d'entrée
        /// (préalablement séparés en 1 page par fichier)
        /// </summary>
        /// <param name="overlayfile">page ayant les données à superposer</param>
        /// <returns>booléen pour indiquer si l'opération a réussit ou pas</returns>
        public static bool OverlayPdf(string overlayfile)
        {
            var isOk = true;

            try
            {
                //on obtien uniquement le nom du fichier
                string filename = Path.GetFileName(overlayfile);
                //on sauvegarde le chemin du fichier temporaire
                DataManager.SetDicoValue(LogTableParam.Intermediaire, overlayfile);

                isOk = Overlay(overlayfile, filename);
                ////string inputFile = ServiceCfg.PdfModel;
                ////string cardFolder = Path.Combine(ServiceCfg.OutputFolderPath, @"pages\");
                ////if (!PdfManager.CheckFolder(cardFolder,true))
                ////    return false;
                ////string outFile = Path.Combine(cardFolder,"CTP_" + filename);

                //////Creation du reader et du document pour lire le document PDF original
                ////PdfReader reader = new PdfReader(inputFile);
                ////Document inputDoc = new Document(reader.GetPageSizeWithRotation(1));

                ////using (FileStream fs = new FileStream(outFile, FileMode.Create))
                ////{

                ////    //Creation du PDF Writer pour créer le nouveau Document PDF
                ////    PdfWriter outputWriter = PdfWriter.GetInstance(inputDoc, fs);
                ////    inputDoc.Open();
                ////    //Creation du Content Byte pour tamponner le PDF writer
                ////    PdfContentByte cb1 = outputWriter.DirectContent;

                ////    //Obtien le document PDF à utiliser comme superposition
                ////    PdfReader overlayReader = new PdfReader(overlayfile);
                ////    PdfImportedPage overLay = outputWriter.GetImportedPage(overlayReader, 1);

                ////    //Obtention de la rotation de page de superposition
                ////    int overlayRotation = overlayReader.GetPageRotation(1);

                ////    int n = reader.NumberOfPages;

                ////    //liste des numéros de pages à marquer dans le modèle
                ////    List<int> pagesList = GetModelPages2Overlay(n);

                ////    int i = 1;
                ////    while (i <= n)
                ////    {
                ////        //S'assurer que la taille de la nouvelle page correspond à celle du document d'origine
                ////        inputDoc.SetPageSize(reader.GetPageSizeWithRotation(i));
                ////        inputDoc.NewPage();

                ////        PdfImportedPage page = outputWriter.GetImportedPage(reader, i);

                ////        int rotation = reader.GetPageRotation(i);

                ////        //Ajout de la page PDF originale avec la bonne rotation
                ////        if (rotation == 90 || rotation == 270)
                ////        {
                ////            cb1.AddTemplate(page, 0, -1f, 1f, 0, 0,
                ////                reader.GetPageSizeWithRotation(i).Height);
                ////        }
                ////        else
                ////        {
                ////            //cb1.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
                ////            cb1.AddTemplate(page, 0, 0, true);
                ////        }

                ////        //si la page en cours est à marquer
                ////        if (pagesList.Contains(i))
                ////        {
                ////            //Ajout de la superposition avec la bonne rotation
                ////            if (overlayRotation == 90 || overlayRotation == 270)
                ////            {
                ////                cb1.AddTemplate(overLay, 0, -1f, 1f, 0, 0,
                ////                    reader.GetPageSizeWithRotation(i).Height);
                ////            }
                ////            else
                ////            {
                ////                //cb1.AddTemplate(overLay, 1f, 0, 0, 1f, 0, 0);
                ////                cb1.AddTemplate(overLay, float.Parse(ServiceCfg.OverlayX.ToString()), float.Parse(ServiceCfg.OverlayY.ToString()), true);
                ////            }

                ////        }
                ////        //Increment de page
                ////        i++;
                ////    }
                ////    //Fermeture du fichier d'entrée
                ////    inputDoc.Close();
                ////    //on garde le fichier de sortie
                ////    _lastPdf = outFile;
                ////    //Fermeture du reader pour le fichier de superposition
                ////    overlayReader.Close();
                ////}

                ////reader.Close();
                //tout est traité dans cette phase on garde le fichier obtenu
                DataManager.SetDicoValue(LogTableParam.Intermediaire, _lastPdf);
            }
            catch (Exception e)
            {
                _lastPdf = string.Empty;
                ServiceCfg.Log.Error("PdfManager.OverlayPdf : ", e);
                DataManager.SetLogTable(-1, "PdfManager.OverlayPdf : " + e.Message);
                isOk = false;
            }
            return(isOk);
        }
Exemple #19
0
        /// <summary>
        /// Handles saving of a set of files to disk.
        /// </summary>
        /// <param name="page">The <see cref="GamePage"/> in which the event originated.</param>
        /// <param name="fileReferences">The file references to save.</param>
        private async void OnSaveRequested(GamePage page, IEnumerable <FileReference> fileReferences)
        {
            uint statusMessageContextID = this.MainStatusBar.GetContextId($"itemLoad_{fileReferences.GetHashCode()}");

            foreach (var fileReference in fileReferences)
            {
                this.StatusSpinner.Active = true;

                uint statusMessageID = this.MainStatusBar.Push
                                       (
                    statusMessageContextID,
                    $"Saving \"{fileReference.Filename}\"..."
                                       );

                string cleanFilepath = fileReference.FilePath.ConvertPathSeparatorsToCurrentNativeSeparator();

                string exportpath;
                if (this.Config.KeepFileDirectoryStructure)
                {
                    exportpath = IOPath.Combine(this.Config.DefaultExportDirectory, cleanFilepath);
                    Directory.CreateDirectory(Directory.GetParent(exportpath).FullName);
                }
                else
                {
                    string filename = IOPath.GetFileName(cleanFilepath);
                    exportpath = IOPath.Combine(this.Config.DefaultExportDirectory, filename);
                    Directory.CreateDirectory(Directory.GetParent(exportpath).FullName);
                }

                byte[] file = await fileReference.ExtractAsync();

                if (file != null)
                {
                    try
                    {
                        if (File.Exists(exportpath))
                        {
                            File.Delete(exportpath);
                        }

                        using (var fs = new FileStream(exportpath, FileMode.CreateNew, FileAccess.Write, FileShare.None))
                        {
                            await fs.WriteAsync(file, 0, file.Length);
                        }
                    }
                    catch (UnauthorizedAccessException unex)
                    {
                        Log.Warn($"Failed to save \"{fileReference.Filename}\": {unex}");
                    }
                    catch (IOException iex)
                    {
                        Log.Warn($"Failed to save \"{fileReference.Filename}\": {iex}");
                    }
                }
                else
                {
                    Log.Warn($"Failed to save \"{fileReference.Filename}\": Could not extract any data from the archives.");
                }

                this.MainStatusBar.Remove(statusMessageContextID, statusMessageID);
            }

            this.StatusSpinner.Active = false;
        }
Exemple #20
0
        /// <summary>
        /// copies files from current folder to "app data" folder, if not
        /// </summary>
        void ICstAppUser.InstallOnThisPC()
        {
            try
            {
                string mainExeFileName;
                bool   closeThisProcess = false;
                // copy files to LocalPcInstallationFolder
                if (!RunningInstalledOnThisPC)
                {
                    var localPcInstallationFolder = LocalPcInstallationFolder;
                    if (!Directory.Exists(localPcInstallationFolder))
                    {
                        Directory.CreateDirectory(localPcInstallationFolder);
                    }
                    var currentProcessDirectory = CurrentProcessDirectory;
                    foreach (var dllFileName in Directory.GetFiles(currentProcessDirectory, "*.*")
                             .Select(x => x.ToLower())
                             .Where(s => s.EndsWith(".config") || s.EndsWith(".dll") || s.EndsWith(".exe") || s.EndsWith(".json")))
                    {
                        File.Copy(dllFileName, Path.Combine(localPcInstallationFolder, Path.GetFileName(dllFileName)), true);
                    }

                    mainExeFileName = Path.Combine(localPcInstallationFolder, Path.GetFileName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName));
                    File.Copy(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName, mainExeFileName, true);

                    // create shortcut on desktop
                    var link = (IShellLink) new ShellLink();
                    link.SetDescription("StarTrinity Continuous Speed Test");
                    link.SetPath(mainExeFileName);
                    var linkFile = (IPersistFile)link;
                    linkFile.Save(DesktopShortcutFileName, false);

                    // create icon in start menu
                    linkFile.Save(StartMenuShortcutFileName, false);

                    // show message box
                    MessageBox.Show($"Installation succeeded.\r\nPress OK to start the new installed program.\r\n\r\nCreated shortcut on desktop and in Start menu\r\nInstallation folder: {localPcInstallationFolder}");

                    // start new process
                    Process.Start(mainExeFileName);

                    closeThisProcess = true;
                }
                else
                {
                    mainExeFileName = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
                }

                if (_cstApp.InstallOnThisPC_AddToAutoStart)
                {
                    var rk = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
                    rk.SetValue(AppNameInRegistry, mainExeFileName + " " + CstApp.TrayCliParameter);
                }

                if (closeThisProcess)
                {
                    System.Windows.Application.Current.Shutdown();
                }
                // RaisePropertyChanged(() => InstalledOnThisPcAndAutostartInTrayMode);
            }
            catch (Exception exc)
            {
                CstApp.HandleException(exc);
            }
        }
Exemple #21
0
        //private static readonly string VssDir = @"C:\____vssMount";


        private static void Main(string[] args)
        {
            ExceptionlessClient.Default.Startup("tYeWS6A5K5uItgpB44dnNy2qSb2xJxiQWRRGWebq");

            SetupNLog();

            _logger = LogManager.GetLogger("EvtxECmd");

            _fluentCommandLineParser = new FluentCommandLineParser <ApplicationArguments>
            {
                IsCaseSensitive = false
            };

            _fluentCommandLineParser.Setup(arg => arg.File)
            .As('f')
            .WithDescription("File to process. This or -d is required\r\n");
            _fluentCommandLineParser.Setup(arg => arg.Directory)
            .As('d')
            .WithDescription("Directory to process that contains evtx files. This or -f is required");

            _fluentCommandLineParser.Setup(arg => arg.CsvDirectory)
            .As("csv")
            .WithDescription(
                "Directory to save CSV formatted results to.");     // This, --json, or --xml required

            _fluentCommandLineParser.Setup(arg => arg.CsvName)
            .As("csvf")
            .WithDescription(
                "File name to save CSV formatted results to. When present, overrides default name");

            _fluentCommandLineParser.Setup(arg => arg.JsonDirectory)
            .As("json")
            .WithDescription(
                "Directory to save JSON formatted results to.");     // This, --csv, or --xml required
            _fluentCommandLineParser.Setup(arg => arg.JsonName)
            .As("jsonf")
            .WithDescription(
                "File name to save JSON formatted results to. When present, overrides default name");

            _fluentCommandLineParser.Setup(arg => arg.XmlDirectory)
            .As("xml")
            .WithDescription(
                "Directory to save XML formatted results to.");     // This, --csv, or --json required

            _fluentCommandLineParser.Setup(arg => arg.XmlName)
            .As("xmlf")
            .WithDescription(
                "File name to save XML formatted results to. When present, overrides default name\r\n");

            _fluentCommandLineParser.Setup(arg => arg.DateTimeFormat)
            .As("dt")
            .WithDescription(
                "The custom date/time format to use when displaying time stamps. Default is: yyyy-MM-dd HH:mm:ss.fffffff")
            .SetDefault("yyyy-MM-dd HH:mm:ss.fffffff");

            _fluentCommandLineParser.Setup(arg => arg.IncludeIds)
            .As("inc")
            .WithDescription(
                "List of event IDs to process. All others are ignored. Overrides --exc Format is 4624,4625,5410")
            .SetDefault(string.Empty);

            _fluentCommandLineParser.Setup(arg => arg.ExcludeIds)
            .As("exc")
            .WithDescription(
                "List of event IDs to IGNORE. All others are included. Format is 4624,4625,5410")
            .SetDefault(string.Empty);

            _fluentCommandLineParser.Setup(arg => arg.StartDate)
            .As("sd")
            .WithDescription(
                "Start date for including events (UTC). Anything OLDER than this is dropped. Format should match --dt")
            .SetDefault(string.Empty);

            _fluentCommandLineParser.Setup(arg => arg.EndDate)
            .As("ed")
            .WithDescription(
                "End date for including events (UTC). Anything NEWER than this is dropped. Format should match --dt")
            .SetDefault(string.Empty);

            _fluentCommandLineParser.Setup(arg => arg.FullJson)
            .As("fj")
            .WithDescription(
                "When true, export all available data when using --json. Default is FALSE.")
            .SetDefault(false);
            _fluentCommandLineParser.Setup(arg => arg.PayloadAsJson)
            .As("pj")
            .WithDescription(
                "When true, include event *payload* as json. Default is TRUE.")
            .SetDefault(true);

            _fluentCommandLineParser.Setup(arg => arg.TimeDiscrepancyThreshold)
            .As("tdt")
            .WithDescription(
                "The number of seconds to use for time discrepancy detection. Default is 1 second")
            .SetDefault(1);

            _fluentCommandLineParser.Setup(arg => arg.Metrics)
            .As("met")
            .WithDescription(
                "When true, show metrics about processed event log. Default is TRUE.\r\n")
            .SetDefault(true);

            _fluentCommandLineParser.Setup(arg => arg.MapsDirectory)
            .As("maps")
            .WithDescription(
                "The path where event maps are located. Defaults to 'Maps' folder where program was executed\r\n  ")
            .SetDefault(Path.Combine(BaseDirectory, "Maps"));

            /*_fluentCommandLineParser.Setup(arg => arg.Vss)
             *  .As("vss")
             *  .WithDescription(
             *      "Process all Volume Shadow Copies that exist on drive specified by -f or -d . Default is FALSE")
             *  .SetDefault(false);*/
            _fluentCommandLineParser.Setup(arg => arg.Dedupe)
            .As("dedupe")
            .WithDescription(
                "Deduplicate -f or -d & VSCs based on SHA-1. First file found wins. Default is TRUE\r\n")
            .SetDefault(true);

            _fluentCommandLineParser.Setup(arg => arg.Sync)
            .As("sync")
            .WithDescription(
                "If true, the latest maps from https://github.com/EricZimmerman/evtx/tree/master/evtx/Maps are downloaded and local maps updated. Default is FALSE\r\n")
            .SetDefault(false);

            _fluentCommandLineParser.Setup(arg => arg.Debug)
            .As("debug")
            .WithDescription("Show debug information during processing").SetDefault(false);

            _fluentCommandLineParser.Setup(arg => arg.Trace)
            .As("trace")
            .WithDescription("Show trace information during processing\r\n").SetDefault(false);

            var header =
                $"EvtxECmd version {Assembly.GetExecutingAssembly().GetName().Version}" +
                "\n\nAuthor: Eric Zimmerman ([email protected])" +
                "\nhttps://github.com/EricZimmerman/evtx" +
                "\nLinux Port : Scott Dermott ([email protected])" +
                "\nhttps://github.com/ScottDermott/evtx";

            var footer =
                @"Examples: EvtxECmd -f ""/Temp/Application.evtx"" --csv ""/temp/out"" --csvf MyOutputFile.csv" +
                "\r\n\t " +
                @" EvtxECmd -f ""/Temp/Application.evtx"" --csv ""/temp/out""" + "\r\n\t " +
                @" EvtxECmd -f ""/Temp/Application.evtx"" --json ""/temp/jsonout""" + "\r\n\t " +
                "\r\n\t" +
                "  Short options (single letter) are prefixed with a single dash. Long commands are prefixed with two dashes\r\n";

            _fluentCommandLineParser.SetupHelp("?", "help")
            .WithHeader(header)
            .Callback(text => _logger.Info(text + "\r\n" + footer));

            var result = _fluentCommandLineParser.Parse(args);

            if (result.HelpCalled)
            {
                return;
            }

            if (result.HasErrors)
            {
                _logger.Error("");
                _logger.Error(result.ErrorText);

                _fluentCommandLineParser.HelpOption.ShowHelp(_fluentCommandLineParser.Options);

                return;
            }

            if (_fluentCommandLineParser.Object.Sync)
            {
                try
                {
                    _logger.Info(header);
                    UpdateFromRepo();
                }
                catch (Exception e)
                {
                    _logger.Error(e, $"There was an error checking for updates: {e.Message}");
                }

                Environment.Exit(0);
            }

            if (_fluentCommandLineParser.Object.File.IsNullOrEmpty() &&
                _fluentCommandLineParser.Object.Directory.IsNullOrEmpty())
            {
                _fluentCommandLineParser.HelpOption.ShowHelp(_fluentCommandLineParser.Options);

                _logger.Warn("-f or -d is required. Exiting");
                return;
            }

            _logger.Info(header);
            _logger.Info("");
            _logger.Info($"Command line: {string.Join(" ", Environment.GetCommandLineArgs().Skip(1))}\r\n");



/*            if (IsAdministrator() == false)
 *          {
 *              _logger.Fatal("Warning: Administrator privileges not found!\r\n");
 *          }*/

            if (_fluentCommandLineParser.Object.Debug)
            {
                LogManager.Configuration.LoggingRules.First().EnableLoggingForLevel(LogLevel.Debug);
            }

            if (_fluentCommandLineParser.Object.Trace)
            {
                LogManager.Configuration.LoggingRules.First().EnableLoggingForLevel(LogLevel.Trace);
            }

            LogManager.ReconfigExistingLoggers();

            /* if (_fluentCommandLineParser.Object.Vss & (IsAdministrator() == false))
             * {
             *   _logger.Error("--vss is present, but administrator rights not found. Exiting\r\n");
             *   return;
             * }*/

            var sw = new Stopwatch();

            sw.Start();

            var ts = DateTimeOffset.UtcNow;

            _errorFiles = new Dictionary <string, int>();

            if (_fluentCommandLineParser.Object.JsonDirectory.IsNullOrEmpty() == false)
            {
                if (Directory.Exists(_fluentCommandLineParser.Object.JsonDirectory) == false)
                {
                    _logger.Warn(
                        $"Path to '{_fluentCommandLineParser.Object.JsonDirectory}' doesn't exist. Creating...");

                    try
                    {
                        Directory.CreateDirectory(_fluentCommandLineParser.Object.JsonDirectory);
                    }
                    catch (Exception)
                    {
                        _logger.Fatal(
                            $"Unable to create directory '{_fluentCommandLineParser.Object.JsonDirectory}'. Does a file with the same name exist? Exiting");
                        return;
                    }
                }

                var outName = $"{ts:yyyyMMddHHmmss}_EvtxECmd_Output.json";

                if (_fluentCommandLineParser.Object.JsonName.IsNullOrEmpty() == false)
                {
                    outName = Path.GetFileName(_fluentCommandLineParser.Object.JsonName);
                }

                var outFile = Path.Combine(_fluentCommandLineParser.Object.JsonDirectory, outName);

                _logger.Warn($"json output will be saved to '{outFile}'\r\n");

                try
                {
                    _swJson = new StreamWriter(outFile, false, Encoding.UTF8);
                }
                catch (Exception)
                {
                    _logger.Error($"Unable to open '{outFile}'! Is it in use? Exiting!\r\n");
                    Environment.Exit(0);
                }

                JsConfig.DateHandler = DateHandler.ISO8601;
            }

            if (_fluentCommandLineParser.Object.XmlDirectory.IsNullOrEmpty() == false)
            {
                if (Directory.Exists(_fluentCommandLineParser.Object.XmlDirectory) == false)
                {
                    _logger.Warn(
                        $"Path to '{_fluentCommandLineParser.Object.XmlDirectory}' doesn't exist. Creating...");

                    try
                    {
                        Directory.CreateDirectory(_fluentCommandLineParser.Object.XmlDirectory);
                    }
                    catch (Exception)
                    {
                        _logger.Fatal(
                            $"Unable to create directory '{_fluentCommandLineParser.Object.XmlDirectory}'. Does a file with the same name exist? Exiting");
                        return;
                    }
                }

                var outName = $"{ts:yyyyMMddHHmmss}_EvtxECmd_Output.xml";

                if (_fluentCommandLineParser.Object.XmlName.IsNullOrEmpty() == false)
                {
                    outName = Path.GetFileName(_fluentCommandLineParser.Object.XmlName);
                }

                var outFile = Path.Combine(_fluentCommandLineParser.Object.XmlDirectory, outName);

                _logger.Warn($"XML output will be saved to '{outFile}'\r\n");

                try
                {
                    _swXml = new StreamWriter(outFile, false, Encoding.UTF8);
                }
                catch (Exception)
                {
                    _logger.Error($"Unable to open '{outFile}'! Is it in use? Exiting!\r\n");
                    Environment.Exit(0);
                }
            }

            if (_fluentCommandLineParser.Object.StartDate.IsNullOrEmpty() == false)
            {
                if (DateTimeOffset.TryParse(_fluentCommandLineParser.Object.StartDate, null, DateTimeStyles.AssumeUniversal, out var dt))
                {
                    _startDate = dt;
                    _logger.Info($"Setting Start date to '{_startDate.Value.ToUniversalTime().ToString(_fluentCommandLineParser.Object.DateTimeFormat)}'");
                }
                else
                {
                    _logger.Warn($"Could not parse '{_fluentCommandLineParser.Object.StartDate}' to a valud datetime! Events will not be filtered by Start date!");
                }
            }
            if (_fluentCommandLineParser.Object.EndDate.IsNullOrEmpty() == false)
            {
                if (DateTimeOffset.TryParse(_fluentCommandLineParser.Object.EndDate, null, DateTimeStyles.AssumeUniversal, out var dt))
                {
                    _endDate = dt;
                    _logger.Info($"Setting End date to '{_endDate.Value.ToUniversalTime().ToString(_fluentCommandLineParser.Object.DateTimeFormat)}'");
                }
                else
                {
                    _logger.Warn($"Could not parse '{_fluentCommandLineParser.Object.EndDate}' to a valud datetime! Events will not be filtered by End date!");
                }
            }

            if (_startDate.HasValue || _endDate.HasValue)
            {
                _logger.Info("");
            }


            if (_fluentCommandLineParser.Object.CsvDirectory.IsNullOrEmpty() == false)
            {
                if (Directory.Exists(_fluentCommandLineParser.Object.CsvDirectory) == false)
                {
                    _logger.Warn(
                        $"Path to '{_fluentCommandLineParser.Object.CsvDirectory}' doesn't exist. Creating...");

                    try
                    {
                        Directory.CreateDirectory(_fluentCommandLineParser.Object.CsvDirectory);
                    }
                    catch (Exception)
                    {
                        _logger.Fatal(
                            $"Unable to create directory '{_fluentCommandLineParser.Object.CsvDirectory}'. Does a file with the same name exist? Exiting");
                        return;
                    }
                }

                var outName = $"{ts:yyyyMMddHHmmss}_EvtxECmd_Output.csv";

                if (_fluentCommandLineParser.Object.CsvName.IsNullOrEmpty() == false)
                {
                    outName = Path.GetFileName(_fluentCommandLineParser.Object.CsvName);
                }

                var outFile = Path.Combine(_fluentCommandLineParser.Object.CsvDirectory, outName);

                _logger.Warn($"CSV output will be saved to '{outFile}'\r\n");

                try
                {
                    _swCsv = new StreamWriter(outFile, false, Encoding.UTF8);

                    _csvWriter = new CsvWriter(_swCsv, CultureInfo.InvariantCulture);
                }
                catch (Exception)
                {
                    _logger.Error($"Unable to open '{outFile}'! Is it in use? Exiting!\r\n");
                    Environment.Exit(0);
                }

                var foo = _csvWriter.Configuration.AutoMap <EventRecord>();

                if (_fluentCommandLineParser.Object.PayloadAsJson == false)
                {
                    foo.Map(t => t.Payload).Ignore();
                }
                else
                {
                    foo.Map(t => t.Payload).Index(22);
                }

                foo.Map(t => t.RecordPosition).Ignore();
                foo.Map(t => t.Size).Ignore();
                foo.Map(t => t.Timestamp).Ignore();

                foo.Map(t => t.RecordNumber).Index(0);
                foo.Map(t => t.EventRecordId).Index(1);
                foo.Map(t => t.TimeCreated).Index(2);
                foo.Map(t => t.TimeCreated).ConvertUsing(t =>
                                                         $"{t.TimeCreated.ToString(_fluentCommandLineParser.Object.DateTimeFormat)}");
                foo.Map(t => t.EventId).Index(3);
                foo.Map(t => t.Level).Index(4);
                foo.Map(t => t.Provider).Index(5);
                foo.Map(t => t.Channel).Index(6);
                foo.Map(t => t.ProcessId).Index(7);
                foo.Map(t => t.ThreadId).Index(8);
                foo.Map(t => t.Computer).Index(9);
                foo.Map(t => t.UserId).Index(10);
                foo.Map(t => t.MapDescription).Index(11);
                foo.Map(t => t.UserName).Index(12);
                foo.Map(t => t.RemoteHost).Index(13);
                foo.Map(t => t.PayloadData1).Index(14);
                foo.Map(t => t.PayloadData2).Index(15);
                foo.Map(t => t.PayloadData3).Index(16);
                foo.Map(t => t.PayloadData4).Index(17);
                foo.Map(t => t.PayloadData5).Index(18);
                foo.Map(t => t.PayloadData6).Index(19);
                foo.Map(t => t.ExecutableInfo).Index(20);
                foo.Map(t => t.SourceFile).Index(21);

                _csvWriter.Configuration.RegisterClassMap(foo);
                _csvWriter.WriteHeader <EventRecord>();
                _csvWriter.NextRecord();
            }

            if (Directory.Exists(_fluentCommandLineParser.Object.MapsDirectory) == false)
            {
                _logger.Warn(
                    $"Maps directory '{_fluentCommandLineParser.Object.MapsDirectory}' does not exist! Event ID maps will not be loaded!!");
            }
            else
            {
                _logger.Info($"Loading maps from '{Path.GetFullPath(_fluentCommandLineParser.Object.MapsDirectory)}'");
                var errors = EventLog.LoadMaps(Path.GetFullPath(_fluentCommandLineParser.Object.MapsDirectory));

                if (errors)
                {
                    return;
                }

                _logger.Info($"Maps loaded: {EventLog.EventLogMaps.Count:N0}");
            }

            _includeIds = new HashSet <int>();
            _excludeIds = new HashSet <int>();

            if (_fluentCommandLineParser.Object.ExcludeIds.IsNullOrEmpty() == false)
            {
                var excSegs = _fluentCommandLineParser.Object.ExcludeIds.Split(',');

                foreach (var incSeg in excSegs)
                {
                    if (int.TryParse(incSeg, out var goodId))
                    {
                        _excludeIds.Add(goodId);
                    }
                }
            }

            if (_fluentCommandLineParser.Object.IncludeIds.IsNullOrEmpty() == false)
            {
                _excludeIds.Clear();
                var incSegs = _fluentCommandLineParser.Object.IncludeIds.Split(',');

                foreach (var incSeg in incSegs)
                {
                    if (int.TryParse(incSeg, out var goodId))
                    {
                        _includeIds.Add(goodId);
                    }
                }
            }

            /*if (_fluentCommandLineParser.Object.Vss)
             * {
             *  string driveLetter;
             *  if (_fluentCommandLineParser.Object.File.IsEmpty() == false)
             *  {
             *      driveLetter = Path.GetPathRoot(Path.GetFullPath(_fluentCommandLineParser.Object.File))
             *          .Substring(0, 1);
             *  }
             *  else
             *  {
             *      driveLetter = Path.GetPathRoot(Path.GetFullPath(_fluentCommandLineParser.Object.Directory))
             *          .Substring(0, 1);
             *  }
             *
             *
             *  Helper.MountVss(driveLetter,VssDir);
             *  Console.WriteLine();
             * }*/

            EventLog.TimeDiscrepancyThreshold = _fluentCommandLineParser.Object.TimeDiscrepancyThreshold;

            if (_fluentCommandLineParser.Object.File.IsNullOrEmpty() == false)
            {
                if (File.Exists(_fluentCommandLineParser.Object.File) == false)
                {
                    _logger.Warn($"'{_fluentCommandLineParser.Object.File}' does not exist! Exiting");
                    return;
                }

                if (_swXml == null && _swJson == null && _swCsv == null)
                {
                    //no need for maps
                    _logger.Debug("Clearing map collection since no output specified");
                    EventLog.EventLogMaps.Clear();
                }

                _fluentCommandLineParser.Object.Dedupe = false;

                ProcessFile(Path.GetFullPath(_fluentCommandLineParser.Object.File));

                /*if (_fluentCommandLineParser.Object.Vss)
                 * {
                 *  var vssDirs = Directory.GetDirectories(VssDir);
                 *
                 *  var root = Path.GetPathRoot(Path.GetFullPath(_fluentCommandLineParser.Object.File));
                 *  var stem = Path.GetFullPath(_fluentCommandLineParser.Object.File).Replace(root, "");
                 *
                 *  foreach (var vssDir in vssDirs)
                 *  {
                 *      var newPath = Path.Combine(vssDir, stem);
                 *      if (File.Exists(newPath))
                 *      {
                 *          ProcessFile(newPath);
                 *      }
                 *  }
                 * }*/
            }
            else
            {
                _logger.Info($"Looking for event log files in '{_fluentCommandLineParser.Object.Directory}'");
                _logger.Info("");

/*                var f = new DirectoryEnumerationFilters
 *              {
 *                  InclusionFilter = fsei => fsei.Extension.ToUpperInvariant() == ".EVTX",
 *                  RecursionFilter = entryInfo => !entryInfo.IsMountPoint && !entryInfo.IsSymbolicLink,
 *                  ErrorFilter = (errorCode, errorMessage, pathProcessed) => true
 *              };*/

/*                var dirEnumOptions =
 *                  DirectoryEnumerationOptions.Files | DirectoryEnumerationOptions.Recursive |
 *                  DirectoryEnumerationOptions.SkipReparsePoints | DirectoryEnumerationOptions.ContinueOnException |
 *                  DirectoryEnumerationOptions.BasicSearch;*/

                var files2 = Directory.EnumerateFileSystemEntries(Path.GetFullPath(_fluentCommandLineParser.Object.Directory), "*.evtx");

                if (_swXml == null && _swJson == null && _swCsv == null)
                {
                    //no need for maps
                    _logger.Debug("Clearing map collection since no output specified");
                    EventLog.EventLogMaps.Clear();
                }

                foreach (var file in files2)
                {
                    ProcessFile(file);
                }

                /*if (_fluentCommandLineParser.Object.Vss)
                 * {
                 *  var vssDirs = Directory.GetDirectories(VssDir);
                 *
                 *  Console.WriteLine();
                 *
                 *  foreach (var vssDir in vssDirs)
                 *  {
                 *      var root = Path.GetPathRoot(Path.GetFullPath(_fluentCommandLineParser.Object.Directory));
                 *      var stem = Path.GetFullPath(_fluentCommandLineParser.Object.Directory).Replace(root, "");
                 *
                 *      var target = Path.Combine(vssDir, stem);
                 *
                 *      _logger.Fatal($"\r\nSearching 'VSS{target.Replace($"{VssDir}\\","")}' for event logs...");
                 *
                 *      var vssFiles = Helper.GetFilesFromPath(target, true, "*.evtx");
                 *
                 *      foreach (var file in vssFiles)
                 *      {
                 *          ProcessFile(file);
                 *      }
                 *  }
                 *
                 * }*/
            }

            _swCsv?.Flush();
            _swCsv?.Close();

            _swJson?.Flush();
            _swJson?.Close();

            _swXml?.Flush();
            _swXml?.Close();

            sw.Stop();
            _logger.Info("");

            var suff = string.Empty;

            if (_fileCount != 1)
            {
                suff = "s";
            }

            _logger.Error(
                $"Processed {_fileCount:N0} file{suff} in {sw.Elapsed.TotalSeconds:N4} seconds\r\n");

            if (_errorFiles.Count > 0)
            {
                _logger.Info("");
                _logger.Error("Files with errors");
                foreach (var errorFile in _errorFiles)
                {
                    _logger.Info($"'{errorFile.Key}' error count: {errorFile.Value:N0}");
                }

                _logger.Info("");
            }

            /*if (_fluentCommandLineParser.Object.Vss)
             * {
             *  if (Directory.Exists(VssDir))
             *  {
             *      foreach (var directory in Directory.GetDirectories(VssDir))
             *      {
             *          Directory.Delete(directory);
             *      }
             *      Directory.Delete(VssDir,true);
             *  }
             * }*/
        }
Exemple #22
0
        protected override Boolean PatchFile(String fileName)
        {
            List <PatchResource> patchResources = new List <PatchResource>();

            foreach (PatchResourceSet set in _resourceSets)
            {
                if (EvaluatePatchResourceSet(set, fileName))
                {
                    // HACK: This just adds them together into a massive list. If the same name is mentioned it'll be overwritten several times
                    // fortunately it isnt' very expensive as only the last "final" one counts, but could do with filtering at this stage maybe?

                    patchResources.AddRange(set.Resources);
                }
                else
                {
                    Package.Log.Add(LogSeverity.Info, "Expression evaluation non-one: " + set.Condition.ExpressionString + ", did not process " + set.Resources.Count + " resources");
                }
            }

            if (patchResources.Count == 0)
            {
                Package.Log.Add(LogSeverity.Warning, "No resources to patch: " + fileName);
                return(false);
            }

            try {
                // for now, use lazy-load under all circumstances. In future analyse the Resources list to see if it's necessary or not
                // but the performance impact is minimal and it's the safest option, so keep it as it is
                using (ResourceSource source = ResourceSource.Open(fileName, false, ResourceSourceLoadMode.LazyLoadData)) {
                    List <String> tempFiles = new List <String>();

                    foreach (PatchResource res in patchResources)
                    {
                        if (res.Source.StartsWith("comp:", StringComparison.OrdinalIgnoreCase))
                        {
                            CompositedImage comp = new CompositedImage(res.Source, Package.RootDirectory);

                            DirectoryInfo packageTempDirectory = new DirectoryInfo(P.Combine(Package.RootDirectory.FullName, "Temp"));
                            if (!packageTempDirectory.Exists)
                            {
                                packageTempDirectory.Create();
                            }

                            // I think not using the *.bmp extension messes up Bitmap import
                            String tempFileName = PackageUtility.GetUnusedFileName(P.Combine(packageTempDirectory.FullName, P.GetFileName(Path) + res.Name) + ".bmp");

                            comp.Save(tempFileName, System.Drawing.Imaging.ImageFormat.Bmp);

                            res.File = tempFileName;
                            tempFiles.Add(tempFileName);
                        }
                        else
                        {
                            res.File = res.Source;
                        }

                        if (!File.Exists(res.File))
                        {
                            Package.Log.Add(LogSeverity.Error, "Data File not found: " + res.File);
                            continue;
                        }

                        ResourceTypeIdentifier typeId = ResourceTypeIdentifier.CreateFromString(res.Type, true);
                        ResourceIdentifier     nameId = ResourceIdentifier.CreateFromString(res.Name);
                        UInt16 langId = String.IsNullOrEmpty(res.Lang) ? UInt16.MaxValue : UInt16.Parse(res.Lang, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture);


                        if (langId == UInt16.MaxValue)                                // if the lang="" attribute was not specified

                        {
                            ResourceName name = source.GetName(typeId, nameId);

                            if (name == null)                              // if the specified name does not exist

                            {
                                if (res.Add)
                                {
                                    UInt16 sysLang = (UInt16)CultureInfo.InvariantCulture.LCID;

                                    ResourceData data = ResourceData.FromFileToAdd(res.File, sysLang, source);
                                    source.Add(typeId, nameId, sysLang, data);
                                }
                                else
                                {
                                    // Error

                                    String sourcePath = source.Name;

                                    Anolis.Core.Source.FileResourceSource frs = source as Anolis.Core.Source.FileResourceSource;
                                    if (frs != null)
                                    {
                                        sourcePath = frs.FileInfo.FullName;
                                    }

                                    Package.Log.Add(LogSeverity.Warning, "Resource name not found: " + sourcePath + '\\' + typeId.ToString() + '\\' + nameId.FriendlyName);
                                }
                            }
                            else
                            {
                                foreach (ResourceLang lang in name.Langs)
                                {
                                    ResourceData data = ResourceData.FromFileToUpdate(res.File, lang);
                                    lang.SwapData(data);
                                }
                            }
                        }
                        else                             // if the lang="" attribute was specified

                        {
                            ResourceLang lang = source.GetLang(typeId, nameId, langId);
                            if (lang == null)
                            {
                                ResourceData data = ResourceData.FromFileToAdd(res.File, langId, source);
                                source.Add(typeId, nameId, langId, data);
                            }
                            else
                            {
                                ResourceData data = ResourceData.FromFileToUpdate(res.File, lang);
                                lang.SwapData(data);
                            }
                        }
                    }                    //foreach

                    // note that Win32ResourceSource now recomptues the PE checksum by itself
                    source.CommitChanges();

                    foreach (String tempFile in tempFiles)
                    {
                        File.Delete(tempFile);
                    }

                    return(true);
                }                //using source
            } catch (AnolisException aex) {
                Package.Log.Add(LogSeverity.Error, "Patch Exception: " + aex.Message);

                if (File.Exists(fileName))
                {
                    File.Delete(fileName);
                }

                throw;
            }
        }
Exemple #23
0
        private static void UpdateFromRepo()
        {
            Console.WriteLine();

            _logger.Info(
                "Checking for updated maps at https://github.com/EricZimmerman/evtx/tree/master/evtx/Maps...");
            Console.WriteLine();
            var archivePath = Path.Combine(BaseDirectory, "____master.zip");

            if (File.Exists(archivePath))
            {
                File.Delete(archivePath);
            }

            using (var client = new WebClient())
            {
                ServicePointManager.Expect100Continue = true;
                ServicePointManager.SecurityProtocol  = SecurityProtocolType.Tls12;
                client.DownloadFile("https://github.com/EricZimmerman/evtx/archive/master.zip", archivePath);
            }

            var fff = new FastZip();

            var directoryFilter = "Maps";

            // Will prompt to overwrite if target file names already exist
            fff.ExtractZip(archivePath, BaseDirectory, FastZip.Overwrite.Always, null,
                           null, directoryFilter, true);

            if (File.Exists(archivePath))
            {
                File.Delete(archivePath);
            }

            var newMapPath = Path.Combine(BaseDirectory, "evtx-master", "evtx", "Maps");

            var orgMapMath = Path.Combine(BaseDirectory, "Maps");

            var newMaps = Directory.GetFiles(newMapPath);

            var newlocalMaps = new List <string>();

            var updatedlocalMaps = new List <string>();

            foreach (var newMap in newMaps)
            {
                var mName = Path.GetFileName(newMap);
                var dest  = Path.Combine(orgMapMath, mName);

                if (File.Exists(dest) == false)
                {
                    //new target
                    newlocalMaps.Add(mName);
                }
                else
                {
                    //current destination file exists, so compare to new
                    //var fiNew = new FileInfo(newMap);
                    //var fi = new FileInfo(dest);

                    if (checkMD5(newMap) != checkMD5(dest))
                    {
                        //updated file
                        updatedlocalMaps.Add(mName);
                    }
                }

                File.Copy(newMap, dest);
            }



            if (newlocalMaps.Count > 0 || updatedlocalMaps.Count > 0)
            {
                _logger.Fatal("Updates found!");
                Console.WriteLine();

                if (newlocalMaps.Count > 0)
                {
                    _logger.Error("New maps");
                    foreach (var newLocalMap in newlocalMaps)
                    {
                        _logger.Info(Path.GetFileNameWithoutExtension(newLocalMap));
                    }

                    Console.WriteLine();
                }

                if (updatedlocalMaps.Count > 0)
                {
                    _logger.Error("Updated maps");
                    foreach (var um in updatedlocalMaps)
                    {
                        _logger.Info(Path.GetFileNameWithoutExtension(um));
                    }

                    Console.WriteLine();
                }

                Console.WriteLine();
            }
            else
            {
                Console.WriteLine();
                _logger.Info("No new maps available");
                Console.WriteLine();
            }

            Directory.Delete(Path.Combine(BaseDirectory, "evtx-master"), true);
        }
Exemple #24
0
        /// <summary>
        /// Create a new character and show the Create Form.
        /// </summary>
        private void ShowNewForm(object sender, EventArgs e)
        {
            string strFilePath = Path.Combine(Application.StartupPath, "settings", "default.xml");

            if (!File.Exists(strFilePath))
            {
                if (MessageBox.Show(LanguageManager.GetString("Message_CharacterOptions_OpenOptions", GlobalOptions.Language), LanguageManager.GetString("MessageTitle_CharacterOptions_OpenOptions", GlobalOptions.Language), MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    Cursor = Cursors.WaitCursor;
                    frmOptions frmOptions = new frmOptions();
                    frmOptions.ShowDialog();
                    Cursor = Cursors.Default;
                }
            }
            Cursor = Cursors.WaitCursor;
            Character objCharacter = new Character();
            string    settingsPath = Path.Combine(Application.StartupPath, "settings");

            string[] settingsFiles = Directory.GetFiles(settingsPath, "*.xml");

            if (settingsFiles.Length > 1)
            {
                frmSelectSetting frmPickSetting = new frmSelectSetting();
                frmPickSetting.ShowDialog(this);

                if (frmPickSetting.DialogResult == DialogResult.Cancel)
                {
                    return;
                }

                objCharacter.SettingsFile = frmPickSetting.SettingsFile;
            }
            else
            {
                string strSettingsFile = settingsFiles[0];
                objCharacter.SettingsFile = Path.GetFileName(strSettingsFile);
            }

            // Show the BP selection window.
            frmSelectBuildMethod frmBP = new frmSelectBuildMethod(objCharacter);

            frmBP.ShowDialog();
            Cursor = Cursors.Default;

            if (frmBP.DialogResult == DialogResult.Cancel)
            {
                return;
            }
            if (objCharacter.BuildMethod == CharacterBuildMethod.Karma || objCharacter.BuildMethod == CharacterBuildMethod.LifeModule)
            {
                Cursor = Cursors.WaitCursor;
                frmKarmaMetatype frmSelectMetatype = new frmKarmaMetatype(objCharacter);
                frmSelectMetatype.ShowDialog();
                Cursor = Cursors.Default;

                if (frmSelectMetatype.DialogResult == DialogResult.Cancel)
                {
                    return;
                }
            }
            // Show the Metatype selection window.
            else if (objCharacter.BuildMethod == CharacterBuildMethod.Priority || objCharacter.BuildMethod == CharacterBuildMethod.SumtoTen)
            {
                Cursor = Cursors.WaitCursor;
                frmPriorityMetatype frmSelectMetatype = new frmPriorityMetatype(objCharacter);
                frmSelectMetatype.ShowDialog();
                Cursor = Cursors.Default;

                if (frmSelectMetatype.DialogResult == DialogResult.Cancel)
                {
                    return;
                }
            }
            Cursor = Cursors.WaitCursor;

            // Add the Unarmed Attack Weapon to the character.
            XmlDocument objXmlDocument = XmlManager.Load("weapons.xml");
            XmlNode     objXmlWeapon   = objXmlDocument.SelectSingleNode("/chummer/weapons/weapon[name = \"Unarmed Attack\"]");

            if (objXmlWeapon != null)
            {
                List <Weapon> lstWeapons = new List <Weapon>();
                Weapon        objWeapon  = new Weapon(objCharacter);
                objWeapon.Create(objXmlWeapon, lstWeapons);
                objWeapon.ParentID = Guid.NewGuid().ToString("D"); // Unarmed Attack can never be removed
                objCharacter.Weapons.Add(objWeapon);
                foreach (Weapon objLoopWeapon in lstWeapons)
                {
                    objCharacter.Weapons.Add(objLoopWeapon);
                }
            }

            frmCreate frmNewCharacter = new frmCreate(objCharacter)
            {
                MdiParent   = this,
                WindowState = FormWindowState.Maximized
            };

            frmNewCharacter.Show();

            objCharacter.CharacterNameChanged += objCharacter_CharacterNameChanged;
            Cursor = Cursors.Default;
        }
Exemple #25
0
    private static void DoWork(string d, string f, string @out, bool ca, bool cn, bool debug, bool trace)
    {
        if (f.IsNullOrEmpty() == false ||
            d.IsNullOrEmpty() == false)
        {
            if (@out.IsNullOrEmpty())
            {
                var helpBld = new HelpBuilder(LocalizationResources.Instance, Console.WindowWidth);
                var hc      = new HelpContext(helpBld, _rootCommand, Console.Out);

                helpBld.Write(hc);

                Console.WriteLine();
                _logger.Warn("--out is required. Exiting");
                Console.WriteLine();
                return;
            }
        }

        if (debug)
        {
            foreach (var r in LogManager.Configuration.LoggingRules)
            {
                r.EnableLoggingForLevel(LogLevel.Debug);
            }

            LogManager.ReconfigExistingLoggers();
            _logger.Debug("Enabled debug messages...");
        }

        if (trace)
        {
            foreach (var r in LogManager.Configuration.LoggingRules)
            {
                r.EnableLoggingForLevel(LogLevel.Trace);
            }

            LogManager.ReconfigExistingLoggers();
            _logger.Trace("Enabled trace messages...");
        }


        var hivesToProcess = new List <string>();

        _logger.Info(Header);
        _logger.Info("");
        _logger.Info($"Command line: {string.Join(" ", Environment.GetCommandLineArgs().Skip(1))}\r\n");

        if (f?.Length > 0)
        {
            if (File.Exists(f) == false)
            {
                _logger.Error($"File '{f}' does not exist.");
                return;
            }

            hivesToProcess.Add(f);
        }
        else if (d?.Length > 0)
        {
            if (Directory.Exists(d) == false)
            {
                _logger.Error($"Directory '{d}' does not exist.");
                return;
            }

            var okFileParts = new HashSet <string>();
            okFileParts.Add("USRCLASS");
            okFileParts.Add("NTUSER");
            okFileParts.Add("SYSTEM");
            okFileParts.Add("SAM");
            okFileParts.Add("SOFTWARE");
            okFileParts.Add("AMCACHE");
            okFileParts.Add("SYSCACHE");
            okFileParts.Add("SECURITY");
            okFileParts.Add("DRIVERS");
            okFileParts.Add("COMPONENTS");

            var directoryEnumerationFilters = new DirectoryEnumerationFilters();
            directoryEnumerationFilters.InclusionFilter = fsei =>
            {
                if (fsei.Extension.ToUpperInvariant() == ".LOG1" || fsei.Extension.ToUpperInvariant() == ".LOG2" ||
                    fsei.Extension.ToUpperInvariant() == ".DLL" ||
                    fsei.Extension.ToUpperInvariant() == ".LOG" ||
                    fsei.Extension.ToUpperInvariant() == ".CSV" ||
                    fsei.Extension.ToUpperInvariant() == ".BLF" ||
                    fsei.Extension.ToUpperInvariant() == ".REGTRANS-MS" ||
                    fsei.Extension.ToUpperInvariant() == ".EXE" ||
                    fsei.Extension.ToUpperInvariant() == ".TXT" || fsei.Extension.ToUpperInvariant() == ".INI")
                {
                    return(false);
                }

                var foundOkFilePart = false;

                foreach (var okFilePart in okFileParts)
                {
                    if (fsei.FileName.ToUpperInvariant().Contains(okFilePart))
                    {
                        foundOkFilePart = true;
                        //     return true;
                    }
                }

                if (foundOkFilePart == false)
                {
                    return(false);
                }

                var fi = new FileInfo(fsei.FullPath);

                if (fi.Length < 4)
                {
                    return(false);
                }

                try
                {
                    using (var fs = new FileStream(fsei.FullPath, FileMode.Open, FileAccess.Read))
                    {
                        using (var br = new BinaryReader(fs, new ASCIIEncoding()))
                        {
                            try
                            {
                                var chunk = br.ReadBytes(4);

                                var sig = BitConverter.ToInt32(chunk, 0);

                                if (sig == 0x66676572)
                                {
                                    return(true);
                                }
                            }
                            catch (Exception)
                            {
                            }

                            return(false);
                        }
                    }
                }
                catch (IOException)
                {
                    if (Helper.IsAdministrator() == false)
                    {
                        throw new UnauthorizedAccessException("Administrator privileges not found!");
                    }

                    var files = new List <string>();
                    files.Add(fsei.FullPath);

                    var rawf = Helper.GetRawFiles(files);

                    if (rawf.First().FileStream.Length == 0)
                    {
                        return(false);
                    }

                    try
                    {
                        var b = new byte[4];
                        rawf.First().FileStream.ReadExactly(b, 4);

                        var sig = BitConverter.ToInt32(b, 0);

                        if (sig == 0x66676572)
                        {
                            return(true);
                        }
                    }
                    catch (Exception)
                    {
                    }

                    return(false);
                }
            };

            directoryEnumerationFilters.RecursionFilter = entryInfo => !entryInfo.IsMountPoint && !entryInfo.IsSymbolicLink;

            directoryEnumerationFilters.ErrorFilter = (errorCode, errorMessage, pathProcessed) => true;

            var dirEnumOptions =
                DirectoryEnumerationOptions.Files | DirectoryEnumerationOptions.Recursive |
                DirectoryEnumerationOptions.SkipReparsePoints | DirectoryEnumerationOptions.ContinueOnException |
                DirectoryEnumerationOptions.BasicSearch;

            if (Directory.Exists(@out) == false)
            {
                _logger.Info($"Creating --out directory '{@out}'...");
                Directory.CreateDirectory(@out);
            }
            else
            {
                if (Directory.GetFiles(@out).Length > 0 && cn)
                {
                    _logger.Warn($"'{@out}' contains files! This may cause --cn to revert back to uncompressed names. Ideally, '{@out}' should be empty.");
                    Console.WriteLine();
                }
            }

            _logger.Fatal($"Searching '{d}' for hives...");

            var files2 =
                Alphaleonis.Win32.Filesystem.Directory.EnumerateFileSystemEntries(d, dirEnumOptions, directoryEnumerationFilters);

            var count = 0;

            try
            {
                hivesToProcess.AddRange(files2);
                count = hivesToProcess.Count;

                _logger.Info($"\tHives found: {count:N0}");
            }
            catch (Exception ex)
            {
                _logger.Fatal($"Could not access all files in '{d}'! Error: {ex.Message}");
                _logger.Error("");
                _logger.Fatal("Rerun the program with Administrator privileges to try again\r\n");
                //Environment.Exit(-1);
            }
        }
        else
        {
            var helpBld = new HelpBuilder(LocalizationResources.Instance, Console.WindowWidth);
            var hc      = new HelpContext(helpBld, _rootCommand, Console.Out);

            helpBld.Write(hc);
            return;
        }


        if (hivesToProcess.Count == 0)
        {
            _logger.Warn("No hives were found. Exiting...");

            return;
        }

        _sw = new Stopwatch();
        _sw.Start();

        foreach (var hiveToProcess in hivesToProcess)
        {
            _logger.Info("");

            byte[] updatedBytes = null;

            _logger.Info($"Processing hive '{hiveToProcess}'");

            if (File.Exists(hiveToProcess) == false)
            {
                _logger.Warn($"'{hiveToProcess}' does not exist. Skipping");
                continue;
            }

            try
            {
                RegistryHive reg;

                var dirname  = Path.GetDirectoryName(hiveToProcess);
                var hiveBase = Path.GetFileName(hiveToProcess);

                List <RawCopyReturn> rawFiles = null;

                try
                {
                    using (var fs = new FileStream(hiveToProcess, FileMode.Open, FileAccess.Read))
                    {
                        reg = new RegistryHive(fs.ReadFully(), hiveToProcess);
                    }
                }
                catch (IOException)
                {
                    //file is in use

                    if (Helper.IsAdministrator() == false)
                    {
                        throw new UnauthorizedAccessException("Administrator privileges not found!");
                    }

                    _logger.Warn($"\t'{hiveToProcess}' is in use. Rerouting...\r\n");

                    var files = new List <string>();
                    files.Add(hiveToProcess);

                    var logFiles = Directory.GetFiles(dirname, $"{hiveBase}.LOG?");

                    foreach (var logFile in logFiles)
                    {
                        files.Add(logFile);
                    }

                    rawFiles = Helper.GetRawFiles(files);

                    if (rawFiles.First().FileStream.Length == 0)
                    {
                        continue;
                    }

                    var bb = rawFiles.First().FileStream.ReadFully();

                    reg = new RegistryHive(bb, rawFiles.First().InputFilename);
                }

                if (reg.Header.PrimarySequenceNumber != reg.Header.SecondarySequenceNumber)
                {
                    if (string.IsNullOrEmpty(dirname))
                    {
                        dirname = ".";
                    }

                    var logFiles = Directory.GetFiles(dirname, $"{hiveBase}.LOG?");

                    if (logFiles.Length == 0)
                    {
                        if (ca)
                        {
                            _logger.Info($"\tHive '{hiveToProcess}' is dirty, but no logs were found in the same directory. --ca is true. Copying...");
                            updatedBytes = File.ReadAllBytes(hiveToProcess);
                        }
                        else
                        {
                            _logger.Info($"\tHive '{hiveToProcess}' is dirty and no transaction logs were found in the same directory. --ca is false. Skipping...");
                            continue;
                        }
                    }

                    if (updatedBytes == null)
                    {
                        if (rawFiles != null)
                        {
                            var lt = new List <TransactionLogFileInfo>();
                            foreach (var rawCopyReturn in rawFiles.Skip(1).ToList())
                            {
                                var bb1 = rawCopyReturn.FileStream.ReadFully();

                                var tt = new TransactionLogFileInfo(rawCopyReturn.InputFilename, bb1);
                                lt.Add(tt);
                            }

                            updatedBytes = reg.ProcessTransactionLogs(lt);
                        }
                        else
                        {
                            updatedBytes = reg.ProcessTransactionLogs(logFiles.ToList());
                        }
                    }
                }

                if (updatedBytes == null)
                {
                    if (ca)
                    {
                        _logger.Info($"\tHive '{hiveToProcess}' is not dirty, but --ca is true. Copying...");
                        updatedBytes = File.ReadAllBytes(hiveToProcess);
                    }
                    else
                    {
                        _logger.Info($"\tHive '{hiveToProcess}' is not dirty and --ca is false. Skipping...");
                        continue;
                    }
                }

                var outFile    = hiveToProcess.Replace(":", "").Replace("\\", "_");
                var outFileAll = Path.Combine(@out, outFile);

                if (cn &&
                    (outFileAll.ToUpperInvariant().Contains("NTUSER") || outFileAll.ToUpperInvariant().Contains("USRCLASS")))
                {
                    var dl   = hiveToProcess[0].ToString();
                    var segs = hiveToProcess.SplitAndTrim('\\');

                    var profile  = segs[2];
                    var filename = Path.GetFileName(hiveToProcess);

                    var outFile2 = $"{dl}_{profile}_{filename}";

                    outFileAll = Path.Combine(@out, outFile2);
                }

                if (File.Exists(outFileAll))
                {
                    var oldOut = outFileAll;

                    outFileAll = Path.Combine(@out, outFile);

                    _logger.Warn($"\tFile '{oldOut}' exists! Saving as non-compressed name: '{outFileAll}'");
                }

                _logger.Fatal($"\tSaving updated hive to '{outFileAll}'");

                using (var fs = new FileStream(outFileAll, FileMode.Create))
                {
                    fs.Write(updatedBytes, 0, updatedBytes.Length);

                    fs.Flush();

                    fs.Close();
                }
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("Sequence numbers do not match and transaction") == false)
                {
                    if (ex.Message.Contains("Administrator privileges not found"))
                    {
                        _logger.Fatal($"Could not access '{hiveToProcess}' because it is in use");
                        _logger.Error("");
                        _logger.Fatal("Rerun the program with Administrator privileges to try again\r\n");
                    }
                    else
                    {
                        _logger.Error($"There was an error: {ex.Message}");
                    }
                }
            }
        }

        _sw.Stop();
        _logger.Info("");

        _logger.Info($"Total processing time: {_sw.Elapsed.TotalSeconds:N3} seconds");
        _logger.Info("");
    }
Exemple #26
0
        public static HashSet <string> GetFiles(
            ResultCache cache,
            IEnumerable <string> searchablePaths,
            IEnumerable <IPattern> includePaths,
            IEnumerable <IPattern> excludePaths,
            string basePath = null)
        {
            searchablePaths = searchablePaths as string[] ?? searchablePaths.ToArray();
            includePaths    = includePaths as IPattern[] ?? includePaths.ToArray();

            if (excludePaths != null)
            {
                excludePaths = excludePaths as IPattern[] ?? excludePaths.ToArray();
            }
            else
            {
                excludePaths = new List <IPattern>();
            }

            basePath = basePath ?? "./";
            bool   returnAbsolutePaths = Path.IsPathRooted(basePath);
            string absBasePath;

            if (basePath == "./" || basePath == ".")
            {
                absBasePath = new DirectoryInfo(Directory.GetCurrentDirectory()).FullName;
            }
            else
            {
                absBasePath = new DirectoryInfo(basePath).FullName;
            }

            (int hash, bool hasResults, HashSet <string> files)cacheRequest =
                cache?.GetResultsOrReserve(
                    searchablePaths,
                    includePaths,
                    excludePaths,
                    basePath)
                ?? (0, false, null);

            if (cacheRequest.hasResults)
            {
                Log.Debug("Getting files for query hash {{{0}}} from cached results for base path '{1}':",
                          cacheRequest.hash, basePath);

                Log.IndentedCollection(cacheRequest.files, Log.Debug);
                return(cacheRequest.files);
            }

            Log.Debug("Getting files for query hash {{{0}}} using base path '{1}' and provided include/exclude paths:",
                      cacheRequest.hash, basePath);

            using (new CompositeDisposable(
                       new Log.ScopedIndent(),
                       new Log.ScopedTimer(Log.Level.Debug, "GetFiles(...)", $"{{{cacheRequest.hash,-11}}} {basePath}")))
            {
                Log.Debug("search paths:");
                Log.IndentedCollection(searchablePaths, Log.Debug);

                HashSet <string>       includeFiles;
                HashSet <GLOB>         includeGlobs;
                HashSet <RegexPattern> includeRegexes;
                HashSet <string>       excludeFiles;
                HashSet <GLOB>         excludeGlobs;
                HashSet <RegexPattern> excludeRegexes;

                (includeFiles, includeGlobs, includeRegexes) = ProcessFileValues(includePaths);
                (excludeFiles, excludeGlobs, excludeRegexes) = ProcessFileValues(excludePaths);
                var searchPathMatches = new Dictionary <string, List <PatternMatch> >();

                foreach (string currentSearchPath in searchablePaths)
                {
                    var currentMatches = new List <PatternMatch>();

                    var dir = new DirectoryInfo(new DirectoryInfo(
                                                    currentSearchPath == "./" || currentSearchPath == "."
                            ? Directory.GetCurrentDirectory()
                            : currentSearchPath)
                                                .FullName);

                    bool makeCandidatesAbsolute = Path.IsPathRooted(currentSearchPath);

                    if (!dir.Exists)
                    {
                        Log.Debug("Skipping searchable directory because it does not exist: {0}'", currentSearchPath);
                        continue;
                    }

                    string[] candidates = dir.GetFilesSafeRecursive("*")
                                          .Select(f => GetPath(makeCandidatesAbsolute, f.FullName, absBasePath))
                                          .Reverse()
                                          .ToArray();

                    DirectoryInfo[] allDirs = dir.GetDirectoriesSafeRecursive("*")
                                              .Reverse()
                                              .Concat(new[] { dir })
                                              .ToArray();

                    #region includes
                    if (includeGlobs != null && includeGlobs.Count > 0)
                    {
                        foreach (GLOB glob in includeGlobs)
                        {
                            IEnumerable <string> matchesForGlob = candidates.Where(f => glob.IsMatch(f));

                            currentMatches.AddRange(matchesForGlob.Select(
                                                        f => new PatternMatch(f, currentSearchPath, "glob \"" + glob.Pattern + "\"")));
                        }
                    }

                    if (includeRegexes != null && includeRegexes.Count > 0)
                    {
                        IEnumerable <PatternMatch> matchesForRegex = includeRegexes.SelectMany(
                            r => r.FilterMatches(candidates).Select(
                                f => new PatternMatch(f,
                                                      currentSearchPath,
                                                      r.ToString())));

                        currentMatches.AddRange(matchesForRegex);
                    }

                    var literalPatternMatches = new Dictionary <string, PatternMatch[]>();
                    if (includeFiles != null && includeFiles.Count > 0)
                    {
                        foreach (string filePattern in includeFiles.ToArray())
                        {
                            string[] matchesForFile =
                                (from dirInfo in allDirs
                                 select Path.Combine(dirInfo.FullName, filePattern)
                                 into includeFilePath
                                 where File.Exists(includeFilePath)
                                 select GetPath(makeCandidatesAbsolute, includeFilePath, absBasePath))
                                .ToArray();

                            PatternMatch[] patternMatchesForFile = matchesForFile.Select(
                                f => new PatternMatch(f, currentSearchPath, filePattern))
                                                                   .ToArray();

                            if (patternMatchesForFile.Length > 0)
                            {
                                literalPatternMatches[filePattern] = patternMatchesForFile;
                                currentMatches.AddRange(patternMatchesForFile);
                            }
                        }
                    }
                    #endregion

                    #region excludes
                    IEnumerable <PatternMatch> tempMatches = currentMatches;
                    if (excludeGlobs != null && excludeGlobs.Count > 0)
                    {
                        var excludeGlob = new CompositeGlob(excludeGlobs, null);
                        tempMatches = tempMatches.Where(m => !excludeGlob.IsMatch(m.File))
                                      .ToList(); // Helps with debugging
                    }

                    if (excludeRegexes != null && excludeRegexes.Count > 0)
                    {
                        tempMatches = tempMatches.Where(m => excludeRegexes.All(r => !r.Regex.IsMatch(m.File)))
                                      .ToList(); // Helps with debugging
                    }

                    if (excludeFiles != null && excludeFiles.Count > 0)
                    {
                        tempMatches = tempMatches.Where(m => excludeFiles.All(x => x != Path.GetFileName(m.File)))
                                      .ToList(); // Helps with debugging
                    }
                    #endregion

                    #region literal validation
                    currentMatches = tempMatches.ToList();
                    foreach (KeyValuePair <string, PatternMatch[]> kvp in literalPatternMatches)
                    {
                        PatternMatch[] patternMatchesForFile = kvp.Value;
                        if (patternMatchesForFile.Length > 1 &&
                            currentMatches.Intersect(patternMatchesForFile).Count() > 1)
                        {
                            Log.Warn("The literal pattern '{0}' matched more than one file.",
                                     kvp.Key);
                            Log.Warn("Only the first match '{0}' will be returned. See all matches below.",
                                     patternMatchesForFile.First().File);

                            int count = 0;
                            Log.IndentedCollection(patternMatchesForFile,
                                                   p => $"{p.File} (from {p.SearchPath}) {(count++ == 0 ? "*" : "")}",
                                                   Log.Warn);

                            currentMatches = currentMatches.Except(patternMatchesForFile.Skip(1)).ToList();
                        }
                    }

                    searchPathMatches[currentSearchPath] = currentMatches;
                    #endregion
                }

                #region validation
                IEnumerable <PatternMatch> allMatches   = searchPathMatches.Values.SelectMany(v => v);
                IEnumerable <PatternMatch> finalMatches = ValidateMatches(allMatches, includePaths);
                #endregion

                #region results
                HashSet <string> allMatchedFiles =
                    finalMatches.Select(m => GetPath(returnAbsolutePaths, m.File, absBasePath)).ToHashSet();

                Log.Debug("include globs:");
                Log.IndentedCollection(includeGlobs, s => s.Pattern, Log.Debug);
                Log.Debug("include regexes:");
                Log.IndentedCollection(includeRegexes, r => r.Value, Log.Debug);
                Log.Debug("include literals:");
                Log.IndentedCollection(includeFiles, Log.Debug);
                Log.Debug("exclude globs:");
                Log.IndentedCollection(excludeGlobs, s => s.Pattern, Log.Debug);
                Log.Debug("exclude regexes:");
                Log.IndentedCollection(excludeRegexes, r => r.Value, Log.Debug);
                Log.Debug("exclude literals:");
                Log.IndentedCollection(excludeFiles, Log.Debug);
                Log.Debug("matched files:");
                Log.IndentedCollection(allMatchedFiles, Log.Debug);

                cache?.CacheResults(allMatchedFiles, cacheRequest.hash);
                return(allMatchedFiles);

                #endregion
            }
        }
        public void Load(string imageFileName)
        {
            var fi          = new FileInfo(imageFileName);
            var boxFileName = Path.Combine(fi.DirectoryName, Path.GetFileNameWithoutExtension(fi.Name) + ".box");

            if (!File.Exists(boxFileName))
            {
                throw new ApplicationException(string.Format("Box file '{0}' was not found", Path.GetFileName(boxFileName)));
            }

            Close();

            _fileStream = new FileStream(imageFileName, FileMode.Open, FileAccess.Read);
            if (TiffHelper.IsTiffFile(_fileStream))
            {
                _tiffDecoder = new TiffBitmapDecoder(_fileStream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                MaxPageIndex = _tiffDecoder.Frames.Count - 1;
            }
            else
            {
                MaxPageIndex = 0;
            }


            int recordIndex = 0;

            using (var reader = new StreamReader(boxFileName, Encoding.UTF8))
            {
                ObservableCollection <TessBoxControl> boxes = null;
                while (true)
                {
                    var line = reader.ReadLine();
                    if (line == null)
                    {
                        break;
                    }
                    var fields = line.Split(' ');
                    if (fields.Length != 6)
                    {
                        throw new ApplicationException(string.Format("Invalid box file record at line {0}", recordIndex));
                    }

                    var boxValue  = fields[0];
                    var pageIndex = int.Parse(fields[5]);
                    var img       = GetPageImage(pageIndex);

                    //Box file coordinates are with an origin at the bottom left on the image
                    var left   = int.Parse(fields[1]);
                    var bottom = img.PixelHeight - int.Parse(fields[2]);
                    var right  = int.Parse(fields[3]);
                    var top    = img.PixelHeight - int.Parse(fields[4]);

                    var width  = right - left;
                    var height = bottom - top;

                    var box = new TessBoxControl();
                    box.Value  = boxValue;
                    box.Width  = width;
                    box.Height = height;
                    Canvas.SetLeft(box, left);
                    Canvas.SetTop(box, top);

                    if (!_pageBoxMap.TryGetValue(pageIndex, out boxes))
                    {
                        boxes = new ObservableCollection <TessBoxControl>();
                        _pageBoxMap[pageIndex] = boxes;
                    }

                    boxes.Add(box);
                    recordIndex++;
                }
            }

            _imageFileName = imageFileName;
            _boxFileName   = boxFileName;
            NotifyPropertyChanged("WindowTitle");

            //set manually to force SelPageIndex to accept the change
            _selPageIndex = -1;
            SelPageIndex  = 0;
        }
Exemple #28
0
 /// <summary>
 /// Returns the file name of a file path.
 /// </summary>
 /// <param name="path">Path to get the file name of.</param>
 /// <param name="withExtension">Determines whether or not the extension is included in the result, defaults to true.</param>
 public static string FileName(string path, bool withExtension = true)
 {
     return(withExtension ? Path.GetFileName(path) : Path.GetFileNameWithoutExtension(path));
 }
        private async Task LoadFile(string fileName)
        {
            string fileExt = IoPath.GetExtension(fileName);

            if (string.IsNullOrWhiteSpace(fileExt))
            {
                return;
            }

            bool generateXaml = _optionSettings.ShowOutputFile;

            if (string.Equals(fileExt, SvgConverter.SvgExt, StringComparison.OrdinalIgnoreCase) ||
                string.Equals(fileExt, SvgConverter.CompressedSvgExt, StringComparison.OrdinalIgnoreCase))
            {
                _svgFilePath = fileName;

                if (_svgPage != null && _optionSettings.ShowInputFile)
                {
                    _svgPage.LoadDocument(fileName);
                }

                if (_drawingPage == null)
                {
                    return;
                }
                _drawingPage.SaveXaml = generateXaml;

                try
                {
                    if (await _drawingPage.LoadDocumentAsync(fileName))
                    {
                        this.Title = AppTitle + " - " + IoPath.GetFileName(fileName);

                        if (_xamlPage != null && !string.IsNullOrWhiteSpace(_drawingDir))
                        {
                            string xamlFilePath = IoPath.Combine(_drawingDir,
                                                                 IoPath.GetFileNameWithoutExtension(fileName) + SvgConverter.XamlExt);

                            _xamlFilePath  = xamlFilePath;
                            _canDeleteXaml = true;

                            if (File.Exists(xamlFilePath) && _optionSettings.ShowOutputFile)
                            {
                                _xamlPage.LoadDocument(xamlFilePath);
                            }
                        }

                        _fileWatcher.Path = IoPath.GetDirectoryName(fileName);
                        // Only watch current file
                        _fileWatcher.Filter = IoPath.GetFileName(fileName);
                        // Begin watching.
                        _fileWatcher.EnableRaisingEvents = true;
                    }
                }
                catch
                {
                    // Try loading the XAML, if generated but the rendering failed...
                    if (_xamlPage != null && !string.IsNullOrWhiteSpace(_drawingDir))
                    {
                        string xamlFilePath = IoPath.Combine(_drawingDir,
                                                             IoPath.GetFileNameWithoutExtension(fileName) + SvgConverter.XamlExt);

                        _xamlFilePath  = xamlFilePath;
                        _canDeleteXaml = true;

                        if (File.Exists(xamlFilePath) && _optionSettings.ShowOutputFile)
                        {
                            _xamlPage.LoadDocument(xamlFilePath);
                        }
                    }
                    throw;
                }
            }
        }
        private void FillTreeView(string sourceDir, string[] svgFiles, TreeViewItem treeItem)
        {
            if (svgFiles != null && svgFiles.Length != 0)
            {
                for (int i = 0; i < svgFiles.Length; i++)
                {
                    string svgFile = svgFiles[i];

                    TextBlock itemText = new TextBlock();
                    itemText.Text   = string.Format("({0:D3}) - {1}", i, IoPath.GetFileName(svgFile));
                    itemText.Margin = new Thickness(3, 0, 0, 0);

                    BulletDecorator fileItem = new BulletDecorator();
                    if (_fileThumbnail != null)
                    {
                        Image image = new Image();
                        image.Source = _fileThumbnail;
                        image.Height = 16;
                        image.Width  = 16;

                        fileItem.Bullet = image;
                    }
                    else
                    {
                        Ellipse bullet = new Ellipse();
                        bullet.Height          = 16;
                        bullet.Width           = 16;
                        bullet.Fill            = Brushes.Goldenrod;
                        bullet.Stroke          = Brushes.DarkGray;
                        bullet.StrokeThickness = 1;

                        fileItem.Bullet = bullet;
                    }
                    fileItem.Margin = new Thickness(0, 0, 10, 0);
                    fileItem.Child  = itemText;

                    TreeViewItem item = new TreeViewItem();
                    item.Tag        = svgFile;
                    item.Header     = fileItem;
                    item.Margin     = new Thickness(0);
                    item.Padding    = new Thickness(2);
                    item.FontSize   = 12;
                    item.FontWeight = FontWeights.Normal;

                    treeItem.Items.Add(item);
                }
            }

            if (string.IsNullOrWhiteSpace(sourceDir) || !Directory.Exists(sourceDir))
            {
                return;
            }

            if (_optionSettings.RecursiveSearch == false)
            {
                return;
            }

            string[] directories = Directory.GetDirectories(sourceDir);
            if (directories != null && directories.Length != 0)
            {
                for (int i = 0; i < directories.Length; i++)
                {
                    string directory = directories[i];
                    svgFiles = Directory.GetFiles(directory, SvgFilePattern, SearchOption.TopDirectoryOnly);
                    {
                        DirectoryInfo directoryInfo = new DirectoryInfo(directory);

                        TextBlock headerText = new TextBlock();
                        headerText.Text   = directoryInfo.Name;
                        headerText.Margin = new Thickness(3, 0, 0, 0);

                        BulletDecorator decorator = new BulletDecorator();
                        if (_folderClose != null)
                        {
                            Image image = new Image();
                            image.Source = _folderClose;

                            decorator.Bullet = image;
                        }
                        else
                        {
                            Ellipse bullet = new Ellipse();
                            bullet.Height          = 16;
                            bullet.Width           = 16;
                            bullet.Fill            = Brushes.Goldenrod;
                            bullet.Stroke          = Brushes.DarkGray;
                            bullet.StrokeThickness = 1;

                            decorator.Bullet = bullet;
                        }
                        decorator.Margin = new Thickness(0, 0, 10, 0);
                        decorator.Child  = headerText;

                        TreeViewItem categoryItem = new TreeViewItem();
                        categoryItem.Tag        = string.Empty;
                        categoryItem.Header     = decorator;
                        categoryItem.Margin     = new Thickness(0);
                        categoryItem.Padding    = new Thickness(3);
                        categoryItem.FontSize   = 14;
                        categoryItem.FontWeight = FontWeights.Bold;

                        treeItem.Items.Add(categoryItem);

                        FillTreeView(directory, svgFiles, categoryItem);

                        if (!categoryItem.HasItems)
                        {
                            treeItem.Items.Remove(categoryItem);
                        }
                    }
                }
            }
        }
Exemple #31
0
        /// <summary>
        /// Get the path of reference assembly where the type is declared.
        /// </summary>
        private static string GetReferenceAssemblyPathBasedOnType(Type type)
        {
            string refAsmFileName = PathType.GetFileName(ClrFacade.GetAssemblies(type.FullName).First().Location);

            return(PathType.Combine(s_netcoreAppRefFolder, refAsmFileName));
        }