private string RenderConstants(ModuleFile file) { var constantDictionaries = this.Options.ConstantsTypes .ToDictionary( tk => tk.Name, tv => tv.GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy) .Where(xx => xx.IsLiteral && !xx.IsInitOnly) .ToDictionary( k => StringFunctions.ConvertToKey(k.Name), v => this.ConvertToJavaScriptValue(v.GetRawConstantValue()))); if (this.Options.Constants.Count > 0) { constantDictionaries["ConstantsExposedByTheApplication"] = this.Options.Constants .ToDictionary( x => StringFunctions.ConvertToKey(x.Key), x => this.ConvertToJavaScriptValue(x.Value)); } return(file.RenderTemplate(new Dictionary <string, object> { { "Constants", constantDictionaries }, })); }
// Load the material constants from the stonehearth mod. This needs to be done before the data columns // are populated,since they use this map to fill in data grid for material ingredients private void LoadMaterialImages() { Module sh = ModuleDataManager.GetInstance().GetMod("stonehearth"); if (sh != null) { ModuleFile resourceConstants = sh.GetAliasFile("data:resource_constants"); if (resourceConstants != null) { JsonFileData jsonFileData = resourceConstants.FileData as JsonFileData; JObject resourceConstantsJson = jsonFileData.Json; JObject resourceJson = resourceConstantsJson["resources"] as JObject; foreach (JProperty resource in resourceJson.Properties()) { string name = resource.Name; string iconLocation = resource.Value["icon"].ToString(); string path = JsonHelper.GetFileFromFileJson(iconLocation, jsonFileData.Directory); if (path != "" && System.IO.File.Exists(path)) { mMaterialImages.Add(name, path); } } } } }
private string RenderPageComponent(ModuleFile file) { return(file.RenderTemplate(new Dictionary <string, object> { { "Page", file.ReferenceId }, })); }
private static string GetFileProviderHint(ModuleFile moduleFile) { return (moduleFile.FileProvider is PhysicalFileProvider physicalFileProvider ? $"{physicalFileProvider.GetType().Name}[{physicalFileProvider.Root}]" : moduleFile.FileProvider.GetType().Name); }
public async Task Issue11_NRE_When_Variable_Has_No_Initializer() { var fooContent = @" var i, length; i = 1; "; var fileProvider = new MemoryFileProvider(); var fooFile = new ModuleFile(fileProvider, "/foo.js") { Content = fooContent }; var moduleBundler = new ModuleBundler(); await moduleBundler.BundleCoreAsync(new[] { fooFile }, CancellationToken.None); var fooLines = GetNonEmptyLines(moduleBundler.Modules.Single(kvp => kvp.Key.FilePath == "/foo.js").Value.Content); Assert.Equal(new[] { "'use strict';", "var i, length;", "i = 1;", }, fooLines); }
/// <summary> /// Constructor. Compiles a rules assembly from the given source files. /// </summary> /// <param name="Plugins">All the plugins included in this assembly</param> /// <param name="ModuleFiles">List of module files to compile</param> /// <param name="TargetFiles">List of target files to compile</param> /// <param name="ModuleFileToPluginInfo">Mapping of module file to the plugin that contains it</param> /// <param name="AssemblyFileName">The output path for the compiled assembly</param> /// <param name="Parent">The parent rules assembly</param> public RulesAssembly(IReadOnlyList <PluginInfo> Plugins, List <FileReference> ModuleFiles, List <FileReference> TargetFiles, Dictionary <FileReference, PluginInfo> ModuleFileToPluginInfo, FileReference AssemblyFileName, RulesAssembly Parent) { this.Plugins = Plugins; this.ModuleFileToPluginInfo = ModuleFileToPluginInfo; this.Parent = Parent; // Find all the source files List <FileReference> AssemblySourceFiles = new List <FileReference>(); AssemblySourceFiles.AddRange(ModuleFiles); AssemblySourceFiles.AddRange(TargetFiles); // Compile the assembly if (AssemblySourceFiles.Count > 0) { CompiledAssembly = DynamicCompilation.CompileAndLoadAssembly(AssemblyFileName, AssemblySourceFiles); } // Setup the module map foreach (FileReference ModuleFile in ModuleFiles) { string ModuleName = ModuleFile.GetFileNameWithoutAnyExtensions(); if (!ModuleNameToModuleFile.ContainsKey(ModuleName)) { ModuleNameToModuleFile.Add(ModuleName, ModuleFile); } } // Setup the target map foreach (FileReference TargetFile in TargetFiles) { string TargetName = TargetFile.GetFileNameWithoutAnyExtensions(); if (!TargetNameToTargetFile.ContainsKey(TargetName)) { TargetNameToTargetFile.Add(TargetName, TargetFile); } } /// Write any deprecation warnings for methods overriden from a base with the [ObsoleteOverride] attribute. Unlike the [Obsolete] attribute, this ensures the message /// is given because the method is implemented, not because it's called. if (CompiledAssembly != null) { foreach (Type CompiledType in CompiledAssembly.GetTypes()) { foreach (MethodInfo Method in CompiledType.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly)) { ObsoleteOverrideAttribute Attribute = Method.GetCustomAttribute <ObsoleteOverrideAttribute>(true); if (Attribute != null) { FileReference Location; if (!TryGetFileNameFromType(CompiledType, out Location)) { Location = new FileReference(CompiledAssembly.Location); } Log.TraceWarning("{0}: warning: {1}", Location, Attribute.Message); } } } } }
private string RenderEnums(ModuleFile file) { var endpointService = this.GetService <IEndpointService>(); var classes = endpointService.GetAllEndpointsClasses(); var enums = DescriptionExtractor.ExtractUniqueEnumsFromClasses(classes); var enumValueItems = new Dictionary <string, string>(); DefaultContractResolver contractResolver = new DefaultContractResolver { NamingStrategy = new CamelCaseNamingStrategy(), }; foreach (var enumItem in enums) { string serializedEnums = JsonConvert.SerializeObject( EnumFunctions.GetEnumValueItems(enumItem.FullName), new JsonSerializerSettings { ContractResolver = contractResolver, Formatting = Formatting.Indented, }); enumValueItems[enumItem.FullName] = JToken.Parse(serializedEnums).ToString(); } return(file.RenderTemplate(new Dictionary <string, object> { { "Enums", enums }, { "EnumsValueItems", enumValueItems }, })); }
public async Task Export_Default_Named() { var fooContent = @"import * as bar from './bar';"; var barContent = @"export default function myFunc() {}"; var fileProvider = new MemoryFileProvider(); fileProvider.CreateFile("/bar.js", barContent); var fooFile = new ModuleFile(fileProvider, null) { Content = fooContent }; var moduleBundler = new ModuleBundler(); await moduleBundler.BundleCoreAsync(new[] { fooFile }, CancellationToken.None); var barLines = GetNonEmptyLines(moduleBundler.Modules.Single(kvp => kvp.Key.FilePath == "/bar.js").Value.Content); Assert.Equal(new[] { "'use strict';", "__es$require.d(__es$exports, \"default\", function() { return myFunc; });", "function myFunc() {}", }, barLines); }
private string RenderLanguageJson(ModuleFile file) { var languageStore = this.GetService <ILanguageStore>(); int languageId = int.Parse(file.ReferenceId); var translationsDictionary = languageStore.GetLanguageTranslationDictionary(languageId); return(JsonConvert.SerializeObject(translationsDictionary)); }
private string RenderTypes(ModuleFile file) { var endpointService = this.GetService <IEndpointService>(); var classes = endpointService.GetAllEndpointsClasses(); return(file.RenderTemplate(new Dictionary <string, object> { { "Classes", classes }, })); }
private string RenderDto(ModuleFile file) { var endpointService = this.GetService <IEndpointService>(); var classes = endpointService.GetAllEndpointsClasses(); return(file.RenderTemplate(new Dictionary <string, object> { { "Class", classes.FirstOrDefault(x => x.FullName == file.ReferenceId) }, })); }
private string RenderTranslations(ModuleFile file) { var languageStore = this.GetService <ILanguageStore>(); var translationsDictionary = languageStore.GetLanguageTranslationDictionary(int.Parse(file.ReferenceId)); return(file.RenderTemplate(new Dictionary <string, object> { { "Translations", translationsDictionary }, })); }
private string RenderServiceAgentInterface(ModuleFile file) { var endpointService = this.GetService <IEndpointService>(); var endpoints = endpointService.GetAllEndpoints(); return(file.RenderTemplate(new Dictionary <string, object> { { "EndpointsController", file.ReferenceId.Replace("ApiController", string.Empty).ToFirstUpper() }, { "Endpoints", endpoints.Where(x => x.ControllerName == file.ReferenceId).ToList() }, })); }
private string RenderTranslationsKeys(ModuleFile file) { var languageStore = this.GetService <ILanguageStore>(); var translationsKeys = languageStore.GetTranslationsKeys(); var translationsKeysDictionary = translationsKeys.ToDictionary(k => this.MakePascalCaseKeyFromTranslationKey(k), v => v); return(file.RenderTemplate(new Dictionary <string, object> { { "TranslationsKeys", translationsKeysDictionary }, })); }
private string RenderTranslationsBase(ModuleFile file) { var languageStore = this.GetService <ILanguageStore>(); var defaultLanguage = languageStore.GetDefaultLanguage(); var translationsDictionary = languageStore.GetLanguageTranslationDictionary(defaultLanguage.Id); return(file.RenderTemplate(new Dictionary <string, object> { { "Translations", translationsDictionary }, })); }
private string RenderEnums(ModuleFile file) { var endpointService = this.GetService <IEndpointService>(); var classes = endpointService.GetAllEndpointsClasses(); var enums = DescriptionExtractor.ExtractUniqueEnumsFromClasses(classes); return(file.RenderTemplate(new Dictionary <string, object> { { "Enums", enums }, })); }
private string RenderEndpoints(ModuleFile file) { var endpointService = this.GetService <IEndpointService>(); var endpoints = endpointService.GetAllEndpoints(); return(file.RenderTemplate(new Dictionary <string, object> { { "EndpointsControllers", endpoints.Select(x => x.ControllerName).Distinct().ToList() }, { "Endpoints", endpoints }, })); }
public async Task Feature_AsyncAwait_And_DynamicImport() { var fooContent = @"import * as bar from './bar'; (async () => await bar.myAsyncFunc3())(); "; var barContent = @" export const myAsyncLambda = async () => await import('x'); export const myAsyncFunc1 = async function() { return await myAsyncLambda(); } export async function myAsyncFunc2() { return await myAsyncFunc1(); } async function myAsyncFunc3() { return await myAsyncFunc2(); } export { myAsyncFunc3 } "; var fileProvider = new MemoryFileProvider(); fileProvider.CreateFile("/bar.js", barContent); var fooFile = new ModuleFile(fileProvider, "/foo.js") { Content = fooContent }; var moduleBundler = new ModuleBundler(); await moduleBundler.BundleCoreAsync(new[] { fooFile }, CancellationToken.None); var fooLines = GetNonEmptyLines(moduleBundler.Modules.Single(kvp => kvp.Key.FilePath == "/foo.js").Value.Content); Assert.Equal(new[] { "'use strict';", "var __es$module_0 = __es$require(\"/bar.js\");", "(async () => await __es$module_0.myAsyncFunc3())();", }, fooLines); var barLines = GetNonEmptyLines(moduleBundler.Modules.Single(kvp => kvp.Key.FilePath == "/bar.js").Value.Content); Assert.Equal(new[] { "'use strict';", "__es$require.d(__es$exports, \"myAsyncLambda\", function() { return myAsyncLambda; });", "__es$require.d(__es$exports, \"myAsyncFunc1\", function() { return myAsyncFunc1; });", "__es$require.d(__es$exports, \"myAsyncFunc2\", function() { return myAsyncFunc2; });", "__es$require.d(__es$exports, \"myAsyncFunc3\", function() { return myAsyncFunc3; });", "const myAsyncLambda = async () => await import('x');", "const myAsyncFunc1 = async function() { return await myAsyncLambda(); }", "async function myAsyncFunc2() { return await myAsyncFunc1(); }", "async function myAsyncFunc3() { return await myAsyncFunc2(); }", }, barLines); }
private string RenderConfigFile(ModuleFile file) { var localizationContext = this.GetService <ILocalizationContext>(); var languages = localizationContext.Languages.ToList(); Language defaultLanguage = languages.FirstOrDefault(x => x.IsDefault); return(file.RenderTemplate(new Dictionary <string, object> { { "Languages", languages }, { "DefaultLanguage", defaultLanguage }, })); }
public async Task Reexport_Everything() { var fooContent = @"import * as bar from './bar';"; var barContent = @"export * from './baz'"; var bazContent = @"export var [myVar1, { a: myVar2, b: { c: myVar3, ...rest1} }, ...rest2] = [1, { a: 2, b: { c: 3.14 } }];"; var fileProvider = new MemoryFileProvider(); fileProvider.CreateFile("/bar.js", barContent); fileProvider.CreateFile("/baz.js", bazContent); var fooFile = new ModuleFile(fileProvider, null) { Content = fooContent }; var moduleBundler = new ModuleBundler(); await moduleBundler.BundleCoreAsync(new[] { fooFile }, CancellationToken.None); var barLines = GetNonEmptyLines(moduleBundler.Modules.Single(kvp => kvp.Key.FilePath == "/bar.js").Value.Content); Assert.Equal(new[] { "'use strict';", "var __es$module_0 = __es$require(\"/baz.js\");", "__es$require.d(__es$exports, \"myVar1\", function() { return __es$module_0.myVar1; });", "__es$require.d(__es$exports, \"myVar2\", function() { return __es$module_0.myVar2; });", "__es$require.d(__es$exports, \"myVar3\", function() { return __es$module_0.myVar3; });", "__es$require.d(__es$exports, \"rest1\", function() { return __es$module_0.rest1; });", "__es$require.d(__es$exports, \"rest2\", function() { return __es$module_0.rest2; });", }, barLines); var bazLines = GetNonEmptyLines(moduleBundler.Modules.Single(kvp => kvp.Key.FilePath == "/baz.js").Value.Content); Assert.Equal(new[] { "'use strict';", "__es$require.d(__es$exports, \"myVar1\", function() { return myVar1; });", "__es$require.d(__es$exports, \"myVar2\", function() { return myVar2; });", "__es$require.d(__es$exports, \"myVar3\", function() { return myVar3; });", "__es$require.d(__es$exports, \"rest1\", function() { return rest1; });", "__es$require.d(__es$exports, \"rest2\", function() { return rest2; });", "var [myVar1, { a: myVar2, b: { c: myVar3, ...rest1} }, ...rest2] = [1, { a: 2, b: { c: 3.14 } }];", }, bazLines); }
private static void AddArchiveToSection(ModuleFile moduleFile, string sectionName, string archivePath) { ModuleFile.ModuleSectionFileList moduleSection; if (!moduleFile.HasSection(sectionName)) { moduleSection = new ModuleFile.ModuleSectionFileList(sectionName); moduleFile.AddSection(moduleSection); } else { moduleSection = moduleFile[sectionName] as ModuleFile.ModuleSectionFileList; } moduleSection.AddArchive(archivePath, true); }
private string RenderRouterList(ModuleFile file) { var pageService = this.GetService <IPageService>(); var languageStore = this.GetService <ILanguageStore>(); var pages = pageService.GetAllPages(); var languages = languageStore.GetLanguages(); var languageRouteRegex = string.Join('|', languages.Where(x => !x.IsDefault).Select(x => x.Code.ToLower())); return(file.RenderTemplate(new Dictionary <string, object> { { "Pages", pages }, { "LanguageRouteRegex", languageRouteRegex }, { "SingleLanguage", languages.Count() < 2 }, })); }
public void TestString() { var m = new ModuleFile() { FileName = "asdfasdf" }; var list = new HashSet<ModuleInfo>(); list.Add(new ModuleInfo()); m.ModuleList = list; var data = Json.JsonConverter.Serialize(m); Log.Debug(data); }
public async Task Reexport_Clause() { var fooContent = @"import * as bar from './bar';"; var barContent = @"export { default, default as defaultAlias, rest, rest as restAlias } from './baz'"; var bazContent = @"var [myVar1, {a: myVar2, b: [myVar3, ...rest]}] = [1, {a: 2, b: [3.14]}]; export { myVar1 as default, rest };"; var fileProvider = new MemoryFileProvider(); fileProvider.CreateFile("/bar.js", barContent); fileProvider.CreateFile("/baz.js", bazContent); var fooFile = new ModuleFile(fileProvider, null) { Content = fooContent }; var moduleBundler = new ModuleBundler(); await moduleBundler.BundleCoreAsync(new[] { fooFile }, CancellationToken.None); var barLines = GetNonEmptyLines(moduleBundler.Modules.Single(kvp => kvp.Key.FilePath == "/bar.js").Value.Content); Assert.Equal(new[] { "'use strict';", "var __es$module_0 = __es$require(\"/baz.js\");", "__es$require.d(__es$exports, \"default\", function() { return __es$module_0.default; });", "__es$require.d(__es$exports, \"defaultAlias\", function() { return __es$module_0.default; });", "__es$require.d(__es$exports, \"rest\", function() { return __es$module_0.rest; });", "__es$require.d(__es$exports, \"restAlias\", function() { return __es$module_0.rest; });", }, barLines); var bazLines = GetNonEmptyLines(moduleBundler.Modules.Single(kvp => kvp.Key.FilePath == "/baz.js").Value.Content); Assert.Equal(new[] { "'use strict';", "__es$require.d(__es$exports, \"default\", function() { return myVar1; });", "__es$require.d(__es$exports, \"rest\", function() { return rest; });", "var [myVar1, {a: myVar2, b: [myVar3, ...rest]}] = [1, {a: 2, b: [3.14]}];", }, bazLines); }
private string RenderStaticContent(ModuleFile file) { var localizationContext = this.GetService <ILocalizationContext>(); Language defaultLanguage = localizationContext.Languages.FirstOrDefault(x => x.IsDefault); ContentKey staticContentKeyWithContent = localizationContext .ContentKeys .Where(x => x.Id == int.Parse(file.ReferenceId)) .Include(x => x.StaticContentList) .FirstOrDefault(); return(file.RenderTemplate(new Dictionary <string, object> { { "Key", staticContentKeyWithContent }, { "DefaultLanguage", defaultLanguage }, })); }
public async Task Export_Named_Clause() { var fooContent = @"import * as bar from './bar';"; var barContent = @"var myVar1 = '1'; let myVar2 = 2; const MY_CONST = 3.14; function myFunc() { return myVar1; } function* myGeneratorFunc() { yield myVar2; } class MyClass { method() { return myFunc(); } } export { myVar1, myVar2 as var2, MY_CONST, myFunc, myGeneratorFunc, MyClass as default }"; var fileProvider = new MemoryFileProvider(); fileProvider.CreateFile("/bar.js", barContent); var fooFile = new ModuleFile(fileProvider, null) { Content = fooContent }; var moduleBundler = new ModuleBundler(); await moduleBundler.BundleCoreAsync(new[] { fooFile }, CancellationToken.None); var barLines = GetNonEmptyLines(moduleBundler.Modules.Single(kvp => kvp.Key.FilePath == "/bar.js").Value.Content); Assert.Equal(new[] { "'use strict';", "__es$require.d(__es$exports, \"myVar1\", function() { return myVar1; });", "__es$require.d(__es$exports, \"var2\", function() { return myVar2; });", "__es$require.d(__es$exports, \"MY_CONST\", function() { return MY_CONST; });", "__es$require.d(__es$exports, \"myFunc\", function() { return myFunc; });", "__es$require.d(__es$exports, \"myGeneratorFunc\", function() { return myGeneratorFunc; });", "__es$require.d(__es$exports, \"default\", function() { return MyClass; });", "var myVar1 = '1';", "let myVar2 = 2;", "const MY_CONST = 3.14;", "function myFunc() { return myVar1; }", "function* myGeneratorFunc() { yield myVar2; }", "class MyClass { method() { return myFunc(); } }", }, barLines); }
public async Task Import_CircularReference() { var fooContent = @"export var fooVar = 1; import { barVar } from './bar'; console.log({fooVar, barVar})"; var barContent = @"export var barVar = 2; import { fooVar } from './foo'; console.log({fooVar, barVar})"; var fileProvider = new MemoryFileProvider(); fileProvider.CreateFile("/foo.js", fooContent); fileProvider.CreateFile("/bar.js", barContent); var fooFile = new ModuleFile(fileProvider, "/foo.js"); var moduleBundler = new ModuleBundler(); await moduleBundler.BundleCoreAsync(new[] { fooFile }, CancellationToken.None); var fooLines = GetNonEmptyLines(moduleBundler.Modules.Single(kvp => kvp.Key.FilePath == "/foo.js").Value.Content); Assert.Equal(new[] { "'use strict';", "var __es$module_0 = __es$require(\"/bar.js\");", "__es$require.d(__es$exports, \"fooVar\", function() { return fooVar; });", "var fooVar = 1;", "console.log({fooVar, barVar: __es$module_0.barVar})", }, fooLines); var barLines = GetNonEmptyLines(moduleBundler.Modules.Single(kvp => kvp.Key.FilePath == "/bar.js").Value.Content); Assert.Equal(new[] { "'use strict';", "var __es$module_0 = __es$require(\"/foo.js\");", "__es$require.d(__es$exports, \"barVar\", function() { return barVar; });", "var barVar = 2;", "console.log({fooVar: __es$module_0.fooVar, barVar})", }, barLines); }
public void WriteModuleFile() { ModuleFile releaseModule = ModManager.ModuleFile.GClone(); if (File.Exists(GetAttribArchivePath())) { string attribPath = GetAttribArchivePath().SubstringAfterFirst(m_sOutputDirectory); AddArchiveToSection(releaseModule, "attrib:common", attribPath); } if (File.Exists(GetDataArchivePath())) { string dataPath = GetDataArchivePath().SubstringAfterFirst(m_sOutputDirectory); AddArchiveToSection(releaseModule, "data:common", dataPath); } releaseModule.WriteDataTo(m_sOutputDirectory + m_sModName + ".module"); }
public static void ProvideSTD(string module) { Console.WriteLine($"Started copying the standard module libs (STD) for module {module}..."); string file = ModuleList.ModuleList.Instance.GetModuleFile(module); //Make sure we have a valid file if (File.Exists(file)) { //Load the module file, or the cached version if there is one. var dmod = ModuleFile.LoadModule(module); //Make sure there is a language before we continue if (!string.IsNullOrWhiteSpace(dmod.Lang)) { //Get the path of the module var modulePath = Path.GetDirectoryName(file); string moduleSTDDir = Path.Combine(modulePath, dmod.Folders["std"]); //Make sure we have a directory to drop them in if (!Directory.Exists(moduleSTDDir)) { Directory.CreateDirectory(moduleSTDDir); } if (ProvideToFolder(moduleSTDDir, dmod.Lang)) { Console.WriteLine($"Completed copying the standard module libs (STD) for module {module}."); } else { Console.WriteLine($"Aborted copying the standard module libs (STD) for module {module} because the language \"{dmod.Lang}\" isn't supported. (maybe its spelled wrong?)"); } } } else { Console.WriteLine($"Aborted copying the standard module libs (STD) for module {module} because it doesn't have a language set."); } }
private void LoadAllRecipes() { foreach (Module module in ModuleDataManager.GetInstance().GetAllModules()) { bool shouldIncludeMod = mBaseModsOnly ? ModuleDataManager.IsBaseMod(module.Name) : true; if (shouldIncludeMod) { ModuleFile jobsIndex = module.GetAliasFile("jobs:index"); if (jobsIndex != null) { JObject jobIndexJson = (jobsIndex.FileData as JsonFileData).Json; JObject jobs = jobIndexJson["jobs"] as JObject; foreach (JProperty job in jobs.Properties()) { string jobAlias = job.Value["description"].ToString(); LoadRecipesForJob(jobAlias); } } } } }
static public void CloseAll() { LoggingManager.SendMessage("ModManager - Closing current mod (if any is loaded)"); if (ModuleFile != null) { ModuleFile.Close(); ModuleFile = null; } if (ModAttribArchives != null) { foreach (SGAFile sga in ModAttribArchives) { sga.Close(); } ModAttribArchives.Clear(); } if (ModDataArchives != null) { foreach (SGAFile sga in ModDataArchives) { sga.Close(); } ModDataArchives.Clear(); } FileManager.ReleaseFileTrees(); if (ModUnloaded != null) { ModUnloaded(); } ModName = null; // normally it isn't a good idea to manually invoke the GarbageCollection but in this case we're releasing // gigabytes of resources; the overall performance greatly benefits from this LoggingManager.SendMessage("ModManager - Manual GarbageCollection in all generations in progess..."); GC.Collect(); }
public void AddSystemManagerModule() { var moduleFile = new ModuleFile { FileName = "ZxdFramework.Silverlight.SystemManager.xap", UploadUser = "******", ModuleList = new List<ModuleInfo> { new ModuleInfo { Author = "����", Category = "System.Setting", Description = "��Ҫ����ϵͳ���õ�ģ��", ModuleType = "ZxdFramework.SystemManager.SystemManagerModule, ZxdFramework.Silverlight.SystemManager, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", ModuleName = "SystemManager", Ref = "ZxdFramework.Silverlight.SystemManager.xap", InitializationMode = InitializationMode.WhenAvailable, DependsOn = new []{ "shell" } } } }; "ModuleFileRepository".GetInstance<IModuleFileRepository>().Add(moduleFile); }
public void AddMembershipModule() { var moduleFile = new ModuleFile { FileName = "ZxdFramework.Silverlight.Membership.UI.xap", UploadUser = "******", ModuleList = new List<ModuleInfo> { new ModuleInfo { Author = "����", Category = "System", Description = "Ȩ����ģ��. �ṩ���û���¼, Ȩ�����õȽ��洦��", ModuleType = "ZxdFramework.Membership.UI.MembershipModule, ZxdFramework.Silverlight.Membership.UI, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", ModuleName = "MembershipModule", Ref = "ZxdFramework.Silverlight.Membership.UI.xap", InitializationMode = InitializationMode.WhenAvailable, DependsOn = new []{ "shell" } } } }; "ModuleFileRepository".GetInstance<IModuleFileRepository>().Add(moduleFile); }
/// <summary> /// �ϴ�����ģ�� /// </summary> /// <param name="modulefile">The modulefile.</param> /// <returns></returns> public bool UploadModuleFile(ModuleFile modulefile) { //modulefile.Save(); ModuleFileRepository.Add(modulefile); return true; }
public void InitModules() { var moduleFile = new ModuleFile { FileName = "ZxdFramework.Silverlight.Shell.UI.xap", UploadUser = "******", ModuleList = new List<ModuleInfo> { new ModuleInfo { Author = "����", Category = "System", Description = "���������ʾģ��", ModuleType = "ZxdFramework.Silverlight.Shell.UI.ShellModule, ZxdFramework.Silverlight.Shell.UI, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", ModuleName = "shell", Ref = "ZxdFramework.Silverlight.Shell.UI.xap", InitializationMode = InitializationMode.WhenAvailable } } }; "ModuleFileRepository".GetInstance<IModuleFileRepository>().Add(moduleFile); AddMembershipModule(); AddSystemManagerModule(); }
/// <summary> /// �ϴ�ģ����·�����ģ����Ϣ /// </summary> /// <param name="moduleFile">The module file.</param> /// <param name="completed">The completed.</param> public void UploadModuleFile(ModuleFile moduleFile, ServiceCompleted<bool> completed) { var @event = SentRequestEvent.CreateRequestEvent("Service/System.json/UploadModuleFile", moduleFile); @event.Result = (a, b) => completed.Invoke(b.GetPostData<bool>(), @event); _eventAggregator.Publish(@event); }
public void WriteMod() { LoggingManager.SendMessage("ModCreator - Creating new mod..."); ModManager.GameDirectory = m_sBaseModulePath.SubstringBeforeLast('\\'); var baseModule = new ModuleFile(m_sBaseModulePath); baseModule.Close(); if (!baseModule.HasSection("attrib:common")) { UIHelper.ShowError( "The selected base module file " + baseModule.FileName + " does not have a [attrib:common] section! Fix it first!"); return; } if (!baseModule.HasSection("data:common")) { UIHelper.ShowError( "The selected module file " + baseModule.FileName + " does not have a [data:common] section! Fix it first!"); return; } if (!baseModule.HasSection("global")) { UIHelper.ShowError( "The selected module file " + baseModule.FileName + " does not have a [global] section! Fix it first!"); return; } string modulePath = ModManager.GameDirectory + m_sModName + ".module"; if (File.Exists(modulePath)) { if ( UIHelper.ShowYNQuestion("Warning", "There already exists a module file with the specified name " + m_sModName + ".module. Overwrite it?") == DialogResult.No) { UIHelper.ShowError("Mod creation failed!"); return; } } LoggingManager.SendMessage("ModCreator - Generating module file for new mod"); ModuleFile newMod = baseModule.GClone(); var globalSection = (ModuleFile.ModuleSectionKeyValue)newMod["global"]; globalSection["Name"] = m_sModName; globalSection["UIName"] = m_sDisplayedModName; globalSection["ModVersion"] = m_sModVersion; globalSection["ModFolder"] = m_sModName; globalSection["Description"] = m_sModDescription; globalSection["UCSBaseIndex"] = m_uUCSBaseIndex.ToString(); var attribSection = (ModuleFile.ModuleSectionFileList)newMod["attrib:common"]; attribSection.AddFolder(m_sModName + "\\DataAttrib", true); Directory.CreateDirectory(ModManager.GameDirectory + m_sModName + "\\DataAttrib"); var dataSection = (ModuleFile.ModuleSectionFileList)newMod["data:common"]; dataSection.AddFolder(m_sModName + "\\Data", true); Directory.CreateDirectory(ModManager.GameDirectory + m_sModName + "\\Data"); if (m_bRepackAttribArchive) { string attribArchivePath = ModManager.GameDirectory + "GameAssets\\Archives\\GameAttrib.sga"; string newArchivePath = m_sModName + "\\Archives\\GameAttrib_orig.sga"; if (!File.Exists(attribArchivePath)) { UIHelper.ShowError("Tried to repack GameAttrib.sga but could not find it! Search at: " + attribArchivePath); } else { if (RepackAttribArchive(attribArchivePath)) { attribSection.RemoveArchive("GameAssets\\Archives\\GameAttrib.sga"); attribSection.AddArchive(newArchivePath, true); } else UIHelper.ShowError("Failed to repack GameAttrib.sga."); } } newMod.WriteDataTo(modulePath); ModulePath = modulePath; LoggingManager.SendMessage("ModCreator - New mod successfully created!"); }
private static void AddArchiveToSection(ModuleFile moduleFile, string sectionName, string archivePath) { ModuleFile.ModuleSectionFileList moduleSection; if (!moduleFile.HasSection(sectionName)) { moduleSection = new ModuleFile.ModuleSectionFileList(sectionName); moduleFile.AddSection(moduleSection); } else moduleSection = moduleFile[sectionName] as ModuleFile.ModuleSectionFileList; moduleSection.AddArchive(archivePath, true); }
// Todo: clean up this method! it's a mess! /// <exception cref="CopeDoW2Exception">The global section of the selected module file is invalid!</exception> static public void LoadModule(string path) { if (IsAnythingLoaded) CloseAll(); LoggingManager.SendMessage("ModManager - Loading module file " + path); GameDirectory = path.SubstringBeforeLast('\\', true); DateTime t1 = DateTime.Now; ModuleFile = new ModuleFile(path); // get basic mod information from module file try { ModAttribDirectory = path.SubstringBeforeLast('\\', true) + ((ModuleFile.ModuleSectionFileList) ModuleFile["attrib:common"]).GetFolderByIndex(0) + '\\'; ModDataDirectory = path.SubstringBeforeLast('\\', true) + ((ModuleFile.ModuleSectionFileList) ModuleFile["data:common"]).GetFolderByIndex(0) + '\\'; var globalSection = ModuleFile["global"] as ModuleFile.ModuleSectionKeyValue; if (globalSection != null) { ModName = globalSection["Name"]; s_sModFolder = globalSection["ModFolder"]; if (globalSection.KeyExists("UCSBaseIndex")) UCSManager.NextIndex = uint.Parse(globalSection["UCSBaseIndex"]); } else throw new CopeDoW2Exception("The global section of the selected module file is invalid!"); } catch (CopeDoW2Exception e) { LoggingManager.SendError("ModManager - Error loading module file: " + e.Message); LoggingManager.HandleException(e); UIHelper.ShowError("Error loading module file " + path.SubstringAfterLast('\\') + ": " + e.Message + ". See log file for more information."); ModuleFile.Close(); if (LoadingFailed != null) LoadingFailed(); return; } if (ModAttribDirectory == ModDataDirectory) { LoggingManager.SendError( "ModManager - The data:common directory and the attrib:common directory of the mod overlap! May cause serious trouble!"); UIHelper.ShowError( "The data:common directory and the attrib:common directory of the mod overlap! This tool does NOT support such module files." + "Please correct the module file before loading it, read the user guide for help."); ModuleFile.Close(); if (LoadingFailed != null) LoadingFailed(); return; } // load mod data if (ModDataArchives == null) ModDataArchives = new List<SGAFile>(); else ModDataArchives.Clear(); if (ModAttribArchives == null) ModAttribArchives = new List<SGAFile>(); else ModAttribArchives.Clear(); LoggingManager.SendMessage("ModManager - Loading mod resources"); List<SGAFile> currentArchives; foreach (ModuleFile.ModuleSection ms in ModuleFile) { if (ms is ModuleFile.ModuleSectionFileList && ms.SectionName == "attrib:common") { currentArchives = ModAttribArchives; } else if (ms is ModuleFile.ModuleSectionFileList && ms.SectionName == "data:common") { currentArchives = ModDataArchives; } else continue; var tmp = (ModuleFile.ModuleSectionFileList)ms; for (int i = 0; i < tmp.ArchiveCount; i++) { if (!File.Exists(ModuleFile.FilePath.SubstringBeforeLast('\\', true) + tmp.GetArchiveByIndex(i))) continue; try { currentArchives.Add( new SGAFile(ModuleFile.FilePath.SubstringBeforeLast('\\', true) + tmp.GetArchiveByIndex(i), FileAccess.Read, FileShare.Read)); } catch (Exception e) { LoggingManager.SendError("ModManager - Error loading SGA-file '" + tmp.GetArchiveByIndex(i) + "':" + e.Message); LoggingManager.HandleException(e); UIHelper.ShowError("Error loading SGA-files: " + e.Message + " See log file for more information."); ModuleFile.Close(); if (LoadingFailed != null) LoadingFailed(); return; } } } ModuleFile.Close(); DateTime t2 = DateTime.Now; LoggingManager.SendMessage("ModManager - Module file successfully loaded in " + (t2 - t1).TotalSeconds + " seconds"); FileManager.FillTrees(); TryToGetKeyProvider(); if (ModLoaded != null) ModLoaded(); }