//todo: to be tested
        public static void SaveAs <T>(this IEnumerable <T> data, ConstructionDataContext context, string filename,
                                      FileType type, string description, Action <T> add, ILogPrint print = null, IShowProgress showProgress = null) where T : class, IFile
        {
            var file = new File
            {
                FileName    = filename,
                Type        = type,
                Description = description
            };
            var id = file.Add(context);

            print?.PrintLog("Start add item");
            showProgress?.SetMaxValue(data.Count());
            int step = 0;

            foreach (var item in data)
            {
                item.FileId = id;
                add.Invoke(item);
                step++;
                showProgress?.SetCurrentValue(step);
            }

            context.SaveChanges();
            showProgress?.Done();
        }
Пример #2
0
        private void barButtonItemAddFile_ItemClick(object sender, ItemClickEventArgs e)
        {
            var addForm = new FileEditWindow();

            if (addForm.ShowDialog() == DialogResult.OK)
            {
                using (var context = new ConstructionDataContext())
                {
                    context.Database.Log = PrintLog;
                    var file = new File
                    {
                        FileName = addForm.FileName,
                        Type     = addForm.FileType
                    };
                    if (!file.Exists(context))
                    {
                        try
                        {
                            file.Add(context);
                            DisplayFiles();
                        }
                        catch (Exception exception)
                        {
                            ShowException(exception, "Add file failed.");
                        }
                    }
                    else
                    {
                        MessageBox.Show(
                            $"The type of file has existed, please try another name. {file.Type}|{file.FileName}");
                    }
                }
            }
        }
        public async Task <ICommandResult> Handle(ImageAddCommand mesage)
        {
            try
            {
                var shard = await _shardingService.GetCurrentWriteShardByYear(ShardGroup);

                File file = new File(shard.Id);
                file.Add(mesage.FileName, mesage.Extentsion, File.TypeEnum.Image, mesage.FilePath, mesage.CreatedUid);
                await _fileRepository.Add(shard.ConnectionString, file);

                ICommandResult result = new CommandResult()
                {
                    Message  = "",
                    ObjectId = file.Id,
                    Status   = CommandResult.StatusEnum.Sucess
                };
                return(result);
            }
            catch (Exception e)
            {
                e.Data["Param"] = mesage;
                ICommandResult result = new CommandResult()
                {
                    Message = e.Message,
                    Status  = CommandResult.StatusEnum.Sucess
                };
                return(result);
            }
        }
Пример #4
0
        /// <summary>
        /// 新建文件
        /// </summary>
        public void NewFile(VirtualFile file)
        {
            //文件存在
            string str = ".file";

            if (!file.Name.EndsWith(str))
            {
                file.Name += str;
            }

            //foreach (var temp in File)
            //{
            //    if (temp.Name == file.Name)
            //    {
            //        throw new Exception("文件存在");
            //    }
            //}

            if (File.Any(temp => temp.Name == file.Name))
            {
                throw new Exception("文件存在");
            }

            file.Path    = Path + "/" + file.Name;
            file.NewTime = DateTime.Now.ToString(CultureInfo.InvariantCulture);
            //file.File = await FolderStorage.CreateFileAsync(file.Name);

            File.Add(file);
        }
Пример #5
0
 internal PdfElement AddElement(PdfElement element)
 {
     _elements.Add(element);
     element.SetupElement(this, ++_element_count);
     File.Add(element);
     return(element);
 }
        /// <summary>
        ///     获取所有文件编码
        /// </summary>
        private void InspectFileEncoding()
        {
            foreach (var temp in FaceFolder.GetFiles())
            //.Select(temp=>new EncodingScrutatorFile(temp)))//.Where(PredicateInclude))
            {
                //通知扫描到这个文件
                var file = new EncodingScrutatorFile(temp)
                {
                    //Parent = FaceFolder
                    Parent = this
                };
                Progress?.Report(file);
                File.Add(file);
                //文件是否包含
                if (!PredicateInclude(temp))
                {
                    file.Ignore = true;
                }


                if (!file.Ignore)
                {
                    new EncodingScrutator(file).InspectFileEncoding();
                }
            }
        }
Пример #7
0
        public void AddFile(User sender, MediaFile file)
        {
            if (!sender.Owns(this))
            {
                throw new AccessDeniedException();
            }

            File.Add(file);
        }
Пример #8
0
        public void Add(string name, string typeName, bool isEnabled)
        {
            File.Add(new InstanceSettings
            {
                Name      = name,
                TypeName  = typeName,
                IsEnabled = isEnabled
            });

            AddObject(name);
        }
Пример #9
0
        private static File SplitFolderLeft(File subFolder, string folderName)
        {
            subFolder.Parent.Files.Remove(subFolder);

            File newParentFolder = new File(folderName, FileType.Folder);
            newParentFolder.Parent = subFolder.Parent;
            subFolder.Parent.Files.Add(newParentFolder);
            newParentFolder.Add(subFolder);

            return newParentFolder;
        }
Пример #10
0
        private int AddFile()
        {
            var file = new File
            {
                FileName    = FileName,
                Type        = FileType.CellMapping,
                Description = Description
            };

            return(file.Add(Context));
        }
        public void Save(String path, CanvasGraph graph)
        {
            cgraph = graph;
            XElement root = new XElement("NetworkObservability");

            DumpTo(graph.Call(graphImpl => graphImpl), ref root);
            root.Add(CreateCommonAttributes(cgraph.CommonAttributes));
            File.Add(root);

            // New way to save
            File.Save(path);
        }
Пример #12
0
        public override void OnNavigatedTo(object sender, object obj)
        {
            List <FileMariyah> file = obj as List <FileMariyah>;

            if (file == null)
            {
                return;
            }
            _file = file;
            foreach (var temp in file)
            {
                File.Add(temp);
            }
        }
Пример #13
0
        public InterpreterEdit(String fileName, ExecutionContext parent)
            : base(parent)
        {
            File = SelectedVolume.GetByName(fileName);

            if (File == null)
            {
                File = new File(fileName);
                File.Add("");
            }

            CursorX = 0;
            CursorY = 2;
        }
Пример #14
0
        internal override bool Execute()
        {
            if (FileSystem.CurrentFile == null || FileSystem.directoriesAndFiles[FileSystem.CurrentFile.FirstBlockNumber] == null)
            {
                return(false);
            }
            File file = (File)FileSystem.directoriesAndFiles[FileSystem.CurrentFile.FirstBlockNumber];

            int[] clusters = FileSystem.FAT.GetFileBlocks(file.FirstClusterNumber);
            //
            // если нужно добавить еще кластеров
            //
            if (FileSystem.FileContent.Count < clusters.Length)
            {
                int   difference  = FileSystem.FileContent.Count - clusters.Length;
                int[] newClusters = new int[difference];
                for (int i = 0; i < difference; i++)
                {
                    newClusters[i] = FileSystem.FAT.GetNextFreeBlock(clusters[0]);
                    if (newClusters[i] == GlobalConstants.EOC)
                    {
                        return(false);
                    }
                    file.Add(FileSystem.ClusterSize, newClusters[i]);
                }
                // модифицировать clusters[]
                int[] clusters1 = new int[clusters.Length + difference];
                for (int i = 0; i < clusters.Length; i++)
                {
                    clusters1[i] = clusters[i];
                }
                int j = 0;
                for (int i = clusters.Length; i < clusters.Length + difference; i++, j++)
                {
                    clusters1[i] = newClusters[j];
                }
                clusters = clusters1;
            }
            for (int i = 0; i < FileSystem.FileContent.Count; i++)
            {
                file.Search(clusters[i]).Block = FileSystem.FileContent[i].ToCharArray();
            }
            FileSystem.directoriesAndFiles[FileSystem.CurrentFile.FirstBlockNumber] = file;  // потому что мы изменили файл (возможно, такое присвоение не обязательно)
            FileSystem.CurrentFile.LastDateRecorded.SetCurrentDate();
            FileSystem.CurrentFile.LastTimeRecorded.SetCurrentHours();
            return(true);
        }
Пример #15
0
        internal override bool Execute()
        {
            File file           = new File();
            int  clusterForFile = FileSystem.FAT.GetNextFreeBlock();

            if (clusterForFile != GlobalConstants.EOC)
            {
                Directory directory;
                if (FileSystem.directoriesAndFiles[directoryCluster] == null)
                {
                    return(false);
                }
                else
                {
                    directory = (Directory)FileSystem.directoriesAndFiles[directoryCluster];
                }

                if (directory.IsThereFreeSpace(directory.LastUsedClusterNumber))
                {
                    CatalogEntry catalogEntry = new CatalogEntry(attributes, 0, clusterForFile, name, extension);
                    if (directory.AddEntry(catalogEntry))
                    {
                        FileSystem.directoriesAndFiles[directoryCluster] = directory;
                        file.Add(FileSystem.ClusterSize, clusterForFile);
                        FileSystem.directoriesAndFiles[clusterForFile] = file;
                        return(true);
                    }
                }
                else
                {
                    int clusterForDirectory = FileSystem.FAT.GetNextFreeBlock(directory.FirstClusterNumber);
                    if (clusterForDirectory != GlobalConstants.EOC)
                    {
                        directory.Add(FileSystem.ClusterSize / 32, clusterForDirectory);   // потому что размер каталожной записи типо 32 байта
                        CatalogEntry catalogEntry = new CatalogEntry(attributes, 0, clusterForFile, name, extension);
                        if (directory.AddEntry(catalogEntry))
                        {
                            FileSystem.directoriesAndFiles[directoryCluster] = directory;
                            FileSystem.directoriesAndFiles[clusterForFile]   = file;
                            return(true);
                        }
                    }
                }
            }
            return(false);
        }
Пример #16
0
        /// <summary>
        /// Saves a **graph** object as Xml file at given path with
        /// a root name specified.
        /// </summary>
        /// <param name="path">File path to store **graph**.</param>
        /// <param name="graph">Graph object to be saved.</param>
        /// <param name="rootName">Root name of the Xml file.</param>
        /// <remarks>
        /// <see cref="DumpTo(IGraph, ref XElement)"/> will be used
        /// to store the **graph** object.
        /// </remarks>
        public void Save(String path, IGraph graph, String rootName)
        {
            XElement root = new XElement(rootName);

            DumpTo(graph, ref root);
            File.Add(root);

            // New way to save
            File.Save(path);

            // Old way to save

            /*
             * var xml = System.IO.File.Create(path);
             * var writer = new StreamWriter(xml);
             * File.Save(writer);
             * writer.Dispose();
             */
        }
        public static bool SaveAs <T>(this IEnumerable <T> data, ConstructionDataContext context, string filename,
                                      out int existsFileId, string description, ILogPrint print = null, IShowProgress showProgress = null) where T : class, IFile
        {
            existsFileId = 0;

            var enumerable = data as T[] ?? data.ToArray();


            var type = ConvertFileType(GetName(enumerable.First()));

            print?.PrintLog("Find the existing files.");
            var file = File.Select(context, filename, type);

            if (file != null)
            {
                existsFileId = file.Id;
                return(false);
            }

            file = new File
            {
                FileName    = filename,
                Description = description,
                Type        = type
            };
            var id = file.Add(context);

            print?.PrintLog($"The file id is {id}");
            showProgress?.SetMaxValue(enumerable.Length);
            int i = 0;

            foreach (var item in enumerable)
            {
                showProgress?.SetCurrentValue(i);
                item.FileId = id;
                i++;
            }
            print?.PrintLog("Saving data to database.");
            context.SaveChanges();
            showProgress?.Done();
            return(true);
        }
Пример #18
0
        private void btnAddFile_Click(object sender, EventArgs e)
        {
            if (pictureBox.Image != null)
            {
                File file = new File();

                file.Name = txtName.Text;
                file.Path = path;

                if (setId != Guid.Empty)
                {
                    file.Id = setId;
                    fileRepository.Update(file);
                }
                else
                {
                    fileRepository.Add(file);
                }
                Close();
            }
        }
Пример #19
0
        /// <summary>
        /// Updates the S2CP ID File with the cuurrent settings
        /// </summary>
        /// <param name="p">The Package to change/read from</param>
        /// <param name="guid">The packages GUID</param>
        /// <param name="name">The Name for the Package (used if the File is created)</param>
        /// <param name="author">Author of this package</param>
        /// <param name="contact">How to contact the Author</param>
        /// <param name="gameguid">The List of original Game Guids</param>
        /// <returns>the stored or the new GlobalGUID</returns>
        public static void UpdateGlobalGuid(File p, string guid, string name, string author, string contact, string gameguid)
        {
            Interfaces.Files.IPackedFileDescriptor pfd = p.FindFile(Data.MetaData.STRING_FILE, 0xffffffff, 0x00000000, 0xffffffff);
            SimPe.PackedFiles.Wrapper.Str          str = null;
            if (pfd == null)
            {
                str = new SimPe.PackedFiles.Wrapper.Str();

                str.FileDescriptor          = new SimPe.Packages.PackedFileDescriptor();
                str.FileDescriptor.Type     = Data.MetaData.STRING_FILE;
                str.FileDescriptor.Group    = 0;
                str.FileDescriptor.SubType  = 0xffffffff;
                str.FileDescriptor.Instance = 0xffffffff;
                str.SynchronizeUserData();
                str.Package = p;

                p.Add(str.FileDescriptor);
            }
            else
            {
                str = new SimPe.PackedFiles.Wrapper.Str();
                str.ProcessData(pfd, p);
            }

            SimPe.PackedFiles.Wrapper.StrLanguageList lng = new SimPe.PackedFiles.Wrapper.StrLanguageList();
            lng.Add(new SimPe.PackedFiles.Wrapper.StrLanguage(1));
            str.Languages = lng;

            if (guid == null)
            {
                guid = System.Guid.NewGuid().ToString();
            }
            str.Items = new SimPe.PackedFiles.Wrapper.StrItemList();
            str.Items.Add(new SimPe.PackedFiles.Wrapper.StrToken(0, lng[0], guid, gameguid));
            str.Items.Add(new SimPe.PackedFiles.Wrapper.StrToken(1, lng[0], author, contact));
            str.Items.Add(new SimPe.PackedFiles.Wrapper.StrToken(2, lng[0], name, ""));

            str.SynchronizeUserData();
        }
Пример #20
0
        public void TestComposite()
        {
            XmlConfigurator.Configure();
            XmlConfigurator.Configure();

            //Elemente vom Dateisystem anlegen
            IDirectoryElement knoten1 = new Folder("Wurzel");

            Assert.AreEqual(knoten1.Size(), 0);  // Test leerer Folder
            IDirectoryElement knoten2 = new Folder("Unterverzeichnis");
            IDirectoryElement blatt1  = new File(100, "Datei1");
            IDirectoryElement blatt2  = new File(500, "Datei2");
            IDirectoryElement blatt3  = new File(20, "Datei3");

            Assert.AreEqual(blatt3.Size(), 20);
            Assert.IsTrue(blatt3.Size() == 20);

            // Dateisystem (Folder und Files) zusammenbauen
            knoten1.Add(knoten2);
            knoten1.Add(blatt1);
            knoten1.Add(blatt2);
            knoten2.Add(blatt3);

            // Groesse des Dateisystems berechnen
            Assert.AreEqual(knoten1.Size(), 620);

            // Ausnahme bei Files testen
            try
            {
                blatt1.Add(blatt2);
                Assert.Fail();
            }
            catch (NotSupportedException e)
            {
                log.Info("Ausnahme unerlaubtes add erkannt");
            }
            log.Info("Test Composite erfolgreich");
        }
Пример #21
0
        public IDictionary <string, PlatformResult> AddResult(Result result)
        {
            File.Add(result);

            switch (result.Kind)
            {
            case ResultKind.Error:
                Errors.Add(result);
                break;

            case  ResultKind.Fail:
                Failures.Add(result);
                break;

            case ResultKind.Ignore:
                Ignores.Add(result);
                break;

            case ResultKind.Success:
                Success.Add(result);
                break;

            case ResultKind.NoError:
                NoErrors.Add(result);
                break;
            }

            string key = string.Format("{0}|{1}|{2}", result.Test.Fixture.Assembly.UniqueName, result.Test.Fixture.UniqueName, result.Test.UniqueName);

            var dict = ExpectedTests[key].ToDictionary(k => k.Platform, v => v);


            var miniKey = result.Platform;

            dict[miniKey].Result = result;

            return(dict);
        }
        public void HandleRequestFileUpload(C2SMessageReader mr)
        {
            if (!ServerCommunicationCenter.commCenter.ClientsEndPoint.ContainsKey(mr.ClientEP()))
            {
                return;
            }
            Debug.WriteLine("SR: Received request for registration");
            ServerMessageProvider smp = new ServerMessageProvider(SocketResourcesManager.srm.ProvideBuffer());
            OutputMessage         om;
            string fileFullName = mr.ReadRegisteringFileFullName();
            string ext          = Utils.GetFileExtensionFromPath(fileFullName);
            string name         = Utils.GetFileNameFromPath(fileFullName);

            bool duplikat = File.Exists(name, ext, mr.ReadRegisteringFileSize());

            if (!duplikat)
            {
                File f = new File();
                f.ApplicationId = mr.ClientEP();
                f.FileExtension = ext;
                f.FileName      = name;
                f.FileSize      = mr.ReadRegisteringFileSize();
                int fileId = f.Add();
                om = smp.ProvidePositiveUploadFileMessage(fileId);
                HashManager shr = new HashManager(mr.ClientEP(), Sizes.GetChunksNumber(mr.ReadRegisteringFileSize()), fileId, new ServerHashManagerListener());
                Debug.WriteLine("File: " + fileId);
                Debug.WriteLine("FileSize: " + f.FileSize);
                ServerObjectGraph.sog.FileRegistrations.Add(fileId, shr);
                Debug.WriteLine("SR: Registration approved");
            }
            else
            {
                om = smp.ProvideNegativeUploadFileMessage();
            }
            ServerCommunicationCenter.commCenter.SendMessageTo(mr.ClientEP(), om);
        }
Пример #23
0
 public void Add(File file)
 {
     file.Add(file);
 }
Пример #24
0
 void InterfaceFile.AddFile(File file)
 {
     file.Add(file);
 }
Пример #25
0
 public int AddFile(File file)
 {
     file.Updatetime = DateTime.UtcNow;
     return(_file.Add(file));
 }
Пример #26
0
        static void Main(string[] args)
        {
            try
            {
                if (args.Count() < 2)
                {
                    //Output Help Details
                    printHelp();
                    Environment.Exit(0); //Exit program after outputing message
                }
                if (args.Count() % 2 != 0)
                {
                    Environment.ExitCode = -2;
                }

                string  Key, Value;
                File    file    = new File(args[0]);
                Section section = file.Sections.Where(s => s["Text"]?.Value == args[1]).FirstOrDefault();
                if (section is null)
                {   //New Section
                    int maxSectionNumber = file.Sections.Where(n => n.Name.StartsWith("Item ")).Select(n => int.Parse(n.Name.Replace("Item ", ""))).Max();
                    section = new Section(string.Format("Item {0}", maxSectionNumber + 1));
                    section.Add(new KeyValuePair("Text", args[1]));
                    for (int i = 2; i <= args.Count() - 2; i += 2)
                    {
                        Key   = args[i];
                        Value = args[i + 1];
                        section.Add(new KeyValuePair(Key, Value));
                    }
                    file.Add(section);
                }
                else
                {   //Existing Section with specified Text Value
                    for (int i = 2; i <= args.Count() - 2; i += 2)
                    {
                        Key   = args[i];
                        Value = args[i + 1];
                        try { section[Key].Value = Value; }                  //Existing Key
                        catch { section.Add(new KeyValuePair(Key, Value)); } //New Key
                    }
                }
                //Retry multiple times before failing
                int Retry = 12;
                for (int t = 0; t <= Retry; t++)
                {
                    try { file.Write(); break; }
                    catch (System.IO.IOException tEx) { if (t >= Retry)
                                                        {
                                                            throw tEx;
                                                        }
                    }
                    System.Threading.Thread.Sleep(1000 * 5);
                }
                Console.WriteLine(string.Format("File saved successfully: {0}", args[0]));
            }
            catch (System.IO.DirectoryNotFoundException) { Environment.ExitCode = -4; Console.WriteLine("Directory not found."); }
            catch (System.IO.DriveNotFoundException) { Environment.ExitCode = -4; Console.WriteLine("Drive not found."); }
            catch (System.IO.EndOfStreamException) { Environment.ExitCode = -3; Console.WriteLine("End of stream Exception."); }
            catch (System.IO.FileLoadException) { Environment.ExitCode = -3; Console.WriteLine("File load Exception."); }
            catch (System.IO.PathTooLongException) { Environment.ExitCode = -3; Console.WriteLine("Path too long."); }
            catch (System.IO.FileNotFoundException) { Environment.ExitCode = -4; Console.WriteLine("File not found."); }
            catch (System.IO.IOException ioEx) { Environment.ExitCode = -3; Console.WriteLine(String.Format("An IO excection has occured: {0}", ioEx)); }
            catch (System.UnauthorizedAccessException) { Environment.ExitCode = -5; Console.WriteLine("Unauthorized Access"); }
            catch (Exception ex) { Environment.ExitCode = -1; Console.WriteLine(String.Format("An unknown exception has occured: {0}", ex)); }
        }
Пример #27
0
        /// <summary>
        /// Updates the S2CP ID File with the cuurrent settings
        /// </summary>
        /// <param name="p">The Package to change/read from</param>
        /// <param name="title">Title of this Object</param>
        /// <param name="description">Description of this Package</param>
        /// <returns>the stored or the new GlobalGUID</returns>
        public static void UpdateGlobalGuid(File p, string title, string description)
        {
            Interfaces.Files.IPackedFileDescriptor pfd = null;
            SimPe.PackedFiles.Wrapper.Str          str = null;

            SimPe.PackedFiles.Wrapper.StrLanguage[] lng = new SimPe.PackedFiles.Wrapper.StrLanguage[1];
            lng[0] = new SimPe.PackedFiles.Wrapper.StrLanguage(1);

            //Title and Description is stored in the CatalogString
            Interfaces.Files.IPackedFileDescriptor[] pfds = p.FindFiles(Data.MetaData.OBJD_FILE);
            uint ctssid = 1;
            uint group  = 0xffffffff;

            if (pfds.Length > 0)
            {
                SimPe.PackedFiles.Wrapper.Objd objd = new SimPe.PackedFiles.Wrapper.Objd(null);
                objd.ProcessData(pfds[0], p);
                ctssid = objd.CTSSId;
                group  = objd.FileDescriptor.Group;
            }

            pfd = p.FindFile(Data.MetaData.CTSS_FILE, 0, group, ctssid);
            if (pfd == null)
            {
                str = new SimPe.PackedFiles.Wrapper.Str();

                str.FileDescriptor          = new SimPe.Packages.PackedFileDescriptor();
                str.FileDescriptor.Type     = Data.MetaData.CTSS_FILE;
                str.FileDescriptor.Group    = 0xffffffff;
                str.FileDescriptor.SubType  = 0x00000000;
                str.FileDescriptor.Instance = 0x1;

                str.Languages.Add(lng[0]);

                p.Add(str.FileDescriptor);
            }
            else
            {
                str = new SimPe.PackedFiles.Wrapper.Str();
                str.ProcessData(pfd, p);
            }

            SimPe.PackedFiles.Wrapper.StrItemList items = str.LanguageItems(1);
            if (str.Items.Length > 0)
            {
                str.Items[0].Title = title;
            }
            else
            {
                str.Add(new SimPe.PackedFiles.Wrapper.StrToken(0, lng[0], title, ""));
            }

            if (str.Items.Length > 1)
            {
                str.Items[1].Title = description;
            }
            else
            {
                str.Add(new SimPe.PackedFiles.Wrapper.StrToken(1, lng[0], description, ""));
            }

            str.SynchronizeUserData();
        }