private void newToolStripMenuItem_Click(object sender, EventArgs e) { NewForm lForm = new NewForm(this); if (lForm.ShowDialog() == DialogResult.OK) { //===================================================================== // Load the file from the CD image //===================================================================== CDImage lCDImage = new CDImage(new FileInfo(lForm.CDImageTextBox.Text)); MMCD.Course lCourse = (MMCD.Course)lForm.CourseDropDown.SelectedItem; byte[] lLevelBinary = lCDImage.Extract(lCourse.CDOffset, lCourse.CDLength); MemoryStream lLevelStream = new MemoryStream(lLevelBinary); Level lNewLevel = new Level(lLevelStream); //===================================================================== // Check that the whole file has been read //===================================================================== if (lLevelStream.Length != lLevelStream.Position) { throw new DeserialisationException(string.Format("Deserialisation terminated early at byte {0} of {1}", lLevelStream.Position, lLevelStream.Length)); } //===================================================================== // Create a new VersionList based on this level, and set it up //===================================================================== VersionList lVersionList = new VersionList(lNewLevel, lCourse.CourseName, lCourse.FileName); RootChunk = lVersionList; mCurrentFile = null; } }
private void OnEnable() { streamingAssetsPathPrefsKey = "StreamingAssetsPathPrefsKey"; if (Directory.Exists(Application.streamingAssetsPath)) { streamingAssetsPath = "Assets/StreamingAssets/"; } else { streamingAssetsPath = EditorPrefs.GetString(streamingAssetsPathPrefsKey, string.Empty); } EditorPrefs.SetString(streamingAssetsPathPrefsKey, streamingAssetsPath); resourcesPathPrefsKey = "ResourcesPathPrefsKey"; if (Directory.Exists(Application.dataPath + "/Resources")) { resourcesPath = "Assets/Resources/"; } else if (Directory.Exists(Application.dataPath + "/resources")) { resourcesPath = "Assets/resources/"; } else { resourcesPath = EditorPrefs.GetString(resourcesPathPrefsKey, string.Empty); } EditorPrefs.SetString(resourcesPathPrefsKey, resourcesPath); VersionList versionList = AssetDatabase.LoadAssetAtPath <VersionList>(resourcesPath + "Version.asset"); currentVersion = null == versionList ? "1.0.0" : versionList.CurrentVersion; }
/// <summary> /// Checks the version /// </summary> /// <exception cref="System.NotImplementedException"></exception> public async Task CheckVersions(Type targetSubscriber = null) { // If 3 mins passed, update info if (targetSubscriber == typeof(UpdateMenuViewModel) && Properties.Settings.Default.LastVersionCheck.AddSeconds(30) <= DateTime.Now || Properties.Settings.Default.LastVersionCheck.AddMinutes(3) <= DateTime.Now) { // Initialize an HttpWebRequest for the current URL. var webReq = (HttpWebRequest)WebRequest.Create(ConstantsBase.ApiUrl + "Version"); webReq.Timeout = 1000; webReq.Headers.Add("Client-Version", _currentVersion.ToString()); // Send request using (WebResponse response = await webReq.GetResponseAsync()) { // Get response var respStream = response.GetResponseStream(); // The downloaded resource ends up in the variable named content. var content = new MemoryStream(); // Read response if stream is not null if (respStream != null) { await respStream.CopyToAsync(content); } // Deserialize string string str = Encoding.Default.GetString(content.ToArray()); VersionList.Clear(); VersionList = JsonConvert.DeserializeObject <List <VersionModel> >(str); // Update AppUpdater hash this._appUpdaterHash = response.Headers["App-Checksum"]; content.Dispose(); } // Update last check time Properties.Settings.Default.LastVersionCheck = DateTime.Now; Properties.Settings.Default.Save(); } if (VersionList == null || !VersionList.Any()) { return; } // Get latest version LatestVersion = VersionList.MaxBy(x => x.VersionNumber); if (CheckVersionsCompleted != null) { bool update = LatestVersion.VersionNumber > _currentVersion; IsUpdateAvailable = update; CheckVersionsCompleted(this, new CheckVersionEventArgs(update, targetSubscriber)); } }
void RevertButton_Click(object sender, EventArgs e) { if (MessageBox.Show("Are you sure? This will lose any unsaved changes in your current version of the level.", "Revert Level", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes) { VersionList lVersionList = (VersionList)mMainForm.RootChunk; lVersionList.CurrentLevel = lVersionList.GetLevel(mVersion); mMainForm.RootChunk = mMainForm.RootChunk; } }
private void RefreshVersions() { if (package == null) { return; } var additionalVersions = AdditionalVersions.ToList(); if (package.KeyVersions.Where(v => v != package.VersionToDisplay).Any(version => Selection.IsSelected(version))) { SetExpandInternal(true); } else if (AdditionalVersions.Any(version => Selection.IsSelected(version))) { SetSeeAllVersions(true); SetExpandInternal(true); } if (!Expander.Expanded) { return; } VersionList.Clear(); var seeAllVersionsClicked = Selection.IsSeeAllVersions(package.VersionToDisplay); var showToolbar = !seeAllVersionsClicked; var versions = seeAllVersionsClicked ? additionalVersions : package.KeyVersions; versions = versions.Where(p => p != package.VersionToDisplay).Reverse(); foreach (var version in versions) { var versionLabel = new PackageVersionLabel(version, Selection); VersionList.Add(versionLabel); } var hasAnyVersion = additionalVersions.Any() || versions.Any(); UIUtils.SetElementDisplay(NoVersions, !hasAnyVersion); UIUtils.SetElementDisplay(SeeAllVersions, hasAnyVersion); UIUtils.SetElementDisplay(VersionToolbar, showToolbar); // TODO: Hard-code until scrollView can size to its content // Note: ListItemMaxHeight is used because there is an issue with VisualElement where at construction time, // styling is not yet applied and max height returns 0 even though the stylesheet has it at 150. var maxHeight = Math.Max(VersionList.style.maxHeight.value.value, ListItemMaxHeight); VersionList.style.minHeight = Math.Min(versions.Count() * ListItemSpacing, maxHeight); // Hack until ScrollList has a better way to do the same -- Vertical scroll bar is not yet visible var maxNumberOfItemBeforeScrollbar = 7; VersionList.EnableClass("hasScrollBar", versions.Count() > maxNumberOfItemBeforeScrollbar); }
public async static Task RefreshVersionListAsync() { var list = await Handler.GetVersionsAsync(); VersionList.Clear(); foreach (var item in list) { VersionList.Add(item); } }
public static void RefreshVersionList() { var list = Handler.GetVersions(); VersionList.Clear(); foreach (var item in list) { VersionList.Add(item); } }
public void GetLessThanTest() { var vl1 = new VersionList(); vl1.AllFiles = this.list; var vl2 = new VersionList(); vl2.GetLessThan(vl1); }
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e) { // app list ApplicationList mApplicationList = new ApplicationList(); VersionList mVersionList = new VersionList(); //foreach (AppDetail app in mApplicationList.AppList){ // Debug.WriteLine( app.Title + app.URL); //} AppsListBox.ItemsSource = mApplicationList.AppList; VersionHistoryListBox.ItemsSource = mVersionList.ItemList; }
private void LoadInternal(eOpenType xiOpenType, string xiFilename) { Chunk lNewRootChunk = null; string lExceptionWhen = "opening file"; try { using (FileStream fs = File.OpenRead(xiFilename)) { lExceptionWhen = "deserialising the file"; switch (xiOpenType) { case eOpenType.LevelBinary: lNewRootChunk = new Level(fs); break; case eOpenType.UnknownBinary: lNewRootChunk = new FileChunk(fs); break; case eOpenType.Mmv: lNewRootChunk = new VersionList(fs); break; case eOpenType.Xml: XmlSerializer xs = new XmlSerializer(typeof(Chunk)); lNewRootChunk = (Chunk)xs.Deserialize(fs); break; default: throw new Exception("unreachable case"); } if (fs.Length != fs.Position) { //check the whole file has been read throw new DeserialisationException(string.Format("Deserialisation terminated early at byte {0} of {1}", fs.Position, fs.Length)); } } } catch (Exception err) { Trace.WriteLine(err); MessageBox.Show(string.Format("Exception occurred while {0}: {1}", lExceptionWhen, err.Message), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } // level loaded OK, now fill tree: RootChunk = lNewRootChunk; mLocalSettings.LastOpenedFile = xiFilename; mLocalSettings.LastOpenedType = xiOpenType; mCurrentFile = xiFilename; mCurrentFileMode = xiOpenType == eOpenType.Mmv ? eSaveMode.Mmv : xiOpenType == eOpenType.Xml ? eSaveMode.Xml : eSaveMode.Binary; }
public void ResolverSort_Lowest() { HashSet <PackageIdentity> installed = new HashSet <PackageIdentity>(); var newPackages = new HashSet <string>(); var comparer = new ResolverComparer(DependencyBehavior.Lowest, installed, newPackages); var packages = new List <ResolverPackage>(VersionList.Select(e => new ResolverPackage("packageA", e))); packages.Sort(comparer); Assert.Equal("0.1.0", packages.First().Version.ToNormalizedString()); }
/// <summary> /// Downloads the version package. /// </summary> /// <exception cref="System.NotImplementedException"></exception> public async Task DownloadLatestVersion() { if (!VersionList.Any()) { await CheckVersions(); } // Get latest version LatestVersion = VersionList.MaxBy(x => x.VersionNumber); if (LatestVersion == null) { throw new InvalidOperationException( "A version wasn't found after successfully reaching the server, this should not happen!"); } // Check if package already is downloaded if (File.Exists(ConstantsBase.UpdatePath) && String.Equals(CrcHelper.GetCrc32HashToString(ConstantsBase.UpdatePath), LatestVersion.CrcHash, StringComparison.CurrentCultureIgnoreCase)) { // Used to raise DownloadCompleted _webClient.CancelAsync(); return; } // Iterate URLs foreach (var url in LatestVersion.DownloadUrls) { Directory.CreateDirectory("tmp"); // Delete file if existent if (File.Exists(ConstantsBase.UpdatePath)) { File.Delete(ConstantsBase.UpdatePath); } // Download file await _webClient.DownloadFileTaskAsync(new Uri(url), ConstantsBase.UpdatePath); if (CrcHelper.GetCrc32HashToString(ConstantsBase.UpdatePath) != LatestVersion.CrcHash) { continue; } } if (!String.Equals(CrcHelper.GetCrc32HashToString(ConstantsBase.UpdatePath), LatestVersion.CrcHash, StringComparison.CurrentCultureIgnoreCase)) { throw new IOException("Could not successfully download the update package! Data corruption occurred! "); } }
private void MainForm_Load(object sender, EventArgs e) { if (!Directory.Exists(location)) { Directory.CreateDirectory(location); } //CONSOLE _writer = new ConsoleStringWriter(this); Console.SetOut(_writer); //END CONSOLE //SETTINGS lastLogin = new LastLogin(); if (File.Exists(Path.Combine(location, "lastlogin"))) { String[] lastLoginData = lastLogin.GetLastLogin(); userText.Text = lastLoginData[0]; passText.Text = lastLoginData[1]; } try { FileStream stream = new FileStream(location + "settings", FileMode.Open); optionRememberBox.Checked = Convert.ToBoolean(stream.ReadByte()); optionConsoleBox.Checked = Convert.ToBoolean(stream.ReadByte()); } catch (Exception) { } //END SETTINGS //SERVER STATUS status = new ServerStatus(this); //END SERVER STATUS //NEM nemQuery = new QueryNEM(this); //END NEM //VERSIONLIST versionList = new VersionList(this); //END VERSIONLIST //OLD REPO repo = new Repo.QueryRepo(this); //END OLD REPO //TECHNIC PLATFORM technicDefaultPacks = new TechnicDefaultPacks(this); }
public async static Task RefreshVersionListAsync() { if (VersionList == null) { VersionList = new ObservableCollection <Version>(); } var list = await Handler.GetVersionsAsync(); VersionList.Clear(); foreach (var item in list) { VersionList.Add(item); } }
public static void RefreshVersionList() { if (VersionList == null) { VersionList = new ObservableCollection <Version>(); } var list = Handler.GetVersions(); VersionList.Clear(); foreach (var item in list) { VersionList.Add(item); } }
public string AddToRepository(string sourceDir, bool beta, string description) { if (!Configured()) return "Error : Not configured"; var build = Tools.GetFileRevision(sourceDir + @"\Yatse2.exe"); if (build == 0) return "Error : Invalid source dir"; if (Directory.Exists(_platformDir + @"\" + build)) { return "Error : Build allready in repository"; } Directory.CreateDirectory(_platformDir + @"\" + build); Directory.CreateDirectory(_platformDir + @"\" + build + @"\Files"); var fileinfos = new Collection<FileInfo>(); var files = Directory.GetFiles(sourceDir, "*.*", SearchOption.AllDirectories); foreach (var file in files) { if (file.Contains(".pdb") || file.Contains(".vshost.") || file.Contains(".application")) continue; var fileinfo = new FileInfo { FilePath = file.Replace(sourceDir, ""), FileHash = FileHash.GetFileHashString(file) }; if (!File.Exists(_platformDir + @"\" + build + @"\Files\" + fileinfo.FileHash + ".dat")) { File.Copy(file, _platformDir + @"\" + build + @"\Files\" + fileinfo.FileHash + ".dat"); } fileinfos.Add(fileinfo); } var versionFile = new VersionFile { Description = description, FileInfos = fileinfos }; versionFile.Save(_repoDir + @"\xmls\Version_" + _platform + "_" + build + ".xml"); var liste = new VersionList(); liste.Load(_repoDir + @"\xmls\Versions_" + _platform + ".xml"); liste.Version.Add(new VersionInfo { Beta = beta, Build = build }); liste.Save(_repoDir + @"\xmls\Versions_" + _platform + ".xml"); return null; }
public void Test() { InvitationRequest request = new InvitationRequest(1111); this.TestFactory(request); InvitationAck ack = new InvitationAck(2222); this.TestFactory(ack); byte[] data = { 12, 34, 56 }; FileDataResponse dataResponse = new FileDataResponse(data, 3333); this.TestFactory(dataResponse); FileEvent e1 = new FileEvent(); e1.Name = "1234"; List <FileEvent> lf = new List <FileEvent>(); lf.Add(e1); PatchRequest patchRequest = new PatchRequest(lf, 4444); this.TestFactory(patchRequest); PeerList peerList = PeerList.GetPeerList("abc"); peerList.AddPeer(new Peer("127.0.0.1", 5555)); PeerListMessage pm = new PeerListMessage(peerList, 6666); this.TestFactory(pm); SyncAck syncAck = new SyncAck(7777); this.TestFactory(syncAck); SyncRequest syncRequest = new SyncRequest(8888); this.TestFactory(syncRequest); File.WriteAllText(".Distribox/VersionList.txt", "[]"); VersionList vl = new VersionList(); VersionListMessage vm = new VersionListMessage(vl, 9999); this.TestFactory(vm); }
public void ResolverSort_HighestMinorInstalled() { HashSet <PackageIdentity> installed = new HashSet <PackageIdentity>(); installed.Add(new PackageIdentity("packageA", NuGetVersion.Parse("2.0.0"))); var newPackages = new HashSet <string>(); var comparer = new ResolverComparer(DependencyBehavior.HighestMinor, installed, newPackages); var packages = new List <ResolverPackage>(VersionList.Select(e => new ResolverPackage("packageA", e))); packages.Sort(comparer); // take the installed one first Assert.Equal("2.0.0", packages.First().Version.ToNormalizedString()); }
public void ResolverSort_IgnoreInstalled() { HashSet <PackageIdentity> installed = new HashSet <PackageIdentity>(); installed.Add(new PackageIdentity("packageA", NuGetVersion.Parse("2.0.0"))); var newPackages = new HashSet <string>(); var comparer = new ResolverComparer(DependencyBehavior.Ignore, installed, newPackages); var packages = new List <ResolverPackage>(VersionList.Select(e => new ResolverPackage("packageA", e))); packages.Sort(comparer); // Ignore should still use the installed package Assert.Equal("2.0.0", packages.First().Version.ToNormalizedString()); Assert.Equal("0.1.0", packages.Last().Version.ToNormalizedString()); }
public void ResolverSort_HighestMinorPreferUpgrade() { HashSet <PackageIdentity> installed = new HashSet <PackageIdentity>(); installed.Add(new PackageIdentity("packageA", NuGetVersion.Parse("2.0.0"))); var newPackages = new HashSet <string>(); var comparer = new ResolverComparer(DependencyBehavior.HighestMinor, installed, newPackages); VersionRange removeRange = new VersionRange(NuGetVersion.Parse("2.0.0"), true, NuGetVersion.Parse("2.0.0"), true); var packages = new List <ResolverPackage>(VersionList.Where(e => !removeRange.Satisfies(e)).Select(e => new ResolverPackage("packageA", e))); packages.Sort(comparer); // take the upgrade of the highest minor Assert.Equal("2.5.0", packages.First().Version.ToNormalizedString()); }
public void ResolverSort_HighestUpgrade() { HashSet <PackageIdentity> installed = new HashSet <PackageIdentity>(); installed.Add(new PackageIdentity("packageA", NuGetVersion.Parse("2.0.0"))); var newPackages = new HashSet <string>(); var comparer = new ResolverComparer(DependencyBehavior.Highest, installed, newPackages); VersionRange removeRange = new VersionRange(NuGetVersion.Parse("2.0.0"), true, NuGetVersion.Parse("2.0.1"), true); var packages = new List <ResolverPackage>(VersionList.Where(e => !removeRange.Satisfies(e)).Select(e => new ResolverPackage("packageA", e))); packages.Sort(comparer); // ignore the installed package if it is not in allowed Assert.Equal("3.0.9", packages.First().Version.ToNormalizedString()); Assert.Equal("0.1.0", packages.Last().Version.ToNormalizedString()); }
public override VersionUriList GetItemVersions(ItemDefinition itemDefinition, CallContext context) { var item = GetItem(itemDefinition.ID); if (item != null) { var versions = new VersionUriList(); foreach (var entry in item.Languages) { var versionList = new VersionList(); foreach (var v in entry.Versions) { versions.Add(new VersionUri(Language.Parse(entry.Language), Sitecore.Data.Version.Parse(v.Number))); } } context.Abort(); return(versions); } return(base.GetItemVersions(itemDefinition, context)); }
public VersionList GetBuildList() { if (!Configured()) return null; var liste = new VersionList(); liste.Load(_repoDir + @"\xmls\Versions_" + _platform + ".xml"); return liste; }
public VersionList GetBuildList(bool beta) { if (!Configured()) return null; var liste = new VersionList(); var liste2 = new VersionList(); liste.Load(_tempDirectory + @"\Versions_" + _platform + ".xml"); foreach (var build in liste.Version) { if (build.Beta && beta ) liste2.Version.Add(build); else if (!build.Beta) liste2.Version.Add(build); } Log("Get build list : Builds founds : " + liste2.Version.Count); return liste2; }
public bool RemoveFromRepository(VersionInfo build) { if (!Configured()) return false; if (File.Exists(_repoDir + @"\xmls\Version_" + _platform + "_" + build.Build + ".xml")) { Directory.Delete(_platformDir + @"\" + build.Build, true); File.Delete(_repoDir + @"\xmls\Version_" + _platform + "_" + build.Build + ".xml"); } var versions = new VersionList(); versions.Load(_repoDir + @"\xmls\Versions_" + _platform + ".xml"); versions.Version.Remove(build); versions.Save(_repoDir + @"\xmls\Versions_" + _platform + ".xml"); return true; }
/// <summary> /// Initializes a new instance of the <see cref="Distribox.Network.VersionListMessage"/> class. /// </summary> /// <param name="list">The list.</param> /// <param name="myPort">My port.</param> public VersionListMessage(VersionList list, int myPort) : base(myPort) { this.List = list; this.Type = MessageType.VersionListMessage; }
public VerListTable(VersionList formRef) { form = formRef; }
///======================================================================== /// Method : publishToolStripMenuItem_Click /// /// <summary> /// The Publish operation /// </summary> /// <param name="sender"></param> /// <param name="e"></param> ///======================================================================== private void publishToolStripMenuItem_Click(object sender, EventArgs e) { PublishForm lForm = new PublishForm(this); if (RootChunk is VersionList) { //===================================================================== // Use the properties saved on the VersionList as defaults //===================================================================== VersionList lVersionList = (VersionList)RootChunk; if (lVersionList.CDFilename != null && lVersionList.CDFilename != "") { lForm.CourseDropDown.SelectedItem = MMCD.Courses.Find(new Predicate <MMCD.Course>( delegate(MMCD.Course xiCourse) { return(xiCourse.FileName == lVersionList.CDFilename); })); } if (lVersionList.BinaryFilename != null && lVersionList.BinaryFilename != "") { lForm.BinaryFileTextBox.Text = lVersionList.BinaryFilename; } if (lVersionList.CourseName != null && lVersionList.CourseName != "") { lForm.NameTextBox.Text = lVersionList.CourseName; } } if (lForm.ShowDialog() == DialogResult.OK) { FileInfo lBinaryFile = new FileInfo(lForm.BinaryFileTextBox.Text); //===================================================================== // If we want to keep backups, make one now //===================================================================== if (lForm.BackupsCheckBox.Checked && lBinaryFile.Exists) { string lBackupExtension = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss.bak"); string lBackupPath = Path.Combine(Path.GetDirectoryName(lForm.BinaryFileTextBox.Text), "Backups"); if (!Directory.Exists(lBackupPath)) { Directory.CreateDirectory(lBackupPath); } string lBackupFile = Path.Combine(lBackupPath, Path.GetFileNameWithoutExtension(lForm.BinaryFileTextBox.Text) + "." + lBackupExtension); lBinaryFile.CopyTo(lBackupFile); //=================================================================== // Remove any outdated backups //=================================================================== FileInfo[] lAllBackups = Array.ConvertAll <string, FileInfo>(Directory.GetFiles(lBackupPath, Path.GetFileNameWithoutExtension(lForm.BinaryFileTextBox.Text) + ".*.bak"), new Converter <string, FileInfo>(delegate(string xiFilename) { return(new FileInfo(xiFilename)); })); Utils.ArrayStableSort(lAllBackups, x => x.CreationTime); for (int ii = (int)lForm.BackupCountUpDown.Value; ii < lAllBackups.Length; ii++) { lAllBackups[ii].Delete(); } } //===================================================================== // Save the binary file //===================================================================== using (FileStream lFileStream = lBinaryFile.Create()) { CurrentLevel.Serialise(lFileStream); } if (lForm.UpdateCDImageCheckBox.Checked) { //=================================================================== // Update the CD image //=================================================================== FileInfo lCDFile = new FileInfo(lForm.CDImageTextBox.Text); CDImage lImage = new CDImage(lCDFile); MMCD.Course lCourse = (MMCD.Course)lForm.CourseDropDown.SelectedItem; byte[] lBinaryData = new byte[lCourse.CDLength]; lBinaryFile.Refresh(); if (lBinaryFile.Length != lCourse.CDLength) { MessageBox.Show("File is the wrong length! It will be padded with zeros or truncated to fit on the CD.", "Publish Course", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } using (FileStream lFileStream = lBinaryFile.OpenRead()) { lFileStream.Read(lBinaryData, 0, (int)Math.Min(lBinaryData.Length, lBinaryFile.Length)); } lImage.Replace(lBinaryData, lCourse.CDOffset); lImage.WriteFile(lCDFile); byte[] lCourseNameForCD = Encoding.ASCII.GetBytes(lCourse.GetCDCourseName(lForm.NameTextBox.Text)); foreach (long lNameOffset in lCourse.NameOffsets) { lImage.Replace(lCourseNameForCD, lNameOffset); lImage.WriteFile(lCDFile); } } if (RootChunk is VersionList) { //=================================================================== // Update the properties saved on the VersionList //=================================================================== VersionList lVersionList = (VersionList)RootChunk; lVersionList.BinaryFilename = lForm.BinaryFileTextBox.Text; if (lForm.UpdateCDImageCheckBox.Checked) { lVersionList.CDFilename = ((MMCD.Course)lForm.CourseDropDown.SelectedItem).FileName; lVersionList.CourseName = lForm.NameTextBox.Text; } //=================================================================== // Save the VersionList //=================================================================== if (mCurrentFile != null) { SaveInternal(mCurrentFileMode, mCurrentFile); } } } }
private void SaveInternal(eSaveMode xiSaveMode, string xiFilename) { if (RootChunk == null) { MessageBox.Show("Can't save: no file is open"); return; } string lExceptionWhen = "saving file"; try { long lPreviousSize = -1; if (xiSaveMode == eSaveMode.Binary && File.Exists(xiFilename)) { lPreviousSize = new FileInfo(xiFilename).Length; } using (FileStream fs = File.Create(xiFilename)) { lExceptionWhen = "serialising the file"; if (xiSaveMode == eSaveMode.Binary) { if (RootChunk is VersionList) { CurrentLevel.Serialise(fs); } else { RootChunk.Serialise(fs); } } else if (xiSaveMode == eSaveMode.Xml) { XmlSerializer xs = new XmlSerializer(typeof(Chunk)); if (RootChunk is VersionList) { xs.Serialize(fs, CurrentLevel); } else { xs.Serialize(fs, RootChunk); } } else if (xiSaveMode == eSaveMode.Mmv) { if (RootChunk is VersionList) { VersionList lVersionList = (VersionList)RootChunk; lVersionList.AddLevel(CurrentLevel); RecursiveAddChunkNode(ChunkTreeView.Nodes[0].Nodes, 1, lVersionList.GetLastVersion()); } else if (RootChunk is Level) { VersionList lVersionList = new VersionList( (Level)RootChunk, Path.GetFileNameWithoutExtension(xiFilename), null); RootChunk = lVersionList; } RootChunk.Serialise(fs); } } if (lPreviousSize != -1 && lPreviousSize != new FileInfo(xiFilename).Length) { MessageBox.Show("WARNING: The size of your level has changed. Please check it's not too large, and check MMEd for bugs that have allowed the size to change.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } catch (Exception err) { Trace.WriteLine(err); MessageBox.Show(string.Format("Exception occurred while {0}: {1}", lExceptionWhen, err.Message), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } mLocalSettings.LastSavedFile = xiFilename; mLocalSettings.LastSavedMode = xiSaveMode; mCurrentFile = xiFilename; mCurrentFileMode = xiSaveMode; }
void OnGUI() { EditorGUILayout.BeginVertical("box"); { EditorGUILayout.LabelField("Version Creator", EditorStyles.boldLabel); EditorGUILayout.Space(); EditorGUILayout.BeginVertical("box"); { EditorGUILayout.BeginHorizontal(); { streamingAssetsPath = EditorGUILayout.TextField("StreamingAssets Path", streamingAssetsPath, GUILayout.Width(440)); if (GUILayout.Button("Select", GUILayout.Width(88))) { streamingAssetsPath = EditorUtility.OpenFolderPanel("Choose a database storage location.", Application.dataPath, "StreamingAssets"); streamingAssetsPath = "Assets" + streamingAssetsPath.Replace(Application.dataPath, string.Empty).Replace("\\", "/") + "/"; EditorPrefs.SetString(streamingAssetsPathPrefsKey, streamingAssetsPath); } } EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); { resourcesPath = EditorGUILayout.TextField("Resouces Path", resourcesPath, GUILayout.Width(440)); if (GUILayout.Button("Select", GUILayout.Width(88))) { resourcesPath = EditorUtility.OpenFolderPanel("Choose the resources.", Application.dataPath, "Resources"); resourcesPath = "Assets" + resourcesPath.Replace(Application.dataPath, string.Empty).Replace("\\", "/") + "/"; EditorPrefs.SetString(resourcesPathPrefsKey, resourcesPath); VersionList versionList = AssetDatabase.LoadAssetAtPath <VersionList>(resourcesPath + "Version.asset"); currentVersion = null == versionList ? "1.0.0" : versionList.CurrentVersion; } } EditorGUILayout.EndHorizontal(); currentVersion = EditorGUILayout.TextField("Current version", currentVersion); if (GUILayout.Button("Preview")) { DirectoryInfo info = new DirectoryInfo(streamingAssetsPath); if (!info.Exists) { streamingAssetsPath = EditorUtility.OpenFolderPanel("Choose a database storage location.", Application.dataPath, "StreamingAssets"); streamingAssetsPath = "Assets" + streamingAssetsPath.Replace(Application.dataPath, string.Empty).Replace("\\", "/") + "/"; EditorPrefs.SetString(streamingAssetsPathPrefsKey, streamingAssetsPath); info = new DirectoryInfo(streamingAssetsPath); } List <FileInfo> fileInfos = Utility.GetAllFileInfoFromTheDirectory(info); versions = new List <VersionTemp>(); int count = fileInfos.Count; for (int i = 0; i < count; i++) { if (fileInfos[i].Extension.Equals(".meta")) { continue; } versions.Add(new VersionTemp(true, fileInfos[i].FullName.Replace("\\", "/").Replace(Application.dataPath + streamingAssetsPath.Remove(0, 6), ""), fileInfos[i].Name, true, false, Utility.GetFileMD5(fileInfos[i].FullName), fileInfos[i].Length)); } } } EditorGUILayout.EndVertical(); EditorGUILayout.BeginVertical("box"); { scrollViewPos = EditorGUILayout.BeginScrollView(scrollViewPos); if (null != versions) { int count = versions.Count; for (int i = 0; i < count; i++) { EditorGUILayout.BeginVertical("box"); versions[i].IsUseful = EditorGUILayout.BeginToggleGroup(versions[i].AssetName, versions[i].IsUseful); EditorGUILayout.LabelField("Name in project", versions[i].AssetName); versions[i].LocalName = EditorGUILayout.TextField("Name in local", versions[i].LocalName); versions[i].IsNeedCheck = EditorGUILayout.Toggle("Need to check", versions[i].IsNeedCheck); versions[i].IsUnzip = EditorGUILayout.Toggle("Need to extract", versions[i].IsUnzip); EditorGUILayout.LabelField("Resource MD5", versions[i].Md5); EditorGUILayout.LabelField("Resource size", versions[i].FileSize / 1024 + "KB"); EditorGUILayout.EndToggleGroup(); EditorGUILayout.EndVertical(); } if (GUILayout.Button("Create")) { List <Version> allFiles = new List <Version>(); List <Version> needCheckFiles = new List <Version>(); for (int i = 0; i < versions.Count; i++) { if (versions[i].IsUseful) { Version version = versions[i].GetVersion(); allFiles.Add(version); if (versions[i].IsNeedCheck) { needCheckFiles.Add(version); } } } VersionList versionList = CreateInstance <VersionList>(); versionList.CurrentVersion = currentVersion; versionList.Files = allFiles.ToArray(); versionList.FilesNeedCheck = needCheckFiles.ToArray(); string savePath = resourcesPath + "Version.asset"; AssetDatabase.CreateAsset(versionList, savePath); AssetDatabase.Refresh(); Selection.activeObject = AssetDatabase.LoadAssetAtPath <Object>(savePath); Close(); } } EditorGUILayout.EndScrollView(); } EditorGUILayout.EndVertical(); } EditorGUILayout.EndVertical(); }