private void btCreateEXE_Click(object sender, RoutedEventArgs e) { try { string sTempFile = Path.Combine(Environment.ExpandEnvironmentVariables("%TEMP%"), Path.GetRandomFileName() + ".json"); SaveAsJSON(sTempFile); string jSW = File.ReadAllText(sTempFile); File.Delete(sTempFile); CreateExe oExe = new CreateExe(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, tbProductName.Text + "_" + tbVersion.Text + "_" + tbArchitecture.Text + "_setup.exe")); if (imgIcon.Tag != null) { oExe.Icon = imgIcon.Tag as byte[]; } oExe.Sources.Add(Properties.Resources.Source.Replace("RZRZRZ", tbProductName.Text)); oExe.Sources.Add(Properties.Resources.RZUpdate); oExe.Sources.Add(Properties.Resources.RZRestApi); oExe.Sources.Add(Properties.Resources.Assembly.Replace("RZRZRZ", tbProductName.Text).Replace("[assembly: AssemblyFileVersion(\"1.0.0.0\")]", "[assembly: AssemblyFileVersion(\"" + tbVersion.Text + "\")]")); System.Resources.ResourceWriter writer = new System.Resources.ResourceWriter("Resources.resx"); writer.AddResource("SW.json", jSW); writer.Generate(); writer.Close(); oExe.cp.EmbeddedResources.Add("Resources.resx"); if (!oExe.Compile()) { MessageBox.Show("Failed to create .Exe", "Error", MessageBoxButton.OK, MessageBoxImage.Error); } File.Delete("Resources.resx"); } catch { } }
/// <summary> /// Gets resource of additional metadata for each of declared symbol. /// </summary> ResourceDescription SourceMetadataResource() { return(new ResourceDescription(".source.metadata.resources", () => { var stream = new MemoryStream(); var table = this.SourceSymbolCollection; var writer = new System.Resources.ResourceWriter(stream); foreach (var r in table.AllRoutines) { var metadata = r.GetSymbolMetadataResource(); if (!string.IsNullOrEmpty(metadata)) { var id = r.ContainingType.GetFullName() + "." + r.MetadataName; writer.AddResource(id, metadata); } } // writer.Generate(); stream.Position = 0; return stream; }, isPublic: true)); }
public ActionResult Create(ResourceLocalization model) { if (!((CustomPrincipal)User).CanAddAdminFeature("UserInterfaceSetting")) { return(RedirectToAction("Index", "Home")); } if (ModelState.IsValid) { var filepath = System.Web.HttpContext.Current.Server.MapPath("~/ResourceFiles/"); var fileexist = System.IO.File.Exists(filepath + model.Name + ".resx"); if (fileexist) { System.IO.File.Delete(filepath + model.Name + ".resx"); //remove old file } using (System.Resources.ResourceWriter resxSet = new System.Resources.ResourceWriter(filepath + model.Name + ".resx")) { foreach (var _model in model.columnmapping) { resxSet.AddResource(_model.source, _model.target); //Create new file } } var myConfiguration = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~"); myConfiguration.AppSettings.Settings["ResourceLocalizationChange"].Value = Convert.ToString(DateTime.UtcNow.Ticks); myConfiguration.Save(); } return(RedirectToAction("Index", "ResourceLocalization")); }
protected void GenerateEmbeddedResource(string path, IResource [] resourceSet) { using (var stream = File.Open(path, FileMode.Create, FileAccess.Write)) using (var writer = new System.Resources.ResourceWriter(stream)) foreach (var resource in resourceSet) { writer.AddResource(resource); } }
protected void AddResourceKey(Type resourceType, string resourceKey, string value) { string pathRoot = System.IO.Path.GetDirectoryName(new System.Uri(System.Reflection.Assembly.GetCallingAssembly().CodeBase).LocalPath); string fileName = string.Format("{0}.{1}.resx", resourceType.Name, this.CurrentCultureISO); fileName = System.IO.Path.Combine(pathRoot, fileName); using (var rw = new System.Resources.ResourceWriter(fileName)) { rw.AddResource(resourceKey, value); } }
private void _addXmlResource(string key, string xml) { //string path = System.IO.Path.GetFullPath(@".\" + resName); using (System.Resources.IResourceWriter writer = new System.Resources.ResourceWriter(/*Properties.Resources.ResourceManager.BaseName*/ _path)) { byte[] buffer = Encoding.Unicode.GetBytes(xml); writer.AddResource(key.ToLower(), buffer); writer.Generate(); } }
public void Translate(string infile, string outfile) { var writer = new System.Resources.ResourceWriter(outfile); foreach (var resource in MSBuildResXReader.GetResourcesFromFile(infile, pathsRelativeToBasePath: true)) { resource.AddTo(writer); } writer.Generate(); writer.Close(); }
protected void AddResourceKeys(Type resourceType, CultureInfo culture, IEnumerable <Tuple <string, string> > keyValues) { string pathRoot = System.IO.Path.GetDirectoryName(new System.Uri(System.Reflection.Assembly.GetCallingAssembly().CodeBase).LocalPath); string fileName = string.Format("{0}.{1}.resx", resourceType.Name, culture); fileName = System.IO.Path.Combine(pathRoot, fileName); using (var rw = new System.Resources.ResourceWriter(fileName)) { foreach (var keyValue in keyValues) { rw.AddResource(keyValue.Item1, keyValue.Item2); } } }
public void Translate(string infile, string outfile) { var writer = new System.Resources.ResourceWriter(outfile); using (var inf = File.OpenText(infile)) { var reader = new mono.ResXResourceReader(inf); foreach (DictionaryEntry d in reader) { writer.AddResource(d.Key.ToString(), d.Value); } } writer.Generate(); writer.Close(); }
internal ResWriterData( ResourceWriter resWriter, Stream memoryStream, String strName, String strFileName, String strFullFileName, ResourceAttributes attribute) { m_resWriter = resWriter; m_memoryStream = memoryStream; m_strName = strName; m_strFileName = strFileName; m_strFullFileName = strFullFileName; m_nextResWriter = null; m_attribute = attribute; }
public static void CreateResourceFile(string filename, Dictionary<string, object> data) { System.IO.MemoryStream memStream = new System.IO.MemoryStream(); System.Resources.ResourceWriter rw = new System.Resources.ResourceWriter(memStream); System.Collections.IDictionaryEnumerator dictEnum = data.GetEnumerator(); while (dictEnum.MoveNext()) { if(dictEnum.Value != null) rw.AddResource(dictEnum.Key.ToString(), dictEnum.Value); } rw.Generate(); byte[] resourceBytes = FileUtils.GetStreamBytes(memStream); resourceBytes = Utilities.CryptoUtils.Encrypt(resourceBytes, "asdlfa9sd879*Lasldflkajsdf243o8729"); // Zip the bytes /*MemoryStream zippedMemStream = new MemoryStream(); System.IO.Compression.GZipStream zipStream = new System.IO.Compression.GZipStream(zippedMemStream, System.IO.Compression.CompressionMode.Compress); byte[] resourceBytes = FileUtils.GetStreamBytes(memStream); zipStream.Write(resourceBytes, 0, resourceBytes.Length); // Now Encrypt the resource file zippedMemStream.Position = 0; resourceBytes = Utilities.CryptoUtils.Encrypt(FileUtils.GetStreamBytes(zippedMemStream), "asdlfa9sd879*Lasldflkajsdf243o8729"); zippedMemStream.Close(); zippedMemStream.Dispose();*/ memStream.Close(); memStream.Dispose(); rw.Close(); rw.Dispose(); File.WriteAllBytes(filename, resourceBytes); }
/// <summary> /// Gets resource of additional metadata for each of declared symbol. /// </summary> ResourceDescription SourceMetadataResource() { return(new ResourceDescription(".source.metadata.resources", () => { var table = this.SourceSymbolCollection; var symbols = // global functions table.GetFunctions().OfType <SourceRoutineSymbol>() // classes, interfaces, traits .Concat <Symbol>(table.GetDeclaredTypes()) // type members - properties, constants .Concat <Symbol>(table.GetDeclaredTypes().SelectMany(t => t.GetMembers().Where(m => m is SourceRoutineSymbol || m is SourceFieldSymbol))); var resources = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase); foreach (var symbol in symbols) { var metadata = symbol.GetSymbolMetadataResource(); if (!string.IsNullOrEmpty(metadata)) { var id = symbol is SourceTypeSymbol type ? type.GetFullName() : symbol.ContainingType.GetFullName() + "." + symbol.MetadataName; resources[id] = metadata; } } var stream = new MemoryStream(); var writer = new System.Resources.ResourceWriter(stream); foreach (var pair in resources) { writer.AddResource(pair.Key, pair.Value); } // writer.Generate(); stream.Position = 0; return stream; }, isPublic: true)); }
internal ResWriterData( ResourceWriter resWriter, Stream memoryStream, String strName, String strFileName, String strFullFileName, ResourceAttributes attribute) { m_resWriter = resWriter; m_memoryStream = memoryStream; m_strName = strName; m_strFileName = strFileName; m_strFullFileName = strFullFileName; m_nextResWriter = null; m_attribute = attribute; }
private ParsedSource ParseFile( TextWriter consoleOutput, PhpParseOptions parseOptions, PhpParseOptions scriptParseOptions, ref bool hadErrors, CommandLineSourceFile file, ErrorLogger errorLogger) { if (file.Path.IsPharFile()) { // phar file archive var phar = Devsense.PHP.Phar.PharFile.OpenPharFile(file.Path); // TODO: report exception // treat the stub as a regular source code: var stub = PhpSyntaxTree.ParseCode(SourceText.From(GetPharStub(phar), Encoding.UTF8), parseOptions, scriptParseOptions, file.Path); // TODO: ConcurrentBuild -> Parallel var prefix = PhpFileUtilities.NormalizeSlashes(PhpFileUtilities.GetRelativePath(file.Path, Arguments.BaseDirectory)); var trees = new List <PhpSyntaxTree>(); var content = new List <Devsense.PHP.Phar.Entry>(); foreach (var entry in phar.Manifest.Entries.Values) { var entryName = PhpFileUtilities.NormalizeSlashes(entry.Name); if (entry.IsCompileEntry()) { var tree = PhpSyntaxTree.ParseCode(SourceText.From(entry.Code, Encoding.UTF8), parseOptions, scriptParseOptions, prefix + "/" + entryName); tree.PharStubFile = stub; trees.Add(tree); } else { content.Add(entry); } } // create resource file var resources = new ResourceDescription($"phar://{prefix}.resources", () => { var stream = new MemoryStream(); var writer = new System.Resources.ResourceWriter(stream); foreach (var entry in content) { var entryName = PhpFileUtilities.NormalizeSlashes(entry.Name); writer.AddResource(entryName, entry.Code); } // writer.Generate(); stream.Position = 0; return(stream); }, isPublic: true); // TODO: report errors if any return(new ParsedSource { SyntaxTree = stub, Manifest = phar.Manifest, Trees = trees, Resources = resources, }); } else { // single source file var diagnosticInfos = new List <DiagnosticInfo>(); var content = TryReadFileContent(file, diagnosticInfos); if (diagnosticInfos.Count != 0) { ReportErrors(diagnosticInfos, consoleOutput, errorLogger); hadErrors = true; } PhpSyntaxTree result = null; if (content != null) { result = PhpSyntaxTree.ParseCode(content, parseOptions, scriptParseOptions, file.Path); } if (result != null && result.Diagnostics.HasAnyErrors()) { ReportErrors(result.Diagnostics, consoleOutput, errorLogger); hadErrors = true; } return(new ParsedSource { SyntaxTree = result }); } }
/********************************************** * * Define embedded managed resource to be stored in this module * * **********************************************/ /// <include file='doc\ModuleBuilder.uex' path='docs/doc[@for="ModuleBuilder.DefineResource1"]/*' /> public IResourceWriter DefineResource( String name, String description, ResourceAttributes attribute) { CodeAccessPermission.DemandInternal(PermissionType.ReflectionEmit); try { Enter(); BCLDebug.Log("DYNIL","## DYNIL LOGGING: ModuleBuilder.DefineResource( " + name + ")"); if (IsTransient()) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_BadResourceContainer")); if (name == null) throw new ArgumentNullException("name"); if (name.Length == 0) throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "name"); Assembly assembly = this.Assembly; if (assembly is AssemblyBuilder) { AssemblyBuilder asmBuilder = (AssemblyBuilder)assembly; if (asmBuilder.IsPersistable()) { asmBuilder.m_assemblyData.CheckResNameConflict(name); MemoryStream stream = new MemoryStream(); ResourceWriter resWriter = new ResourceWriter(stream); ResWriterData resWriterData = new ResWriterData( resWriter, stream, name, String.Empty, String.Empty, attribute); // chain it to the embedded resource list resWriterData.m_nextResWriter = m_moduleData.m_embeddedRes; m_moduleData.m_embeddedRes = resWriterData; return resWriter; } else { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_BadResourceContainer")); } } else { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_BadResourceContainer")); } } finally { Exit(); } }
private IResourceWriter DefineResourceNoLock(String name, String description, ResourceAttributes attribute) { // Define embedded managed resource to be stored in this module if (IsTransient()) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_BadResourceContainer")); if (name == null) throw new ArgumentNullException("name"); if (name.Length == 0) throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "name"); Assembly assembly = this.Assembly; if (assembly is AssemblyBuilder) { AssemblyBuilder asmBuilder = (AssemblyBuilder)assembly; if (asmBuilder.IsPersistable()) { asmBuilder.m_assemblyData.CheckResNameConflict(name); MemoryStream stream = new MemoryStream(); ResourceWriter resWriter = new ResourceWriter(stream); ResWriterData resWriterData = new ResWriterData( resWriter, stream, name, String.Empty, String.Empty, attribute); // chain it to the embedded resource list resWriterData.m_nextResWriter = m_moduleData.m_embeddedRes; m_moduleData.m_embeddedRes = resWriterData; return resWriter; } else { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_BadResourceContainer")); } } else { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_BadResourceContainer")); } }
// The method that is called to invoke our task. public override bool Execute() { if (InputFiles == null) { return(true); } var outCodeItems = new List <TaskItem>(); var outResItems = new List <TaskItem>(); string generatorName = typeof(JsonResourceGenerator).FullName; string generatorVersion = typeof(JsonResourceGenerator).GetTypeInfo().Assembly.GetName().Version.ToString(); // loop over all the .resj files we were given foreach (var iFile in InputFiles) { var fn = Path.GetFileNameWithoutExtension(iFile.ItemSpec); var culturePart = Path.GetExtension(fn); var hasCulture = false; if (culturePart?.Length > 1) { culturePart = culturePart.Substring(1); hasCulture = Culture.IsValidCulture(culturePart); } var fileDir = Path.GetDirectoryName(iFile.ItemSpec); var filePath = iFile.ItemSpec; var logger = new FileErrorLogger(this, filePath); // load the Json from the file var text = File.ReadAllText(filePath); var json = new JsonReader(new StringReader(text), logger.JsonError); var doc = JsonDocument.Load(json); if (doc.RootNode == null) { logger.ParseError("Failed to parse json text.", doc); continue; } if (doc.RootNode.NodeType != JsonNodeType.Object) { logger.ParseError("Expected object as root node.", doc.RootNode); continue; } var root = (JsonObject)doc.RootNode; var resName = iFile.GetMetadata("ResourceName"); if (string.IsNullOrEmpty(resName)) { resName = Path.GetFileNameWithoutExtension(iFile.ItemSpec); } var resourceName = resName + ".resources"; Directory.CreateDirectory(OutputPath); // write the generated C# code and resources file. if (!hasCulture) { var codeFile = Path.Combine(OutputPath, iFile.ItemSpec + ".g.cs"); var access = iFile.GetMetadata("AccessModifier"); var noCodeGen = StringComparer.OrdinalIgnoreCase.Equals(access, AccessNoCodeGen); if (!noCodeGen) { var isPublic = StringComparer.OrdinalIgnoreCase.Equals(access, AccessPublic); var ns = iFile.GetMetadata("Namespace"); string className = Path.GetFileNameWithoutExtension(iFile.ItemSpec); outCodeItems.Add(new TaskItem(codeFile)); Directory.CreateDirectory(Path.GetDirectoryName(codeFile)); using (var oStream = new FileStream(codeFile, FileMode.Create)) using (var w = new StreamWriter(oStream)) { if (!string.IsNullOrEmpty(ns)) { w.WriteLine($"namespace {ns} {{"); w.WriteLine(); } // very simplistic resource accessor class mostly duplicated from resx output. w.Write($@"using global::System.Reflection; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> [global::System.Diagnostics.DebuggerNonUserCode()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute(""{generatorName}"", ""{generatorVersion}"")] {(isPublic ? "public " : string.Empty)}static partial class {className} {{ static global::System.Resources.ResourceManager rm; static global::System.Globalization.CultureInfo resourceCulture; static global::System.Resources.ResourceManager ResourceManager {{ get {{ if (object.ReferenceEquals(rm, null)) {{ rm = new global::System.Resources.ResourceManager(""{resName}"", typeof({className}).GetTypeInfo().Assembly); }} return rm; }} }} static global::System.Globalization.CultureInfo Culture {{ get {{ return resourceCulture; }} set {{ resourceCulture = value; }} }} "); foreach (var section in root.Keys) { var value = root[section]; switch (section) { case "Strings": case "Files": if (value.NodeType == JsonNodeType.Object) { var obj = (JsonObject)value; foreach (var item in obj) { string comment = null; if (section == "Strings") { // https://stackoverflow.com/a/19498780 string stringValue = new XText(((JsonString)item.Value).Value).ToString(); comment = $"Looks up a localized string similar to {stringValue.Substring(0, Math.Min(stringValue.Length, 100))}"; } else if (section == "Files") { comment = $"Looks up a {item.Key} text file"; } if (comment != null) { IEnumerable <string> commentLines = comment.Split(new[] { "\r", "\n", "\r\n" }, StringSplitOptions.None); w.Write($@" /// <summary> /// {string.Join(Environment.NewLine + " /// ", commentLines)}. /// </summary>"); } w.Write($@" public static string {item.Key} {{ get {{ return ResourceManager.GetString(""{item.Key}"", resourceCulture); }} }} "); } } else { //logger.ParseError("Expected Json object.", value); } break; default: //logger.ParseError("Unexpected property.", value); break; } } w.WriteLine("}"); if (!string.IsNullOrEmpty(ns)) { w.WriteLine(); w.WriteLine("}"); } } } } // prepare the generated files we are about to write. var resFile = Path.Combine(OutputPath, resourceName); var resItem = new TaskItem(resFile); resItem.SetMetadata("LogicalName", resName + ".resources"); resItem.SetMetadata("ManifestResourceName", resourceName); resItem.SetMetadata("OutputResource", resourceName); resItem.SetMetadata("WithCulture", hasCulture ? "true" : "false"); resItem.SetMetadata("Type", "Non-Resx"); outResItems.Add(resItem); if (hasCulture) { resItem.SetMetadata("Culture", culturePart); } else { } json = new JsonReader(new StringReader(text), logger.JsonError); using (var rw = new System.Resources.ResourceWriter(resFile)) { foreach (var section in root.Keys) { var sectionNode = root[section]; var isFile = false; switch (section) { case "Strings": isFile = false; break; case "Files": isFile = true; break; default: logger.ParseError("Unexpected section.", sectionNode); continue; } if (sectionNode.NodeType != JsonNodeType.Object) { logger.ParseError("Expected json object", sectionNode); continue; } var sectionObj = (JsonObject)sectionNode; foreach (var key in sectionObj.Keys) { var str = sectionObj[key]; if (str.NodeType != JsonNodeType.String) { logger.ParseError("Expected string value", str); continue; } var strVal = (JsonString)str; string txt; if (isFile) { var textFilePath = Path.Combine(fileDir, strVal.Value); if (!File.Exists(textFilePath)) { logger.ParseError("Resource file '" + strVal.Value + "' not found.", str); continue; } try { using (var iStream = File.OpenRead(textFilePath)) using (var reader = new StreamReader(iStream)) { txt = reader.ReadToEnd(); } } catch (Exception e) { logger.ParseError(e.Message, str); continue; } } else { txt = strVal.Value; } // write our string to the resources binary rw.AddResource(key, txt); } } } } // put the artifacts we created in the output properties. OutputCode = outCodeItems.ToArray(); OutputResources = outResItems.ToArray(); return(!hasError); }
protected void bt_Compile_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(tb_Filename.Text)) { ShowMessage("Filename is missing.. !", MessageType.Error); return; } if (string.IsNullOrEmpty(tb_PSSCript.Text)) { ShowMessage("PowerShell script cannot be empty.. !", MessageType.Error); return; } string sPSTest = TestPowerShellSyntax(tb_PSSCript.Text); if (!string.IsNullOrEmpty(sPSTest)) { ShowMessage("Syntax Error:" + sPSTest, MessageType.Error); return; } string sFilename = Environment.ExpandEnvironmentVariables(Server.MapPath("~/App_Data/" + Path.GetRandomFileName().Split('.')[0] + ".exe")); //string sResname = Environment.ExpandEnvironmentVariables(Server.MapPath("~/App_Data/" + Path.GetRandomFileName().Split('.')[0])); //Directory.CreateDirectory(sResname); if (!Directory.Exists(Server.MapPath("~/App_Data"))) { try { Directory.CreateDirectory(Server.MapPath("~/App_Data")); } catch { } } //string sFilename = Environment.ExpandEnvironmentVariables(Server.MapPath("~/App_Data/" + tb_Filename.Text)); string sResname = Environment.ExpandEnvironmentVariables(Server.MapPath("~/App_Data/Resources.resx")); try { File.Delete(sFilename); File.Delete(sResname); } catch { } CreateExe oExe = new CreateExe(sFilename, Server.MapPath("~/Bin")); oExe.cp.CompilerOptions = Environment.ExpandEnvironmentVariables("/win32icon:\"" + Server.MapPath("~/Images/powershell.ico") + "\" /optimize"); oExe.Sources.Add(Properties.Resources.Source); oExe.Sources.Add(Properties.Resources.Assembly); System.Resources.ResourceWriter writer = new System.Resources.ResourceWriter(sResname); writer.AddResource("psCode.ps1", " " + Zip(tb_PSSCript.Text.Trim())); writer.Generate(); writer.Close(); oExe.cp.EmbeddedResources.Add(sResname); if (!oExe.Compile()) { //MessageBox.Show("Failed to create .Exe", "Error", MessageBoxButton.OK, MessageBoxImage.Error); sFilename.ToString(); } //File.Delete(sResname); //Directory.Delete(sResname); Response.ContentType = "application/octet-stream"; Response.AppendHeader("Content-Disposition", "attachment; filename=" + tb_Filename.Text); Response.TransmitFile(sFilename); Response.End(); try { File.Delete(sFilename); File.Delete(sResname); } catch { } }
private void _addNewResource(string key, string value) { System.Resources.IResourceWriter writer = new System.Resources.ResourceWriter(Properties.Resources.ResourceManager.BaseName); writer.AddResource(key, value); writer.Close(); }
// The method that is called to invoke our task. public override bool Execute() { if (InputFiles == null) { return(true); } var outCodeItems = new List <TaskItem>(); var outResItems = new List <TaskItem>(); // loop over all the .resj files we were given foreach (var iFile in InputFiles) { var fn = Path.GetFileNameWithoutExtension(iFile.ItemSpec); var culturePart = Path.GetExtension(fn); var hasCulture = false; if (culturePart?.Length > 1) { culturePart = culturePart.Substring(1); hasCulture = Culture.IsValidCulture(culturePart); } var fileDir = Path.GetDirectoryName(iFile.ItemSpec); var filePath = iFile.ItemSpec; var logger = new FileErrorLogger(this, filePath); // load the Json from the file var text = File.ReadAllText(filePath); var json = new JsonReader(new StringReader(text), logger.JsonError); var doc = JsonDocument.Load(json); if (doc.RootNode == null) { logger.ParseError("Failed to parse json text.", doc); continue; } if (doc.RootNode.NodeType != JsonNodeType.Object) { logger.ParseError("Expected object as root node.", doc.RootNode); continue; } var root = (JsonObject)doc.RootNode; var resName = iFile.GetMetadata("ResourceName"); if (string.IsNullOrEmpty(resName)) { resName = Path.GetFileNameWithoutExtension(iFile.ItemSpec); } var resourceName = resName + ".resources"; Directory.CreateDirectory(OutputPath); // write the generated C# code and resources file. if (!hasCulture) { var codeFile = Path.Combine(OutputPath, iFile.ItemSpec + ".g.cs"); var access = iFile.GetMetadata("AccessModifier"); var noCodeGen = StringComparer.OrdinalIgnoreCase.Equals(access, AccessNoCodeGen); if (!noCodeGen) { var isPublic = StringComparer.OrdinalIgnoreCase.Equals(access, AccessPublic); var ns = iFile.GetMetadata("Namespace"); string className = Path.GetFileNameWithoutExtension(iFile.ItemSpec); outCodeItems.Add(new TaskItem(codeFile)); Directory.CreateDirectory(Path.GetDirectoryName(codeFile)); using (var oStream = new FileStream(codeFile, FileMode.Create)) using (var w = new StreamWriter(oStream)) { if (!string.IsNullOrEmpty(ns)) { w.WriteLine("namespace " + ns + " {"); } // very simplistic resource accessor class mostly duplicated from resx output. w.WriteLine("using global::System.Reflection;"); if (isPublic) { w.Write("public "); } w.WriteLine("static partial class " + className + " { "); w.WriteLine("static global::System.Resources.ResourceManager rm;"); w.WriteLine("static global::System.Globalization.CultureInfo resourceCulture;"); w.WriteLine("static global::System.Resources.ResourceManager ResourceManager {"); w.WriteLine("get {"); w.WriteLine("if(object.ReferenceEquals(rm, null)) {"); w.WriteLine("rm = new global::System.Resources.ResourceManager(\"" + resName + "\", typeof(" + className + ").GetTypeInfo().Assembly);"); w.WriteLine("}"); w.WriteLine("return rm;"); w.WriteLine("}"); w.WriteLine("}"); w.WriteLine("static global::System.Globalization.CultureInfo Culture {"); w.WriteLine("get {"); w.WriteLine("return resourceCulture;"); w.WriteLine("}"); w.WriteLine("set {"); w.WriteLine("resourceCulture = value;"); w.WriteLine("}"); w.WriteLine("}"); foreach (var section in root.Keys) { var value = root[section]; switch (section) { case "Strings": case "Files": if (value.NodeType == JsonNodeType.Object) { var obj = (JsonObject)value; foreach (var key in obj.Keys) { w.WriteLine("public static string " + key + " {"); w.WriteLine("get {"); w.WriteLine("return ResourceManager.GetString(\"" + key + "\", resourceCulture);"); w.WriteLine("}"); w.WriteLine("}"); } } else { //logger.ParseError("Expected Json object.", value); } break; default: //logger.ParseError("Unexpected property.", value); break; } } w.WriteLine("}"); if (!string.IsNullOrEmpty(ns)) { w.WriteLine("}"); } } } } // prepare the generated files we are about to write. var resFile = Path.Combine(OutputPath, resourceName); var resItem = new TaskItem(resFile); resItem.SetMetadata("LogicalName", resName + ".resources"); resItem.SetMetadata("ManifestResourceName", resourceName); resItem.SetMetadata("OutputResource", resourceName); resItem.SetMetadata("WithCulture", hasCulture ? "true" : "false"); resItem.SetMetadata("Type", "Non-Resx"); outResItems.Add(resItem); if (hasCulture) { resItem.SetMetadata("Culture", culturePart); } else { } json = new JsonReader(new StringReader(text), logger.JsonError); using (var rw = new System.Resources.ResourceWriter(resFile)) { foreach (var section in root.Keys) { var sectionNode = root[section]; var isFile = false; switch (section) { case "Strings": isFile = false; break; case "Files": isFile = true; break; default: logger.ParseError("Unexpected section.", sectionNode); continue; } if (sectionNode.NodeType != JsonNodeType.Object) { logger.ParseError("Expected json object", sectionNode); continue; } var sectionObj = (JsonObject)sectionNode; foreach (var key in sectionObj.Keys) { var str = sectionObj[key]; if (str.NodeType != JsonNodeType.String) { logger.ParseError("Expected string value", str); continue; } var strVal = (JsonString)str; string txt; if (isFile) { var textFilePath = Path.Combine(fileDir, strVal.Value); if (!File.Exists(textFilePath)) { logger.ParseError("Resource file '" + strVal.Value + "' not found.", str); continue; } try { using (var iStream = File.OpenRead(textFilePath)) using (var reader = new StreamReader(iStream)) { txt = reader.ReadToEnd(); } } catch (Exception e) { logger.ParseError(e.Message, str); continue; } } else { txt = strVal.Value; } // write our string to the resources binary rw.AddResource(key, txt); } } } } // put the artifacts we created in the output properties. OutputCode = outCodeItems.ToArray(); OutputResources = outResItems.ToArray(); return(!hasError); }
public void writeToUnknownSink(string key, string str) { System.Resources.ResourceWriter writer = new System.Resources.ResourceWriter(key); writer.AddResource(key, str); }