Пример #1
0
        private static void TestCalculate()
        {
            WorldParser        world       = new WorldParser(@"Jsons\World.json");
            LoginResultParser  loginResult = new LoginResultParser(@"Jsons\LoginResult.json", false);
            LocalizationParser dict        = new LocalizationParser(@"Jsons\Runes.json");
            DropRateCalculator calc        = new DropRateCalculator();
            var result = calc.Calculate(loginResult.pChests, world, dict);

            List <dynamic> output = new List <dynamic>();

            foreach (var r in result)
            {
                var     key         = r.Key.Split('|');
                int     chestNumber = int.Parse(key[0]);
                string  type        = key[1];
                string  name        = key[2];
                var     value       = r.Value;
                dynamic e           = new ExpandoObject();
                e.ChestNumber = chestNumber;
                e.Name        = name;
                e.Type        = type;
                e.Expectation = value.ExpectationInAll;
                e.Chance      = value.ChanceInAll;
                e.Stars       = value.Stars;
                output.Add(e);
            }
            var arr  = output.Select(e => $"{e.ChestNumber},{e.Name},{e.Type},{e.Chance},{e.Expectation},{e.Stars}").ToArray();
            var text = string.Join(Environment.NewLine, arr);

            text = "ChestNumber,Name,Type,Chance,Expectation,Stars" + Environment.NewLine + text;
            File.WriteAllText(@"c:\temp\output.csv", text);
        }
Пример #2
0
        internal static void ProcessXhtmlDocument(XhtmlDocument xhtmlDocument, IPage page)
        {
            using (Profiler.Measure("Normalizing XHTML document"))
            {
                NormalizeXhtmlDocument(xhtmlDocument);
            }

            using (Profiler.Measure("Resolving relative paths"))
            {
                ResolveRelativePaths(xhtmlDocument);
            }

            using (Profiler.Measure("Sorting <head> elements"))
            {
                PrioritizeHeadNodes(xhtmlDocument);
            }

            using (Profiler.Measure("Appending C1 meta tags"))
            {
                AppendC1MetaTags(page, xhtmlDocument);
            }

            using (Profiler.Measure("Parsing localization strings"))
            {
                LocalizationParser.Parse(xhtmlDocument);
            }
        }
Пример #3
0
        /// <exclude />
        public static Control Render(XDocument document, FunctionContextContainer contextContainer, IXElementToControlMapper mapper, IPage page)
        {
            using (TimerProfilerFacade.CreateTimerProfiler())
            {
                ExecuteEmbeddedFunctions(document.Root, contextContainer);

                ResolvePageFields(document, page);

                NormalizeAspNetForms(document);

                if (document.Root.Name != Namespaces.Xhtml + "html")
                {
                    return(new LiteralControl(document.ToString()));
                }

                XhtmlDocument xhtmlDocument = new XhtmlDocument(document);
                NormalizeXhtmlDocument(xhtmlDocument);

                ResolveRelativePaths(xhtmlDocument);

                PrioritizeHeadNodex(xhtmlDocument);

                AppendC1MetaTags(page, xhtmlDocument);

                LocalizationParser.Parse(xhtmlDocument);

                return(xhtmlDocument.AsAspNetControl(mapper));
            }
        }
Пример #4
0
    void SetLocData()
    {
        LocalizationParser Loc1 = GameObject.Find("DataObj").GetComponent <LocalizationParser>();

        locData2 = Loc1._tempLD2;
        loccount = Loc1._localizationData.Length;
        //Debug.Log(locData2[1, 1]);
        //Debug.Log(loccount);
    }
Пример #5
0
    void SetLocData()
    {
        LocalizationParser Loc1 = this.GetComponent <LocalizationParser>();

        locData2 = Loc1._tempLD2;
        loccount = Loc1._localizationData.Length;
        //Debug.Log(locData2[1, 1]);
        //Debug.Log(loccount);
    }
Пример #6
0
        public static void ParseLocalizationLine(object state)
        {
            LocalizationState localizationFileState = state as LocalizationState;

            if (IsTaskCanceled(localizationFileState))
            {
                return;
            }

            var pdxLocalization = LocalizationParser.ParseLocalization(localizationFileState.line);

            if (pdxLocalization != null)
            {
                var key   = (String)pdxLocalization.GetType().GetProperty("Key").GetValue(pdxLocalization);
                var value = (String)pdxLocalization.GetType().GetProperty("Value").GetValue(pdxLocalization);

                lock (localizationFileState.localizations) {
                    var localization = localizationFileState.localizations.Find(l => l.Key.Equals(key));
                    if (localization != null)
                    {
                        if (localizationFileState.sub == STELLARIS_PATH_LOCALIZATION_ENGLISH)
                        {
                            localization.ValueEnglish = value;
                        }
                        else if (localizationFileState.sub == STELLARIS_PATH_LOCALIZATION_SIMPLE_CHINESE)
                        {
                            localization.ValueSimpChinese = value;
                        }
                    }
                    else
                    {
                        var fileName = localizationFileState.file.Name.Substring(0, localizationFileState.file.Name.LastIndexOf("."));
                        fileName = fileName.Replace("_l_simp_chinese", "");
                        fileName = fileName.Replace("_l_english", "");
                        fileName = fileName.Replace("l_simp_chinese", "");
                        fileName = fileName.Replace("l_english", "");

                        PdxLocalization newLocalization = new PdxLocalization {
                            Key      = key,
                            FileName = fileName
                        };

                        if (localizationFileState.sub == STELLARIS_PATH_LOCALIZATION_ENGLISH)
                        {
                            newLocalization.ValueEnglish = value;
                        }
                        else if (localizationFileState.sub == STELLARIS_PATH_LOCALIZATION_SIMPLE_CHINESE)
                        {
                            newLocalization.ValueSimpChinese = value;
                        }

                        localizationFileState.localizations.AddLast(newLocalization);
                    }
                }
            }
        }
            private XslCompiledTransform BuildCompiledTransform()
            {
                using (DebugLoggingScope.CompletionTime(this.GetType(), $"Loading and compiling {_xsltFunction.XslFilePath}"))
                {
                    string folderPath = Path.GetDirectoryName(_xsltFunction.XslFilePath);
                    string fileName   = Path.GetFileName(_xsltFunction.XslFilePath);

                    IXsltFile xsltFileHandle;

                    try
                    {
                        var xsltFileHandles =
                            (from file in DataFacade.GetData <IXsltFile>()
                             where String.Equals(file.FolderPath, folderPath, StringComparison.OrdinalIgnoreCase) &&
                             String.Equals(file.FileName, fileName, StringComparison.OrdinalIgnoreCase)
                             select file).ToList();

                        Verify.That(xsltFileHandles.Count == 1, "XSLT file path {0} found {1} times. Only one instance was expected.", _xsltFunction.XslFilePath, xsltFileHandles.Count);
                        xsltFileHandle = xsltFileHandles[0];
                    }
                    catch (Exception ex)
                    {
                        Log.LogError("XsltBasedFunctionProvider", ex);
                        throw;
                    }

                    if (!_subscribedToFileChanges)
                    {
                        xsltFileHandle.SubscribeOnChanged(ClearCachedData);
                        _subscribedToFileChanges = true;
                    }

                    var xslCompiledTransform = new XslCompiledTransform();


                    XDocument doc;
                    using (Stream xsltSourceStream = xsltFileHandle.GetReadStream())
                    {
                        using (XmlReader xmlReader = XmlReader.Create(xsltSourceStream))
                        {
                            doc = XDocument.Load(xmlReader);
                        }
                    }

                    ResolveImportIncludePaths(doc);

                    LocalizationParser.Parse(doc);

                    xslCompiledTransform.Load(doc.CreateReader(), XsltSettings.TrustedXslt, new XmlUrlResolver());


                    return(xslCompiledTransform);
                }
            }
        public void CanParse_should_be_false_then_true()
        {
            var args = new CanParseArgs()
            {
                File     = "common\\gamerules\\test.txt",
                GameType = "Stellaris"
            };
            var parser = new  LocalizationParser(new CodeParser(new Logger()), null);

            parser.CanParse(args).Should().BeFalse();
            args.File = "loc\\loc.yml";
            parser.CanParse(args).Should().BeTrue();
        }
Пример #9
0
        internal static void ProcessXhtmlDocument(XhtmlDocument xhtmlDocument, IPage page)
        {
            using (Profiler.Measure("Normalizing XHTML document"))
            {
                NormalizeXhtmlDocument(xhtmlDocument);
            }

            using (Profiler.Measure("Resolving relative paths"))
            {
                ResolveRelativePaths(xhtmlDocument);
            }

            using (Profiler.Measure("Appending C1 meta tags"))
            {
                AppendC1MetaTags(page, xhtmlDocument);
            }

            using (Profiler.Measure("Sorting <head> elements"))
            {
                PrioritizeHeadNodes(xhtmlDocument);
            }

            using (Profiler.Measure("Parsing localization strings"))
            {
                LocalizationParser.Parse(xhtmlDocument);
            }

            using (Profiler.Measure("Converting URLs from internal to public format (XhtmlDocument)"))
            {
                InternalUrls.ConvertInternalUrlsToPublic(xhtmlDocument);
            }

            var filters = ServiceLocator.GetServices <IPageContentFilter>().OrderBy(f => f.Order).ToList();

            if (filters.Any())
            {
                using (Profiler.Measure("Executing page content filters"))
                {
                    filters.ForEach(filter =>
                    {
                        using (Profiler.Measure($"Filter: {filter.GetType().FullName}"))
                        {
                            filter.Filter(xhtmlDocument, page);
                        }
                    });
                }
            }
        }
        //loads file
        private void LoadLocalizationFile()
        {
            //load window
            string filepath = EditorUtility.OpenFilePanel("Load Localization File", Application.streamingAssetsPath, "*json;*yml");

            //operation
            bool success = LocalizationParser.ReadLocalizationFile(filepath, out localizationData);

            //if operation successful...
            if (success)
            {
                //store file properties
                filename      = Path.GetFileNameWithoutExtension(filepath);
                fileExtension = Path.GetExtension(filepath).Replace(".", "");
            }
        }
        //saves current file
        private void SaveLocalizationFile()
        {
            //save window
            string filepath = EditorUtility.SaveFilePanel("Save Localization File", Application.streamingAssetsPath, filename, fileExtension);

            //operation
            bool success = LocalizationParser.WriteLocalizationFile(filepath, localizationData);

            //if operation successful...
            if (success)
            {
                //store file properties
                filename      = Path.GetFileNameWithoutExtension(filepath);
                fileExtension = Path.GetExtension(filepath).Replace(".", "");
            }
        }
Пример #12
0
        private void Load()
        {
            try
            {
                var body = GetLoginBody("QqZ5d1kWkz1D", "GQWLAycpxwFo");
                if (_worldFilePath == null)
                {
                    _worldFilePath = HttpContext.Current.Server.MapPath(@"~\Jsons\World.json");
                }
                if (_runeFilePath == null)
                {
                    _runeFilePath = HttpContext.Current.Server.MapPath(@"~\Jsons\Runes.json");
                }
                WorldParser world = new WorldParser(_worldFilePath);

                LoginResultParser  loginResult = new LoginResultParser(body, true);
                LocalizationParser dict        = new LocalizationParser(_runeFilePath);
                DropRateCalculator calc        = new DropRateCalculator();
                var            result          = calc.Calculate(loginResult.pChests, world, dict);
                List <dynamic> output          = new List <dynamic>();
                foreach (var r in result)
                {
                    var     key         = r.Key.Split('|');
                    int     chestNumber = int.Parse(key[0]);
                    string  type        = key[1];
                    string  name        = key[2];
                    var     value       = r.Value;
                    dynamic e           = new ExpandoObject();
                    e.ChestNumber = chestNumber;
                    e.Chest       = Enum.GetName(typeof(ChestType), chestNumber);
                    e.Name        = name;
                    e.Type        = type;
                    e.Expectation = value.ExpectationInAll;
                    e.Chance      = value.ChanceInAll;
                    e.Stars       = value.Stars;
                    output.Add(e);
                }
                CalculationResult = output;
                LastUpdated       = DateTime.Now;
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex);
                CalculationResult = null;
            }
        }
Пример #13
0
        static void Main(string[] args)
        {
            void ArgError(string arg, string cmd)
            {
                Console.WriteLine(string.Format("Error: Invalid number of argument parameters specified for '{0}' \n", arg));
                Console.WriteLine("Usage:");
                Command_Usage(cmd);
                Exit(1);
            }

            // Parse command line arguments
            try
            {
                // Parse first argument, whether it's the file path or the help command
                if (File.Exists(args[0]))
                {
                    parsedArgs.Add("file", new string[] { args[0] });
                }
                else if (args[0] == "-h" || args[0] == "--help" || args[0] == "help")
                {
                    if (args.Length == 1)
                    {
                        Command_Help();
                        Exit(0);
                    }
                    else if (args.Length > 1)
                    {
                        Console.WriteLine("Usage:");
                        switch (args[1])
                        {
                        case "-sv":
                        case "--set-value":
                            Command_Usage("set-value");
                            break;

                        case "-gv":
                        case "--get-value":
                            Command_Usage("get-value");
                            break;
                        }
                        Exit(0);
                    }
                }
                else
                {
                    Console.WriteLine(string.Format("Error: File does not exist at path: '{0}'", args[0]));
                    Exit(1);
                }

                // Parse the rest of the arguments
                for (int i = 1; i < args.Length; i++)
                {
                    switch (args[i])
                    {
                    case "-sv":
                    case "--set-value":
                        string svKeyPath  = args[i + 1];
                        string svKeyValue = args[i + 2];

                        if (svKeyPath.StartsWith("-"))
                        {
                            ArgError(args[i], "set-value");
                        }
                        if (svKeyValue.StartsWith("-"))
                        {
                            ArgError(args[i], "set-value");
                        }

                        parsedArgs.Add("set-value", new string[] { svKeyPath, svKeyValue });
                        break;

                    case "-gv":
                    case "--get-value":
                        string gvKeyPath = args[i + 1];

                        if (gvKeyPath.StartsWith("-"))
                        {
                            ArgError(args[i], "get-value");
                        }

                        parsedArgs.Add("get-value", new string[] { gvKeyPath });
                        break;
                    }
                }
            }
            catch (IndexOutOfRangeException)
            {
                Console.WriteLine("Error: Invalid number of arguments.\n");
                Command_Help();
                Exit(1);
            }

            //parsedArgs["file"][0] = @"J:\BF2_ModTools\data_LCT\Common\Localize\english.cfg";
            //parsedArgs["file"][0] = @"J:\BF2_ModTools\data_TCW\data_TCW\Common\Localize\english.cfg";
            //parsedArgs["file"][0] = @"J:\BF2_ModTools\data_LCT\Common\Localize\english.cfg";

            // Begin processing the arguments if the file was specified
            if (parsedArgs.ContainsKey("file"))
            {
                try
                {
                    db = LocalizationParser.ParseDataBase(parsedArgs["file"][0]);

                    // Process arguments
                    if (parsedArgs.ContainsKey("set-value"))
                    {
                        Command_SetValue();
                        Exit(0, false);
                    }

                    if (parsedArgs.ContainsKey("get-value"))
                    {
                        Command_GetValue();
                        Exit(0);
                    }



                    //Key testrootkey = db.GetKey("testrootkey");
                    //testrootkey.SetValue("new test value");

                    //db.WriteToFile(parsedArgs["file"][0]);
                    //Console.WriteLine(StringExt.ConvertUnicodeListToString(db.GetKey("testrootkey").BinaryValues));

                    //string testString = "\u0002";
                    //Console.WriteLine(testString);

                    //string testString = "\0\0TCW_Dev_Build_30813/01\r\nPROPERTY OF FRAYED WIRES STUDIOS\r\nDO NOT DISTRIBUTE";
                    //List<string> testBinaryList = StringExt.ConvertStringToUnicodeList(testString);
                    //foreach (string s in testBinaryList)
                    //{
                    //	Console.WriteLine(s);
                    //}
                    //Console.WriteLine("\n\nSize: " + testString.Length * 2);
                    //Console.WriteLine("\n\n" + StringExt.ConvertUnicodeListToString(testBinaryList));

                    //List<string> testList = new List<string>();
                    //testList.Add("00000000450034007500F500440056006700F500240057009600C6004600F500");
                    //testList.Add("33000300230013001300F20003001300D000A00005002500F400050054002500");
                    //testList.Add("450095000200F400640002006400250014009500540044000200750094002500");
                    //testList.Add("54003500020035004500550044009400F4003500D000A0004400F4000200E400");
                    //testList.Add("F400450002004400940035004500250094002400550045005400");

                    //Console.WriteLine(StringExt.ConvertUnicodeListToString(testList));
                }
                catch (System.Security.SecurityException ex)
                {
                    Console.WriteLine(ex.Message);
                    Command_Help();
                    Exit(3);
                }
                catch (NotSupportedException ex)
                {
                    Console.WriteLine(ex.Message);
                    Command_Help();
                    Exit(3);
                }
                catch (FileNotFoundException)
                {
                    Console.WriteLine("Error: File not found at path: " + parsedArgs["file"][0]);
                    Exit(3);
                }
                catch (UnauthorizedAccessException ex)
                {
                    Console.WriteLine(ex.Message);
                    Command_Help();
                    Exit(3);
                }
                catch (IOException ex)
                {
                    Console.WriteLine(ex.Message);
                    Command_Help();
                    Exit(3);
                }
                catch (ArgumentNullException ex)
                {
                    Console.WriteLine(ex.Message);
                    Command_Help();
                    Exit(3);
                }
                catch (ArgumentException ex)
                {
                    Console.WriteLine(ex.Message);
                    Command_Help();
                    Exit(3);
                }
            }
            else
            {
                Console.WriteLine("Error: File not specified!\n");
                Command_Help();
                Exit(1);
            }
        }
Пример #14
0
        private void editPreviewActivity_ExecuteCode(object sender, EventArgs e)
        {
            Stopwatch functionCallingStopwatch = null;
            long      millisecondsToken        = 0;

            CultureInfo oldCurrentCulture   = Thread.CurrentThread.CurrentCulture;
            CultureInfo oldCurrentUICulture = Thread.CurrentThread.CurrentUICulture;

            try
            {
                IXsltFunction xslt = this.GetBinding <IXsltFunction>("CurrentXslt");

                string xslTemplate = this.GetBinding <string>("XslTemplate");

                IFile persistemTemplateFile = IFileServices.TryGetFile <IXsltFile>(xslt.XslFilePath);
                if (persistemTemplateFile != null)
                {
                    string persistemTemplate = persistemTemplateFile.ReadAllText();

                    if (this.GetBinding <int>("XslTemplateLastSaveHash") != persistemTemplate.GetHashCode())
                    {
                        xslTemplate = persistemTemplate;
                        ConsoleMessageQueueFacade.Enqueue(new LogEntryMessageQueueItem {
                            Level = LogLevel.Fine, Message = "XSLT file on file system was used. It has been changed by another process.", Sender = this.GetType()
                        }, this.GetCurrentConsoleId());
                    }
                }

                List <NamedFunctionCall> namedFunctions = this.GetBinding <IEnumerable <NamedFunctionCall> >("FunctionCalls").ToList();

                // If preview is done multiple times in a row, with no postbacks an object reference to BaseFunctionRuntimeTreeNode may be held
                // If the function in the BaseFunctionRuntimeTreeNode have ben unloaded / reloaded, this preview will still run on the old instance
                // We force refresh by serializing / deserializing
                foreach (NamedFunctionCall namedFunction in namedFunctions)
                {
                    namedFunction.FunctionCall = (BaseFunctionRuntimeTreeNode)FunctionFacade.BuildTree(namedFunction.FunctionCall.Serialize());
                }


                List <ManagedParameterDefinition> parameterDefinitions = this.GetBinding <IEnumerable <ManagedParameterDefinition> >("Parameters").ToList();

                Guid        pageId        = this.GetBinding <Guid>("PageId");
                string      dataScopeName = this.GetBinding <string>("PageDataScopeName");
                string      cultureName   = this.GetBinding <string>("ActiveCultureName");
                CultureInfo cultureInfo   = null;
                if (cultureName != null)
                {
                    cultureInfo = CultureInfo.CreateSpecificCulture(cultureName);
                }

                IPage page;

                TransformationInputs transformationInput;
                using (new DataScope(DataScopeIdentifier.Deserialize(dataScopeName), cultureInfo))
                {
                    Thread.CurrentThread.CurrentCulture   = cultureInfo;
                    Thread.CurrentThread.CurrentUICulture = cultureInfo;

                    page = DataFacade.GetData <IPage>(f => f.Id == pageId).FirstOrDefault();
                    if (page != null)
                    {
                        PageRenderer.CurrentPage = page;
                    }

                    functionCallingStopwatch = Stopwatch.StartNew();
                    transformationInput      = RenderHelper.BuildInputDocument(namedFunctions, parameterDefinitions, true);
                    functionCallingStopwatch.Stop();

                    Thread.CurrentThread.CurrentCulture   = oldCurrentCulture;
                    Thread.CurrentThread.CurrentUICulture = oldCurrentUICulture;
                }


                string output = "";
                string error  = "";
                try
                {
                    Thread.CurrentThread.CurrentCulture   = cultureInfo;
                    Thread.CurrentThread.CurrentUICulture = cultureInfo;

                    var styleSheet = XElement.Parse(xslTemplate);

                    XsltBasedFunctionProvider.ResolveImportIncludePaths(styleSheet);

                    LocalizationParser.Parse(styleSheet);

                    XDocument transformationResult = new XDocument();
                    using (XmlWriter writer = new LimitedDepthXmlWriter(transformationResult.CreateWriter()))
                    {
                        XslCompiledTransform xslTransformer = new XslCompiledTransform();
                        xslTransformer.Load(styleSheet.CreateReader(), XsltSettings.TrustedXslt, new XmlUrlResolver());

                        XsltArgumentList transformArgs = new XsltArgumentList();
                        XslExtensionsManager.Register(transformArgs);

                        if (transformationInput.ExtensionDefinitions != null)
                        {
                            foreach (IXsltExtensionDefinition extensionDef in transformationInput.ExtensionDefinitions)
                            {
                                transformArgs.AddExtensionObject(extensionDef.ExtensionNamespace.ToString(),
                                                                 extensionDef.EntensionObjectAsObject);
                            }
                        }

                        Exception   exception   = null;
                        HttpContext httpContext = HttpContext.Current;

                        Thread thread = new Thread(delegate()
                        {
                            Thread.CurrentThread.CurrentCulture   = cultureInfo;
                            Thread.CurrentThread.CurrentUICulture = cultureInfo;

                            Stopwatch transformationStopwatch = Stopwatch.StartNew();

                            try
                            {
                                using (ThreadDataManager.Initialize())
                                    using (new DataScope(DataScopeIdentifier.Deserialize(dataScopeName), cultureInfo))
                                    {
                                        HttpContext.Current = httpContext;

                                        var reader = transformationInput.InputDocument.CreateReader();
                                        xslTransformer.Transform(reader, transformArgs, writer);
                                    }
                            }
                            catch (ThreadAbortException ex)
                            {
                                exception = ex;
                                Thread.ResetAbort();
                            }
                            catch (Exception ex)
                            {
                                exception = ex;
                            }

                            transformationStopwatch.Stop();

                            millisecondsToken = transformationStopwatch.ElapsedMilliseconds;
                        });

                        thread.Start();
                        bool res = thread.Join(1000);  // sadly, this needs to be low enough to prevent StackOverflowException from fireing.

                        if (res == false)
                        {
                            if (thread.ThreadState == System.Threading.ThreadState.Running)
                            {
                                thread.Abort();
                            }
                            throw new XslLoadException("Transformation took more than 1000 milliseconds to complete. This could be due to a never ending recursive call. Execution aborted to prevent fatal StackOverflowException.");
                        }

                        if (exception != null)
                        {
                            throw exception;
                        }
                    }

                    if (xslt.OutputXmlSubType == "XHTML")
                    {
                        XhtmlDocument xhtmlDocument = new XhtmlDocument(transformationResult);

                        output = xhtmlDocument.Root.ToString();
                    }
                    else
                    {
                        output = transformationResult.Root.ToString();
                    }
                }
                catch (Exception ex)
                {
                    output = "<error/>";
                    error  = string.Format("{0}\n{1}", ex.GetType().Name, ex.Message);

                    Exception inner = ex.InnerException;

                    string indent = "";

                    while (inner != null)
                    {
                        indent = indent + " - ";
                        error  = error + "\n" + indent + inner.Message;
                        inner  = inner.InnerException;
                    }
                }
                finally
                {
                    Thread.CurrentThread.CurrentCulture   = oldCurrentCulture;
                    Thread.CurrentThread.CurrentUICulture = oldCurrentUICulture;
                }

                Page currentPage = HttpContext.Current.Handler as Page;
                if (currentPage == null)
                {
                    throw new InvalidOperationException("The Current HttpContext Handler must be a System.Web.Ui.Page");
                }

                UserControl inOutControl = (UserControl)currentPage.LoadControl(UrlUtils.ResolveAdminUrl("controls/Misc/MarkupInOutView.ascx"));
                inOutControl.Attributes.Add("in", transformationInput.InputDocument.ToString());
                inOutControl.Attributes.Add("out", output);
                inOutControl.Attributes.Add("error", error);
                inOutControl.Attributes.Add("statusmessage", string.Format("Execution times: Total {0} ms. Functions: {1} ms. XSLT: {2} ms.",
                                                                           millisecondsToken + functionCallingStopwatch.ElapsedMilliseconds,
                                                                           functionCallingStopwatch.ElapsedMilliseconds,
                                                                           millisecondsToken));

                FlowControllerServicesContainer serviceContainer = WorkflowFacade.GetFlowControllerServicesContainer(WorkflowEnvironment.WorkflowInstanceId);
                var webRenderService = serviceContainer.GetService <IFormFlowWebRenderingService>();
                webRenderService.SetNewPageOutput(inOutControl);
            }
            catch (Exception ex)
            {
                FlowControllerServicesContainer serviceContainer = WorkflowFacade.GetFlowControllerServicesContainer(WorkflowEnvironment.WorkflowInstanceId);
                Control errOutput        = new LiteralControl("<pre>" + ex.ToString() + "</pre>");
                var     webRenderService = serviceContainer.GetService <IFormFlowWebRenderingService>();
                webRenderService.SetNewPageOutput(errOutput);
            }
        }
        public void Parse_should_yield_results()
        {
            DISetup.SetupContainer();

            var sb = new StringBuilder();

            sb.AppendLine(@"l_english:");
            sb.AppendLine(@" NEW_ACHIEVEMENT_2_0_NAME:0 ""Brave New World""");
            sb.AppendLine(@" NEW_ACHIEVEMENT_2_0_DESC:0 ""Colonize a planet""");
            sb.AppendLine(@" NEW_ACHIEVEMENT_2_1_NAME:0 ""Digging Deep""");

            var sb2 = new StringBuilder();

            sb2.AppendLine(@"l_english:");
            sb2.AppendLine(@" NEW_ACHIEVEMENT_2_0_NAME:0 ""Brave New World""");

            var sb3 = new StringBuilder();

            sb3.AppendLine(@"l_english:");
            sb3.AppendLine(@" NEW_ACHIEVEMENT_2_0_DESC:0 ""Colonize a planet""");

            var sb4 = new StringBuilder();

            sb4.AppendLine(@"l_english:");
            sb4.AppendLine(@" NEW_ACHIEVEMENT_2_1_NAME:0 ""Digging Deep""");

            var args = new ParserArgs()
            {
                ContentSHA      = "sha",
                ModDependencies = new List <string> {
                    "1"
                },
                File    = "loc\\loc.yml",
                Lines   = sb.ToString().Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries),
                ModName = "fake"
            };
            var parser = new LocalizationParser(new CodeParser(new Logger()), null);
            var result = parser.Parse(args).ToList();

            result.Should().NotBeNullOrEmpty();
            result.Count().Should().Be(3);
            for (int i = 0; i < 3; i++)
            {
                result[i].ContentSHA.Should().Be("sha");
                result[i].Dependencies.First().Should().Be("1");
                result[i].File.Should().Be("loc\\loc.yml");
                switch (i)
                {
                case 0:
                    result[i].Code.Trim().Should().Be(sb2.ToString().Trim());
                    result[i].Id.Should().Be("NEW_ACHIEVEMENT_2_0_NAME");
                    result[i].ValueType.Should().Be(Common.ValueType.SpecialVariable);
                    break;

                case 1:
                    result[i].Code.Trim().Should().Be(sb3.ToString().Trim());
                    result[i].Id.Should().Be("NEW_ACHIEVEMENT_2_0_DESC");
                    result[i].ValueType.Should().Be(Common.ValueType.SpecialVariable);
                    break;

                case 2:
                    result[i].Code.Trim().Should().Be(sb4.ToString().Trim());
                    result[i].Id.Should().Be("NEW_ACHIEVEMENT_2_1_NAME");
                    result[i].ValueType.Should().Be(Common.ValueType.SpecialVariable);
                    break;

                default:
                    break;
                }
                result[i].ModName.Should().Be("fake");
                result[i].Type.Should().Be("loc\\l_english-yml");
            }
        }
Пример #16
0
        public override void ExecuteResult(ControllerContext context)
        {
            string markup;

            using (TimerProfilerFacade.CreateTimerProfiler())
            {
                var page          = PageRenderer.CurrentPage;
                var markupBuilder = new StringBuilder();
                var sw            = new StringWriter(markupBuilder);
                var output        = new HtmlTextWriter(sw);

                IView view;
                using (Profiler.Measure("Resolving view for template"))
                {
                    view = FindView(context).View;
                }

                var viewContext = new ViewContext(context, view, ViewData, TempData, output);

                view.Render(viewContext, output);

                markup = markupBuilder.ToString();
                var xml = XDocument.Parse(markup);

                var functionContext = PageRenderer.GetPageRenderFunctionContextContainer();

                functionContext = new FunctionContextContainer(functionContext, new Dictionary <string, object>
                {
                    { "viewContext", viewContext }
                });

                using (Profiler.Measure("Executing embedded functions"))
                {
                    PageRenderer.ExecuteEmbeddedFunctions(xml.Root, functionContext);
                }

                using (Profiler.Measure("Resolving pagefields"))
                {
                    PageRenderer.ResolvePageFields(xml, page);
                }

                var document = new XhtmlDocument(xml);

                using (Profiler.Measure("Normalizing html"))
                {
                    PageRenderer.NormalizeXhtmlDocument(document);
                }

                PageRenderer.ResolveRelativePaths(document);
                PageRenderer.AppendC1MetaTags(page, document);

                using (Profiler.Measure("Resolving localized strings"))
                {
                    LocalizationParser.Parse(document);
                }

                markup = document.ToString();

                using (Profiler.Measure("Changing 'internal' page urls to 'public'"))
                {
                    markup = PageUrlHelper.ChangeRenderingPageUrlsToPublic(markup);
                }

                using (Profiler.Measure("Changing 'internal' media urls to 'public'"))
                {
                    markup = MediaUrlHelper.ChangeInternalMediaUrlsToPublic(markup);
                }

                markup = _mvcContext.FormatXhtml(markup);
            }

            if (_mvcContext.ProfilingEnabled)
            {
                markup = _mvcContext.BuildProfilerReport();

                context.HttpContext.Response.ContentType = "text/xml";
            }

            context.HttpContext.Response.Write(markup);
        }
Пример #17
0
        public virtual IHttpActionResult Body([FromBody] string body)
        {
            InitializeFullPageCaching(System.Web.HttpContext.Current);

            if (string.IsNullOrWhiteSpace(body))
            {
                NotFound();
            }

            var decrypted = LazyFunctionCallDataProvider.UnprotectFunctionCall(body);

            if (decrypted == null)
            {
                return(NotFound());
            }

            HttpContext.RewritePath(HttpContext.Request.FilePath, HttpContext.Request.PathInfo, decrypted.QueryString);

            using (var data = new DataConnection(PublicationScope.Published, ComposerContext.CultureInfo))
            {
                // Grab a function object to execute
                IFunction function = FunctionFacade.GetFunction(decrypted.FunctionName);

                PageRenderer.CurrentPage = PageManager.GetPageById(decrypted.PageId);;

                // Execute the function, passing all query string parameters as input parameters
                var functionResult = (XhtmlDocument)FunctionFacade.Execute <object>(function, decrypted.Parameters.ToDictionary(d => d.Key, d => (object)d.Value));


                // output result
                if (functionResult != null)
                {
                    var functionContext = new FunctionContextContainer();

                    PageRenderer.ExecuteEmbeddedFunctions(functionResult.Root, functionContext);

                    //PageRenderer.ProcessXhtmlDocument(functionResult, productPage);

                    using (Profiler.Measure("Normalizing XHTML document"))
                    {
                        PageRenderer.NormalizeXhtmlDocument(functionResult);
                    }

                    using (Profiler.Measure("Resolving relative paths"))
                    {
                        PageRenderer.ResolveRelativePaths(functionResult);
                    }


                    using (Profiler.Measure("Parsing localization strings"))
                    {
                        LocalizationParser.Parse(functionResult);
                    }

                    using (Profiler.Measure("Converting URLs from internal to public format (XhtmlDocument)"))
                    {
                        InternalUrls.ConvertInternalUrlsToPublic(functionResult);
                    }

                    //TODO: Update C1 Version
                    //PageRenderer.ProcessDocumentHead(functionResult);

                    StringBuilder sb = new StringBuilder();

                    foreach (var node in functionResult.Body.Nodes())
                    {
                        sb.Append(node.ToString());
                    }

                    return(Json(sb.ToString()));
                }
            }

            return(NotFound());
        }