private bool AlreadyDownloaded(FileData saveFile, DateTime fileTimestamp)
        {
            //Check to see if our on disk zip is up to date
            if (File.Exists(saveFile.TimestampFile) && File.Exists(saveFile.DiskFile))
            {
                string timestamp;

                using (var reader = new StreamReader(saveFile.TimestampFile))
                {
                    timestamp = reader.ReadToEnd();
                }

                DateTime lastAccess;

                if (DateTime.TryParse(timestamp, out lastAccess))
                {
                    if (lastAccess == fileTimestamp)
                        return true;
                }

                return false;
            }

            //Create directory since it doesn't exist
            Directory.CreateDirectory(Path.GetDirectoryName(saveFile.DiskFile));

            return false;
        }
        public void CanSerializeBinaryFileWithContentType()
        {
            using (MemoryStream s = new MemoryStream())
              {
            FileData data = new FileData
            {
              MyString = "Abc ÆØÅ",
              MyFile = new Ramone.IO.File("..\\..\\data1.gif", "image/gif")
            };
            new MultipartFormDataSerializer(typeof(FileData)).Serialize(s, data, Encoding.UTF8, "xyzq");

            string expected = @"
            --xyzq
            Content-Disposition: form-data; name=""MyString""
            Content-Type: text/plain; charset=utf-8

            Abc ÆØÅ
            --xyzq
            Content-Disposition: form-data; name=""MyFile""; filename=""data1.gif""
            Content-Type: image/gif

            ";

            s.Seek(0, SeekOrigin.Begin);
            using (StreamReader r = new StreamReader(s))
            {
              string result = r.ReadToEnd();
              if (!result.StartsWith(expected))
            Console.Write(string.Format("Expected: \n{0}\n\nGot:\n{1}", expected, result));
              Assert.IsTrue(result.StartsWith(expected), "Serialized result must begin with expected value (see console output)");
            }
              }
        }
Example #3
0
        private void AddFile(string filename)
        {
            DateTime date = DateFromFile(filename);
            try
            {
                DateTime dateFromName = DateFromFilename(filename);
                if (date.Equals(dateFromName))
                {
                    WriteLog(filename + " has same creation datetime. ignored");
                    return;
                }
            }
            catch (FormatException)
            {
                // ignore
            }

            foreach (ListViewItem i in lvFiles.Items)
            {
                if (i.Tag.Equals(filename))
                    return;
            }

            FileData fileData = new FileData(filename);
            ListViewItem item = new ListViewItem();
            item.Tag = fileData;
            fileData.SyncTo(item);

            lvFiles.Items.Add(item);
        }
Example #4
0
        private static void CollectFiles(string folder)
        {
            Shell32.Shell shell = new Shell32.Shell();
            Shell32.Folder objFolder = shell.NameSpace(folder);

            foreach (Shell32.FolderItem2 item in objFolder.Items())
            {
                if (item.IsFolder)
                    CollectFiles(item.Path);
                else
                {
                    if (!item.Type.ToUpper().StartsWith("MP3") && !item.Type.ToUpper().StartsWith("MPEG"))
                    {
                        LogError(item.Name + " has unsuupported file type of " + item.Type);
                        continue;
                    }
                    FileData fileData = new FileData();
                    fileData.name = item.Name;
                    fileData.size = item.Size;
                    fileData.modified = item.ModifyDate;
                    fileData.path = item.Path;
                    fileData.type = item.Type;
                    int.TryParse(objFolder.GetDetailsOf(item, yearID), out fileData.year);
                    string properName = fileData.name.Split(new char[] { '.' })[0];
                    if (dict.ContainsKey(fileData.size))
                    {
                        LogError(fileData.name + " clashed with " + dict[fileData.size].name);
                        count++;
                    }
                    dict[fileData.size] = fileData;
                }
            }
        }
        public void CannotSerializeFileWithInternationalCharactersInFilenameWhenSettingsDisallowIt()
        {
            ObjectSerializerSettings settings = new ObjectSerializerSettings();
              settings.EnableNonAsciiCharactersInMultipartFilenames = false;

              using (MemoryStream s = new MemoryStream())
              {
            FileData data = new FileData
            {
              MyFile = new FileWithSpecialName("..\\..\\data1.txt", "Bøllefrø.txt")
            };
            new MultipartFormDataSerializer(typeof(FileData)).Serialize(s, data, Encoding.UTF8, "xyzq", settings);

            string expected = @"
            --xyzq
            Content-Disposition: form-data; name=""MyFile""; filename=""Bxllefrx.txt""

            Æüî´`'";

            s.Seek(0, SeekOrigin.Begin);
            using (StreamReader r = new StreamReader(s))
            {
              string result = r.ReadToEnd();
              Assert.AreEqual(expected, result);
            }
              }
        }
 public void ConvertToControls(FileData fileData)
 {
     RemoveAllChildren();
     //PanelContainer.Controls.Clear();
     //PanelContainer.Height = fileData.ResolutionHeight;
     //PanelContainer.Width = fileData.ResolutionWidth;
     foreach (var item in fileData.Elements)
         AddCustomControl(item);
 }
Example #7
0
		public File(FileData file, AbstractDirectory parent)
		{
			Parent = parent;

			NewName = file.Name;
			Name = file.Name;
			Title = file.Name;
			Size = file.Length;
			Updated = file.Updated;
			Created = file.Created;
		}
Example #8
0
        /// <summary>
        /// Load file data.
        /// </summary>
        /// <param name="path">The full path.</param>
        /// <returns>The file data.</returns>
        public FileData LoadFile(string path)
        {
            var lines = GetLines(path);

            var file = new FileData
            {
                // used Trim because Line with space start and end AND Line without space start and end are EQUALS
                Lines = lines.Select(x => new Line{Text = x, Hash = Sha1Util.GetHashString(x.Trim())}).ToList()
            };

            return file;
        }
        internal FileRetriever(FileData fileData, string relativePath, Stream fileStream)
        {
            if (fileData == null) {
                throw new ApplicationException("Application Bug");
            }

            if (relativePath == null) {
                relativePath = "";
            }

            FileData = fileData;
            FileStream = fileStream;
            RelativeDirectoryPath = relativePath;
        }
Example #10
0
        public static FileData GetFileSize(FileData file)
        {
            string[] sizes = { "B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };
            double len = new FileInfo(file.FileName).Length;
            int order = 0;
            while (len >= 1024 && order + 1 < sizes.Length)
            {
                order++;
                len = len / 1024;
            }
            file.Size = len;
            file.Type = (Useful_Classes.MyComputer.FileData.FileSizeType)Enum.Parse(typeof(Useful_Classes.MyComputer.FileData.FileSizeType), sizes[order]);

            return file;
        }
Example #11
0
        public File(IFileSystem fs, FileData file, AbstractDirectory parent)
            : base(fs)
        {
            Parent = parent;

            NewName = file.Name;
            Name = file.Name;
            Title = file.Name;
            Size = file.Length;
            Updated = file.Updated;
            Created = file.Created;

            url = file.VirtualPath;

            string icon = ImagesUtility.GetResizedPath(file.VirtualPath, "icon");
            if (FileSystem.FileExists(icon))
                this.iconUrl = icon;
        }
Example #12
0
    //
    // Méthodes de service
    //

    /// <summary>
    /// Ajoute une librarie à une liste d'affichage des librairies.
    /// </summary>
    /// <param name="list">liste hôte</param>
    /// <param name="file">descripteur des informations associées à la librairie</param>
    private void DoAddLibrary( ListView list, FileData file ) {

      // déterminer l'index de l'icône
      int iconIndex = file.IsFiltered ? icoPlugin : icoDllBleu;

      // déterminer l'index image de l'état
      int stateIndex = 0;
      if ( file.IsFiltered )
        stateIndex = file.IsErrored ? icoStop : file.IsWarned ? icoWarning : file.IsInfoed ? icoInfo : file.IsLoaded ? file.IsInstalled ? icoRondVert : icoRondRouge : icoWarning;
      else
        stateIndex = file.IsErrored ? icoStop : file.IsWarned ? icoWarning : file.IsInfoed ? icoInfo : file.IsLoaded ? -1 : icoWarning;

      // ajouter l'itemReport
      ListViewItem item = list.Items.Add( file.FileName );
      item.ImageIndex = stateIndex;
      item.StateImageIndex = iconIndex;
      item.Tag = file;
    }
        public AuthenticationServer()
        {
            m_Data = new FileData("Users");
            m_Data.load();
            m_Data.save();

            //Get all the users from the save file
            UserInfoSaveData[] users = m_Data.get<UserInfoSaveData>();
            if (users != null)
            {
                //Clear our current user list
                m_Users.Clear();
                //add each user from the harddisk into a proper network user on the server ram
                for (int i = 0; i < users.Length; i++)
                {
                    m_Users.Add(users[i].networkUser);
                    m_Users[i].id = m_UserIDGen.getUniqueNumber();
                    m_Users[i].isOnline = false;
                }
            }
        }
Example #14
0
        FileData ParseSingleFile(byte[] data, int startIndex, int endIndex, Encoding encoding)
        {
            FileData ans = new FileData();
            ans.Success = false;

            string content = encoding.GetString(data, startIndex, endIndex-startIndex);

            // Look for Content-Type
            Regex re = new Regex(@"(?<=Content\-Type:)(.*?)(?=\r\n\r\n)");
            Match contentTypeMatch = re.Match(content);

            // Look for filename
            re = new Regex(@"(?<=filename\=\"")(.*?)(?=\"")");
            Match filenameMatch = re.Match(content);

            // Did we find the required values?
            if (contentTypeMatch.Success && filenameMatch.Success)
            {
                // Set properties
                ans.ContentType = contentTypeMatch.Value.Trim();
                ans.Filename = filenameMatch.Value.Trim();

                // Get the start & end indexes of the file contents
                int localStartIndex = startIndex + contentTypeMatch.Index + contentTypeMatch.Length + "\r\n\r\n".Length;

                int contentLength = endIndex - localStartIndex;

                // Extract the file contents from the byte array
                byte[] fileData = new byte[contentLength];

                Buffer.BlockCopy(data, localStartIndex, fileData, 0, contentLength);

                ans.FileContents = fileData;
                ans.Success = true;
            }

            return ans;
        }
Example #15
0
        public static int Execute( List<string> args )
        {
            //args = new string[] { @"c:\Users\Georg\Documents\Visual Studio 2008\Projects\slz\slz\bin\Release\STRCONFIG.STP" };

            if ( args.Count != 1 ) {
                Console.WriteLine( "Usage: SPKDunpack file" );
                return -1;
            }

            byte[] spkd = File.ReadAllBytes( args[0] );

            uint FileAmount = Util.SwapEndian( BitConverter.ToUInt32( spkd, 4 ) );
            uint BlockSize = Util.SwapEndian( BitConverter.ToUInt32( spkd, 12 ) );
            FileData[] FileInfos = new FileData[FileAmount + 1];

            for ( int i = 0; i < FileAmount; i++ ) {
                FileInfos[i] = new FileData();
                FileInfos[i].Name = ASCIIEncoding.GetEncoding( 0 ).GetString( spkd, ( i + 1 ) * (int)BlockSize, 16 );
                FileInfos[i].Name = FileInfos[i].Name.Substring( 0, FileInfos[i].Name.IndexOf( '\0' ) );
                FileInfos[i].Unknown = Util.SwapEndian( BitConverter.ToUInt32( spkd, ( i + 1 ) * (int)BlockSize + 16 ) );
                FileInfos[i].FileStart1 = Util.SwapEndian( BitConverter.ToUInt32( spkd, ( i + 1 ) * (int)BlockSize + 20 ) );
                FileInfos[i].FileStart2 = Util.SwapEndian( BitConverter.ToUInt32( spkd, ( i + 1 ) * (int)BlockSize + 24 ) );
                FileInfos[i].Something = Util.SwapEndian( BitConverter.ToUInt32( spkd, ( i + 1 ) * (int)BlockSize + 28 ) );
            }
            FileInfos[FileAmount] = new FileData();
            FileInfos[FileAmount].FileStart1 = (UInt32)spkd.Length;

            DirectoryInfo d = System.IO.Directory.CreateDirectory( args[0] + ".ext" );
            for ( int i = 0; i < FileAmount; i++ ) {
                int Filesize = (int)FileInfos[i + 1].FileStart1 - (int)FileInfos[i].FileStart1;
                byte[] b = new byte[Filesize];
                Buffer.BlockCopy( spkd, (int)FileInfos[i].FileStart1, b, 0, Filesize );
                File.WriteAllBytes( d.FullName + "\\" + FileInfos[i].Name, b );
            }

            return 0;
        }
Example #16
0
        void DoFiles(DefaultWatcherData data, string directory, bool dispatch)
        {
            bool direxists = Directory.Exists(directory);

            if (direxists && data.IncludeSubdirs)
            {
                foreach (string d in Directory.GetDirectories(directory))
                {
                    DoFiles(data, d, dispatch);
                }
            }

            string [] files = null;
            if (!direxists)
            {
                files = NoStringsArray;
            }
            else if (!data.NoWildcards)
            {
                files = Directory.GetFileSystemEntries(directory, data.FileMask);
            }
            else
            {
                // The pattern does not have wildcards
                if (File.Exists(data.FileMask) || Directory.Exists(data.FileMask))
                {
                    files = new string [] { data.FileMask }
                }
                ;
                else
                {
                    files = NoStringsArray;
                }
            }

            /* Set all as untested */
            foreach (string filename in data.Files.Keys)
            {
                FileData fd = (FileData)data.Files [filename];
                if (fd.Directory == directory)
                {
                    fd.NotExists = true;
                }
            }

            /* New files */
            foreach (string filename in files)
            {
                FileData fd = (FileData)data.Files [filename];
                if (fd == null)
                {
                    try {
                        data.Files.Add(filename, CreateFileData(directory, filename));
                    } catch {
                        // The file might have been removed in the meanwhile
                        data.Files.Remove(filename);
                        continue;
                    }

                    if (dispatch)
                    {
                        DispatchEvents(data.FSW, FileAction.Added, filename);
                    }
                }
                else if (fd.Directory == directory)
                {
                    fd.NotExists = false;
                }
            }

            if (!dispatch)             // We only initialize the file list
            {
                return;
            }

            /* Removed files */
            ArrayList removed = null;

            foreach (string filename in data.Files.Keys)
            {
                FileData fd = (FileData)data.Files [filename];
                if (fd.NotExists)
                {
                    if (removed == null)
                    {
                        removed = new ArrayList();
                    }

                    removed.Add(filename);
                    DispatchEvents(data.FSW, FileAction.Removed, filename);
                }
            }

            if (removed != null)
            {
                foreach (string filename in removed)
                {
                    data.Files.Remove(filename);
                }

                removed = null;
            }

            /* Changed files */
            foreach (string filename in data.Files.Keys)
            {
                FileData fd = (FileData)data.Files [filename];
                DateTime creation, write;
                try {
                    creation = File.GetCreationTime(filename);
                    write    = File.GetLastWriteTime(filename);
                } catch {
                    /* Deleted */
                    if (removed == null)
                    {
                        removed = new ArrayList();
                    }

                    removed.Add(filename);
                    DispatchEvents(data.FSW, FileAction.Removed, filename);
                    continue;
                }

                if (creation != fd.CreationTime || write != fd.LastWriteTime)
                {
                    fd.CreationTime  = creation;
                    fd.LastWriteTime = write;
                    DispatchEvents(data.FSW, FileAction.Modified, filename);
                }
            }

            if (removed != null)
            {
                foreach (string filename in removed)
                {
                    data.Files.Remove(filename);
                }
            }
        }
Example #17
0
        void ParseProtobufManifestPayload(ContentManifestPayload payload)
        {
            Files = new List<FileData>(payload.mappings.Count);

            foreach (var file_mapping in payload.mappings)
            {
                FileData filedata = new FileData(file_mapping.filename, (EDepotFileFlag)file_mapping.flags, file_mapping.size, file_mapping.sha_content, FilenamesEncrypted, file_mapping.chunks.Count);

                foreach (var chunk in file_mapping.chunks)
                {
                    filedata.Chunks.Add( new ChunkData( chunk.sha, BitConverter.GetBytes(chunk.crc), chunk.offset, chunk.cb_compressed, chunk.cb_original ) );
                }

                Files.Add(filedata);
            }
        }
Example #18
0
        private void LoadXML(string filename, XmlReader reader)
        {
            Element current = null;
            IXMLLoader currentLoader = null;

            // Set the "IsEditorLibrary" flag for any library with type="editor", and its sub-libraries
            bool isEditorLibrary = false;
            if (m_currentFile.Count > 0 && m_currentFile.Peek().IsEditorLibrary) isEditorLibrary = true;
            if (reader.GetAttribute("type") == "editor") isEditorLibrary = true;

            if (!IsCompiledFile && m_currentFile.Count == 0 && m_worldModel.Version >= WorldModelVersion.v530)
            {
                ScanForTemplates(filename);
            }

            FileData data = new FileData
            {
                Filename = reader.BaseURI,
                IsEditorLibrary = isEditorLibrary
            };

            m_currentFile.Push(data);
            UpdateLoadStatus();

            while (reader.Read())
            {
                switch (reader.NodeType)
                {
                    case XmlNodeType.Element:
                        currentLoader = GetLoader(reader.Name, current);
                        currentLoader.StartElement(reader, ref current);
                        break;
                    case XmlNodeType.EndElement:
                        GetLoader(reader.Name, current).EndElement(reader, ref current);
                        break;
                    case XmlNodeType.Text:
                    case XmlNodeType.CDATA:
                        currentLoader.SetText(reader.ReadContentAsString(), ref current);
                        // if we've eaten the content of this element, then the reader will have gone
                        // past the EndElement already, so we need to trigger the EndElement here
                        GetLoader(reader.Name, current).EndElement(reader, ref current);
                        currentLoader = null;
                        break;
                }
            }

            m_currentFile.Pop();
            UpdateLoadStatus();
        }
Example #19
0
 /// <summary>
 /// Détermine une étape de progression comme chargement d'une librairie
 /// </summary>
 /// <param name="file">descripteur des informations associées à la librairie</param>
 internal void Progress( FileData file ) {
   DoAddLibrary( libraries, file );
   libraries.Update();
   statusLabel.Text = file.FileName == "" ? "" : "Chargement de : " + file.FileName;
   statusLabel.Update();
   statusProgress.Value = libraries.Items.Count;
   statusProgress.Update();
   Application.DoEvents();
 }
Example #20
0
 public PluginData(FileData filedata, XmlNode xmlnode)
 {
     fileData = filedata;
     xmlNode = xmlnode;
     try
     {
         this.md5 = xmlNode.Attributes.GetNamedItem("md5").Value;
     }
     catch { this.md5 = ""; }
     try
     {
         this.tagType = xmlNode.Attributes.GetNamedItem("tagtype").Value;
     }
     catch { this.tagType = filedata.name.Split('-')[0]; }
     try
     {
         this.author = xmlNode.Attributes.GetNamedItem("author").Value;
     }
     catch { this.author = "unknown"; }
     try
     {
         this.version = xmlNode.Attributes.GetNamedItem("version").Value;
     }
     catch { this.version = "0.0"; }
 }
Example #21
0
		// ---------------------------------------------------------------------------

		private bool ReadData(String FileName, ref FileData Data)
		{ 
			FileStream fs = null;
			BinaryReader Source = null;
			char[] ID = new char[16];
			int ObjectCount;
			int ObjectSize;
			long Position;

			bool result;

			// Read file data
			try
			{
				fs = new FileStream(FileName, FileMode.Open, FileAccess.Read);
				fs.Lock(0,fs.Length);
				Source = new BinaryReader(fs);

				Data.FileSize = (int)fs.Length;
    
				// Check for existing header
				ID = Utils.ReadTrueChars(Source,16);

				if ( Utils.ArrEqualsArr(WMA_HEADER_ID,ID) )
				{
					fs.Seek(8, SeekOrigin.Current);
					ObjectCount = Source.ReadInt32();		  
					fs.Seek(2, SeekOrigin.Current);
					// Read all objects in header and get needed data
					for (int iterator=0; iterator<ObjectCount; iterator++)
					{
						Position = fs.Position;
						ID = Utils.ReadTrueChars(Source,16);
						ObjectSize = Source.ReadInt32();			
						ReadObject(ID, Source, ref Data);
						fs.Seek(Position + ObjectSize, SeekOrigin.Begin);				
					}
				}
				result = true;
			} 
			catch (Exception e) 
			{
				System.Console.WriteLine(e.StackTrace);
				//LogDelegator.GetLogDelegate()(Log.LV_ERROR, e.Message);
				result = false;
			}
			if (fs != null)
			{
				fs.Unlock(0,fs.Length);
				fs.Close();
			}
			return result;
		}
Example #22
0
		// ---------------------------------------------------------------------------

		private bool IsValid(FileData Data)
		{
			// Check for data validity
			return (
				(Data.MaxBitRate > 0) && (Data.MaxBitRate < 320000) &&
				((Data.Channels == WMA_CM_MONO) || (Data.Channels == WMA_CM_STEREO)) &&
				(Data.SampleRate >= 8000) && (Data.SampleRate <= 96000) &&
				(Data.ByteRate > 0) && (Data.ByteRate < 40000) );
		}
Example #23
0
        private void DoDownloadAndSaveAllFiles(List<FileData> filesToDownload, List<FileData> successfullyDownloadedFiles)
        {
            bool cancelled = false;

            foreach (var fileData in filesToDownload)
            {
                if (cancelled)
                {
                    break;
                }

                _currentFile = fileData;

                var url = new Uri(fileData.ServerFile);
                var request = (HttpWebRequest)WebRequest.Create(url);
                HttpWebResponse response = null;
                try
                {
                    response = (HttpWebResponse)request.GetResponse();
                    response.Close();
                }
                catch (WebException e)
                {
                    // Victor Chelaru
                    // October 11, 2015
                    // We used to notify
                    // the user that a file
                    // failed to download, but
                    // many projects have files
                    // which cannot be updated through
                    // this command. This isn't a bad thing,
                    // so we don't want to tell the user that
                    // errors occurred:
                    //PluginManager.ReceiveError("Unable to download " + fileData.ServerFile);
                    continue;
                }

                DoDownloadAndSaveFile(ref cancelled, fileData, url, response);
                PluginManager.ReceiveOutput("Successfully downloaded " + fileData.ServerFile);

                if (updateWorkerThread.CancellationPending)
                {
                    return;
                }
                else
                {
                    successfullyDownloadedFiles.Add(fileData);
                }
            }
        }
Example #24
0
		// ---------------------------------------------------------------------------

		private void ReadObject(char[] ID, BinaryReader Source, ref FileData Data)
		{
			// Read data from header object if supported
			if ( Utils.ArrEqualsArr(WMA_FILE_PROPERTIES_ID,ID) )
			{
				// Read file properties
				Source.BaseStream.Seek(80, SeekOrigin.Current);
				Data.MaxBitRate = Source.ReadInt32();
			}
			if ( Utils.ArrEqualsArr(WMA_STREAM_PROPERTIES_ID,ID) )
			{
				// Read stream properties
				Source.BaseStream.Seek(58, SeekOrigin.Current);
				Data.FormatTag = Source.ReadUInt16();
				Data.Channels = Source.ReadUInt16();
				Data.SampleRate = Source.ReadInt32();
				Data.ByteRate = Source.ReadInt32();    
			}
			if ( Utils.ArrEqualsArr(WMA_CONTENT_DESCRIPTION_ID,ID) )
			{
				// Read standard tag data
				Source.BaseStream.Seek(4, SeekOrigin.Current);
				ReadTagStandard(Source, ref Data.Tag);
			}
			if ( Utils.ArrEqualsArr(WMA_EXTENDED_CONTENT_DESCRIPTION_ID,ID) )
			{
				// Read extended tag data
				Source.BaseStream.Seek(4, SeekOrigin.Current);
				ReadTagExtended(Source, ref Data.Tag);
			}
		}
Example #25
0
		// --- functions ---
		
		private void AddFiles(string[] files) {
			listviewFiles.SuspendLayout();
			listviewFiles.BeginUpdate();
			foreach (string file in files) {
				bool add = true;
				foreach (ListViewItem item in listviewFiles.Items) {
					FileData data = item.Tag as FileData;
					if (data != null && data.FullPath.Equals(file, StringComparison.OrdinalIgnoreCase)) {
						add = false;
						break;
					}
				}
				if (add) {
					ListViewItem item = new ListViewItem(Path.GetFileName(file));
					item.SubItems.Add("Processing...");
					var data = new FileData(file, item);
					item.Tag = data;
					listviewFiles.Items.Add(item);
				}
			}
			listviewFiles.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);
			int[] widths = new int[listviewFiles.Columns.Count];
			for (int i = 0; i < listviewFiles.Columns.Count; i++) {
				widths[i] = listviewFiles.Columns[i].Width;
			}
			listviewFiles.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);
			for (int i = 0; i < listviewFiles.Columns.Count; i++) {
				if (widths[i] > listviewFiles.Columns[i].Width) {
					listviewFiles.Columns[i].Width = widths[i];
				}
			}
			listviewFiles.EndUpdate();
			listviewFiles.ResumeLayout();
			ButtonValidateClick(null, null);
		}
Example #26
0
        private void DoDownloadAndSaveFile(ref bool cancelled, FileData fileData, Uri url, HttpWebResponse response)
        {
            int bytesDownloaded = 0;
            var fileSize = response.ContentLength;
            var fileTimeStamp = response.LastModified;

            using (var mClient = new WebClient())
            {
                if (!AlreadyDownloaded(fileData, fileTimeStamp))
                {
                    using (var webStream = mClient.OpenRead(url))
                    {
                        using (var fileStream = new FileStream(fileData.DiskFile, FileMode.Create, FileAccess.Write,
                                                        FileShare.None))
                        {
                            _fileName = fileData.FileName;

                            int bytesRead = 0;
                            var byteBuffer = new byte[fileSize];

                            if (webStream != null)
                            {
                                var start = DateTime.Now;

                                while ((bytesRead = webStream.Read(byteBuffer, 0, byteBuffer.Length)) > 0)
                                {
                                    fileStream.Write(byteBuffer, 0, bytesRead);
                                    bytesDownloaded += bytesRead;

                                    UpdateDownloadProgressAndSpeed(bytesDownloaded, byteBuffer, start);

                                    if (updateWorkerThread.CancellationPending)
                                    {
                                        cancelled = true;
                                        break;
                                    }
                                }
                            }
                        }
                    }

                    using (var writer = new StreamWriter(fileData.TimestampFile))
                    {
                        writer.Write(fileTimeStamp.ToString());
                    }

                    _downloadedFile = true;
                }
                else
                {
                    pbValue.BeginInvoke(
                        new EventHandler(
                            delegate
                            {
                                pbValue.Value = 100;
                                Application.DoEvents();
                            }));
                }
            }
        }
Example #27
0
		private void ValidateData(FileData data) {
			var decoder = new CsvB3dDecoder.Decoder();
			var manager = new MyTextureManager();
			var logger = new MyErrorLogger();
			var options = new TrainsimApi.Codecs.MeshDecodingOptions(manager, logger);
			#if !DEBUG
			try {
				#endif
				Mesh mesh = decoder.Load(data.FullPath, options);
				Validator.CheckMeshFaces(mesh, logger);
				data.ErrorMessage = logger.Builder.ToString();
				#if !DEBUG
			} catch (Exception ex) {
				data.ErrorMessage = "Unhandled exception:" + Environment.NewLine + ex.Message + Environment.NewLine + Environment.NewLine + "Please forward this error to the author of this program along with the file that caused the error.";
			}
			#endif
			listviewFiles.Invoke(new ThreadStart(() => {
			                                     	if (listviewFiles.Items.Contains(data.Item)) {
			                                     		data.Item.SubItems[1].Text = logger.Count.ToString();
			                                     		if (listviewFiles.SelectedItems.Count != 0 && listviewFiles.SelectedItems[0] == data.Item) {
			                                     			ListviewFilesSelectedIndexChanged(null, null);
			                                     		}
			                                     	}
			                                     }));
		}
        void ParseBinaryManifest(Steam3Manifest manifest)
        {
            Files = new List<FileData>();
            FilenamesEncrypted = manifest.AreFileNamesEncrypted;

            foreach (var file_mapping in manifest.Mapping)
            {
                FileData filedata = new FileData(file_mapping.FileName, file_mapping.Flags, file_mapping.TotalSize, file_mapping.HashContent, FilenamesEncrypted);

                foreach (var chunk in file_mapping.Chunks)
                {
                    filedata.Chunks.Add( new ChunkData( chunk.ChunkGID, chunk.CRC, chunk.Offset, chunk.CompressedSize, chunk.DecompressedSize ) );
                }

                Files.Add(filedata);
            }
        }
Example #29
0
		// ---------------------------------------------------------------------------

		public bool ReadFromFile(String FileName)
		{
			FileData Data = new FileData();

			// Reset variables and load file data
			FResetData();
			Data.Reset();

			bool result = ReadData(FileName, ref Data);

			// Process data if loaded and valid
			if ( result && IsValid(Data) )
			{
				FValid = true;
				// Fill properties with loaded data
				FFileSize = Data.FileSize;
				FChannelModeID = (byte)Data.Channels;
				FSampleRate = Data.SampleRate;
				FDuration = Data.FileSize * 8 / Data.MaxBitRate;
				FBitRate = Data.ByteRate * 8 / 1000;
				FIsVBR = (WMA_GSM_VBR_ID == Data.FormatTag);
				FIsLossless = (WMA_LOSSLESS_ID == Data.FormatTag);
				FTitle = Data.Tag[0].Trim();
				FArtist = Data.Tag[1].Trim();
				FAlbum = Data.Tag[2].Trim();
				FTrack = ExtractTrack(Data.Tag[3].Trim());
				FYear = Data.Tag[4].Trim();
				FGenre = Data.Tag[5].Trim();
				FComment = Data.Tag[6].Trim();
			}
	
			return result;
		}
 //Implementation helpers
 private string CreateNewName(
     FileData fileData
     )
 {
     return DataStore.GetRootPath() + "/" + fileData.RelativePath.Replace("\\", "/").ToLower();
 }
		static FileData CreateFileData (string directory, string filename)
		{
			FileData fd = new FileData ();
			string fullpath = Path.Combine (directory, filename);
			fd.Directory = directory;
			fd.Attributes = File.GetAttributes (fullpath);
			fd.CreationTime = File.GetCreationTime (fullpath);
			fd.LastWriteTime = File.GetLastWriteTime (fullpath);
			return fd;
		}