예제 #1
0
        public static string ProposeFileName(this Reference source, FileNameTrimType fileNameTrimType = FileNameTrimType.None)
        {
            if (source == null)
            {
                return(null);
            }

            var renameSettings = source.Project.Engine.Settings.Engine.Settings.Rename;

            // TODO DL: für 5.2 abändern http://tfs2012:8080/tfs/CITAVICollection/Citavi/_workitems/edit/17175
            //var values = renameSettings.NameDefineIds .Select(id => GetValue(source, id)).ToList();
            var values = new List <ReferencePropertyId> {
                ReferencePropertyId.ShortTitle
            }.Select(id => source.GetReferencePropertybyId(id)).ToList();

            values.RemoveAll(v => string.IsNullOrWhiteSpace(v));

            var result = string.Join(renameSettings.Separator.ToStringSeparator(), values);

            if (string.IsNullOrEmpty(result))
            {
                return(null);
            }

            result = Path2.GetValidFileName(result.Clean());

            if (fileNameTrimType != FileNameTrimType.None)
            {
                result = result.Trim(fileNameTrimType, renameSettings.MaxNameLength);
            }

            return(result);
        }
        // Eventhandlers

        void BtnFolderBrowserDialog_Click(object sender, EventArgs e)
        {
            using (var folderBrowseDialog = new FolderBrowserDialog {
                Description = Properties.Resources.FolderBrowseDialogDescription
            })
            {
                var root = Path2.GetFullPathFromPathWithVariables(txtPath.Text);
                if (System.IO.Directory.Exists(root))
                {
                    folderBrowseDialog.SelectedPath = root;
                }

                if (folderBrowseDialog.ShowDialog(this) != DialogResult.OK)
                {
                    return;
                }

                var entry = GetPathWithVariablesFromFullPath(folderBrowseDialog.SelectedPath);

                if (!string.IsNullOrEmpty(entry) && !folderBrowseDialog.SelectedPath.Equals(entry, StringComparison.OrdinalIgnoreCase) && MessageBox.Show(this, Properties.Resources.PathAsVariableMessage.FormatString(folderBrowseDialog.SelectedPath, entry), Owner.ProductName, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    txtPath.Text = entry;
                    lblEnvironmentFullPath.Text = Path2.GetFullPathFromPathWithVariables(entry);
                }
                else
                {
                    txtPath.Text = folderBrowseDialog.SelectedPath;
                    lblEnvironmentFullPath.Text = folderBrowseDialog.SelectedPath;
                }
            }
        }
        void RunTravers(MacroContainer container, bool supressMessage = false)
        {
            if (IsValidDirectory(out string message))
            {
                var menu = GetMacroMenu(container.Form);

                if (menu != null)
                {
                    var button = menu.InsertCommandbarButton(1, Key_Button_OpenInExplorer, MacroManagerResources.OpenInExplorerCommand);
                    container.Tools.Add(button.Tool, "OpenInExplorerCommand");
                }

                var macrosDirectory = Path2.GetFullPathFromPathWithVariables(Settings[Key_MacrosDirectory]);


                int folderCounter = 1;
                int fileCounter   = 1;

                if (Directory.Exists(macrosDirectory))
                {
                    DirectoryConverter.Travers(menu, 3, ref folderCounter, ref fileCounter, macrosDirectory, container, true);
                }
            }
            else
            {
                if (!supressMessage)
                {
                    MessageBox.Show(container.Form, message, container.Form.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
        static async Task <List <FetchResult> > FetchReferencesByFileAsync(MainForm mainForm, string directory, IProgress <PercentageAndTextProgressInfo> progress, CancellationToken cancellationToken)
        {
            var results = new List <FetchResult>();

            var pathes = Path2.GetFilesSafe(new DirectoryInfo(directory), "*.pdf", SearchOption.AllDirectories).Select(fileInfo => fileInfo.FullName).ToList();

            var fileImportSupport = new FileImportSupport();

            for (var i = 0; i < pathes.Count; i++)
            {
                cancellationToken.ThrowIfCancellationRequested();

                var path = pathes[i];

                var referencesFromFile = await fileImportSupport.ImportFilesAsync(mainForm.Project, mainForm.Project.Engine.TransformerManager, new List <string>() { path }, AttachmentAction.Copy);

                if ((bool)referencesFromFile?.Any())
                {
                    results.Add(new FetchResult {
                        Path = path, References = referencesFromFile
                    });
                }

                progress.Report(new PercentageAndTextProgressInfo {
                    Percentage = Convert.ToInt32(100 / pathes.Count * i)
                });
            }

            return(results);
        }
        // Methods

        void InitializeDirectory(string directory)
        {
            if (!string.IsNullOrEmpty(directory))
            {
                txtPath.Text = directory;
                lblEnvironmentFullPath.Text = Path2.GetFullPathFromPathWithVariables(directory);
            }
        }
 void ToolStripItem_ItemClick(object sender, EventArgs e)
 {
     if (sender is ToolStripItem item)
     {
         txtPath.Text = item.Text;
         lblEnvironmentFullPath.Text = Path2.GetFullPathFromPathWithVariables(item.Text);
     }
 }
예제 #7
0
        public void Perform(MVVMNode node)
        {
            if (!EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo())
            {
                return;
            }
            if (!EditorUtility.DisplayDialog("Warning!", "Before scaffolding the core, make sure you saved and compiled!",
                                             "Yes, I saved and compiled!",
                                             "Cancel"))
            {
                return;
            }

            var paths      = InvertApplication.Container.Resolve <DatabaseService>().CurrentConfiguration.CodeOutputPath + "/";
            var scenesPath = System.IO.Path.Combine(paths, "Scenes");

            var sceneName         = node.Graph.Namespace + "KernelScene.unity";
            var sceneNameWithPath = System.IO.Path.Combine(scenesPath, sceneName);

            var          prefabName         = node.Graph.Namespace + "Kernel.prefab";
            var          prefabNameWithPath = Path2.Combine(paths, prefabName);
            var          relativeScenesPath = System.IO.Path.Combine(paths, "Scenes");
            var          relativeScenePath  = System.IO.Path.Combine(relativeScenesPath + "/", sceneName);
            uFrameKernel uFrameMVVMKernel   = null;

            if (File.Exists(sceneNameWithPath))
            {
                var gameObject = (GameObject)AssetDatabase.LoadAssetAtPath(prefabNameWithPath, typeof(GameObject));
                uFrameMVVMKernel = gameObject.GetComponent <uFrameKernel>();
                SyncKernel(node, uFrameMVVMKernel.gameObject);
            }
            else
            {
                var eScene = EditorSceneManager.NewScene(NewSceneSetup.EmptyScene);
                if (!Directory.Exists(scenesPath))
                {
                    Directory.CreateDirectory(scenesPath);
                }
                uFrameMVVMKernel = FindComponentInScene <uFrameKernel>() ?? new GameObject("Kernel").AddComponent <uFrameKernel>();
                var services = SyncKernel(node, uFrameMVVMKernel.gameObject);

                services.gameObject.AddComponent <ViewService>();
                services.gameObject.AddComponent <SceneManagementService>();

                PrefabUtility.CreatePrefab(prefabNameWithPath, uFrameMVVMKernel.gameObject, ReplacePrefabOptions.ConnectToPrefab);
                EditorSceneManager.SaveScene(eScene, relativeScenePath);
            }

            if (!UnityEditor.EditorBuildSettings.scenes.Any(s => s.path.EndsWith(node.Graph.SystemPath + "KernelScene.unity")))
            {
                var list = EditorBuildSettings.scenes.ToList();
                list.Add(new EditorBuildSettingsScene(relativeScenePath, true));
                EditorBuildSettings.scenes = list.ToArray();
            }
            AssetDatabase.Refresh();
        }
예제 #8
0
    public void OnGUI()
    {
        if (!_capturing)
        {
            if (GUILayout.Button("Generate Documentation"))
            {
                var repository = InvertGraphEditor.DesignerWindow.DiagramViewModel.CurrentRepository;
                _screenshots = repository.AllOf <GraphNode>().ToList();
                _capturing   = true;
                NextScreenshot();
            }
            return;
        }

        if (drawer == null)
        {
            return;
        }
        foreach (var item in drawer.Children)
        {
            //if (!(item is DiagramNodeDrawer)) continue;
            //if (item is ScreenshotNodeDrawer) continue;
            item.Draw(InvertGraphEditor.PlatformDrawer, 1f);
        }


        if (Event.current.type == EventType.Repaint)
        {
            Texture2D texture2D = new Texture2D(Mathf.RoundToInt(this.position.width), Mathf.RoundToInt(this.position.height), (TextureFormat)3, false);

            texture2D.ReadPixels(new Rect(0f, 0f, this.position.width, this.position.height), 0, 0);
            texture2D.Apply();
            byte[] bytes = texture2D.EncodeToPNG();
            Object.DestroyImmediate((Object)texture2D, true);
            var directory = Path.Combine("Documentation", "Screenshots");
            if (!Directory.Exists(directory))
            {
                Directory.CreateDirectory(directory);
            }
            File.WriteAllBytes(Path2.Combine("Documentation", "Screenshots", _screenshots[_currentScreenshotIndex - 1].Name + ".png"), bytes);
            Debug.Log("Saved image " + _screenshots[_currentScreenshotIndex - 1].Name + ".png");
            NextScreenshot();
        }

        //this.Close();
    }
예제 #9
0
 internal static void CheckInvalidPathChars(string path, bool checkAdditional = false)
 {
     if (path != null)
     {
         if (!Path2.HasIllegalCharacters(path, checkAdditional))
         {
             return;
         }
         else
         {
             throw new ArgumentException("The path has invalid characters.", "path");
         }
     }
     else
     {
         throw new ArgumentNullException("path");
     }
 }
        bool ExistDirectory(string directory)
        {
            if (string.IsNullOrEmpty(directory))
            {
                MessageBox.Show(this, Properties.Resources.FolderBrowseDialogDescription, Owner.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return(false);
            }

            var path = Path2.GetFullPathFromPathWithVariables(directory);

            if (System.IO.Directory.Exists(path))
            {
                return(true);
            }

            MessageBox.Show(this, Properties.Resources.DirectoryNotResolveMessage.FormatString(path), Owner.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            return(false);
        }
        bool IsValidDirectory(out string message)
        {
            message = null;

            if (!Settings.ContainsKey(Key_MacrosDirectory))
            {
                message = MacroManagerResources.ConfigurateAddonMessage;
                return(false);
            }

            if (!Directory.Exists(Path2.GetFullPathFromPathWithVariables(Settings[Key_MacrosDirectory])))
            {
                message = MacroManagerResources.DirectoryNotFoundMessage;
                return(false);
            }

            return(true);
        }
예제 #12
0
        public static void Run(MainForm mainForm)
        {
            var counter = 0;

            string sourcePath;

            using (var folderDialog = new FolderBrowserDialog {
                Description = ImportPdfsAndCategorySystemResource.FolderBrowserDialogDescription
            })
            {
                if (folderDialog.ShowDialog() != DialogResult.OK)
                {
                    return;
                }

                sourcePath = folderDialog.SelectedPath;
            }

            var action        = AttachmentAction.Copy;
            var directoryInfo = new DirectoryInfo(sourcePath);
            var fileInfos     = Path2.GetFilesSafe(directoryInfo, "*.pdf", SearchOption.AllDirectories).ToList();
            var newReferences = new List <Reference>();

            foreach (var filePath in fileInfos.Select(info => info.FullName).ToList())
            {
                var referencesFromFile = new FileImportSupport().ImportFiles(mainForm.Project, mainForm.Project.Engine.TransformerManager, new List <string>()
                {
                    filePath
                }, action);

                if (referencesFromFile != null && referencesFromFile.Any())
                {
                    var referencesFromFileAdded = mainForm.Project.References.AddRange(referencesFromFile);

                    var fileName = Path.GetFileName(filePath);
                    AddCategories(referencesFromFileAdded, filePath.Substring(sourcePath.Length, filePath.Length - sourcePath.Length - fileName.Length));
                    counter++;
                }
            }

            MessageBox.Show(mainForm, ImportPdfsAndCategorySystemResource.MacroResultMessage.FormatString(counter), mainForm.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
예제 #13
0
        public static string GetFileName(string path)
        {
            char chr;

            if (path != null)
            {
                Path2.CheckInvalidPathChars(path, false);
                int length = path.Length;
                int num    = length;
                do
                {
                    int num1 = num - 1;
                    num = num1;
                    if (num1 < 0)
                    {
                        return(path);
                    }
                    chr = path[num];
                }while (chr != Path2.DirectorySeparatorChar && chr != Path2.AltDirectorySeparatorChar && chr != Path2.VolumeSeparatorChar);
                return(path.Substring(num + 1, length - num - 1));
            }
            return(path);
        }
예제 #14
0
파일: CsScript.cs 프로젝트: tapika/syncProj
    /// <summary>
    /// Compiles .cs script into dll/pdb, loads as assembly, and executes Main function.
    /// Temporary dll/pdb gets deleted. If .cs throws exception - it will be converted to
    /// error information, including .cs filename and source code line information.
    /// </summary>
    /// <param name="_path">Path to script which to execute</param>
    /// <param name="bAllowThrow">true if allow to throw exceptions</param>
    /// <param name="errors">Errors if any</param>
    /// <param name="args">Main argument parameters</param>
    /// <param name="bCompileOnly">true if only to compile</param>
    /// <returns>true if execution was successful.</returns>
    static public bool RunScript(String _path, bool bCompileOnly, bool bAllowThrow, out String errors, params String[] args)
    {
        errors = "";

        // ----------------------------------------------------------------
        //  Load script
        // ----------------------------------------------------------------
        String path = Path.GetFullPath(_path);

        if (!File.Exists(path))
        {
            errors = "Error: Could not load file '" + Exception2.getPath(path) + "': File does not exists.";
            if (bAllowThrow)
            {
                throw new Exception2(errors, 1);
            }
            return(false);
        }

        // Create syncProj cache folder next to syncProj.exe executable.
        String cacheDir = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "syncProjCache");

        if (!Directory.Exists(cacheDir))
        {
            DirectoryInfo di = Directory.CreateDirectory(cacheDir);
            di.Attributes = FileAttributes.Directory | FileAttributes.Hidden;
        }

        String   dllBaseName = Path.GetFileNameWithoutExtension(_path);
        String   tempDll;
        String   dllInfoFile     = "";
        DateTime dllInfoRealDate = DateTime.MinValue;

        for (int i = 1; ; i++)
        {
            tempDll = Path.Combine(cacheDir, dllBaseName);
            if (i != 1)
            {
                tempDll += i;
            }

            dllInfoFile = tempDll + "_script.txt";       // We keep here C# script full path just not to get collisions.
            if (!File.Exists(dllInfoFile))
            {
                File.WriteAllText(dllInfoFile, path);
                break;
            }

            String pathFromFile = "";
            //
            // Another instance of syncProj might be accessing same file at the same time, we try to retry automatically after some delay.
            //
            for (int iTry = 0; iTry < 20; iTry++)
            {
                try
                {
                    pathFromFile = File.ReadAllText(dllInfoFile);
                    break;
                }
                catch (Exception)
                {
                    Thread.Sleep(10 + iTry * 5);   // 5*20+10, overall (5*20+10)*20 / 2 = 1.1 sec
                }
            }

            if (pathFromFile == path)
            {
                dllInfoRealDate = File.GetLastWriteTime(dllInfoFile);
                break;
            }
        }

        String pdb = tempDll + ".pdb";

        tempDll += ".dll";

        List <String> filesToCompile = new List <string>();

        filesToCompile.Add(path);

        //---------------------------------------------------------------------------------------------------
        //  Get referenced .cs script file list, and from referenced files further other referenced files.
        //---------------------------------------------------------------------------------------------------
        CsScriptInfo csInfo = getCsFileInfo(filesToCompile[0], true);

        filesToCompile.AddRange(csInfo.csFiles);

        bool bCompileDll = false;

        //---------------------------------------------------------------------------------------------------
        // Compile .dll only if script.cs and it's dependent .cs are newer than compiled .dll.
        //---------------------------------------------------------------------------------------------------
        if (!File.Exists(tempDll))
        {
            bCompileDll = true;
        }

        DateTime dllInfoTargetDate = DateTime.MinValue;

        //---------------------------------------------------------------------------------------------------
        // Calculate target date anyway, so we can set it to file.
        // I have made such logic that scripts will be compiled if date / time of main script or any sub-script is changed.
        //---------------------------------------------------------------------------------------------------
        List <long> times = filesToCompile.Select(x => File.GetLastWriteTime(x).Ticks).ToList();

        //
        // If we are referencing any local .dll file, add it's time into calculation scheme.
        //
        foreach (String refDll in csInfo.refFiles)
        {
            if (File.Exists(refDll))
            {
                times.Add(File.GetLastAccessTime(refDll).Ticks);
            }
        }

        // If syncProj.exe also changed, requires recompiling all .dll's.
        // GetEntryAssembly() returns null during unit testing.
        String exeFile = System.Reflection.Assembly.GetExecutingAssembly().Location;

        times.Add(File.GetLastWriteTime(exeFile).Ticks);

        times.Sort();

        //---------------------------------------------------------------------------------------------------
        //  Basically we have multiple files, each with it's own modification date, we need to detect if any of files
        //  has changed  - either updated forth (svn update) or back (svn revert with set file dates to last commit time)
        //  We try to calculate date / time from multiple date times
        //---------------------------------------------------------------------------------------------------

        long time = times[0];                               // smallest date/time

        for (int i = 1; i < times.Count; i += 2)
        {
            if (i + 1 == times.Count)
            {
                time = (time + times[i]) / 2;               // medium between current date/time and highest
            }
            else
            {
                time += (times[i + 1] - times[i]) / 2;      // just take different between dates / times and get medium from there.
            }
        }

        dllInfoTargetDate = new DateTime(time);
        if (times.Count != 1)
        {
            dllInfoTargetDate.AddSeconds(-times.Count);     // Just some checksum on how many files we actually have.
        }
        if (!bCompileDll)
        {
            if (dllInfoRealDate != dllInfoTargetDate)
            {
                bCompileDll = true;
            }
        }

        if (csInfo.DebugEnabled())
        {
            if (!bCompileDll)
            {
                Console.WriteLine(Exception2.getPath(path) + " dll is up-to-date.");
            }
            else
            {
                Console.WriteLine(Exception2.getPath(path) + " dll will be compiled.");
            }
            //+ ": Date found: " + dllInfoRealDate.ToString("o") + " Date expected: " + dllInfoTargetDate.ToString("o")
        }

        if (bCompileDll)
        {
            // ----------------------------------------------------------------
            //  Compile it into ram
            // ----------------------------------------------------------------
            if (provider == null)
            {
                provider = new CSharpCodeProvider();
            }
#pragma warning disable 618
            if (compiler == null)
            {
                compiler = provider.CreateCompiler();
            }
#pragma warning restore 618
            CompilerParameters compilerparams = new CompilerParameters();
            compilerparams.GenerateExecutable = false;
#if NODEBUGTRACE
            // Currently it's not possible to generate in ram pdb debugging information.
            // Compiler option /debug:full should in theory allow that, but it does not work.
            compilerparams.GenerateInMemory = true;
#else
            compilerparams.GenerateInMemory        = false;
            compilerparams.IncludeDebugInformation = true;                // Needed to get line / column numbers
            compilerparams.OutputAssembly          = tempDll;
            compilerparams.CompilerOptions         = "/d:DEBUG /d:TRACE"; // /debug+ /debug:full /optimize-
#endif

            // Add assemblies from my domain - all which are not dynamic.
            if (refAssemblies == null)
            {
                var assemblies = AppDomain.CurrentDomain.GetAssemblies().Where(a => !a.IsDynamic).Select(a => a.Location).ToList();

                for (int i = 0; i < assemblies.Count; i++)
                {
                    if (assemblies[i].EndsWith(".exe") && !assemblies[i].EndsWith("\\syncproj.exe"))
                    {
                        assemblies.RemoveAt(i);
                        i--;
                    }
                }

                refAssemblies = assemblies.ToArray();
            }
            compilerparams.ReferencedAssemblies.AddRange(refAssemblies);
            foreach (var f in csInfo.refFiles)
            {
                compilerparams.ReferencedAssemblies.Add(f);
            }

            // ----------------------------------------------------------------
            //  If compile errors - report and exit.
            // ----------------------------------------------------------------
            CompilerResults results = compiler.CompileAssemblyFromFileBatch(compilerparams, filesToCompile.ToArray());
            if (results.Errors.HasErrors)
            {
                // Mimic visual studio error handling.
                StringBuilder sb = new StringBuilder();
                foreach (CompilerError error in results.Errors)
                {
                    // Missing reference file will not give any file or line information, we just use compilation
                    // script filename, and first line position. (Not exactly right, but something at least).

                    if (error.FileName == "")
                    {
                        sb.Append(Exception2.getPath(filesToCompile[0]));
                    }
                    else
                    {
                        sb.Append(Exception2.getPath(error.FileName));
                    }

                    if (error.Line == 0)
                    {
                        // error CS0006: Metadata file 'MystiqueDll.dll' could not be found
                        sb.Append("(1,1)");
                    }
                    else
                    {
                        sb.Append("(" + error.Line + "," + error.Column + ")");
                    }

                    sb.AppendFormat(": error {0}: {1}\r\n", error.ErrorNumber, error.ErrorText);
                }
                errors = sb.ToString();
                if (bAllowThrow)
                {
                    throw new Exception2(errors);
                }

                return(false);
            }
        } //if

        try
        {
            File.SetLastWriteTime(dllInfoFile, dllInfoTargetDate);
        }
        catch (Exception)
        {
            // Visual studio can launch multiple instances of syncProj, and then each will try to compile it's own copy.
            // Add here just some guard, let's check if this needs to be improved later on.
        }

        if (bCompileOnly)
        {
            return(true);
        }

        //------------------------------------------------------------------------------------------------------
        //
        // Let's check that script contains correct css_ref (Might be copied from another project).
        // We allow here also multiple copies of syncProj, as long as path to syncProj.exe is valid in .cs header
        // (Can be edited by C# script)
        //
        //------------------------------------------------------------------------------------------------------
        Regex  reCssRef          = new Regex("^ *//css_ref  *(.*syncproj\\.exe);?([\r\n]+|$)", RegexOptions.Multiline | RegexOptions.IgnoreCase);
        bool   bUpdateScriptPath = false;
        String targetCsPath      = "";

        using (StreamReader reader = new StreamReader(path))
        {
            for (int i = 0; i < 10; i++)
            {
                String line = reader.ReadLine() ?? "";
                var    re   = reCssRef.Match(line);
                if (re.Success)
                {
                    // Current path, referred from C# script
                    String currentCsPath = re.Groups[1].Value;
                    String dir           = Path.GetDirectoryName(path);
                    String exePath       = SolutionOrProject.getSyncProjExeLocation(dir, currentCsPath);
                    targetCsPath = Path2.makeRelative(exePath, dir);
                    String referredExe = currentCsPath;

                    if (!Path.IsPathRooted(referredExe))        // Uses relative path, let's make it absolute.
                    {
                        referredExe = Path.Combine(dir, currentCsPath);
                    }

                    if (currentCsPath != targetCsPath && !File.Exists(referredExe))
                    {
                        bUpdateScriptPath = true;               // Path is not the same as ours, and .exe referred by C# script does not exists.
                    }
                } //if
            } //for
        }     //using

        if (bUpdateScriptPath)
        {
            String file    = File.ReadAllText(path);
            String newFile = reCssRef.Replace(file, new MatchEvaluator(m => { return("//css_ref " + targetCsPath + "\r\n"); }));
            File.WriteAllText(path, newFile);
        }

        // ----------------------------------------------------------------
        //  Preload compiled .dll and it's debug information into ram.
        // ----------------------------------------------------------------
        MethodInfo entry    = null;
        String     funcName = "";
        Assembly   asm      = Assembly.LoadFrom(tempDll);

        //Assembly asm = results.CompiledAssembly;
        // ----------------------------------------------------------------
        //  Locate entry point
        // ----------------------------------------------------------------
        BindingFlags flags        = BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.IgnoreCase;
        Type         builderClass = null;

        foreach (Type type in asm.GetTypes())
        {
            funcName = "Main";
            entry    = type.GetMethod(funcName, flags);

            if (entry == null)
            {
                funcName = "ScriptMain";
                entry    = type.GetMethod(funcName, flags);
            }

            if (entry != null)
            {
                builderClass = type;
                break;
            }
        }

        if (entry == null)
        {
            errors = String.Format("{0}(1,1): error: Code does not have 'Main' function\r\n", Exception2.getPath(path));
            if (bAllowThrow)
            {
                throw new Exception2(errors);
            }
            return(false);
        }

        if (entry.GetParameters().Length != 1)
        {
            errors = String.Format("{0}(1,1): error: Function '{1}' is not expected to have {2} parameter(s)\r\n", Exception2.getPath(path), funcName, entry.GetParameters().Length);
            if (bAllowThrow)
            {
                throw new Exception2(errors);
            }
            return(false);
        }

        String oldScriptRelativeDir = SolutionProjectBuilder.m_scriptRelativeDir;
        String scriptSubPath        = Path2.makeRelative(Path.GetDirectoryName(_path), SolutionProjectBuilder.m_workPath);
        SolutionProjectBuilder.m_scriptRelativeDir = scriptSubPath;
        String oldScriptPath = SolutionProjectBuilder.m_currentlyExecutingScriptPath;
        SolutionProjectBuilder.m_currentlyExecutingScriptPath = _path;
        String oldDir = Environment.CurrentDirectory;
        //
        // We set current directory to where script is, just so script can use Directory.GetFiles without specifying directory.
        //
        Directory.SetCurrentDirectory(Path.GetDirectoryName(_path));

        // ----------------------------------------------------------------
        //  Run script
        // ----------------------------------------------------------------
        try
        {
            entry.Invoke(null, new object[] { args });
            Directory.SetCurrentDirectory(oldDir);
            SolutionProjectBuilder.m_scriptRelativeDir            = oldScriptRelativeDir;
            SolutionProjectBuilder.m_currentlyExecutingScriptPath = oldScriptPath;
        }
        catch (Exception ex)
        {
            Directory.SetCurrentDirectory(oldDir);
            SolutionProjectBuilder.m_scriptRelativeDir            = oldScriptRelativeDir;
            SolutionProjectBuilder.m_currentlyExecutingScriptPath = oldScriptPath;
            Exception2 ex2 = ex.InnerException as Exception2;
            if (ex2 != null && bAllowThrow)
            {
                throw ex2;
            }

            try
            {
                StackFrame[] stack    = new StackTrace(ex.InnerException, true).GetFrames();
                StackFrame   lastCall = stack[0];

                errors = String.Format("{0}({1},{2}): error: {3}\r\n", path,
                                       lastCall.GetFileLineNumber(), lastCall.GetFileColumnNumber(), ex.InnerException.Message);
            } catch (Exception ex3)
            {
                errors = String.Format("{0}(1,1): error: Internal error - exception '{3}'\r\n", path, ex3.Message);
            }
            if (bAllowThrow)
            {
                throw new Exception2(errors);
            }
            return(false);
        }

        return(true);
    } //RunScript
        protected override void OnBeforePerformingCommand(BeforePerformingCommandEventArgs e)
        {
            e.Handled = true;

            var container = _containers.FirstOrDefault(c => c.Form.Equals(e.Form));

            switch (e.Key)
            {
            case (Key_Button_ShowMacroEditor):
            {
                CurrentEditor(e.Form, false, out bool hidden, out bool isNew).Activate();
            }
            break;

            case (Key_Button_Refresh):
            {
                UpdateTools(container);
            }
            break;

            case (Key_Button_Config):
            {
                using (var directoryDialog = new DirectoryDialog(Settings.TryGetStringValue(Key_MacrosDirectory))
                    {
                        Owner = e.Form
                    })
                {
                    if (directoryDialog.ShowDialog() == DialogResult.OK)
                    {
                        Settings[Key_MacrosDirectory] = directoryDialog.Directory;
                        Program.Settings.InitialDirectories.SetInitialDirectoryContext(Citavi.Settings.InitialDirectoryContext.Macros, Path2.GetFullPathFromPathWithVariables(directoryDialog.Directory));
                        UpdateTools(container);
                    }
                }
            }
            break;

            case (Key_Button_OpenInExplorer):
            {
                if (IsValidDirectory(out string message))
                {
                    var path = Path2.GetFullPathFromPathWithVariables(Settings[Key_MacrosDirectory]);
                    Process.Start("explorer.exe", path);
                }
                else
                {
                    MessageBox.Show(e.Form, message, e.Form.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            break;

            default:

                if (e.Key.StartsWith(Key_Button_Directory, StringComparison.OrdinalIgnoreCase))
                {
                    if (container.Macros.ContainsKey(e.Key))
                    {
                        var macro = container.Macros[e.Key];

                        if (File.Exists(macro.Path))
                        {
                            var hide = macro.Action == MacroAction.Run;

                            _editor = CurrentEditor(e.Form, hide, out bool hidden, out bool isNew);

                            if (!isNew && _editor.IsDirty())
                            {
                                if (MessageBox.Show(e.Form, MacroManagerResources.UserWarningSaveMessage, e.Form.ProductName, MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
                                {
                                    _editor.Save();
                                }
                            }

                            _editor.MacroCode = File.ReadAllText(macro.Path);
                            _editor.SetFilePath(macro.Path);
                            _editor.Activate();

                            if (macro.Action == MacroAction.Run)
                            {
                                _editor.Run();
                            }

                            if (hidden)
                            {
                                _editor.Close();
                            }
                        }
                        else
                        {
                            MessageBox.Show(e.Form, MacroManagerResources.PathNotFoundMessage.FormatString(macro.Path), e.Form.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                            UpdateTools(container, true);
                        }
                    }
                    else
                    {
                        e.Handled = false;
                    }
                }
                else
                {
                    e.Handled = false;
                }
                break;
            }

            base.OnBeforePerformingCommand(e);
        }
예제 #16
0
 static void DoTest1()
 {
     Console.WriteLine("This script ran from: " + Path2.makeRelative(getCsDir(), m_workPath));
     Console.WriteLine("Script name: " + getCsFileName());
 } //Main
예제 #17
0
        private void DownloadAll()
        {
            try
            {
                UserCredential credential;

                using (var stream =
                           new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
                {
                    string credPath = System.Environment.GetFolderPath(
                        System.Environment.SpecialFolder.Personal);
                    credPath = Path.Combine(credPath, ".credentials/drive-dotnet-quickstart.json");

                    credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                        GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, new FileDataStore(credPath, true)).Result;
                }

                // Create Drive API service.
                var service = new DriveService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName       = ApplicationName,
                });

                // Define parameters of request.
                FilesResource.ListRequest listRequest = service.Files.List();
                listRequest.PageSize = 10;
                listRequest.Fields   = "nextPageToken, files(id, name)";
                var request = service.Files.List();
                request.Spaces   = "appDataFolder";
                request.Fields   = "nextPageToken, files(id, name)";
                request.PageSize = 10;
                var result     = request.Execute();
                var driveFiles = result.Files.ToList();
                Directory.CreateDirectory("Budgets");
                var localFiles = Directory.EnumerateFiles(_path, "*.sqlite").ToList();


                foreach (var file in localFiles)
                {
                    var fileName = Path.GetFileName(file);
                    if (driveFiles.Any(x => x.Name.Equals(fileName) && File.GetLastWriteTime(file) < x.ModifiedTime))
                    {
                        //DOWNLOAD NEW VERSION TO PC
                        Dispatcher.Invoke((Action)(() =>
                        {
                            _budgetList.Add(new Budget(fileName, Path.GetFullPath(file), Path.GetFileNameWithoutExtension(file)));
                            var budget = _budgetList.First(x => x.Name.Equals(fileName));
                            budget.LoadAble = false;
                            budget.State = "Updating";
                            ListViewBudgets.ItemsSource = _budgetList;
                            ListViewBudgets.Items.Refresh();
                        }));
                        var fileId          = driveFiles.First(x => x.Name.Equals(Path.GetFileName(file))).Id;
                        var downloadRequest = service.Files.Get(fileId);
                        var stream          = new MemoryStream();
                        downloadRequest.Download(stream);
                        var downloadPath = Path.Combine(_path, Path2.GetFileName(file));
                        stream.Position = 0;
                        var fileStream = File.Create(downloadPath);
                        stream.CopyTo(fileStream);
                        fileStream.Close();
                        Dispatcher.Invoke(() =>
                        {
                            var budget                  = _budgetList.First(x => x.Name.Equals(fileName));
                            budget.LoadAble             = true;
                            budget.State                = "Ready";
                            ListViewBudgets.ItemsSource = _budgetList;
                            ListViewBudgets.Items.Refresh();
                        });
                    }
                }
                foreach (var file in driveFiles)
                {
                    if (!localFiles.Any(x => Path.GetFileName(x).Equals(file.Name)))
                    {
                        //DOWNLOAD NEW BUDGET TO PC
                        this.Dispatcher.Invoke((Action)(() =>
                        {
                            string noExtension = file.Name;
                            string[] a = noExtension.Split('.');
                            noExtension = a[0];
                            _budgetList.Add(new Budget(file.Name, "", noExtension));
                            var budget = _budgetList.First(x => x.Name.Equals(file.Name));
                            budget.LoadAble = false;
                            budget.State = "Downloading";
                            ListViewBudgets.ItemsSource = _budgetList;
                            ListViewBudgets.Items.Refresh();
                        }));
                        var fileId          = file.Id;
                        var downloadRequest = service.Files.Get(fileId);
                        var stream          = new System.IO.MemoryStream();
                        downloadRequest.Download(stream);
                        var downloadPath = Path.Combine(_path, file.Name);
                        stream.Position = 0;
                        var fileStream = File.Create(downloadPath);
                        stream.CopyTo(fileStream);
                        fileStream.Close();
                        this.Dispatcher.Invoke((Action)(() =>
                        {
                            var budget = _budgetList.First(x => x.Name.Equals(file.Name));
                            budget.Path = Path.GetFullPath(downloadPath);
                            budget.NameWithoutExtension = Path.GetFileNameWithoutExtension(downloadPath);
                            budget.LoadAble = false;
                            budget.State = "Ready";
                            ListViewBudgets.ItemsSource = _budgetList;
                            ListViewBudgets.Items.Refresh();
                        }));
                    }
                }
            }
            catch (Exception exception) when(exception is Google.GoogleApiException || exception is HttpRequestException)
            {
                bool retry = false;

                Dispatcher.Invoke((Action)(() =>
                {
                    YesNo yesNo = new YesNo("Quickbudget failed to connect to Google Drive. Do you want to try again?")
                    {
                        Owner = GetWindow(this)
                    };
                    yesNo.ShowDialog();
                    if (yesNo.IsSuccesful)
                    {
                        retry = true;
                    }
                }));
                if (retry)
                {
                    DownloadAll();
                }
                else
                {
                    //TODO load local
                }
            }
        }
예제 #18
0
    public static void Main()
    {
        if (Program.ProjectShells.Count == 0)
        {
            return;                                                     //no project open
        }
        if (IsBackupAvailable() == false)
        {
            return;                                                             //user wants to backup his/her project first
        }
        int counter = 0;

        try
        {
            string sourcePath;

            FolderBrowserDialog folderDialog = new FolderBrowserDialog();
            folderDialog.Description = "Select a root folder for the PDF files to be imported ...";
            DialogResult folderResult = folderDialog.ShowDialog();
            if (folderResult == DialogResult.OK)
            {
                sourcePath = folderDialog.SelectedPath;
            }
            else
            {
                return;
            }

            AttachmentAction action = AttachmentAction.Link;             //suggested: .Link or .Copy

            DirectoryInfo   dir       = new DirectoryInfo(sourcePath);
            List <FileInfo> fileInfos = Path2.GetFilesSafe(dir, "*.pdf", SearchOption.AllDirectories).ToList();

            List <Reference>             newReferences = new List <Reference>();
            SwissAcademic.Citavi.Project activeProject = Program.ActiveProjectShell.Project;

            List <string> filePaths = fileInfos.Select <FileInfo, string>(info => info.FullName).ToList();
            foreach (string filePath in filePaths)
            {
                DebugMacro.WriteLine("START IMPORT: " + filePath);
                List <Reference> referencesFromFile = new FileImportSupport().ImportFiles(activeProject, activeProject.Engine.TransformerManager, new List <string>()
                {
                    filePath
                }, action);

                if (referencesFromFile != null && referencesFromFile.Any())
                {
                    var referencesFromFileAdded = activeProject.References.AddRange(referencesFromFile);

                    var fileName = Path.GetFileName(filePath);
                    AddCategories(referencesFromFileAdded, filePath.Substring(sourcePath.Length, filePath.Length - sourcePath.Length - fileName.Length));
                    DebugMacro.WriteLine("SUCCESS");
                    counter++;
                }
                else
                {
                    DebugMacro.WriteLine("ERROR importing file");
                }
            }
        }         //end try

        finally
        {
            MessageBox.Show(string.Format("Macro has finished execution.\r\n{0} changes were made.", counter.ToString()), "Citavi", MessageBoxButtons.OK, MessageBoxIcon.Information);
        } //end finally
    }     //end main()
예제 #19
0
파일: ChanGen.cs 프로젝트: Urankhai/3DChaSi
    /*
    // Update is called once per frame
    void Update()
    {
        update_flag = 1;

        Rx_MPC1 = Rx_Seen_MPC_Script.seen_MPC1;
        Rx_MPC2 = Rx_Seen_MPC_Script.seen_MPC2;
        Rx_MPC3 = Rx_Seen_MPC_Script.seen_MPC3;

        Tx_MPC1 = Tx_Seen_MPC_Script.seen_MPC1;
        Tx_MPC2 = Tx_Seen_MPC_Script.seen_MPC2;
        Tx_MPC3 = Tx_Seen_MPC_Script.seen_MPC3;


    }
    */

    private void FixedUpdate()
    {
        Rx_MPC1 = Rx_Seen_MPC_Script.seen_MPC1;
        Rx_MPC2 = Rx_Seen_MPC_Script.seen_MPC2;
        Rx_MPC3 = Rx_Seen_MPC_Script.seen_MPC3;

        Tx_MPC1 = Tx_Seen_MPC_Script.seen_MPC1;
        Tx_MPC2 = Tx_Seen_MPC_Script.seen_MPC2;
        Tx_MPC3 = Tx_Seen_MPC_Script.seen_MPC3;



        ///////////////////////////////////////////////////////////////////////////////////
        /// LOS
        ///////////////////////////////////////////////////////////////////////////////////
        // float startTime = Time.realtimeSinceStartup;
        if (!Physics.Linecast(Tx.transform.position, Rx.transform.position))
        {
            float LOS_distance = (Tx.transform.position - Rx.transform.position).magnitude;
            if (LOS_Tracer)
            {
                Debug.DrawLine(Tx.transform.position, Rx.transform.position, Color.magenta);
            }
        }
        // Debug.Log(((Time.realtimeSinceStartup - startTime) * 1000000f) + "microsec");
        ///////////////////////////////////////////////////////////////////////////////////
        /// MPC1
        ///////////////////////////////////////////////////////////////////////////////////
        List<int> common_mpc1 = new List<int>();

        CommonMPC1(Rx_MPC1, Tx_MPC1, out common_mpc1);

        List<int> active_MPC1 = new List<int>();
        for (int i = 0; i < common_mpc1.Count; i++)

        {
            // defining peprendicular to the considered normal that is parallel to the ground. 
            Vector3 n_perp = new Vector3(-MPC1[common_mpc1[i]].Normal.z, 0, MPC1[common_mpc1[i]].Normal.x);
            float rx_distance = (Rx.transform.position - MPC1[common_mpc1[i]].Coordinates).magnitude;
            float tx_distance = (Rx.transform.position - MPC1[common_mpc1[i]].Coordinates).magnitude;
            Vector3 rx_direction = (Rx.transform.position - MPC1[common_mpc1[i]].Coordinates).normalized;
            Vector3 tx_direction = (Tx.transform.position - MPC1[common_mpc1[i]].Coordinates).normalized;

            if ((Vector3.Dot(n_perp, rx_direction) * Vector3.Dot(n_perp, tx_direction)) < 0)
            {
                active_MPC1.Add(common_mpc1[i]);
                if (MPC1_Tracer)
                {
                    Debug.DrawLine(Rx.transform.position, MPC1[common_mpc1[i]].Coordinates, Color.red);
                    Debug.DrawLine(Tx.transform.position, MPC1[common_mpc1[i]].Coordinates, Color.blue);
                }
            }
        }




        ///////////////////////////////////////////////////////////////////////////////////
        /// MPC2
        ///////////////////////////////////////////////////////////////////////////////////
        List<Path2> second_order_paths = new List<Path2>();

        int brute_force = 1;
        for (int i = 0; i < Rx_MPC2.Count; i++)
        {
            List<GeoComp> temp_list = new List<GeoComp>();
            if (brute_force == 1)
            {
                temp_list = GlobeCom2[Rx_MPC2[i]];
            }
            else
            {
                for (int j = 0; j < MPC2.Count; j++)
                {
                    float dist_xxx = (MPC2[j].Coordinates - MPC2[Rx_MPC2[i]].Coordinates).magnitude;
                    if (dist_xxx < 70)
                    {
                        if (!Physics.Linecast(MPC2[j].Coordinates, MPC2[Rx_MPC2[i]].Coordinates))
                        {
                            float aod = Mathf.Acos(Vector3.Dot((MPC2[j].Coordinates - MPC2[Rx_MPC2[i]].Coordinates).normalized, MPC2[j].Normal));
                            float aoa = Mathf.Acos(-Vector3.Dot((MPC2[j].Coordinates - MPC2[Rx_MPC2[i]].Coordinates).normalized, MPC2[Rx_MPC2[i]].Normal));
                            GeoComp asd = new GeoComp(j, dist_xxx, aod, aoa);
                            temp_list.Add(asd);
                        }
                    }
                }
            }

            for (int ii = 0; ii < Tx_MPC2.Count; ii++)
            {
                if (temp_list.Any(geocom => geocom.MPCIndex == Tx_MPC2[ii]))
                {
                    int temp_index = temp_list.FindIndex(geocom => geocom.MPCIndex == Tx_MPC2[ii]);
                    // defining peprendicular to the considered normal that is parallel to the ground. 
                    V6 temp_Rx_MPC2 = MPC2[Rx_MPC2[i]];
                    V6 temp_Tx_MPC2 = MPC2[Tx_MPC2[ii]];

                    Vector3 n_perp1 = new Vector3(-temp_Rx_MPC2.Normal.z, 0, temp_Rx_MPC2.Normal.x);
                    Vector3 Rx_dir1 = (Rx.transform.position - temp_Rx_MPC2.Coordinates).normalized;
                    Vector3 RT = (temp_Tx_MPC2.Coordinates - temp_Rx_MPC2.Coordinates).normalized;

                    Vector3 n_perp2 = new Vector3(-temp_Tx_MPC2.Normal.z, 0, temp_Tx_MPC2.Normal.x);
                    Vector3 Tx_dir2 = (Tx.transform.position - temp_Tx_MPC2.Coordinates).normalized;
                    Vector3 TR = (temp_Rx_MPC2.Coordinates - temp_Tx_MPC2.Coordinates).normalized;

                    if ((Vector3.Dot(n_perp1, Rx_dir1) * Vector3.Dot(n_perp1, RT) < 0) && (Vector3.Dot(n_perp2, Tx_dir2) * Vector3.Dot(n_perp2, TR) < 0))
                    {
                        float rx_distance2MPC2 = (Rx.transform.position - MPC2[Rx_MPC2[i]].Coordinates).magnitude;
                        float tx_distance2MPC2 = (Tx.transform.position - MPC2[Tx_MPC2[ii]].Coordinates).magnitude;
                        float MPC2_distance = temp_list[temp_index].Distance;
                        float total_distance = rx_distance2MPC2 + MPC2_distance + tx_distance2MPC2;

                        Path2 temp_path2 = new Path2(Rx.transform.position, MPC2[Rx_MPC2[i]].Coordinates, MPC2[Tx_MPC2[ii]].Coordinates, Tx.transform.position, total_distance, 0.0f);
                        second_order_paths.Add(temp_path2);
                        if (MPC2_Tracer)
                        {
                            Debug.DrawLine(temp_path2.Rx_Point, temp_path2.MPC2_1, Color.green);
                            Debug.DrawLine(temp_path2.MPC2_1, temp_path2.MPC2_2, Color.yellow);
                            Debug.DrawLine(temp_path2.MPC2_2, temp_path2.Tx_Point, Color.cyan);
                        }
                    }
                }
            }

        }



    }
    public static void Main()
    {
        //reference to the active project and the main window
        Form primaryMainForm = Program.ActiveProjectShell.PrimaryMainForm;

        if (primaryMainForm == null)
        {
            return;
        }

        SwissAcademic.Citavi.Project activeProject = Program.ActiveProjectShell.Project;
        if (activeProject == null)
        {
            return;
        }

        if (IsBackupAvailable() == false)
        {
            return;                                                                     //user wants to backup his/her project first
        }
        //if no reference filters applied, macro cannot operate
        if (Program.ActiveProjectShell.PrimaryMainForm.ReferenceEditorFilterSet.Filters.Count == 0)
        {
            string message = "This macro requires a selection of references to operate on.\r\n";
            message += "Please select some references with PDF files attached.";
            MessageBox.Show(message, "Citavi");
            return;
        }

        //path to the current project's CitaviFiles folder
        string citaviFilesPath = activeProject.GetFolderPath(CitaviFolder.CitaviFiles);

        List <Reference> references = Program.ActiveProjectShell.PrimaryMainForm.GetFilteredReferences();

        //List<Reference> references = CollectionUtility.ToList(activeProject.References);

        #region Generate list of file locations to move

        //first we create a list of files attached to the currently selected references,
        //having a PDF extension,
        //and existing inside the CitaviFiles folder
        List <FileMoveOperation> fileMoveOperations = new List <FileMoveOperation>();

        foreach (Reference reference in references)
        {
            foreach (Location location in reference.Locations)
            {
                if (location.LocationType != LocationType.ElectronicAddress)
                {
                    continue;
                }

                if (location.AddressUri.AddressInfo == ElectronicAddressInfo.CitaviFiles)
                {
                    if (Path.GetExtension(location.Address).Equals(".pdf", StringComparison.OrdinalIgnoreCase))
                    {
                        FileMoveOperation fileMoveOperation = new FileMoveOperation(location);
                        fileMoveOperations.Add(fileMoveOperation);
                        //MessageBox.Show(fileMoveOperation.SourcePath);
                        //MessageBox.Show(fileMoveOperation.OriginalFileName);
                    }
                }
            }
        }

        if (fileMoveOperations.Count == 0)
        {
            string message = string.Format("The {0} selected reference(s) do not have any PDF files attached, that are stored inside the CitaviFiles folder.", references.Count);
            MessageBox.Show(message, "Citavi");
            return;
        }

        #endregion Generate list of file locations to move

        #region Prompt user for target folder to move files to

        string targetFolderPath = string.Empty;

        using (var folderPicker = new CommonOpenFileDialog())
        {
            folderPicker.IsFolderPicker   = true;
            folderPicker.Title            = string.Format("Select the folder where you want to move the {0} PDF files to.", fileMoveOperations.Count);
            folderPicker.InitialDirectory = Program.Settings.InitialDirectories.GetInitialDirectory(SwissAcademic.Citavi.Settings.InitialDirectoryContext.LocalFile, null);
            if (folderPicker.ShowDialog() == CommonFileDialogResult.Ok)
            {
                targetFolderPath = folderPicker.FileName;
            }
            else
            {
                MessageBox.Show("Macro execution cancelled upon user's request.", "Citavi");
                return;
            }
        }



        #endregion Prompt user for target folder to move files to

        #region Copy the files to the new folder

        DirectoryInfo targetDirectory = new DirectoryInfo(targetFolderPath);

        foreach (FileMoveOperation fileMoveOperation in fileMoveOperations)
        {
            //avoid overwriting a possible existing file
            fileMoveOperation.TargetPath = Path2.GetUniqueFilePath(targetDirectory, fileMoveOperation.OriginalFileName);
            try
            {
                File.Copy(fileMoveOperation.SourcePath, fileMoveOperation.TargetPath, false);
                fileMoveOperation.CopySuccess = true;
            }
            catch (Exception exception)
            {
                fileMoveOperation.Errors.Add(exception);
                fileMoveOperation.CopySuccess = false;
            }
        }

        #endregion Copy the files to the new region

        #region Relink each reference to the new files

        foreach (FileMoveOperation fileMoveOperation in fileMoveOperations)
        {
            if (fileMoveOperation.CopySuccess)
            {
                try
                {
                    fileMoveOperation.TargetLocation       = fileMoveOperation.SourceLocation.Reference.Locations.Add(LocationType.ElectronicAddress, fileMoveOperation.TargetPath, string.Empty, false);
                    fileMoveOperation.TargetLocation.Notes = fileMoveOperation.SourceLocation.Notes;
                    fileMoveOperation.RelinkSuccess        = true;
                }
                catch (Exception exception)
                {
                    fileMoveOperation.Errors.Add(exception);
                    fileMoveOperation.RelinkSuccess = false;
                }
            }
        }

        #endregion Relink each reference to the new files

        #region Delete the original locations and move the files in the CitaviFiles folder to CitaviFiles\RecycleBin

        foreach (FileMoveOperation fileMoveOperation in fileMoveOperations)
        {
            if (fileMoveOperation.RelinkSuccess)
            {
                try
                {
                    Location locationToDelete = fileMoveOperation.SourceLocation;
                    Project  locationProject  = locationToDelete.Project;

                    if (locationToDelete == null)
                    {
                        continue;
                    }

                    ElectronicAddressUri addressUriToDelete = locationToDelete.AddressUri;
                    locationToDelete.Reference.Locations.Remove(locationToDelete);
                    Program.ActiveProjectShell.Save(primaryMainForm);


                    DirectoryInfo recycleBinDirectory = new DirectoryInfo(locationProject.GetFolderPath(CitaviFolder.RecycleBin));
                    string        deletedFilePath     = Path2.GetUniqueFilePath(recycleBinDirectory, fileMoveOperation.OriginalFileName);
                    File.Move(fileMoveOperation.SourcePath, deletedFilePath);

                    fileMoveOperation.DeleteSuccess = true;
                }
                catch (Exception exception)
                {
                    fileMoveOperation.Errors.Add(exception);
                    fileMoveOperation.DeleteSuccess = false;
                }
            }
        }

        #endregion Delete the original locations and move the files in the CitaviFiles folder to CitaviFiles\RecycleBin



        MessageBox.Show("Macro has finished execution.", "Citavi");
    }
예제 #21
0
        private void btnAddFilePath_Click(object sender, EventArgs e)
        {
            try
            {
                btnPrimaryDir.BackColor  = Color.FromName("Control");
                btnSecondDir.BackColor   = Color.FromName("Control");
                btnAddFilePath.BackColor = Color.FromName("Control");
                string Path1;
                string Path2;


                if (rbPrimaryDir.Checked)
                {
                    if (textBox2.Text == "")
                    {
                        rbSecondaryDir.BackColor = Color.Yellow;
                        btnSecondDir.BackColor   = Color.Yellow;
                    }

                    rbPrimaryDir.BackColor = Color.FromName("Control");

                    tvFilesView.SelectedNode.BackColor = Color.Blue;
                    tvFilesView.SelectedNode.ForeColor = Color.White;

                    if (tvFilesView.SelectedNode.PrevNode != null || tvFilesView.SelectedNode.PrevNode.BackColor == Color.Green ||
                        tvFilesView.SelectedNode.PrevNode.BackColor == Color.Blue)
                    {
                        tvFilesView.SelectedNode.PrevNode.BackColor = Color.White;
                        tvFilesView.SelectedNode.PrevNode.ForeColor = Color.Black;
                    }

                    Path1         = tvFilesView.SelectedNode.FullPath.ToString();
                    Path1         = Path1.Insert(1, ":");
                    textBox1.Text = Path1;
                }
                else if (rbSecondaryDir.Checked)
                {
                    if (textBox1.Text == "")
                    {
                        rbPrimaryDir.BackColor  = Color.Yellow;
                        btnPrimaryDir.BackColor = Color.Yellow;
                    }

                    rbSecondaryDir.BackColor = Color.FromName("Control");

                    rbSecondaryDir.BackColor           = Color.Transparent;
                    tvFilesView.SelectedNode.BackColor = Color.Green;
                    tvFilesView.SelectedNode.ForeColor = Color.White;

                    if (tvFilesView.SelectedNode.PrevNode != null || tvFilesView.SelectedNode.PrevNode.BackColor == Color.Blue ||
                        tvFilesView.SelectedNode.PrevNode.BackColor == Color.Green)
                    {
                        tvFilesView.SelectedNode.PrevNode.BackColor = Color.White;
                        tvFilesView.SelectedNode.PrevNode.ForeColor = Color.Black;
                    }

                    Path2         = tvFilesView.SelectedNode.FullPath.ToString();
                    Path2         = Path2.Insert(1, ":");
                    textBox2.Text = Path2;
                }
                else
                {
                    tbOutPut.Text = "Pick two Directories to begin!";
                    errorProvider.SetError(rbPrimaryDir, "Select One");
                    errorProvider.SetError(rbSecondaryDir, "Select One");
                    errorProvider.SetError(btnPrimaryDir, "Select a Directory");
                    errorProvider.SetError(btnSecondDir, "Select a Directory");
                }

                Path1 = textBox1.Text;
                Path2 = textBox2.Text;

                if (Path1 != "" && Path2 != "")
                {
                    btnCompare.BackColor = Color.Yellow;
                    tbOutPut.Text        = "Green Light to compare Files !";
                    tbOutPut.BackColor   = Color.Green;
                    tbOutPut.ForeColor   = Color.White;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        public static async Task SendByEMailAsync(this Reference reference, MainForm mainForm)
        {
            var mailTemplate        = new MailTemplate();
            var attachmentFileNames = new StringBuilder();

            foreach (var location in reference.Locations.GetAvailable())
            {
                var fileInfo = new FileInfo(location.Address.Resolve().GetLocalPathSafe());
                mailTemplate.Attachments.Add(fileInfo.FullName);
                attachmentFileNames.AppendLine(fileInfo.Name);
            }

            var shortTitle = (string.IsNullOrEmpty(reference.ShortTitle)
                             ? SendReferenceByEmailResources.ShortTitleMissing
                             : reference.ShortTitle).UnciodeToLatin();

            mailTemplate.Subject = "Citavi: " + shortTitle;

            var stringBuilder = new StringBuilder();

            foreach (var c in shortTitle)
            {
                if (c < 32 || c > 254)
                {
                    continue;
                }
                stringBuilder.Append(c);
                if (stringBuilder.Length > 50)
                {
                    break;
                }
            }
            shortTitle = Path2.GetValidFileName(stringBuilder.ToString());
            var risTempFileName = Path.Combine(Path.GetTempPath(), shortTitle + ".ris");
            var risExportDataExchangeProptery = new FileExportDataExchangeProperty
            {
                FileName         = risTempFileName,
                ExportReferences = new List <Reference>()
                {
                    reference
                },
                Transformer = Program.Engine.TransformerManager.GetById(Transformer.RISTransformerId)
            };
            var exporter = new Exporter();
            var success  = false;

            using (var fs = File.OpenWrite(risTempFileName))
            {
                success = await exporter.RunAsync(risExportDataExchangeProptery, fs, CancellationToken.None, null);
            }
            if (!success)
            {
                return;
            }

            mailTemplate.Attachments.Add(risTempFileName);
            attachmentFileNames.AppendLine(Path.GetFileName(risTempFileName));

            mailTemplate.Body = mailTemplate.Attachments.Count > 0
                        ? string.Format(SendReferenceByEmailResources.SendReferenceByEMailBodyText_WithAttachments, reference.Project.Name, reference.ToString(TextFormat.Text), attachmentFileNames.ToString())
                        : string.Format(SendReferenceByEmailResources.SendReferenceByEMailBodyText, reference.Project.Name, reference.ToString(TextFormat.Text));

            try
            {
                Outlook.Send(mailTemplate);
            }
            catch (System.Runtime.InteropServices.COMException)
            {
                MessageBox.Show(mainForm, SendReferenceByEmailResources.OutlookRightsMessage, mainForm.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
 void TxtPath_TextChanged(object sender, EventArgs e) => lblEnvironmentFullPath.Text = Path2.GetFullPathFromPathWithVariables(txtPath.Text);
예제 #24
0
 CreateDescriptor(Path2, PipFragmentType.AbsolutePath, f => f.GetPathValue(), (v, p) => p.Add(v)),
예제 #25
0
        // Methods

        public override void OnBeforePerformingCommand(MainForm mainForm, BeforePerformingCommandEventArgs e)
        {
            e.Handled = true;

            var container = _containers.FirstOrDefault(c => c.MainForm.Equals(mainForm));

            switch (e.Key)
            {
            case ButtonKey_ShowMacroEditor:
            {
                GetOrCreateMacroEditorForm(false, out bool _, out bool _).Activate();
            }
            break;

            case ButtonKey_Refresh:
            {
                UpdateTools(container);
            }
            break;

            case ButtonKey_Configurate:
            {
                using (var directoryDialog = new DirectoryForm(mainForm, Settings.TryGetStringValue(SettingsKey)))
                {
                    if (directoryDialog.ShowDialog() == DialogResult.OK)
                    {
                        if (!directoryDialog.Directory.Equals(Settings.TryGetStringValue(SettingsKey), StringComparison.OrdinalIgnoreCase))
                        {
                            Settings[SettingsKey] = directoryDialog.Directory;
                            Program.Settings.InitialDirectories.SetInitialDirectoryContext(Citavi.Settings.InitialDirectoryContext.Macros, Path2.GetFullPathFromPathWithVariables(directoryDialog.Directory));
                            UpdateTools(container);
                        }
                    }
                }
            }
            break;

            case ButtonKey_OpenInExplorer:
            {
                if (IsValidDirectory(out string message))
                {
                    var path = Path2.GetFullPathFromPathWithVariables(Settings[SettingsKey]);
                    Process.Start("explorer.exe", path);
                }
                else
                {
                    MessageBox.Show(mainForm, message, mainForm.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            break;

            default:

                if (e.Key.StartsWith(ButtonKey, StringComparison.OrdinalIgnoreCase))
                {
                    if (container.Macros.ContainsKey(e.Key))
                    {
                        var macro = container.Macros[e.Key];

                        if (File.Exists(macro.Path))
                        {
                            var hide = macro.Action == MacroAction.Run;

                            var editor = GetOrCreateMacroEditorForm(hide, out bool hidden, out bool isNew);

                            if (!isNew && editor.IsDirty())
                            {
                                if (MessageBox.Show(mainForm, Properties.Resources.UserWarningSaveMessage, mainForm.ProductName, MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
                                {
                                    editor.Save();
                                }
                            }

                            editor.MacroCode = File.ReadAllText(macro.Path);
                            editor.SetFilePath(macro.Path);
                            editor.Activate();

                            if (macro.Action == MacroAction.Run)
                            {
                                editor.Run();
                            }

                            if (hidden)
                            {
                                editor.Close();
                            }
                        }
                        else
                        {
                            MessageBox.Show(mainForm, Properties.Resources.PathNotFoundMessage.FormatString(macro.Path), mainForm.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                            UpdateTools(container, true);
                        }
                    }
                    else
                    {
                        e.Handled = false;
                    }
                }
                else
                {
                    e.Handled = false;
                }
                break;
            }
        }
예제 #26
0
    public void Execute(int index)
    {
        OutputDelays[index]     = 0;
        OutputAmplitudes[index] = 0;

        V6 level1 = SeenMPC2Table[Rx_MPC2Array[index]];

        float distance1 = (level1.Coordinates - Rx_Position).magnitude;

        int temp_index = Mathf.FloorToInt(index / MaxListsLength);
        int temp_i     = index - temp_index * MaxListsLength;

        if (temp_i <= LookUpTable2ID[Rx_MPC2Array[index]].y - LookUpTable2ID[Rx_MPC2Array[index]].x)
        {
            int temp_l = LookUpTable2ID[Rx_MPC2Array[index]].x + temp_i;

            V6      level2           = SeenMPC2Table[LookUpTable2[temp_l].MPCIndex];
            Vector3 level2_to_level1 = (level1.Coordinates - level2.Coordinates).normalized;
            float   distance2        = (level1.Coordinates - level2.Coordinates).magnitude;

            // check if level2 is seen by Tx
            int   existence_flag = 0;
            float Tx_att         = 0f;
            for (int i = 0; i < Tx_MPC2.Length; i++)
            {
                if (LookUpTable2[temp_l].MPCIndex == Tx_MPC2[i])
                {
                    existence_flag = 1;
                    Tx_att         = Tx_MPC2_att[i];
                    break;
                }
            }

            if (existence_flag == 1)
            {
                Vector3 normal1      = level1.Normal;
                Vector3 n_perp1      = new Vector3(-normal1.z, 0, normal1.x);
                Vector3 Rx_to_level1 = (level1.Coordinates - Rx_Position).normalized;

                Vector3 normal2      = level2.Normal;
                Vector3 n_perp2      = new Vector3(-normal2.z, 0, normal2.x);
                Vector3 level2_to_Tx = (Tx_Position - level2.Coordinates).normalized;

                // check if the two vectors come from different sides of the normal
                if ((Vector3.Dot(n_perp2, level2_to_level1) * Vector3.Dot(n_perp2, level2_to_Tx) < 0) && (Vector3.Dot(n_perp1, level2_to_level1) * Vector3.Dot(n_perp1, Rx_to_level1) < 0))
                {
                    double theta11 = Math.Acos(Vector3.Dot(normal1, -Rx_to_level1));
                    double theta12 = Math.Acos(Vector3.Dot(normal1, -level2_to_level1));
                    int    I11, I12, I13;
                    if (theta11 + theta12 < 0.35)
                    {
                        I11 = 0;
                    }
                    else
                    {
                        I11 = 1;
                    }
                    if (theta11 < 1.22)
                    {
                        I12 = 0;
                    }
                    else
                    {
                        I12 = 1;
                    }
                    if (theta12 < 1.22)
                    {
                        I13 = 0;
                    }
                    else
                    {
                        I13 = 1;
                    }

                    float angular_gain1 = (float)Math.Exp(-12 * ((theta11 + theta12 - 0.35) * I11 + (theta11 - 1.22) * I12 + (theta12 - 1.22) * I13));

                    double theta21 = Math.Acos(Vector3.Dot(normal2, level2_to_Tx));
                    double theta22 = Math.Acos(Vector3.Dot(normal1, level2_to_level1));
                    int    I21, I22, I23;
                    if (theta21 + theta22 < 0.35)
                    {
                        I21 = 0;
                    }
                    else
                    {
                        I21 = 1;
                    }
                    if (theta21 < 1.22)
                    {
                        I22 = 0;
                    }
                    else
                    {
                        I22 = 1;
                    }
                    if (theta22 < 1.22)
                    {
                        I23 = 0;
                    }
                    else
                    {
                        I23 = 1;
                    }

                    float angular_gain2 = (float)Math.Exp(-12 * ((theta21 + theta22 - 0.35) * I21 + (theta21 - 1.22) * I22 + (theta22 - 1.22) * I23));

                    float angular_gain = angular_gain1 * angular_gain2;

                    float distance3  = level2_to_Tx.magnitude;
                    float distance   = distance1 + distance2 + distance3;
                    Path2 temp_path2 = new Path2(Rx_Position, level1.Coordinates, level2.Coordinates, Tx_Position, distance, angular_gain);
                    SecondOrderPaths[index] = temp_path2;

                    OutputDelays[index]     = distance;// / Speed_of_Light;
                    OutputAmplitudes[index] = Tx_att * Rx_MPC2Array_att[index] * angular_gain * (float)Math.Pow(1 / distance, 2);
                }
            }
        }
    }
예제 #27
0
        static void Main(string[] args)
        {
            /*
             *
             */
            CommandLine options = new CommandLine();

            if (options.Parse(args) == false)
            {
                Environment.Exit(1001);
                return;
            }

            if (options.Help == true)
            {
                options.HelpShow();
                Environment.Exit(1002);
                return;
            }

            _options = options;


            /*
             *
             */
            string[] files = Yttrium.Glob.Do(options.FilePatterns.ToArray());

            if (files == null || files.Length == 0)
            {
                Console.WriteLine("error: no matching files.");
                Environment.Exit(2);
            }


            /*
             *
             */
            Console.WriteLine("~ mode: '{0}'", _options.Mode);


            /*
             *
             */
            Microsoft.Office.Interop.Visio.Application visio = null;
            bool anyError = false;

            try
            {
                /*
                 *
                 */
                ModelExporter exporter = new ModelExporter();
                exporter.PageStart += new EventHandler <PageEventArgs>(OnPageStart);
                exporter.PageEnd   += new EventHandler <PageEventArgs>(OnPageEnd);
                exporter.StepStart += new EventHandler <PageStepEventArgs>(OnStepStart);
                exporter.StepEnd   += new EventHandler <PageStepEventArgs>(OnStepEnd);

                /*
                 *
                 */
                visio = new Microsoft.Office.Interop.Visio.Application();
                visio.AlertResponse = 1;
                visio.Visible       = false;

                foreach (string file in files)
                {
                    /*
                     *
                     */
                    Console.Write("+ opening '{0}'...", Path2.RelativePath(file));
                    FileInfo fileInfo = new FileInfo(file);

                    if (fileInfo.Exists == false)
                    {
                        ConsoleFail();
                        Console.WriteLine(" - file does not exist");

                        anyError = true;
                        continue;
                    }


                    /*
                     * Open the document: if the document is not a valid/compatible Visio
                     * document, this will fail.
                     */
                    Microsoft.Office.Interop.Visio.Document document;

                    try
                    {
                        document = visio.Documents.Open(fileInfo.FullName);
                        ConsoleOk();
                    }
                    catch (Exception ex)
                    {
                        ConsoleFail();

                        if (options.Verbose == true)
                        {
                            ConsoleDump(ex);
                        }

                        anyError = true;
                        continue;
                    }


                    /*
                     * Settings
                     */
                    ModelExportSettings exportSettings = new ModelExportSettings();
                    exportSettings.Program = "ModelExport";
                    exportSettings.Mode    = options.Mode;
                    exportSettings.Path    = options.OutputDirectory ?? fileInfo.DirectoryName;

                    exporter.Settings = exportSettings;


                    /*
                     * Export.
                     */
                    ModelCommandResult result = null;

                    ModelCommand command = new ModelCommand();
                    command.Document  = document;
                    command.Operation = ModelOperation.ExportAll;

                    if (options.ValidateOnly == true)
                    {
                        command.Operation = ModelOperation.ValidateAll;
                    }


                    try
                    {
                        result = exporter.Execute(command);
                    }
                    catch (Exception ex)
                    {
                        anyError = true;

                        if (options.Verbose == true)
                        {
                            ConsoleDump(ex);
                        }
                    }
                    finally
                    {
                        document.Close();
                    }

                    if (result == null)
                    {
                        continue;
                    }


                    /*
                     *
                     */
                    Console.WriteLine("");
                    Console.WriteLine("execution summary");
                    Console.WriteLine("-------------------------------------------------------------------------");

                    foreach (ModelCommandPageResult pageResult in result.Pages)
                    {
                        Console.Write(pageResult.Name);

                        if (pageResult.Success == true)
                        {
                            ConsoleOk();
                        }
                        else
                        {
                            ConsoleFail();
                        }

                        foreach (ModelResultItem item in pageResult.Items)
                        {
                            string marker;

                            switch (item.ItemType)
                            {
                            case ModelResultItemType.Error:
                                Console.ForegroundColor = ConsoleColor.DarkRed;
                                marker = "!";
                                break;

                            case ModelResultItemType.Warning:
                                Console.ForegroundColor = ConsoleColor.DarkYellow;
                                marker = "W";
                                break;

                            default:
                                marker = " ";
                                break;
                            }

                            if (item.VisioShapeId == null)
                            {
                                Console.WriteLine("{0} [page] {1}#{2}: {3}", marker, item.Actor, item.Code, item.Description);
                            }
                            else
                            {
                                Console.WriteLine("{0} [{1}] {2}#{3}: {4}", marker, item.VisioShapeId, item.Actor, item.Code, item.Description);
                            }

                            Console.ResetColor();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ConsoleDump(ex);
            }
            finally
            {
                // This _needs_ to be performed here: in case an exception is caught,
                // make sure that Visio is closed or otherwise a zombie process will
                // be left running on the machine.
                if (visio != null)
                {
                    visio.Quit();
                }
            }


            /*
             *
             */
            if (anyError == true)
            {
                Environment.Exit(3);
            }
            else
            {
                Environment.Exit(0);
            }
        }