public static void Extract(Files files)
 {
     if ((files & Files.InTheHandManaged) == Files.InTheHandManaged)
     {
         if (!File.Exists("InTheHand.Net.Personal.dll"))
             File.WriteAllBytes("InTheHand.Net.Personal.dll", Resources.InTheHand_Net_Personal);
     }
     if ((files & Files.InTheHandNative) == Files.InTheHandNative)
     {
         if (!File.Exists("32feetWidcomm.dll"))
         {
             if (CPU.Is64BitOperatingSystem())
                 File.WriteAllBytes("32feetWidcomm.dll", Resources._32feetWidcommx64);
             else
                 File.WriteAllBytes("32feetWidcomm.dll", Resources._32feetWidcommx86);
         }
     }
     if ((files & Files.VLC) == Files.VLC)
     {
         if (!File.Exists("libvlc.dll"))
             File.WriteAllBytes("libvlc.dll", Resources.libvlc);
         if (!File.Exists("libvlccore.dll"))
             File.WriteAllBytes("libvlccore.dll", Resources.libvlccore);
         if (!File.Exists("Vlc.DotNet.Core.dll"))
             File.WriteAllBytes("Vlc.DotNet.Core.dll", Resources.Vlc_DotNet_Core);
         if (!File.Exists("Vlc.DotNet.Forms.dll"))
             File.WriteAllBytes("Vlc.DotNet.Forms.dll", Resources.Vlc_DotNet_Forms);
     }
 }
Пример #2
0
        public Form1()
        {
            InitializeComponent();

            Files mainView = new Files() { Dock = DockStyle.Fill };
            Controls.Add(mainView);
        }
Пример #3
0
 public void Execute(object parameter)
 {
     Contact c = (Contact)parameter;
     Files FilesPage = new Files(c);
     App.Current.MainWindow = FilesPage;
     FilesPage.Show();
 }
Пример #4
0
		public SerwerSMS( String username, String password ){
		
			if( string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password) ){
				throw new Exception("Brak danych");
			}
			
			
			this.username 	= 	username;
			this.password 	= 	password;
			
			this.messages 	= 	new Messages(this);
			this.files 		= 	new Files(this);
			this.blacklist  = 	new Blacklist(this);
			this.error 		= 	new Errors(this);
			this.phones 	= 	new Phones(this);
			this.stats 		= 	new Stats(this);
			this.account 	= 	new Account(this);
			this.contacts 	= 	new Contacts(this);
			this.groups		= 	new Groups(this);
			this.payments	= 	new Payments(this);
			this.senders	= 	new Senders(this);
			this.premium	= 	new Premium(this);
			this.templates	= 	new Templates(this);
			this.subaccounts= 	new Subaccounts(this);
					
		}
Пример #5
0
        public IQueryable<Files> List(string virtualPath)
        {
            string RepositoryDirectory = "c:\\ClientFiles";

            string basePath = RepositoryDirectory;

            if (!string.IsNullOrEmpty(virtualPath))
                basePath = Path.Combine(RepositoryDirectory, virtualPath);

            DirectoryInfo dirInfo = new DirectoryInfo(basePath);
            FileInfo[] files = dirInfo.GetFiles("*.*", SearchOption.AllDirectories);

            var vv = (from f in files
                      select new StorageFileInfo()
                      {
                          Size = f.Length,
                          VirtualPath = f.FullName.Substring(f.FullName.IndexOf(RepositoryDirectory) + RepositoryDirectory.Length + 1)
                      }).ToArray();

            var lff = new List<Files>();
            foreach (var info in vv)
            {
                var ff = new Files();
                ff.FileName = info.VirtualPath;
                ff.FileSize = info.Size;
                lff.Add(ff);
            }
            return lff.AsQueryable();
        }
Пример #6
0
        public Files ConvertToCotents()
        {
            Files aFiles = new Files();

            aFiles.Code = this.Code;
            aFiles.Info = this.Info;
            aFiles.Intro = this.Intro;
            aFiles.Title = this.Title;

            aFiles.CodeAlbums = this.CodeAlbums;
            aFiles.CreateByIDUser = this.CreateByIDUser;
            aFiles.Disable = this.Disable;
            aFiles.DownloadCount = this.DownloadCount;
            aFiles.Height = this.Height;
            aFiles.Width = this.Width;
            aFiles.ID = this.ID;
            aFiles.IDLang = this.IDLang;

            aFiles.Image = this.Image;
            aFiles.Image1 = this.Image1;
            aFiles.Image2 = this.Image2;
            aFiles.Image3 = this.Image3;
            aFiles.Info = this.Info;
            aFiles.Status = this.Status;
            aFiles.Type = this.Type;
            aFiles.UploadDate = this.UploadDate;
            aFiles.ViewCount = this.ViewCount;

            return aFiles;
        }
Пример #7
0
        public void SetValue(Files aFiles)
        {
            this.AlbumsName = "";
            this.Code = aFiles.Code;
            this.CodeAlbums = aFiles.CodeAlbums;
            this.CreateByIDUser = aFiles.CreateByIDUser;
            this.Disable = aFiles.Disable;
            this.DownloadCount = aFiles.DownloadCount;
            this.Height = aFiles.Height;
            this.Width = aFiles.Width;
            this.ID = aFiles.ID;
            this.IDLang = aFiles.IDLang;

            this.Image = aFiles.Image;
            this.Image1 = aFiles.Image1;
            this.Image2 = aFiles.Image2;
            this.Image3 = aFiles.Image3;
            this.Info = aFiles.Info;
            this.Status = aFiles.Status;
            this.Type = aFiles.Type;
            this.UploadDate = aFiles.UploadDate;
            this.ViewCount = aFiles.ViewCount;

            this.Info = aFiles.Info;
            this.Intro = aFiles.Intro;
            this.Title = aFiles.Title;
        }
Пример #8
0
        public Download(string url, string file, FileDownloaded completionCallback, ProgressCallback progressCallback, Files f)
        {
            try
            {
                m_Url = url;
                m_CompletionCallback = completionCallback;
                try
                {
                    m_Stream = new FileStream( file, FileMode.OpenOrCreate, FileAccess.Write );
                }
                catch (IOException e)
                {
                    file = String.Concat( file, ".new" );
                    m_Stream = new FileStream( file, FileMode.OpenOrCreate, FileAccess.Write );
                }

                m_ProgressCallback = progressCallback;
                m_File = f;
                m_Thread = new Thread(new ThreadStart(DownloadFile));
                m_Thread.Start();
            }
            catch (Exception)
            {
                throw;
            }
        }
Пример #9
0
 public ActionResult Create(FormCollection collection)
 {
     var model = new Files();
     this.TryUpdateModel<Files>(model);
     this.ProjectService.SaveFile(model);
     return this.RefreshParent();
 }
Пример #10
0
        public ActionResult Create(AddStudentVM vm, HttpPostedFileBase upload)
        {
            var id = _work.EnrollDep.Find(x => x.Depid == vm.Depid && x.Campid == vm.Campid).Select(x => x.DepEnrolId);
            int enrollid = id.Single();

            var id2 = _work.EnrollBatch.Find(x => x.batch_id == vm.batch_id && x.DepEnrolId == enrollid).Select(x => x.BatchEnrolId);
            int BatchEnrollId = id2.Single();

            var SecEnrollId = _work.EnrollSection.Find(x => x.sec_id == vm.sec_id && x.BatchEnrolId == BatchEnrollId).Select(x => x.SecEnrolId).Single();

            Files f = new Files();
            Student st = new Student();

            st.Name = vm.Name;
            st.Email = vm.Email;
            st.Phone = vm.Phone;
            st.SecEnrolId = SecEnrollId;
            st.CreateDate = vm.CreateDate;
            st.semester = Semester.First.ToString();

            var errors = ModelState.Values.SelectMany(v => v.Errors);
            if (ModelState.IsValid)
            {
                if (upload != null && upload.ContentLength > 0)
                {

                    string path = Path.Combine(Server.MapPath("~/ProfilePhotos"),
                                      Path.GetFileName(upload.FileName));
                    upload.SaveAs(path);

                    ViewBag.Message = "File uploaded successfully";

                    f.FileName = Path.GetFileName(upload.FileName);
                }

                st.file = f;

                IEnumerable<CourseToDep> Allcourse = _work.CourseToDep.Find(x => x.semester == Semester.First && x.DepEnrolId == enrollid);

                List<StudentRegistration> obj = new List<StudentRegistration>();

                foreach (CourseToDep c in Allcourse)
                {
                    StudentRegistration reg = new StudentRegistration();
                    reg.Grades = Grades.initial;
                    reg.PersonId = f.PersonId;
                    reg.Semester = Semester.First;
                    reg.CId = c.CId;
                    reg.CreateDate = vm.CreateDate;
                    obj.Add(reg);
                }
                st.StudentReg = obj;

                _work.Student.Insert(st);
                _work.Save();

            }
            return RedirectToAction("Index");
        }
Пример #11
0
 public static int AddFileToDB(Files fi)
 {
     using (var db = new IndexerModel())
     {
         db.Files.Add(fi);
         return db.SaveChanges();
     }
 }
Пример #12
0
        public LocalLister(Files files, BackupProgress backupProgress)
        {
            this.files = files;
            this.backupProgress = backupProgress;

            executor = new AbortableTaskExecutor(ListBackupLocations);
            Settings.Default.PropertyChanged += SettingsChanged;
        }
Пример #13
0
        //
        // GET: /Cms/Files/

        public ActionResult Index(FileRequest request)
        {
          //  ViewData.Add("Channal", new SelectList(EnumHelper.GetItemValueList<EnumChannal>(), "Key", "Value"));
            var model = new Files();
            this.RenderMyViewData(model);
            var result = this.ProjectService.GetFileList(request);
            return View(result);
        }
Пример #14
0
 public void Setup()
 {
     files = new Files();
     abcdFile = File(mocks, "abcd");
     files.Add(abcdFile);
     abdcFile = File(mocks, "abdc");
     files.Add(abdcFile);
     history = new HistoryTest.HistoryStub();
 }
Пример #15
0
        public BackupEngine(Files files, BackupProgress backupProgress)
        {
            this.files = files;
            this.backupProgress = backupProgress;

            executor = new AbortableTaskExecutor(Backup);
            retryHelper = new RetryHelper();
            retryHelper.ExceptionOccured += ExceptionOccured;
        }
Пример #16
0
 public ActionResult Create(FormCollection collection)
 {
     var model = new Files();
     model.SignDate = DateTime.Now.ToString("yyyy/MM/dd");
     model.FulfillDate = DateTime.Now.ToString("yyyy/MM/dd");
     model.EndDate = DateTime.Now.ToString("yyyy/MM/dd");
     model.Code = "NO."+model.CreateTime.ToFileTime();
     this.TryUpdateModel<Files>(model);
     this.ProjectService.SaveFile(model);
     return this.RefreshParent();
 }
Пример #17
0
 static void Main()
 {
     Application.EnableVisualStyles();
     Application.SetCompatibleTextRenderingDefault(false);
     Files F = new Files();
   /*  try
     {
         F.LoadSettings(Defines.SettingFilePath);
     }catch(Exception ex) { MessageBox.Show("读取配置文件失败。错误信息:\n" + ex.Message, "错误提示"); } */
     Application.Run(new MainForm());
 }
Пример #18
0
        public void AddFile(string content, ASSET_TYPES assetType)
        {
            using (var fileContext = new FileContext()) {
                var file = new Files {
                    AssetTypeID = (int)assetType,
                    Content = content
                };

                fileContext.FilesDS.Add(file);
                fileContext.SaveChanges();
            }
        }
Пример #19
0
        public void Put(Files request)
        {
            var targetFile = GetAndValidateExistingPath(request);

            if (!this.Config.TextFileExtensions.Contains(targetFile.Extension))
                throw new NotSupportedException("PUT Can only update text files, not: " + targetFile.Extension);

            if (request.TextContents == null)
                throw new ArgumentNullException("TextContents");

            File.WriteAllText(targetFile.FullName, request.TextContents);
        }
Пример #20
0
        private void toFiles(object sender, RoutedEventArgs e)
        {
            var item = (sender as FrameworkElement).DataContext;
            int index = ContactListView.Items.IndexOf(item);

            int contactIndex = Contacts.ElementAt(index).UserId;

            Console.WriteLine("Index of item clicked files: " + contactIndex);

            Files newFilesWpf = new Files(contactIndex);
            newFilesWpf.Show();
        }
Пример #21
0
Файл: Form1.cs Проект: LKND/FM
 private void btnOpenFile_Click(object sender, EventArgs e)
 {
     progressBar1.Maximum = 100;
     for (int i = 0; i < 100; i++)
     {
         progressBar1.Value = i;
         System.Threading.Thread.Sleep(10);
     }
     MessageBox.Show("Файл Открыт");
     progressBar1.Value = 0;
     Files files=new Files();
     files.Open();
 }
Пример #22
0
 /// <summary>
 /// POST数据
 /// </summary>
 /// <param name="requestUrl"></param>
 /// <param name="parameters"></param>
 /// <param name="files"></param>
 /// <param name="callback"></param>
 protected virtual void PostData(string requestUrl, Parameters parameters, Files files, Action<string> callback)
 {
     this.LastError = null;
     this.AddOAuthParameter("POST", requestUrl, parameters);
     var request = new AsyncHttpRequest(requestUrl, this.OAuth.Charset) { Parameters = parameters };
     if (files != null)
     {
         request.PostFile(EndGetResponseData, files, callback);
     }
     else
     {
         request.Post(EndGetResponseData, callback);
     }
 }
Пример #23
0
        public object Get(Files request)
        {
            var targetFile = GetAndValidateExistingPath(request);

            var isDirectory = Directory.Exists(targetFile.FullName);

            if (!isDirectory && request.ForDownload)
                return new HttpResult(targetFile, asAttachment: true);

            var response = isDirectory
                ? new FilesResponse { Directory = GetFolderResult(targetFile.FullName) }
                : new FilesResponse { File = GetFileResult(targetFile) };

            return response;
        }
Пример #24
0
 public void Upload(Action<Status> callback, UploadFile image, string status, string source = null,
                    string location = null, string mode = null, string format = null)
 {
     if (string.IsNullOrEmpty(status)) throw new ArgumentException("status不能为空");
     UpdateStatusCallBack = callback;
     var parameters = new Parameters();
     parameters.Add("status", status);
     if (!string.IsNullOrEmpty(source)) parameters.Add("source", source);
     if (!string.IsNullOrEmpty(mode)) parameters.Add("mode", mode);
     if (!string.IsNullOrEmpty(format)) parameters.Add("format", format);
     if (!string.IsNullOrEmpty(location)) parameters.Add("location", location);
     var file = new Files();
     file.Add("photo", image);
     PostData("http://api.fanfou.com/photos/upload.json", parameters, file, UpdateStatusEnd);
 }
Пример #25
0
 private void SaveFileAs(string title) //另存为文件
 {
     SaveFileDialog FileExplorer = new SaveFileDialog();
     FileExplorer.Title = title;
     FileExplorer.FileName = Files.CurrentFile;
     FileExplorer.Filter = "所有文件|*.*|Smart Z源文件|*.zs|C#源文件|*.cs|C++源文件|*.cpp";
     if (FileExplorer.ShowDialog() != DialogResult.OK) return;
     string FilePath = FileExplorer.FileName;
     byte[] FileContent = System.Text.Encoding.Default.GetBytes(this.richTextBox1.Text);
     try
     {
         Files F = new Files();
         F.SaveFile(FilePath, FileContent);
         this.IfSaved = true; //设置为已保存
         this.Text = Files.CurrentFile + " - " + Defines.DefaultMainFormTitle;
     }
     catch (Exception ex) { MessageBox.Show("保存文件失败:\n" + ex.Message, "错误消息", MessageBoxButtons.OK); }
 }
Пример #26
0
 private void SaveFile() //保存文件
 {
     string FilePath = null;
     if (Files.CurrentFile == null)
     {
         this.SaveFileAs();
         return;
     }
     else { FilePath = Files.CurrentFile; }
     byte[] FileContent = System.Text.Encoding.Default.GetBytes(this.richTextBox1.Text);
     try
     {
         Files F = new Files();
         F.SaveFile(FilePath, FileContent);
         this.IfSaved = true; //设置为已保存
         this.Text = Files.CurrentFile + " - " + Defines.DefaultMainFormTitle;
     }
     catch (Exception ex) { MessageBox.Show("保存文件失败:\n" + ex.Message, "错误消息", MessageBoxButtons.OK); }
 }
Пример #27
0
        public void cd(string next)
        {
            if (current.directory(next) == true)
            {
                this.current = current.nomdossier(next);

                    int taille = arbo.Length;
                    Array.Resize(ref arbo, taille + 1);
                    arbo[taille] = next;
            }
            if (current.directorydfiles(next) == true)
            {
                this.current = current.nomdossier(next);

                int taille = arbo.Length;
                Array.Resize(ref arbo, taille + 1);
                arbo[taille] = next;
            }
        }
Пример #28
0
        public JsonResult AddFiles(string RelationID, string files, bool isDel)
        {
            string[] arrFile = Server.UrlDecode(files).Split('|');
            if (isDel)
                FilesService.instance().DeleteByRelationID(new Guid(RelationID));
            foreach (var item in arrFile)
            {
                Files f = new Files();
                f.ID = Guid.NewGuid();
                f.CompanyID = UserDateTicket.Company.ID;
                f.RelationID = new Guid(RelationID);
                f.Type = 0;
                f.Large = f.FilePath = f.Middle = f.Small = item;
                f.FileExt = System.IO.Path.GetExtension(item);
                f.FileSize = Util.Utils.GetFileSize_(System.Configuration.ConfigurationManager.AppSettings["sourceWeb"] + item);
                FilesService.instance().Insert(f);

            }
            return Json("ok", JsonRequestBehavior.AllowGet);
        }
Пример #29
0
        public void Post(Files request)
        {
            var targetDir = GetPath(request);

            var isExistingFile = targetDir.Exists
                && (targetDir.Attributes & FileAttributes.Directory) != FileAttributes.Directory;

            if (isExistingFile)
                throw new NotSupportedException(
                "POST only supports uploading new files. Use PUT to replace contents of an existing file");

            if (!Directory.Exists(targetDir.FullName))
                Directory.CreateDirectory(targetDir.FullName);

            foreach (var uploadedFile in base.RequestContext.Files)
            {
                var newFilePath = Path.Combine(targetDir.FullName, uploadedFile.FileName);
                uploadedFile.SaveTo(newFilePath);
            }
        }
Пример #30
0
        public void Run()
        {
            var portList = new List<PortListingItem>
            {
                    new PortListingItem("FTP", 21),
                    new PortListingItem("SSH", 22),
                    new PortListingItem("SMTP", 25),
                    new PortListingItem("HTTP", 80)
                };

            using (var fileCT = new FileContext())
            {
                var file = new Files
                {
                    AssetTypeID = (int) ASSET_TYPES.PORT_DEFINITIONS,
                    Content = BasePA.GetJSONStringFromT(new PortDefinitionsResponseItem {Ports = portList})
                };

                fileCT.FilesDS.Add(file);
                fileCT.SaveChanges();
            }
        }
Пример #31
0
        /// <summary>
        /// Action: Browse
        /// </summary>
        /// <param name="objectId">Associated State Variable: A_ARG_TYPE_ObjectID</param>
        /// <param name="browseFlag">Associated State Variable: A_ARG_TYPE_BrowseFlag</param>
        /// <param name="filter">Associated State Variable: A_ARG_TYPE_Filter</param>
        /// <param name="startingIndex">Associated State Variable: A_ARG_TYPE_Index</param>
        /// <param name="requestedCount">Associated State Variable: A_ARG_TYPE_Count</param>
        /// <param name="sortCriteria">Associated State Variable: A_ARG_TYPE_SortCriteria</param>
        /// <param name="result">Associated State Variable: A_ARG_TYPE_Result</param>
        /// <param name="numberReturned">Associated State Variable: A_ARG_TYPE_Count</param>
        /// <param name="totalMatches">Associated State Variable: A_ARG_TYPE_Count</param>
        /// <param name="updateID">Associated State Variable: A_ARG_TYPE_UpdateID</param>
        public override void Browse(String objectId, Enum_A_ARG_TYPE_BrowseFlag browseFlag, String filter, UInt32 startingIndex,
                                    UInt32 requestedCount, String sortCriteria, out String result, out UInt32 numberReturned, out UInt32 totalMatches,
                                    out UInt32 updateID)
        {
            updateID       = 0;
            numberReturned = 0;
            totalMatches   = 0;
            StringBuilder sb = new StringBuilder();

            sb.AppendLine(@"<DIDL-Lite xmlns:dc=""http://purl.org/dc/elements/1.1/"" " +
                          @"xmlns:upnp=""urn:schemas-upnp-org:metadata-1-0/upnp/"" " +
                          @"xmlns=""urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/"">");
            try
            {
                FolderBase folder    = (objectId == "0" || objectId == "-1") ? new MainEntry() : GetFolder(objectId);
                var        userAgent = GetUserAgent();

                switch (browseFlag)
                {
                case Enum_A_ARG_TYPE_BrowseFlag.BROWSEDIRECTCHILDREN:
                    bool isFreeboxV5 = (userAgent == UserAgent.FreeboxV5);
                    if (isFreeboxV5)
                    {
                        // In order to enchain the audio files on the Freebox V5
                        IPAddress address = GetCaller().Address;
                        if (Files.ContainsKey(address))
                        {
                            Files.Remove(address);
                        }
                    }

                    FolderBase   subFolder;
                    BrowseResult browseResult;
                    bool         exit = false;
                    do
                    {
                        // Browse the folder
                        browseResult = folder.Browse(startingIndex, requestedCount, userAgent);

                        if (browseResult != null && browseResult.TotalCount == 1 && browseResult.Entries.Count > 0)
                        {
                            // If there is only 1 folder, we will browse the subfolder
                            subFolder = browseResult.Entries[0] as FolderBase;
                            if (subFolder == null)
                            {
                                exit = true;
                            }
                            else
                            {
                                folder = subFolder;
                            }
                        }
                        else
                        {
                            exit = true;
                        }
                    }while (!exit);

                    if (browseResult != null)
                    {
                        bool   v6Workaround = (userAgent == UserAgent.FreeboxV6 && !folder.UsePathAsId && String.IsNullOrEmpty(folder.Path));
                        string line;
                        string dcTitle = "<dc:title>";
                        var    format  = dcTitle + Podcast.GetLinesNumberingFormat(browseResult.TotalCount);
                        int    i       = 1;
                        foreach (var entry in browseResult.Entries)
                        {
                            if (entry is Shutdown && Application.IsMono)
                            {
                                // Unable to shutdown on Linux, Mac
                                browseResult.TotalCount -= 1;
                                continue;
                            }

                            line = entry.ToString(GetReceiver(), objectId, userAgent);
                            if (line == null)
                            {
                                browseResult.TotalCount -= 1;
                                continue;
                            }

                            if (v6Workaround)
                            {
                                // To keep the order of the folders
                                line = line.Replace(dcTitle, String.Format(format, i + startingIndex, String.Empty));
                                i   += 1;
                            }
                            sb.AppendLine(line);
                            numberReturned += 1;
                            AddToFileList(entry, isFreeboxV5);
                        }
                        totalMatches = (uint)browseResult.TotalCount;
                    }
                    break;

                default:
                    sb.AppendLine((folder ?? (Entry) new Entries.File()
                    {
                        Path = HttpUtility.UrlDecode(objectId)
                    }).ToString(GetReceiver(), "-1", userAgent));
                    numberReturned = 1;
                    totalMatches   = 1;
                    break;
                }
            }
            catch (Exception ex)
            {
                Utils.WriteException(ex);
            }
            sb.Append(@"</DIDL-Lite>");
            result = sb.ToString();
        }
Пример #32
0
        public void Run(string[] args)
        {
            Logger.Log(LogLevel.Info, Log.CORE_START, Util.GetProductName(), Util.GetProductVersion(), Util.GetProductAuthor());
            Logger.Log(LogLevel.Verbose, Log.CORE_READ_CONFIG);
            config = Files.ReadConfig <CoreConfiguration>();
            Logger.Log(LogLevel.Info, Log.CORE_READ_CONFIG_OK);
            Logger.MinLevel  = config.LogMinimumLevel;
            Logger.LogToFile = config.LogToFile;
            Logger.LogFile   = config.LogFileName;

            components.Add(Database);
            components.Add(Server);
            components.Add(WebAdmin);
            components.Add(Plugins);

            if (config.EnableRuntime)
            {
                components.Add(Rcon);
                components.Add(Players);
                components.Add(Announce);
                components.Add(Game);
                components.Add(Commands);
                components.Add(Mods);

                if (Config.EnableEmptyRestart)
                {
                    components.Add(new EmptyRestart(this));
                }
            }

            Scheduler.TickDelay = Config.TickDelay;

            Rcon.Disconnected += new EventHandler(Rcon_Disconnected);
            Rcon.ChatInput    += new EventHandler(Rcon_Chat);

            Server.ServerStarted += new EventHandler(Server_Started);
            Server.ServerStopped += new EventHandler(Server_Stopped);
            Server.ServerCrashed += new EventHandler(Server_Crashed);

            Announce.Broadcast += new EventHandler(Announce_Broadcast);

            foreach (ComponentBase h in components)
            {
                h.Configure(Config);
                h.OnInit();
                if (h.UpdateInterval > 0)
                {
                    Scheduler.PushRepeatingTask(h.Task);
                }
            }

            if (!Database.WebUserExists())
            {
                SetupWebUser();
            }
            else
            {
                foreach (string s in args)
                {
                    if (s.Equals(ARG_RESET_WEBUSER))
                    {
                        Logger.Log(LogLevel.Info, "Resetting web users...");
                        Database.TruncateWebUsers();
                        SetupWebUser();
                    }
                }
            }

            Scheduler.Start();
            if (Config.AutoLaunchServer)
            {
                Scheduler.PushTask(Server.Start);
            }

            string cmd = string.Empty;

            while ((cmd = Console.ReadLine()) != "quit")
            {
                if (cmd == "import maps")
                {
                    Database.ImportMaps(ServerMap.ReadServerMapConfig(this));
                }
                else if (Commands.IsConsoleCommand(cmd))
                {
                    //using the scheduler to execute so we dont have to worry about concurrency
                    Scheduler.PushTask(() => { Commands.HandleConsoleCommand(cmd); });
                }
            }

            Scheduler.Stop();
            foreach (ComponentBase h in components)
            {
                h.OnDeInit();
            }
        }
 private string getListOfCurrentJarStubsForClassPath(string classPath)
 {
     foreach (var jarStubFile in Files.getFilesFromDir_returnFullPath(IKVMConfig.jarStubsCacheDir))
         classPath += string.Format(";\"{0}\"", jarStubFile);
     return classPath;
 }        
Пример #34
0
 public bool Exists(string filename)
 {
     return(Files.ContainsKey(filename));
 }
Пример #35
0
        public void Parse()
        {
            // We go through all includes from all files
            // This is a list of yet unparsed included files
            var Includes = new List <string> {
                RootFilePath
            };

            while (Includes.Count != 0)
            {
                var newIncludes = new List <string>();

                foreach (var file in Includes)
                {
                    var parsed = new SourceFile(file);
                    parsed.Parse();

                    if (parsed.ModuleName != Name)
                    {
                        ErrorReporter.ErrorFL("File is included in module {1} but belongs in module {2}",
                                              file, Name, parsed.ModuleName);
                    }

                    foreach (var include in parsed.Includes)
                    {
                        var actualInclude = Path.Combine(new FileInfo(file).DirectoryName, include);
                        if (Files.Contains(actualInclude))
                        {
                            ErrorReporter.NoteFL("Trying to include {0} into the module {1} but it is already included",
                                                 file, include, Name);
                        }

                        newIncludes.Add(actualInclude);
                    }

                    foreach (var import in parsed.Imports)
                    {
                        // Standard library imports are handled specially
                        if (import.StartsWith("std", 0))
                        {
                            Imports.Add(import);
                            continue;
                        }

                        var actualImport = Path.Combine(
                            new FileInfo(file).DirectoryName,
                            import.Replace('.', Path.DirectorySeparatorChar));

                        if (!Imports.Contains(actualImport))
                        {
                            Imports.Add(actualImport);
                        }
                    }
                }

                Includes.ForEach((x) => Files.Add(x));

                Includes.Clear();
                Includes = newIncludes;
            }
        }
 public override void WriteFile(string path, string content) => Files.Add(path, content);
Пример #37
0
 private void DeleteFileAction()
 {
     workstationService.RemoveFile(SelectedFile);
     Files.Remove(Files.Where(x => x.FileId == SelectedFile.FileId).Single());
 }
Пример #38
0
        protected void BtnUpload_Click(object sender, EventArgs e)
        {
            if (!this.FupFile.HasFile)
            {
                this.ReturnManage("上传失败,重新上传。");
                return;
            }
            int  uploadFileMaxSize = 0;
            int  uploadSize        = 0;
            bool flag  = false;
            bool flag2 = false;

            if (!SiteConfig.SiteOption.EnableUploadFiles)
            {
                this.ReturnManage("权限错误:对不起网站没有开启上传权限。");
                return;
            }
            if (!PEContext.Current.Admin.Identity.IsAuthenticated)
            {
                if (!PEContext.Current.User.Identity.IsAuthenticated)
                {
                    UserGroupsInfo userGroupById = UserGroups.GetUserGroupById(-2);
                    if (string.IsNullOrEmpty(userGroupById.GroupSetting))
                    {
                        this.ReturnManage("匿名会员组不存在!");
                        return;
                    }
                    UserPurviewInfo groupSetting = UserGroups.GetGroupSetting(userGroupById.GroupSetting);
                    if (groupSetting.IsNull)
                    {
                        this.ReturnManage("匿名会员组没有进行权限设置!");
                        return;
                    }
                    if (!groupSetting.EnableUpload)
                    {
                        this.ReturnManage("匿名会员组没有开启上传权限!");
                        return;
                    }
                    uploadSize = groupSetting.UploadSize;
                }
                else
                {
                    if (!PEContext.Current.User.UserInfo.UserPurview.EnableUpload)
                    {
                        this.ReturnManage("所属会员组没有开启上传权限!");
                        return;
                    }
                    uploadSize = PEContext.Current.User.UserInfo.UserPurview.UploadSize;
                }
            }
            string str = Path.GetExtension(this.FupFile.FileName).ToLower();

            if (!this.CheckFilePostfix(str.Replace(".", "")))
            {
                this.ReturnManage("上传文件类型不对!必须上传" + this.m_FileExtArr + "的后缀名!");
                return;
            }
            if (string.Compare(this.m_ModuleName, "Node", StringComparison.OrdinalIgnoreCase) == 0)
            {
                FieldInfo           fieldInfoByFieldName = Field.GetFieldInfoByFieldName(this.m_ModelId, this.m_FieldName);
                Collection <string> settings             = fieldInfoByFieldName.Settings;
                switch (fieldInfoByFieldName.FieldType)
                {
                case FieldType.PictureType:
                    uploadFileMaxSize = DataConverter.CLng(settings[1]);
                    flag2             = DataConverter.CBoolean(settings[4]);
                    flag = DataConverter.CBoolean(settings[5]);
                    goto Label_01EA;

                case FieldType.FileType:
                    uploadFileMaxSize = DataConverter.CLng(settings[0]);
                    goto Label_01EA;
                }
            }
            else
            {
                uploadFileMaxSize = SiteConfig.SiteOption.UploadFileMaxSize;
            }
Label_01EA:
            if (!PEContext.Current.Admin.Identity.IsAuthenticated && (uploadFileMaxSize > uploadSize))
            {
                uploadFileMaxSize = uploadSize;
            }
            if (((int)this.FupFile.FileContent.Length) > (uploadFileMaxSize * 0x400))
            {
                this.ReturnManage("请上传小于" + uploadFileMaxSize.ToString() + "KB的文件!");
            }
            else
            {
                string str2     = DataSecurity.MakeFileRndName();
                string filename = FileSystemObject.CreateFileFolder((VirtualPathUtility.AppendTrailingSlash(SiteConfig.SiteOption.UploadDir) + this.FileSavePath()).Replace("//", "/"), HttpContext.Current) + str2 + str;
                this.FupFile.SaveAs(filename);
                string thumbnailPath = "";
                if (flag)
                {
                    thumbnailPath = this.m_ShowPath + str2 + "_S" + str;
                    Thumbs.GetThumbsPath(this.m_ShowPath + str2 + str, thumbnailPath);
                }
                else
                {
                    thumbnailPath = this.m_ShowPath + str2 + str;
                }
                if (flag2)
                {
                    WaterMark.AddWaterMark(this.m_ShowPath + str2 + str);
                }
                EasyOne.Model.Accessories.FileInfo fileInfo = new EasyOne.Model.Accessories.FileInfo();
                fileInfo.Name  = this.FupFile.FileName;
                fileInfo.Path  = thumbnailPath;
                fileInfo.Size  = (int)this.FupFile.FileContent.Length;
                fileInfo.Quote = 1;
                if (string.Compare(this.m_ModuleName, "soft", StringComparison.OrdinalIgnoreCase) == 0)
                {
                    Files.Add(fileInfo);
                }
                this.GetScriptByModuleName(fileInfo);
                this.ReturnManage("上传成功!");
            }
        }
Пример #39
0
        // **** Corpus Layout ****
        //
        // Test_Corpus (directory)
        // Test_Corpus.imdi (corpus meta data file)
        // Test_Corpus\Test_Corpus_Catalog.imdi (catalogue of information)
        // Test_Corpus\Test_Session (directory)
        // Test_Corpus\Test_Session.imdi (session meta data file)
        // Test_Corpus\Test_Session\Contributors (directory - contains files pertaining to contributers/actors)
        // Test_Corpus\Test_Session\Files*.* (session files)
        // Test_Corpus\Contributors\Files*.* (contributor/actor files)

        /// <summary>Add a file for this contributor</summary>
        /// <param name="file"></param>
        public void AddFile(IMDIFile file)
        {
            Files.Add(file);
        }
Пример #40
0
    /// <summary>
    /// 提交后保存
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnUpload_Click(object sender, EventArgs e)
    {
        string UploadFileName = "";
        string UploadType     = Request.Form["Upload"];                       //文件方式
        int    FileSize       = StringDeal.ToInt(GetConfig.File("FileSize")); //文件最大上传
        string UploadFilePath = GetConfig.File("UploadFilePath");             //文件上传路径
        string SelectFile     = Request.Form["SelectFile"];                   //选择服务器上的文件名
        string WebUrl         = Request.Form["WebUrl"];                       //网络文件地址

        if (String.IsNullOrEmpty(UploadFilePath))
        {
            UploadFilePath = "../../Upload/File/";
        }
        if (FileSize == 0)
        {
            FileSize = 1020000;
        }
        else
        {
            FileSize = FileSize * 1024;
        }
        if (UploadType == "upload1")
        {
            UploadFilePath = UploadFilePath + DateTime.Today.ToString("yyyyMM") + "/";
            Files.CreateFolder(UploadFilePath);
            #region 大文件上传
            try
            {
                foreach (Telerik.WebControls.UploadedFile file in RadUploadContext.Current.UploadedFiles)
                {
                    if (file.FileName != "")
                    {
                        if (file.ContentLength > FileSize)
                        {
                            StringDeal.Alter("文件大小不能超过" + FileSize / 1024 + "KB");
                        }
                        else if (FormatUploadType(file.FileName))
                        {
                            string FileExt = file.GetExtension();
                            System.Threading.Thread.Sleep(1000);
                            string FileName = StringDeal.GetGuid() + FileExt;
                            file.SaveAs(this.Server.MapPath(UploadFilePath + FileName), true);
                            Response.StatusCode = 200;
                            UploadFileName      = UploadFilePath + FileName;
                        }
                        else
                        {
                            StringDeal.Alter("上传文件格式不正确!");
                        }
                    }
                }
            }
            catch
            {
            }
            #endregion
        }
        else if (UploadType == "upload2")
        {
            #region  择服务器上的保存
            UploadFileName = SelectFile;
            #endregion
        }
        else
        {
            #region 输入网络文件地址保存
            UploadFileName = WebUrl;
            #endregion
        }

        Response.Write("<script language='javascript' type='text/javascript'>window.parent.loadinndlg().document.getElementById('" + InputName + "').value='" + UploadFileName + "';window.parent.cancel();</script>");
    }
Пример #41
0
        /// <inheritdoc />
        public override void Process(BotData data)
        {
            base.Process(data);

            // Setup
            var request = new Request();

            request.Setup(data.GlobalSettings, securityProtocol, AutoRedirect, data.ConfigSettings.MaxRedirects, AcceptEncoding);

            var localUrl = ReplaceValues(Url, data);

            data.Log(new LogEntry($"Calling URL: {localUrl}", Colors.MediumTurquoise));

            // Set content
            switch (RequestType)
            {
            case RequestType.Standard:
                request.SetStandardContent(ReplaceValues(PostData, data), ReplaceValues(ContentType, data), Method, EncodeContent, GetLogBuffer(data));
                break;

            case RequestType.BasicAuth:
                request.SetBasicAuth(ReplaceValues(AuthUser, data), ReplaceValues(AuthPass, data));
                break;

            case RequestType.Multipart:
                var contents = MultipartContents.Select(m =>
                                                        new MultipartContent()
                {
                    Name        = ReplaceValues(m.Name, data),
                    Value       = ReplaceValues(m.Value, data),
                    ContentType = ReplaceValues(m.Value, data),
                    Type        = m.Type
                });
                request.SetMultipartContent(contents, ReplaceValues(MultipartBoundary, data), GetLogBuffer(data));
                break;
            }

            // Set proxy
            if (data.UseProxies)
            {
                request.SetProxy(data.Proxy);
            }

            // Set headers
            data.Log(new LogEntry("Sent Headers:", Colors.DarkTurquoise));
            var headers = CustomHeaders.Select(h =>
                                               new KeyValuePair <string, string> (ReplaceValues(h.Key, data), ReplaceValues(h.Value, data))
                                               ).ToDictionary(h => h.Key, h => h.Value);

            request.SetHeaders(headers, AcceptEncoding, GetLogBuffer(data));

            // Set cookies
            data.Log(new LogEntry("Sent Cookies:", Colors.MediumTurquoise));

            foreach (var cookie in CustomCookies) // Add new user-defined custom cookies to the bot's cookie jar
            {
                data.Cookies[ReplaceValues(cookie.Key, data)] = ReplaceValues(cookie.Value, data);
            }

            request.SetCookies(data.Cookies, GetLogBuffer(data));

            // End the request part
            data.LogNewLine();

            // Perform the request
            try
            {
                (data.Address, data.ResponseCode, data.ResponseHeaders, data.Cookies) = request.Perform(localUrl, Method, GetLogBuffer(data));
            }
            catch (Exception ex)
            {
                if (data.ConfigSettings.IgnoreResponseErrors)
                {
                    data.Log(new LogEntry(ex.Message, Colors.Tomato));
                    data.ResponseSource = ex.Message;
                    return;
                }
                throw;
            }

            // Save the response content
            switch (ResponseType)
            {
            case ResponseType.String:
                data.ResponseSource = request.SaveString(ReadResponseSource, data.ResponseHeaders, GetLogBuffer(data));
                break;

            case ResponseType.File:
                if (SaveAsScreenshot)
                {
                    Files.SaveScreenshot(request.GetResponseStream(), data);     // Read the stream
                    data.Log(new LogEntry("File saved as screenshot", Colors.Green));
                }
                else
                {
                    request.SaveFile(ReplaceValues(DownloadPath, data), GetLogBuffer(data));
                }
                break;

            case ResponseType.Base64String:
                var base64 = Convert.ToBase64String(request.GetResponseStream().ToArray());
                InsertVariable(data, false, base64, OutputVariable);
                break;

            default:
                break;
            }
        }
Пример #42
0
    /// <summary>
    /// Moves document.
    /// </summary>
    private void PerformAction(object parameter)
    {
        AddLog(GetString(CopyMoveAction.ToLowerCSafe() == "copy" ? "media.copy.startcopy" : "media.move.startmove"));

        if (LibraryInfo != null)
        {
            // Library path (used in recursive copy process)
            string libPath = MediaLibraryInfoProvider.GetMediaLibraryFolderPath(SiteContext.CurrentSiteName, LibraryInfo.LibraryFolder);

            // Ensure libPath is in original path type
            libPath = Path.GetFullPath(libPath);

            // Original path on disk from query
            string origPath = Path.GetFullPath(DirectoryHelper.CombinePath(libPath, FolderPath));

            // Original path in DB
            string origDBPath = Path.EnsureSlashes(FolderPath);

            // New path in DB
            string newDBPath;

            AddLog(NewPath);

            // Check if requested folder is in library root folder
            if (!origPath.StartsWithCSafe(libPath, true))
            {
                CurrentError = GetString("media.folder.nolibrary");
                AddLog(CurrentError);
                return;
            }

            string origFolderName = Path.GetFileName(origPath);

            if ((String.IsNullOrEmpty(Files) && !mAllFiles) && string.IsNullOrEmpty(origFolderName))
            {
                NewPath = NewPath + "\\" + LibraryInfo.LibraryFolder;
                NewPath = NewPath.Trim('\\');
            }

            // New path on disk
            string newPath = NewPath;

            // Process current folder copy/move action
            if (String.IsNullOrEmpty(Files) && !AllFiles)
            {
                newPath = Path.EnsureEndBackslash(newPath) + origFolderName;
                newPath = newPath.Trim('\\');

                // Check if moving into same folder
                if ((CopyMoveAction.ToLowerCSafe() == "move") && (newPath == FolderPath))
                {
                    CurrentError = GetString("media.move.foldermove");
                    AddLog(CurrentError);
                    return;
                }

                // Error if moving folder into itself
                string newRootPath           = Path.GetDirectoryName(newPath).Trim();
                string newSubRootFolder      = Path.GetFileName(newPath).ToLowerCSafe().Trim();
                string originalSubRootFolder = Path.GetFileName(FolderPath).ToLowerCSafe().Trim();
                if (String.IsNullOrEmpty(Files) && (CopyMoveAction.ToLowerCSafe() == "move") && newPath.StartsWithCSafe(Path.EnsureEndBackslash(FolderPath)) &&
                    (originalSubRootFolder == newSubRootFolder) && (newRootPath == FolderPath))
                {
                    CurrentError = GetString("media.move.movetoitself");
                    AddLog(CurrentError);
                    return;
                }

                try
                {
                    // Get unique path for copy or move
                    string path = Path.GetFullPath(DirectoryHelper.CombinePath(libPath, newPath));
                    path    = MediaLibraryHelper.EnsureUniqueDirectory(path);
                    newPath = path.Remove(0, (libPath.Length + 1));

                    // Get new DB path
                    newDBPath = Path.EnsureSlashes(newPath.Replace(Path.EnsureEndBackslash(libPath), ""));
                }
                catch (Exception ex)
                {
                    CurrentError = GetString("general.erroroccurred") + " " + ex.Message;
                    EventLogProvider.LogException("MediaFolder", CopyMoveAction, ex);
                    AddLog(CurrentError);
                    return;
                }
            }
            else
            {
                origDBPath = Path.EnsureSlashes(FolderPath);
                newDBPath  = Path.EnsureSlashes(newPath.Replace(libPath, "")).Trim('/');
            }

            // Error if moving folder into its subfolder
            if ((String.IsNullOrEmpty(Files) && !AllFiles) && (CopyMoveAction.ToLowerCSafe() == "move") && newPath.StartsWithCSafe(Path.EnsureEndBackslash(FolderPath)))
            {
                CurrentError = GetString("media.move.parenttochild");
                AddLog(CurrentError);
                return;
            }

            // Error if moving files into same directory
            if ((!String.IsNullOrEmpty(Files) || AllFiles) && (CopyMoveAction.ToLowerCSafe() == "move") && (newPath.TrimEnd('\\') == FolderPath.TrimEnd('\\')))
            {
                CurrentError = GetString("media.move.fileserror");
                AddLog(CurrentError);
                return;
            }

            NewPath      = newPath;
            AsyncNewPath = newPath;

            // If mFiles is empty handle directory copy/move
            if (String.IsNullOrEmpty(Files) && !mAllFiles)
            {
                try
                {
                    switch (CopyMoveAction.ToLowerCSafe())
                    {
                    case "move":
                        MediaLibraryInfoProvider.MoveMediaLibraryFolder(SiteContext.CurrentSiteName, MediaLibraryID, origDBPath, newDBPath);
                        break;

                    case "copy":
                        MediaLibraryInfoProvider.CopyMediaLibraryFolder(SiteContext.CurrentSiteName, MediaLibraryID, origDBPath, newDBPath, CurrentUser.UserID);
                        break;
                    }
                }
                catch (UnauthorizedAccessException ex)
                {
                    CurrentError = GetString("general.erroroccurred") + " " + GetString("media.security.accessdenied");
                    EventLogProvider.LogException("MediaFolder", CopyMoveAction, ex);
                    AddLog(CurrentError);
                }
                catch (ThreadAbortException ex)
                {
                    if (CMSThread.Stopped(ex))
                    {
                        // When canceled
                        CurrentInfo = GetString("general.actioncanceled");
                        AddLog(CurrentInfo);
                    }
                    else
                    {
                        // Log error
                        CurrentError = GetString("general.erroroccurred") + " " + ex.Message;
                        EventLogProvider.LogException("MediaFolder", CopyMoveAction, ex);
                        AddLog(CurrentError);
                    }
                }
                catch (Exception ex)
                {
                    CurrentError = GetString("general.erroroccurred") + " " + ex.Message;
                    EventLogProvider.LogException("MediaFolder", CopyMoveAction, ex);
                    AddLog(CurrentError);
                }
            }
            else
            {
                string origDBFilePath;
                string newDBFilePath;

                if (!mAllFiles)
                {
                    try
                    {
                        string[] files = Files.Split('|');
                        foreach (string filename in files)
                        {
                            origDBFilePath = (string.IsNullOrEmpty(origDBPath)) ? filename : origDBPath + "/" + filename;
                            newDBFilePath  = (string.IsNullOrEmpty(newDBPath)) ? filename : newDBPath + "/" + filename;
                            AddLog(filename);
                            CopyMove(origDBFilePath, newDBFilePath);
                        }
                    }
                    catch (UnauthorizedAccessException ex)
                    {
                        CurrentError = GetString("general.erroroccurred") + " " + GetString("media.security.accessdenied");
                        EventLogProvider.LogException("MediaFile", CopyMoveAction, ex);
                        AddLog(CurrentError);
                    }
                    catch (ThreadAbortException ex)
                    {
                        if (CMSThread.Stopped(ex))
                        {
                            // When canceled
                            CurrentInfo = GetString("general.actioncanceled");
                            AddLog(CurrentInfo);
                        }
                        else
                        {
                            // Log error
                            CurrentError = GetString("general.erroroccurred") + " " + ex.Message;
                            EventLogProvider.LogException("MediaFile", CopyMoveAction, ex);
                            AddLog(CurrentError);
                        }
                    }
                    catch (Exception ex)
                    {
                        CurrentError = GetString("general.erroroccurred") + " " + ex.Message;
                        EventLogProvider.LogException("MediaFile", CopyMoveAction, ex);
                        AddLog(CurrentError);
                    }
                }
                else
                {
                    var fileNames = GetFileNames().ToList();
                    if (!fileNames.Any())
                    {
                        return;
                    }

                    foreach (string fileName in fileNames)
                    {
                        AddLog(fileName);

                        origDBFilePath = (string.IsNullOrEmpty(origDBPath)) ? fileName : origDBPath + "/" + fileName;
                        newDBFilePath  = (string.IsNullOrEmpty(newDBPath)) ? fileName : newDBPath + "/" + fileName;

                        try
                        {
                            CopyMove(origDBFilePath, newDBFilePath);
                        }
                        catch (UnauthorizedAccessException ex)
                        {
                            CurrentError = GetString("general.erroroccurred") + " " + GetString("media.security.accessdenied");
                            EventLogProvider.LogException("MediaFile", CopyMoveAction, ex);
                            AddLog(CurrentError);
                            return;
                        }
                        catch (ThreadAbortException ex)
                        {
                            if (CMSThread.Stopped(ex))
                            {
                                // When canceled
                                CurrentInfo = GetString("general.actioncanceled");
                                AddLog(CurrentInfo);
                            }
                            else
                            {
                                // Log error
                                CurrentError = GetString("general.erroroccurred") + " " + ex.Message;
                                EventLogProvider.LogException("MediaFile", CopyMoveAction, ex);
                                AddLog(CurrentError);
                                return;
                            }
                        }
                        catch (Exception ex)
                        {
                            CurrentError = GetString("general.erroroccurred") + " " + ex.Message;
                            EventLogProvider.LogException("MediaFile", CopyMoveAction, ex);
                            AddLog(CurrentError);
                            return;
                        }
                    }
                }
            }
        }
    }
Пример #43
0
 public ProtoManifest(DepotManifest sourceManifest, ulong id) : this()
 {
     sourceManifest.Files.ForEach(f => Files.Add(new FileData(f)));
     ID = id;
 }
Пример #44
0
        public override Files getFiles()
        {
            Files kfiles = base.getFiles();

            return(kfiles);
        }
        public override bool Execute()
        {
            XAttribute[] rootAttributes = RootAttributes
                                          ?.Select(item => new XAttribute(item.ItemSpec, item.GetMetadata("Value")))
                                          .ToArray();

            var frameworkManifest = new XElement("FileList", rootAttributes);

            var usedFileProfiles = new HashSet <string>();

            foreach (var f in Files
                     .Select(item => new
            {
                Item = item,
                Filename = Path.GetFileName(item.ItemSpec),
                AssemblyName = FileUtilities.GetAssemblyName(item.ItemSpec),
                FileVersion = FileUtilities.GetFileVersion(item.ItemSpec),
                IsNative = item.GetMetadata("IsNativeImage") == "true",
                IsSymbolFile = item.GetMetadata("IsSymbolFile") == "true",
                PackagePath = item.GetMetadata("PackagePath")
            })
                     .Where(f =>
                            !f.IsSymbolFile &&
                            (f.Filename.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) || f.IsNative))
                     .OrderBy(f => f.Filename, StringComparer.Ordinal))
            {
                string path    = Path.Combine(f.PackagePath, f.Filename).Replace('\\', '/');
                string type    = f.IsNative ? "Native" : "Managed";
                var    element = new XElement("File", new XAttribute("Path", path));

                if (path.StartsWith("analyzers/", StringComparison.Ordinal))
                {
                    type = "Analyzer";

                    if (path.EndsWith(".resources.dll", StringComparison.Ordinal))
                    {
                        // omit analyzer resources
                        continue;
                    }

                    var pathParts = path.Split('/');

                    if (pathParts.Length < 3 || !pathParts[1].Equals("dotnet", StringComparison.Ordinal) || pathParts.Length > 4)
                    {
                        Log.LogError($"Unexpected analyzer path format {path}.  Expected  'analyzers/dotnet(/language)/analyzer.dll");
                    }

                    // Check if we have enough parts for language directory and include it
                    if (pathParts.Length > 3)
                    {
                        element.Add(new XAttribute("Language", pathParts[2]));
                    }
                }

                element.Add(new XAttribute("Type", type));

                if (f.AssemblyName != null)
                {
                    byte[] publicKeyToken = f.AssemblyName.GetPublicKeyToken();
                    string publicKeyTokenHex;

                    if (publicKeyToken != null)
                    {
                        publicKeyTokenHex = BitConverter.ToString(publicKeyToken)
                                            .ToLowerInvariant()
                                            .Replace("-", "");
                    }
                    else
                    {
                        Log.LogError($"No public key token found for assembly {f.Item.ItemSpec}");
                        publicKeyTokenHex = "";
                    }

                    element.Add(
                        new XAttribute("AssemblyName", f.AssemblyName.Name),
                        new XAttribute("PublicKeyToken", publicKeyTokenHex),
                        new XAttribute("AssemblyVersion", f.AssemblyName.Version));
                }
                else if (!f.IsNative)
                {
                    // This file isn't managed and isn't native. Leave it off the list.
                    continue;
                }

                element.Add(new XAttribute("FileVersion", f.FileVersion));

                frameworkManifest.Add(element);
            }

            Directory.CreateDirectory(Path.GetDirectoryName(TargetFile));
            File.WriteAllText(TargetFile, frameworkManifest.ToString());

            return(!Log.HasLoggedErrors);
        }
Пример #46
0
 public int AddFile(string file)
 {
     return(Files.Add(file));
 }
Пример #47
0
 private void Button_Refresh_Click(object sender, RoutedEventArgs e)
 {
     Files.reloadFiles();
     refreshDisplay();
 }
        public override bool RunTask()
        {
            var libraryProjectDir = Path.GetFullPath(LibraryProjectIntermediatePath);

            foreach (var directory in Directories)
            {
                if (!Directory.Exists(directory.ItemSpec))
                {
                    Log.LogDebugMessage($"Directory does not exist, skipping: {directory.ItemSpec}");
                    continue;
                }
                string stampFile     = directory.GetMetadata("StampFile");
                string directoryHash = Files.HashString(directory.ItemSpec);
                if (string.IsNullOrEmpty(stampFile))
                {
                    if (Path.GetFullPath(directory.ItemSpec).StartsWith(libraryProjectDir))
                    {
                        // If inside the `lp` directory
                        stampFile = Path.GetFullPath(Path.Combine(directory.ItemSpec, "..", "..")) + ".stamp";
                    }
                    else
                    {
                        // Otherwise use a hashed stamp file
                        stampFile = Path.Combine(StampDirectory, $"{directoryHash}.stamp");
                    }
                }

                bool generateArchive = false;
                bool.TryParse(directory.GetMetadata(ResolveLibraryProjectImports.AndroidSkipResourceProcessing), out generateArchive);

                IEnumerable <string> files;
                string filesCache = directory.GetMetadata("FilesCache");
                if (string.IsNullOrEmpty(filesCache))
                {
                    if (Path.GetFullPath(directory.ItemSpec).StartsWith(libraryProjectDir))
                    {
                        filesCache = Path.Combine(directory.ItemSpec, "..", "files.cache");
                    }
                    else
                    {
                        filesCache = Path.Combine(directory.ItemSpec, "..", $"{directoryHash}-files.cache");
                    }
                }
                DateTime lastwriteTime      = File.Exists(stampFile) ? File.GetLastWriteTimeUtc(stampFile) : DateTime.MinValue;
                DateTime cacheLastWriteTime = File.Exists(filesCache) ? File.GetLastWriteTimeUtc(filesCache) : DateTime.MinValue;

                if (File.Exists(filesCache) && cacheLastWriteTime >= lastwriteTime)
                {
                    Log.LogDebugMessage($"Reading cached Library resources list from  {filesCache}");
                    files = File.ReadAllLines(filesCache);
                }
                else
                {
                    if (!File.Exists(filesCache))
                    {
                        Log.LogDebugMessage($"Cached Library resources list {filesCache} does not exist.");
                    }
                    else
                    {
                        Log.LogDebugMessage($"Cached Library resources list {filesCache} is out of date.");
                    }
                    if (generateArchive)
                    {
                        files = new string[1] {
                            stampFile
                        };
                    }
                    else
                    {
                        files = Directory.EnumerateFiles(directory.ItemSpec, "*.*", SearchOption.AllDirectories);
                    }
                }

                if (files.Any())
                {
                    if (!File.Exists(filesCache) || cacheLastWriteTime < lastwriteTime)
                    {
                        File.WriteAllLines(filesCache, files, Encoding.UTF8);
                    }
                    var taskItem = new TaskItem(directory.ItemSpec, new Dictionary <string, string> ()
                    {
                        { "FileFound", files.First() },
                    });
                    directory.CopyMetadataTo(taskItem);

                    if (string.IsNullOrEmpty(directory.GetMetadata("StampFile")))
                    {
                        taskItem.SetMetadata("StampFile", stampFile);
                    }
                    else
                    {
                        Log.LogDebugMessage($"%(StampFile) already set: {stampFile}");
                    }
                    if (string.IsNullOrEmpty(directory.GetMetadata("FilesCache")))
                    {
                        taskItem.SetMetadata("FilesCache", filesCache);
                    }
                    else
                    {
                        Log.LogDebugMessage($"%(FilesCache) already set: {filesCache}");
                    }
                    output.Add(taskItem);
                    foreach (var file in files)
                    {
                        if (Aapt2.IsInvalidFilename(file))
                        {
                            Log.LogDebugMessage($"Invalid filename, ignoring: {file}");
                            continue;
                        }
                        var fileTaskItem = new TaskItem(file, new Dictionary <string, string> ()
                        {
                            { "ResourceDirectory", directory.ItemSpec },
                            { "StampFile", generateArchive ? stampFile : file },
                            { "FilesCache", filesCache },
                            { "Hash", stampFile },
                            { "_ArchiveDirectory", Path.Combine(directory.ItemSpec, "..", "flat" + Path.DirectorySeparatorChar) },
                            { "_FlatFile", generateArchive ?  $"{Path.GetFileNameWithoutExtension (stampFile)}.flata"  : Monodroid.AndroidResource.CalculateAapt2FlatArchiveFileName(file) },
                        });
                        libraryResourceFiles.Add(fileTaskItem);
                    }
                }
            }
            return(!Log.HasLoggedErrors);
        }
Пример #49
0
 private void DeleteAction()
 {
     workstationService.RemoveWorkstation(SelectedWorkstation);
     Workstations.Remove(Workstations.Where(x => x.WorkstationId == SelectedWorkstation.WorkstationId).Single());
     Files.ToList().RemoveAll(x => x.WorkstationId == SelectedWorkstation.WorkstationId);
 }
Пример #50
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!QueryHelper.ValidateHash("hash"))
        {
            return;
        }

        // Check if hashtable containing dialog parameters is not empty
        if ((Parameters == null) || (Parameters.Count == 0))
        {
            return;
        }

        // Initialize events
        ctlAsyncLog.OnFinished += ctlAsyncLog_OnFinished;
        ctlAsyncLog.OnError    += ctlAsyncLog_OnError;
        ctlAsyncLog.OnCancel   += ctlAsyncLog_OnCancel;

        // Get the source node
        MediaLibraryID = ValidationHelper.GetInteger(Parameters["libraryid"], 0);
        CopyMoveAction = ValidationHelper.GetString(Parameters["action"], string.Empty);
        FolderPath     = Path.EnsureBackslashes(ValidationHelper.GetString(Parameters["path"], ""));
        Files          = ValidationHelper.GetString(Parameters["files"], "").Trim('|');
        RootFolder     = MediaLibraryHelper.GetMediaRootFolderPath(SiteContext.CurrentSiteName);
        AllFiles       = ValidationHelper.GetBoolean(Parameters["allFiles"], false);
        NewPath        = Path.EnsureBackslashes(ValidationHelper.GetString(Parameters["newpath"], ""));

        // Target folder
        string tarFolder = NewPath;

        if (string.IsNullOrEmpty(tarFolder) && (LibraryInfo != null))
        {
            tarFolder = LibraryInfo.LibraryFolder + " (root)";
        }
        lblFolder.Text = tarFolder;

        if (!IsLoad)
        {
            if (AllFiles || String.IsNullOrEmpty(Files))
            {
                if (AllFiles)
                {
                    lblFilesToCopy.ResourceString = "media.folder.filestoall" + CopyMoveAction.ToLowerCSafe();
                }
                else
                {
                    lblFilesToCopy.ResourceString = "media.folder.folderto" + CopyMoveAction.ToLowerCSafe();
                }

                // Source folder
                string srcFolder = FolderPath;
                if (string.IsNullOrEmpty(srcFolder) && (LibraryInfo != null))
                {
                    srcFolder = LibraryInfo.LibraryFolder + "&nbsp;(root)";
                }
                lblFileList.Text = HTMLHelper.HTMLEncode(srcFolder);
            }
            else
            {
                lblFilesToCopy.ResourceString = "media.folder.filesto" + CopyMoveAction.ToLowerCSafe();
                string[] fileList = Files.Split('|');
                foreach (string file in fileList)
                {
                    lblFileList.Text += HTMLHelper.HTMLEncode(DirectoryHelper.CombinePath(FolderPath.TrimEnd('\\'), file)) + "<br />";
                }
            }

            if (!RequestHelper.IsCallback() && !RequestHelper.IsPostBack())
            {
                bool performAction = ValidationHelper.GetBoolean(Parameters["performaction"], false);
                if (performAction)
                {
                    // Perform Move or Copy
                    PerformAction();
                }
            }

            pnlInfo.Visible  = true;
            pnlEmpty.Visible = false;
        }
        else
        {
            pnlInfo.Visible  = false;
            pnlEmpty.Visible = true;
            lblEmpty.Text    = GetString("media.copymove.select");

            // Disable New folder button
            ScriptHelper.RegisterStartupScript(Page, typeof(Page), "DisableNewFolderOnLoad", ScriptHelper.GetScript("if ((window.parent != null) && window.parent.DisableNewFolderBtn) { window.parent.DisableNewFolderBtn(); }"));
        }
    }
Пример #51
0
        public void download_Update_and_Install()
        {
            //ensure this dll is loaded in memory
            "FluentSharp.NGit.dll".assembly().Location.info();

            //use the O2 Fork:
            config("SosNet",
                   "https://github.com/o2platform/O2_Fork_SoS_Net.git".uri(),
                   "Sos.Net.exe");
            var codeDir = this.Install_Dir.pathCombine("O2_Fork_SoS_Net");

            if (codeDir.dirExists().isFalse())
            {
                this.Install_Uri.git_Clone(codeDir);
            }
            else
            {
                codeDir.git_Pull();
                var solutionFile = codeDir.pathCombine("SOS.Net.sln");

                solutionFile.build().waitForBuildCompletion().ConsoleOut.str().info();
                Files.copyFilesFromDirectoryToDirectory(codeDir.pathCombine(@"SOS.Net\bin\Debug"), this.Install_Dir);

                //show.info(assemblies);
            }

            /*
             * //Previously we use the original version from bitbucket
             * config("SosNet",
             *         "https://bitbucket.org/grozeille/sosnet/downloads/SOS.Net.zip".uri(),
             *         "Sos.Net.exe");
             * installFromZip_Web();
             */
            //get PssCor4.dll and sosex.dll windb extensions

            var x86_Folder = this.Install_Dir.pathCombine("x86").createDir();
            var x64_Folder = this.Install_Dir.pathCombine("x64").createDir();

            //Psscor4
            var psscorDir  = this.Install_Dir.pathCombine("Psscor4").createDir();
            var pssCor4Zip = Install_Dir.pathCombine("Psscor4.zip");

            if (psscorDir.fileExists().isFalse())
            {
                if (pssCor4Zip.fileExists().isFalse())
                {
                    var pssCor4Exe = "http://download.microsoft.com/download/2/C/E/2CE778CF-3A42-48FE-9EFF-4C76B4ECB147/Psscor4.EXE".download();

                    pssCor4Exe.startProcess("/Q /T:\"{0}\"".format(Install_Dir))
                    .WaitForExit();
                }
                var pssCor4_x86 = psscorDir.pathCombine(@"x86\x86\psscor4.dll");
                var pssCor4_x64 = psscorDir.pathCombine(@"amd64\amd64\psscor4.dll");
                if (pssCor4_x86.fileExists().isFalse())
                {
                    if (pssCor4Zip.fileExists())
                    {
                        pssCor4Zip.unzip(Install_Dir);
                        Files.copy(pssCor4_x86, x86_Folder);
                        Files.copy(pssCor4_x86.replace(".dll", ".pdb"), x86_Folder);
                        Files.copy(pssCor4_x64, x64_Folder);
                        Files.copy(pssCor4_x64.replace(".dll", ".pdb"), x64_Folder);
                    }
                    else
                    {
                        "[psscor4 install], could not find psscor4  zip file: {0}".error(pssCor4Zip);
                    }
                }
            }

            //sosex
            var sosEx = x86_Folder.pathCombine("sosex.dll");

            if (sosEx.fileExists().isFalse())
            {
                var sos32_zip = "http://www.stevestechspot.com/downloads/sosex_32.zip".download();
                sos32_zip.unzip(x86_Folder);


                var sos64_zip = "http://www.stevestechspot.com/downloads/sosex_64.zip".download();
                sos64_zip.unzip(x64_Folder);
            }
            //this.showInfo();

            /*Action<string, string,Uri> install = (installFolder, installFile, installUri)=>
             *      {
             *              config("DebugAnalyzer", "DebugAnalyzer v1.2.5", installFile);
             *      this.Install_Uri = installUri;
             *      this.Executable = this.Install_Dir.pathCombine(installFolder + @"\DebugAnalyzer.exe");
             *      installFromZip_Web();
             * };
             *
             * install	("x86", "DAx86.zip", "http://www.debuganalyzer.net/file.axd?file=DAx86.zip".uri());
             * install	("x64", "DAx64.zip", "http://www.debuganalyzer.net/file.axd?file=DAx64.zip".uri());
             * //install 2.0 version
             * //install("Acorns.Hawkeye.125.N2", "Acorns.Hawkeye.125.N2.zip", "http://download.codeplex.com/Download/Release?ProjectName=hawkeye&DownloadId=196206&FileTime=129391670111230000&Build=18924".uri());
             * //install 4.0 version
             * //install("Acorns.Hawkeye.125.N4", "Acorns.Hawkeye.125.N4.zip", "http://download.codeplex.com/Download/Release?ProjectName=hawkeye&DownloadId=196207&FileTime=129391675391630000&Build=18924".uri());
             */
        }
Пример #52
0
        public static bool xmlDB_Libraries_ImportFromZip(this TM_Xml_Database tmDatabase, string zipFileToImport, string unzipPassword)
        {
            var result = false;

            try
            {
                var currentLibraryPath = tmDatabase.Path_XmlLibraries;
                if (currentLibraryPath.isNull())
                {
                    return(false);
                }
                if (zipFileToImport.isUri())
                {
                    "[xmlDB_Libraries_ImportFromZip] provided value was an URL so, downloading it: {0}".info(zipFileToImport);
                    zipFileToImport = new Web().downloadBinaryFile(zipFileToImport);
                    //zipFileToImport =  zipFileToImport.uri().download();
                }
                "[xmlDB_Libraries_ImportFromZip] importing library from: {0}".info(zipFileToImport);
                if (zipFileToImport.fileExists().isFalse())
                {
                    "[xmlDB_Libraries_ImportFromZip] could not find file to import".error(zipFileToImport);
                }
                else
                {
                    // handle the zips we get from GitHub

                    var tempDir = @"..\_".add_RandomLetters(3).tempDir(false).fullPath(); //trying to make the unzip path as small as possible
                    var fastZip = new ICSharpCode.SharpZipLib.Zip.FastZip {
                        Password = unzipPassword ?? ""
                    };
                    fastZip.ExtractZip(zipFileToImport, tempDir, "");

                    Files.copyFolder(tempDir, currentLibraryPath, true, true, "");          // just copy all files into Library path
                    result = true;

                    /*
                     * var gitZipFolderName = tempDir.folders().first().folderName();				// the first folder should be the one created by gitHub's zip
                     * var xmlFile_Location1 = tempDir.pathCombine(gitZipFolderName + ".xml");
                     * var xmlFile_Location2 = tempDir.pathCombine(gitZipFolderName).pathCombine(gitZipFolderName + ".xml");
                     * if (xmlFile_Location1.fileExists() || xmlFile_Location2.fileExists())
                     *  // if these exists here, just copy the unziped files directly
                     * {
                     *  Files.copyFolder(tempDir, currentLibraryPath, true, true, ".git");
                     *  if (xmlFile_Location1.fileExists())
                     *      Files.copy(xmlFile_Location1, currentLibraryPath.pathCombine(gitZipFolderName));
                     *  result = true;
                     * }
                     * else
                     * {
                     *  //if (zipFileToImport.extension() == ".master")
                     *  var gitZipDir = tempDir.pathCombine(gitZipFolderName);
                     *  foreach (var libraryFolder in gitZipDir.folders())
                     *  {
                     *      var libraryName = libraryFolder.folderName();
                     *      var targetFolder = currentLibraryPath.pathCombine(libraryName);
                     *
                     *      //default behaviour is to override the existing libraries
                     *      Files.copyFolder(libraryFolder, currentLibraryPath);
                     *
                     *      //handle the case where the xml file is located outside the library folder
                     *      var libraryXmlFile = gitZipDir.pathCombine("{0}.xml".format(libraryName));
                     *      if (libraryXmlFile.fileExists())
                     *          Files.copy(libraryXmlFile, targetFolder);
                     *              // put it in the Library folder which is where it really should be
                     *  }
                     *  var virtualMappings = gitZipDir.pathCombine("Virtual_Articles.xml");
                     *  if (virtualMappings.fileExists())
                     *  {
                     *      Files.copy(virtualMappings, currentLibraryPath); // copy virtual mappings if it exists
                     *      tmDatabase.mapVirtualArticles();
                     *  }
                     *  result = true;
                     * } */
                }
            }
            catch (Exception ex)
            {
                ex.log("[xmlDB_Libraries_ImportFromZip]");
            }

            if (result)
            {
                tmDatabase.reloadGuidanceExplorerObjects();
            }
            //tmDatabase.loadLibraryDataFromDisk();

            return(result);
        }
Пример #53
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIDocument     uiDoc      = commandData.Application.ActiveUIDocument;
            Document       doc        = uiDoc.Document;
            int            boundcount = 0;
            List <Element> rooms      = new FilteredElementCollector(doc, uiDoc.ActiveView.Id).OfCategory(BuiltInCategory.OST_Rooms).ToElements().ToList();
            List <string>  Lines      = new List <string>();

            foreach (Element e in rooms)
            {
                Room r      = e as Room;
                var  bounds = r.CollectBounds();
                if (bounds.Count() > boundcount)
                {
                    boundcount = bounds.Count();
                }
                for (int i = 0; i < bounds.Count(); i++)
                {
                    string result = "Y";
                    var    b1     = bounds.GetBound(i - 2);
                    var    b2     = bounds.GetBound(i - 1);
                    var    b3     = bounds.GetBound(i);
                    var    b4     = bounds.GetBound(i + 1);
                    var    b5     = bounds.GetBound(i + 2);
                    var    D1     = b2.Direction(b3);
                    var    D2     = b3.Direction(b4);
                    var    D3     = b1.Direction(b2);
                    var    D4     = b4.Direction(b5);
                    if (D1.AngleBetween(D2) < 0.0872665)
                    {
                        result = "N";
                    }
                    if (D1.UnitLength() < 3)
                    {
                        if (D3.AngleBetween(D2) < 0.0872665)
                        {
                            result = "N";
                        }
                    }
                    if (D2.UnitLength() < 3)
                    {
                        if (D1.AngleBetween(D4) < 0.0872665)
                        {
                            result = "N";
                        }
                    }
                    string s = b1[0] + "," + b1[1] + "," + b1[2] + "," +
                               b2[0] + "," + b2[1] + "," + b2[2] + "," +
                               b3[0] + "," + b3[1] + "," + b3[2] + "," +
                               b4[0] + "," + b4[1] + "," + b4[2] + "," +
                               b5[0] + "," + b5[1] + "," + b5[2] + "," + result;
                    Lines.Add(s);
                }
            }
            string fn = null;

            while (fn == null)
            {
                fn = Files.GetFile();
            }
            TaskDialog.Show("Max Bounds", boundcount.ToString());
            File.WriteAllLines(fn + "_Boundary.csv", Lines);

            return(Result.Succeeded);
        }
Пример #54
0
        public void CreateProjectFiles(DecompileContext ctx)
        {
            var filenameCreator     = new FilenameCreator(Directory, DefaultNamespace);
            var resourceNameCreator = new ResourceNameCreator(Options.Module, filenameCreator);

            AllowUnsafeBlocks = DotNetUtils.IsUnsafe(Options.Module);
            InitializeSplashScreen();
            if (Options.Decompiler.CanDecompile(DecompilationType.AssemblyInfo))
            {
                var filename = filenameCreator.CreateFromRelativePath(Path.Combine(PropertiesFolder, "AssemblyInfo"), Options.Decompiler.FileExtension);
                Files.Add(new AssemblyInfoProjectFile(Options.Module, filename, Options.DecompilationContext, Options.Decompiler, createDecompilerOutput));
            }

            var ep = Options.Module.EntryPoint;

            if (ep != null && ep.DeclaringType != null)
            {
                StartupObject = ep.DeclaringType.ReflectionFullName;
            }

            applicationManifest = ApplicationManifest.TryCreate(Options.Module.Win32Resources, filenameCreator);
            if (ApplicationManifest != null)
            {
                Files.Add(new ApplicationManifestProjectFile(ApplicationManifest.Filename));
            }

            foreach (var rsrc in Options.Module.Resources)
            {
                ctx.CancellationToken.ThrowIfCancellationRequested();
                switch (rsrc.ResourceType)
                {
                case ResourceType.Embedded:
                    foreach (var file in CreateEmbeddedResourceFiles(Options.Module, resourceNameCreator, (EmbeddedResource)rsrc))
                    {
                        Files.Add(file);
                        Files.AddRange(CreateSatelliteFiles(rsrc.Name, filenameCreator, file));
                    }
                    break;

                case ResourceType.AssemblyLinked:
                    //TODO: What should be created here?
                    break;

                case ResourceType.Linked:
                    //TODO: What should be created here?
                    break;

                default:
                    break;
                }
            }
            InitializeXaml();
            InitializeResX();
            foreach (var type in Options.Module.Types)
            {
                ctx.CancellationToken.ThrowIfCancellationRequested();
                if (!DecompileType(type))
                {
                    continue;
                }
                Files.Add(CreateTypeProjectFile(type, filenameCreator));
            }
            CreateEmptyAppXamlFile();

            var existingAppConfig = Options.Module.Location + ".config";

            if (File.Exists(existingAppConfig))
            {
                Files.Add(new AppConfigProjectFile(filenameCreator.CreateName("App.config"), existingAppConfig));
            }

            applicationIcon = ApplicationIcon.TryCreate(Options.Module.Win32Resources, Path.GetFileName(Directory), filenameCreator);

            var dirs   = new HashSet <string>(Files.Select(a => GetDirectoryName(a.Filename)).Where(a => a != null), StringComparer.OrdinalIgnoreCase);
            int errors = 0;

            foreach (var dir in dirs)
            {
                ctx.CancellationToken.ThrowIfCancellationRequested();
                try {
                    System.IO.Directory.CreateDirectory(dir);
                }
                catch (Exception ex) {
                    if (errors++ < 20)
                    {
                        ctx.Logger.Error(string.Format(dnSpy_Decompiler_Resources.MSBuild_CouldNotCreateDirectory2, dir, ex.Message));
                    }
                }
            }
        }
Пример #55
0
 public void AddFile(string file)
 {
     Files.Add(file);
 }
Пример #56
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldLogQueriesViaBolt() throws java.io.IOException
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldLogQueriesViaBolt()
        {
            // *** GIVEN ***

            Socket           socket  = new Socket("localhost", Neo4j.boltURI().Port);
            DataInputStream  dataIn  = new DataInputStream(socket.InputStream);
            DataOutputStream dataOut = new DataOutputStream(socket.OutputStream);

            // Bolt handshake
            send(dataOut, new sbyte[] { ( sbyte )0x60, ( sbyte )0x60, unchecked (( sbyte )0xB0), ( sbyte )0x17, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 });
            receive(dataIn, new sbyte[] { 0, 0, 0, 1 });

            // This has been taken from: http://alpha.neohq.net/docs/server-manual/bolt-examples.html

            // Send INIT "MyClient/1.0" { "scheme": "basic", "principal": "neo4j", "credentials": "secret"}
            Send(dataOut, "00 40 B1 01  8C 4D 79 43  6C 69 65 6E  74 2F 31 2E\n" + "30 A3 86 73  63 68 65 6D  65 85 62 61  73 69 63 89\n" + "70 72 69 6E  63 69 70 61  6C 85 6E 65  6F 34 6A 8B\n" + "63 72 65 64  65 6E 74 69  61 6C 73 86  73 65 63 72\n" + "65 74 00 00");
            // Receive SUCCESS {}
            ReceiveSuccess(dataIn);

            // *** WHEN ***

            for (int i = 0; i < 5; i++)
            {
                // Send RUN "RETURN 1 AS num" {}
                Send(dataOut, "00 13 b2 10  8f 52 45 54  55 52 4e 20  31 20 41 53 20 6e 75 6d  a0 00 00");
                // Receive SUCCESS { "fields": ["num"], "result_available_after": X }
                //non-deterministic so just ignore it here
                ReceiveSuccess(dataIn);

                //receive( dataIn, "00 0f b1 70  a1 86 66 69  65 6c 64 73  91 83 6e 75 6d 00 00" );

                // Send PULL_ALL
                Send(dataOut, "00 02 B0 3F  00 00");
                // Receive RECORD[1]
                Receive(dataIn, "00 04 b1 71  91 01 00 00");
                // Receive SUCCESS { "type": "r", "result_consumed_after": Y }
                //non-deterministic so just ignore it here
                ReceiveSuccess(dataIn);
            }

            // *** THEN ***

            Path           queriesLog = Neo4j.Config.get(GraphDatabaseSettings.log_queries_filename).toPath();
            IList <string> lines      = Files.readAllLines(queriesLog);

            assertThat(lines, hasSize(5));
            foreach (string line in lines)
            {
                assertThat(line, containsString("INFO"));
                assertThat(line, containsString("bolt-session"));
                assertThat(line, containsString("MyClient/1.0"));
                assertThat(line, containsString("client/127.0.0.1:"));
                assertThat(line, containsString("server/127.0.0.1:" + Neo4j.boltURI().Port));
                assertThat(line, containsString(" - RETURN 1 AS num - {}"));
            }

            // *** CLEAN UP ***

            // Send RESET
            Send(dataOut, "00 02 b0 0f 00 00");
            // Receive SUCCESS {}
            Receive(dataIn, "00 03 b1 70  a0 00 00");

            socket.close();
        }
Пример #57
0
		public void Execute()
		{
			if (Shared.Instance.Debug)
			{
				using (Color(ConsoleColor.DarkGray))
				{
					Console.WriteLine("Patterns:");
					foreach (var pattern in Patterns)
					{
						Console.WriteLine(pattern);
					}
				}
			}

			// Console.WriteLine("Replace to " + ReplaceTo);

			foreach (var pattern in Patterns)
			{
				var pattern2 = ImprovePattern(pattern);
				_regexes.Add(new Regex(pattern2, RegexOptions.Compiled | RegexOptions.Multiline));
			}

			if (string.IsNullOrWhiteSpace(Dir))
			{
				throw new Exception("Directory not defined");
			}

			if (!Directory.Exists(Dir))
			{
				throw new Exception("Directory does not exists");
			}

			if (Files.Count == 0)
			{
				if (Recursive)
				{
					Files.Add("**/*");
				}
				else
				{
					// STDIN
					Files.Add("-");
				}
			}

			var groupedContext = GroupMatchesByContext
				? new Dictionary<ColoredMessage, CaptureResult>()
				: null;


			if (Files.Count == 1 && (File.Exists(Files[0]) || Files[0] == "-"))
			{
				// single
				Process(file: Files[0], printFileName: false);
			}
			else
			{
				var di = new DirectoryInfo(Dir);

				var includes = Files
						.Select(x => new
						{
							IsFullPath = Path.GetFullPath(x) == x,
							Pattern = x,
						})
						.Select(x =>
							x.IsFullPath
								? x.Pattern.Substring(di.FullName.Length + 1)
								: (Recursive
									? (x.Pattern.StartsWith("**/") ? x.Pattern : "**/" + x.Pattern)
									: x.Pattern)
						)
					;

				var excludes = FilesSelectorOptions.ExcludeGlobs
						.Select(x => new
						{
							IsFullPath = Path.GetFullPath(x) == x,
							Pattern = x,
						})
						.Select(x =>
							x.IsFullPath
								? x.Pattern.Substring(di.FullName.Length + 1)
								: x.Pattern
						)
					;

				var matcher = new Matcher();
				matcher.AddIncludePatterns(includes);
				matcher.AddExcludePatterns(excludes);

				var res = matcher.Execute(new DirectoryInfoWrapper(di));
				foreach (var filePatternMatch in res.Files.OrderBy(x => x.Path))
				{
					var file = filePatternMatch.Path;
					if (Path.AltDirectorySeparatorChar != Path.DirectorySeparatorChar)
					{
						file = file.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
					}
					Process(file, printFileName: true, groupedContext);
				}
			}

			if (groupedContext != null)
			{
				foreach (var kvp in groupedContext.OrderBy(x=>x.Value.FileNames.First()))
				{
					Console.WriteLine();
					if (kvp.Value.FileNames.Count > 1)
					{
						using (Color(ConsoleColor.Magenta))
						{
							Console.WriteLine($"{kvp.Value.FileNames.Count} files:");
						}
					}
					
					foreach (var file in kvp.Value.FileNames)
					{
						PrintFileName(file);
					}

					kvp.Key.ToConsole();
				}
				/*
				if (groupedContext.Count > 1)
				{
					// using (Color(ConsoleColor.Gray))
					{
						Console.WriteLine();
						Console.WriteLine($"{groupedContext.Count} groups of similar context");
					}
				}
				*/
			}
		}
Пример #58
0
        public override TaskStatus Run()
        {
            Info("Generating SHA-1 hashes...");

            bool success           = true;
            bool atLeastOneSucceed = false;

            var files = SelectFiles();

            if (files.Length > 0)
            {
                var md5Path = Path.Combine(Workflow.WorkflowTempFolder,
                                           string.Format("SHA1_{0:yyyy-MM-dd-HH-mm-ss-fff}.xml", DateTime.Now));

                var xdoc = new XDocument(new XElement("Files"));
                foreach (FileInf file in files)
                {
                    try
                    {
                        var sha1 = GetSha1(file.Path);
                        if (xdoc.Root != null)
                        {
                            xdoc.Root.Add(new XElement("File",
                                                       new XAttribute("path", file.Path),
                                                       new XAttribute("name", file.FileName),
                                                       new XAttribute("sha1", sha1)));
                        }
                        InfoFormat("SHA-1 hash of the file {0} is {1}", file.Path, sha1);

                        if (!atLeastOneSucceed)
                        {
                            atLeastOneSucceed = true;
                        }
                    }
                    catch (ThreadAbortException)
                    {
                        throw;
                    }
                    catch (Exception e)
                    {
                        ErrorFormat("An error occured while generating the md5 of the file {0}", e, file.Path);
                        success = false;
                    }
                }
                xdoc.Save(md5Path);
                Files.Add(new FileInf(md5Path, Id));
            }

            var status = Status.Success;

            if (!success && atLeastOneSucceed)
            {
                status = Status.Warning;
            }
            else if (!success)
            {
                status = Status.Error;
            }

            Info("Task finished.");
            return(new TaskStatus(status, false));
        }
        void Add(Section section)
        {
            string current_texname = null;
            string f = null;

            for (int i = 0; i < section.Count; i++)
            {
                Entry e = section [i];
                switch (e.Name.ToLowerInvariant())
                {
                case "file":
                    if (e.Count != 1)
                    {
                        throw new Exception("Invalid number of values in " + section.Name + " Entry " + e.Name + ": " + e.Count);
                    }
                    if (f != null)
                    {
                        throw new Exception("Duplicate " + e.Name + " Entry in " + section.Name);
                    }
                    Files.Add(e[0].ToString());
                    f = e[0].ToString();
                    break;

                case "texture_name":
                    if (e.Count != 1)
                    {
                        throw new Exception("Invalid number of values in " + section.Name + " Entry " + e.Name + ": " + e.Count);
                    }
                    current_texname = e [0].ToString();
                    break;

                case "tex_shape":
                    Shapes[e[0].ToString()] =
                        new TextureShape(
                            e[0].ToString(),
                            e[0].ToString(),
                            new RectangleF(0, 0, 1, 1)
                            );
                    break;

                case "shape_name":
                    if (e.Count != 1)
                    {
                        throw new Exception("Invalid number of values in " + section.Name + " Entry " + e.Name + ": " + e.Count);
                    }
                    var        shape_name = e [0].ToString();
                    RectangleF dimensions;
                    if (i + 1 >= section.Count || section[i + 1].Name.ToLower() != "dim")
                    {
                        dimensions = new RectangleF(0, 0, 1, 1);
                    }
                    else
                    {
                        e = section[i + 1];
                        if (e.Name != "dim")
                        {
                            throw new Exception("expected dim, got " + e.Name);
                        }
                        if (e.Count != 4)
                        {
                            throw new Exception("Invalid number of values in " + section.Name + " Entry " + e.Name + ": " + e.Count);
                        }
                        dimensions = new RectangleF(e[0].ToSingle(), e[1].ToSingle(), e[2].ToSingle(), e[3].ToSingle());
                    }

                    Shapes.Add(shape_name,
                               new TextureShape(
                                   current_texname,
                                   shape_name,
                                   dimensions
                                   ));
                    i++;
                    break;

                case "name":
                    shapeTexName = e[0].ToString();
                    break;

                default:
                    FLLog.Warning("Ini", "Invalid entry " + e.Name + " in " + e.File);
                    break;
                }
            }
        }
Пример #60
0
        ProjectFile CreateTypeProjectFile(TypeDef type, FilenameCreator filenameCreator)
        {
            var bamlFile = TryGetBamlFile(type);

            if (bamlFile != null)
            {
                var             filename = filenameCreator.Create(GetTypeExtension(type), type.FullName);
                TypeProjectFile newFile;
                var             isAppType = DotNetUtils.IsSystemWindowsApplication(type);
                if (!Options.Decompiler.CanDecompile(DecompilationType.PartialType))
                {
                    newFile = new TypeProjectFile(type, filename, Options.DecompilationContext, Options.Decompiler, createDecompilerOutput);
                }
                else
                {
                    newFile = new XamlTypeProjectFile(type, filename, Options.DecompilationContext, Options.Decompiler, createDecompilerOutput);
                }
                newFile.DependentUpon = bamlFile;
                if (isAppType && DotNetUtils.IsStartUpClass(type))
                {
                    bamlFile.IsAppDef = true;
                    StartupObject     = null;
                }
                if (isAppType)
                {
                    appTypeProjFile = newFile;
                }
                return(newFile);
            }

            const string DESIGNER = ".Designer";
            var          resxFile = TryGetResXFile(type);

            if (DotNetUtils.IsWinForm(type))
            {
                var fname = resxFile != null?Path.GetFileNameWithoutExtension(resxFile.Filename) : type.Name.String;

                var filename = filenameCreator.CreateFromNamespaceName(GetTypeExtension(type), type.ReflectionNamespace, fname);
                var dname    = filenameCreator.CreateFromNamespaceName(GetTypeExtension(type), type.ReflectionNamespace, fname + DESIGNER);

                var newFile = new WinFormsProjectFile(type, filename, Options.DecompilationContext, Options.Decompiler, createDecompilerOutput);
                if (resxFile != null)
                {
                    resxFile.DependentUpon = newFile;
                }
                var winFormsDesignerFile = new WinFormsDesignerProjectFile(newFile, dname, createDecompilerOutput);
                winFormsDesignerFile.DependentUpon = newFile;
                Files.Add(winFormsDesignerFile);
                return(newFile);
            }
            else if (resxFile != null)
            {
                var filename = filenameCreator.CreateFromNamespaceName(GetTypeExtension(type), type.ReflectionNamespace, Path.GetFileNameWithoutExtension(resxFile.Filename) + DESIGNER);
                var newFile  = new TypeProjectFile(type, filename, Options.DecompilationContext, Options.Decompiler, createDecompilerOutput);
                newFile.DependentUpon  = resxFile;
                newFile.AutoGen        = true;
                newFile.DesignTime     = true;
                resxFile.Generator     = type.IsPublic ? "PublicResXFileCodeGenerator" : "ResXFileCodeGenerator";
                resxFile.LastGenOutput = newFile;
                return(newFile);
            }

            var bt = type.BaseType;

            if (bt != null && bt.FullName == "System.Configuration.ApplicationSettingsBase")
            {
                var         designerFilename = filenameCreator.Create(DESIGNER + GetTypeExtension(type), type.FullName);
                var         settingsFilename = filenameCreator.Create(".settings", type.FullName);
                ProjectFile designerTypeFile;
                if (Options.Decompiler.CanDecompile(DecompilationType.PartialType))
                {
                    var typeFilename     = filenameCreator.Create(GetTypeExtension(type), type.FullName);
                    var settingsTypeFile = new SettingsTypeProjectFile(type, typeFilename, Options.DecompilationContext, Options.Decompiler, createDecompilerOutput);
                    designerTypeFile = new SettingsDesignerTypeProjectFile(settingsTypeFile, designerFilename, createDecompilerOutput);
                    Files.Add(settingsTypeFile);
                }
                else
                {
                    designerTypeFile = new TypeProjectFile(type, designerFilename, Options.DecompilationContext, Options.Decompiler, createDecompilerOutput);
                }
                var settingsFile = new SettingsProjectFile(type, settingsFilename);
                designerTypeFile.DependentUpon         = settingsFile;
                designerTypeFile.AutoGen               = true;
                designerTypeFile.DesignTimeSharedInput = true;
                settingsFile.Generator     = type.IsPublic ? "PublicSettingsSingleFileGenerator" : "SettingsSingleFileGenerator";
                settingsFile.LastGenOutput = designerTypeFile;
                Files.Add(settingsFile);
                return(designerTypeFile);
            }

            var newFilename = filenameCreator.Create(GetTypeExtension(type), type.FullName);

            return(new TypeProjectFile(type, newFilename, Options.DecompilationContext, Options.Decompiler, createDecompilerOutput));
        }