Exemplo n.º 1
0
        public void ProcessRequest(HttpContext context)
        {
            if (!UserValidationFacade.IsLoggedIn())
            {
                return;
            }

            try
            {
                string t = context.Request["t"];
                Verify.That(!t.IsNullOrEmpty(), "Missing query string argument 't'");

                string p = context.Request["p"];
                Verify.That(!p.IsNullOrEmpty(), "Missing query string argument 'p'");

                Guid templateId = Guid.Parse(t);
                Guid pageId     = Guid.Parse(p);


                string filePath;

                PageTemplatePreview.PlaceholderInformation[] placeholders;
                PageTemplatePreview.GetPreviewInformation(context, pageId, templateId, out filePath, out placeholders);

                Verify.That(C1File.Exists(filePath), "Preview file missing");
                context.Response.ContentType = "image/png";
                context.Response.WriteFile(filePath);
            }
            catch (Exception ex)
            {
                Log.LogError(this.GetType().ToString(), ex.ToString());
                throw;
            }
        }
Exemplo n.º 2
0
        protected override Activity LoadWorkflowInstanceState(Guid instanceId)
        {
            string filename   = GetFileName(instanceId);
            bool   deleteFile = false;

            if (C1File.Exists(filename))
            {
                try
                {
                    object obj = DeserializeActivity(null, instanceId);
                    return((Activity)obj);
                }
                catch (Exception ex)
                {
                    LoggingService.LogCritical(LogTitle, ex);
                    deleteFile = true;
                }
            }

            if (deleteFile)
            {
                Log.LogWarning(LogTitle, $"Failed to load workflow with id '{filename}'. Deleting file.");
                C1File.Delete(filename);

                MarkWorkflowAsAborted(instanceId);
            }

            return(null);
        }
Exemplo n.º 3
0
        /// <exclude />
        public static string GetFunctionCode(this IInlineFunction function)
        {
            string filepath = GetSourceFilePath(function);

            // Making 5 attempts to read the file
            for (int i = 5; i > 0; i--)
            {
                try
                {
                    return(C1File.ReadAllText(filepath));
                }
                catch (FileNotFoundException)
                {
                    throw;
                }
                catch (IOException)
                {
                    if (i == 1)
                    {
                        throw;
                    }

                    Thread.Sleep(100);
                }
            }
            throw new InvalidOperationException("This line should not be reachable");
        }
        private static void LoadAllowedPaths()
        {
            _allAllowedPaths.Clear();

            string webauthorizationConfigPath = HostingEnvironment.MapPath(webauthorizationRelativeConfigPath);

            if (!C1File.Exists(webauthorizationConfigPath))
            {
                Log.LogInformation("AdministrativeAuthorizationHttpModule ", "File '{0}' not found - all access to the ~/Composite folder will be blocked", webauthorizationConfigPath);
                return;
            }

            XDocument webauthorizationConfigDocument = XDocumentUtils.Load(webauthorizationConfigPath);

            XAttribute loginPagePathAttribute = Verify.ResultNotNull(webauthorizationConfigDocument.Root.Attribute("loginPagePath"), "Missing '{0}' attribute on '{1}' root element", loginPagePathAttributeName, webauthorizationRelativeConfigPath);
            string     relativeLoginPagePath  = Verify.StringNotIsNullOrWhiteSpace(loginPagePathAttribute.Value, "Unexpected empty '{0}' attribute on '{1}' root element", loginPagePathAttributeName, webauthorizationRelativeConfigPath);

            _loginPagePath = UrlUtils.ResolveAdminUrl(relativeLoginPagePath);

            foreach (XElement allowElement in webauthorizationConfigDocument.Root.Elements(allowElementName))
            {
                XAttribute relativePathAttribute = Verify.ResultNotNull(allowElement.Attribute(allow_pathAttributeName), "Missing '{0}' attribute on '{1}' element in '{2}'.", allow_pathAttributeName, allowElement, webauthorizationRelativeConfigPath);
                string     relativePath          = Verify.StringNotIsNullOrWhiteSpace(relativePathAttribute.Value, "Empty '{0}' attribute on '{1}' element in '{2}'.", allow_pathAttributeName, allowElement, webauthorizationRelativeConfigPath);

                string fullPath = UrlUtils.ResolveAdminUrl(relativePath).ToLowerInvariant();
                _allAllowedPaths.Add(fullPath);
            }
        }
Exemplo n.º 5
0
        private void EmbedExceptionSourceCode(Exception ex)
        {
            if (ex is ThreadAbortException ||
                ex is StackOverflowException ||
                ex is OutOfMemoryException ||
                ex is ThreadInterruptedException)
            {
                return;
            }

            var stackTrace = new StackTrace(ex, true);


            foreach (var frame in stackTrace.GetFrames())
            {
                string fileName = frame.GetFileName();

                if (fileName != null && File.Exists(fileName))
                {
                    var sourceCode = C1File.ReadAllLines(fileName);

                    XhtmlErrorFormatter.EmbedSourceCodeInformation(ex, sourceCode, frame.GetFileLineNumber());
                    return;
                }
            }
        }
        public void ProcessRequest(HttpContext context)
        {
            if (!UserValidationFacade.IsLoggedIn())
            {
                context.Response.ContentType = MimeTypeInfo.Text;
                context.Response.Write("No user logged in");
                context.Response.StatusCode = 401;
                return;
            }

            try
            {
                string t = context.Request["t"];
                Verify.That(!t.IsNullOrEmpty(), "Missing query string argument 't'");

                string p = context.Request["p"];
                Verify.That(!p.IsNullOrEmpty(), "Missing query string argument 'p'");

                Guid templateId = Guid.Parse(t);
                Guid pageId     = Guid.Parse(p);


                PageTemplatePreview.GetPreviewInformation(context, pageId, templateId, out string filePath, out _);

                Verify.That(C1File.Exists(filePath), "Preview file missing");
                context.Response.ContentType = "image/png";
                context.Response.WriteFile(filePath);
            }
            catch (Exception ex)
            {
                Log.LogError(nameof(TemplatePreviewHttpHandler), ex);
                throw;
            }
        }
Exemplo n.º 7
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);
            }
        }
        private void finalizeCodeActivity_SaveFile_ExecuteCode(object sender, EventArgs e)
        {
            UploadedFile uploadedFile = this.GetBinding <UploadedFile>("UploadedFile");

            if (uploadedFile.HasFile)
            {
                string currentPath = GetCurrentPath();
                string filename    = uploadedFile.FileName;

                string fullFilename = System.IO.Path.Combine(currentPath, filename);

                if (C1File.Exists(fullFilename))
                {
                    FileUtils.Delete(fullFilename);
                }

                using (C1FileStream fs = new C1FileStream(fullFilename, FileMode.CreateNew))
                {
                    uploadedFile.FileStream.CopyTo(fs);
                }

                SpecificTreeRefresher specificTreeRefresher = this.CreateSpecificTreeRefresher();
                specificTreeRefresher.PostRefreshMesseges(this.EntityToken);

                if (this.EntityToken is WebsiteFileElementProviderEntityToken)
                {
                    WebsiteFileElementProviderEntityToken folderToken = (WebsiteFileElementProviderEntityToken)this.EntityToken;
                    var newFileToken = new WebsiteFileElementProviderEntityToken(folderToken.ProviderName, fullFilename, folderToken.RootPath);
                    SelectElement(newFileToken);
                }
            }
        }
Exemplo n.º 9
0
        internal static Dictionary <Guid, string> GetInstalledPackages()
        {
            var result = new Dictionary <Guid, string>();

            string baseDirectory = PathUtil.Resolve(GlobalSettingsFacade.PackageDirectory);

            if (!C1Directory.Exists(baseDirectory))
            {
                return(result);
            }

            string[] packageDirectories = C1Directory.GetDirectories(baseDirectory);
            foreach (string packageDirecoty in packageDirectories)
            {
                if (C1File.Exists(Path.Combine(packageDirecoty, PackageSystemSettings.InstalledFilename)))
                {
                    string filename = Path.Combine(packageDirecoty, PackageSystemSettings.PackageInformationFilename);

                    if (C1File.Exists(filename))
                    {
                        string path = packageDirecoty.Remove(0, baseDirectory.Length);
                        if (path.StartsWith("\\"))
                        {
                            path = path.Remove(0, 1);
                        }

                        Guid id = new Guid(path);

                        result.Add(id, filename);
                    }
                }
            }

            return(result);
        }
Exemplo n.º 10
0
        public IUrlFormatter Assemble(IBuilderContext context, UrlFormatterData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache)
        {
            var data = (StringReplaceUrlFormatterData)objectConfiguration;

            string rulesFile = data.RulesFile;

            if (!rulesFile.IsNullOrEmpty())
            {
                string fullPath = HostingEnvironment.MapPath(rulesFile);
                Verify.That(C1File.Exists(fullPath), "Cannot find file '{0}'", rulesFile);

                try
                {
                    XDocument xDoc = XDocumentUtils.Load(fullPath);

                    return(new StringReplaceUrlFormatter(
                               xDoc.Root.Elements()
                               .Select(e => new Pair <string, string>(GetAttributeNotNull(e, "oldValue"), GetAttributeNotNull(e, "newValue"))).ToList()));
                }
                catch (Exception e)
                {
                    throw new ConfigurationErrorsException("Failed to process file '{0}'".FormatWith(rulesFile), e);
                }
            }

            var replacements = data.Replace.Cast <ReplacementRuleConfigurationElement>();

            return(new StringReplaceUrlFormatter(replacements.Select(r => new Pair <string, string>(r.OldValue, r.NewValue)).ToList()));
        }
Exemplo n.º 11
0
        private void DeleteOldWorkflows()
        {
            using (GlobalInitializerFacade.CoreIsInitializedScope)
            {
                foreach (string filename in C1Directory.GetFiles(SerializedWorkflowsDirectory))
                {
                    DateTime creationTime = C1File.GetLastWriteTime(filename);

                    if (DateTime.Now.Subtract(creationTime) > OldFileExistenceTimeout)
                    {
                        Guid instanceId = new Guid(Path.GetFileNameWithoutExtension(filename));

                        if (Path.GetExtension(filename) == "bin")
                        {
                            try
                            {
                                WorkflowRuntime.GetWorkflow(instanceId);
                                AbortWorkflow(instanceId);
                            }
                            catch (Exception)
                            {
                            }
                        }

                        C1File.Delete(filename);

                        Log.LogVerbose(LogTitle, $"Old workflow instance file deleted {filename}");
                    }
                }
            }
        }
Exemplo n.º 12
0
        /// <exclude />
        public override void Uninstall()
        {
            Verify.IsNotNull(_filesToDelete as object ?? _filesToCopy, "{0} has not been validated", this.GetType().Name);

            foreach (string filename in _filesToDelete)
            {
                Log.LogVerbose(LogTitle, "Uninstalling the file '{0}'", filename);

                FileUtils.Delete(filename);
            }

            foreach (var fileToCopy in _filesToCopy)
            {
                string targetFile = fileToCopy.Item2;

                Log.LogVerbose(LogTitle, "Restoring file from a backup copy'{0}'", targetFile);

                if ((C1File.GetAttributes(targetFile) & FileAttributes.ReadOnly) > 0)
                {
                    FileUtils.RemoveReadOnly(targetFile);
                }

                C1File.Copy(fileToCopy.Item1, targetFile, true);
            }
        }
Exemplo n.º 13
0
    protected void Page_Load(object sender, EventArgs e)
    {
        var xsdFiles = C1Directory.GetFiles(this.MapPath(""), "*.xsd");

        XElement xsdFilesTable = new XElement("table",
                                              new XElement("tr",
                                                           new XElement("td", "Namespace"),
                                                           new XElement("td", "Last generated")));

        foreach (string xsdFile in xsdFiles)
        {
            DateTime lastWrite = C1File.GetLastWriteTime(xsdFile);

            XDocument schemaDocument  = XDocumentUtils.Load(xsdFile);
            string    targetNamespace = schemaDocument.Root.Attribute("targetNamespace").Value;

            xsdFilesTable.Add(
                new XElement("tr",
                             new XElement("td",
                                          new XElement("a",
                                                       new XAttribute("href", Path.GetFileName(xsdFile)),
                                                       targetNamespace)),
                             new XElement("td", lastWrite)));
        }

        XsdTable.Controls.Add(new LiteralControl(xsdFilesTable.ToString()));

        GenerateButton.Click += new EventHandler(GenerateButton_Click);
    }
Exemplo n.º 14
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="filename">
        /// Format:
        ///     ~\Filename.txt
        ///     ~\Directory1\Directory2\Filename.txt
        ///     ~/Filename.txt
        ///     ~/Directory1/Directory2/Filename.txt
        /// </param>
        /// <returns></returns>
        public Stream GetFileStream(string filename)
        {
            var parstedFilename = ParseFilename(filename);

            if (!_entryNames.Contains(parstedFilename))
            {
                string note = "";

                var entryWithAnotherCasing = _entryNames
                                             .FirstOrDefault(en => en.Equals(parstedFilename, StringComparison.InvariantCultureIgnoreCase));

                if (entryWithAnotherCasing != null)
                {
                    note = $" There's another entry with different casing '{entryWithAnotherCasing}'.";
                }

                throw new ArgumentException($"The file '{filename}' does not exist in the zip." + note);
            }

            var zipArchive = new ZipArchive(C1File.Open(ZipFilename, FileMode.Open, FileAccess.Read));

            var entryPath = filename.Substring(2).Replace('\\', '/');

            var entry = zipArchive.GetEntry(entryPath);

            if (entry == null)
            {
                zipArchive.Dispose();

                throw new InvalidOperationException($"Entry '{entryPath}' not found");
            }

            return(new StreamWrapper(entry.Open(), () => zipArchive.Dispose()));
        }
Exemplo n.º 15
0
 public static void WriteXmlElement(string key, string value)
 {
     if (!C1File.Exists(XmlFileName))
     {
         WriteXml(new Dictionary <string, string> {
             { key, value }
         });
     }
     else
     {
         var doc  = XDocument.Load(XmlFileName);
         var root = doc.Root;
         if (root != null)
         {
             var element = root.Elements("Mapping").FirstOrDefault(el =>
             {
                 var oldPathAttr = el.Attribute("OldPath");
                 return(oldPathAttr != null && oldPathAttr.Value == key);
             });
             if (element != null)
             {
                 var newPathAttr = element.Attribute("NewPath");
                 if (newPathAttr != null)
                 {
                     newPathAttr.Value = value;
                 }
             }
             else
             {
                 root.Add(new XElement("Mapping", new XAttribute("OldPath", key), new XAttribute("NewPath", value)));
             }
             doc.Save(XmlFileName);
         }
     }
 }
Exemplo n.º 16
0
        private void EmbedSourceCodeInformation(HttpCompileException ex)
        {
            var compilationErrors = ex.Results.Errors;

            if (!compilationErrors.HasErrors)
            {
                return;
            }

            CompilerError firstError = null;

            for (int i = 0; i < compilationErrors.Count; i++)
            {
                if (!compilationErrors[i].IsWarning)
                {
                    firstError = compilationErrors[i];
                    break;
                }
            }

            Verify.IsNotNull(firstError, "Failed to finding an error in the compiler results.");

            // Not showing source code of not related files
            if (!firstError.FileName.StartsWith(PathUtil.Resolve(VirtualPath), StringComparison.OrdinalIgnoreCase))
            {
                return;
            }

            string[] sourceCode = C1File.ReadAllLines(firstError.FileName);

            XhtmlErrorFormatter.EmbedSourceCodeInformation(ex, sourceCode, firstError.Line);
        }
        public IEnumerable <EntityToken> GetParents(EntityToken entityToken)
        {
            WebsiteFileElementProviderEntityToken castedEntityToken = (WebsiteFileElementProviderEntityToken)entityToken;

            if ((C1File.Exists(castedEntityToken.Path) == false) &&
                (C1Directory.Exists(castedEntityToken.Path) == false))
            {
                return(null);
            }

            string newFolderPath = Path.GetDirectoryName(castedEntityToken.Path);

            string rootFolder = castedEntityToken.RootPath;

            if (newFolderPath != rootFolder)
            {
                Verify.That(newFolderPath.Length > rootFolder.Length,
                            "File/folder path '{0}' does not much root folder '{1}'",
                            newFolderPath, rootFolder);

                return(new EntityToken[] { new WebsiteFileElementProviderEntityToken(castedEntityToken.Source, newFolderPath, castedEntityToken.RootPath) });
            }

            return(new EntityToken[] { new WebsiteFileElementProviderRootEntityToken(castedEntityToken.Source, castedEntityToken.RootPath) });
        }
Exemplo n.º 18
0
        private void EmbedExecutionExceptionSourceCode(Exception ex)
        {
            if (ex is ThreadAbortException ||
                ex is StackOverflowException ||
                ex is OutOfMemoryException ||
                ex is ThreadInterruptedException)
            {
                return;
            }

            var stackTrace = new StackTrace(ex, true);

            string fullFilePath = PathUtil.Resolve(VirtualPath);

            foreach (var frame in stackTrace.GetFrames())
            {
                string fileName = frame.GetFileName();

                if (fileName != null && fileName.StartsWith(fullFilePath, StringComparison.InvariantCultureIgnoreCase))
                {
                    var sourceCode = C1File.ReadAllLines(fileName);

                    XhtmlErrorFormatter.EmbedSourceCodeInformation(ex, sourceCode, frame.GetFileLineNumber());
                    return;
                }
            }
        }
        private void initializeCodeActivity_ExecuteCode(object sender, EventArgs e)
        {
            string markup;

            if (C1File.Exists(this.FilePath))
            {
                markup = C1File.ReadAllText(this.FilePath);
            }
            else
            {
                // someone deleted the feature file, but that won't stop us!
                XhtmlDocument template = new XhtmlDocument();
                template.Head.Add("");
                template.Body.Add("");
                markup = template.ToString();
            }

            this.Bindings.Add("FeatureName", this.FeatureName);
            this.Bindings.Add("Markup", markup);

            if (Path.GetExtension(this.FilePath) == ".html")
            {
                this.documentFormActivity1.FormDefinitionFileName = @"\Administrative\PageTemplateFeature\EditVisual.xml";
            }
            else
            {
                this.documentFormActivity1.FormDefinitionFileName = @"\Administrative\PageTemplateFeature\EditMarkup.xml";
            }
        }
        public FlowToken Execute(EntityToken entityToken, ActionToken actionToken, FlowControllerServicesContainer flowControllerServicesContainer)
        {
            string currentConsoleId = flowControllerServicesContainer.GetService <IManagementConsoleMessageService>().CurrentConsoleId;

            string serializedEntityToken = EntityTokenSerializer.Serialize(entityToken);

            StringBuilder sb = new StringBuilder();

            var elementInformationService = flowControllerServicesContainer.GetService <IElementInformationService>();

            if (elementInformationService != null)
            {
                Dictionary <string, string> piggybag = elementInformationService.Piggyback;

                foreach (var kvp in piggybag)
                {
                    Core.Serialization.StringConversionServices.SerializeKeyValuePair(sb, kvp.Key, kvp.Value);
                }
            }

            Guid   id       = Guid.NewGuid();
            string filename = Path.Combine(PathUtil.Resolve(GlobalSettingsFacade.TempDirectory), string.Format("{0}.showinfo", id));

            C1File.WriteAllLines(filename, new string[] { serializedEntityToken, sb.ToString() });

            string url = string.Format("{0}?PiggyBagId={1}", UrlUtils.ResolveAdminUrl("content/views/showelementinformation/Default.aspx"), id);

            ConsoleMessageQueueFacade.Enqueue(new OpenViewMessageQueueItem {
                Url = url, ViewId = Guid.NewGuid().ToString(), ViewType = ViewType.Main, Label = "Show Element Information..."
            }, currentConsoleId);

            return(null);
        }
        private static void LoadC1ConsoleAccessConfig()
        {
            // defaults - keeping these if config file is missing or f****d up somehow
            _forceHttps            = false;
            _allowFallbackToHttp   = true;
            _customHttpsPortNumber = null;

            string c1ConsoleAccessConfigPath = HostingEnvironment.MapPath(c1ConsoleAccessRelativeConfigPath);

            if (C1File.Exists(c1ConsoleAccessConfigPath))
            {
                try
                {
                    XDocument accessDoc = XDocumentUtils.Load(c1ConsoleAccessConfigPath);
                    _allowC1ConsoleRequests = _allowC1ConsoleRequests && (bool)accessDoc.Root.Attribute("enabled");

                    XElement protocolElement = accessDoc.Root.Element("ClientProtocol");
                    _forceHttps          = (bool)protocolElement.Attribute("forceHttps");
                    _allowFallbackToHttp = (bool)protocolElement.Attribute("allowFallbackToHttp");

                    var customHttpsPortNumberAttrib = protocolElement.Attribute("customHttpsPortNumber");

                    if (customHttpsPortNumberAttrib != null && customHttpsPortNumberAttrib.Value.Length > 0)
                    {
                        _customHttpsPortNumber = (int)customHttpsPortNumberAttrib;
                    }
                }
                catch (Exception ex)
                {
                    Log.LogError("Authorization", "Problem parsing '{0}'. Will use defaults and allow normal access. Error was '{1}'", c1ConsoleAccessRelativeConfigPath, ex.Message);
                }
            }
        }
        public FlowToken Execute(EntityToken entityToken, ActionToken actionToken, FlowControllerServicesContainer flowControllerServicesContainer)
        {
            string currentConsoleId = flowControllerServicesContainer.GetService <IManagementConsoleMessageService>().CurrentConsoleId;

            string serializedEntityToken = EntityTokenSerializer.Serialize(entityToken);

            if (actionToken.Serialize() == "ShowGraph")
            {
                string url = string.Format("{0}?EntityToken={1}", UrlUtils.ResolveAdminUrl("content/views/relationshipgraph/Default.aspx"), System.Web.HttpUtility.UrlEncode(serializedEntityToken));

                ConsoleMessageQueueFacade.Enqueue(new OpenViewMessageQueueItem {
                    Url = url, ViewId = Guid.NewGuid().ToString(), ViewType = ViewType.Main, Label = "Show graph..."
                }, currentConsoleId);
            }
            else if (actionToken.Serialize() == "ShowOrientedGraph")
            {
                Guid   id       = Guid.NewGuid();
                string filename = Path.Combine(PathUtil.Resolve(GlobalSettingsFacade.TempDirectory), string.Format("{0}.RelationshipGraph", id));
                C1File.WriteAllLines(filename, new string[] { serializedEntityToken });

                string url = string.Format("{0}?Id={1}", UrlUtils.ResolveAdminUrl("content/views/relationshipgraph/ShowRelationshipOrientedGraph.aspx"), id);

                ConsoleMessageQueueFacade.Enqueue(new OpenViewMessageQueueItem {
                    Url = url, ViewId = Guid.NewGuid().ToString(), ViewType = ViewType.Main, Label = "Show graph..."
                }, currentConsoleId);
            }

            return(null);
        }
Exemplo n.º 23
0
        private IEnumerable <PackageFragmentValidationResult> LoadPackageFragmentInstallerBinaries()
        {
            string binariesDirectory = Path.Combine(this.PackageInstallationDirectory, PackageSystemSettings.BinariesDirectoryName);

            if (!C1Directory.Exists(binariesDirectory))
            {
                yield break;
            }

            foreach (string filename in C1Directory.GetFiles(binariesDirectory))
            {
                string newFilename = Path.Combine(this.TempDirectory, Path.GetFileName(filename));
                C1File.Copy(filename, newFilename);

                Log.LogVerbose("PackageUninstaller", "Loading package uninstaller fragment assembly '{0}'", newFilename);

                Exception exception = null;
                try
                {
                    PackageAssemblyHandler.AddAssembly(newFilename);
                }
                catch (Exception ex)
                {
                    exception = ex;
                }

                if (exception != null)
                {
                    yield return(new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, exception));
                }
            }
        }
Exemplo n.º 24
0
        //public static string AttributeValue(this XElement element, XName attributeName)
        //{
        //    return element.Attributes(attributeName).Select(d => d.Value).FirstOrDefault();
        //}

        //public static string ElementValue(this XElement element, XName elementName)
        //{
        //    return element.Elements(elementName).Select(d => d.Value).FirstOrDefault();
        //}

        //public static IEnumerable<T> NotNull<T>(this IEnumerable<T> source)
        //{
        //    return source.Where(d => d != null);
        //}

        public static void DeleteActivity(this DataConnection conn, Guid activityId, DataSourceId dataSourceId)
        {
            try
            {
                var activity = conn.Get <IActivity>().Where(d => d.Id == activityId).FirstOrDefault();

                var activityChanges = conn.Get <IDataChanges>().Where(d => d.ActivityId == activityId).ToList();

                if (dataSourceId != null)
                {
                    if (dataSourceId.InterfaceType == typeof(IMediaFile))
                    {
                        try
                        {
                            var mediaFileId           = dataSourceId.DataId.GetProperty <Guid>("Id");
                            var mediaFileActivityPath = CleanerFacade.GetMediaFileActivityPath(mediaFileId, activityId);
                            C1File.Delete(mediaFileActivityPath);
                        }
                        catch (Exception e)
                        {
                            Log.LogWarning(CleanerFacade.Title, e);
                        }
                    }
                }

                conn.Delete <IDataChanges>(activityChanges);
                conn.Delete(activity);

                Log.LogVerbose(CleanerFacade.Title, "Delete activity '{0}'".Push(activityId));
            }
            catch
            { }
        }
            public static CachedFunctionInformation Deserialize(string filePath)
            {
                var lines = C1File.ReadAllLines(filePath);

                if (lines == null || lines.Length == 0)
                {
                    return(null);
                }

                Type type = TypeManager.TryGetType(lines[0]);

                if (type == null)
                {
                    return(null);
                }

                bool   preventCaching = bool.Parse(lines[1]);
                string description    = string.Join(Environment.NewLine, lines.Skip(2));

                return(new CachedFunctionInformation
                {
                    Description = description,
                    PreventCaching = preventCaching,
                    ReturnType = type
                });
            }
Exemplo n.º 26
0
        /// <exclude />
        public static XslCompiledTransform GetCompiledXsltTransform(string stylesheetPath)
        {
            lock (_lock)
            {
                DateTime lastXsltFileWrite = C1File.GetLastWriteTime(stylesheetPath);

                bool compiledVersionExists = _xsltLookup.ContainsKey(stylesheetPath);
                bool reloadFresh           = (DateTime.Now - lastXsltFileWrite).Minutes < 30;

                if (compiledVersionExists == false || lastXsltFileWrite > _xsltFileTimestamps[stylesheetPath] || reloadFresh)
                {
                    XslCompiledTransform xslt = new XslCompiledTransform();
                    using (XmlReader reader = XmlReaderUtils.Create(stylesheetPath))
                    {
                        xslt.Load(reader);
                    }

                    if (compiledVersionExists)
                    {
                        _xsltLookup.Remove(stylesheetPath);
                        _xsltFileTimestamps.Remove(stylesheetPath);
                    }

                    _xsltLookup.Add(stylesheetPath, xslt);
                    _xsltFileTimestamps.Add(stylesheetPath, lastXsltFileWrite);
                }
            }

            return(_xsltLookup[stylesheetPath]);
        }
Exemplo n.º 27
0
        private void GetFunctionCode(string copyFromFunctionName, out string markupTemplate, out string code)
        {
            IFunction function = FunctionFacade.GetFunction(copyFromFunctionName);

            if (function is FunctionWrapper)
            {
                function = (function as FunctionWrapper).InnerFunction;
            }

            var    razorFunction = (UserControlBasedFunction)function;
            string filePath      = PathUtil.Resolve(razorFunction.VirtualPath);
            string codeFilePath  = filePath + ".cs";

            Verify.That(C1File.Exists(codeFilePath), "Codebehind file not found: {0}", codeFilePath);

            markupTemplate = C1File.ReadAllText(filePath);
            code           = C1File.ReadAllText(codeFilePath);

            const string quote             = "\"";
            string       codeFileReference = quote + Path.GetFileName(codeFilePath) + quote;

            int codeReferenceOffset = markupTemplate.IndexOf(codeFileReference, StringComparison.OrdinalIgnoreCase);

            Verify.That(codeReferenceOffset > 0, "Failed to find codebehind file reference '{0}'".FormatWith(codeFileReference));

            markupTemplate = markupTemplate.Replace(codeFileReference,
                                                    quote + Marker_CodeFile + quote,
                                                    StringComparison.OrdinalIgnoreCase);
        }
Exemplo n.º 28
0
        internal string LoadAndValidateCustomFormMarkupPath(string customFormMarkupPath)
        {
            string path;

            try
            {
                path = PathUtil.Resolve(customFormMarkupPath);
                if (!C1File.Exists(path))
                {
                    AddValidationError("TreeValidationError.CustomFormMarkup.MissingFile", path);
                    return(customFormMarkupPath);
                }
            }
            catch
            {
                AddValidationError("TreeValidationError.CustomFormMarkup.BadMarkupPath", customFormMarkupPath);
                return(customFormMarkupPath);
            }


            try
            {
                XDocument.Load(path);
            }
            catch (Exception ex)
            {
                Log.LogError(nameof(ActionNode), $"Failed to load xml file '{path}'");
                Log.LogError(nameof(ActionNode), ex);

                AddValidationError("TreeValidationError.CustomFormMarkup.InvalidXml", customFormMarkupPath);
            }

            return(path);
        }
        public void Delete(IEnumerable <DataSourceId> dataSourceIds)
        {
            foreach (DataSourceId dataSourceId in dataSourceIds)
            {
                if (dataSourceId == null)
                {
                    throw new ArgumentException("DataSourceIds must me non-null");
                }
            }

            foreach (DataSourceId dataSourceId in dataSourceIds)
            {
                MediaDataId dataId = dataSourceId.DataId as MediaDataId;

                if (dataId.MediaType == _fileType)
                {
                    if (IsReadOnlyFolder(dataId.Path))
                    {
                        throw new ArgumentException("Cannot delete read only file " + dataId.FileName);
                    }
                    C1File.Delete(GetAbsolutePath(dataId));
                }
                else
                {
                    if (IsReadOnlyFolder(dataId.Path))
                    {
                        throw new ArgumentException("Cannot delete read only folder " + dataId.Path);
                    }
                    C1Directory.Delete(GetAbsolutePath(dataId), true);
                }
            }
        }
Exemplo n.º 30
0
        private void initializeCodeActivity_ExecuteCode(object sender, EventArgs e)
        {
            string path = Path.Combine(PathUtil.Resolve(GlobalSettingsFacade.TreeDefinitionsDirectory), this.Filename);

            this.Bindings.Add("TreeId", Path.GetFileNameWithoutExtension(this.Filename));
            this.Bindings.Add("TreeDefinitionMarkup", C1File.ReadAllText(path));
        }