Exemplo n.º 1
0
        public static void CompileCss(string sassFilePath, string cssFilePath, DateTime?folderLastUpdatedUtc = null)
        {
            var sassCompiler = new SassCompiler(new SassOptions
            {
                InputPath             = sassFilePath,
                OutputStyle           = SassOutputStyle.Compact,
                IncludeSourceComments = false,
            });


            var result = sassCompiler.Compile();


            if (result.ErrorStatus != 0)
            {
                throw new InvalidOperationException("Compiling sass caused a scripting host error. " +
                                                    string.Format("Error status: {0}. File: {1}. Line: {2}. Column: {3}. Message: {4}", result.ErrorStatus, result.ErrorFile, result.ErrorLine, result.ErrorColumn, result.ErrorMessage));
            }

            C1File.WriteAllText(cssFilePath, result.Output);

            if (folderLastUpdatedUtc.HasValue)
            {
                File.SetLastWriteTimeUtc(cssFilePath, folderLastUpdatedUtc.Value);
            }
        }
Exemplo n.º 2
0
        public static void CompressLess(string lessFilePath, string cssFilePath, DateTime folderLastUpdatedUtc)
        {
            var    scriptProc = InitProcess(lessFilePath);
            string output     = GetOutput(scriptProc);

            C1File.WriteAllText(cssFilePath, output);

            File.SetLastWriteTimeUtc(cssFilePath, folderLastUpdatedUtc);
        }
        private void saveStateCodeActivity_ExecuteCode(object sender, EventArgs e)
        {
            string content = this.GetBinding <string>("Markup");

            FileUtils.RemoveReadOnly(this.FilePath);

            C1File.WriteAllText(this.FilePath, content);

            this.SetSaveStatus(true);
        }
Exemplo n.º 4
0
        public virtual string GenerateNextOrderId(OrderCreationSettings settings)
        {
            int orderId;

            lock (Lock)
            {
                var content = C1File.ReadAllText(LastUsedOrderIdFile);
                int.TryParse(content, out orderId);

                orderId = orderId + 1;

                C1File.WriteAllText(LastUsedOrderIdFile, orderId.ToString(CultureInfo.InvariantCulture));
            }

            string sOrderId;

            if (settings.MinimumOrderIdLength > 0)
            {
                var format = "D" + settings.MinimumOrderIdLength;

                sOrderId = orderId.ToString(format, CultureInfo.InvariantCulture);
            }
            else
            {
                sOrderId = orderId.ToString(CultureInfo.InvariantCulture);
            }

            if (!String.IsNullOrEmpty(settings.OrderIdPrefix))
            {
                sOrderId = settings.OrderIdPrefix + sOrderId;
            }

            if (ECommerce.IsTestMode)
            {
                var hashMachineName = Environment.MachineName.GetHashCode().ToString(CultureInfo.InvariantCulture);
                if (hashMachineName.StartsWith("-"))
                {
                    hashMachineName = hashMachineName.Remove(0, 1);
                }

                var maxMachineNameLength = 20 - 6 - sOrderId.Length;
                if (hashMachineName.Length > maxMachineNameLength)
                {
                    hashMachineName = hashMachineName.Substring(0, maxMachineNameLength);
                }

                sOrderId = String.Format("TEST-{0}-{1}", hashMachineName, sOrderId);
            }

            sOrderId = sOrderId.Trim();

            return(sOrderId);
        }
        public string CompileCss(string sourceFilePath)
        {
            var absouteLessFilePath = HttpContext.Current.Server.MapPath(sourceFilePath);
            var scriptProc          = InitProcess(absouteLessFilePath);

            string output = GetOutput(scriptProc);

            var filePathCss = absouteLessFilePath.Substring(0, absouteLessFilePath.Length - FileExtention.Length) + ".min.css";

            C1File.WriteAllText(filePathCss, output);

            return(sourceFilePath.Substring(0, sourceFilePath.Length - ".less".Length) + ".min.css");
        }
Exemplo n.º 6
0
        /// <summary>
        /// </summary>
        /// <param name="virtualLessFilePath">virtual path to the LESS file</param>
        /// <returns> virtual path to the compressed CSS file</returns>
        public static string CompressLess(string virtualLessFilePath)
        {
            var absouteLessFilePath = HttpContext.Current.Server.MapPath(virtualLessFilePath);
            var scriptProc          = InitProcess(absouteLessFilePath);

            string output = GetOutput(scriptProc);

            var filePathCss = absouteLessFilePath.Substring(0, absouteLessFilePath.Length - ".less".Length) + ".min.css";

            C1File.WriteAllText(filePathCss, output);

            return(virtualLessFilePath.Substring(0, virtualLessFilePath.Length - ".less".Length) + ".min.css");
        }
Exemplo n.º 7
0
        /// <exclude />
        public static void SetFunctinoCode(this IInlineFunction function, string content)
        {
            string directoryPath = PathUtil.Resolve(GlobalSettingsFacade.InlineCSharpFunctionDirectory);

            if (C1Directory.Exists(directoryPath) == false)
            {
                C1Directory.CreateDirectory(directoryPath);
            }

            string filepath = Path.Combine(directoryPath, function.CodePath);

            C1File.WriteAllText(filepath, content);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Renders a url and return a full path to a rendered image, or <value>null</value> when rendering process is failing or inaccessible.
        /// </summary>
        public static async Task <RenderingResult> RenderUrlAsync(HttpContext context, string url, string mode)
        {
            string dropFolder = GetCacheFolder(mode);

            if (!C1Directory.Exists(dropFolder))
            {
                C1Directory.CreateDirectory(dropFolder);
            }
            string urlHash = Convert.ToBase64String(BitConverter.GetBytes(url.GetHashCode())).Substring(0, 6).Replace('+', '-').Replace('/', '_');

            string outputImageFileName = Path.Combine(dropFolder, urlHash + ".png");
            string outputFileName      = Path.Combine(dropFolder, urlHash + ".output");
            string errorFileName       = Path.Combine(dropFolder, urlHash + ".error");

            if (C1File.Exists(outputImageFileName) || C1File.Exists(outputFileName))
            {
#if BrowserRender_NoCache
                File.Delete(outputFileName);
#else
                string output = C1File.Exists(outputFileName) ? C1File.ReadAllText(outputFileName) : null;

                return(new RenderingResult {
                    FilePath = outputImageFileName, Output = output, Status = RenderingResultStatus.Success
                });
#endif
            }

            if (!Enabled)
            {
                return(null);
            }

            var result = await MakePreviewRequestAsync(context, url, outputImageFileName, mode);

            if (result.Status >= RenderingResultStatus.Error)
            {
                C1File.WriteAllText(errorFileName, result.Output);
            }

            if (!Enabled)
            {
                return(null);
            }

            if (result.Status == RenderingResultStatus.Success)
            {
                C1File.WriteAllText(outputFileName, result.Output);
            }

            return(result);
        }
Exemplo n.º 9
0
        private void saveStateCodeActivity_ExecuteCode(object sender, EventArgs e)
        {
            string content = this.GetBinding <string>("TreeDefinitionMarkup");

            string path = Path.Combine(PathUtil.Resolve(GlobalSettingsFacade.TreeDefinitionsDirectory), this.Filename);

            FileUtils.RemoveReadOnly(path);

            C1File.WriteAllText(path, content);

            this.SetSaveStatus(true);

            this.RefreshCurrentEntityToken();
        }
Exemplo n.º 10
0
        public Logger(Guid jobId)
        {
            var path = PathUtil.Resolve(String.Format(LogPath, jobId));

            DirectoryUtils.EnsurePath(path);

            if (!C1File.Exists(path))
            {
                C1File.WriteAllText(path, "Job started");
            }

            var fs = new FileStream(path, FileMode.Open, FileAccess.Write, FileShare.ReadWrite);

            _log = new StreamWriter(fs);
        }
        private void IfFeatureNameFree(object sender, System.Workflow.Activities.ConditionalEventArgs e)
        {
            string name = this.GetBinding <string>("Name");

            if (name.Length > 50)
            {
                e.Result = false;
                this.ShowFieldMessage("Name", StringResourceSystemFacade.GetString("Composite.Plugins.PageTemplateFeatureElementProvider", "AddWorkflow.NameTooLong"));
                return;
            }

            if (!C1Directory.Exists(PathUtil.Resolve(GlobalSettingsFacade.PageTemplateFeaturesDirectory)))
            {
                try
                {
                    C1Directory.CreateDirectory(PathUtil.Resolve(GlobalSettingsFacade.PageTemplateFeaturesDirectory));
                }
                catch (Exception)
                {
                    e.Result = false;
                    this.ShowFieldMessage("Name", string.Format("Can not create directory '{0}'", GlobalSettingsFacade.PageTemplateFeaturesDirectory));
                }
            }

            string xmlFilename  = Path.Combine(PathUtil.Resolve(GlobalSettingsFacade.PageTemplateFeaturesDirectory), name + ".xml");
            string htmlFilename = Path.Combine(PathUtil.Resolve(GlobalSettingsFacade.PageTemplateFeaturesDirectory), name + ".html");

            e.Result = !C1File.Exists(xmlFilename) && !C1File.Exists(htmlFilename);

            if (!e.Result)
            {
                this.ShowFieldMessage("Name", StringResourceSystemFacade.GetString("Composite.Plugins.PageTemplateFeatureElementProvider", "AddWorkflow.NameInUse"));
                return;
            }

            try
            {
                C1File.WriteAllText(xmlFilename, "tmp");
                C1File.Delete(xmlFilename);
            }
            catch (Exception)
            {
                e.Result = false;
                this.ShowFieldMessage("Name", StringResourceSystemFacade.GetString("Composite.Plugins.PageTemplateFeatureElementProvider", "AddWorkflow.NameNotValidInFilename"));
            }
        }
        static CaptchaConfiguration()
        {
            string configurationFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, CaptchaConfigurationFilePath);

            string password = null;

            if (C1File.Exists(configurationFilePath))
            {
                var doc = new XmlDocument();
                try
                {
                    using (var sr = new C1StreamReader(configurationFilePath))
                    {
                        doc.Load(sr);
                    }

                    var passwordNode = doc.SelectSingleNode("captcha/password");
                    if (!string.IsNullOrEmpty(passwordNode?.InnerText))
                    {
                        password = passwordNode.InnerText;
                    }
                }
                catch (Exception)
                {
                    // Do nothing
                }

                if (password != null)
                {
                    Password = password;
                    return;
                }

                // Deleting configuration file
                C1File.Delete(configurationFilePath);
            }


            password = Guid.NewGuid().ToString();

            string configFile = @"<captcha> <password>{0}</password> </captcha>".FormatWith(password);

            C1File.WriteAllText(configurationFilePath, configFile);

            Password = password;
        }
        private void finalizecodeActivity_ExecuteCode(object sender, EventArgs e)
        {
            var provider = GetFunctionProvider <RazorFunctionProvider>();

            string functionName      = this.GetBinding <string>(Binding_Name);
            string functionNamespace = ChangeNamespaceAccordingToExistingFolders(provider, this.GetBinding <string>(Binding_Namespace));
            string functionFullName  = functionNamespace + "." + functionName;

            AddNewTreeRefresher addNewTreeRefresher = this.CreateAddNewTreeRefresher(this.EntityToken);

            string fileName = functionName + ".cshtml";
            string folder   = Path.Combine(provider.PhysicalPath, functionNamespace.Replace('.', '\\'));

            string cshtmlFilePath = Path.Combine(folder, fileName);

            string code;

            string copyFromFunction = this.GetBinding <string>(Binding_CopyFromFunctionName);

            if (string.IsNullOrEmpty(copyFromFunction))
            {
                code = NewRazorFunction_CSHTML;
            }
            else
            {
                code = GetFunctionCode(copyFromFunction);
            }

            C1Directory.CreateDirectory(folder);
            C1File.WriteAllText(cshtmlFilePath, code);

            UserSettings.LastSpecifiedNamespace = functionNamespace;

            provider.ReloadFunctions();

            var newFunctionEntityToken = new FileBasedFunctionEntityToken(provider.Name, functionFullName);

            addNewTreeRefresher.PostRefreshMesseges(newFunctionEntityToken);

            var container        = WorkflowFacade.GetFlowControllerServicesContainer(WorkflowEnvironment.WorkflowInstanceId);
            var executionService = container.GetService <IActionExecutionService>();

            executionService.Execute(newFunctionEntityToken, new WorkflowActionToken(typeof(EditRazorFunctionWorkflow)), null);
        }
Exemplo n.º 14
0
        private void codeActivity2_ExecuteCode(object sender, EventArgs e)
        {
            AddNewTreeRefresher addNewTreeRefresher = this.CreateAddNewTreeRefresher(this.EntityToken);

            Guid   newTemplateId = Guid.NewGuid();
            string newTitle      = this.GetBinding <string>(Binding_Title);

            string newPageTemplate_Markup, newPageTemplate_Codebehind, templateFolder;

            Guid copyOfId = this.GetBinding <Guid>("CopyOfId");

            if (copyOfId == Guid.Empty)
            {
                newPageTemplate_Markup     = NewMasterPage_Markup;
                newPageTemplate_Codebehind = NewMasterPage_Codebehind;

                templateFolder = GetMasterPagesRootFolder();
            }
            else
            {
                ParseTemplateForCopying(copyOfId, out newPageTemplate_Markup, out newPageTemplate_Codebehind, out templateFolder);
            }

            string masterFilePath, codeFilePath;

            GenerateFileNames(templateFolder, newTitle, newTemplateId, out masterFilePath, out codeFilePath);

            newPageTemplate_Markup     = newPageTemplate_Markup.Replace(Marker_Codebehind, Path.GetFileName(codeFilePath));
            newPageTemplate_Codebehind = newPageTemplate_Codebehind
                                         .Replace(Marker_TemplateId, newTemplateId.ToString())
                                         .Replace(Marker_TemplateTitle, CSharpEncodeString(newTitle));

            C1File.WriteAllText(codeFilePath, newPageTemplate_Codebehind);
            C1File.WriteAllText(masterFilePath, newPageTemplate_Markup);

            var entityToken = new PageTemplateEntityToken(newTemplateId);

            PageTemplateProviderRegistry.FlushTemplates();

            addNewTreeRefresher.PostRefreshMesseges(entityToken);

            this.ExecuteAction(entityToken, new WorkflowActionToken(typeof(EditMasterPageWorkflow)));
        }
Exemplo n.º 15
0
        private static bool NeedToRun()
        {
            var checkLastRunTimeFilePath = HostingEnvironment.MapPath(_lastRunDateTimeFilePath) ?? string.Empty;

            if (!C1File.Exists(checkLastRunTimeFilePath))
            {
                C1File.WriteAllText(checkLastRunTimeFilePath, DateTime.Now.ToString(CultureInfo.InvariantCulture));
                return(true);
            }
            var lastrunDateTime = DateTime.Parse(File.ReadAllText(checkLastRunTimeFilePath), CultureInfo.InvariantCulture);
            var now             = DateTime.Now;

            if (lastrunDateTime.AddHours(double.Parse(Config.SendEveryNHours)) < now)
            {
                C1File.WriteAllText(checkLastRunTimeFilePath, DateTime.Now.ToString(CultureInfo.InvariantCulture));
                return(true);
            }
            return(false);
        }
        private ICollection <PackageFragmentValidationResult> FinalizeProcess(bool install)
        {
            try
            {
                if (_zipFilename != null && C1File.Exists(_zipFilename))
                {
                    C1File.Delete(_zipFilename);
                }

                Func <IList <PackageFragmentValidationResult>, bool> isNotEmpty = list => list != null && list.Count > 0;

                bool installationFailed = isNotEmpty(_preInstallValidationResult) ||
                                          isNotEmpty(_validationResult) ||
                                          isNotEmpty(_installationResult);

                if (installationFailed && C1Directory.Exists(_packageInstallDirectory))
                {
                    C1Directory.Delete(_packageInstallDirectory, true);
                }

                if (!installationFailed && install)
                {
                    Log.LogInformation(LogTitle, "Package successfully installed");

                    C1File.WriteAllText(Path.Combine(_packageInstallDirectory, PackageSystemSettings.InstalledFilename), "");

                    // Moving package files to a proper location, if an newer version of an already installed package is installed
                    if (_originalPackageInstallDirectory != null)
                    {
                        C1Directory.Delete(_originalPackageInstallDirectory, true);

                        C1Directory.Move(_packageInstallDirectory, _originalPackageInstallDirectory);
                    }
                }

                return(new PackageFragmentValidationResult[0]);
            }
            catch (Exception ex)
            {
                return(new [] { new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, ex) });
            }
        }
Exemplo n.º 17
0
        private void finalizecodeActivity_ExecuteCode(object sender, EventArgs e)
        {
            string functionName         = this.GetBinding <string>(Binding_Name);
            string functionNamespace    = this.GetBinding <string>(Binding_Namespace);
            string copyFromFunctionName = this.GetBinding <string>(Binding_CopyFromFunctionName);
            string functionFullName     = functionNamespace + "." + functionName;

            var provider = GetFunctionProvider <UserControlFunctionProvider>();

            AddNewTreeRefresher addNewTreeRefresher = this.CreateAddNewTreeRefresher(this.EntityToken);

            string fileName       = functionName + ".ascx";
            string folder         = Path.Combine(provider.PhysicalPath, functionNamespace.Replace('.', '\\'));
            string markupFilePath = Path.Combine(folder, fileName);
            string codeFilePath   = markupFilePath + ".cs";

            string markupTemplate = NewUserControl_Markup;
            string code           = NewUserControl_CodeFile;

            if (!copyFromFunctionName.IsNullOrEmpty())
            {
                GetFunctionCode(copyFromFunctionName, out markupTemplate, out code);
            }

            C1Directory.CreateDirectory(folder);
            C1File.WriteAllText(codeFilePath, code);
            C1File.WriteAllText(markupFilePath, markupTemplate.Replace(Marker_CodeFile, functionName + ".ascx.cs"));


            UserSettings.LastSpecifiedNamespace = functionNamespace;

            provider.ReloadFunctions();

            var newFunctionEntityToken = new FileBasedFunctionEntityToken(provider.Name, functionFullName);

            addNewTreeRefresher.PostRefreshMesseges(newFunctionEntityToken);

            var container        = WorkflowFacade.GetFlowControllerServicesContainer(WorkflowEnvironment.WorkflowInstanceId);
            var executionService = container.GetService <IActionExecutionService>();

            executionService.Execute(newFunctionEntityToken, new WorkflowActionToken(typeof(EditUserControlFunctionWorkflow)), null);
        }
Exemplo n.º 18
0
        /// <exclude />
        public static string BuildTopLevelClassNames(IEnumerable <string> scriptFilenames, string folderPath, string targetPath)
        {
            var classes = new StringBuilder();

            classes.AppendLine("var topLevelClassNames = [ // Don't edit! This file is automatically generated.");

            bool first = true;

            foreach (string scriptFilename in scriptFilenames)
            {
                string scriptPath = scriptFilename.Replace("${root}", folderPath);
                if (scriptPath.IndexOf("/scripts/source/page/") == -1)
                {
                    if (first)
                    {
                        first = false;
                    }
                    else
                    {
                        classes.AppendLine(",");
                    }

                    int _start  = scriptPath.LastIndexOf("/") + 1;
                    int _length = scriptPath.LastIndexOf(".js") - _start;

                    string className = scriptPath.Substring(_start, _length);

                    classes.Append("\t\"" + className + "\"");
                }
            }

            classes.AppendLine("];");

            string classesFilename = targetPath + "\\" + "toplevelclassnames.js";

            FileUtils.RemoveReadOnly(classesFilename);

            C1File.WriteAllText(classesFilename, string.Empty /* GetTimestampString() */);
            C1File.AppendAllText(classesFilename, classes.ToString());

            return(classesFilename);
        }
        private void finalizeCodeActivity_Finalize_ExecuteCode(object sender, EventArgs e)
        {
            string name       = this.GetBinding <string>("Name");
            string editorType = this.GetBinding <string>("EditorType");

            string filename = PageTemplateFeatureFacade.GetNewPageTemplateFeaturePath(name, editorType);

            var template = new XhtmlDocument();

            template.Head.Add("");
            template.Body.Add(new XElement(Namespaces.Xhtml + "p", ""));

            C1File.WriteAllText(filename, template.ToString());

            this.CloseCurrentView();
            this.RefreshRootEntityToken();

            this.ExecuteAction(PageTemplateFeatureEntityToken.BuildFeatureEntityToken(name),
                               new WorkflowActionToken(typeof(EditPageTemplateFeatureWorkflow)));
        }
Exemplo n.º 20
0
        /// <exclude/>
        public override IEnumerable <XElement> Install()
        {
            Verify.IsNotNull(_contentToAdd, "FileModifyPackageFragmentInstaller has not been validated");

            foreach (ContentToAdd content in _contentToAdd)
            {
                if (C1File.Exists(content.Path))
                {
                    using (C1StreamWriter sw = C1File.AppendText(content.Path))
                    {
                        sw.Write(content.Content);
                        sw.Close();
                    }
                }
                else
                {
                    C1File.WriteAllText(content.Path, content.Content);
                }
            }
            return(new[] { this.Configuration.FirstOrDefault() });
        }
Exemplo n.º 21
0
        /// <exclude />
        public static string MergeScripts(string type, IEnumerable <string> scriptFilenames, string folderPath, string targetPath)
        {
            string sourcesFilename = targetPath + "\\" + type + "-uncompressed.js";

            FileUtils.RemoveReadOnly(sourcesFilename);

            C1File.WriteAllText(sourcesFilename, string.Empty /* GetTimestampString() */);

            foreach (string scriptFilename in scriptFilenames)
            {
                string scriptPath = scriptFilename.Replace("${root}", folderPath).Replace("/", "\\");

                string lines = C1File.ReadAllText(scriptPath);


                C1File.AppendAllText(sourcesFilename, lines);
                C1File.AppendAllText(sourcesFilename, Environment.NewLine + Environment.NewLine);
            }

            return(sourcesFilename);
        }
        private void codeActivity2_ExecuteCode(object sender, EventArgs e)
        {
            AddNewTreeRefresher addNewTreeRefresher = this.CreateAddNewTreeRefresher(this.EntityToken);

            Guid   newTemplateId = Guid.NewGuid();
            string newTitle      = this.GetBinding <string>(Binding_Title);

            string newPageTemplateMarkup, folderPath;

            Guid copyOfId = this.GetBinding <Guid>("CopyOfId");

            if (copyOfId == Guid.Empty)
            {
                newPageTemplateMarkup = DefaultRazorTemplateMarkup;
                folderPath            = GetRazorTemplatesRootFolder();
            }
            else
            {
                ParseExistingTemplateForCopying(copyOfId, out newPageTemplateMarkup, out folderPath);
            }

            newPageTemplateMarkup = newPageTemplateMarkup
                                    .Replace(Marker_TemplateId, newTemplateId.ToString())
                                    .Replace(Marker_TemplateTitle, CSharpEncodeString(newTitle));


            string filePath = GeneratedCshtmlFileName(folderPath, newTitle, newTemplateId);

            C1File.WriteAllText(filePath, newPageTemplateMarkup);

            var entityToken = new PageTemplateEntityToken(newTemplateId);

            PageTemplateProviderRegistry.FlushTemplates();

            addNewTreeRefresher.PostRefreshMesseges(entityToken);

            this.ExecuteAction(entityToken, new WorkflowActionToken(typeof(EditRazorPageTemplateWorkflow)));
        }
Exemplo n.º 23
0
        public FlowToken Execute(EntityToken entityToken, ActionToken actionToken, FlowControllerServicesContainer flowControllerServicesContainer)
        {
            var ns = ((GenerateClassWithKeysActionToken)actionToken).Namespace;

            var resourceKeys = LocalizationsFacade.GetResourceKeys(String.Empty).Select(k => k.Key);
            var generator    = new ClassKeysGenerator(resourceKeys, ns);

            var content = generator.Generate();

            var dir = PathUtil.Resolve("~" + Path.Combine("/", UrlUtils.AdminRootPath, LocalPath));

            if (!C1Directory.Exists(dir))
            {
                C1Directory.CreateDirectory(dir);
            }

            var file = Path.Combine(dir, "Resources.txt");

            C1File.WriteAllText(file, content);

            var url = UrlUtils.ResolveAdminUrl(UrlUtils.Combine(LocalPath, Path.GetFileName(file)));

            var currentConsoleId = flowControllerServicesContainer.GetService <IManagementConsoleMessageService>().CurrentConsoleId;

            var openViewMessageItem = new OpenViewMessageQueueItem
            {
                Label    = "Resources.cs",
                Url      = url,
                ViewId   = Guid.NewGuid().ToString(),
                ViewType = ViewType.Main
            };

            ConsoleMessageQueueFacade.Enqueue(openViewMessageItem, currentConsoleId);

            return(null);
        }
Exemplo n.º 24
0
        private void finalizeCodeActivity_Finalize_ExecuteCode(object sender, EventArgs e)
        {
            string definitionName = this.GetBinding <string>("DefinitionName");
            string templateName   = this.GetBinding <string>("TemplateName");
            string positionName   = this.GetBinding <string>("PositionName");

            string template;

            switch (templateName)
            {
            case "Empty":
                template = string.Format(@"<?xml version=""1.0"" encoding=""UTF-8""?>
<ElementStructure xmlns=""http://*****:*****@"<?xml version=""1.0"" encoding=""UTF-8""?>
<ElementStructure xmlns=""http://*****:*****@"<?xml version=""1.0"" encoding=""UTF-8""?>
<ElementStructure xmlns=""http://http://www.composite.net/ns/management/trees/treemarkup/1.0"" xmlns:f=""http://www.composite.net/ns/function/1.0"">


  <ElementStructure.AutoAttachments>
    <NamedParent Name=""{0}"" Position=""Top""/>
  </ElementStructure.AutoAttachments>

  <ElementRoot>
    <Children>      
      <Element Label=""My DSL Tree Demo"" Id=""ParentFilteringId1"">
        <Children>
          <Element Label=""Simple Element"" Id=""ParentFilteringId2"">            
            <Children>              
              <DataElements Type=""Composite.Data.Types.IPageTemplate"">
                <Children>
                  <DataElements Type=""Composite.Data.Types.IPage"">
                    <Filters>
                      <ParentIdFilter ParentType=""Composite.Data.Types.IPageTemplate"" ReferenceFieldName=""TemplateId"" />
                    </Filters>
                  </DataElements>
                </Children>
              </DataElements>
            </Children>
          </Element>
        </Children>
      </Element>
    </Children>
  </ElementRoot>
</ElementStructure>", positionName);
                break;

            default:
                throw new InvalidOperationException();
            }


            string filename = Path.Combine(PathUtil.Resolve(GlobalSettingsFacade.TreeDefinitionsDirectory), definitionName + ".xml");

            C1File.WriteAllText(filename, template);

            this.RefreshRootEntityToken();
        }
Exemplo n.º 25
0
 /// <exclude />
 public void WriteAllText(string content)
 {
     // Default encode is Composite.Core.IO.StreamWriter.UTF8NoBOM, which is UTF8 without encoding signature
     C1File.WriteAllText(this.FullPath, content, Encoding.UTF8);
 }
Exemplo n.º 26
0
            /*
             * Moth knows about the ugly parameters, please refactor!
             * We should probably supply XSLT params by webcontrol markup...
             */

            public static MemoryStream Transform(MemoryStream buffer, String mode, String browser, String platform)
            {
                var readerSettings = new XmlReaderSettings();

                readerSettings.XmlResolver     = null;
                readerSettings.DtdProcessing   = DtdProcessing.Parse;
                readerSettings.CheckCharacters = false;

                List <string> xsltFilePaths = GetTransformationsInPriority().ToList();

                if (xsltFilePaths.Count == 0)
                {
                    return(buffer);
                }

                // Detection doctype
                buffer.Seek(0, SeekOrigin.Begin);
                var line    = new C1StreamReader(buffer).ReadLine();
                var doctype = line.Contains("<!DOCTYPE");

                buffer.Seek(0, SeekOrigin.Begin);


                MemoryStream outputStream = null;

                int xsltCount = xsltFilePaths.Count;

                for (int i = 0; i < xsltCount; i++)
                {
                    string xsltFilePath = xsltFilePaths[i];
                    bool   isFirst      = (i == 0);

                    MemoryStream inputStream = isFirst ? buffer : outputStream;
                    inputStream.Position = 0;
                    outputStream         = new MemoryStream();

                    /*
                     * Hardcoding a parameter for masterfilter.xsl
                     * TODO: parametersetup in webcontrol markup!
                     */

                    var transformer = GetCachedTransformation(xsltFilePath);

                    var argList = new XsltArgumentList();
                    if (!string.IsNullOrEmpty(mode))
                    {
                        argList.AddParam("mode", "", mode);
                    }
                    if (!string.IsNullOrEmpty(browser))
                    {
                        argList.AddParam("browser", "", browser);
                    }
                    if (!string.IsNullOrEmpty(platform))
                    {
                        argList.AddParam("platform", "", platform);
                    }
                    argList.AddParam("version", "", RuntimeInformation.ProductVersion.ToString());
                    argList.AddParam("doctype", "", doctype.ToString());
                    argList.AddParam("appVirtualPath", "", GetAppRootPath());

                    var reader = XmlReader.Create(inputStream, readerSettings);
                    var writer = XmlWriter.Create(outputStream, transformer.OutputSettings);

                    try
                    {
                        transformer.Transform(reader, argList, writer);
                    }
                    catch (XmlException xmlException)
                    {
                        string tempFilePath = TempDirectoryFacade.GetTempFileName(".xml");

                        inputStream.Position = 0;
                        string markup = new C1StreamReader(inputStream).ReadToEnd();

                        C1File.WriteAllText(tempFilePath, markup);

                        throw new InvalidOperationException(
                                  "Incorrect xml markup, source saved in '{0}'".FormatWith(tempFilePath),
                                  xmlException);
                    }
                }

                Verify.That(outputStream != null, "NullRef");

                return(outputStream);
            }
        private bool ValidateMarkup(string virtualPath, string content, out EntityToken newEntityToken)
        {
            newEntityToken = null;

            string filePath = PathUtil.Resolve(virtualPath);
            string fileName = Path.GetFileName(filePath);

            string tempFileName        = RazorPageTemplateProvider.TempFilePrefix + fileName;
            string tempFileVirtualPath = virtualPath.Substring(0, virtualPath.Length - fileName.Length) + tempFileName;
            string tempFile            = Path.Combine(Path.GetDirectoryName(filePath), tempFileName);

            try
            {
                C1File.WriteAllText(tempFile, content);

                WebPageBase webPageBase;

                try
                {
                    webPageBase = WebPage.CreateInstanceFromVirtualPath(tempFileVirtualPath);
                }
                catch (Exception ex)
                {
                    Log.LogWarning(LogTitle, "Compilation failed while validating changes to '{0}'", virtualPath);
                    Log.LogWarning(LogTitle, ex);

                    string message = ex.Message;

                    if (message.StartsWith(tempFile, StringComparison.OrdinalIgnoreCase))
                    {
                        message = fileName + message.Substring(tempFile.Length);
                    }

                    ShowWarning(GetText("EditTemplate.Validation.CompilationFailed")
                                .FormatWith(message));
                    return(false);
                }

                if (!(webPageBase is RazorPageTemplate))
                {
                    if (IsPageTemplate)
                    {
                        var templateDescriptor = GetPageTemplateDescriptor();

                        if (templateDescriptor.IsValid)
                        {
                            ShowWarning(GetText("EditTemplate.Validation.IncorrectBaseClass")
                                        .FormatWith(typeof(RazorPageTemplate).FullName));
                            return(false);
                        }

                        newEntityToken = new SharedCodeFileEntityToken(virtualPath);
                        return(true);
                    }

                    return(true);
                }

                Guid templateId;

                var pageTemplate = webPageBase as RazorPageTemplate;
                pageTemplate.Configure();

                try
                {
                    templateId = pageTemplate.TemplateId;
                }
                catch (Exception ex)
                {
                    ShowPropertyError("TemplateId", ex);
                    return(false);
                }

                try
                {
                    string templateTitle = pageTemplate.TemplateTitle;
                }
                catch (Exception ex)
                {
                    ShowPropertyError("TemplateTitle", ex);
                    return(false);
                }

                if (!IsPageTemplate)
                {
                    newEntityToken = new PageTemplateEntityToken(templateId);
                    return(true);
                }

                var pageTemplateDescriptor = GetPageTemplateDescriptor();

                if (pageTemplateDescriptor.IsValid)
                {
                    // Forbidding to change template id from this workflow in order to avoid mistakes
                    if (templateId != pageTemplateDescriptor.Id)
                    {
                        ShowWarning(GetText("EditTemplate.Validation.TemplateIdChanged").FormatWith(pageTemplateDescriptor.Id));
                        return(false);
                    }
                }
                else
                {
                    newEntityToken = new PageTemplateEntityToken(templateId);
                }
            }
            finally
            {
                C1File.Delete(tempFile);
            }

            return(true);
        }