Пример #1
0
        public FizzPackfile(string fname)
        {
            this.fname = fname;

            using(stream = File.Open(fname, FileMode.Open, FileAccess.Read, FileShare.Read)) {
                BinaryReader br = new BinaryReader(stream);
                if(br.ReadUInt32() != 0xdeadba11)
                    throw new Exception("Invalid FizzPackfile");
                if(br.ReadUInt32() != 4)
                    throw new Exception("Invalid FizzPackfile");

                fileCount = br.ReadInt32();
                nameTableLength = br.ReadInt32();

                List<FileRecord> temp = new List<FileRecord>();
                for(int i=0; i<fileCount; i++) {
                    FileRecord fr = new FileRecord();
                    fr.hash = br.ReadUInt32();
                    fr.offset = br.ReadInt32();
                    fileRecords[fr.hash] = fr;
                    temp.Add(fr);
                }

                for(int i=0; i<fileCount; i++)
                    temp[i].nameOffset = br.ReadInt32();

                //read the lengths
                for(int i=0; i<fileCount; i++) {
                    stream.Position = temp[i].offset;
                    temp[i].length = br.ReadInt32();
                    temp[i].offset += 4;
                }

            }
        }
Пример #2
0
		public void CanParseComplex(){
			var result = new FileRecord("DU  \"a\\320\\247 - b\" -> \"a\\320\\247 - b2\"");
			Assert.AreEqual(FileState.Deleted, result.FirstState);
			Assert.AreEqual(FileState.Updated, result.SecondState);
			Assert.AreEqual("aЧ - b", result.FileName);
			Assert.AreEqual("aЧ - b2", result.NewFileName);
			Assert.True(result.IsConflict);
		}
Пример #3
0
		public void NewModifiedFile()
		{
			var result = new FileRecord(" M test2");
			Assert.AreEqual(FileState.NotModified, result.FirstState);
			Assert.AreEqual(FileState.Modified, result.SecondState);
			Assert.AreEqual("test2", result.FileName);
			
		}
Пример #4
0
		public void CanParseHaskel(){
			var result = new FileRecord("A  \"a\\320\\247 - b\"");
			Assert.AreEqual(FileState.Added,result.FirstState);
			Assert.AreEqual(FileState.NotModified,result.SecondState);
			Assert.AreEqual("aЧ - b",result.FileName);
			Assert.AreEqual("",result.NewFileName);
			Assert.False(result.IsConflict);
		}
Пример #5
0
		public void CanParseSimple(){
			var result = new FileRecord("?? x");
			Assert.AreEqual(FileState.Untracked,result.FirstState);
			Assert.AreEqual(FileState.Untracked,result.SecondState);
			Assert.AreEqual("x",result.FileName);
			Assert.AreEqual("",result.NewFileName);
			Assert.False(result.IsConflict);
		}
        public static FileRecord AddToOpenList(String fullName, int access, int share)
        {
            fullName = fullName.ToUpper();

            FileRecord record = new FileRecord(fullName, share);
            lock (m_openFiles)
            {
                int count = m_lockedDirs.Count;

                for (int i = 0; i < count; i++)
                {
                    if (IsInDirectory(fullName, (String)m_lockedDirs[i]))
                    {
                        throw new IOException("", (int)IOException.IOExceptionErrorCode.UnauthorizedAccess);
                    }
                }

                FileRecord current;
                count = m_openFiles.Count;

                for (int i = 0; i < count; ++i)
                {
                    current = (FileRecord)m_openFiles[i];
                    if (current.FullName == fullName)
                    {
                        // Given the previous fileshare info and the requested fileaccess and fileshare
                        // the following is the ONLY combinations that we should allow -- All others
                        // should failed with IOException
                        // (Behavior verified on desktop .NET)
                        //
                        // Previous FileShare   Requested FileAccess    Requested FileShare
                        // Read                 Read                    ReadWrite
                        // Write                Write                   ReadWrite
                        // ReadWrite            Read                    ReadWrite
                        // ReadWrite            Write                   ReadWrite
                        // ReadWrite            ReadWrite               ReadWrite
                        //
                        // The following check take advantage of the fact that the value for
                        // Read, Write, and ReadWrite in FileAccess enum and FileShare enum are
                        // identical.
                        if ((share != FileShareReadWrite) ||
                           ((current.Share & access) != access))
                        {
                            throw new IOException("", (int)IOException.IOExceptionErrorCode.UnauthorizedAccess);
                        }
                    }
                }

                m_openFiles.Add(record);
            }

            return record;
        }
Пример #7
0
		public void CanParseWithWS(){
			var result = new FileRecord("?? a b");
			Assert.AreEqual(FileState.Untracked, result.FirstState);
			Assert.AreEqual(FileState.Untracked, result.SecondState);
			Assert.AreEqual("a b", result.FileName);
			Assert.AreEqual("", result.NewFileName);
			Assert.False(result.IsConflict);

			result = new FileRecord("A  \"a b\"");
			Assert.AreEqual(FileState.Added, result.FirstState);
			Assert.AreEqual(FileState.NotModified, result.SecondState);
			Assert.AreEqual("a b", result.FileName);
			Assert.AreEqual("", result.NewFileName);
			Assert.False(result.IsConflict);
		}
Пример #8
0
        public static ScheduledJob Get(string path)
        {
            FileRecord record = FileRecord.Get(path, true);

            return(new ScheduledJob(record.GetContent()));
        }
Пример #9
0
        public IActionResult ImportPOST()
        {
            //IFormFile file = Request.Form.Files[0];
            var           file        = HttpContext.Request.Form.Files;
            string        folderName  = "UploadExcel";
            string        webRootPath = _webHostEnvironment.WebRootPath;
            string        newPath     = Path.Combine(webRootPath, folderName);
            StringBuilder sb          = new StringBuilder();

            if (!Directory.Exists(newPath))
            {
                Directory.CreateDirectory(newPath);
            }
            if (file[0].Length > 0)
            {
                string sFileExtension = Path.GetExtension(file[0].FileName).ToLower();
                ISheet sheet;
                string fullPath = Path.Combine(newPath, file[0].FileName);
                using (var stream = new FileStream(fullPath, FileMode.Create))
                {
                    file[0].CopyTo(stream);
                    stream.Position = 0;
                    if (sFileExtension == ".xls")
                    {
                        HSSFWorkbook hssfwb = new HSSFWorkbook(stream); //This will read the Excel 97-2000 formats
                        sheet = hssfwb.GetSheetAt(0);                   //get first sheet from workbook
                    }
                    else
                    {
                        XSSFWorkbook hssfwb = new XSSFWorkbook(stream); //This will read 2007 Excel format
                        sheet = hssfwb.GetSheetAt(0);                   //get first sheet from workbook
                    }
                    IRow headerRow = sheet.GetRow(0);                   //Get Header Row
                    int  cellCount = headerRow.LastCellNum;
                    List <FileRecord> fileRowList = new List <FileRecord>();
                    for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++) //Read Excel File
                    {
                        IRow row = sheet.GetRow(i);
                        if (row == null)
                        {
                            continue;
                        }
                        FileRecord f = new FileRecord
                        {
                            CodeNumber        = row.GetCell(1).ToString(),
                            Name              = row.GetCell(2).ToString(),
                            Description       = row.GetCell(3).ToString(),
                            PhoneNumber       = row.GetCell(4).ToString(),
                            TakenTo           = row.GetCell(5).ToString(),
                            ReturnedFrom      = row.GetCell(6).ToString(),
                            shelfNumber       = row.GetCell(7).ToString(),
                            CurrentLocation   = row.GetCell(8).ToString(),
                            CollectingOfficer = row.GetCell(9).ToString(),
                            RecordingOfficer  = row.GetCell(10).ToString(),
                            IsActive          = true,
                            DateCreated       = DateTime.UtcNow
                        };
                        _db.FileRecord.Add(f);
                    }
                    _db.SaveChanges();
                }
            }
            return(Redirect("/Admin/File/Index"));
        }
Пример #10
0
        internal static ScheduledJob Get(string volume, int recordNumber)
        {
            FileRecord record = FileRecord.Get(volume, recordNumber, true);

            return(new ScheduledJob(record.GetContent()));
        }
Пример #11
0
 public FileRecord CreateFileRecord(FileRecord fileRecord)
 {
     return(_fileRecordsRepository.CreateFileRecord(fileRecord));
 }
Пример #12
0
        ///  <summary>
        ///  Finds the appropriate file based on version, site, and section.
        ///  </summary>
        ///  <remarks>
        ///  
        ///  </remarks>
        /// <param name="request">The request object</param>
        /// <param name="fileName">The name of the file to find, including extension.</param>
        ///  <param name="section">The section of the site the file is for.</param>
        ///  <param name="site">The site the file is for.</param>
        ///  <param name="version">The version of the site the file is for.</param>
        ///  <param name="rootPath">The relative path from the application root to
        /// 			the directory to search for the file.</param>
        ///  <param name="type">The<c>FileType</c> of the file.</param>
        ///  <returns>A <c>FileRecord</c> containing the information on the file located,
        /// 			or <c>null</c> if no file was found.</returns>
        private FileRecord FindFile(
            MvcRequest request,
            String fileName,
            String section,
            String site,
            int version,
            String rootPath,
            FileType type)
        {
            bool found = false;
            FileRecord fileRec = new FileRecord {
                                                    rootPath = rootPath,
                                                    version = version.ToString(CultureInfo.InvariantCulture),
                                                    site = site,
                                                    section = section,
                                                    subPath = fileName
                                                };

            if (this.FileExists(fileRec)) {
                fileRec.fullPath = "/" + fileRec.BuildPath();
                found = true;
            } else {
                switch (type) {
                    case FileType.PAGE:
                        //  check for <version>/[configuration["defaultDirName"]/<section>/<file>
                        if (string.IsNullOrEmpty(this.defaultLanguageDirName)) {
                            throw new ApplicationException("Default directory name not found in sites.config ["
                                    + DEFAULT_LANGUAGE_DIR_NAME + "]");
                        }
                        fileRec.site = this.defaultLanguageDirName;
                        if (this.FileExists(fileRec)) {
                            fileRec.fullPath = "/" + fileRec.BuildPath();
                            found = true;
                        }
                        break;

                    case FileType.CONTENT:
                        //  check for <version>/<site>/<language>/<section>/<file>
                        //  (NOTE: this is only applicable for content)
                        fileRec.language = LanguageUtilities.GetLanguage(request, site);
                        if (this.FileExists(fileRec)) {
                            fileRec.fullPath = "/" + fileRec.BuildPath();
                            found = true;
                        }
                        break;
                }

                if (!found) {
                    try {
                        //  get the configuration section for the specified site
                        XmlConfiguration config = SitesConfig.GetInstance().GetConfig("sites", site);
                        //  get the value of the defaultPageSearchMethod setting for the site
                        String searchMethod = config.GetValue("//defaultPageSearchMethod");

                        //  if the defaultPageSearchMethod setting is to check
                        //  the previous version(s), recursively call FindFile
                        //  with the next lower version
                        if (SEARCH_METHOD_PREVIOUS_VER.Equals(searchMethod) && (version > 1)) {
                            fileRec = this.FindFile(request, fileName, section, site, version - 1, rootPath, type);
                            found = this.FileExists(fileRec);

                            //  check for <version>/[configuration["defaultDirName"]/<file>
                        } else if (SEARCH_METHOD_DEFAULT.Equals(searchMethod)) {
                            fileRec.site = this.defaultLanguageDirName;
                            fileRec.section = null;
                            fileRec.language = null;
                            if (this.FileExists(fileRec)) {
                                fileRec.fullPath = "/" + fileRec.BuildPath();
                                found = true;
                            }
                        }
                    } catch (Exception e) {
                        LogManager.GetCurrentClassLogger().Error(
                            errorMessage => errorMessage("PageFinder.FindFile : "), e);
                        fileRec = null;
                    }
                }
            }

            //  log info if the file was not found
            if (!found) {
                //  get the components of the file name
                string[] pieces = fileName.Split('.');
                //  we only want to log items like 'file.xml' and ignore ones like 'file.css.xml'
                if (pieces.Length == 2) {
                    LogManager.GetCurrentClassLogger().Warn(
                        warnMessage => warnMessage("PageFinder.FindFile: file not found: file = '{0}', section = '{1}', site = '{2}', version = {3}",
                                                    fileName,
                                                    section,
                                                    site,
                                                    version));
                }
                fileRec = null;
            }

            return fileRec;
        }
        public IActionResult Import()
        {
            //IFormFile file = Request.Form.Files[0];
            var           file        = HttpContext.Request.Form.Files;
            string        folderName  = "UploadExcel";
            string        webRootPath = _webHostEnvironment.WebRootPath;
            string        newPath     = Path.Combine(webRootPath, folderName);
            StringBuilder sb          = new StringBuilder();

            if (!Directory.Exists(newPath))
            {
                Directory.CreateDirectory(newPath);
            }
            if (file[0].Length > 0)
            {
                string sFileExtension = Path.GetExtension(file[0].FileName).ToLower();
                ISheet sheet;
                string fullPath = Path.Combine(newPath, file[0].FileName);
                using (var stream = new FileStream(fullPath, FileMode.Create))
                {
                    file[0].CopyTo(stream);
                    stream.Position = 0;
                    if (sFileExtension == ".xls")
                    {
                        HSSFWorkbook hssfwb = new HSSFWorkbook(stream); //This will read the Excel 97-2000 formats
                        sheet = hssfwb.GetSheetAt(0);                   //get first sheet from workbook
                    }
                    else
                    {
                        XSSFWorkbook hssfwb = new XSSFWorkbook(stream); //This will read 2007 Excel format
                        sheet = hssfwb.GetSheetAt(0);                   //get first sheet from workbook
                    }
                    IRow headerRow = sheet.GetRow(0);                   //Get Header Row
                    int  cellCount = headerRow.LastCellNum;
                    //sb.Append("<table class='table table-bordered'><tr>");

                    //for (int j = 0; j<cellCount; j++)
                    //{
                    //    NPOI.SS.UserModel.ICell cell = headerRow.GetCell(j);
                    //    if (cell == null || string.IsNullOrWhiteSpace(cell.ToString())) continue;
                    //    sb.Append("<th>" + cell.ToString() + "</th>");
                    //}
                    //sb.Append("</tr>");
                    //sb.AppendLine("<tr>");
                    List <FileRecord> fileRowList = new List <FileRecord>();
                    for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++) //Read Excel File
                    {
                        IRow row = sheet.GetRow(i);
                        if (row == null)
                        {
                            continue;
                        }
                        FileRecord f = new FileRecord
                        {
                            CodeNumber  = row.GetCell(1).ToString(),
                            Name        = row.GetCell(2).ToString(),
                            Description = row.GetCell(3).ToString()
                        };
                        _db.FileRecord.Add(f);
                        //fileRowList.Add(f);
                        //if (row.Cells.All(d => d.CellType == CellType.Blank)) continue;
                        //for (int j = row.FirstCellNum; j<cellCount; j++)
                        //{
                        //    if (row.GetCell(j) != null)
                        //        sb.Append("<td>" + row.GetCell(j).ToString() + "</td>");
                        //}
                        //sb.AppendLine("</tr>");
                        //_db.FileRecord.Add(fileRowList);
                    }
                    _db.SaveChanges();


                    //sb.Append("</table>");
                }
            }
            //return this.Content(sb.ToString());
            return(RedirectToAction(nameof(Index)));
        }
        public async Task <IActionResult> PostLargeFile(int bufferSize)
        {
            var boundary = Request.GetMultipartBoundary();
            var reader   = new MultipartReader(boundary, Request.Body);

            FileRecord fileRecord = default;
            var        section    = await reader.ReadNextSectionAsync();

            if (!section.IsJson())
            {
                return(BadRequest());
            }
            else
            {
                fileRecord = section.ReadAs <FileRecord>();
            }

            section = await reader.ReadNextSectionAsync();

            var inputStream = section.Body;
            var folder      = Path.Combine(Path.GetTempPath(), "FileUploadExperimentVault");

            if (!Directory.Exists(folder))
            {
                Directory.CreateDirectory(folder);
            }
            var file = Path.Combine(folder, $"{fileRecord.FileId}.tmp");

            using (var outputStream = IOFile.OpenWrite(file))
            //using (var bufferedStream = new BufferedStream(inputStream, BufferSize))
            {
                try
                {
                    //await inputStream.CopyToAsync(outputStream, bufferSize);


                    while (inputStream.Position < fileRecord.Size)
                    {
                        var buffer = new byte[bufferSize];
                        var length = await inputStream.ReadAsync(buffer, 0, buffer.Length);

                        await outputStream.WriteAsync(buffer, 0, length);

                        await outputStream.FlushAsync();
                    }
                }
                catch (AggregateException e)
                {
                    return(BadRequest(e.InnerException));
                }
            }


            var info = new FileInfo(file);

            if (info.Length != fileRecord.Size)
            {
                return(BadRequest("Size doesn't match."));
            }

            if (await reader.ReadNextSectionAsync() != null)
            {
                return(BadRequest());
            }

            return(await Task.FromResult(Ok()));
        }
Пример #15
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static AlternateDataStream[] GetInstancesByPath(string path)
        {
            FileRecord record = FileRecord.Get(path, false);

            return(GetInstances(record));
        }
Пример #16
0
        private void showScript(FileInfo file, FileRecord rec)
        {
            string       text = "";
            FileStream   fs   = new FileStream(file.FullName, FileMode.Open, FileAccess.Read);
            StreamReader sr   = new StreamReader(fs, Encoding.Default);

            rec.FileIcon = new BitmapImage(new Uri(CONST_STRING.CSharpIcon, UriKind.Relative));
            int           leftNumber    = 0;
            List <string> namespaceList = new List <string>();

            while (true)
            {
                text = sr.ReadLine();
                if (text == null)
                {
                    break;
                }
                int  posNameSpace = text.IndexOf("namespace");
                int  posClass     = text.IndexOf("class");
                int  leftPos      = text.IndexOf("{");
                int  rightPos     = text.IndexOf("}");
                bool b            = false;
                if (posNameSpace != -1)
                {
                    int    pos2 = text.IndexOf("{", posNameSpace + 1);
                    string ns   = "";
                    if (pos2 != -1)
                    {
                        b  = true;
                        ns = text.Substring(posNameSpace + 10, pos2 - posNameSpace - 10).Trim();
                        leftNumber++;
                    }
                    else
                    {
                        ns = text.Substring(posNameSpace + 10).Trim();
                    }
                    namespaceList.Add(ns);
                }
                if (leftPos != -1 && !b)
                {
                    leftNumber++;
                }
                b = false;
                if (posClass != -1)
                {
                    int    pos2      = text.IndexOf("{");
                    string className = "";
                    if (pos2 != -1)
                    {
                        b         = true;
                        className = text.Substring(posClass + 6, pos2 - posClass - 6).Trim();
                        leftNumber++;
                    }
                    else
                    {
                        className = text.Substring(posClass + 6).Trim();
                    }
                    string nsName = "";
                    for (int i = 0; i < namespaceList.Count; i++)
                    {
                        nsName = nsName + namespaceList[i] + ".";
                    }
                    if (className.IndexOf(":") != -1)
                    {
                        int    comPos  = className.IndexOf(":");
                        string compStr = className.Substring(comPos + 1);
                        if (compStr.Trim() == "Component")
                        {
                            className = className.Substring(0, comPos);
                            className = nsName + className;
                            ScriptNode r = new ScriptNode();
                            r.ShowText = className.Trim();
                            r.DragText = className.Trim();
                            rec.SubRecords.Add(r);
                        }
                    }
                }
                if (rightPos != -1 && !b)
                {
                    leftNumber--;
                    if (namespaceList.Count > leftNumber)
                    {
                        namespaceList.RemoveAt(leftNumber);
                    }
                }
            }

            sr.Close();
        }
Пример #17
0
        static void Main(string[] args)
        {
            /*
             * Assumptions:
             * Input file is in the valid format and each field contains valid data. General validation is present to catch likely failures.
             * Example Output presented the expected datatypes (int and string).
             */

            string argumentExceptionString = "The Record Type did not match the expected format.";
            string inputPath        = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), @"Sample.csv");
            string resultOutputPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), @"Results.json");

            Console.WriteLine("Attempting to convert file.");
            try
            {
                using (var reader = new StreamReader(inputPath))
                {
                    var fileRecord = new FileRecord()
                    {
                        Orders = new List <Order>()
                    };
                    while (!reader.EndOfStream)
                    {
                        var nextLine = ReadNextLine(reader);
                        // Process File Start
                        if (nextLine[0].Equals("F", StringComparison.InvariantCultureIgnoreCase))
                        {
                            fileRecord.Date = nextLine[1];
                            fileRecord.Type = nextLine[2];

                            nextLine = ReadNextLine(reader);

                            // Process Order Start
                            if (nextLine[0].Equals("O", StringComparison.InvariantCultureIgnoreCase))
                            {
                                Order newOrder = new Order()
                                {
                                    Date   = nextLine[1],
                                    Code   = nextLine[2],
                                    Number = nextLine[3],
                                    Items  = new List <Item>()
                                };
                                nextLine = ReadNextLine(reader);

                                // Process Buyer
                                if (nextLine[0].Equals("B", StringComparison.InvariantCultureIgnoreCase))
                                {
                                    newOrder.Buyer = new Buyer()
                                    {
                                        Name   = nextLine[1],
                                        Street = nextLine[2],
                                        Zip    = nextLine[3]
                                    };
                                    nextLine = ReadNextLine(reader);
                                }

                                // Recursively Process Items
                                if (nextLine[0].Equals("L", StringComparison.InvariantCultureIgnoreCase))
                                {
                                    nextLine = ParseItem(nextLine, newOrder, reader);
                                }
                                // Process Timings
                                if (nextLine[0].Equals("T", StringComparison.InvariantCultureIgnoreCase))
                                {
                                    var timings = new Timing()
                                    {
                                        Start  = Int32.Parse(nextLine[1]),
                                        Stop   = Int32.Parse(nextLine[2]),
                                        Gap    = Int32.Parse(nextLine[3]),
                                        Offset = Int32.Parse(nextLine[4]),
                                        Pause  = Int32.Parse(nextLine[5])
                                    };
                                    newOrder.Timings = timings;
                                    nextLine         = ReadNextLine(reader);
                                }
                                // If Record Type does not match expected end input throw exception.
                                else
                                {
                                    throw new ArgumentException(argumentExceptionString);
                                }
                                fileRecord.Orders.Add(newOrder);
                            }
                            // Process End of File
                            if (nextLine[0].Equals("E", StringComparison.InvariantCultureIgnoreCase))
                            {
                                fileRecord.Ender = new Ender()
                                {
                                    Process = Int32.Parse(nextLine[1]),
                                    Paid    = Int32.Parse(nextLine[2]),
                                    Created = Int32.Parse(nextLine[3])
                                };
                            }
                            // If Record Type does not match expected end input throw exception.
                            else
                            {
                                throw new ArgumentException(argumentExceptionString);
                            }
                        }
                        // Convert to Json sting using Camel case to match challange example output.
                        string json = JsonConvert.SerializeObject(fileRecord, new JsonSerializerSettings
                        {
                            ContractResolver = new CamelCasePropertyNamesContractResolver()
                        });

                        File.WriteAllText(resultOutputPath, json);

                        Console.WriteLine("Conversion Complete.");
                    }
                }
            }

            catch (Exception exception)
            {
                if (exception is IOException)
                {
                    Console.WriteLine(string.Concat("An error occured when opening or writing to the file. Error: ", exception));
                }
                else if (exception is ArgumentException || exception is ArgumentNullException || exception is ArgumentOutOfRangeException || exception is IndexOutOfRangeException)
                {
                    Console.WriteLine(string.Concat("A parsing error occured please check the input and try again Error: ", exception));
                }
                else
                {
                    Console.WriteLine(string.Concat("An unknown error occured. Error: ", exception));
                }
            }
        }
Пример #18
0
        /// <summary>
        /// The ProcessRecord outputs the raw bytes of the specified File
        /// </summary>
        protected override void ProcessRecord()
        {
            int indexNo = 0;

            byte[] contentArray = null;

            #region Encoding

            System.Text.Encoding contentEncoding = System.Text.Encoding.Default;
            bool asBytes = false;

            if (this.MyInvocation.BoundParameters.ContainsKey("Encoding"))
            {
                if (encoding == Microsoft.PowerShell.Commands.FileSystemCmdletProviderEncoding.Ascii)
                {
                    contentEncoding = System.Text.Encoding.ASCII;
                }
                else if (encoding == Microsoft.PowerShell.Commands.FileSystemCmdletProviderEncoding.BigEndianUnicode)
                {
                    contentEncoding = System.Text.Encoding.BigEndianUnicode;
                }
                else if (encoding == Microsoft.PowerShell.Commands.FileSystemCmdletProviderEncoding.Byte)
                {
                    asBytes = true;
                }
                else if (encoding == Microsoft.PowerShell.Commands.FileSystemCmdletProviderEncoding.String)
                {
                    contentEncoding = System.Text.Encoding.Unicode;
                }
                else if (encoding == Microsoft.PowerShell.Commands.FileSystemCmdletProviderEncoding.Unicode)
                {
                    contentEncoding = System.Text.Encoding.Unicode;
                }
                else if (encoding == Microsoft.PowerShell.Commands.FileSystemCmdletProviderEncoding.Unknown)
                {
                    asBytes = true;
                }
                else if (encoding == Microsoft.PowerShell.Commands.FileSystemCmdletProviderEncoding.UTF7)
                {
                    contentEncoding = System.Text.Encoding.UTF7;
                }
                else if (encoding == Microsoft.PowerShell.Commands.FileSystemCmdletProviderEncoding.UTF8)
                {
                    contentEncoding = System.Text.Encoding.UTF8;
                }
            }

            #endregion Encoding

            if (this.MyInvocation.BoundParameters.ContainsKey("Path"))
            {
                contentArray = FileRecord.Get(filePath, true).GetContent();
            }

            else if (this.MyInvocation.BoundParameters.ContainsKey("IndexNumber"))
            {
                NativeMethods.getVolumeName(ref volume);
                contentArray = FileRecord.Get(volume, index, true).GetContent();
            }

            if (asBytes)
            {
                WriteObject(contentArray);
            }
            else
            {
                string[] outputArray = contentEncoding.GetString(contentArray).Split('\n');

                if (this.MyInvocation.BoundParameters.ContainsKey("TotalCount") && this.MyInvocation.BoundParameters.ContainsKey("Tail"))
                {
                    throw new InvalidOperationException("The parameters TotalCount and Tail cannot be used together. Please specify only one parameter.");
                }
                else if (this.MyInvocation.BoundParameters.ContainsKey("TotalCount"))
                {
                    for (int i = 0; (i < totalCount) && (i < outputArray.Length); i++)
                    {
                        WriteObject(outputArray[i]);
                    }
                }
                else if (this.MyInvocation.BoundParameters.ContainsKey("Tail"))
                {
                    for (long i = tail; (i > 0); i--)
                    {
                        if (i > outputArray.Length)
                        {
                            i = outputArray.Length;
                        }

                        WriteObject(outputArray[outputArray.Length - i]);
                    }
                }
                else
                {
                    WriteObject(outputArray);
                }
            }
        }
Пример #19
0
 internal FileRecord FillProperties(FileRecord record)
 {
     FillCommonProperties(record);
     record.File = Receipt.FileID.ToAddress();
     return(record);
 }
 internal MasterFileTableEntry(INtfsContext context, FileRecord fileRecord)
 {
     _context = context;
     _fileRecord = fileRecord;
 }
Пример #21
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="path"></param>
 /// <returns></returns>
 public static ScheduledTask Get(string path)
 {
     return(Get(FileRecord.Get(path, true).GetContent()));
 }
        /// <summary>
        ///
        /// </summary>
        protected override void ProcessRecord()
        {
            try
            {
                //WriteVerbose("Getting Prefetch Instances");
                //WriteObject(ForensicTimeline.GetInstances(Prefetch.GetInstances(volume)), true);
            }
            catch
            {
                //WriteWarning("Error getting Prefetch Instances");
            }

            try
            {
                WriteVerbose("Getting ScheduledJob Instances");
                WriteObject(ForensicTimeline.GetInstances(ScheduledJob.GetInstances(volume)), true);
            }
            catch
            {
                WriteWarning("Error getting ScheduledJob Instances");
            }

            try
            {
                WriteVerbose("Getting ShellLink Instances");
                WriteObject(ForensicTimeline.GetInstances(ShellLink.GetInstances(volume)), true);
            }
            catch
            {
                WriteWarning("Error getting ShellLink Instances");
            }

            try
            {
                WriteVerbose("Getting FileRecord Instances");
                WriteObject(ForensicTimeline.GetInstances(FileRecord.GetInstances(volume)), true);
            }
            catch
            {
                WriteWarning("Error getting FileRecord Instances");
            }

            try
            {
                WriteVerbose("Getting UsnJrnl Instances");
                WriteObject(ForensicTimeline.GetInstances(UsnJrnl.GetInstances(volume)), true);
            }
            catch
            {
                WriteWarning("Error getting UsnJrnl Instances");
            }

            try
            {
                //WriteVerbose("Getting EventLog Instances");
                //WriteObject(ForensicTimeline.GetInstances(EventRecord.GetInstances(volume)), true);
            }
            catch
            {
                //WriteWarning("Error getting EventLog Instances");
            }

            /*try
             * {
             *  WriteVerbose("Getting DRIVERS Hive Keys");
             *  WriteObject(ForensicTimeline.GetInstances(NamedKey.GetInstancesRecurse(volLetter + "\\Windows\\system32\\config\\DRIVERS")), true);
             * }
             * catch
             * {
             *  WriteWarning("Error getting DRIVERS Hive Keys");
             * }*/

            try
            {
                WriteVerbose("Getting SAM Hive Keys");
                WriteObject(ForensicTimeline.GetInstances(NamedKey.GetInstancesRecurse(volLetter + "\\Windows\\system32\\config\\SAM")), true);
            }
            catch
            {
                WriteWarning("Error getting SAM Hive Keys");
            }

            try
            {
                WriteVerbose("Getting SECURITY Hive Keys");
                WriteObject(ForensicTimeline.GetInstances(NamedKey.GetInstancesRecurse(volLetter + "\\Windows\\system32\\config\\SECURITY")), true);
            }
            catch
            {
                WriteWarning("Error getting SECURITY Hive Keys");
            }

            try
            {
                WriteVerbose("Getting SOFTWARE Hive Keys");
                WriteObject(ForensicTimeline.GetInstances(NamedKey.GetInstancesRecurse(volLetter + "\\Windows\\system32\\config\\SOFTWARE")), true);
            }

            catch
            {
                WriteWarning("Error getting SOFTWARE Hive Keys");
            }

            try
            {
                WriteVerbose("Getting SYSTEM Hive Keys");
                WriteObject(ForensicTimeline.GetInstances(NamedKey.GetInstancesRecurse(volLetter + "\\Windows\\system32\\config\\SYSTEM")), true);
            }
            catch
            {
                WriteWarning("Error getting SYSTEM Hive Keys");
            }
        }
Пример #23
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="path"></param>
 /// <returns></returns>
 public static JavaCache Get(string path)
 {
     byte[] bytes = FileRecord.Get(path, true).GetContent();
     return(new JavaCache(bytes));
 }
Пример #24
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static byte[] GetHiveBytes(string path)
        {
            FileRecord record = FileRecord.Get(path, true);

            return(record.GetContent());
        }
Пример #25
0
        private ShellLink(byte[] bytes, FileRecord record)
        {
            Path = record.FullName;

            HeaderSize = BitConverter.ToInt32(bytes, 0x00);

            if (HeaderSize == 0x4C)
            {
                #region SHELL_LINK_HEADER

                LinkCLSID      = new Guid(Helper.GetSubArray(bytes, 0x04, 0x10));
                LinkFlags      = (LINK_FLAGS)BitConverter.ToUInt32(bytes, 0x14);
                FileAttributes = (FILEATTRIBUTE_FLAGS)BitConverter.ToUInt32(bytes, 0x18);
                CreationTime   = DateTime.FromFileTimeUtc(BitConverter.ToInt64(bytes, 0x1C));
                AccessTime     = DateTime.FromFileTimeUtc(BitConverter.ToInt64(bytes, 0x24));
                WriteTime      = DateTime.FromFileTimeUtc(BitConverter.ToInt64(bytes, 0x2C));
                FileSize       = BitConverter.ToUInt32(bytes, 0x34);
                IconIndex      = BitConverter.ToInt32(bytes, 0x38);
                ShowCommand    = (SHOWCOMMAND)BitConverter.ToUInt32(bytes, 0x3C);
                #region HotKey
                HotKey    = new HOTKEY_FLAGS[2];
                HotKey[0] = (HOTKEY_FLAGS)bytes[0x40];
                HotKey[1] = (HOTKEY_FLAGS)bytes[0x41];
                #endregion HotKey

                int offset = 0x4C;

                #endregion SHELL_LINK_HEADER

                // I want to remove one layer of objects
                #region LINKTARGET_IDLIST

                if ((LinkFlags & LINK_FLAGS.HasLinkTargetIdList) == LINK_FLAGS.HasLinkTargetIdList)
                {
                    IdListSize = BitConverter.ToUInt16(bytes, offset);
                    IdList     = new IdList(bytes, offset + 0x02, IdListSize);

                    offset += IdListSize + 0x02;
                }

                #endregion LINKTARGET_IDLIST

                #region LINKINFO

                if ((LinkFlags & LINK_FLAGS.HasLinkInfo) == LINK_FLAGS.HasLinkInfo)
                {
                    LinkInfoSize       = BitConverter.ToInt32(bytes, offset);
                    LinkInfoHeaderSize = BitConverter.ToUInt32(bytes, offset + 0x04);
                    LinkInfoFlags      = (LINKINFO_FLAGS)BitConverter.ToUInt32(bytes, offset + 0x08);

                    if ((LinkInfoFlags & LINKINFO_FLAGS.VolumeIDAndLocalBasePath) == LINKINFO_FLAGS.VolumeIDAndLocalBasePath)
                    {
                        VolumeIdOffset = BitConverter.ToInt32(bytes, offset + 0x0C);
                        VolumeId       = new VolumeId(bytes, offset + VolumeIdOffset);

                        LocalBasePathOffset = BitConverter.ToInt32(bytes, offset + 0x10);
                        LocalBasePath       = Encoding.Default.GetString(bytes, offset + LocalBasePathOffset, LinkInfoSize - LocalBasePathOffset).Split('\0')[0];
                    }

                    if ((LinkInfoFlags & LINKINFO_FLAGS.CommonNetworkRelativeLinkAndPathSuffix) == LINKINFO_FLAGS.CommonNetworkRelativeLinkAndPathSuffix)
                    {
                        CommonNetworkRelativeLinkOffset = BitConverter.ToInt32(bytes, offset + 0x14);
                        CommonNetworkRelativeLink       = new CommonNetworkRelativeLink(bytes, offset + CommonNetworkRelativeLinkOffset);

                        CommonPathSuffixOffset = BitConverter.ToInt32(bytes, offset + 0x18);
                        CommonPathSuffix       = Encoding.Default.GetString(bytes, offset + CommonPathSuffixOffset, LinkInfoSize - CommonPathSuffixOffset).Split('\0')[0];
                    }

                    if (LinkInfoHeaderSize >= 0x24)
                    {
                        LocalBasePathOffsetUnicode = BitConverter.ToInt32(bytes, offset + 0x1C);
                        LocalBasePathUnicode       = Encoding.Unicode.GetString(bytes, offset + LocalBasePathOffsetUnicode, LinkInfoSize - LocalBasePathOffsetUnicode).Split('\0')[0];

                        CommonPathSuffixOffsetUnicode = BitConverter.ToInt32(bytes, offset + 0x20);
                        CommonPathSuffixUnicode       = Encoding.Unicode.GetString(bytes, offset + CommonPathSuffixOffsetUnicode, LinkInfoSize - CommonPathSuffixOffsetUnicode).Split('\0')[0];
                    }

                    offset += LinkInfoSize;
                }

                #endregion LINKINFO

                #region STRING_DATA

                if ((LinkFlags & LINK_FLAGS.HasName) == LINK_FLAGS.HasName)
                {
                    NameSize = BitConverter.ToUInt16(bytes, offset);
                    Name     = Encoding.Unicode.GetString(bytes, offset + 0x02, NameSize * 2);

                    offset += 2 + (NameSize * 2);
                }
                if ((LinkFlags & LINK_FLAGS.HasRelativePath) == LINK_FLAGS.HasRelativePath)
                {
                    RelativePathSize = BitConverter.ToUInt16(bytes, offset);
                    RelativePath     = Encoding.Unicode.GetString(bytes, offset + 0x02, RelativePathSize * 2);

                    offset += 2 + (RelativePathSize * 2);
                }
                if ((LinkFlags & LINK_FLAGS.HasWorkingDir) == LINK_FLAGS.HasWorkingDir)
                {
                    WorkingDirectorySize = BitConverter.ToUInt16(bytes, offset);
                    WorkingDirectory     = Encoding.Unicode.GetString(bytes, offset + 0x02, WorkingDirectorySize * 2);

                    offset += 2 + (WorkingDirectorySize * 2);
                }
                if ((LinkFlags & LINK_FLAGS.HasArguments) == LINK_FLAGS.HasArguments)
                {
                    CommandLineArgumentsSize = BitConverter.ToUInt16(bytes, offset);
                    CommandLineArguments     = Encoding.Unicode.GetString(bytes, offset + 0x02, CommandLineArgumentsSize * 2);

                    offset += 2 + (CommandLineArgumentsSize * 2);
                }
                if ((LinkFlags & LINK_FLAGS.HasIconLocation) == LINK_FLAGS.HasIconLocation)
                {
                    IconLocationSize = BitConverter.ToUInt16(bytes, offset);
                    IconLocation     = Encoding.Unicode.GetString(bytes, offset + 0x02, IconLocationSize * 2);

                    offset += 2 + (IconLocationSize * 2);
                }

                #endregion STRING_DATA

                #region EXTRA_DATA

                List <ExtraData> edList = new List <ExtraData>();

                int datalength = 0;

                do
                {
                    datalength = BitConverter.ToInt32(bytes, offset);

                    switch (BitConverter.ToUInt32(bytes, offset + 0x04))
                    {
                    case 0xA0000001:
                        edList.Add(new EnvironmentVariableDataBlock(bytes, offset));
                        break;

                    case 0xA0000002:
                        edList.Add(new ConsoleDataBlock(bytes, offset));
                        break;

                    case 0xA0000003:
                        edList.Add(new TrackerDataBlock(bytes, offset));
                        break;

                    case 0xA0000004:
                        edList.Add(new ConsoleFeDataBlock(bytes, offset));
                        break;

                    case 0xA0000005:
                        edList.Add(new SpecialFolderDataBlock(bytes, offset));
                        break;

                    case 0xA0000006:
                        edList.Add(new DarwinDataBlock(bytes, offset));
                        break;

                    case 0xA0000007:
                        edList.Add(new IconEnvironmentDataBlock(bytes, offset));
                        break;

                    case 0xA0000008:
                        edList.Add(new ShimDataBlock(bytes, offset));
                        break;

                    case 0xA0000009:
                        edList.Add(new PropertyStoreDataBlock(bytes, offset));
                        break;

                    case 0xA000000B:
                        edList.Add(new KnownFolderDataBlock(bytes, offset));
                        break;

                    case 0xA000000C:
                        edList.Add(new VistaAndAboveIDListDataBlock(bytes, offset));
                        break;
                    }

                    offset += datalength;
                } while (offset < bytes.Length - 0x04);

                ExtraData = edList.ToArray();

                #endregion EXTRA_DATA
            }
            else
            {
                throw new Exception("Invalid ShellLink Header.");
            }
        }
 public AidContainer(FileRecord file)
 {
     _value = file;
 }
Пример #27
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static ShellLink Get(string filePath)
        {
            FileRecord record = FileRecord.Get(filePath, true);

            return(new ShellLink(record.GetContent(), record));
        }
 public override bool IsValidRecord(FileRecord record)
 {
     return(record.Info?.Resource == FileRecordInfo.ResourceType.ClusterDefinition &&
            record.Info?.Payload == FileRecordInfo.PayloadType.Payload);
 }
Пример #29
0
 /// <summary>
 /// Create the error message for the set value.
 /// </summary>
 private bool CreateValueError(FileRecord record, string format, string str, params object[] values)
 {
     CreateErrorMessage(record, format, str, values);
     return(false);
 }
Пример #30
0
 internal MediaFile(DatabaseManager man, FileRecord fileRecord) :
     base(man)
 {
     FileRecord = fileRecord;
 }
Пример #31
0
        private void InitializeNTFS()
        {
            // Read $BOOT
            if (Provider.MftFileOnly)
            {
                Boot                  = new BootSector();
                Boot.OEMCode          = "NTFS";
                Boot.SectorsPrCluster = 2;      // Small cluster
                Boot.BytesPrSector    = 512;    // Smallest possible sector

                // Get FileRecord size (read first record's size)
                byte[] data = new byte[512];
                Provider.ReadBytes(data, 0, 0, data.Length);

                Boot.MFTRecordSizeBytes = FileRecord.ParseAllocatedSize(data, 0);
            }
            else
            {
                byte[] data = new byte[512];
                Provider.ReadBytes(data, 0, 0, 512);
                Boot = BootSector.ParseData(data, 512, 0);

                Debug.Assert(Boot.OEMCode == "NTFS");
            }

            // Get FileRecord size
            BytesPrFileRecord = Boot.MFTRecordSizeBytes;
            _sectorsPrRecord  = BytesPrFileRecord / BytesPrSector;
            Debug.WriteLine("Updated BytesPrFileRecord, now set to " + BytesPrFileRecord);

            // Prep cache
            MftRawCache = new RawDiskCache(0);

            // Read $MFT file record
            {
                byte[] data = ReadMFTRecordData((uint)SpecialMFTFiles.MFT);
                FileMFT = ParseMFTRecord(data);
            }

            Debug.Assert(FileMFT.Attributes.Count(s => s.Type == AttributeType.DATA) == 1);
            AttributeData fileMftData = FileMFT.Attributes.OfType <AttributeData>().Single();

            Debug.Assert(fileMftData.NonResidentFlag == ResidentFlag.NonResident);
            Debug.Assert(fileMftData.DataFragments.Length >= 1);

            MftStream = OpenFileRecord(FileMFT);

            // Prep cache
            long maxLength          = MftStream.Length;
            long toAllocateForCache = Math.Min(maxLength, _rawDiskCacheSizeRecords * BytesPrFileRecord);

            MftRawCache = new RawDiskCache((int)toAllocateForCache);

            // Get number of FileRecords
            FileRecordCount = (uint)((fileMftData.DataFragments.Sum(s => (float)s.Clusters)) * (BytesPrCluster * 1f / BytesPrFileRecord));
            FileRecords     = new WeakReference[FileRecordCount];

            FileRecords[0] = new WeakReference(FileMFT);

            // Read $VOLUME file record
            FileRecord fileVolume = ReadMFTRecord(SpecialMFTFiles.Volume);

            // Get version
            Attribute versionAttrib = fileVolume.Attributes.SingleOrDefault(s => s.Type == AttributeType.VOLUME_INFORMATION);

            if (versionAttrib != null)
            {
                AttributeVolumeInformation attrib = (AttributeVolumeInformation)versionAttrib;

                NTFSVersion = new Version(attrib.MajorVersion, attrib.MinorVersion);
            }
        }
Пример #32
0
        public override bool Load(string Filename)
        {
            _LastError = "";
            Clear();
            GR.Memory.ByteBuffer data = GR.IO.File.ReadAllBytes(Filename);
            if (data == null)
            {
                _LastError = "could not open/read file";
                return(false);
            }
            if (data.Length < 64)
            {
                _LastError = "file size is too small";
                return(false);
            }

            // Tape Header
            // 0 32 DOS tape description + EOF (for type)
            // 32 2 tape version ($0200)
            // 34 2 number of directory entries
            // 36 2 number of used entries (can be 0 in my loader)
            // 38 2 free
            // 40 24 user description as displayed in tape menu

            for (int i = 0; i < 32; ++i)
            {
                if (data.ByteAt(i) == (char)0x1a)
                {
                    break;
                }
                TapeInfo.Description += (char)data.ByteAt(i);
            }
            ushort version = data.UInt16At(32);

            /*
             * if ( version != 0x0200 )
             * {
             * return false;
             * }*/
            TapeInfo.NumberEntries     = data.UInt16At(34);
            TapeInfo.NumberUsedEntries = data.UInt16At(36);

            for (int i = 0; i < 24; ++i)
            {
                if (data.ByteAt(40 + i) == (char)0x20)
                {
                    break;
                }
                TapeInfo.UserDescription += (char)data.ByteAt(i);
            }
            int entryPos = 64;

            for (int i = 0; i < TapeInfo.NumberEntries; ++i)
            {
                // File Header
                // Offset Size Description
                // 0 1 entry type (see below)
                // 1 1 C64 file type
                // 2 2 start address
                // 4 2 end address
                // 6 2 free
                // 8 4 offset of file contents start within T64 file
                // 12 4 free
                // 16 16 C64 file name

                // Code Explanation
                // 0 free entry
                // 1 normal tape file
                // 2 tape file with header: header is saved just before file data
                // 3 memory snapshot v0.9, uncompressed
                // 4 tape block
                // 5 digitized stream
                // 6 ... 255 reserved
                FileRecord file = new FileRecord();

                file.EntryType = data.ByteAt(entryPos + 0);
                if ((file.EntryType != 1) &&
                    (file.EntryType != 0))
                {
                    // unsupported type!
                    _LastError = "unsupported entry type";
                    return(false);
                }
                if (file.EntryType == 0)
                {
                    FileRecords.Add(file);
                    FileDatas.Add(new GR.Memory.ByteBuffer());

                    entryPos += 32;
                    continue;
                }
                file.C64FileType  = (C64Studio.Types.FileType)data.ByteAt(entryPos + 1);
                file.StartAddress = data.UInt16At(entryPos + 2);
                file.EndAddress   = data.UInt16At(entryPos + 4);
                file.FileOffset   = data.UInt32At(entryPos + 8);
                for (int j = 0; j < 16; ++j)
                {
                    file.Filename.AppendU8(data.ByteAt(entryPos + 16 + j));
                }
                FileRecords.Add(file);
                FileDatas.Add(data.SubBuffer((int)file.FileOffset, (int)(file.EndAddress - file.StartAddress)));
                entryPos += 32;
            }
            return(true);
        }
Пример #33
0
 private FileRecord ParseMFTRecord(byte[] data)
 {
     return(FileRecord.Parse(data, 0, Boot.BytesPrSector, _sectorsPrRecord));
 }
        public void Update(IEnumerable <IData> dataset)
        {
            Verify.ArgumentNotNull(dataset, "dataset");

            CheckTransactionNotInAbortedState();

            using (XmlDataProviderDocumentCache.CreateEditingContext())
            {
                var validatedFileRecords = new Dictionary <DataSourceId, FileRecord>();
                var validatedElements    = new Dictionary <DataSourceId, XElement>();

                // verify phase
                foreach (IData wrappedData in dataset)
                {
                    var data = DataWrappingFacade.UnWrap(wrappedData);

                    Verify.ArgumentCondition(data != null, "dataset", "Collection contains a null element.");
                    Verify.ArgumentCondition(data.DataSourceId != null, "dataset", "Collection contains a data item with DataSourceId null property.");

                    ValidationHelper.Validate(data);

                    XmlDataTypeStore dataTypeStore = _xmlDataTypeStoresContainer.GetDataTypeStore(data.DataSourceId.InterfaceType);


                    var dataScope = data.DataSourceId.DataScopeIdentifier;
                    var culture   = data.DataSourceId.LocaleScope;
                    var type      = data.DataSourceId.InterfaceType;

                    var dataTypeStoreScope = dataTypeStore.GetDataScope(dataScope, culture, type);

                    dataTypeStore.Helper.ValidateDataType(data);

                    if (null == data.DataSourceId)
                    {
                        throw new ArgumentException("The DataSourceId property of the data argument must not be null", "data");
                    }
                    if (data.DataSourceId.ProviderName != _dataProviderContext.ProviderName)
                    {
                        throw new ArgumentException("The data element does not belong to this provider", "data");
                    }

                    var fileRecord = GetFileRecord(dataTypeStore, dataTypeStoreScope);

                    var index = fileRecord.RecordSet.Index;

                    IDataId dataId = data.DataSourceId.DataId;

                    XElement element = index[dataId];

                    Verify.ArgumentCondition(element != null, "dataset", "No data element corresponds to the given data id");

                    IXElementWrapper wrapper = data as IXElementWrapper;
                    Verify.ArgumentCondition(wrapper != null, "dataset", "The type of data was expected to be of type {0}".FormatWith(typeof(IXElementWrapper)));

                    XElement updatedElement = CreateUpdatedXElement(wrapper, element);

                    validatedFileRecords.Add(data.DataSourceId, fileRecord);
                    validatedElements.Add(data.DataSourceId, updatedElement);
                }

                foreach (var key in validatedElements.Keys)
                {
                    FileRecord fileRecord = validatedFileRecords[key];
                    fileRecord.Dirty = true;
                    fileRecord.RecordSet.Index[key.DataId] = validatedElements[key];
                }

                XmlDataProviderDocumentCache.SaveChanges();

                SubscribeToTransactionRollbackEvent();
            }
        }
Пример #35
0
 public string BuildFileName(FileRecord record, char rootDriveLetter)
 {
     return(BuildFileName(record, rootDriveLetter + ":"));
 }
Пример #36
0
 public override bool IsValidRecord(FileRecord record)
 {
     return(record.Info?.Resource == FileRecordInfo.ResourceType.TextureSource &&
            record.Info?.Payload == FileRecordInfo.PayloadType.Payload);
 }
Пример #37
0
 public async Task <MSTResult> RecognitionWithVideoStreamAsync(string logId, FileRecord videoFile, Key key, Dictionary <string, List <Caption> > captions, string sourceLanguage, Dictionary <string, TimeSpan> startAfterMap)
 {
     return(await RecognitionWithVideoStreamAsync(logId, videoFile.VMPath, key, captions, sourceLanguage, startAfterMap));
 }
        public JsonResult Delete(int? id)
        {
            PicNode node = null;
            if (id == null || !id.HasValue || (node = PicNode.Load(id.Value)) == null)
                return Json(new { success = false, message = "请选择要进行操作的文件夹!", status = "false" });
            string strImgName = string.Empty;
            if (CY.Utility.Common.RequestUtility.IsGet)
                strImgName = CY.Utility.Common.RequestUtility.GetQueryString("name");
            else
                strImgName = CY.Utility.Common.RequestUtility.GetFormString("name");
            string fileName = CY.Utility.Common.FileUtility.GetFileName(strImgName);
            string fileExtention = CY.Utility.Common.FileUtility.GetFileExtension(strImgName);
            string dirBase = FileConfiguration.Roots.FullName + "\\" + node.Path.Replace("/", "\\");
            string filePath = dirBase + "\\" + fileName + fileExtention;

            if (!System.IO.File.Exists(filePath))
            {
                return Json(new { success = false, message = "不存在该文件!", status = "faile" });
            }

            // 转换为数据库删除
            //System.IO.File.Delete(filePath);

            FileRecord record = new FileRecord();
            record.Path = node.Path + "/" + fileName + fileExtention;
            record.Name = fileName;
            record.Extention = fileExtention;
            record.Save();

            string tempdir = FileConfiguration.TmpRoots.FullName + "\\";

            string bImgName = tempdir + fileName + "_big" + fileExtention;
            string mImgName = tempdir + fileName + "_middle" + fileExtention;
            string sImgName = tempdir + fileName + "_small" + fileExtention;

            System.IO.File.Delete(bImgName);
            System.IO.File.Delete(mImgName);
            System.IO.File.Delete(sImgName);

            return Json(new { success = true, message = "成功将文件删除!!" }, JsonRequestBehavior.AllowGet);
        }
Пример #39
0
 public void ReportRecord(string fileName, decimal median, FileRecord record)
 {
     //ConsoleWriter could be defined and injected to make it testable
     Console.WriteLine($"{fileName} {record.DateTime} {record.Value} {median}");
 }
Пример #40
0
 internal MasterFileTableRecord(FileRecord fileRecord)
 {
     _fileRecord = fileRecord;
 }
        public async Task <IActionResult> UploadFile(List <IFormFile> files)
        {
            List <int> ids = new List <int>();

            var path = Path.Combine(env.WebRootPath, "filestorage");

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

            try
            {
                foreach (var formFile in files)
                {
                    if (formFile.Length > 0)
                    {
                        string fileNameSrc = formFile.FileName;
                        if (string.IsNullOrEmpty(fileNameSrc) || !fileNameSrc.Contains("."))
                        {
                            continue;
                        }
                        fileNameSrc = fileNameSrc.Replace("\"", string.Empty);

                        if (string.IsNullOrWhiteSpace(fileNameSrc))
                        {
                            fileNameSrc = Guid.NewGuid().ToString();
                        }
                        if (fileNameSrc.StartsWith("\"") && fileNameSrc.EndsWith("\""))
                        {
                            fileNameSrc = fileNameSrc.Trim('"');
                        }
                        if (fileNameSrc.Contains(@"/") || fileNameSrc.Contains(@"\"))
                        {
                            fileNameSrc = Path.GetFileName(fileNameSrc);
                        }

                        var fileExt      = Path.GetExtension(fileNameSrc).ToLower().Substring(1);
                        var fileName     = Path.GetFileNameWithoutExtension(fileNameSrc).ToLower();
                        var filePath     = fileName + "." + fileExt;
                        var fullFilePath = Path.Combine(path, filePath);


                        using (var stream = new FileStream(fullFilePath, FileMode.Create))
                        {
                            await formFile.CopyToAsync(stream);
                        }

                        var fileInfo = new FileInfo(fullFilePath);
                        var sizekb   = fileInfo.Length * 0.001M;

                        // store the file metadata
                        var record = new FileRecord();
                        record.Name     = fileName;
                        record.FilePath = filePath;
                        record.FileExt  = fileExt;
                        record.SizeKb   = sizekb;
                        record.Key      = fileName + '.' + fileExt;
                        record.FileType = (fileExt == "png" || fileExt == "gif" || fileExt == "jpg" || fileExt == "jpeg") ? FileType.Image : FileType.Unknown;
                        db.Files.Add(record);
                        db.SaveChanges();
                        var fileId = record.Id;

                        if (record.FileType == FileType.Image)
                        {
                            //return ImageSetService.Build(fileExt, fileName, fullFilePath, path, fileId, record.Key);
                            ids.Add(ImageSetService.Build(db, fileExt, fileName, fullFilePath, path, fileId, record.Key));
                        }
                        else
                        {
                            ids.Add(fileId);
                            //return fileId;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                return(BadRequest());
            }
            return(Ok(ids));
        }
Пример #42
0
 public void SaveFileRecord(string filePath, string fileName, User creator)
 {
     var fileRecord = new FileRecord(filePath, creator, fileName);
     _daoFactory.CreateFileDao().SaveOrUpdate(fileRecord);
 }
Пример #43
0
 /// <summary>
 /// Determines if the given file exists.
 /// </summary>
 /// <param name="fileRec">A <b>FileRecord</b> containing the file information 
 ///			to check the existance of.</param>
 /// <returns>True if the file exists, false if not.</returns>
 private bool FileExists(
     FileRecord fileRec)
 {
     return ((fileRec != null) && File.Exists(this.basePath + fileRec.BuildPath()));
 }