예제 #1
0
 private string GetResourceKey(string resourceFileName, string key)
 {
     System.Resources.ResXResourceReader rsxr = null;
     try
     {
         rsxr = new System.Resources.ResXResourceReader(resourceFileName);
         System.Collections.DictionaryEntry d = default(System.Collections.DictionaryEntry);
         foreach (DictionaryEntry d_loopVariable in rsxr)
         {
             if (d_loopVariable.Key.ToString().ToLower().Equals(key.ToLower()))
             {
                 return(d_loopVariable.Key.ToString());
             }
         }
         return(null);
     }
     catch (Exception e)
     {
         string logMessage = $"Unable to find key {key} in resource file: {resourceFileName}.";
         logger.Warn(logMessage);
         throw new Exception(logMessage, e);
     }
     finally
     {
         if (rsxr != null)
         {
             rsxr.Close();
         }
     }
 }
예제 #2
0
        public static void ReadRessourceFile()
        {
            //Requires Assembly System.Windows.Forms '
            string filename = @"C:\Program Files\paint.net\resx\PaintDotNet.Strings.3.resx";

            filename = "/root/github/EntityFrameworkCore/src/EFCore.Sqlite.Core/Properties/SqliteStrings.resx";
            filename = "/root/github/ExpressProfiler/ExpressProfiler/MainForm.resx";
            System.Resources.ResXResourceReader rsxr = new System.Resources.ResXResourceReader(filename);

            // Iterate through the resources and display the contents to the console. '
            foreach (System.Collections.DictionaryEntry d in rsxr)
            {
                if (d.Key != null)
                {
                    System.Console.Write(d.Key.ToString() + ":\t");
                }

                if (d.Value != null)
                {
                    System.Console.Write(d.Value.ToString());
                }

                System.Console.WriteLine();
            }

            //Close the reader. '
            rsxr.Close();
        }
예제 #3
0
        public static void RenderJsResource(string RsPath,string JsPath)
        {
            //var RsPath = "~//App_GlobalResources//resource1.resx";
            //var JsPath = "~//common//js//abc.js";
            RsPath = HttpContext.Current.Server.MapPath(RsPath);
            JsPath = HttpContext.Current.Server.MapPath(JsPath);
            var script = new StringBuilder();
            using (var resourceReader = new System.Resources.ResXResourceReader(RsPath))
            {
                foreach (DictionaryEntry entry in resourceReader)
                {
                    var key = ZConvert.ToString(entry.Key).Replace('.', '_');
                    var value = ZConvert.ToString(entry.Value);
                    script.Append(",");
                    script.Append(key);
                    script.Append(":");
                    script.Append('"' + value + '"');
                    script.Append("\r\n");
                }
            }

            try
            {
                var str = "var lang = {\r\n " + script.ToString().Trim(',') + "}";
                ZFiles.DeleteFiles(JsPath);
                ZFiles.WriteStrToTxtFile(JsPath, str, FileMode.CreateNew);
            }
            catch
            {

            }
        }
예제 #4
0
        public static void RenderJsResource(string RsPath, string JsPath)
        {
            //var RsPath = "~//App_GlobalResources//resource1.resx";
            //var JsPath = "~//common//js//abc.js";
            RsPath = HttpContext.Current.Server.MapPath(RsPath);
            JsPath = HttpContext.Current.Server.MapPath(JsPath);
            var script = new StringBuilder();

            using (var resourceReader = new System.Resources.ResXResourceReader(RsPath))
            {
                foreach (DictionaryEntry entry in resourceReader)
                {
                    var key   = ZConvert.ToString(entry.Key).Replace('.', '_');
                    var value = ZConvert.ToString(entry.Value);
                    script.Append(",");
                    script.Append(key);
                    script.Append(":");
                    script.Append('"' + value + '"');
                    script.Append("\r\n");
                }
            }

            try
            {
                var str = "var lang = {\r\n " + script.ToString().Trim(',') + "}";
                ZFiles.DeleteFiles(JsPath);
                ZFiles.WriteStrToTxtFile(JsPath, str, FileMode.CreateNew);
            }
            catch
            {
            }
        }
예제 #5
0
        public IntroForm()
        {
            InitializeComponent();

            if (ResourceHelper.ResourceFileExists("Applications"))
            {
                foreach (var item in ResourceHelper.GetFileNames())
                {
                    var listItem = new ListViewItem(item.Substring(0, item.LastIndexOf(".")));
                    AppList.Items.Add(listItem);
                }
            }

            bool resourceFileexists    = System.IO.Directory.Exists(@".\Resources");
            bool applicationResxExists = System.IO.File.Exists(@".\Resources\Applications.resx");

            if (!resourceFileexists)
            {
                System.IO.Directory.CreateDirectory(@".\Resources");
            }

            //if (!applicationResxExists)
            //    System.IO.File.Create(@".\Resources\Applications.resx");

            var resx =
                new System.Resources.ResXResourceReader(@".\Resources\Applications.resx");
        }
 public void AddLanguage(string language, Stream data)
 {
     var dict = new Dictionary<string, string>();
     var reader = new System.Resources.ResXResourceReader(data);
     foreach (System.Collections.DictionaryEntry de in reader)
         dict[(string)de.Key] = (string)de.Value;
     stringStorage[language] = dict;
 }
        private void KGySerializeObjects(object[] referenceObjects, bool compatibilityMode = true, bool checkCompatibleEquality = true, Func <Type, string> typeNameConverter = null, ITypeResolutionService typeResolver = null)
        {
            Console.WriteLine($"------------------KGySoft ResXResourceWriter (Items Count: {referenceObjects.Length}; Compatibility mode: {compatibilityMode})--------------------");
            StringBuilder sb = new StringBuilder();

            using (ResXResourceWriter writer = new ResXResourceWriter(new StringWriter(sb), typeNameConverter)
            {
                CompatibleFormat = compatibilityMode
            })
            {
                int i = 0;
                foreach (object item in referenceObjects)
                {
                    writer.AddResource(i++ + "_" + (item == null ? "null" : item.GetType().Name), item);
                }
            }

            Console.WriteLine(sb.ToString());
            List <object> deserializedObjects = new List <object>();

            using (ResXResourceReader reader = ResXResourceReader.FromFileContents(sb.ToString(), typeResolver))
            {
                foreach (DictionaryEntry item in reader)
                {
                    deserializedObjects.Add(item.Value);
                }
            }

            AssertItemsEqual(referenceObjects, deserializedObjects.ToArray());

#if NETFRAMEWORK
            if (compatibilityMode)
            {
                deserializedObjects.Clear();
                using (SystemResXResourceReader reader = SystemResXResourceReader.FromFileContents(sb.ToString(), typeResolver))
                {
                    try
                    {
                        foreach (DictionaryEntry item in reader)
                        {
                            deserializedObjects.Add(item.Value);
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine($"System serialization failed: {e}");
                        Console.WriteLine("Skipping equality check");
                        return;
                    }
                }

                if (checkCompatibleEquality)
                {
                    AssertItemsEqual(referenceObjects, deserializedObjects.ToArray());
                }
            }
#endif
        }
예제 #8
0
        private void MyDiary_Loaded(object sender, RoutedEventArgs e)
        {
            Colorit();
            string date_string    = DateTime.Now.ToString("yyyy-MM-dd");
            string weekday_string = DateTime.Now.DayOfWeek.ToString();

            this.Label_time.Content = date_string + " " + weekday_string;
            this.diaryBox.Text      = original_text;

            WinChange(0);

            string help_msg = "";

            help_msg += "MyDiary By BlackHand\n";
            help_msg += "o : 打开日记\n";
            help_msg += "c : 更换颜色\n";
            help_msg += "×: 退出";
            Label_helptext.Content = help_msg;

            System.Resources.ResXResourceReader rr = new System.Resources.ResXResourceReader(respath);
            var dict = rr.GetEnumerator();

            while (dict.MoveNext())
            {
                if (dict.Key.ToString() == "FILEPATH")
                {
                    Filepath = dict.Value.ToString();
                }
                if (dict.Key.ToString() == "PASSWORD")
                {
                    pword = dict.Value.ToString();
                }
            }
            rr.Close();

            /*
             * try
             * {
             *  ManageReg();
             * }
             * catch
             * {
             *  MessageBox.Show("请使用管理员权限打开本应用。");
             *  Application.Current.Shutdown();
             * }
             */

            string path = System.IO.Path.GetDirectoryName(Filepath);

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
                FileStream fs = new FileStream(Filepath, FileMode.Append);
                fs.Close();
            }
        }
        public void AddLanguage(string language, Stream data)
        {
            var dict   = new Dictionary <string, string>();
            var reader = new System.Resources.ResXResourceReader(data);

            foreach (System.Collections.DictionaryEntry de in reader)
            {
                dict[(string)de.Key] = (string)de.Value;
            }
            stringStorage[language] = dict;
        }
예제 #10
0
        private void SystemSerializeObjects(object[] referenceObjects, Func <Type, string> typeNameConverter = null, ITypeResolutionService typeResolver = null)
        {
#if !NETCOREAPP2_0
            using (new TestExecutionContext.IsolatedContext())
            {
                Console.WriteLine($"------------------System ResXResourceWriter (Items Count: {referenceObjects.Length})--------------------");
                try
                {
                    StringBuilder sb = new StringBuilder();
                    using (SystemResXResourceWriter writer =
#if NET35 || NETCOREAPP3_0
                               new SystemResXResourceWriter(new StringWriter(sb))
#else
                               new SystemResXResourceWriter(new StringWriter(sb), typeNameConverter)
#endif

                           )
                    {
                        int i = 0;
                        foreach (object item in referenceObjects)
                        {
                            writer.AddResource(i++ + "_" + (item == null ? "null" : item.GetType().Name), item);
                        }
                    }

                    Console.WriteLine(sb.ToString());
                    List <object> deserializedObjects = new List <object>();
                    using (SystemResXResourceReader reader = SystemResXResourceReader.FromFileContents(sb.ToString(), typeResolver))
                    {
                        foreach (DictionaryEntry item in reader)
                        {
                            deserializedObjects.Add(item.Value);
                        }
                    }

                    AssertItemsEqual(referenceObjects, deserializedObjects.ToArray());
                }
                catch (Exception e)
                {
                    Console.WriteLine($"System serialization failed: {e}");
                }
            }
#endif
        }
예제 #11
0
        public void AddLanguageFile(string languageId, string fullFilename)
        {
            using (System.Resources.ResXResourceReader reader =
                new System.Resources.ResXResourceReader(fullFilename))
            {
                reader.UseResXDataNodes = true;
                foreach (DictionaryEntry de in reader)
                {
                    string key = (string)de.Key;
                    if (key.StartsWith(">>") || key.StartsWith("$"))
                        continue;

                    System.Resources.ResXDataNode dataNode = de.Value as System.Resources.ResXDataNode;
                    if (dataNode == null)
                        continue;
                    if (dataNode.FileRef != null)
                        continue;

                    string valueType = dataNode.GetValueTypeName((System.ComponentModel.Design.ITypeResolutionService)null);
                    if (!valueType.StartsWith("System.String, "))
                        continue;

                    object valueObject = dataNode.GetValue((System.ComponentModel.Design.ITypeResolutionService)null);
                    string value = valueObject == null ? "" : valueObject.ToString();

                    ResourceData data;
                    if (!resourceData.TryGetValue(key, out data))
                    {
                        data = new ResourceData(this, key);
                        resourceData.Add(key, data);
                    }
                    if (string.IsNullOrEmpty(data.Comments) && !string.IsNullOrEmpty(dataNode.Comment))
                        data.Comments = dataNode.Comment;

                    if (string.IsNullOrEmpty(languageId))
                        data.BaseData = value;
                    else
                        data.SetData(languageId, value);
                }
            }
        }
        public static Dictionary <string, Font> LoadRess(string FsPath)
        {
            MonoBug();
            System.Resources.ResXResourceReader test     = new System.Resources.ResXResourceReader(FsPath);
            Dictionary <string, Font>           ResXData = new Dictionary <string, Font>();

            // Iterate through the resources and display the contents to the console.
            try
            {
                foreach (DictionaryEntry d in test)
                {
                    ResXData.Add(d.Key.ToString(), (Font)d.Value);
                    //if(!VarGlobal.LessVerbose)Console.WriteLine(d.Key.ToString() + ":\t" + d.Value.ToString());
                }
            }
            catch (Exception Ex)
            {
                if (!VarGlobal.LessVerbose)
                {
                    Console.WriteLine("{0}{1}{1}{2}", Ex.Message, Environment.NewLine, Ex.StackTrace);
                }
                MonoBug();
            }
            try
            {
                if (null != test)
                {
                    test.Close();
                }
            }
            catch (Exception Ex)
            {
                if (!VarGlobal.LessVerbose)
                {
                    Console.WriteLine("{0}{1}{1}{2}", Ex.Message, Environment.NewLine, Ex.StackTrace);
                }
                MonoBug();
            }
            return(ResXData);
        }
예제 #13
0
        public void ParseData()
        {
            string path      = Path.Combine(Files.GetExecutingPath(), "Resources\\TestRes.resx");
            var    refReader = new System.Resources.ResXResourceReader(path, new[] { new AssemblyName("System.Drawing"), new AssemblyName("System") });

            refReader.BasePath = Files.GetExecutingPath();
            ResXResourceReader reader = new ResXResourceReader(path);

            Assert.AreNotEqual(
                refReader.Cast <object>().Count(), // this forces immediate enumeration
                reader.Cast <object>().Count());   // this returns duplicates as separated items

            Assert.AreNotEqual(
                refReader.Cast <object>().Count(), // cached
                reader.Cast <object>().Count());   // second enumeration is cached, though still returns duplicates

            reader = new ResXResourceReader(path)
            {
                AllowDuplicatedKeys = false
            };
            Assert.AreEqual(
                refReader.Cast <object>().Count(), // cached
                reader.Cast <object>().Count());   // duplication is off (not lazy now)
        }
예제 #14
0
        private void CreateResourceFromImage(bool entire)
        {
            Bitmap bitmap = null;

            if (entire)
            {
                bitmap = (Bitmap)(zoomPanControl.ZoomPanImage.Clone());
            }
            else if (HasImageSelection && !entire)
            {
                bitmap = ((Bitmap)zoomPanControl.ZoomPanImage).Clone(partBox, ((Bitmap)zoomPanControl.ZoomPanImage).PixelFormat);
            }
            if (bitmap != null)
            {
                if (Statics.DTE.Solution.IsOpen)
                {
                    foreach (EnvDTE.Project proj in Statics.DTE.Solution.Projects)
                    {
                        if (proj.Name.Contains("Test"))
                        {
                            try
                            {
                                string resFile, resDesignFile, resNameSpace;
                                System.CodeDom.Compiler.CodeDomProvider provider;
                                if (proj.FileName.EndsWith("vbproj"))
                                {
                                    resFile       = Path.GetDirectoryName(proj.FileName) + @"\My Project\Resources.resx";
                                    resDesignFile = Path.GetDirectoryName(proj.FileName) + @"\My Project\Resources.Designer.vb";
                                    vbNS          = resNameSpace = proj.Properties.Item("RootNamespace").Value.ToString();
                                    provider      = new Microsoft.VisualBasic.VBCodeProvider();
                                }
                                else
                                {
                                    resFile       = Path.GetDirectoryName(proj.FileName) + @"\Properties\Resources.resx";
                                    resDesignFile = Path.GetDirectoryName(proj.FileName) + @"\Properties\Resources.Designer.cs";
                                    resNameSpace  = proj.Properties.Item("DefaultNamespace").Value + ".Properties";
                                    provider      = new Microsoft.CSharp.CSharpCodeProvider();
                                }
                                ImageInputForm inputForm = new ImageInputForm();
                                inputForm.ShowDialog();

                                System.Resources.ResXResourceReader reader = new System.Resources.ResXResourceReader(resFile);
                                using (System.Resources.ResXResourceWriter writer = new System.Resources.ResXResourceWriter(resFile + ".new"))
                                {
                                    System.Collections.IDictionaryEnumerator iterator = reader.GetEnumerator();
                                    while (iterator.MoveNext())
                                    {
                                        writer.AddResource(iterator.Key.ToString(), iterator.Value);
                                    }
                                    writer.AddResource(inputForm.Input, bitmap);
                                    writer.Generate();
                                }
                                File.Copy(resFile + ".new", resFile, true);
                                File.Delete(resFile + ".new");
                                string[] unMatched;
                                System.CodeDom.CodeCompileUnit unit = System.Resources.Tools.StronglyTypedResourceBuilder.Create(resFile, "Resources",
                                                                                                                                 resNameSpace,
                                                                                                                                 provider,
                                                                                                                                 true, out unMatched);
                                using (StreamWriter designWriter = new StreamWriter(resDesignFile))
                                {
                                    provider.GenerateCodeFromCompileUnit(unit, designWriter,
                                                                         new System.CodeDom.Compiler.CodeGeneratorOptions());
                                }
                                MessageBox.Show("Image generation succeeded", "Resources Updated");
                                if (entire)
                                {
                                    entireResName = inputForm.Input;
                                    NotifyPropertyChanged("EntireResName");
                                }
                                else
                                {
                                    partResName = inputForm.Input;
                                    NotifyPropertyChanged("PartialResName");
                                }

                                return;
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show("Image generation failed\n" + ex.Message, "Resources Did Not Update");
                                return;
                            }
                        }
                    }
                    MessageBox.Show("You need to have a project open, named *Test*", "Resources Did Not Update");
                    return;
                }
                MessageBox.Show("You need to have a solution open with a project named *Test*", "Resources Did Not Update");
                return;
            }
        }
예제 #15
0
        private void ReadResourceFile(string filename, DataTable stringsTable, string valueColumn, bool isTranslated)
        {
            using(System.Resources.ResXResourceReader reader=new System.Resources.ResXResourceReader(filename))
            {
                reader.UseResXDataNodes=true;

                foreach(DictionaryEntry de in reader)
                {
                    string key=(string)de.Key;

                    if((key.StartsWith(">>")||key.StartsWith("$"))&&key!="$this.Text") continue;

                    System.Resources.ResXDataNode dataNode=de.Value as System.Resources.ResXDataNode;

                    if(dataNode==null) continue;
                    if(dataNode.FileRef!=null) continue;

                    string valueType=dataNode.GetValueTypeName((System.ComponentModel.Design.ITypeResolutionService)null);

                    if(!valueType.StartsWith("System.String, ")) continue;

                    object valueObject=dataNode.GetValue((System.ComponentModel.Design.ITypeResolutionService)null);
                    string value=valueObject==null?"":valueObject.ToString();

                    DataRow[] existingRows=stringsTable.Select("Key = '"+key+"'");

                    if(existingRows.Length==0)
                    {
                        DataRow newRow=stringsTable.NewRow();
                        newRow["Key"]=key;
                        newRow[valueColumn]=value;
                        newRow["Comment"]=dataNode.Comment;
                        newRow["Error"]=false;
                        newRow["Translated"]=isTranslated&&!string.IsNullOrEmpty(value);
                        stringsTable.Rows.Add(newRow);
                    }
                    else
                    {
                        existingRows[0][valueColumn]=value;
                        if(string.IsNullOrEmpty((string)existingRows[0]["Comment"])&&!string.IsNullOrEmpty(dataNode.Comment))
                        {
                            existingRows[0]["Comment"]=dataNode.Comment;
                        }
                        if(isTranslated&&!string.IsNullOrEmpty(value))
                        {
                            existingRows[0]["Translated"]=true;
                        }
                    }
                }
            }
        }
예제 #16
0
        /// <summary>
        /// 创建Orc实例(from Stream)
        /// </summary>
        /// <param name="offsetX"></param>
        /// <param name="offsetY"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <param name="resource"></param>
        /// <returns></returns>
        public static OrcUtil getInstance(int[] offsetX, int offsetY, int width, int height, Stream resource)
        {
            OrcUtil rtn = new OrcUtil();
            rtn.offsetX = offsetX;
            rtn.offsetY = offsetY;
            rtn.width = width;
            rtn.height = height;
            rtn.dict = new Dictionary<Bitmap, String>();

            System.Resources.ResXResourceReader resxReader = new System.Resources.ResXResourceReader(resource);
            IDictionaryEnumerator enumerator = resxReader.GetEnumerator();
            while (enumerator.MoveNext())
            {
                DictionaryEntry entry = (DictionaryEntry)enumerator.Current;
                rtn.dict.Add((Bitmap)entry.Value, (String)entry.Key);
            }
            return rtn;
        }
예제 #17
0
        private void generateResourceMenuItem_Click(object sender, EventArgs e)
        {
            Point origStart = GetOriginalXY(selStartMousePos);
            Point origEnd   = GetOriginalXY(selEndMousePos);

            if (selStartMousePos.X != 0 || selStartMousePos.Y != 0)
            {
                int       top    = origStart.Y < origEnd.Y ? origStart.Y : origEnd.Y;
                int       left   = origStart.X < origEnd.X ? origStart.X : origEnd.X;
                int       width  = Math.Abs(origEnd.X - origStart.X);
                int       height = Math.Abs(origEnd.Y - origStart.Y);
                Rectangle box    = new Rectangle(left, top, width, height);
                Bitmap    bitmap = ((Bitmap)image).Clone(box, ((Bitmap)image).PixelFormat);

                if (Statics.DTE.Solution.IsOpen)
                {
                    foreach (EnvDTE.Project proj in Statics.DTE.Solution.Projects)
                    {
                        if (proj.Name.Contains("Test"))
                        {
                            try
                            {
                                ImageInputForm inputForm = new ImageInputForm();
                                inputForm.ShowDialog();

                                Microsoft.CSharp.CSharpCodeProvider codeProvider = new Microsoft.CSharp.CSharpCodeProvider();
                                string resFile       = Path.GetDirectoryName(proj.FileName) + @"\Properties\Resources.resx";
                                string resDesginFile = Path.GetDirectoryName(proj.FileName) + @"\Properties\Resources.Designer.cs";
                                System.Resources.ResXResourceReader reader = new System.Resources.ResXResourceReader(resFile);
                                using (System.Resources.ResXResourceWriter writer = new System.Resources.ResXResourceWriter(resFile + ".new"))
                                {
                                    System.Collections.IDictionaryEnumerator iterator = reader.GetEnumerator();
                                    while (iterator.MoveNext())
                                    {
                                        writer.AddResource(iterator.Key.ToString(), iterator.Value);
                                    }
                                    writer.AddResource(inputForm.Input, bitmap);
                                    writer.Generate();
                                }
                                File.Copy(resFile + ".new", resFile, true);
                                File.Delete(resFile + ".new");
                                string[] unMatched;
                                System.CodeDom.CodeCompileUnit unit = System.Resources.Tools.StronglyTypedResourceBuilder.Create(resFile, "Resources",
                                                                                                                                 proj.Properties.Item("DefaultNamespace").Value + ".Properties",
                                                                                                                                 codeProvider,
                                                                                                                                 true, out unMatched);
                                using (StreamWriter designWriter = new StreamWriter(resDesginFile))
                                {
                                    codeProvider.GenerateCodeFromCompileUnit(unit, designWriter,
                                                                             new System.CodeDom.Compiler.CodeGeneratorOptions());
                                }
                                MessageBox.Show("Image generation succeeded", "Resources Updated");
                                return;
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show("Image generation failed\n" + ex.Message, "Resources Did Not Update");
                            }
                        }
                    }
                    MessageBox.Show("You need to have a project open, named *Test*", "Resources Did Not Update");
                    return;
                }
                MessageBox.Show("You need to have a solution open with a project named *Test*", "Resources Did Not Update");
                return;
            }
        }
        public string GetJavaScript()
        {
            if(!FileExists())
            {
                return "alert('GlobalResourcesToJavaScript: Can't find the file " + GetResXFilePath() + ".');";
            }

            if (!string.IsNullOrEmpty(JavaScriptObjectName) && File.Exists(GetResXFilePath()))
            {
                var script = new StringBuilder();
                using (System.Resources.ResXResourceReader resourceReader = new System.Resources.ResXResourceReader(GetResXFilePath()))
                {
                    // Start by namespacing the object
                    // If there are no periods in our name, simply start our object definition
                    if(JavaScriptObjectName.Split('.').Length == 1)
                    {
                        script.Append("var " + JavaScriptObjectName + " = { ");
                    }

                    // If there are periods in the name, the developer wants to nest their objects.
                    // This is helpful if there is more than one resource file being translated into javascript.
                    // An example would be the core resource file, with the name 'resources'.
                    // Then, they translate a second resource file, whit the name 'resources.labels'.
                    // This helps the developer to organize their code accordingly.
                    else
                    {
                        var nameparts = JavaScriptObjectName.Split('.');
                        for(var x = 0; x < nameparts.Length; x++)
                        {
                            // If this is the first part of the namespace, let's any existing instances, 
                            // or create a new one if this is the first time it's been instantiated.
                            if(x == 0)
                            {
                                script.Append("var " + nameparts[0] + " = " + nameparts[0] + " || {};\r");
                            }

                            // If this is not the first part...
                            else
                            {
                                // Create the namespace name up to this point.
                                var variable = "";
                                for(var y = 0; y < x + 1; y++)
                                {
                                    if(variable != "") variable += ".";
                                    variable += nameparts[y];
                                }

                                // If this is the last part of the namespace, let's start defining the object.
                                if(x == JavaScriptObjectName.Split('.').Length - 1)
                                {
                                    script.Append(variable + " = { ");
                                }

                                // If there are more parts of the namespace to define, let's set the object and move on.
                                else
                                {
                                    script.Append(variable + " = {};\r");
                                }
                            }
                        }
                    }


                    // Write out the resource items into JSON
                    bool first = true;
                    foreach (DictionaryEntry entry in resourceReader)
                    {
                        if (first)
                            first = false;
                        else
                            script.Append(" , ");
 
                        script.Append(NormalizeVariableName(entry.Key as string));
                        script.Append(":");
                        script.Append("'" + GetResourceValue(entry.Key as string) + "'");
                    }
                    script.Append(" };");
                    return script.ToString();
                }
            }

            return "alert('GlobalResourcesToJavaScript: Could not load the resource file " + GetResXFilePath() + ".');";
        }
예제 #19
0
        public string GetJavaScript()
        {
            if (!FileExists())
            {
                return("console.log('GlobalResourcesToJavaScript: Cannot find the file " + GetResXFilePath() + ".');");
            }

            if (!string.IsNullOrEmpty(JavaScriptObjectName) && File.Exists(GetResXFilePath()))
            {
                var script = new StringBuilder();
                using (System.Resources.ResXResourceReader resourceReader = new System.Resources.ResXResourceReader(GetResXFilePath()))
                {
                    // Start by namespacing the object
                    // If there are no periods in our name, simply start our object definition
                    if (JavaScriptObjectName.Split('.').Length == 1)
                    {
                        script.Append("var " + JavaScriptObjectName + " = { ");
                    }

                    // If there are periods in the name, the developer wants to nest their objects.
                    // This is helpful if there is more than one resource file being translated into javascript.
                    // An example would be the core resource file, with the name 'resources'.
                    // Then, they translate a second resource file, whit the name 'resources.labels'.
                    // This helps the developer to organize their code accordingly.
                    else
                    {
                        var nameparts = JavaScriptObjectName.Split('.');
                        for (var x = 0; x < nameparts.Length; x++)
                        {
                            // If this is the first part of the namespace, let's any existing instances,
                            // or create a new one if this is the first time it's been instantiated.
                            if (x == 0)
                            {
                                script.Append("var " + nameparts[0] + " = " + nameparts[0] + " || {};\r");
                            }

                            // If this is not the first part...
                            else
                            {
                                // Create the namespace name up to this point.
                                var variable = "";
                                for (var y = 0; y < x + 1; y++)
                                {
                                    if (variable != "")
                                    {
                                        variable += ".";
                                    }
                                    variable += nameparts[y];
                                }

                                // If this is the last part of the namespace, let's start defining the object.
                                if (x == JavaScriptObjectName.Split('.').Length - 1)
                                {
                                    script.Append(variable + " = { ");
                                }

                                // If there are more parts of the namespace to define, let's set the object and move on.
                                else
                                {
                                    script.Append(variable + " = {};\r");
                                }
                            }
                        }
                    }


                    // Write out the resource items into JSON
                    bool first = true;
                    foreach (DictionaryEntry entry in resourceReader)
                    {
                        if (first)
                        {
                            first = false;
                        }
                        else
                        {
                            script.Append(" , ");
                        }

                        var resourceValue = GetResourceValue(entry.Key as string)
                                            .Replace("\r", "")
                                            .Replace("\n", "");

                        script.Append(NormalizeVariableName(entry.Key as string));
                        script.Append(":");
                        script.Append("'" + resourceValue + "'");
                    }
                    script.Append(" };");
                    return(script.ToString());
                }
            }

            return("alert('GlobalResourcesToJavaScript: Could not load the resource file " + GetResXFilePath() + ".');");
        }