private static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs)
	{
		DirectoryInfo dir = new DirectoryInfo(sourceDirName);
		DirectoryInfo[] dirs = dir.GetDirectories();

		if (!dir.Exists)
		{
			throw new DirectoryNotFoundException(
				"Source directory does not exist or could not be found: "
				+ sourceDirName);
		}

		if (!Directory.Exists(destDirName))
		{
			Directory.CreateDirectory(destDirName);
		}

		FileInfo[] files = dir.GetFiles();
		foreach (FileInfo file in files)
		{
			string temppath = Path.Combine(destDirName, file.Name);
			file.CopyTo(temppath, true);
		}

		if (copySubDirs)
		{
			foreach (DirectoryInfo subdir in dirs)
			{
				string temppath = Path.Combine(destDirName, subdir.Name);
				DirectoryCopy(subdir.FullName, temppath, copySubDirs);
			}
		}
	}
    /// <summary>
    /// Recursive Copy Directory Method
    /// </summary>
    private static void CopyAll(DirectoryInfo source, DirectoryInfo target)
    {
        // Check if the source directory exists, if not, don't do any work.
        if (!Directory.Exists(source.FullName))
        {
            return;
        }

        // Check if the target directory exists, if not, create it.
        if (!Directory.Exists(target.FullName))
        {
            Directory.CreateDirectory(target.FullName);
        }

        // Copy each file into it’s new directory.
        foreach (var fileInfo in source.GetFiles())
        {
            fileInfo.CopyTo (Path.Combine (target.ToString (), fileInfo.Name), true);
        }

        // Copy each subdirectory using recursion.
        foreach (var subDirInfo in source.GetDirectories())
        {
            DirectoryInfo nextTargetSubDir = target.CreateSubdirectory(subDirInfo.Name);
            CopyAll(subDirInfo, nextTargetSubDir);
        }
    }
 public void CheckForFilesToUpdate()
 {
     WrapInMutex(() =>
                     {
                         var newStrings = new List<string>();
                         foreach (var targetDirectory in File.ReadAllLines(taskFilePath))
                         {
                             var trimmed = targetDirectory.Trim();
                             if (trimmed.Length == 0)
                             {
                                 continue;
                             }
                             var directoryInfo = new DirectoryInfo(trimmed);
                             if (!directoryInfo.Exists)
                             {
                                 continue;
                             }
                             if (fileExporter.ExportTask(directoryInfo))
                             {
                                 var path = Path.Combine(trimmed, "Costura.dll");
                                 errorDisplayer.ShowInfo(string.Format("Costura: Updated '{0}' to version {1}.", path, CurrentVersion.Version));
                             }
                             else
                             {
                                 newStrings.Add(trimmed);
                             }
                         }
                         File.WriteAllLines(taskFilePath, newStrings);
                     });
 }
    public static IEnumerable<string> IterateDirectory(DirectoryInfo dir)
    {
        DirectoryInfo[] directories = dir.GetDirectories("*", SearchOption.TopDirectoryOnly);

        foreach (var directory in directories)
        {
            yield return string.Format("<DIR> {0}:", directory);

            foreach (var file in directory.GetFiles("*.*", SearchOption.AllDirectories))
            {
                yield return string.Format(" - {0}", file);
            }

            foreach (var subDirectory in directory.GetDirectories("*", SearchOption.TopDirectoryOnly))
            {
                yield return string.Format(" - <DIR> {0}:", subDirectory);

                foreach (var file in subDirectory.GetFiles("*.*", SearchOption.AllDirectories))
                {
                    yield return string.Format("    -- {0}", file);
                }
            }

            yield return " ";
        }
    }
 /// <summary>
 /// Destory Old Excel
 /// </summary>
 private void destroyOldExcel()
 {
     try
     {
         string path = Server.MapPath("~") + @"ExcelReport\";
         string folderName = DateTime.Now.ToString("yyyyMMdd");
         DirectoryInfo root = new DirectoryInfo(path);
         DirectoryInfo[] nodes = root.GetDirectories();
         FileInfo[] files = null;
         for (int i = 0; i < nodes.Length; i++)
         {
             if (!string.Equals(nodes[i].Name, folderName))
             {
                 files = nodes[i].GetFiles();
                 for (int j = 0; j < files.Length; j++)
                 {
                     if (files[j].Attributes.ToString().IndexOf("ReadOnly") != -1)
                     {
                         files[j].Attributes = FileAttributes.Normal;
                     }
                     files[j].Delete();
                 }
                 nodes[i].Delete();
             }
         }
     }
     catch { }
 }
 /// <summary>
 /// Recursively convert all source files and subfolders
 /// </summary>
 /// <param name="directory"></param>
 public static void AssetsConvertLineEndings(DirectoryInfo directory)
 {
     if (null == directory)
     {
         return;
     }
     // get all source files
     foreach (string extension in EXTENSION_SOURCE)
     {
         foreach (FileInfo file in directory.GetFiles(extension))
         {
             ConvertAsset(file);
         }
     }
     // scan subfolders
     foreach (DirectoryInfo subDir in directory.GetDirectories())
     {
         if (null == subDir)
         {
             continue;
         }
         if (subDir.Name.ToUpper().Equals(".SVN"))
         {
             continue;
         }
         //Debug.Log(string.Format("Directory: {0}", subDir));
         AssetsConvertLineEndings(subDir);
     }
 }
    public Folder(string path)
    {
        DirectoryInfo dirInfo = new DirectoryInfo(path);
            this.Name = dirInfo.Name;

            CreateRecursivelyFilesAndFolders(dirInfo);
    }
    public void LoadFolders()
    {
        if (Directory.Exists(this.RealImagePath)) {
            DirectoryInfo _currentFolder = new DirectoryInfo(this.current_path.Value);
            DirectoryInfo[] _subs = _currentFolder.GetDirectories();

            this.FolderList.DataSource = _subs;
            this.FolderList.DataBind();
            //get files in patterns
            string[] pattern = { "*.jpg", "*.jpeg", "*.gif" ,"*.png","*.bmp"};
            List<FileInfo> _imagesFound = new List<FileInfo>();
            foreach (string filter in pattern) {
                _imagesFound.AddRange(_currentFolder.GetFiles(filter));
            }
            this.FileList.DataSource = _imagesFound;
            this.FileList.DataBind();

            //Response.Write(_currentFolder.FullName);
            //Response.Write(Server.MapPath(this._rootPath));

            if (!_currentFolder.FullName.Equals( Server.MapPath(this._rootPath),StringComparison.InvariantCulture))
            {
                DirectoryInfo _parent = _currentFolder.Parent;

                this.go_up_btn.CommandArgument = _parent.FullName + "\\";
                this.go_up_btn.Visible = true;

            }
            else
            {
                this.go_up_btn.Visible = false;
            }
            this.current_folder_name_lbl.Text = this.current_path.Value;
        }
    }
    public static void AssetsConvertLineEndings()
    {
        try
        {
            DirectoryInfo projectDir = new DirectoryInfo(Directory.GetCurrentDirectory());
            if (null == projectDir)
            {
                return;
            }
            foreach (DirectoryInfo subDir in projectDir.GetDirectories())
            {
                if (null == subDir)
                {
                    continue;
                }
                if (subDir.Name.ToUpper().Equals("ASSETS"))
                {
                    AssetsConvertLineEndings(subDir);
                }
            }
        }
        catch (System.Exception ex)
        {
            Debug.LogError(string.Format("Exception={0}", ex));
        }

        AssetDatabase.Refresh();
        Debug.Log(string.Format("{0} Processing is done", DateTime.Now));
    }
Example #10
0
    public void ShowSaveGames(bool show) {
        pauseMenu.transform.FindChild("PauseButtonPanel").GetComponent<CanvasGroup>().alpha = System.Convert.ToSingle(!show);
        pauseMenu.transform.FindChild("PauseButtonPanel").GetComponent<CanvasGroup>().interactable = !show;
        pauseMenu.transform.FindChild("PauseButtonPanel").GetComponent<CanvasGroup>().blocksRaycasts = !show;

        pauseMenu.transform.FindChild("LoadGamePanel").GetComponent<CanvasGroup>().alpha = System.Convert.ToSingle(show);
        pauseMenu.transform.FindChild("LoadGamePanel").GetComponent<CanvasGroup>().interactable = show;
        pauseMenu.transform.FindChild("LoadGamePanel").GetComponent<CanvasGroup>().blocksRaycasts = show;

        var children = new List<GameObject>();
        foreach (Transform child in pauseMenu.transform.FindChild("LoadGamePanel/Scroll View/Viewport/Content"))  {
            children.Add(child.gameObject);
        }
        children.ForEach(child => Destroy(child));

        DirectoryInfo info = new DirectoryInfo(Application.persistentDataPath);
        FileInfo[] files = info.GetFiles("*.fsf").OrderByDescending(p => p.CreationTime).ToArray();
        foreach (FileInfo file in files)
        {
            FileInfo localFile = file;
            string[] parts = System.IO.Path.GetFileNameWithoutExtension(localFile.Name).Split('_');
            GameObject go = Instantiate(Resources.Load("UIPrefabs/SaveGameButton"), Vector3.zero, Quaternion.identity) as GameObject;
            go.transform.SetParent(pauseMenu.transform.FindChild("LoadGamePanel/Scroll View/Viewport/Content"));
            go.transform.localScale = Vector3.one;
            if (parts.Length == 4) {
                go.transform.FindChild("GameDetails").GetComponent<TextMeshProUGUI>().text = string.Format("Administrator : {0}\n{1}, {2} {3}", parts[0], parts[1], parts[2], parts[3].Replace('-', ':'));
            }
            else {
                go.transform.FindChild("GameDetails").GetComponent<TextMeshProUGUI>().text = "UNRECOGNIZED SAVE FILE FORMAT";
            }
            go.transform.GetComponent<Button>().onClick.AddListener(delegate {
                LoadGame(Application.persistentDataPath + "/" + localFile.Name);
            });
        }
    }
    static void WalkDirectoryTree(DirectoryInfo root, DirectoryTree folderTree, Folder currentFolder)
    {
        FileInfo[] files = null;
        DirectoryInfo[] subDirs = null;

        try
        {
            files = root.GetFiles("*.*");
        }

        catch (UnauthorizedAccessException e)
        {
            log.Add(e.Message);
        }

        catch (DirectoryNotFoundException e)
        {
            Console.WriteLine(e.Message);
        }

        if (files != null)
        {
            currentFolder.Files = files.Select(f => new File(f.Name, f.Length)).ToList();

            subDirs = root.GetDirectories();

            currentFolder.ChildFolders = subDirs.Select(d => new Folder(d.Name)).ToList();
            var i = 0;
            foreach (DirectoryInfo dirInfo in subDirs)
            {
                WalkDirectoryTree(dirInfo, folderTree, currentFolder.ChildFolders[i]);
                i++;
            }
        }
    }
    private void RecurseDirectory(string unityPath)
    {
        DirectoryInfo dir = new DirectoryInfo(System.IO.Path.Combine(Application.dataPath, unityPath));

        Debug.Log("Compiling: " + unityPath);

        foreach (FileInfo f in dir.GetFiles("*.prefab"))
        {
            string prefabName = "Assets/" + unityPath + "/" + f.Name;

            GameObject o = (GameObject)AssetDatabase.LoadAssetAtPath(prefabName, typeof(GameObject));
            if (o == null)
                continue;

            PartTools pt = o.GetComponent<PartTools>();
            if (pt == null)
                continue;

            if (pt.production)
            {
                Debug.Log("Compiling: " + prefabName);
                Target.partPrefabs.Add(pt);
            }
            else
            {
                Debug.Log("Skipping: " + prefabName);
            }
        }

        foreach (DirectoryInfo d in dir.GetDirectories())
        {
            RecurseDirectory(unityPath + "/" + d.Name);
        }
    }
Example #13
0
    public void CreateButtons()
    {
        SongButtonList = new List<GameObject>();
        Debug.Log("Createbuttons");
        string path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);
        DirectoryInfo dir = new DirectoryInfo(path + "/DanceDanceAssassination/Steps/");
        FileInfo[] info = dir.GetFiles();
        foreach (FileInfo f in info)
        {
            Debug.Log(f.ToString());
            SongData.Song song = null;
            if (Application.isEditor)
            {
                song = SongData.SongImportExport.LoadSongPath(f.ToString());
            }
            else
            {
                song = SongData.SongImportExport.LoadSongPath(path + "/DanceDanceAssassination/Steps/" + f.ToString());
            }
            //SongData.Song song = SongData.SongImportExport.LoadSongPath(f.ToString());
            GameObject button = Instantiate(ButtonPrefab);
            button.GetComponent<SongSelectButton>().DisplayName = song.DisplayName;
            button.GetComponent<SongSelectButton>().SongDisplayName = song.SongName;
            button.GetComponent<SongSelectButton>().ArtistDisplayName = song.ArtistName;
            button.GetComponent<SongSelectButton>().MusicName = song.MusicName;
            Debug.Log("Musicname is: "+button.GetComponent<SongSelectButton>().MusicName);
            button.GetComponent<SongSelectButton>().SteplistName = f.Name;
            Debug.Log("Steplist is: " + button.GetComponent<SongSelectButton>().SteplistName);

            button.name = song.DisplayName;
            button.SetActive(false);
            SongButtonList.Add(button);
        }
    }
Example #14
0
	internal void getFiles()
	{
		if (System.IO.Directory.Exists(myPath))
		{
			DirectoryInfo dir = new DirectoryInfo(myPath);
			Debug.Log("Looking for files in dir: "+myPath);
			
			FileInfo[] info = dir.GetFiles("*."+extention);
			
			// Get number of files, and set the length for the texture2d array
			int totalFiles =  info.Length;
			slides = new Texture2D[totalFiles];
			
			int i = 0;
			
			//Read all found files
			foreach (FileInfo f in info)
			{
				string filePath = f.Directory + "/" + f.Name;
				Debug.Log("["+i+"] file found: "+filePath);
				
				var bytes     = System.IO.File.ReadAllBytes(filePath);
				var tex         = new Texture2D(1, 1);
				
				tex.LoadImage(bytes);
				slides[i] = tex;
				
				i++;
			}
		}
		else
		{
			Debug.Log ("Directory DOES NOT exist! ");
		}
	}
Example #15
0
	void getMapsInfo()
	{     
		DirectoryInfo dir = new DirectoryInfo(Application.dataPath+"/Maps/");
		FileInfo[] info = dir.GetFiles("*.*");
		foreach (FileInfo f in info) 
		{
			if(f.FullName.EndsWith("meta"))
			{
				continue;
			}

			if(f.FullName.EndsWith("jpg"))
			{
				Texture2D tex = (Texture2D) Resources.Load(f.Name);
				thumbnails.Add(tex);
				Debug.Log ("Thumbnail "+ f.Name + " added!");
				continue;

			}
			lvlNames.Add(f.Name.Replace(".save",""));
			Debug.Log (f.Name.Replace(".save",""));
		}

		//lvl1text.text = lvlNames [1];
		//lvl2text.text = lvlNames [2];

		

	}
Example #16
0
 public static void renameFile(DirectoryInfo directory, FileInfo[] files, int i, string nameNumber)
 {
     Console.WriteLine(directory.Name);
     string newName = directory.FullName+@"\"+directory.Name + "-" + nameNumber+((FileInfo)files[i]).Extension;
     Console.WriteLine(newName);
     File.Move(((FileInfo)files[i]).FullName, newName);
 }
Example #17
0
 public static void CopyFilesRecursively(DirectoryInfo source, DirectoryInfo target)
 {
     foreach (DirectoryInfo dir in source.GetDirectories())
         CopyFilesRecursively(dir, target.CreateSubdirectory(dir.Name));
     foreach (FileInfo file in source.GetFiles())
         file.CopyTo(Path.Combine(target.FullName, file.Name));
 }
Example #18
0
    public static void DeleteOldLogFiles()
    {
        Tools.WriteInfo("Entered DeleteOldLogFiles()");

        try
        {

            DirectoryInfo ofs = new DirectoryInfo(Tools.LogPath);

            foreach (FileInfo oFile in ofs.GetFiles())
            {
                if ((oFile.Extension.ToLower() == ".txt") && ((oFile.Name.ToLower().Contains("info_") == true || oFile.Name.ToLower().Contains("error_") == true)))//&&(oFile.Name.Contains("Volumetric") == true)
                {
                    TimeSpan t1 = System.DateTime.Today.Date.Subtract(oFile.CreationTime.Date);
                    if (t1.TotalDays > 30)
                    {
                        oFile.Delete();
                    }
                }
            }
            ofs = null;

        }
        finally
        {
            Tools.WriteInfo("Exit DeleteOldLogFiles() Successfully.");
            Tools.WriteInfo("--------------------------------------------------------------------------------------------------------------");
        }
    }
Example #19
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Session["LoginStatus"] == null)
            {
                Response.Redirect("Signin.aspx");
            }
        }

        StringBuilder sb = new StringBuilder();
        sb.AppendLine("<table class=\"table table-hover\">");

        sb.AppendLine("<tr><th width=\"50%\">文件名</th><th width=\"20%\">大小</th><th width=\"20%\">修改日期</th><th></th></tr>");

        DirectoryInfo directoryInfo = new DirectoryInfo(pptpath);

        foreach (FileInfo fileinfo in directoryInfo.GetFiles())
        {
            sb.AppendLine("<tr><td><a href=\"./file/ppt/" + fileinfo.Name + "\">" + fileinfo.Name + "</a></td><td>" + fileinfo.Length / 1024 + " KB</td><td>" + fileinfo.LastAccessTime + "</td><td><a class=\"btn btn-small btn-primary\" href=\"./file/ppt/" + fileinfo.Name + "\">下载</a>");
            if (Session["LoginId"].ToString() == "246246" || Session["LoginId"].ToString() == "91225")
            {
                sb.AppendLine("<a class=\"btn btn-danger btn-small\" href=\"DeleteFile.aspx?type=ppt&filename=" + fileinfo.Name + "\">删除</a>");
            }
            sb.AppendLine("</td></tr>");
        }
        sb.AppendLine("<tr><td colspan=\"4\"><a class=\"btn btn-info btn-small\" href=\"AddFile.aspx?type=ppt\">添加</a></td></tr>");
        sb.AppendLine("</table>");
        this.pptTable = sb.ToString();
    }
    static void CreateAnimationAssets()
    {
        string rootFolder = "Assets/Resources/fbx/";
        if (!Directory.Exists(rootFolder))
        {
            Directory.CreateDirectory(rootFolder);
            return;
        }
        // 遍历目录,查找生成controller文件
        var folders = Directory.GetDirectories(rootFolder);
        foreach (var folder in folders)
        {
            DirectoryInfo info = new DirectoryInfo(folder);
            string folderName = info.Name;
            // 创建animationController文件
            AnimatorController aController =
                AnimatorController.CreateAnimatorControllerAtPath(string.Format("{0}/animation.controller", folder));
            // 得到其layer
            var layer = aController.layers[0];
            // 绑定动画文件
            AddStateTranstion(string.Format("{0}/{1}_model.fbx", folder, folderName), layer);
            // 创建预设
            GameObject go = LoadFbx(folderName);
            PrefabUtility.CreatePrefab(string.Format("{0}/{1}.prefab", folder, folderName), go);
            DestroyImmediate(go);
        }


    }
    /// <summary>
    /// Returns 304 (use cached version) code to the client if
    /// file was not changed since last request.
    /// </summary>
    /// <param name="fileInfo">File location information</param>
    /// <returns>True if 304 was returned.</returns>
    public static bool Returned304(DirectoryInfo dirInfo)
    {
        if (!dirInfo.Exists)
            return false;

        return Returned304(dirInfo.LastWriteTime);
    }
Example #22
0
    public void Handler()
    {
        Byte[] byteSent = new Byte[1];
        Byte[] bytesReceived = new Byte[1];
        DirectoryInfo directoryInfo;

        int bytes;
        String data = "";

        String currentByteString = "";
        char currentByteChar;

        while(true)
        {
            while (true)
            {
                bytes = cSocket.Receive(bytesReceived, bytesReceived.Length, 0);

                // Console.WriteLine(Encoding.ASCII.GetString(bytesReceived, 0, bytes));
                currentByteString = System.Text.Encoding.ASCII.GetString(bytesReceived, 0, bytes);
                currentByteChar = currentByteString[0];
                // Console.WriteLine(currentByteChar);

                if (currentByteChar == '\0')
                {
                    Console.WriteLine("*** DEBUG: Found null character, returning directory contents...");

                    break;
                }

                data += currentByteString;

                Console.WriteLine("*** DEBUG: Current data: " + data);
            }

            //Process the data sent by the client.
            if(data == "exit")
            {
                break;
            }

            directoryInfo = new DirectoryInfo(data);

            FileInfo[] fileArray = directoryInfo.GetFiles();
            string files = "";

            foreach (FileInfo fileInfo in fileArray)
            {
                files += fileInfo.Name;
                files += "\n";
            }

            byte[] msg = System.Text.Encoding.ASCII.GetBytes(files);

            // Send request to the server
            cSocket.Send(msg, msg.Length, 0);
        }

        cSocket.Close();
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        DirectoryInfo dir = new DirectoryInfo(MapPath("~/Upload images/"));
        FileInfo[] file = dir.GetFiles();
        ArrayList list = new ArrayList();
        ArrayList listvid = new ArrayList();
        ArrayList listaud = new ArrayList();
        foreach (FileInfo file2 in file)
        {
            if (file2.Extension == ".jpg" || file2.Extension == ".jpeg" || file2.Extension == ".gif" || file2.Extension == ".png")
            {
                list.Add(file2);
            }

            if (file2.Extension == ".mp4")
            {
                listvid.Add(file2);
            }

            if (file2.Extension == ".mp3")
            {
                listaud.Add(file2);
            }
        }

        DataList3.DataSource = listaud;
        DataList3.DataBind();
        DataList1.DataSource = list;
        DataList1.DataBind();

        DataList2.DataSource = listvid;
        DataList2.DataBind();
    }
Example #24
0
    // Use this for initialization
    void Start()
    {
        controller.GetComponent<BoxCollider> ().enabled = false;
        DirectoryInfo dirInfo = new DirectoryInfo("Assets/Resources/Songs");
        FileInfo[] files = dirInfo.GetFiles();
        int index = -2;
        foreach (FileInfo fileInfo in files) {
            if (fileInfo.Extension != ".meta") {
                string name = fileInfo.Name.Split('.')[0];
                GameObject button = Instantiate(buttonPrefab) as GameObject;
                button.transform.FindChild("Text").GetComponent<UnityEngine.UI.Text>().text = name;
                button.GetComponent<ButtonClicked>().name = name;

                button.transform.SetParent(songList.transform);
                Vector3 pos = buttonPrefab.transform.localPosition;
                pos.y += index++ * WIDTH_GAP;
                button.transform.localPosition = pos;
                button.transform.localRotation = buttonPrefab.transform.localRotation;
                button.transform.localScale = buttonPrefab.transform.localScale;
            }
        }

        transform.Find("Score").GetComponent<UnityEngine.UI.Text>().text =
            "Score:" + Player.mScore;
        transform.Find("Combo").GetComponent<UnityEngine.UI.Text>().text =
            "Combo:" + Player.mCombo;
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Session["LoginStatus"] == null)
            {
                Response.Redirect("Signin.aspx");
            }

            if (Session["LoginId"].ToString() == "246246" || Session["LoginId"].ToString() == "91225")
            {
                update = "<a class=\"btn btn-info\" href=\"updateSimulatorApp.aspx\">更新</a>";
            }
        }
        this.DownloadUrl = "./file/Simulator/" + System.Configuration.ConfigurationManager.AppSettings["SimulatorFileName"];
        this.ManualUrl = "./file/Simulator/" + System.Configuration.ConfigurationManager.AppSettings["SimulatorManualName"];
        this.Version = System.Configuration.ConfigurationManager.AppSettings["SimulatorVersion"];

        DirectoryInfo directoryInfo = new DirectoryInfo(System.Configuration.ConfigurationManager.AppSettings["SimulatorLocalPath"]);

        foreach (FileInfo fileinfo in directoryInfo.GetFiles())
        {
            if (fileinfo.Name == ConfigurationManager.AppSettings["SimulatorFileName"])
            {
                this.UpdateTime = fileinfo.LastWriteTime.ToString();
            }
        }
    }
    /// <summary>
    /// Check wether or not the folder is a png folder
    /// </summary>
    /// <returns></returns>
    private bool folderIsPngFolder()
    {
        DirectoryInfo dir = new DirectoryInfo(this.dicomPath);
        FileInfo[] info = dir.GetFiles("*.png*");

        return info.Length > 2;
    }
    public static void enablePromptAfterInstall( bool enable )
    {
        // find all the config.plist files in plugin directories
        string basePath = Path.Combine( Application.dataPath, "Editor" );
        var dirInfo = new DirectoryInfo( basePath );

        var pluginDirs = from dir in dirInfo.GetDirectories()
                            let files = dir.GetFiles( "config.plist" )
                            where files.Length == 1
                            select files[0];

        // loop through our pluginDirs
        foreach( var dir in pluginDirs )
        {
            if( !File.Exists( dir.FullName ) )
                continue;

            // initialize the hashtable and plistKeys
            Hashtable plistContents = new Hashtable();

            PListEditor.loadPlistFromFile( dir.FullName, plistContents );

            if( plistContents.ContainsKey( "neverShowCompletedMessage" ) )
            {
                plistContents["neverShowCompletedMessage"] = !enable;
                PListEditor.savePlistToFile( dir.FullName, plistContents );
            }
        }
    }
Example #28
0
    protected void Page_Load(object sender, EventArgs e)
    {
        DirectoryInfo dir = new DirectoryInfo(MapPath("~/Health_new/p_typhoid"));
        FileInfo[] file = dir.GetFiles();
        ArrayList list = new ArrayList();
        foreach (FileInfo file2 in file)
        {
            if (file2.Extension == ".mp3")
            {
                list.Add(file2);
            }
        }
        DataList1.DataSource = list;
        DataList1.DataBind();

        dir = new DirectoryInfo(MapPath("~/Health_new/d_typhoid"));
        file = dir.GetFiles();
        list = new ArrayList();
        foreach (FileInfo file2 in file)
        {
            if (file2.Extension == ".mp3")
            {
                list.Add(file2);
            }
        }
        DataList2.DataSource = list;
        DataList2.DataBind();
    }
 public static void GetAssets(string extension, Dictionary<string, string> files, DirectoryInfo directory)
 {
     if (null == directory)
     {
         return;
     }
     foreach (FileInfo file in directory.GetFiles(extension))
     {
         if (string.IsNullOrEmpty(file.FullName) ||
             files.ContainsKey(file.FullName.ToLower()))
         {
             continue;
         }
         files.Add(file.FullName.ToLower(), file.FullName);
     }
     foreach (DirectoryInfo subDir in directory.GetDirectories())
     {
         if (null == subDir)
         {
             continue;
         }
         if (subDir.Name.ToUpper().Equals(".SVN"))
         {
             continue;
         }
         //Debug.Log(string.Format("Directory: {0}", subDir));
         GetAssets(extension, files, subDir);
     }
 }
Example #30
0
File: test.cs Project: mono/gert
	static void Main ()
	{
		DirectoryInfo di;
		DirectoryInfo [] dirs;
		FileInfo [] files;

		string basedir = AppDomain.CurrentDomain.BaseDirectory;

		di = new DirectoryInfo (basedir);
		dirs = di.GetDirectories ();
		files = di.GetFiles ();

		Assert.AreEqual (3, dirs.Length, "#A1");
		Assert.AreEqual (".svn", dirs [0].Name, "#A2");
		Assert.AreEqual ("dirB", dirs [1].Name, "#A3");
		Assert.AreEqual ("test", dirs [2].Name, "#A4");

		Assert.AreEqual (4, files.Length, "#B1");
		Assert.AreEqual ("default.build", files [0].Name, "#B2");
		Assert.AreEqual ("fileB.txt", files [1].Name, "#B3");
		Assert.AreEqual ("test.cs", files [2].Name, "#B4");
		Assert.AreEqual ("test.exe", files [3].Name, "#B5");

		di = new DirectoryInfo (Path.Combine (basedir, "dirB"));
		dirs = di.GetDirectories ();
		files = di.GetFiles ();

		Assert.AreEqual (0, dirs.Length, "#C1");

		Assert.AreEqual (1, files.Length, "#D1");
		Assert.AreEqual ("fileA.tmp", files [0].Name, "#D2");
	}
Example #31
0
        public static void Load(string folder)
        {
            if (folder == "")
            {
                folder = Directory.GetCurrentDirectory();
            }
            DirectoryInfo di = new DirectoryInfo(folder);

            foreach (FileInfo fi in di.GetFiles("request.*"))
            {
                TextReader tr = new StreamReader(fi.FullName, Encoding.GetEncoding(1251));

                string email        = "";
                string faction_name = "Faction";
                string gender       = "MAN";
                string chosen_name  = "";
                string special      = "";
                Lang   lng          = Lang.En;
                bool   body         = false;

                while (true)
                {
                    string s = tr.ReadLine();
                    if (s == null)
                    {
                        break;
                    }
                    if (s.Trim() == "")
                    {
                        body = true;
                    }

                    if (s.IndexOf(":") == -1)
                    {
                        continue;
                    }
                    string name = s.Substring(0, s.IndexOf(":")).ToLower();
                    string val  = s.Substring(s.IndexOf(":") + 2);

                    if (name == "from")
                    {
                        email = val;
                    }

                    if (!body)
                    {
                        continue;
                    }

                    if (name == "faction")
                    {
                        faction_name = MyStrings.GetValidString(val);
                    }
                    if (name == "chosen" && val.ToLower() == "woman")
                    {
                        gender = "WOMA";
                    }
                    if (name == "name")
                    {
                        chosen_name = MyStrings.GetValidString(val);
                    }
                    if (name == "language" && val.ToLower() == "ru")
                    {
                        lng = Lang.Ru;
                    }
                    if (name == "skill")
                    {
                        special = val;
                    }
                }
                tr.Close();

                if (email != "")
                {
                    // Create new faction
                    Faction f = new Faction();
                    f.Email        = email;
                    f.Name         = faction_name;
                    f.Options.Lang = lng;
                    for (int i = 0; i < 6; i++)
                    {
                        f.Password += (Char)('a' + Constants.Random('z' - 'a'));
                    }

                    // Select region with less faction players and monsters and more wanderers
                    Region r        = Map.Regions[Constants.Random(Map.Regions.Count)];
                    int    unwanted = 0;
                    int    wanted   = 0;
                    foreach (Person p in r.Persons)
                    {
                        if (!p.Faction.IsNPC || p.Man.IsMonster)
                        {
                            unwanted++;
                        }
                        else
                        {
                            wanted++;
                        }
                    }

                    int j     = Map.Regions.IndexOf(r);
                    int start = j;
                    while (true)
                    {
                        j++;
                        if (j >= Map.Regions.Count)
                        {
                            j = 0;
                        }
                        if (j == start)
                        {
                            break;
                        }
                        Region r2 = Map.Regions[j];
                        if (r2._radiation >= 90 || r2.Radiation >= 90 || !r2.Terrain.Walking)
                        {
                            continue;
                        }
                        int unwanted2 = 0;
                        int wanted2   = 0;
                        foreach (Person p in r2.Persons)
                        {
                            if (!p.Faction.IsNPC || p.Man.IsMonster || p.Insanity >= Constants.DangerousInsanity)
                            {
                                unwanted2++;
                            }
                            else
                            {
                                wanted2++;
                            }
                        }

                        if (unwanted2 < unwanted ||
                            (unwanted2 == unwanted && wanted2 > wanted))
                        {
                            r        = r2;
                            unwanted = unwanted2;
                            wanted   = wanted2;
                        }
                    }

                    if (r._radiation >= 90 || !r.Terrain.Walking)
                    {
                        throw new Exception("What region you picked you?");
                    }

                    // Create Chosen One
                    Person chosen = new Person(f, r);
                    chosen.Chosen = true;
                    if (chosen_name != "")
                    {
                        chosen.Name = chosen_name;
                    }
                    else
                    {
                        chosen.Name = NameGenerator.Name(gender);
                    }
                    chosen.Avoiding = true;

                    chosen.AddItems(ItemType.Get(gender), 1);
                    foreach (Item itm in DataFile.ChosenItems)
                    {
                        chosen.AddItems(itm.Type, itm.Amount);
                    }
                    foreach (Skill sk in DataFile.ChosenSkills)
                    {
                        chosen.AddSkill(sk.Type).Level = sk.Level;
                    }

                    // Special skill
                    if (special != "")
                    {
                        SkillType spec = SkillType.GetByAnyName(special);
                        if (spec != null)
                        {
                            Skill spec_skill = DataFile.ChosenSpecial.GetByType(spec);
                            if (spec_skill != null)
                            {
                                chosen.AddSkill(spec_skill.Type).Level = spec_skill.Level;
                            }
                        }
                    }

                    // Show all buildable objects
                    foreach (Skill sk in chosen.Skills)
                    {
                        foreach (BuildingType bt in BuildingType.List)
                        {
                            if (!bt.NoBuild && bt.Materials.Count > 0 &&
                                bt.Materials[0].Type.InstallSkill.Type == sk.Type)
                            {
                                f.ShowBuilding(bt);
                            }
                        }
                    }

                    Console.WriteLine("..Faction created for " + email);
                }
            }
        }
Example #32
0
    // xxx/Unity.exe -quit -batchmode -executeMethod CommandBuild.BuildAndroid
    public static void BuildAPK(bool release = true, string version = "0.0.1")
    {
        Debug.Log("开始 Build( Android )");
#if !Unity_Android
        Debug.Log("切换到 Android平台");
        EditorUserBuildSettings.SwitchActiveBuildTarget(BuildTargetGroup.Android, BuildTarget.Android);
#endif
        EditorUserBuildSettings.androidBuildSystem           = AndroidBuildSystem.Gradle;
        EditorUserBuildSettings.exportAsGoogleAndroidProject = false;
        PlayerSettings.defaultInterfaceOrientation           = UIOrientation.Portrait;
        PlayerSettings.allowedAutorotateToLandscapeLeft      = true;
        PlayerSettings.allowedAutorotateToLandscapeRight     = true;
        PlayerSettings.allowedAutorotateToPortrait           = false;
        PlayerSettings.allowedAutorotateToPortraitUpsideDown = false;
        PlayerSettings.keyaliasPass  = "******";
        PlayerSettings.keystorePass  = "******";
        PlayerSettings.bundleVersion = version;
        // build option
        BuildOptions opt = BuildOptions.None;
        System.DateTime.Now.Date.ToString();

        string export = "../" + Application.productName + "_" + PlayerSettings.bundleVersion.Replace('.', '_') + "_" + System.DateTime.Now.ToString("yyyyMMddHHmmss");
        //+ ".apk";
        if (release)
        {
            export += "_release.apk";
            PlayerSettings.SetScriptingDefineSymbolsForGroup(BuildTargetGroup.Android, "");
        }
        else
        {
            export += "_debug.apk";
            PlayerSettings.SetScriptingDefineSymbolsForGroup(BuildTargetGroup.Android, "DEBUG_BUILD");
        }

        bool isDebug = false;
        //export 参数 导出目录
        var args  = System.Environment.GetCommandLineArgs();
        int index = Array.IndexOf(args, "-export");
        if (-1 != index)
        {
            export = args[index + 1];
        }
        Debug.Log("##### Export 路径 : " + export);

        index   = Array.IndexOf(args, "-debug");
        isDebug = (-1 != index);
        Debug.Log("##### Debug 版本 : " + isDebug);


        if (isDebug)
        {
            opt |= BuildOptions.Development | BuildOptions.ConnectWithProfiler | BuildOptions.AllowDebugging;
        }

        //opt |= BuildOptions.Il2CPP;
        //PlayerSettings.SetScriptingBackend(BuildTargetGroup.Android, ScriptingImplementation.IL2CPP);

        //opt |= BuildOptions.AcceptExternalModificationsToPlayer;
        var           scenes = GetScenes();
        DirectoryInfo dir    = new DirectoryInfo(export);
        if (dir.Exists)
        {
            dir.Delete(true);
        }
        BuildReport report = BuildPipeline.BuildPlayer(scenes, export, BuildTarget.Android, opt);

        // error check
        if (report.summary.result == BuildResult.Succeeded)
        {
            Debug.Log("Build( Android ) 成功.");
        }
        else
        {
            Debug.Log("Build( Android ) 失败!");
            Debug.LogError(report.summary.result.ToString());
        }
    }
Example #33
0
        public override bool ProcessDataFile(string strDataFilePath, clsDatasetFileInfo datasetFileInfo)
        {
            // Returns True if success, False if an error

            try {
                var ioFolderInfo = new DirectoryInfo(strDataFilePath);
                datasetFileInfo.FileSystemCreationTime     = ioFolderInfo.CreationTime;
                datasetFileInfo.FileSystemModificationTime = ioFolderInfo.LastWriteTime;

                // The acquisition times will get updated below to more accurate values
                datasetFileInfo.AcqTimeStart = datasetFileInfo.FileSystemModificationTime;
                datasetFileInfo.AcqTimeEnd   = datasetFileInfo.FileSystemModificationTime;

                datasetFileInfo.DatasetName   = GetDatasetNameViaPath(ioFolderInfo.Name);
                datasetFileInfo.FileExtension = ioFolderInfo.Extension;

                // Sum up the sizes of all of the files in this folder
                datasetFileInfo.FileSizeBytes = 0;
                var intFileCount = 0;
                foreach (var item in ioFolderInfo.GetFiles())
                {
                    datasetFileInfo.FileSizeBytes += item.Length;

                    if (intFileCount == 0)
                    {
                        // Assign the first file's modification time to .AcqTimeStart and .AcqTimeEnd
                        // Necessary in case _header.txt is missing
                        datasetFileInfo.AcqTimeStart = item.LastWriteTime;
                        datasetFileInfo.AcqTimeEnd   = item.LastWriteTime;
                    }

                    if (item.Name.ToLower() == "_header.txt")
                    {
                        // Assign the file's modification time to .AcqTimeStart and .AcqTimeEnd
                        // These will get updated below to more precise values
                        datasetFileInfo.AcqTimeStart = item.LastWriteTime;
                        datasetFileInfo.AcqTimeEnd   = item.LastWriteTime;
                    }

                    intFileCount += 1;
                }

                datasetFileInfo.ScanCount = 0;

                var objNativeFileIO = new clsMassLynxNativeIO();

                if (objNativeFileIO.GetFileInfo(ioFolderInfo.FullName, out var udtHeaderInfo))
                {
                    var dtNewStartDate = DateTime.Parse(udtHeaderInfo.AcquDate + " " + udtHeaderInfo.AcquTime);

                    var intFunctionCount = objNativeFileIO.GetFunctionCount(ioFolderInfo.FullName);

                    if (intFunctionCount > 0)
                    {
                        // Sum up the scan count of all of the functions
                        // Additionally, find the largest EndRT value in all of the functions
                        float sngEndRT = 0;
                        for (var intFunctionNumber = 1; intFunctionNumber <= intFunctionCount; intFunctionNumber++)
                        {
                            if (objNativeFileIO.GetFunctionInfo(ioFolderInfo.FullName, 1, out clsMassLynxNativeIO.udtMSFunctionInfoType udtFunctionInfo))
                            {
                                datasetFileInfo.ScanCount += udtFunctionInfo.ScanCount;
                                if (udtFunctionInfo.EndRT > sngEndRT)
                                {
                                    sngEndRT = udtFunctionInfo.EndRT;
                                }
                            }
                        }

                        if (dtNewStartDate >= MINIMUM_ACCEPTABLE_ACQ_START_TIME)
                        {
                            datasetFileInfo.AcqTimeStart = dtNewStartDate;

                            if (sngEndRT > 0)
                            {
                                datasetFileInfo.AcqTimeEnd = datasetFileInfo.AcqTimeStart.Add(MinutesToTimeSpan(sngEndRT));
                            }
                            else
                            {
                                datasetFileInfo.AcqTimeEnd = datasetFileInfo.AcqTimeStart;
                            }
                        }
                        else
                        {
                            // Keep .AcqTimeEnd as the file modification date
                            // Set .AcqTimeStart based on .AcqEndTime
                            if (sngEndRT > 0)
                            {
                                datasetFileInfo.AcqTimeStart = datasetFileInfo.AcqTimeEnd.Subtract(MinutesToTimeSpan(sngEndRT));
                            }
                            else
                            {
                                datasetFileInfo.AcqTimeEnd = datasetFileInfo.AcqTimeStart;
                            }
                        }
                    }
                    else
                    {
                        if (dtNewStartDate >= MINIMUM_ACCEPTABLE_ACQ_START_TIME)
                        {
                            datasetFileInfo.AcqTimeStart = dtNewStartDate;
                        }
                    }
                }
                else
                {
                    // Error getting the header info using clsMassLynxNativeIO
                    // Continue anyway since we've populated some of the values
                }

                return(true);
            } catch (Exception) {
                return(false);
            }
        }
        private void ConvertFiles(DirectoryInfo source, DirectoryInfo target)
        {
            _errorFile = null;

            FileSvgConverter fileConverter = new FileSvgConverter(this.SaveXaml,
                                                                  this.SaveZaml, this.DrawingSettings);

            fileConverter.Background            = this.Background;
            fileConverter.FallbackOnWriterError = _fallbackOnWriterError;

            string targetDirName = target.ToString();
            string xamlFilePath;

            IEnumerable <string> fileIterator = DirectoryUtils.FindFiles(
                source, "*.*", SearchOption.TopDirectoryOnly);

            foreach (string svgFileName in fileIterator)
            {
                string fileExt = Path.GetExtension(svgFileName);
                if (string.Equals(fileExt, ".svg", StringComparison.OrdinalIgnoreCase) ||
                    string.Equals(fileExt, ".svgz", StringComparison.OrdinalIgnoreCase))
                {
                    try
                    {
                        FileAttributes fileAttr = File.GetAttributes(svgFileName);
                        if (!_includeHidden)
                        {
                            if ((fileAttr & FileAttributes.Hidden) == FileAttributes.Hidden)
                            {
                                continue;
                            }
                        }

                        xamlFilePath = Path.Combine(targetDirName,
                                                    Path.GetFileNameWithoutExtension(svgFileName) + ".xaml");

                        fileConverter.Convert(svgFileName, xamlFilePath);

                        File.SetAttributes(xamlFilePath, fileAttr);
                        // if required to set the security or access control
                        if (_includeSecurity)
                        {
                            File.SetAccessControl(xamlFilePath, File.GetAccessControl(svgFileName));
                        }

                        _convertedCount++;

                        if (fileConverter.WriterErrorOccurred)
                        {
                            _writerErrorOccurred = true;
                        }
                    }
                    catch
                    {
                        _errorFile = svgFileName;

                        throw;
                    }
                }
            }
        }
        public void mySearch()
        {
            endSearch = false;

            DirectoryInfo DirInf       = null;
            StreamReader  StreamReader = StreamReader.Null;

            if (txtSearchTerm != null)
            {
                SearchTerm = txtSearchTerm.Text;
                log("SearchTerm set");
            }

            if (FolderLocation != null)
            {
                DirInf = new DirectoryInfo(FolderLocation);
                log("DirectoryInfo initialized");
            }

            List <FileInfo> Files = new List <FileInfo>();

            Files.AddRange(DirInf.GetFiles("*.txt"));
            if (Files.Count > 0)
            {
                log("Files populated\n");
            }
            else
            {
                log("No Files Found!");
            }

            txtLog.AppendText("Lines: ");

            string currentLine;
            int    fileCount  = 0;
            int    count      = 0;
            int    startIndex = txtLog.TextLength;

            new Thread(() => new ControlForm().ShowDialog()).Start();

            foreach (FileInfo fInf in Files)
            {
                fileCount++;
                lblFiles.Text = fileCount.ToString();
                StreamReader  = fInf.OpenText();
                while (!StreamReader.EndOfStream && !endSearch)
                {
                    count++;
                    currentLine = StreamReader.ReadLine();
                    if (currentLine.Contains(SearchTerm))
                    {
                        output(currentLine);
                        txtLog.Text = txtLog.Text.Remove(startIndex, txtLog.TextLength - startIndex);
                        log(count.ToString());
                    }
                    txtLog.Text = txtLog.Text.Remove(startIndex, txtLog.TextLength - startIndex);
                    log(count.ToString());
                    lineCount = count;
                    updateLabel();
                }
            }
            StreamReader.Close();

            output("Runtime: " + timeTook);
            controlForm.Close();
        }
        public FileSystemVirtualDirectory(IVirtualPathProvider owningProvider, IVirtualDirectory parentDirectory, DirectoryInfo dInfo)
            : base(owningProvider, parentDirectory)
        {
            if (dInfo == null)
                throw new ArgumentNullException("dInfo");

            this.BackingDirInfo = dInfo;
        }
        public static bool Compile(bool debug)
        {
            Console.Write("Compiling scripts: ");

            if (m_AdditionalReferences != null)
            {
                throw new ApplicationException("already compiled");
            }

            m_AdditionalReferences = new ArrayList();

            libraries = new ArrayList();
            libraries.Add(new Library(Core.Config.GetLibraryConfig("core"),
                                      "core", Core.Assembly));
            m_AdditionalReferences.Add(Core.ExePath);

            /* first compile ./Scripts/ for RunUO compatibility */
            string compatScripts = Path.Combine(Core.BaseDirectory, "Scripts");

            if (Directory.Exists(compatScripts))
            {
                bool result = Compile("legacy", compatScripts,
                                      Core.Config.GetLibraryConfig("legacy"),
                                      debug);
                if (!result)
                {
                    return(false);
                }
            }

            /* now compile all libraries in ./local/src/ */
            DirectoryInfo srcDir = Core.LocalDirectoryInfo
                                   .CreateSubdirectory("src");

            foreach (DirectoryInfo sub in srcDir.GetDirectories())
            {
                string libName = sub.Name.ToLower();
                if (libName == "core" || libName == "legacy")
                {
                    Console.WriteLine("Warning: the library name '{0}' is invalid",
                                      libName);
                    continue;
                }

                bool result = Compile(libName, sub.FullName,
                                      Core.Config.GetLibraryConfig(libName),
                                      debug);
                if (!result)
                {
                    return(false);
                }
            }

            /* delete unused cache directories */
            DirectoryInfo cacheDir = Core.CacheDirectoryInfo
                                     .CreateSubdirectory("lib");

            foreach (DirectoryInfo sub in cacheDir.GetDirectories())
            {
                string libName = sub.Name.ToLower();
                if (GetLibrary(sub.Name) == null)
                {
                    sub.Delete(true);
                }
            }

            /* load libraries from ./local/lib/ */
            DirectoryInfo libDir = Core.LocalDirectoryInfo
                                   .CreateSubdirectory("lib");

            foreach (FileInfo libFile in libDir.GetFiles("*.dll"))
            {
                string fileName = libFile.Name;
                string libName  = fileName.Substring(0, fileName.Length - 4).ToLower();

                if (libName == "core" || libName == "legacy")
                {
                    Console.WriteLine("Warning: the library name '{0}' is invalid",
                                      libName);
                    continue;
                }

                if (GetLibrary(libName) != null)
                {
                    Console.WriteLine("Warning: duplicate library '{0}' in ./local/src/{1}/ and ./local/lib/{2}",
                                      libName, libName, fileName);
                    continue;
                }

                libraries.Add(new Library(Core.Config.GetLibraryConfig(libName),
                                          libName,
                                          Assembly.LoadFrom(libFile.FullName)));
                m_AdditionalReferences.Add(libFile.FullName);
            }

            /* done */
            Console.WriteLine();

            return(true);
        }
        private static bool Compile(string name, string path,
                                    LibraryConfig libConfig,
                                    bool debug)
        {
            DirectoryInfo cache = Core.CacheDirectoryInfo
                                  .CreateSubdirectory("lib")
                                  .CreateSubdirectory(name);

            if (!cache.Exists)
            {
                Console.WriteLine("Failed to create directory {0}", cache.FullName);
                return(false);
            }

            string    csFile = Path.Combine(cache.FullName, name + ".dll");
            Hashtable files  = GetScripts(libConfig, path, "*.cs");

            if (files.Count > 0)
            {
                string stampFile = Path.Combine(cache.FullName, name + ".stm");
                if (File.Exists(csFile) && CheckStamps(files, stampFile))
                {
                    libraries.Add(new Library(libConfig, name,
                                              Assembly.LoadFrom(csFile)));
                    m_AdditionalReferences.Add(csFile);
                    Console.Write("{0}. ", name);
                }
                else
                {
                    CompilerResults results = CompileCSScripts(name, files.Keys,
                                                               csFile,
                                                               libConfig,
                                                               debug);
                    if (results != null)
                    {
                        if (results.Errors.HasErrors)
                        {
                            return(false);
                        }
                        libraries.Add(new Library(libConfig, name,
                                                  results.CompiledAssembly));
                        WriteStampFile(stampFile, files);
                    }
                }
            }

            string vbFile = Path.Combine(cache.FullName, name + "-vb.dll");

            files = GetScripts(libConfig, path, "*.vb");
            if (files.Count > 0)
            {
                string stampFile = Path.Combine(cache.FullName, name + "-vb.stm");
                if (File.Exists(vbFile) && CheckStamps(files, stampFile))
                {
                    libraries.Add(new Library(libConfig, name,
                                              Assembly.LoadFrom(vbFile)));
                    m_AdditionalReferences.Add(vbFile);
                    Console.Write("{0}/VB. ", name);
                }
                else
                {
                    CompilerResults results = CompileVBScripts(name, files.Keys, vbFile,
                                                               libConfig,
                                                               debug);
                    if (results != null)
                    {
                        if (results.Errors.HasErrors)
                        {
                            return(false);
                        }
                        libraries.Add(new Library(libConfig, name,
                                                  results.CompiledAssembly));
                    }
                }
            }

            return(true);
        }
Example #39
0
        private void opProj1_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog FBD        = new FolderBrowserDialog();
            OpenFileDialog      OFD        = new OpenFileDialog();
            ListView            item       = new ListView();
            DirectoryInfo       dir        = new DirectoryInfo(ProjectPath);
            ReviewForm1         newProject = new ReviewForm1();

            try
            {
                OFD.Multiselect      = true;
                OFD.Filter           = "XML | *.xml";
                OFD.Title            = "Please open a valid reference file:";
                OFD.RestoreDirectory = true;
                OFD.ShowDialog();

                if (OFD.ShowDialog() == DialogResult.OK)
                {
                    foreach (string fileDir in Directory.EnumerateFiles(ProjectPath))
                    {
                        projectView1.Items.Clear();
                        //info.Paths = imgList1.Items.ToString();
                        projectView1.Items.Add(OFD.FileName);
                    }

                    foreach (string file in Directory.EnumerateDirectories(ProjectPath))
                    {
                        DirectoryInfo dirInfo = new DirectoryInfo(file);
                        this.projectView1.Items.Add(dirInfo.Name);
                    }
                }
                else
                {
                    MessageBox.Show("Please select valid reference file(s).");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "ProjectForm1", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            string          constring   = "Data Source= C:/Xamarin_Projects/Old/042514/ScreenshotReviewer2/ScreenshotReviewerDB1.sdf";
            string          Query       = "Select tblData1.*, tblInfo1.*, tblProject.*, tblUsers1.* from tblData1 CROSS JOIN tblInfo1 CROSS JOIN tblProject CROSS JOIN tblUsers1;";
            SqlCeConnection conDataBase = new SqlCeConnection(constring);
            SqlCeCommand    cmdDataBase = new SqlCeCommand(Query, conDataBase);
            SqlCeDataReader myReader;

            try
            {
                conDataBase.Open();
                myReader = cmdDataBase.ExecuteReader();
                string        Tags        = (string)myReader["Tags"];
                string        UserName    = (string)myReader["UserName"];
                string        Role        = (string)myReader["Role"];
                Image         ImageData1  = (Image)myReader["ImageData1"];
                Image         ImageData2  = (Image)myReader["ImageData2"];
                string        Lang        = (string)myReader["Lang"];
                string        Name        = (string)myReader["Name"];
                string        ImageStatus = (string)myReader["ImageStatus"];
                string        Path        = (string)myReader["Path"];
                string        Progress    = (string)myReader["Progress"];
                string        ProjectName = (string)myReader["ProjectName"];
                string        Comment     = (string)myReader["Comment"];
                XmlSerializer xs          = new XmlSerializer(typeof(Information1));
                FileStream    readXML     = new FileStream(OFD.FileName, FileMode.Open, FileAccess.Read, FileShare.Read);
                Information1  info        = (Information1)xs.Deserialize(readXML);

                while (myReader.Read())
                {
                    ReviewForm1.Comments1.Text    = Comment;
                    ReviewForm1.ImageData1        = ImageData1;
                    ReviewForm1.ImageData2        = ImageData2;
                    ReviewForm1.ImageStatus1.Text = ImageStatus;
                    ReviewForm1.ImageStatus2.Text = ImageStatus;
                    ReviewForm1.ImageStatus3.Text = ImageStatus;
                    ReviewForm1.ImageStatus4.Text = ImageStatus;
                    ReviewForm1.Tags1.Text        = Tags;
                    usrName1.Text          = UserName;
                    ReviewForm1.Lang1.Text = Lang;
                    ReviewForm1.Lang2.Text = Lang;
                    ReviewForm1.Lang3.Text = Lang;
                    ReviewForm1.Lang4.Text = Lang;
                    ReviewForm1.Lang5.Text = Lang;
                    ReviewForm1.Lang6.Text = Lang;
                    //ReviewForm1.ImagePath.Text =
                    newProject.ShowDialog();
                    readXML.Close();
                    conDataBase.Close();
                }
                this.Hide();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "ProjectForm1", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Example #40
0
    // xxx/Unity.exe -quit -batchmode -executeMethod CommandBuild.BuildAndroid
    public static void BuildAndroid()
    {
        Debug.Log("开始 Build( Android )");
#if !Unity_Android
        Debug.Log("切换到 Android平台");
        EditorUserBuildSettings.SwitchActiveBuildTarget(BuildTargetGroup.Android, BuildTarget.Android);
#endif
        EditorUserBuildSettings.androidBuildSystem           = AndroidBuildSystem.Gradle;
        EditorUserBuildSettings.exportAsGoogleAndroidProject = true;
        PlayerSettings.defaultInterfaceOrientation           = UIOrientation.Portrait;
        PlayerSettings.allowedAutorotateToLandscapeLeft      = true;
        PlayerSettings.allowedAutorotateToLandscapeRight     = true;
        PlayerSettings.allowedAutorotateToPortrait           = false;
        PlayerSettings.allowedAutorotateToPortraitUpsideDown = false;
        // build option
        BuildOptions opt     = BuildOptions.None;
        string       export  = "../Output";
        bool         isDebug = false;
        //export 参数 导出目录
        var args  = System.Environment.GetCommandLineArgs();
        int index = Array.IndexOf(args, "-export");
        if (-1 != index)
        {
            export = args[index + 1];
        }
        Debug.Log("##### Export 路径 : " + export);

        index   = Array.IndexOf(args, "-debug");
        isDebug = (-1 != index);
        Debug.Log("##### Debug 版本 : " + isDebug);

        if (isDebug)
        {
            PlayerSettings.SetScriptingDefineSymbolsForGroup(BuildTargetGroup.Android, "DEBUG_BUILD");
            opt |= BuildOptions.Development | BuildOptions.ConnectWithProfiler | BuildOptions.AllowDebugging;
        }
        else
        {
        }

        //opt |= BuildOptions.Il2CPP;
        opt |= BuildOptions.AcceptExternalModificationsToPlayer;
        var           scenes = GetScenes();
        DirectoryInfo dir    = new DirectoryInfo(export);
        if (dir.Exists)
        {
            dir.Delete(true);
        }
        BuildReport report = BuildPipeline.BuildPlayer(scenes, export, BuildTarget.Android, opt);

        // error check
        if (report.summary.result == BuildResult.Succeeded)
        {
            Debug.Log("Build( Android ) 成功.");
        }
        else
        {
            Debug.Log("Build( Android ) 失败!");
            Debug.LogError(report.summary.result.ToString());
        }
    }
Example #41
0
	/// <summary>
	/// 转换Excel文件
	/// </summary>
	private static void Convert()
	{
		PlayerPrefs.SetString("sourcePath", sourcePath);
		PlayerPrefs.SetString("targetPath", targetPath);
		//D:/ExcalToTxt/Assets/sourcefile/Pass.xlsx
		//"D:/ExcalToTxt/Assets/sourcefilePass.xlsx"
		DirectoryInfo direction = new DirectoryInfo(sourcePath);
        FileInfo[] alldatatabletext = direction.GetFiles();
        for (int i = 0; i < alldatatabletext.Length; i++)
        {
            if (alldatatabletext[i].Name.EndsWith(".xlsx"))
            {
                //获取Excel文件的绝对路径
                string excelPath = sourcePath +"/"+ alldatatabletext[i].Name;

				string txtPath = targetPath + "/" + alldatatabletext[i].Name;
				//构造Excel工具类
				ExcelUtility excel = new ExcelUtility(excelPath);

                //判断编码类型
                Encoding encoding = null;
                if (indexOfEncoding == 0)
                {
                    encoding = Encoding.GetEncoding("utf-8");
                }
                else if (indexOfEncoding == 1)
                {
                    encoding = Encoding.GetEncoding("gb2312");
                }

                //判断输出类型
                string output = "";
                if (indexOfFormat == 0)
                {
					output = txtPath.Replace(".xlsx", ".txt");
					excel.ConvertToCSV(output, encoding);
					
                }
                else if (indexOfFormat == 1)
                {
					output = txtPath.Replace(".xlsx", ".json");
					excel.ConvertToJson(output, encoding);
				}
                else if (indexOfFormat == 2)
                {
                    output = txtPath.Replace(".xlsx", ".xml");
                    excel.ConvertToXml(output);
                }

                //判断是否保留源文件
                if (!keepSource)
                {
                    FileUtil.DeleteFileOrDirectory(excelPath);
                }

                //刷新本地资源
                AssetDatabase.Refresh();
            }
        }
        /*foreach (string assetsPath in excelList)
        {
            //获取Excel文件的绝对路径
            string excelPath = pathRoot + "/" + assetsPath;
            //构造Excel工具类
            ExcelUtility excel = new ExcelUtility(excelPath);

            //判断编码类型
            Encoding encoding = null;
            if (indexOfEncoding == 0)
            {
                encoding = Encoding.GetEncoding("utf-8");
            }
            else if (indexOfEncoding == 1)
            {
                encoding = Encoding.GetEncoding("gb2312");
            }

            //判断输出类型
            string output = "";
            if (indexOfFormat == 0)
            {
                output = excelPath.Replace(".xlsx", ".json");
                excel.ConvertToJson(output, encoding);
            }
            else if (indexOfFormat == 1)
            {
                output = excelPath.Replace(".xlsx", ".txt");
                excel.ConvertToCSV(output, encoding);
            }
            else if (indexOfFormat == 2)
            {
                output = excelPath.Replace(".xlsx", ".xml");
                excel.ConvertToXml(output);
            }

            //判断是否保留源文件
            if (!keepSource)
            {
                FileUtil.DeleteFileOrDirectory(excelPath);
            }

            //刷新本地资源
            AssetDatabase.Refresh();
        }*/

        //转换完后关闭插件
        //这样做是为了解决窗口
        //再次点击时路径错误的Bug
        //instance.Close();

    }
Example #42
0
        static void Main(string[] args)
        {
            string path;

            if (args.Length > 0)
            {
                path = args[0];
            }
            else
            {
                Console.Write("Path: ");
                path = Console.ReadLine().Trim('"');
            }
            path = Path.GetFullPath(path);
            if (path.EndsWith(".ini"))
            {
                path = Path.GetDirectoryName(path);
            }
            string  mtnfn = new DirectoryInfo(path).Name;
            MTNInfo info  = IniSerializer.Deserialize <MTNInfo>(Path.Combine(path, mtnfn + ".ini"));
            string  fext  = null;

            switch (info.ModelFormat)
            {
            case ModelFormat.Basic:
            case ModelFormat.BasicDX:
                fext = "*.sa1mdl";
                break;

            case ModelFormat.Chunk:
                fext = "*.sa2mdl";
                break;

            case ModelFormat.GC:
                fext = "*.sa2bmdl";
                break;
            }
            SortedDictionary <int, NJS_OBJECT> mdls = new SortedDictionary <int, NJS_OBJECT>();

            foreach (string fn in Directory.EnumerateFiles(path, fext))
            {
                if (int.TryParse(Path.GetFileNameWithoutExtension(fn), out int i) && i >= 0 && i < info.Frames)
                {
                    mdls[i] = new ModelFile(fn).Model;
                }
            }
            NJS_OBJECT first   = mdls.First().Value;
            int        nodecnt = first.CountMorph();

            int[]        vcnt  = new int[nodecnt];
            ushort[][]   polys = new ushort[nodecnt][];
            NJS_OBJECT[] nodes = first.GetObjects().Where(a => a.Morph).ToArray();
            for (int i = 0; i < nodecnt; i++)
            {
                switch (nodes[i].Attach)
                {
                case BasicAttach batt:
                    vcnt[i] = batt.Vertex.Length;
                    List <ushort> plist = new List <ushort>();
                    foreach (NJS_MESHSET mesh in batt.Mesh)
                    {
                        foreach (Poly p in mesh.Poly)
                        {
                            plist.AddRange(p.Indexes);
                        }
                    }
                    polys[i] = plist.ToArray();
                    break;

                case ChunkAttach catt:
                    if (catt.Vertex != null)
                    {
                        vcnt[i] = catt.Vertex.Sum(a => a.VertexCount);
                    }
                    plist = new List <ushort>();
                    foreach (PolyChunkStrip pcs in catt.Poly.OfType <PolyChunkStrip>())
                    {
                        foreach (PolyChunkStrip.Strip s in pcs.Strips)
                        {
                            plist.AddRange(s.Indexes);
                        }
                    }
                    polys[i] = plist.ToArray();
                    break;
                }
            }
            NJS_MOTION mtn = new NJS_MOTION()
            {
                Name = info.Name, Frames = info.Frames, InterpolationMode = info.InterpolationMode, ModelParts = nodecnt
            };

            foreach ((int frame, NJS_OBJECT mdl) in mdls)
            {
                NJS_OBJECT[] nodes2 = mdl.GetObjects().Where(a => a.Morph).ToArray();
                if (nodes2.Length != nodecnt)
                {
                    Console.WriteLine("Warning: Model {0} skeleton does not match first file!", frame);
                    if (nodes2.Length > mtn.ModelParts)
                    {
                        mtn.ModelParts = nodes2.Length;
                    }
                }
                for (int i = 0; i < nodes2.Length; i++)
                {
                    switch (nodes2[i].Attach)
                    {
                    case BasicAttach batt:
                        if (batt.Vertex.Length != vcnt[i])
                        {
                            Console.WriteLine("Warning: Model {0} node {1} vertex count does not match first file!", frame, i);
                        }
                        AnimModelData amd;
                        if (!mtn.Models.TryGetValue(i, out amd))
                        {
                            amd = new AnimModelData()
                            {
                                VertexName = mtn.MdataName + "_vtx_" + i, NormalName = mtn.MdataName + "_nor_" + i
                            };
                            mtn.Models[i] = amd;
                        }
                        amd.Vertex[frame] = batt.Vertex;
                        if (batt.Normal != null)
                        {
                            amd.Normal[frame] = batt.Normal;
                        }
                        List <ushort> plist = new List <ushort>();
                        foreach (NJS_MESHSET mesh in batt.Mesh)
                        {
                            foreach (Poly p in mesh.Poly)
                            {
                                plist.AddRange(p.Indexes);
                            }
                        }
                        if (!polys[i].SequenceEqual(plist))
                        {
                            Console.WriteLine("Warning: Model {0} node {1} poly data does not match first file!", frame, i);
                        }
                        break;

                    case ChunkAttach catt:
                        if (catt.Vertex != null)
                        {
                            if (catt.Vertex.Sum(a => a.VertexCount) != vcnt[i])
                            {
                                Console.WriteLine("Warning: Model {0} node {1} vertex count does not match first file!", frame, i);
                            }
                            if (!mtn.Models.TryGetValue(i, out amd))
                            {
                                amd = new AnimModelData()
                                {
                                    VertexName = mtn.MdataName + "_vtx_" + i, NormalName = mtn.MdataName + "_nor_" + i
                                };
                                mtn.Models[i] = amd;
                            }
                            amd.Vertex[frame] = catt.Vertex.SelectMany(a => a.Vertices).ToArray();
                            if (catt.Vertex.All(a => a.Normals != null))
                            {
                                amd.Normal[frame] = catt.Vertex.SelectMany(a => a.Normals).ToArray();
                            }
                        }
                        plist = new List <ushort>();
                        foreach (PolyChunkStrip pcs in catt.Poly.OfType <PolyChunkStrip>())
                        {
                            foreach (PolyChunkStrip.Strip s in pcs.Strips)
                            {
                                plist.AddRange(s.Indexes);
                            }
                        }
                        polys[i] = plist.ToArray();
                        break;
                    }
                }
            }
            foreach ((int _, AnimModelData amd) in mtn.Models)
            {
                amd.VertexItemName = Enumerable.Range(0, amd.Vertex.Count).Select(a => amd.VertexName + "_" + a).ToArray();
                if (amd.Normal.Count > 0)
                {
                    amd.NormalItemName = Enumerable.Range(0, amd.Normal.Count).Select(a => amd.NormalName + "_" + a).ToArray();
                }
            }
            mtn.Save(Path.Combine(path, $"{mtnfn}.saanim"));
        }
Example #43
0
        /// <summary>
        ///   Clears a folder based on specified conditions</summary>
        /// <param name="directoryToClean">
        ///   Folder to be cleared</param>
        /// <param name="autoExpireTime">
        ///   Files with creation time older than this is deleted. If passed as 0, time
        ///   based cleanup is skipped.</param>
        /// <param name="maxFilesInDirectory">
        ///   If more than this number of files exists, files will be deleted starting from
        ///   oldest to newest. By passing 0, all files can be deleted. If passed as -1,
        ///   file count based cleanup is skipped.</param>
        /// <param name="checkFileName">
        ///   Safety file to be checked. If it is specified and it doesn't exists, operation
        ///   is aborted.</param>
        /// <remarks>
        ///   If any errors occur during cleanup, this doesn't raise an exception
        ///   and ignored. Other errors might raise an exception. As errors are
        ///   ignored, method can't gurantee that less than specified number of files
        ///   will be in the folder after it ends.</remarks>
        public static void PurgeDirectory(string directoryToClean,
                                          TimeSpan autoExpireTime, int maxFilesInDirectory, string checkFileName)
        {
            checkFileName = checkFileName ?? String.Empty;
            if (checkFileName.Length > 0)
            {
                checkFileName = System.IO.Path.GetFileName(checkFileName).Trim();
                if (!System.IO.File.Exists(System.IO.Path.Combine(directoryToClean, checkFileName)))
                {
                    return;
                }
            }

            // get folder information
            DirectoryInfo directoryInfo = new DirectoryInfo(directoryToClean);

            // if no time condition, or all files are to be deleted (maxFilesInDirectory = 0)
            // no need for this part
            if (autoExpireTime.Ticks != 0 && maxFilesInDirectory != 0)
            {
                // subtract limit from now and find lower limit for files to be deleted
                DateTime autoExpireLimit = DateTime.Now.Subtract(autoExpireTime);

                // traverse all files and if older than limit, try to delete
                Array.ForEach <FileInfo>(
                    Array.FindAll <FileInfo>(
                        directoryInfo.GetFiles(),
                        delegate(FileInfo fi) { return(fi.CreationTime < autoExpireLimit); }),
                    delegate(FileInfo fiOld)
                {
                    if (!checkFileName.Equals(fiOld.Name, StringComparison.OrdinalIgnoreCase))
                    {
                        try
                        {
                            if (Log.DebugLevel)
                            {
                                Log.Debug("Deleting Expired Temporary File : " + fiOld.Name);
                            }
                            fiOld.Delete();
                        }
                        catch
                        {
                        }
                    }
                });
            }

            // if maxFilesInDirectory is -1 than no count based deletion
            if (maxFilesInDirectory >= 0)
            {
                // list all files
                FileInfo[] files = directoryInfo.GetFiles();

                // if count is above limit
                if (files.Length > maxFilesInDirectory)
                {
                    // if not all files are going to be deleted, sort them by date
                    if (maxFilesInDirectory != 0)
                    {
                        Array.Sort <FileInfo>(files,
                                              delegate(FileInfo x, FileInfo y)
                                              { return(x.CreationTime < y.CreationTime ? -1 : 1); });
                    }

                    // delete all before last "maxFilesInDirectory" files.
                    for (int i = 0; i < files.Length - maxFilesInDirectory; i++)
                    {
                        if (!checkFileName.Equals(files[i].Name, StringComparison.OrdinalIgnoreCase))
                        {
                            try
                            {
                                if (Log.DebugLevel)
                                {
                                    Log.Debug("MaxFiles Passed, Deleting Temporary File : " + files[i].Name);
                                }
                                files[i].Delete();
                            }
                            catch
                            {
                            }
                        }
                    }
                }
            }
        }
        /// <summary> Moves the incoming digital resource folder, along with all files and subdirectories, to a new location </summary>
        /// <param name="DestinationDirectory"> New location for this incoming digital resource </param>
        /// <returns> TRUE if successful, otherwise FALSE </returns>
        public bool Move(string DestinationDirectory)
        {
            try
            {
                // Make sure the destination directory exists
                if (!Directory.Exists(DestinationDirectory))
                {
                    Directory.CreateDirectory(DestinationDirectory);
                }

                // Determine the new folder for this
                DirectoryInfo dirInfo    = new DirectoryInfo(resourceFolder);
                string        destFolder = DestinationDirectory + dirInfo.Name;

                // Does this directory appear to be a VID folder, with a BibID folder above it?
                // If so, we will flatten this folder structure
                string thisDirName = dirInfo.Name.ToUpper().Replace("VID", "");
                if ((thisDirName.Length == 5) && (SobekCM_Item.is_vids_format(thisDirName)))
                {
                    // Is the parent directory is a bibid format, we will flatten this a Bib ID?
                    string bibidCheck = Directory.GetParent(resourceFolder).Name;
                    if (SobekCM_Item.is_bibid_format(bibidCheck))
                    {
                        // Flatten this bibi/vid structure then and make the new destination folder bibid_vid
                        destFolder = DestinationDirectory + bibidCheck + "_" + dirInfo.Name.ToUpper().Replace("VID", "");
                    }
                    else if (bibidCheck.Length == 2)
                    {
                        // Put in special code for directories dropped in builder from resource folder
                        // That is, look for the pair-tree format
                        string check = bibidCheck;
                        int    count = 0;
                        while ((Directory.GetParent(bibidCheck) != null) && (count < 4))
                        {
                            string parent = Directory.GetParent(bibidCheck).Name;
                            if (parent.Length != 2)
                            {
                                check = String.Empty;
                                break;
                            }

                            check = check + parent;
                            count++;
                        }

                        if (check.Length == 10)
                        {
                            destFolder = DestinationDirectory + check + "_" + dirInfo.Name.ToUpper().Replace("VID", "");
                        }
                    }
                }

                // If the destination directory exists, delete it
                if (Directory.Exists(destFolder))
                {
                    Directory.Delete(destFolder, true);
                }

                // Move this directory
                Directory.Move(resourceFolder, destFolder);
                resourceFolder = destFolder;

                // If the parent directory is empty, try to delete it
                string parentDir = resourceFolder;
                while ((Directory.GetParent(parentDir) != null) && (Directory.GetParent(parentDir).GetFiles().Length == 0))
                {
                    parentDir = Directory.GetParent(parentDir).FullName;
                    try
                    {
                        Directory.Delete(parentDir);
                    }
                    catch (Exception)
                    {
                        // If unable to delete the directory, not the worst thing
                    }
                }

                return(true);
            }
            catch
            {
                return(false);
            }
        }
Example #45
0
        private static bool TryRecursiveFolderDelete(List <Breadcrumb> breadcrumbs, string path)
        {
            DirectoryInfo directory = new DirectoryInfo(path);

            breadcrumbs.Add(new Breadcrumb(BreadcrumbType.BeginRecurseIntoDirectory, path));

            try
            {
                try
                {
                    foreach (FileInfo file in directory.GetFiles())
                    {
                        try
                        {
                            file.Attributes = FileAttributes.Normal;
                        }
                        catch (ArgumentException)
                        {
                            // Setting the attributes will throw an ArgumentException in situations where
                            // it really ought to throw IOExceptions, e.g. because the file is currently locked
                            return(false);
                        }

                        if (!TryDelete(breadcrumbs, file))
                        {
                            return(false);
                        }
                    }

                    foreach (DirectoryInfo subDirectory in directory.GetDirectories())
                    {
                        if (!TryRecursiveFolderDelete(breadcrumbs, subDirectory.FullName))
                        {
                            return(false);
                        }
                    }
                }
                catch (DirectoryNotFoundException e)
                {
                    // For junctions directory.GetFiles() or .GetDirectories() can throw DirectoryNotFoundException
                    breadcrumbs.Add(new Breadcrumb(BreadcrumbType.DeleteFailed, path, e));
                }
                catch (IOException e)
                {
                    // There is a race when enumerating while a virtualization instance is being shut down
                    // If GVFlt receives the enumeration request before it knows that GVFS has been shut down
                    // (and then GVFS does not handle the request because it is shut down) we can get an IOException
                    breadcrumbs.Add(new Breadcrumb(BreadcrumbType.DeleteFailed, path, e));
                    return(false);
                }

                if (!TryDelete(breadcrumbs, directory))
                {
                    return(false);
                }

                return(true);
            }
            finally
            {
                breadcrumbs.Add(new Breadcrumb(BreadcrumbType.EndRecurseIntoDirectory, path));
            }
        }
Example #46
0
        /// <summary>
        /// Initializes a new instance of the <see cref="XmlObject"/> class
        /// for reading and/or writing.
        ///
        /// If the file does not exists it will be created.
        /// </summary>
        /// <exception cref="ArgumentNullException">
        /// When <paramref name="fallbackxmlcontent"/> or <paramref name="xmlfilename"/> is <see langword="null"/> or <see cref="string.Empty"/>.
        /// </exception>
        /// <param name="xmlfilename">
        /// The name of the XML File to load into the <see cref="XmlObject"/>.
        /// </param>
        /// <param name="fallbackxmlcontent">
        /// The fallback content string to write into the fallback XML File
        /// if the file does not exist or if the file is empty.
        /// </param>
        /// <param name="saveToCurrentDirectory">
        /// Controls weather to save the file to the xmlfilename param string if
        /// it is the full path or to the Current Directory if it supplies file name only.
        /// This implies that that file is saved to the fully qualified path of the
        /// current working directory prefixed before the filename.
        /// </param>
        public XmlObject(string xmlfilename, string fallbackxmlcontent, bool saveToCurrentDirectory)
        {
            if (string.IsNullOrEmpty(xmlfilename))
            {
                throw new ArgumentNullException(nameof(xmlfilename) /*, "'xmlfilename' cannot be null or empty."*/);
            }

            if (string.IsNullOrEmpty(fallbackxmlcontent))
            {
                throw new ArgumentNullException(nameof(fallbackxmlcontent) /*, "'fallbackxmlcontent' cannot be null or empty."*/);
            }

            this.ObjLock                  = new object();
            this.ElementsAdded            = new Dictionary <string, XmlElementData>();
            this.ElementsEdits            = new Dictionary <string, XmlElementData>();
            this.ElementAttributesDeleted = new Dictionary <string, XmlElementData>();
            this.ElementsDeleted          = new List <string>();
            if (saveToCurrentDirectory)
            {
                var directory = new DirectoryInfo(xmlfilename);
                if (!directory.Parent.Exists)
                {
                    throw new DirectoryNotFoundException(Resources.XmlObject_Directory_Not_Found);
                }

#if NET40 || NET45 || NET451 || NET452 || NET46 || NET461 || NET462 || NET47 || NET471 || NET472 || NET48 || NETCOREAPP2_0 || NETSTANDARD2_0
                if (!xmlfilename.Contains(Directory.GetCurrentDirectory()) &&
#else
                if (!xmlfilename.Contains(Directory.GetCurrentDirectory(), StringComparison.Ordinal) &&
#endif
                    directory.Parent.FullName == Directory.GetCurrentDirectory())
                {
                    xmlfilename = Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + xmlfilename;
                }
            }

#if NET40 || NET45 || NET451 || NET452 || NET46 || NET461 || NET462 || NET47 || NET471 || NET472 || NET48 || NETCOREAPP2_0 || NETSTANDARD2_0
            if (!fallbackxmlcontent.Contains("<?xml version=\"1.0\" encoding=\"utf-8\" ?>"))
#else
            if (!fallbackxmlcontent.Contains("<?xml version=\"1.0\" encoding=\"utf-8\" ?>", StringComparison.Ordinal))
#endif
            {
                // insert root element at begginning of string data.
                fallbackxmlcontent = fallbackxmlcontent.Insert(0, "<?xml version=\"1.0\" encoding=\"utf-8\" ?>");
            }

            long fileSize = 0;
            this.CachedXmlfilename = xmlfilename;
            if (!xmlfilename.Equals(":memory", StringComparison.Ordinal))
            {
                this.Exists     = File.Exists(xmlfilename);
                this.HasChanged = !this.Exists;
                var fileinfo = new FileInfo(xmlfilename);
                if (!fileinfo.Directory.Exists)
                {
                    throw new DirectoryNotFoundException(Resources.XmlObject_Directory_Not_Found);
                }

                if (this.Exists)
                {
                    fileSize = fileinfo.Length;
                }
            }

            this.Doc = fileSize > 0 ? XDocument.Load(xmlfilename) : XDocument.Parse(fallbackxmlcontent);
        }
Example #47
0
 public static string GetTestDirectory()
 {
     var directory = new DirectoryInfo(ExecutingDirectory);
     return Path.Combine(directory.Parent.Parent.Parent.FullName, "test");
 }
        static void PrintAttendanceSheet(string input_path, string output_path, List <Class> classes)
        {
            // Fetch attendance data
            var total_attendance = new List <Attendance>();
            {
                var dir_info = new DirectoryInfo(input_path);
                foreach (var file_info in dir_info.GetFiles("*.csv").OrderBy(f => f.LastWriteTime))
                {
                    var attendance = new Attendance()
                    {
                        Date      = file_info.LastWriteTime,
                        Attendees = new HashSet <string>(),
                    };

                    var lines = File.ReadAllLines(file_info.FullName);
                    for (int i = 1; i < lines.Length; i++)
                    {
                        var first_cell = lines[i].Split('\t')[0];
                        attendance.Attendees.Add(first_cell);
                    }

                    total_attendance.Add(attendance);
                }
            }

            // Print excel result sheet
            {
                // Boot Excel
                var instance = new Excel.Application();
                instance.Visible       = false;
                instance.DisplayAlerts = false;
                var             workbook  = instance.Workbooks.Add();
                Excel.Worksheet worksheet = workbook.Worksheets.Add();

                // Set base background color
                Excel.Range big_chunk = worksheet.Range[
                    worksheet.Cells[1, 1],
                    worksheet.Cells[100, 100]
                                        ];
                big_chunk.Interior.Color        = Excel.XlRgbColor.rgbOrange;
                big_chunk.Interior.TintAndShade = 0.8;

                // Fill cells with data
                {
                    var top_row_offset        = 1;
                    var attendance_col_offset = 4;

                    for (int i = 0; i < total_attendance.Count; i++)
                    {
                        var attendance = total_attendance[i];
                        var cell       = worksheet.Cells[top_row_offset, attendance_col_offset + i];
                        cell.Value = "'" + attendance.Date.ToString("dd/MM", CultureInfo.InvariantCulture);
                        cell.Interior.TintAndShade = 0.6;
                    }

                    var start_row_offset = top_row_offset;
                    foreach (var @class in classes)
                    {
                        PrintStudentAttendance(worksheet, @class, start_row_offset, total_attendance, attendance_col_offset);
                        start_row_offset += @class.Names.Count + 2;
                    }
                }

                // Save Excel sheet
                workbook.SaveAs(output_path);
                workbook.Close();
                instance.Quit();
            }
        }
Example #49
0
        public ActionResult ViewStorefront(string url)
        {
            var culture = _wca.GetContext().CurrentCulture.Trim();
            var cultureUsed = culture == "en-SG" ? "en-SG" : (culture == "id-ID" ? "id-ID" : "en-MY");
            var storeFront = _storeService.GetStoreByUrl(url);
            if (storeFront.Campaigns[0].CampaignRecord.CampaignCulture != cultureUsed)
            {
                _cookieCultureService.SetCulture(storeFront.Campaigns[0].CampaignRecord.CampaignCulture);
                return RedirectToAction("ViewStorefront", new { url = url });
            }
            var campaigns = _campaignService.GetCampaignsOfUser(int.Parse(storeFront.TeeyootUserId.ToString())).Where(c => c.IsApproved).ToList();
            var model = new StoreViewModel();
            model.Campaigns = campaigns;

            var destFolder = Path.Combine(Server.MapPath("/Media/Storefronts/"), storeFront.TeeyootUserId.ToString(), storeFront.Id.ToString());
            DirectoryInfo dir = new DirectoryInfo(destFolder);

            if (dir.Exists == true)
            {
                foreach (FileInfo fi in dir.GetFiles())
                {
                    model.Img = "/Media/Storefronts/" + storeFront.TeeyootUserId.ToString() + "/" + storeFront.Id.ToString() + "/" + fi.Name;
                }
            }
            if (model.Img == null)
            {
                model.Img = "/Media/Default/images/storefront.png";
            }
            model.Title = storeFront.Title;
            model.Description = storeFront.Description;
            IList<CampaignRecord> selectedCamp = new List<CampaignRecord>();
            foreach (var camp in storeFront.Campaigns)
            {
                selectedCamp.Add(camp.CampaignRecord);
            }
            model.SelectedCampaigns = selectedCamp;
            model.CrossSelling = storeFront.CrossSelling;
            model.HideStore = storeFront.HideStore;
            model.Url = storeFront.Url;
            model.Id = storeFront.Id;
            ViewBag.PriceConversionService = _priceConversionService;

            var user = _wca.GetContext().CurrentUser;
            
                if (user != null)
                {
                    var teeyootUser = user.ContentItem.Get(typeof(TeeyootUserPart));

                    if (teeyootUser.Id == storeFront.TeeyootUserId)
                    {
                        return View(model);
                    }
                    else
                    {

                        if (!storeFront.HideStore)
                        {
                            return View("StorefrontForClient", model);
                        }
                        else
                        {
                            return View("NotFound", Request.UrlReferrer != null ? Request.UrlReferrer.PathAndQuery : "");
                        }
                    }
                }
                else
                {
                    if (!storeFront.HideStore)
                    {
                        return View("StorefrontForClient", model);
                    }
                    else
                    {
                        return View("NotFound", Request.UrlReferrer != null ? Request.UrlReferrer.PathAndQuery : "");
                    }
                    
                }
           
        }
Example #50
0
        public Client(uint appId)
        {
            if (Instance != null)
            {
                throw new System.Exception("Only one Facepunch.Steamworks.Client can exist - dispose the old one before trying to create a new one.");
            }

            Instance = this;
            native   = new Interop.NativeInterface();

            //
            // Get other interfaces
            //
            if (!native.InitClient(this))
            {
                native.Dispose();
                native   = null;
                Instance = null;
                return;
            }

            //
            // Setup interfaces that client and server both have
            //
            SetupCommonInterfaces();

            //
            // Client only interfaces
            //
            Voice             = new Voice(this);
            ServerList        = new ServerList(this);
            LobbyList         = new LobbyList(this);
            App               = new App(this);
            Stats             = new Stats(this);
            Achievements      = new Achievements(this);
            MicroTransactions = new MicroTransactions(this);
            User              = new User(this);
            RemoteStorage     = new RemoteStorage(this);

            Workshop.friends = Friends;

            Stats.UpdateStats();

            //
            // Cache common, unchanging info
            //
            AppId        = appId;
            Username     = native.friends.GetPersonaName();
            SteamId      = native.user.GetSteamID();
            BetaName     = native.apps.GetCurrentBetaName();
            OwnerSteamId = native.apps.GetAppOwner();
            var appInstallDir = native.apps.GetAppInstallDir(AppId);

            if (!String.IsNullOrEmpty(appInstallDir) && Directory.Exists(appInstallDir))
            {
                InstallFolder = new DirectoryInfo(appInstallDir);
            }
            BuildId            = native.apps.GetAppBuildId();
            CurrentLanguage    = native.apps.GetCurrentGameLanguage();
            AvailableLanguages = native.apps.GetAvailableGameLanguages().Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries); // TODO: Assumed colon separated



            //
            // Run update, first call does some initialization
            //
            Update();
        }
Example #51
0
 public VlcMediaPlayer(DirectoryInfo vlcLibDirectory)
     : this(VlcManager.GetInstance(vlcLibDirectory))
 {
 }
Example #52
0
 public static void EmptyTempFolder()
 {
     var directory = new DirectoryInfo(TempFolder);
     foreach (FileInfo file in directory.GetFiles()) file.Delete();
     foreach (DirectoryInfo subDirectory in directory.GetDirectories()) subDirectory.Delete(true);
 }
Example #53
0
    public static bool ExportAssetBundleFolders(AssetBundleWindow thisWindow)
    {
        //To keep track of the versions with the control file
        Dictionary<string, int> bundleVersions = new Dictionary<string, int>();

        //A list of all the assets in each bundle
        //This will be saved into the file bundleContents.txt;
        Dictionary<string, List<string>> bundleContents = new Dictionary<string, List<string>>();

        //The AssetBundle folder
        string path = Application.dataPath + thisWindow.exportLocation;

        //The folder location in the editor
        string assetBundleFolderLocation = thisWindow.assetBundleFolderLocation;

        //Create directory if it does not exist
        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
        }
        //Read and parse the control file
        ReadBundleControlFile(path + bundleControlFileName, bundleVersions);
        //Read and parse the contents file
        ReadBundleContentsFile(path + bundleContentsFileName, bundleContents);

		//Check if the directory exist
        if (!Directory.Exists(Application.dataPath + assetBundleFolderLocation))
        {
            Debug.LogError("Specified 'AssetBundles folder' does not exist! Open Assets->Bundle Creator->Asset Bundle Creator to correct it");
            return false;
        }

        int createdBundles = 0;
        string[] directoryNames = Directory.GetDirectories(Application.dataPath + assetBundleFolderLocation);
        foreach (string folderPath in directoryNames)
        {
            //Generate the name of this asset bundle
            DirectoryInfo dirInfo = new DirectoryInfo(folderPath);

            //if the user has specified a build target, add a prefix to the bundle name
            string bundleName = "";
			string directoryName = dirInfo.Name;
			if(thisWindow.setLowerCaseName)
			{
				directoryName = directoryName.ToLower();
			}
			
            if (!thisWindow.optionalSettings)
            {
                bundleName = directoryName + thisWindow.bundleFileExtension;
            }
            else
            {
                bundleName = thisWindow.buildTarget.ToString().ToLower() + "_" + directoryName + thisWindow.bundleFileExtension;
            }

            List<Object> toInclude = new List<Object>();
            string[] assetsInFolder = Directory.GetFiles(folderPath);

            //To save in the contents file(information)
            List<string> assetListInFolder = new List<string>();

            foreach (string asset in assetsInFolder)
            {
                string thisFileName = Path.GetFileName(asset);
                if (asset.EndsWith(".prefab"))
                {
                    string internalFilePath = "Assets" + assetBundleFolderLocation + dirInfo.Name + "/" + thisFileName;
                    GameObject prefab = (GameObject)Resources.LoadAssetAtPath(internalFilePath, typeof(GameObject));
                    toInclude.Add((Object)prefab);

                    assetListInFolder.Add(thisFileName);
                }
                else if (!asset.EndsWith(".meta"))
                {
                    //toInclude.AddRange(AssetDatabase.LoadAllAssetsAtPath(assetBundleFolderLocation + dirInfo.Name + "/" + thisFileName));
					string internalFilePath = "Assets" + assetBundleFolderLocation + dirInfo.Name + "/" + thisFileName;
                    toInclude.Add((Object)Resources.LoadAssetAtPath(internalFilePath, typeof(Object)));
                    assetListInFolder.Add(thisFileName);
                }
            }

            //Build only if there are any files in this folder
            if (toInclude.Count > 0)
            {
                //Check if the bundle already have been created
                if (bundleContents.ContainsKey(bundleName))
                {
                    bundleContents.Remove(bundleName);
                }
                //Add to the contents text file
                bundleContents.Add(bundleName, assetListInFolder);

                Debug.Log("Building bundle:" + bundleName);
                if (!BuildAssetBundle(thisWindow, toInclude, path + bundleName))
                {
                    return false; //It failed, abort everything
                }
                createdBundles++;

                //Checks to save the version numbers
                int versionNumber = -1;
                bundleVersions.TryGetValue(bundleName, out versionNumber);

                if (versionNumber == -1)
                {
                    versionNumber = 1;
                }
                else
                {
                    versionNumber++;
                    bundleVersions.Remove(bundleName);
                }
                bundleVersions.Add(bundleName, versionNumber);
            }
            toInclude.Clear();
        }

        WriteBundleControlFile(path + bundleControlFileName, bundleVersions, path);
        WriteBundleContentsFile(path + bundleContentsFileName, bundleContents, path);
        bundleVersions.Clear();
        foreach (KeyValuePair<string, List<string>> pair in bundleContents)
        {
            pair.Value.Clear();
        }
        bundleContents.Clear();

        Debug.Log("***Successfully Created " + createdBundles + " AssetBundles!***");
        return true;
    }
Example #54
0
 public AlbumResult(DirectoryInfo dir)
 {
     Album = new AlbumData();
     Directory = dir;
 }
        /// <summary>
        /// Does the Analysis
        /// Returns a DataTable
        /// </summary>
        /// <param name="fiSegmentOfSourceFile"></param>
        /// <param name="configDict"></param>
        /// <param name="diOutputDir"></param>
        /// <param name="opFileName"></param>
        /// <param name="segmentStartOffset"></param>
        /// <param name="config"></param>
        /// <param name="segmentAudioFile"></param>
        public static Tuple <BaseSonogram, double[, ], double[], List <AcousticEvent>, TimeSpan> Analysis(FileInfo fiSegmentOfSourceFile, Dictionary <string, string> configDict, DirectoryInfo diOutputDir, string opFileName, TimeSpan segmentStartOffset)
        {
            //set default values
            int    bandWidth          = 500; //detect bars in bands of this width.
            int    frameSize          = 1024;
            double windowOverlap      = 0.0;
            double intensityThreshold = double.Parse(configDict[key_INTENSITY_THRESHOLD]);
            //intensityThreshold = 0.01;

            AudioRecording recording = AudioRecording.GetAudioRecording(fiSegmentOfSourceFile, RESAMPLE_RATE, diOutputDir.FullName, opFileName);

            if (recording == null)
            {
                LoggedConsole.WriteLine("############ WARNING: Recording could not be obtained - likely file does not exist.");
                return(null);
            }
            int      sr                   = recording.SampleRate;
            double   binWidth             = recording.SampleRate / (double)frameSize;
            double   frameDuration        = frameSize / (double)sr;
            double   frameOffset          = frameDuration * (1 - windowOverlap); //seconds between start of each frame
            double   framesPerSecond      = 1 / frameOffset;
            TimeSpan tsRecordingtDuration = recording.Duration;
            int      colStep              = (int)Math.Round(bandWidth / binWidth);

            //i: GET SONOGRAM AS MATRIX
            double epsilon  = Math.Pow(0.5, recording.BitsPerSample - 1);
            var    results2 = DSP_Frames.ExtractEnvelopeAndAmplSpectrogram(recording.WavReader.Samples, sr, epsilon, frameSize, windowOverlap);

            double[] avAbsolute = results2.Average;                //average absolute value over the minute recording
            //double[] envelope = results2.Item2;
            double[,] spectrogram = results2.AmplitudeSpectrogram; //amplitude spectrogram. Note that column zero is the DC or average energy value and can be ignored.
            double windowPower = results2.WindowPower;

            //############################ NEXT LINE FOR DEBUGGING ONLY
            //spectrogram = GetTestSpectrogram(spectrogram.GetLength(0), spectrogram.GetLength(1), 0.01, 0.03);

            var output         = DetectGratingEvents(spectrogram, colStep, intensityThreshold);
            var amplitudeArray = output.Item2; //for debug purposes only

            //convert List of Dictionary events to List of ACousticevents.
            //also set up the hits matrix.
            int rowCount       = spectrogram.GetLength(0);
            int colCount       = spectrogram.GetLength(1);
            var hitsMatrix     = new double[rowCount, colCount];
            var acousticEvents = new List <AcousticEvent>();

            double minFrameCount = 8; //this assumes that the minimum grid is 2 * 4 = 8 long

            foreach (Dictionary <string, double> item in output.Item1)
            {
                int minRow     = (int)item[key_START_FRAME];
                int maxRow     = (int)item[key_END_FRAME];
                int frameCount = maxRow - minRow + 1;
                if (frameCount < minFrameCount)
                {
                    continue;                             //only want events that are over a minimum length
                }
                int    minCol      = (int)item[key_MIN_FREQBIN];
                int    maxCol      = (int)item[key_MAX_FREQBIN];
                double periodicity = item[key_PERIODICITY];

                double[] subarray = DataTools.Subarray(avAbsolute, minRow, maxRow - minRow + 1);
                double   severity = 0.1;
                int[]    bounds   = DataTools.Peaks_CropToFirstAndLast(subarray, severity);
                minRow = minRow + bounds[0];
                maxRow = minRow + bounds[1];
                if (maxRow >= rowCount)
                {
                    maxRow = rowCount - 1;
                }

                Oblong o  = new Oblong(minRow, minCol, maxRow, maxCol);
                var    ae = new AcousticEvent(segmentStartOffset, o, results2.NyquistFreq, frameSize, frameDuration, frameOffset, frameCount);
                ae.Name            = string.Format("p={0:f0}", periodicity);
                ae.Score           = item[key_SCORE];
                ae.ScoreNormalised = item[key_SCORE] / 0.5;
                acousticEvents.Add(ae);

                //display event on the hits matrix
                for (int r = minRow; r < maxRow; r++)
                {
                    for (int c = minCol; c < maxCol; c++)
                    {
                        hitsMatrix[r, c] = periodicity;
                    }
                }
            } //foreach

            //set up the songogram to return. Use the existing amplitude sonogram
            int bitsPerSample = recording.WavReader.BitsPerSample;
            //NoiseReductionType nrt = SNR.Key2NoiseReductionType("NONE");
            NoiseReductionType nrt = SNR.KeyToNoiseReductionType("STANDARD");
            var sonogram           = (BaseSonogram)SpectrogramStandard.GetSpectralSonogram(recording.BaseName, frameSize, windowOverlap, bitsPerSample, windowPower, sr, tsRecordingtDuration, nrt, spectrogram);

            sonogram.DecibelsNormalised = new double[sonogram.FrameCount];
            for (int i = 0; i < sonogram.FrameCount; i++) //foreach frame or time step
            {
                sonogram.DecibelsNormalised[i] = 2 * Math.Log10(avAbsolute[i]);
            }
            sonogram.DecibelsNormalised = DataTools.normalise(sonogram.DecibelsNormalised);

            return(Tuple.Create(sonogram, hitsMatrix, amplitudeArray, acousticEvents, tsRecordingtDuration));
        } //Analysis()
        public void GenerateSchemaForDirectoryInfo()
        {
            JsonSchemaGenerator generator = new JsonSchemaGenerator();

            generator.UndefinedSchemaIdHandling = UndefinedSchemaIdHandling.UseTypeName;
            generator.ContractResolver          = new CustomDirectoryInfoMapper();

            JsonSchema schema = generator.Generate(typeof(DirectoryInfo), true);

            string json = schema.ToString();

            Assert.AreEqual(@"{
  ""id"": ""System.IO.DirectoryInfo"",
  ""type"": [
    ""object"",
    ""null""
  ],
  ""additionalProperties"": false,
  ""properties"": {
    ""Name"": {
      ""type"": [
        ""string"",
        ""null""
      ]
    },
    ""Parent"": {
      ""$ref"": ""System.IO.DirectoryInfo""
    },
    ""Exists"": {
      ""type"": ""boolean""
    },
    ""FullName"": {
      ""type"": [
        ""string"",
        ""null""
      ]
    },
    ""Extension"": {
      ""type"": [
        ""string"",
        ""null""
      ]
    },
    ""CreationTime"": {
      ""type"": ""string""
    },
    ""CreationTimeUtc"": {
      ""type"": ""string""
    },
    ""LastAccessTime"": {
      ""type"": ""string""
    },
    ""LastAccessTimeUtc"": {
      ""type"": ""string""
    },
    ""LastWriteTime"": {
      ""type"": ""string""
    },
    ""LastWriteTimeUtc"": {
      ""type"": ""string""
    },
    ""Attributes"": {
      ""type"": ""integer""
    }
  }
}", json);

            DirectoryInfo temp = new DirectoryInfo(@"c:\temp");

            JTokenWriter   jsonWriter = new JTokenWriter();
            JsonSerializer serializer = new JsonSerializer();

            serializer.Converters.Add(new IsoDateTimeConverter());
            serializer.ContractResolver = new CustomDirectoryInfoMapper();
            serializer.Serialize(jsonWriter, temp);

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

            jsonWriter.Token.Validate(schema, (sender, args) => errors.Add(args.Message));

            Assert.AreEqual(0, errors.Count);
        }
        public static DataTable AnalysisReturnsDataTable(int iter, FileInfo fiSegmentOfSourceFile, Dictionary <string, string> configDict, DirectoryInfo diOutputDir)
        {
            string opFileName = "temp.wav";
            //######################################################################
            var results = Analysis(fiSegmentOfSourceFile, configDict, diOutputDir, opFileName, TimeSpan.Zero);

            //######################################################################

            if (results == null)
            {
                return(null);
            }
            var sonogram          = results.Item1;
            var hits              = results.Item2;
            var scores            = results.Item3;
            var predictedEvents   = results.Item4;
            var recordingTimeSpan = results.Item5;

            double    segmentDuration    = double.Parse(configDict[key_SEGMENT_DURATION]);
            double    segmentStartMinute = segmentDuration * iter;
            DataTable dataTable          = null;

            if ((predictedEvents == null) || (predictedEvents.Count == 0))
            {
                LoggedConsole.WriteLine("############ WARNING: No acoustic events were returned from the analysis.");
            }
            else
            {
                string analysisName = configDict[key_ANALYSIS_NAME];
                string fName        = Path.GetFileNameWithoutExtension(fiSegmentOfSourceFile.Name);
                foreach (AcousticEvent ev in predictedEvents)
                {
                    ev.FileName = fName;
                    //ev.Name = analysisName; //name is the periodicity
                    ev.SegmentDurationSeconds = recordingTimeSpan.TotalSeconds;
                }
                //write events to a data table to return.
                dataTable = WriteEvents2DataTable(segmentStartMinute, recordingTimeSpan, predictedEvents);
                string sortString = key_START_ABS + " ASC";
                dataTable = DataTableTools.SortTable(dataTable, sortString); //sort by start time before returning
            }

            //draw images of sonograms
            int  DRAW_SONOGRAMS = int.Parse(configDict[key_DRAW_SONOGRAMS]);        // options to draw sonogram
            bool saveSonogram   = false;

            if ((DRAW_SONOGRAMS == 2) || ((DRAW_SONOGRAMS == 1) && (predictedEvents.Count > 0)))
            {
                saveSonogram = true;
            }
            if (saveSonogram)
            {
                double eventThreshold = 0.1;
                string imagePath      = Path.Combine(diOutputDir.FullName, Path.GetFileNameWithoutExtension(fiSegmentOfSourceFile.FullName) + "_" + (int)segmentStartMinute + "min.png");
                Image  image          = DrawSonogram(sonogram, hits, scores, predictedEvents, eventThreshold);
                image.Save(imagePath, ImageFormat.Png);
            }

            return(dataTable);
        }
        public static Image AnalysisReturnsSonogram(int iter, FileInfo fiSegmentOfSourceFile, Dictionary <string, string> configDict, DirectoryInfo diOutputDir)
        {
            double segmentDuration             = double.Parse(configDict[key_SEGMENT_DURATION]);
            double segmentStartMinute          = segmentDuration * iter;
            string newFileNameWithoutExtention = Path.GetFileNameWithoutExtension(fiSegmentOfSourceFile.FullName) + "_" + (int)segmentStartMinute + "min";
            string opFileName = newFileNameWithoutExtention + ".wav";

            //######################################################################
            var results = Analysis(fiSegmentOfSourceFile, configDict, diOutputDir, opFileName, TimeSpan.Zero);
            //######################################################################
            var sonogram          = results.Item1;
            var hits              = results.Item2;
            var scores            = results.Item3;
            var predictedEvents   = results.Item4;
            var recordingTimeSpan = results.Item5;

            LoggedConsole.WriteLine("\tRecording Duration: {0:f2}seconds", recordingTimeSpan.TotalSeconds);

            double eventThreshold = 0.1;
            Image  image          = DrawSonogram(sonogram, hits, scores, predictedEvents, eventThreshold);
            string imagePath      = Path.Combine(diOutputDir.FullName, newFileNameWithoutExtention + ".png");

            image.Save(imagePath, ImageFormat.Png);
            return(image);
        }
 private static bool IsSolutionRoot(DirectoryInfo dir)
 {
     return File.Exists(Path.Combine(dir.FullName, "SmartStoreNET.sln"));
 }
Example #60
0
        public static void CopyDirectory(string oldDir, string newDir)
        {
            DirectoryInfo od = new DirectoryInfo(oldDir);

            CopyDirInfo(od, oldDir, newDir);
        }