Beispiel #1
0
        public static void SerializeToXml(string path, IEnumerable <ShortcutInfo> shortcuts)
        {
            var doc = new XDocument(
                new XElement(
                    new XElement(
                        "Shortcuts",
                        shortcuts.Select(f =>
                                         new XElement(
                                             nameof(ShortcutInfo),
                                             new XAttribute(nameof(f.Value), f.Value),
                                             new XAttribute(nameof(f.Description), f.Description),
                                             new XAttribute(nameof(f.Comment), f.Comment),
                                             new XElement(nameof(f.Languages), f.Languages.Select(language => new XElement(nameof(Language), language.ToString()))),
                                             new XElement(nameof(f.Tags), f.Tags.Select(tag => new XElement("Tag", tag)))
                                             )
                                         )
                        )
                    )
                );

            using (var stringWriter = new Utf8StringWriter())
            {
                var xmlWriterSettings = new XmlWriterSettings()
                {
                    OmitXmlDeclaration = false,
                    NewLineChars       = "\r\n",
                    IndentChars        = "  ",
                    Indent             = true
                };

                using (XmlWriter xmlWriter = XmlWriter.Create(stringWriter, xmlWriterSettings))
                    doc.WriteTo(xmlWriter);

                IOUtility.WriteAllText(path, stringWriter.ToString());
            }
        }
Beispiel #2
0
        public void ToConsole(Exception e)
        {
            if (e == null)
            {
                return;
            }

            lock (VitaNexCore.ConsoleLock)
            {
                Console.Write('[');
                Utility.PushColor(ConsoleColor.Green);
                Console.Write(Name);
                Utility.PopColor();
                Console.Write("]: ");
                Utility.PushColor(ConsoleColor.Red);
                Console.WriteLine((Quiet && !Debug) ? e.Message : e.ToString());
                Utility.PopColor();
            }

            if (Debug)
            {
                e.Log(IOUtility.EnsureFile(VitaNexCore.LogsDirectory + "/Debug/" + TypeOf.FullName + ".log"));
            }
        }
        public void LoadState()
        {
            IOUtility.EnsureFile(VitaNexCore.CacheDirectory + "/States/" + _TypeOf.FullName + ".state").Deserialize(
                reader =>
            {
                if (reader.End())
                {
                    return;
                }

                int version = reader.GetVersion();

                switch (version)
                {
                case 0:
                    {
                        _Name      = reader.ReadString();
                        _Debug     = reader.ReadBool();
                        _QuietMode = reader.ReadBool();
                    }
                    break;
                }
            });
        }
Beispiel #4
0
        public ActionResult Preview(string imagePath, string rotateTypes)
        {
            var    physicalPath = Server.MapPath(HttpUtility.UrlDecode(imagePath));
            var    imageFormat  = ImageTools.ConvertToImageFormat(Path.GetExtension(physicalPath));
            Stream imageStream  = new MemoryStream();
            Stream outputStream = new MemoryStream();

            try
            {
                imageStream = RotateImage(rotateTypes, physicalPath, imageFormat);

                ImageTools.ResizeImage(imageStream, outputStream, imageFormat, 0, 200, true, 80);
                outputStream.Position = 0;
                return(File(outputStream, IOUtility.MimeType(physicalPath)));
            }
            finally
            {
                if (imageStream != null)
                {
                    imageStream.Close();
                    imageStream.Dispose();
                }
            }
        }
Beispiel #5
0
 public Object Run()
 {
     return(IOUtility.GetResourceAsStream(root.Assembly, "Resources/", resourceName));
 }
Beispiel #6
0
        /// <summary>
        /// Read Row and convert each value into a variableValue
        /// and each row to a Datatuple
        /// </summary>
        /// <param name="row">List of values in one row</param>
        /// <param name="indexOfRow">Currently row index</param>
        /// <returns>DataTuple</returns>
        public DataTuple ReadRow(List <string> row, int indexOfRow)
        {
            DataTuple dt    = new DataTuple();
            string    value = "";

            // convert row to List<VariableValue>
            for (int i = 0; i < row.Count(); i++)
            {
                VariableIdentifier variableIdentifier = this.SubmitedVariableIdentifiers.ElementAt(i);
                long variableId = 0;
                if (variableIdentifier.id > 0)
                {
                    variableId = this.SubmitedVariableIdentifiers.ElementAt(i).id;
                }
                else
                {
                    variableId = getVariableUsage(variableIdentifier).Id;
                }



                // if variable from systemtype datatime
                // maybee needs to convert into the default datetime culture format
                if (this.StructuredDataStructure.Variables.Where(p => p.Id.Equals(variableId)).FirstOrDefault().DataAttribute.DataType.SystemType.Equals("DateTime"))
                {
                    Dlm.Entities.DataStructure.DataType dataType = this.StructuredDataStructure.Variables.Where(p => p.Id.Equals(variableId)).FirstOrDefault().DataAttribute.DataType;

                    if (dataType != null && dataType.Extra != null)
                    {
                        DataTypeDisplayPattern dp = DataTypeDisplayPattern.Materialize(dataType.Extra);
                        if (dp != null && !string.IsNullOrEmpty(dp.StringPattern))
                        {
                            value = IOUtility.ConvertToDateUS(row[i], dp.StringPattern);
                        }
                        else
                        {
                            value = IOUtility.ConvertDateToCulture(row[i]);
                        }
                    }
                    else
                    {
                        value = IOUtility.ConvertDateToCulture(row[i]);
                    }
                }
                else
                {
                    if (this.StructuredDataStructure.Variables.Where(p => p.Id.Equals(variableId)).FirstOrDefault().DataAttribute.DataType.SystemType.Equals("Double") ||
                        this.StructuredDataStructure.Variables.Where(p => p.Id.Equals(variableId)).FirstOrDefault().DataAttribute.DataType.SystemType.Equals("Decimal") ||
                        this.StructuredDataStructure.Variables.Where(p => p.Id.Equals(variableId)).FirstOrDefault().DataAttribute.DataType.SystemType.Equals("Float"))
                    {
                        value = row[i];

                        if (Info.Decimal.Equals(DecimalCharacter.comma))
                        {
                            if (value.Contains("."))
                            {
                                value = value.Replace(".", "");
                            }
                            if (value.Contains(","))
                            {
                                value = value.Replace(',', '.');
                            }
                        }

                        if (Info.Decimal.Equals(DecimalCharacter.point))
                        {
                            if (value.Contains(","))
                            {
                                value = value.Remove(',');
                            }
                        }
                    }
                    else
                    {
                        value = row[i];
                    }
                }

                dt.VariableValues.Add(DatasetManager.CreateVariableValue(value, "", DateTime.Now, DateTime.Now, new ObtainingMethod(), variableId, new List <ParameterValue>()));
            }


            return(dt);
        }
        public static void Configure()
        {
            Is64Bit = (IntPtr.Size == 8);

            KnownInstallationRegistryKeys = new[]
            {
                @"Electronic Arts\EA Games\Ultima Online Classic", @"Electronic Arts\EA Games\Ultima Online Stygian Abyss Classic",
                @"Origin Worlds Online\Ultima Online\KR Legacy Beta", @"EA Games\Ultima Online: Mondain's Legacy\1.00.0000",
                @"Origin Worlds Online\Ultima Online\1.0", @"Origin Worlds Online\Ultima Online Third Dawn\1.0",
                @"EA GAMES\Ultima Online Samurai Empire", @"EA Games\Ultima Online: Mondain's Legacy",
                @"EA GAMES\Ultima Online Samurai Empire\1.0", @"EA GAMES\Ultima Online Samurai Empire\1.00.0000",
                @"EA GAMES\Ultima Online: Samurai Empire\1.0", @"EA GAMES\Ultima Online: Samurai Empire\1.00.0000",
                @"EA Games\Ultima Online: Mondain's Legacy\1.0", @"EA Games\Ultima Online: Mondain's Legacy\1.00.0000",
                @"Origin Worlds Online\Ultima Online Samurai Empire BETA\2d\1.0",
                @"Origin Worlds Online\Ultima Online Samurai Empire BETA\3d\1.0",
                @"Origin Worlds Online\Ultima Online Samurai Empire\2d\1.0",
                @"Origin Worlds Online\Ultima Online Samurai Empire\3d\1.0"
            };

            KnownRegistryKeyValueNames = new[] { @"ExePath", @"InstallDir", @"Install Dir", @"GameExecutionPath" };

            Console.WriteLine("Searching for Ultima Online installations...");
            var paths = new List <string>();

            var dpCustom = typeof(DataPath).GetField("CustomPath", BindingFlags.NonPublic | BindingFlags.Static);

            if (dpCustom != null)
            {
                string custom = dpCustom.GetValue(null) as string;

                if (!String.IsNullOrWhiteSpace(custom) && !paths.Contains(custom))
                {
                    paths.Add(custom);
                }
            }

            var cache = IOUtility.EnsureFile(VitaNexCore.BaseDirectory + "/DataPath.bin");

            cache.Deserialize(
                r =>
            {
                var l = r.ReadArray(r.ReadString);

                paths.AddRange(
                    l.Not(paths.Contains).Where(path => File.Exists(IOUtility.GetSafeFilePath(path + "/client.exe", true))));
            });

            paths.AddRange(Locate().Not(paths.Contains));

            DetectedPaths = paths.ToArray();

            if (DetectedPaths.Length > 0)
            {
                Console.WriteLine("Found {0:#,0} Ultima Online installations:", DetectedPaths.Length);
                DetectedPaths.ForEach(Console.WriteLine);

                Core.DataDirectories.AddRange(DetectedPaths);
            }
            else
            {
                Console.WriteLine("Could not find any Ultima Online installations.");

                if (!Core.Service && Core.DataDirectories.Count == 0)
                {
                    int    attempt = 0;
                    string path    = IOUtility.GetSafeDirectoryPath(GetConsoleInput());

                    while (String.IsNullOrWhiteSpace(path) && attempt < 3)
                    {
                        path = IOUtility.GetSafeDirectoryPath(GetConsoleInput());

                        if (Directory.Exists(path))
                        {
                            break;
                        }

                        Console.WriteLine("The directory could not be found.");
                        path = null;
                        attempt++;
                    }

                    if (attempt < 3)
                    {
                        Core.DataDirectories.Add(path);
                    }
                }
            }

            cache.Serialize(w => w.WriteArray(Core.DataDirectories.ToArray(), w.Write));
        }
Beispiel #8
0
 public DataWriter(IOUtility iOUtility, DatasetManager datasetManager)
 {
     IOUtility      = iOUtility;
     DatasetManager = datasetManager;
 }
Beispiel #9
0
 public void Save(BinaryWriter bw)
 {
     IOUtility.WriteString(bw, this.id);
     IOUtility.WriteString(bw, this.title);
     IOUtility.WriteString(bw, this.description);
 }
Beispiel #10
0
        private void Init()
        {
            VitaNexCore.TryCatch(
                () =>
            {
                Status = CompileStatus.Initializing;

                if (!InputDirectory.Exists)
                {
                    Status        = CompileStatus.Aborted;
                    StatusMessage = "Input directory '" + InputDirectory + "' does not exist.";
                    return;
                }

                var infos = new List <FileInfo>();

                foreach (var file in FileMasks.SelectMany(
                             t => InputDirectory.GetFiles(t, SearchOption.AllDirectories).Where(file => !infos.Contains(file))))
                {
                    infos.Add(file);
                }

                var files = infos.ToArray();
                infos.Clear();

                if (files.Length == 0)
                {
                    Status        = CompileStatus.Aborted;
                    StatusMessage = "No files to compile.";
                    return;
                }

                var refs      = new List <string>();
                var fileNames = new List <string>();

                foreach (var fName in files.Select(t => t.FullName)
                         .Where(fName => !String.IsNullOrEmpty(fName))
                         .Where(fName => !fileNames.Contains(fName)))
                {
                    fileNames.Add(fName);
                }

                foreach (var t in DefaultReferences.Where(t => !String.IsNullOrEmpty(t)).Where(t => !refs.Contains(t)))
                {
                    refs.Add(t);
                }

                foreach (var t in References.Where(t => !String.IsNullOrEmpty(t)).Where(t => !refs.Contains(t)))
                {
                    refs.Add(t);
                }

                var configs = GetConfigFiles();

                if (configs != null)
                {
                    foreach (var t in configs.Select(GetConfigAssemblies)
                             .SelectMany(
                                 asm => asm.Where(t => !String.IsNullOrEmpty(t))
                                 .Where(t => File.Exists(IOUtility.GetSafeFilePath(IOUtility.GetBaseDirectory() + "/" + t, true)))
                                 .Where(t => !refs.Contains(t))))
                    {
                        refs.Add(t);
                    }
                }

                Status     = CompileStatus.Compiling;
                Parameters = new CompilerParameters(
                    refs.ToArray(),
                    IOUtility.GetUnusedFilePath(OutputDirectory.FullName, OutputFileName),
                    Debug)
                {
                    GenerateExecutable = false,
                    WarningLevel       = 4,
                    CompilerOptions    = String.Empty
                };

                foreach (var arg in Arguments)
                {
                    Parameters.CompilerOptions += arg + " ";
                }

                Results = Provider.CompileAssemblyFromFile(Parameters, fileNames.ToArray());

                if (Results.Errors.Count > 0)
                {
                    int errorCount = 0, warningCount = 0;

                    foreach (CompilerError e in Results.Errors)
                    {
                        if (e.IsWarning)
                        {
                            ++warningCount;
                        }
                        else
                        {
                            ++errorCount;
                        }
                    }

                    Errors = new string[Results.Errors.Count];

                    for (var e = 0; e < Results.Errors.Count; e++)
                    {
                        Errors[e] = String.Format(
                            "[{0}][{1}][{2}]: Line {3}, Column {4}\n{5}",
                            Results.Errors[e].IsWarning ? "Warning" : "Error",
                            Results.Errors[e].FileName,
                            Results.Errors[e].ErrorNumber,
                            Results.Errors[e].Line,
                            Results.Errors[e].Column,
                            Results.Errors[e].ErrorText);
                    }

                    StatusMessage = String.Format(
                        "Finished compiling with {0} error{1} and {2} warning{3}",
                        errorCount,
                        errorCount > 1 ? "s" : "",
                        warningCount,
                        warningCount > 1 ? "s" : "");

                    Status = CompileStatus.Completed;
                }
                else
                {
                    StatusMessage = "Finished compiling with no errors or warnings.";
                    Status        = CompileStatus.Completed;
                }
            },
                ex =>
            {
                Status        = CompileStatus.Aborted;
                StatusMessage = ex.Message;
            });

            if (CompiledCallback != null)
            {
                CompiledCallback(Results);
            }
        }
 static PokerPersistance()
 {
     _PersistenceFile = IOUtility.EnsureFile(VitaNexCore.SavesDirectory + "/ActionCams/Cameras.bin");
 }
Beispiel #12
0
        void CreationFunction(object parameter)
        {
            var tag = (string)parameter;

            creationProgressBarValue = 0;

            try
            {
                string sourcePath = VirtualFileSystem.Directories.Project;

                FileInfo[] allFiles = new DirectoryInfo(sourcePath).GetFiles("*.*", SearchOption.AllDirectories);

                long totalLength = 0;
                foreach (var fileInfo in allFiles)
                {
                    totalLength += fileInfo.Length;
                }

                foreach (string dirPath in Directory.GetDirectories(sourcePath, "*", SearchOption.AllDirectories))
                {
                    if (Directory.Exists(dirPath))
                    {
                        Directory.CreateDirectory(dirPath.Replace(sourcePath, creationDirectory));
                    }
                }

                long processedLength = 0;
                foreach (var fileInfo in allFiles)
                {
                    if (File.Exists(fileInfo.FullName))
                    {
                        File.Copy(fileInfo.FullName, fileInfo.FullName.Replace(sourcePath, creationDirectory), false);
                    }

                    processedLength         += fileInfo.Length;
                    creationProgressBarValue = (int)((double)processedLength / (double)totalLength * 100.0);
                    if (creationProgressBarValue > 100)
                    {
                        creationProgressBarValue = 100;
                    }

                    if (!creationInProgress)
                    {
                        return;
                    }
                }

                //if( tag == "Clean" )
                //{
                //	var directory = Path.Combine( creationDirectory, @"Project\Data\_Dev" );
                //	EditorMessageBox.ShowInfo( directory );
                //}

                //Public build
                if (tag == "PublicBuild" || tag == "PublicBuildEmpty")
                {
                    //delete files from root of Assets
                    {
                        var dataDirectory = Path.Combine(creationDirectory, @"Assets");
                        var info          = new DirectoryInfo(dataDirectory);
                        foreach (var file in info.GetFiles())
                        {
                            file.Delete();
                        }
                    }

                    //clear User settings
                    var path = Path.Combine(creationDirectory, @"User settings");
                    if (Directory.Exists(path))
                    {
                        IOUtility.ClearDirectory(path);
                    }

                    //delete _Dev
                    {
                        path = Path.Combine(creationDirectory, @"Assets\_Dev");
                        if (Directory.Exists(path))
                        {
                            Directory.Delete(path, true);
                        }
                    }

                    //delete Caches\Files\_Dev
                    {
                        path = Path.Combine(creationDirectory, @"Caches\Files\_Dev");
                        if (Directory.Exists(path))
                        {
                            Directory.Delete(path, true);
                        }
                    }

                    //delete Binaries\NeoAxis.Internal\Localization
                    path = Path.Combine(creationDirectory, @"Binaries\NeoAxis.Internal\Localization");
                    if (Directory.Exists(path))
                    {
                        Directory.Delete(path, true);
                    }

                    if (tag == "PublicBuildEmpty")
                    {
                        //delete _Tests
                        path = Path.Combine(creationDirectory, @"Assets\_Tests");
                        if (Directory.Exists(path))
                        {
                            Directory.Delete(path, true);
                        }

                        //delete Samples\Nature Demo
                        path = Path.Combine(creationDirectory, @"Assets\Samples\Nature Demo");
                        if (Directory.Exists(path))
                        {
                            Directory.Delete(path, true);
                        }

                        //delete Samples\Sci-fi Demo
                        path = Path.Combine(creationDirectory, @"Assets\Samples\Sci-fi Demo");
                        if (Directory.Exists(path))
                        {
                            Directory.Delete(path, true);
                        }

                        ////delete Samples
                        //path = Path.Combine( creationDirectory, @"Assets\Samples" );
                        //if( Directory.Exists( path ) )
                        //	Directory.Delete( path, true );

                        //delete Caches\Files\_Tests
                        path = Path.Combine(creationDirectory, @"Caches\Files\_Tests");
                        if (Directory.Exists(path))
                        {
                            Directory.Delete(path, true);
                        }

                        //delete Caches\Files\Samples\Sci-fi Demo
                        path = Path.Combine(creationDirectory, @"Caches\Files\Samples\Sci-fi Demo");
                        if (Directory.Exists(path))
                        {
                            Directory.Delete(path, true);
                        }

                        ////delete Caches\Files
                        //path = Path.Combine( creationDirectory, @"Caches\Files" );
                        //if( Directory.Exists( path ) )
                        //	Directory.Delete( path, true );

                        //fix EditorDockingDefault.config
                        try
                        {
                            File.Copy(
                                Path.Combine(sourcePath, @"Assets\Base\Tools\EditorDockingDefault_Empty.config"),
                                Path.Combine(creationDirectory, @"Assets\Base\Tools\EditorDockingDefault.config"), true);
                        }
                        catch { }

                        ////fix Project.csproj
                        //try
                        //{
                        //	var fileName = Path.Combine( creationDirectory, "Project.csproj" );

                        //	var newLines = new List<string>();
                        //	foreach( var line in File.ReadAllLines( fileName ) )
                        //	{
                        //		if( !line.Contains( @"Assets\Samples\" ) )
                        //			newLines.Add( line );
                        //	}

                        //	File.WriteAllLines( fileName, newLines );
                        //}
                        //catch { }
                    }

                    //delete EditorDockingDefault_Empty.config
                    try
                    {
                        File.Delete(Path.Combine(creationDirectory, @"Assets\Base\Tools\EditorDockingDefault_Empty.config"));
                    }
                    catch { }

                    //delete NeoAxis.DeveloperBuild.config
                    path = Path.Combine(creationDirectory, @"NeoAxis.DeveloperBuild.config");
                    if (File.Exists(path))
                    {
                        File.Delete(path);
                    }

                    //delete obj folders
                    foreach (string dirPath in Directory.GetDirectories(creationDirectory, "obj", SearchOption.AllDirectories))
                    {
                        if (Directory.Exists(dirPath))
                        {
                            Directory.Delete(dirPath, true);
                        }
                    }

                    //delete .vs folders
                    foreach (string dirPath in Directory.GetDirectories(creationDirectory, ".vs", SearchOption.AllDirectories))
                    {
                        if (Directory.Exists(dirPath))
                        {
                            Directory.Delete(dirPath, true);
                        }
                    }

                    //rewrite ProjectSettings.component
                    {
                        var content  = @".component NeoAxis.Component_ProjectSettings
{
	Name = All

	.component NeoAxis.Component_ProjectSettings_PageBasic
	{
		Name = General
	}
	.component NeoAxis.Component_ProjectSettings_PageBasic
	{
		Name = Scene Editor
	}
	.component NeoAxis.Component_ProjectSettings_PageBasic
	{
		Name = UI Editor
	}
	.component NeoAxis.Component_ProjectSettings_PageBasic
	{
		Name = C# Editor
	}
	.component NeoAxis.Component_ProjectSettings_PageBasic
	{
		Name = Shader Editor
	}
	.component NeoAxis.Component_ProjectSettings_PageBasic
	{
		Name = Text Editor
	}
	.component NeoAxis.Component_ProjectSettings_PageBasic
	{
		Name = Ribbon and Toolbar
	}
	.component NeoAxis.Component_ProjectSettings_PageBasic
	{
		Name = Shortcuts
	}
	.component NeoAxis.Component_ProjectSettings_PageBasic
	{
		Name = Custom Splash Screen
	}
}";
                        var fileName = Path.Combine(creationDirectory, @"Assets\Base\ProjectSettings.component");
                        File.WriteAllText(fileName, content);
                    }

                    //make zip archive
                    {
                        var fileName = tag == "PublicBuild" ? "Default project with Starter Content, Sci-fi Demo, Nature Demo, Test scenes.zip" : "Default project with Starter Content.zip";
                        //var fileName = tag == "PublicBuild" ? "Default project with sample content.zip" : "Empty project.zip";
                        var zipfileName = Path.Combine(creationDirectory, fileName);

                        //can't write zip file to same folder. using temp file.
                        var tempFileName = Path.GetTempPath() + Guid.NewGuid().ToString() + ".zip";
                        ZipFile.CreateFromDirectory(creationDirectory, tempFileName, CompressionLevel.Optimal, false);
                        File.Copy(tempFileName, zipfileName);
                        File.Delete(tempFileName);

                        //ZipFile.CreateFromDirectory( creationDirectory, zipfileName, CompressionLevel.Optimal, false );
                    }
                }

                creationProgressBarValue = 100;

                //open folder
                try
                {
                    Win32Utility.ShellExecuteEx(null, creationDirectory);
                    //Process.Start( "explorer.exe", creationDirectory );
                }
                catch { }

                ////run process
                //string executableFileName = Path.Combine( creationDirectory, "NeoAxis.Studio.exe" );
                //var runMapProcess = Process.Start( executableFileName, "" );

                //end
                creationInProgress = false;

                ScreenNotifications.Show(Translate("The project was created successfully."));
            }
            catch (Exception ex)
            {
                EditorMessageBox.ShowWarning(ex.Message);
            }
        }
Beispiel #13
0
        public void CreateDirectory(string dir)
        {
            var physicalPath = Path.Combine(this.storagePath, dir);

            IOUtility.EnsureDirectoryExists(physicalPath);
        }
Beispiel #14
0
        public void DeleteDirectory(string dir)
        {
            string fullPath = Path.Combine(this.storagePath, dir);

            IOUtility.DeleteDirectory(fullPath, true);
        }
        public static void Import(string[] fileNames, string destRealFolder)          //Initial )
        {
            try
            {
                if (!Directory.Exists(destRealFolder))
                {
                    Directory.CreateDirectory(destRealFolder);
                }
            }
            catch (Exception e)
            {
                EditorMessageBox.ShowWarning(e.Message);
                return;
            }

            ////check files inside project Data folder
            //{
            //	foreach( var fileName in fileNames )
            //	{
            //		var virtualPath = VirtualPathUtils.GetVirtualPathByReal( fileName );
            //		if( !string.IsNullOrEmpty( virtualPath ) )
            //		{
            //			Log.Warning( "Unable to import from project \'Data\' folder. The file already inside the project." );
            //			return;
            //		}
            //	}
            //}

            //processing

            //!!!!пока просто копирование
            //нужно зависимые скопировать
            //также может какую-то обработку делать

            ////select folder if exists files outside Assets folder
            //string destRealFolder = "";
            //{
            //	var existsOutside = fileNames.Any( fileName => string.IsNullOrEmpty( VirtualPathUtility.GetVirtualPathByReal( fileName ) ) );
            //	if( existsOutside )
            //	{
            //		if( string.IsNullOrEmpty( destRealFolderInitial ) )
            //		{
            //			again:;
            //			destRealFolder = VirtualPathUtility.GetRealPathByVirtual( "Import" );
            //			if( !Directory.Exists( destRealFolder ) )
            //				destRealFolder = VirtualPathUtility.GetRealPathByVirtual( "" );

            //			CommonOpenFileDialog dialog = new CommonOpenFileDialog();
            //			dialog.InitialDirectory = destRealFolder;
            //			dialog.IsFolderPicker = true;
            //			if( dialog.ShowDialog() == CommonFileDialogResult.Ok )
            //			{
            //				destRealFolder = dialog.FileName;

            //				if( !VirtualPathUtility.GetVirtualPathByReal( destRealFolder, out _ ) )
            //				{
            //					EditorMessageBox.ShowWarning( "Need select folder inside Assets folder." );
            //					//Log.Warning( "Need select folder inside Data folder." );
            //					goto again;
            //				}
            //			}
            //		}
            //		else
            //			destRealFolder = destRealFolderInitial;
            //	}
            //}

            List <string> fileNamesToSelect = new List <string>();

            foreach (var fileName in fileNames)
            {
                var virtualPath = VirtualPathUtility.GetVirtualPathByReal(fileName);
                if (!string.IsNullOrEmpty(virtualPath))
                {
                    //already inside Data folder
                    fileNamesToSelect.Add(fileName);
                }
                else
                {
                    //copy to Data folder

                    string destinationFileName;
                    try
                    {
                        destinationFileName = Path.Combine(destRealFolder, Path.GetFileName(fileName));

                        if (Directory.Exists(fileName))
                        {
                            IOUtility.CopyDirectory(fileName, destinationFileName);
                        }
                        else
                        {
                            File.Copy(fileName, destinationFileName);
                        }
                    }
                    catch (Exception e)
                    {
                        EditorMessageBox.ShowWarning(e.Message);
                        //Log.Warning( e.Message );
                        return;
                    }

                    fileNamesToSelect.Add(destinationFileName);
                }
            }

            //select new files
            EditorAPI.SelectFilesOrDirectoriesInMainResourcesWindow(fileNamesToSelect.ToArray());
            EditorAPI.SelectDockWindow(EditorAPI.FindWindow <ResourcesWindow>());
        }
 public static void WriteProjectReadMe(SnippetDirectory[] snippetDirectories, string directoryPath)
 {
     IOUtility.WriteAllText(
         Path.Combine(directoryPath, "README.md"),
         GenerateProjectReadMe(snippetDirectories));
 }
Beispiel #17
0
        private static string GetJSON(bool forceUpdate)
        {
            if (!UpdateStats(forceUpdate))
            {
                return(JSONResponse);
            }

            var values    = new Dictionary <string, SimpleType>();
            var subValues = new List <string>();

            string serverObject  = "\"server\": { }";
            string statsObject   = "\"stats\": { }";
            string playersObject = "\"players\": [ ]";
            string guildsObject  = "\"guilds\": [ ]";

            if (CMOptions.DisplayServer)
            {
                values.Clear();

                values.Add("name", ServerList.ServerName);

                IPEndPoint ipep =
                    Server.Network.Listener.EndPoints.FirstOrDefault(
                        ip =>
                        ip.Address.ToString() != "0.0.0.0" && ip.Address.ToString() != "127.0.0.1" &&
                        !ip.Address.ToString().StartsWith("192.168"));

                if (ipep != null)
                {
                    values.Add("host", ipep.Address.ToString());
                    values.Add("port", ipep.Port);
                }

                values.Add("framework", Environment.OSVersion.VersionString);

                serverObject = JSON.EncodeObject("server", values);
            }

            if (CMOptions.DisplayStats)
            {
                values.Clear();

                Stats.ForEach((k, v) => values.Add(k, v.Data));

                statsObject = JSON.EncodeObject("stats", values);
            }

            if (CMOptions.DisplayPlayers)
            {
                var playerObjects = new List <string>(Snapshot.Sum(kv => kv.Value.Count));

                Snapshot.ForEach(
                    (ip, states) => states.ForEach(
                        ns =>
                {
                    values.Clear();

                    Mobile m = ns.Mobile;

                    values.Add("id", m.Serial.Value);
                    values.Add("name", m.RawName ?? String.Empty);
                    values.Add("title", m.Title ?? String.Empty);
                    values.Add("profile", m.Profile ?? String.Empty);
                    values.Add("guild_id", m.Guild != null ? m.Guild.Id : -1);
                    values.Add("guild_abbr", m.Guild != null ? m.Guild.Abbreviation ?? String.Empty : String.Empty);

                    string jsonInfo = JSON.EncodeObject("info", values);

                    string jsonStats = "\"stats\": [ ]";

                    if (CMOptions.DisplayPlayerStats)
                    {
                        values.Clear();

                        values.Add("str", m.Str);
                        values.Add("str_raw", m.RawStr);

                        values.Add("dex", m.Dex);
                        values.Add("dex_raw", m.RawDex);

                        values.Add("int", m.Int);
                        values.Add("int_raw", m.RawInt);

                        values.Add("hits", m.Hits);
                        values.Add("hits_max", m.HitsMax);

                        values.Add("stam", m.Stam);
                        values.Add("stam_max", m.StamMax);

                        values.Add("mana", m.Mana);
                        values.Add("mana_max", m.ManaMax);

                        jsonStats = JSON.EncodeObject("stats", values);
                    }

                    string jsonSkills = "\"skills\": [ ]";

                    if (CMOptions.DisplayPlayerSkills)
                    {
                        subValues.Clear();

                        foreach (Skill skill in m.Skills)
                        {
                            values.Clear();

                            values.Add("id", skill.SkillID);
                            values.Add("name", skill.Name);
                            values.Add("base", skill.Base);
                            values.Add("value", skill.Value);
                            values.Add("cap", skill.Cap);

                            subValues.Add(JSON.EncodeObject(values));
                        }

                        jsonSkills = JSON.FormatArray("skills", subValues);
                    }

                    string jsonEquip = "\"equip\": [ ]";

                    if (CMOptions.DisplayPlayerEquip)
                    {
                        subValues.Clear();

                        foreach (Item item in m.Items.Where(i => i.Parent == m))
                        {
                            values.Clear();

                            values.Add("id", item.Serial.Value);
                            values.Add("type", item.GetType().Name);
                            values.Add("layer", (int)item.Layer);
                            values.Add("art", item.ItemID);
                            values.Add("hue", item.Hue);
                            values.Add("name", item.ResolveName());

                            subValues.Add(JSON.EncodeObject(values));
                        }

                        jsonEquip = JSON.FormatArray("equip", subValues);
                    }

                    playerObjects.Add(String.Format("{{ {0} }}", String.Join(", ", jsonInfo, jsonStats, jsonSkills, jsonEquip)));
                }));

                playersObject = JSON.FormatArray("players", playerObjects);
            }

            if (CMOptions.DisplayGuilds)
            {
                var guildObjects = new List <string>(BaseGuild.List.Count);

                BaseGuild.List.ForEach(
                    (id, bg) =>
                {
                    values.Clear();

                    values.Add("id", bg.Id);
                    values.Add("name", bg.Name);
                    values.Add("abbr", bg.Abbreviation);
                    values.Add("type", bg.Type.ToString());
                    values.Add("disbanded", bg.Disbanded);

                    string jsonInfo    = "\"info\": { }";
                    string jsonMembers = "\"members\": [ ]";
                    string jsonAllies  = "\"allies\": [ ]";
                    string jsonEnemies = "\"enemies\": [ ]";

                    if (bg is Guild)
                    {
                        var g = (Guild)bg;

                        values.Add("leader_id", g.Leader != null ? g.Leader.Serial.Value : -1);
                        values.Add("leader_name", g.Leader != null ? g.Leader.RawName : String.Empty);
                        values.Add("charter", g.Charter ?? String.Empty);
                        values.Add("website", g.Website ?? String.Empty);

                        jsonInfo = JSON.EncodeObject("info", values);

                        subValues.Clear();

                        foreach (Mobile m in g.Members)
                        {
                            values.Clear();

                            values.Add("id", m.Serial.Value);
                            values.Add("name", m.RawName ?? String.Empty);
                            values.Add("title", m.Title ?? String.Empty);

                            subValues.Add(JSON.EncodeObject(values));
                        }

                        jsonMembers = JSON.FormatArray("members", subValues);

                        subValues.Clear();

                        foreach (Guild ally in g.Allies)
                        {
                            values.Clear();

                            values.Add("id", ally.Id);
                            values.Add("abbr", ally.Abbreviation ?? String.Empty);
                            values.Add("name", ally.Name ?? String.Empty);

                            subValues.Add(JSON.EncodeObject(values));
                        }

                        jsonAllies = JSON.FormatArray("allies", subValues);

                        subValues.Clear();

                        foreach (Guild enemy in g.Enemies)
                        {
                            values.Clear();

                            values.Add("id", enemy.Id);
                            values.Add("abbr", enemy.Abbreviation ?? String.Empty);
                            values.Add("name", enemy.Name ?? String.Empty);

                            subValues.Add(JSON.EncodeObject(values));
                        }

                        jsonEnemies = JSON.FormatArray("enemies", subValues);
                    }

                    guildObjects.Add(String.Format("{{ {0} }}", String.Join(", ", jsonInfo, jsonMembers, jsonAllies, jsonEnemies)));
                });

                guildsObject = JSON.FormatArray("guilds", guildObjects);
            }

            string vncVersion = String.Format("\"vnc_version\": {0}", JSON.Encode(VitaNexCore.Version.Value));
            string modVersion = String.Format("\"mod_version\": {0}", JSON.Encode(CMOptions.ModuleVersion));

            JSONResponse = String.Format(
                "{{ {0} }}", String.Join(", ", vncVersion, modVersion, serverObject, statsObject, playersObject, guildsObject));

            File.WriteAllText(
                IOUtility.GetSafeFilePath(VitaNexCore.DataDirectory + "/WebStats.json", true), JSONResponse, Encoding.UTF8);

            return(JSONResponse);
        }
Beispiel #18
0
        public MapLoader(Stream file)
        {
            Console.WriteLine("### Opening map: " + ((BigStream)file).Name);
            BinaryReader binaryReader = new BinaryReader(file);
            uint         flag         = binaryReader.ReadUInt32();

            switch (flag)
            {
            case 1884121923U:
                Console.WriteLine("### Map is in uncompressed format");
                break;

            case 5390661U:
                Console.WriteLine("### Map is in compressed RefPack format, decompressing...");

                BinaryWriter output = new BinaryWriter((Stream) new MemoryStream((int)binaryReader.BaseStream.Length));
                binaryReader.BaseStream.Position = 8L;
                IOUtility.DecompressData(binaryReader, output);
                binaryReader = new BinaryReader(output.BaseStream);
                byte[] numArray = new byte[(int)output.BaseStream.Length];
                output.BaseStream.Position = 0L;
                output.BaseStream.Read(numArray, 0, (int)output.BaseStream.Length);
                File.WriteAllBytes("decompressed.map", numArray);
                binaryReader.BaseStream.Position = 4L;

                break;

            default:
                Console.WriteLine("### Unknow map format, not supported");
                return;
            }

            Map map = new Map();

            SubAsset.map = map;
            Asset.map    = map;

            binaryReader.BaseStream.Position = 4L;
            string[] assetStrings = new string[binaryReader.ReadInt32()];
            map.nameIDs     = new Dictionary <string, int>(assetStrings.Length);
            map.majorAssets = new Dictionary <string, MajorAsset>();
            StreamWriter streamWriter1 = new StreamWriter("assetStrings.txt");

            for (int index = assetStrings.Length - 1; index >= 0; --index)
            {
                assetStrings[index] = binaryReader.ReadString();
                streamWriter1.WriteLine("{0,-20}\t{1}", (object)assetStrings[index], (object)(index + 1));
                //Console.WriteLine(assetStrings[index]);
                int num = binaryReader.ReadInt32();
                if (num != index + 1)
                {
                    Console.WriteLine("!\t string suffix {0} mismatch with index {1}", (object)num, (object)(index + 1));
                }
            }
            streamWriter1.Close();
            SubAsset.assetNames = assetStrings;
            StreamWriter streamWriter2 = new StreamWriter("majorAssetStrings.txt");
            long         position      = binaryReader.BaseStream.Position;

            while (binaryReader.BaseStream.Position < binaryReader.BaseStream.Length)
            {
                int    num1 = binaryReader.ReadInt32();
                short  num2 = binaryReader.ReadInt16();
                int    num3 = binaryReader.ReadInt32();
                string key  = assetStrings[num1 - 1];
                binaryReader.BaseStream.Position -= 10L;
                streamWriter2.WriteLine("{0,-20}\t{1,-6}\t{2,-3}\t{3}", (object)key, (object)num3, (object)num1, (object)num2);
                File.WriteAllBytes(assetStrings[num1 - 1] + ".bin", binaryReader.ReadBytes(num3 + 10));
                binaryReader.BaseStream.Position -= (long)(num3 + 10);
                switch (key)
                {
                case "AssetList":
                    Console.WriteLine("AssetList");
                    map.majorAssets.Add(key, (MajorAsset)(map.assetList = new AssetList(binaryReader)));
                    continue;

                case "GlobalVersion":
                    Console.WriteLine("GlobalVersion");
                    map.majorAssets.Add(key, (MajorAsset) new GlobalVersion(binaryReader));
                    continue;

                case "HeightMapData":
                    Console.WriteLine("HeigthMapData");
                    map.heightMap = new HeightMapData(binaryReader);
                    map.majorAssets.Add(key, (MajorAsset)map.heightMap);
                    map.mapWidth  = map.heightMap.mapWidth;
                    map.mapHeight = map.heightMap.mapHeight;
                    continue;

                /*
                 * case "BlendTileData":
                 *  Console.WriteLine("BlendTileData");
                 *  map.blendTile = new BlendTileData(binaryReader, map.mapWidth, map.mapHeight);
                 *  map.majorAssets.Add(key, (MajorAsset)map.blendTile);
                 *  continue;
                 * case "WorldInfo":
                 *  Console.WriteLine("WorldInfo");
                 *  map.worldInfo = new WorldInfo(binaryReader, assetStrings);
                 *  map.majorAssets.Add(key, (MajorAsset)map.worldInfo);
                 *  continue;
                 * case "MPPositionList":
                 *  Console.WriteLine("MPPositionList");
                 *  map.mpPositionList = new MPPositionList(binaryReader);
                 *  map.majorAssets.Add(key, (MajorAsset)map.mpPositionList);
                 *  continue;
                 * case "SidesList":
                 *  Console.WriteLine("SidesList");
                 *  map.sidesList = new SidesList(binaryReader);
                 *  map.majorAssets.Add(key, (MajorAsset)map.sidesList);
                 *  continue;
                 * case "LibraryMapLists":
                 *  Console.WriteLine("LibraryMapLists");
                 *  map.majorAssets.Add(key, (MajorAsset)new LibraryMapLists(binaryReader));
                 *  continue;
                 * case "Teams":
                 *  Console.WriteLine("Teams");
                 *  map.majorAssets.Add(key, (MajorAsset)new Teams(binaryReader));
                 *  continue;
                 * case "PlayerScriptsList":
                 *  Console.WriteLine("PlayerScriptsList");
                 *  map.majorAssets.Add(key, (MajorAsset)new PlayerScriptsList(binaryReader));
                 *  continue;
                 * case "BuildLists":
                 *  Console.WriteLine("BuildLists");
                 *  map.majorAssets.Add(key, (MajorAsset)new BuildLists(binaryReader));
                 *  continue;
                 * case "ObjectsList":
                 *  Console.WriteLine("ObjectList");
                 *  map.objectList = new ObjectsList(binaryReader);
                 *  map.majorAssets.Add(key, (MajorAsset)map.objectList);
                 *  continue;
                 * case "TriggerAreas":
                 *  Console.WriteLine("TriggerAreas");
                 *  map.majorAssets.Add(key, (MajorAsset)new TriggerAreas(binaryReader));
                 *  continue;
                 * case "GlobalWaterSettings":
                 *  Console.WriteLine("GlobalWaterSettings");
                 *  map.majorAssets.Add(key, (MajorAsset)new GlobalWaterSettings(binaryReader));
                 *  continue;
                 * case "FogSettings":
                 *  Console.WriteLine("FogSettings");
                 *  map.majorAssets.Add(key, (MajorAsset)new FogSettings(binaryReader));
                 *  continue;
                 * case "MissionHotSpots":
                 *  Console.WriteLine("MissionHotSpots");
                 *  map.majorAssets.Add(key, (MajorAsset)new MissionHotSpots(binaryReader));
                 *  continue;
                 * case "MissionObjectives":
                 *  Console.WriteLine("MissionObjectives");
                 *  map.majorAssets.Add(key, (MajorAsset)new MissionObjectives(binaryReader));
                 *  continue;
                 * case "StandingWaterAreas":
                 *  Console.WriteLine("StandingWaterAreas");
                 *  map.majorAssets.Add(key, (MajorAsset)new StandingWaterAreas(binaryReader));
                 *  continue;
                 * case "RiverAreas":
                 *  Console.WriteLine("RiverAreas");
                 *  map.majorAssets.Add(key, (MajorAsset)new RiverAreas(binaryReader));
                 *  continue;
                 * case "StandingWaveAreas":
                 *  Console.WriteLine("StandingWaveAreas");
                 *  map.majorAssets.Add(key, (MajorAsset)new StandingWaveAreas(binaryReader));
                 *  continue;
                 * case "GlobalLighting":
                 *  Console.WriteLine("GlobalLighting");
                 *  map.majorAssets.Add(key, (MajorAsset)new GlobalLighting(binaryReader));
                 *  continue;
                 * case "PostEffectsChunk":
                 *  Console.WriteLine("PostEffectsChunk");
                 *  map.majorAssets.Add(key, (MajorAsset)new PostEffectsChunk(binaryReader));
                 *  continue;
                 * case "EnvironmentData":
                 *  Console.WriteLine("EnvironmentData");
                 *  map.majorAssets.Add(key, (MajorAsset)new EnvironmentData(binaryReader));
                 *  continue;
                 * case "NamedCameras":
                 *  Console.WriteLine("NamedCameras");
                 *  map.majorAssets.Add(key, (MajorAsset)new NamedCameras(binaryReader));
                 *  continue;
                 * case "CameraAnimationList":
                 *  Console.WriteLine("CameraAnimationList");
                 *  map.majorAssets.Add(key, (MajorAsset)new CameraAnimationList(binaryReader));
                 *  continue;
                 * case "WaypointsList":
                 *  Console.WriteLine("WaypointsList");
                 *  map.majorAssets.Add(key, (MajorAsset)new WaypointsList(binaryReader));
                 *  continue;
                 */
                default:
                    Console.WriteLine("*\t Asset: {0} not parsed, error occurred, ending parsing", (object)key);
                    binaryReader.BaseStream.Position = binaryReader.BaseStream.Length;
                    continue;
                }
            }
            streamWriter2.Close();
            StreamWriter streamWriter3 = new StreamWriter("parsed assetStrings.txt");

            foreach (KeyValuePair <string, int> keyValuePair in map.nameIDs)
            {
                streamWriter3.WriteLine("{0,-20}\t{1}", (object)keyValuePair.Key, (object)keyValuePair.Value);
            }
            streamWriter3.Close();
            //map.mapWidth = map.heightMap.mapWidth;
            //map.mapHeight = map.heightMap.mapHeight;
            //map.mapBorder = map.heightMap.borderWidth;
            //map.PlayerCount = map.objectList.StartingLocationsCount;
            binaryReader.Close();
            file.Close();
            //Console.WriteLine("\t Map exported to \"{0}.bin\"", (object)Path.GetFileNameWithoutExtension(file));
            Console.WriteLine("*\t Done parsing \"{0}\"", (object)file);
        }
Beispiel #19
0
 public MissionHotSpot(BinaryReader br)
 {
     this.id          = IOUtility.ReadString(br);
     this.title       = IOUtility.ReadString(br);
     this.description = IOUtility.ReadString(br);
 }
Beispiel #20
0
        /// <summary>
        /// 检测Excel key 是否合法
        /// </summary>
        private void CheckExcelLocalizationKey()
        {
            if (mLocalizationExcelData == null)
            {
                mIsFormatEnable = false;
                return;
            }
            DataTable dataTable = mLocalizationExcelData.Tables[0];

            if (dataTable.Rows.Count < 2)
            {
                mIsFormatEnable = false;
                Debug.LogError("当前读取的表中不包含任何数据" + dataTable.TableName);
                return;
            }

            mIsFormatEnable = true;
            #region 获取一共有多少列数据
            int Column = 1;
            for (int dex = StartRow; dex < dataTable.Rows[0].ItemArray.Length; dex++)
            {
                var column = dataTable.Rows[0].ItemArray[dex];
                if (string.IsNullOrEmpty(column.ToString()))
                {
                    break;
                }
                ++Column;
            }
            Debug.Log(string.Format("一共有{0} 列有效的列", Column));
            #endregion


            StringBuilder            stringBuilder = new StringBuilder();
            Dictionary <string, int> allKeyRecords = new Dictionary <string, int>();

            for (int row = 2; row < dataTable.Rows.Count; ++row)
            {
                string key = dataTable.Rows[row][0].ToString(); //每一行的第一列为本地化的key

                if (string.IsNullOrEmpty(key))
                {
                    mIsFormatEnable = false;
                    stringBuilder.Append(string.Format("Row={0}  Key 为null", row));
                    stringBuilder.Append(System.Environment.NewLine);
                    continue;
                }

                if (allKeyRecords.ContainsKey(key))
                {
                    mIsFormatEnable = false;
                    stringBuilder.Append(string.Format("Row={0}  Key={1} 重复的key", row + (StartRow - 1), key));
                    stringBuilder.Append(System.Environment.NewLine);
                    continue;
                }
                else
                {
                    allKeyRecords[key] = row;
                }

                if (Regex.IsMatch(key, s_LocalizationKeyReg, RegexOptions.Singleline) == false)
                {
                    mIsFormatEnable = false;

                    stringBuilder.Append(string.Format("Row={0}  Key={1} 格式错误", row, key));
                    stringBuilder.Append(System.Environment.NewLine);
                    continue;
                }
            }

            if (mIsFormatEnable == false)
            {
                string content         = stringBuilder.ToString();
                string errorFormatPath = Application.dataPath.CombinePathEx(ConstDefine.S_EditorName).CombinePathEx("localizationErrorFormat.txt");
                IOUtility.CreateOrSetFileContent(errorFormatPath, content, false);
                Debug.LogInfor("Excel 中部分Key 格式错误,已经输出保存到文件" + errorFormatPath);
                return;
            }
            Debug.LogEditorInfor("本地化语言表Excel 格式正确,可以导出");
        }
Beispiel #21
0
 public DataWriter(IOUtility iOUtility) : this(iOUtility, new DatasetManager())
 {
 }
Beispiel #22
0
        protected override void onGUIHeader()
        {
            GUI.Label(headerRect, Title, titleStyle);

            // Portrait
            if (_node.Portrait != null)
            {
                // Get the portrait texture, if it's changed.
                if (_portraitName != _node.Portrait.name)
                {
                    string   spriteSheet = AssetDatabase.GetAssetPath(_node.Portrait);
                    Sprite[] sprites     = AssetDatabase.LoadAllAssetsAtPath(spriteSheet).OfType <Sprite>().ToArray();

                    if (sprites.Length == 1)
                    {
                        _portrait = _node.Portrait.texture;
                    }
                    else
                    {
                        var path     = IOUtility.GetPath(_node.Portrait);
                        var importer = (TextureImporter)TextureImporter.GetAtPath(path);
                        if (importer.isReadable)
                        {
                            _portrait = new Texture2D((int)_node.Portrait.rect.width, (int)_node.Portrait.rect.height);
                            var pixels = _node.Portrait.texture.GetPixels((int)_node.Portrait.textureRect.x,
                                                                          (int)_node.Portrait.textureRect.y,
                                                                          (int)_node.Portrait.textureRect.width,
                                                                          (int)_node.Portrait.textureRect.height);
                            _portrait.SetPixels(pixels);
                            _portrait.Apply();
                        }
                        else
                        {
                            _portrait = _node.Portrait.texture;
                        }
                    }

                    _portraitName = _node.Portrait.name;
                }

                Rect r = new Rect(headerRect.x - 30, headerRect.y - 30, 60, 60);
                GUI.Label(r, _portrait);
            }

            // Actor Name
            if (_node.ActorName != "")
            {
                GUIContent label = new GUIContent(_node.ActorName);
                Vector2    size  = _actorNameStyle.CalcSize(label);
                Color      c     = headerColor; c.a = .5f;

                float xPos = headerRect.x;
                if (_node.Portrait != null)
                {
                    xPos += 30;
                }

                Rect r = new Rect(xPos + 5, headerRect.y - size.y - 10, size.x + 10, size.y + 5);
                EditorGUI.DrawRect(r, c);
                GUI.Label(r, label, _actorNameStyle);
            }

            float x = headerRect.x + headerRect.width - 5;
            float y = headerRect.y + (headerRect.height - 20) / 2;


            // Audio Clip
            if (_node.Audio != null)
            {
                GUI.Label(new Rect(x - 20, y, 20, 20), EditorGUIUtility.IconContent("SceneviewAudio"));
                x -= 30;
            }

            // Custom Camera
            if (_node.CustomCameraEnable)
            {
                GUI.Label(new Rect(x - 20, y - 3, 40, 20), new GUIContent(_node.CameraIndex.ToString(), EditorGUIUtility.IconContent("Camera Icon").image), textStyle);
            }
        }
        public Maybe <ILineNode> Execute(EAParser parse, Token self, IList <IParamNode> parameters, MergeableGenerator <Token> tokens)
        {
            ExecTimer.Timer.AddTimingPoint(ExecTimer.KEY_GENERIC);

            Maybe <string> validFile = FileSearcher.FindFile(Path.GetDirectoryName(self.FileName), IOUtility.GetToolFileName(parameters[0].ToString()));

            if (validFile.IsNothing)
            {
                parse.Error(parameters[0].MyLocation, "Tool " + parameters[0].ToString() + " not found.");
                return(new Nothing <ILineNode>());
            }

            //from http://stackoverflow.com/a/206347/1644720
            // Start the child process.
            System.Diagnostics.Process p = new System.Diagnostics.Process();
            p.StartInfo.RedirectStandardError = true;
            // Redirect the output stream of the child process.
            p.StartInfo.WorkingDirectory       = Path.GetDirectoryName(self.FileName);
            p.StartInfo.UseShellExecute        = false;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.CreateNoWindow         = true;
            p.StartInfo.FileName = validFile.FromJust;
            StringBuilder argumentBuilder = new StringBuilder();

            for (int i = 1; i < parameters.Count; i++)
            {
                parameters[i].AsAtom().IfJust((IAtomNode n) => { parameters[i] = n.Simplify(); });
                argumentBuilder.Append(parameters[i].PrettyPrint());
                argumentBuilder.Append(' ');
            }
            argumentBuilder.Append("--to-stdout");
            p.StartInfo.Arguments = argumentBuilder.ToString();
            p.Start();
            // Do not wait for the child process to exit before
            // reading to the end of its redirected stream.
            // p.WaitForExit();
            // Read the output stream first and then wait.
            MemoryStream outputBytes = new MemoryStream();
            MemoryStream errorStream = new MemoryStream();

            p.StandardOutput.BaseStream.CopyTo(outputBytes);
            p.StandardError.BaseStream.CopyTo(errorStream);
            p.WaitForExit();

            byte[] output = outputBytes.GetBuffer().Take((int)outputBytes.Length).ToArray();
            if (errorStream.Length > 0)
            {
                parse.Error(self.Location, Encoding.ASCII.GetString(errorStream.GetBuffer().Take((int)errorStream.Length).ToArray()));
            }
            else if (output.Length >= 7 && Encoding.ASCII.GetString(output.Take(7).ToArray()) == "ERROR: ")
            {
                parse.Error(self.Location, Encoding.ASCII.GetString(output.Skip(7).ToArray()));
            }
            else
            {
                outputBytes.Position = 0; //Reset MemoryStream position so StreamReader starts reading from beginning.
                Tokenizer t = new Tokenizer();
                tokens.PrependEnumerator(t.Tokenize(outputBytes, Path.GetFileName(self.FileName) + ", Line " + self.LineNumber + "; " + parameters[0].ToString()).GetEnumerator());
            }

            ExecTimer.Timer.AddTimingPoint(parameters[0].ToString().ToLower());

            return(new Nothing <ILineNode>());
        }
Beispiel #24
0
        public static void BackupState(PlayerMobile m, bool logging, out int count, out int fails)
        {
            var root = VitaNexCore.DataDirectory + "/PlayerBackup/" + m.Account.Username + "/" + m.Serial;

            var idxFile = IOUtility.EnsureFile(root + ".idx", true);
            var binFile = IOUtility.EnsureFile(root + ".bin", true);

            var logFile = logging ? IOUtility.EnsureFile(root + ".log") : null;
            var log     = logging ? new StringBuilder() : null;

            if (log != null)
            {
                log.AppendLine();
                log.AppendLine(new String('*', 10));
                log.AppendLine();
                log.AppendLine("BACKUP:\tDate[{0}]\tMobile[{1}]", DateTime.UtcNow, m);
                log.AppendLine();
            }

            var idxlen   = 0L;
            var idxCount = 0;
            var idxFails = 0;

            idxFile.Serialize(
                idx =>
            {
                idx.SetVersion(0);

                idx.Write(m.Serial.Value);

                WriteLength(idx, false, idxlen, idxCount);

                binFile.Serialize(
                    bin =>
                {
                    bin.SetVersion(0);

                    var items = m.FindItemsByType <Item>(true, i => i != null && !i.Deleted);

                    foreach (var item in items)
                    {
#if NEWPARENT
                        var parent    = item.Parent != null ? item.Parent.Serial : Serial.MinusOne;
                        var logParent = item.Parent ?? (object)Serial.MinusOne;
#else
                        var parent    = item.ParentEntity != null ? item.ParentEntity.Serial : Serial.MinusOne;
                        var logParent = item.ParentEntity ?? (object)Serial.MinusOne;
#endif
                        var pos = bin.Position;

                        Exception x = null;
                        string status;

                        try
                        {
                            item.Serialize(bin);

                            status = "SAVED";
                        }
                        catch (Exception e)
                        {
                            ++idxFails;
                            x = e;

                            status = "ERROR";
                        }

                        var len = bin.Position - pos;

                        if (log != null)
                        {
                            log.AppendLine(
                                "WRITE:\tIndex[{0}]\t\tLength[{1}]\tStatus[{2}]\tItem[{3}]\t\t\tParent[{4}]",
                                //
                                pos,
                                len,
                                status,
                                item,
                                logParent);

                            if (x != null)
                            {
                                log.AppendLine();
                                log.AppendLine(new String('*', 10));
                                log.AppendLine(x.ToString());
                                log.AppendLine(new String('*', 10));
                                log.AppendLine();
                            }
                        }

                        WriteIndex(idx, item.GetType(), item.Serial, parent, pos, len);

                        idxlen += len;
                        ++idxCount;
                    }
                });

                WriteLength(idx, true, idxlen, idxCount);
            });

            count = idxCount;
            fails = idxFails;

            if (log == null)
            {
                return;
            }

            log.AppendLine();
            log.AppendLine("RESULT:\tCount[{0}]\tFails[{1}]\tLength[{2}]", count - fails, fails, idxlen);
            log.AppendLine();
            logFile.AppendText(false, log.ToString());
        }
Beispiel #25
0
        private static void DisplayRetroBoot()
        {
            #if MONO
            Console.WriteLine("VITA-NEX: CORE " + Version);
            Console.WriteLine("Root Directory:     " + RootDirectory);
            Console.WriteLine("Working Directory:  " + BaseDirectory);
            Console.WriteLine("Build Directory:    " + BuildDirectory);
            Console.WriteLine("Data Directory:     " + DataDirectory);
            Console.WriteLine("Cache Directory:    " + CacheDirectory);
            Console.WriteLine("Services Directory: " + ServicesDirectory);
            Console.WriteLine("Modules Directory:  " + ModulesDirectory);
            Console.WriteLine("Backup Directory:   " + BackupDirectory);
            Console.WriteLine("Saves Directory:    " + SavesDirectory);
            Console.WriteLine("Logs Directory:     " + LogsDirectory);
            Console.WriteLine("http://core.vita-nex.com");

            if (FirstBoot)
            {
                Console.WriteLine("Please see: " + RootDirectory + "/LICENSE");
            }

            if (Core.Debug)
            {
                Console.WriteLine("Server is running in DEBUG mode.");
            }
            #else
            ConsoleColor defBG;

            lock (ConsoleLock)
            {
                defBG = Console.BackgroundColor;
                Console.WriteLine();

                Console.BackgroundColor = _BorderColor;
                Console.Write(new String(' ', Console.WindowWidth));
            }

            DrawLine();
            DrawLine("**** VITA-NEX: CORE " + Version + " ****", 1);
            DrawLine();

            DrawLine("Root Directory:     " + RootDirectory);
            DrawLine("Working Directory:  " + BaseDirectory);
            DrawLine("Build Directory:    " + BuildDirectory);
            DrawLine("Data Directory:     " + DataDirectory);
            DrawLine("Cache Directory:    " + CacheDirectory);
            DrawLine("Services Directory: " + ServicesDirectory);
            DrawLine("Modules Directory:  " + ModulesDirectory);
            DrawLine("Backup Directory:   " + BackupDirectory);
            DrawLine("Saves Directory:    " + SavesDirectory);
            DrawLine("Logs Directory:     " + LogsDirectory);
            DrawLine();

            DrawLine("http://core.vita-nex.com", 1);
            DrawLine();

            if (FirstBoot)
            {
                File.ReadAllLines(IOUtility.GetSafeFilePath(RootDirectory + "/LICENSE", true)).ForEach(line => DrawLine(line));
                DrawLine();
            }

            if (Core.Debug)
            {
                DrawLine("Server is running in DEBUG mode.");
                DrawLine();
            }

            lock (ConsoleLock)
            {
                Console.BackgroundColor = _BorderColor;
                Console.Write(new String(' ', Console.WindowWidth));

                Console.BackgroundColor = defBG;
                Utility.PopColor();
                Console.WriteLine();
            }
            #endif
        }
Beispiel #26
0
        public static void RestoreState(
            PlayerMobile m,
            Serial serial,
            bool moveExisting,
            bool logging,
            out int created,
            out int deleted,
            out int ignored,
            out int moved)
        {
            var pack = m.Backpack;

            if (pack == null || pack.Deleted)
            {
                m.AddItem(
                    pack = new Backpack
                {
                    Movable = false
                });
            }

            var bank = m.BankBox;

            if (bank == null || bank.Deleted)
            {
                m.AddItem(
                    bank = new BankBox(m)
                {
                    Movable = false
                });
            }

            if (serial == Serial.MinusOne)
            {
                serial = m.Serial;
            }

            var root = VitaNexCore.DataDirectory + "/PlayerBackup/" + m.Account.Username + "/" + serial;

            var idxFile = IOUtility.EnsureFile(root + ".idx");
            var binFile = IOUtility.EnsureFile(root + ".bin");

            var logFile = logging ? IOUtility.EnsureFile(root + ".log") : null;
            var log     = logging ? new StringBuilder() : null;

            if (log != null)
            {
                log.AppendLine();
                log.AppendLine(new String('*', 10));
                log.AppendLine();
                log.AppendLine("RESTORE:\tDate[{0}]\tMobile[{1}]", DateTime.UtcNow, m);
                log.AppendLine();
            }

            int idxCreated = 0, idxDeleted = 0, idxIgnored = 0, idxMoved = 0;

            idxFile.Deserialize(
                idx =>
            {
                idx.GetVersion();

                var ser = idx.ReadInt();

                if (ser != m.Serial.Value)
                {
                    if (log != null)
                    {
                        log.AppendLine("INVALID:\tSerial[{0:X8}]", ser);
                    }

                    return;
                }

                long idxLength;
                int idxCount;

                ReadLength(idx, false, out idxLength, out idxCount);

                if (log != null)
                {
                    log.AppendLine("INDEX:\tCount[{0}]\tLength[{1}]", idxCount, idxLength);
                }

                var items = new Tuple <Item, Serial, long, long, string> [idxCount];

                binFile.Deserialize(
                    bin =>
                {
                    bin.GetVersion();

                    var restored = new Dictionary <Item, Serial>();

                    Backpack oldPack = null;
                    BankBox oldBank  = null;

                    for (var i = 0; i < idxCount; i++)
                    {
                        Type type;
                        Serial s, parent;
                        long binIndex, binLength;

                        ReadIndex(idx, out type, out s, out parent, out binIndex, out binLength);

                        var valid  = s.IsValid && s.IsItem;
                        var exists = World.Items.ContainsKey(s);

                        Item item = null;

                        if (exists)
                        {
                            item = World.Items[s];

                            if (item == null || item.Deleted)
                            {
                                World.Items.Remove(s);
                                exists = false;
                            }
                        }

                        object logItem;
                        string status;

                        if (!exists && valid && type.IsEqualOrChildOf <Item>())
                        {
                            item = type.CreateInstanceSafe <Item>(s);

                            if (item == null)
                            {
                                ++idxIgnored;

                                logItem = s;
                                status  = "NULL";
                            }
                            else if (item.Deleted)
                            {
                                ++idxDeleted;

                                item    = null;
                                logItem = s;
                                status  = "DELETED";
                            }
                            else
                            {
                                ++idxCreated;

                                World.AddItem(item);

                                logItem = item;
                                status  = "CREATED";
                            }
                        }
                        else if (exists && valid && moveExisting && item.RootParent != m)
                        {
                            ++idxMoved;

                            logItem = item;
                            status  = "MOVE";
                        }
                        else
                        {
                            ++idxIgnored;

                            item    = null;
                            logItem = s;
                            status  = exists ? "EXISTS" : "INVALID";
                        }

                        if (log != null)
                        {
                            log.AppendLine(
                                "DATA:\tIndex[{0}]\t\tLength[{1}]\tStatus[{2}]\tItem[{3}]\t\t\tParent[{4}]",
                                //
                                binIndex,
                                binLength,
                                status,
                                logItem,
                                parent);
                        }

                        items[i] = Tuple.Create(item, parent, binIndex, binLength, status);
                    }

                    foreach (var t in items)
                    {
                        var item   = t.Item1;
                        var parent = t.Item2;
                        var index  = t.Item3;
                        var length = t.Item4;
                        var status = t.Item5;

                        bin.Seek(index, SeekOrigin.Begin);

                        if (item == null)
                        {
                            bin.Seek(index + length, SeekOrigin.Begin);
                            continue;
                        }

                        Exception x = null;

                        if (status == "MOVE")
                        {
                            bin.Seek(index + length, SeekOrigin.Begin);

                            status = "IGNORED";
                        }
                        else
                        {
                            try
                            {
                                item.Deserialize(bin);

                                status = "LOADED";
                            }
                            catch (Exception e)
                            {
                                --idxCreated;
                                ++idxDeleted;

                                item.Delete();
                                x = e;

                                status = "ERROR";
                            }
                        }

                        if (log != null)
                        {
                            log.AppendLine(
                                "READ:\tIndex[{0}]\tLength[{1}]\tStatus[{2}]\tItem[{3}]\t\t\tParent[{4}]",
                                index,
                                length,
                                status,
                                item,
                                parent);

                            if (x != null)
                            {
                                log.AppendLine();
                                log.AppendLine(new String('*', 10));
                                log.AppendLine(x.ToString());
                                log.AppendLine(new String('*', 10));
                                log.AppendLine();
                            }
                        }

                        if (parent == m.Serial)
                        {
                            if (item is BankBox)
                            {
                                oldBank = (BankBox)item;
                            }
                            else if (item is Backpack)
                            {
                                oldPack = (Backpack)item;
                            }
                        }

                        restored.Add(item, parent);
                    }

                    if (log != null)
                    {
                        log.AppendLine();
                    }

                    Point3D p;

                    foreach (var kv in restored.Where(kv => !kv.Key.Deleted).OrderBy(kv => kv.Value))
                    {
                        var item = kv.Key;

                        if ((item == oldPack || item == oldBank) && item != pack && item != bank)
                        {
                            if (item.Parent is Item)
                            {
                                ((Item)item.Parent).RemoveItem(item);
                            }
                            else if (item.Parent is Mobile)
                            {
                                ((Mobile)item.Parent).RemoveItem(item);
                            }

                            item.Parent = null;
                            continue;
                        }

                        var parent = World.FindEntity(kv.Value);

                        if (item != pack && item != bank && (item.Parent == oldPack || item.Parent == oldBank))
                        {
                            ((Item)item.Parent).RemoveItem(item);
                        }

                        if (parent != null)
                        {
                            if (item == pack || item == bank)
                            {
                                m.AddItem(item);
                            }
                            else if (parent == pack || parent == oldPack)
                            {
                                p = item.Location;
                                pack.DropItem(item);
                                item.Location = p;
                            }
                            else if (parent == bank || parent == oldBank)
                            {
                                p = item.Location;
                                bank.DropItem(item);
                                item.Location = p;
                            }
                            else if (parent is Container)
                            {
                                if (parent.Deleted)
                                {
                                    bank.DropItem(item);
                                }
                                else
                                {
                                    p = item.Location;
                                    ((Container)parent).DropItem(item);
                                    item.Location = p;
                                }
                            }
                            else if (parent is Mobile)
                            {
                                if (!m.EquipItem(item))
                                {
                                    pack.DropItem(item);
                                }
                            }
                            else
                            {
                                bank.DropItem(item);
                            }

                            item.SetLastMoved();
                            item.UpdateTotals();
                            item.Delta(ItemDelta.Update);
                        }
                        else if (Cleanup.IsBuggable(item))
                        {
                            --idxCreated;
                            ++idxDeleted;

                            item.Delete();
                        }
                        else
                        {
                            item.Internalize();
                        }
                    }

                    if (oldPack != null && oldPack != pack && !restored.ContainsKey(oldPack))
                    {
                        oldPack.Delete();
                    }

                    if (oldBank != null && oldBank != bank && !restored.ContainsKey(oldBank))
                    {
                        oldBank.Delete();
                    }

                    if (log != null)
                    {
                        log.AppendLine();
                    }

                    foreach (var kv in restored)
                    {
                        if (kv.Key.Deleted)
                        {
                            if (log != null)
                            {
                                log.AppendLine("DELETED:\tItem[{0}]\t\tParent[{1}]", kv.Key, kv.Value);
                            }
                        }
                        else if (kv.Key.RootParent == m && kv.Key.Map == Map.Internal && kv.Key.Location == Point3D.Zero)
                        {
                            if (log != null)
                            {
                                log.AppendLine("INTERNAL:\tItem[{0}]\t\tParent[{1}]", kv.Key, kv.Value);
                            }
                        }
                        else if (kv.Key.RootParent != m)
                        {
                            if (log != null)
                            {
                                log.AppendLine("IGNORED:\tItem[{0}]\t\tParent[{1}]", kv.Key, kv.Value);
                            }
                        }
                        else
                        {
                            if (log != null)
                            {
                                log.AppendLine("RESTORED:\tItem[{0}]\t\tParent[{1}]", kv.Key, kv.Key.Parent);
                            }
                        }
                    }

                    restored.Clear();

                    m.SendEverything();
                });
            });

            created = idxCreated;
            deleted = idxDeleted;
            ignored = idxIgnored;
            moved   = idxMoved;

            if (log == null)
            {
                return;
            }

            log.AppendLine();
            log.AppendLine(
                "RESULT:\tCreated[{0}]\t\tDeleted[{1}]\t\tIgnored[{2}]\t\tMoved[{3}]",
                created,
                deleted,
                ignored,
                moved);

            logFile.AppendText(false, log.ToString());
        }
Beispiel #27
0
        static VitaNexCore()
        {
            _INITVersion = "5.2.0.0";

            _INITQueue    = new Queue <Tuple <string, string> >();
            _INITHandlers = new Dictionary <string, Action <string> >();

            var basePath = IOUtility.GetSafeDirectoryPath(Core.BaseDirectory + "/VitaNexCore");

            if (!Directory.Exists(basePath))
            {
                FirstBoot = true;
            }

            BaseDirectory = IOUtility.EnsureDirectory(basePath);

            var first = IOUtility.GetSafeFilePath(BaseDirectory + "/FirstBoot.vnc", true);

            if (!File.Exists(first))
            {
                FirstBoot = true;

                IOUtility.EnsureFile(first)
                .AppendText(
                    true,
                    "This file serves no other purpose than to identify if",
                    "the software has been initialized for the first time. ",
                    "To re-initialize 'First-Boot' mode, simply delete this",
                    "file before starting the application.");
            }

            var root = FindRootDirectory(Core.BaseDirectory + "/Scripts/VitaNex");

            if (root != null && root.Exists)
            {
                RootDirectory = root;

                ParseVersion();
                ParseINIT();

                RegisterINITHandler(
                    "ROOT_DIR",
                    path =>
                {
                    root = FindRootDirectory(path);

                    if (root == null || !root.Exists)
                    {
                        return;
                    }

                    RootDirectory = root;

                    ParseVersion();
                });
            }

            BackupExpireAge = TimeSpan.FromDays(7);

            RegisterINITHandler(
                "BACKUP_EXPIRE",
                time =>
            {
                TimeSpan ts;

                if (TimeSpan.TryParse(time, out ts))
                {
                    BackupExpireAge = ts;
                }
            });

            Core.Slice += Slice;
        }
Beispiel #28
0
        static Filters()
        {
            _Filters = new Dictionary <PlayerMobile, List <IFilter> >();

            _Persistence = IOUtility.EnsureFile(VitaNexCore.SavesDirectory + "/Filters/Profiles.bin");
        }
Beispiel #29
0
        /// <summary>
        /// Resizes the image.
        /// </summary>
        /// <param name="url">The URL.</param>
        /// <param name="width">The width.</param>
        /// <param name="height">The height.</param>
        /// <param name="preserverAspectRatio">The preserver aspect ratio.保持比例</param>
        /// <param name="quality">The quality.</param>
        /// <returns></returns>
        public virtual ActionResult ResizeImage(string url, int width, int height, bool?preserverAspectRatio, int?quality)
        {
            if (string.IsNullOrEmpty(url))
            {
                throw new ArgumentNullException(url);
            }
            if (!ImageTools.IsImageExtension(Path.GetExtension(url)))
            {
                throw new HttpException(403, "");
            }
            url = HttpUtility.UrlDecode(url);
            var index = url.IndexOf("?");

            if (index != -1)
            {
                url = url.Substring(0, index);
            }

            preserverAspectRatio = preserverAspectRatio ?? true;
            quality = quality ?? 80;

            if (url.StartsWith("http://") || url.StartsWith("https://"))
            {
                //now no image cache for azure blob
                var provider     = Kooboo.CMS.Content.Persistence.Providers.DefaultProviderFactory.GetProvider <Kooboo.CMS.Content.Persistence.IMediaContentProvider>();
                var mediaContent = new MediaContent()
                {
                    VirtualPath = url
                };
                var data = provider.GetContentStream(mediaContent);
                if (data != null)
                {
                    using (var imageStream = new MemoryStream(data))
                    {
                        var    imageFormat = ImageTools.ConvertToImageFormat(Path.GetExtension(mediaContent.VirtualPath));
                        Stream outStream   = new MemoryStream();
                        ImageTools.ResizeImage(imageStream, outStream, imageFormat, width, height, preserverAspectRatio.Value, quality.Value);
                        outStream.Position = 0;
                        return(File(outStream, IOUtility.MimeType(url)));
                    }
                }
                else
                {
                    return(null);
                }
            }
            else
            {
                var imageFullPath = Server.MapPath(url);
                var cachingPath   = GetCachingFilePath(imageFullPath, width, height, preserverAspectRatio.Value, quality.Value);

                if (!System.IO.File.Exists(cachingPath))
                {
                    if (!System.IO.File.Exists(cachingPath))
                    {
                        var dir = Path.GetDirectoryName(cachingPath);
                        IOUtility.EnsureDirectoryExists(dir);
                        var success = ImageTools.ResizeImage(imageFullPath, cachingPath, width, height, preserverAspectRatio.Value, quality.Value);
                        if (!success)
                        {
                            cachingPath = imageFullPath;
                        }
                    }
                }
                SetCache(HttpContext.Response, 2592000, "*");
                return(File(cachingPath, IOUtility.MimeType(imageFullPath)));
            }
        }
 public static void WriteSolutionReadMe(SnippetDirectory[] snippetDirectories, GeneralSettings settings)
 {
     IOUtility.WriteAllText(
         Path.Combine(settings.SolutionDirectoryPath, settings.ReadMeFileName),
         GenerateSolutionReadMe(snippetDirectories, settings));
 }