コード例 #1
0
ファイル: CommentInfo.cs プロジェクト: kimduquan/DMIS
        public CommentInfo(List <Node> comments, List <Node> likesForComments, string markupStr)
        {
            var commentsMarkup = new StringBuilder();
            var hiddenComments = new StringBuilder();

            var index = 0;

            foreach (var comment in comments)
            {
                var likesForComment = likesForComments.Where(l => RepositoryPath.GetParentPath(RepositoryPath.GetParentPath(l.Path)) == comment.Path).ToList();

                var commentGc       = comment as GenericContent;
                var commentLikeInfo = new LikeInfo(likesForComment, commentGc.Id);
                var commentMarkup   = WallHelper.GetCommentMarkup(markupStr, commentGc.CreationDate, commentGc.CreatedBy as User, commentGc.Description, commentGc.Id, commentLikeInfo, comment);

                // if it is one of the last two comments, add it to visible comments list, otherwise to hidden comments list
                if (index < comments.Count - 2)
                {
                    hiddenComments.Append(commentMarkup);
                }
                else
                {
                    commentsMarkup.Append(commentMarkup);
                }
                index++;
            }

            CommentsMarkup       = commentsMarkup.ToString();
            HiddenCommentsMarkup = hiddenComments.ToString();
            CommentCount         = comments.Count;
        }
コード例 #2
0
ファイル: PortalContextModule.cs プロジェクト: kimduquan/DMIS
        private static int?GetCacheHeaderSetting(Uri requestUri, NodeHead requestedNodeHead)
        {
            if (requestUri == null || requestedNodeHead == null)
            {
                return(null);
            }

            var extension   = Path.GetExtension(requestUri.AbsolutePath).ToLower().Trim(new[] { ' ', '.' });
            var contentType = requestedNodeHead.GetNodeType().Name;

            //shortcut: deal with real files only
            if (string.IsNullOrEmpty(extension) || string.IsNullOrEmpty(contentType))
            {
                return(null);
            }

            var cacheHeaderSettings = Settings.GetValue <IEnumerable <CacheHeaderSetting> >(PortalSettings.SETTINGSNAME, PortalSettings.SETTINGS_CACHEHEADERS, requestedNodeHead.Path);

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

            foreach (var chs in cacheHeaderSettings)
            {
                //check if one of the criterias does not match
                var extMismatch        = !string.IsNullOrEmpty(chs.Extension) && chs.Extension != extension;
                var contentTypeMismach = !string.IsNullOrEmpty(chs.ContentType) && chs.ContentType != contentType;
                var pathMismatch       = !string.IsNullOrEmpty(chs.Path) && !requestedNodeHead.Path.StartsWith(RepositoryPath.Combine(chs.Path, "/"));

                if (extMismatch || pathMismatch || contentTypeMismach)
                {
                    continue;
                }

                //found a match
                return(chs.MaxAge);
            }

            return(null);
        }
コード例 #3
0
ファイル: Propfind.cs プロジェクト: y1027/sensenet
        internal void WriteSingleItem(Node node, WebdavType wdType, string binaryPropertyName)
        {
            // set nodeName extensions
            var nodeName = node.Name;
            var nodePath = node.Path;

            if (wdType == WebdavType.Content)
            {
                nodeName = nodeName + ".Content";
                nodePath = nodePath + ".Content";
            }
            else if (wdType == WebdavType.ContentType)
            {
                nodeName = nodeName + "Ctd.xml";
                nodePath = nodePath + "Ctd.xml";
            }
            else if (wdType != WebdavType.Folder)
            {
                if (binaryPropertyName != "Binary")
                {
                    nodeName = string.Concat(node.Name, ".", binaryPropertyName);
                }

                nodePath = RepositoryPath.Combine(node.ParentPath, nodeName);
            }

            // response
            _writer.WriteStartElement(XmlNS.DAV_Prefix, "response", XmlNS.DAV);
            // href
            _writer.WriteStartElement(XmlNS.DAV_Prefix, "href", XmlNS.DAV);
            _writer.WriteString(_handler.RepositoryPathToUrl(nodePath));
            _writer.WriteEndElement();

            // propstat
            _writer.WriteStartElement(XmlNS.DAV_Prefix, "propstat", XmlNS.DAV);
            // propstat/status
            _writer.WriteStartElement(XmlNS.DAV_Prefix, "status", XmlNS.DAV);

            _writer.WriteString("HTTP/1.1 200 OK");
            _writer.WriteEndElement(); // propstat/status

            // propstat/prop
            _writer.WriteStartElement(XmlNS.DAV_Prefix, "prop", XmlNS.DAV);

            // propstat/prop/getcontentlenght
            _writer.WriteStartElement(XmlNS.DAV_Prefix, "getcontentlength", XmlNS.DAV);

            if (wdType == WebdavType.File)
            {
                var f = node as IFile;
                if (f != null && node.SavingState == ContentSavingState.Finalized)
                {
                    _writer.WriteString(((BinaryData)node[binaryPropertyName]).Size.ToString());
                }
                else
                {
                    _writer.WriteString("0");
                }
            }
            else
            {
                _writer.WriteString("0");
            }

            _writer.WriteEndElement(); // propstat/prop/getcontentlenght

            // lockdiscovery
            if (node.Locked)
            {
                Lock.WriteLockDiscovery(_writer, node, node.LockTimeout);
            }

            // supportedlock
            _writer.WriteStartElement(XmlNS.DAV_Prefix, "supportedlock", XmlNS.DAV);
            _writer.WriteStartElement(XmlNS.DAV_Prefix, "lockentry", XmlNS.DAV);
            _writer.WriteStartElement(XmlNS.DAV_Prefix, "lockscope", XmlNS.DAV);
            _writer.WriteStartElement(XmlNS.DAV_Prefix, "exclusive", XmlNS.DAV);
            _writer.WriteEndElement(); // exclusive
            _writer.WriteEndElement(); // lockscope
            _writer.WriteStartElement(XmlNS.DAV_Prefix, "locktype", XmlNS.DAV);
            _writer.WriteStartElement(XmlNS.DAV_Prefix, "write", XmlNS.DAV);
            _writer.WriteEndElement(); // write
            _writer.WriteEndElement(); // locktype
            _writer.WriteEndElement(); // lockentry
            _writer.WriteEndElement(); // supportedlock

            // propstat/prop/creationdate
            _writer.WriteStartElement(XmlNS.DAV_Prefix, "creationdate", XmlNS.DAV);
            _writer.WriteString(node.CreationDate.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.sZ"));
            _writer.WriteEndElement(); // propstat/prop/creationdate

            // propstat/prop/displayname
            _writer.WriteStartElement(XmlNS.DAV_Prefix, "displayname", XmlNS.DAV);

            _writer.WriteString(nodeName);
            _writer.WriteEndElement(); // propstat/prop/displayname

            var eTag = Guid.NewGuid().ToString();

            // propstat/prop/getetag
            _writer.WriteStartElement(XmlNS.DAV_Prefix, "getetag", XmlNS.DAV);
            _writer.WriteString(eTag);
            _writer.WriteEndElement(); // propstat/prop/getetag

            // propstat/prop/getlastmodified
            _writer.WriteStartElement(XmlNS.DAV_Prefix, "getlastmodified", XmlNS.DAV);
            _writer.WriteString(node.ModificationDate.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.sZ"));
            _writer.WriteEndElement(); // propstat/prop/getlastmodified

            // propstat/prop/resourcetype
            _writer.WriteStartElement(XmlNS.DAV_Prefix, "resourcetype", XmlNS.DAV);
            if (wdType == WebdavType.Folder)
            {
                // propstat/prop/resourcetype/collection
                _writer.WriteStartElement(XmlNS.DAV_Prefix, "collection", XmlNS.DAV);
                _writer.WriteEndElement(); // propstat/prop/resourcetype/collection
            }
            _writer.WriteEndElement();     // propstat/prop/resourcetype

            _writer.WriteStartElement(XmlNS.MSRepl_Prefix, "repl-uid", XmlNS.MSRepl);
            _writer.WriteString("rid:{");
            _writer.WriteString(eTag);
            _writer.WriteString("}");
            _writer.WriteEndElement();

            _writer.WriteStartElement(XmlNS.MSRepl_Prefix, "resourcetag", XmlNS.MSRepl);
            _writer.WriteString("rt:");
            _writer.WriteString(eTag);
            _writer.WriteString("@00000000000");
            _writer.WriteEndElement();

            // propstat/prop/isFolder
            _writer.WriteStartElement(XmlNS.DAV_Prefix, "isfolder", XmlNS.DAV);
            if (wdType == WebdavType.Folder)
            {
                _writer.WriteString("t");
            }
            else
            {
                _writer.WriteString("0");
            }
            _writer.WriteEndElement(); // propstat/prop/isFolder

            // propstat/prop/iscollection
            _writer.WriteStartElement(XmlNS.DAV_Prefix, "iscollection", XmlNS.DAV);
            if (wdType == WebdavType.Folder)
            {
                _writer.WriteString("1");
            }
            else
            {
                _writer.WriteString("0");
            }
            _writer.WriteEndElement(); // propstat/prop/iscollection

            // propstat/prop/getcontenttype
            _writer.WriteStartElement(XmlNS.DAV_Prefix, "getcontenttype", XmlNS.DAV);
            if (wdType == WebdavType.Folder)
            {
                _writer.WriteString("application/octet-stream");
            }
            else
            {
                _writer.WriteString("text/xml");
            }
            _writer.WriteEndElement(); // propstat/prop/getcontenttype
            _writer.WriteEndElement(); // propstat/prop
            _writer.WriteEndElement(); // propstat
            _writer.WriteEndElement(); // response
        }
コード例 #4
0
ファイル: ContentListTest.cs プロジェクト: vlslavik/SenseNet
        public void ContentList_Modify()
        {
            List <string> listDefs = new List <string>();

            listDefs.Add(@"<?xml version='1.0' encoding='utf-8'?>
<ContentListDefinition xmlns='http://schemas.sensenet.com/SenseNet/ContentRepository/ContentListDefinition'>
	<Fields>
	</Fields>
</ContentListDefinition>
");
            listDefs.Add(@"<?xml version='1.0' encoding='utf-8'?>
<ContentListDefinition xmlns='http://schemas.sensenet.com/SenseNet/ContentRepository/ContentListDefinition'>
	<Fields>
		<ContentListField name='#LF0' type='ShortText' />
		<ContentListField name='#LF1' type='ShortText' />
	</Fields>
</ContentListDefinition>
");
            listDefs.Add(@"<?xml version='1.0' encoding='utf-8'?>
<ContentListDefinition xmlns='http://schemas.sensenet.com/SenseNet/ContentRepository/ContentListDefinition'>
	<Fields>
		<ContentListField name='#LF0' type='ShortText' />
	</Fields>
</ContentListDefinition>
");
            listDefs.Add(@"<?xml version='1.0' encoding='utf-8'?>
<ContentListDefinition xmlns='http://schemas.sensenet.com/SenseNet/ContentRepository/ContentListDefinition'>
	<Fields>
	</Fields>
</ContentListDefinition>
");
            listDefs.Add(@"<?xml version='1.0' encoding='utf-8'?>
<ContentListDefinition xmlns='http://schemas.sensenet.com/SenseNet/ContentRepository/ContentListDefinition'>
	<Fields>
		<ContentListField name='#LF0' type='ShortText' />
		<ContentListField name='#LF1' type='ShortText' />
		<ContentListField name='#LF2' type='ShortText' />
	</Fields>
</ContentListDefinition>
");
            listDefs.Add(@"<?xml version='1.0' encoding='utf-8'?>
<ContentListDefinition xmlns='http://schemas.sensenet.com/SenseNet/ContentRepository/ContentListDefinition'>
	<Fields>
		<ContentListField name='#LF0' type='ShortText' />
		<ContentListField name='#LF2' type='ShortText' />
	</Fields>
</ContentListDefinition>
");
            listDefs.Add(@"<?xml version='1.0' encoding='utf-8'?>
<ContentListDefinition xmlns='http://schemas.sensenet.com/SenseNet/ContentRepository/ContentListDefinition'>
	<Fields>
		<ContentListField name='#LF0' type='ShortText' />
		<ContentListField name='#LF1' type='ShortText' />
		<ContentListField name='#LF2' type='ShortText' />
	</Fields>
</ContentListDefinition>
");
            listDefs.Add(@"<?xml version='1.0' encoding='utf-8'?>
<ContentListDefinition xmlns='http://schemas.sensenet.com/SenseNet/ContentRepository/ContentListDefinition'>
	<Fields>
		<ContentListField name='#LF2' type='ShortText' />
	</Fields>
</ContentListDefinition>
");
            listDefs.Add(@"<?xml version='1.0' encoding='utf-8'?>
<ContentListDefinition xmlns='http://schemas.sensenet.com/SenseNet/ContentRepository/ContentListDefinition'>
	<Fields>
		<ContentListField name='#LF0' type='ShortText' />
		<ContentListField name='#LF3' type='ShortText' />
		<ContentListField name='#LF2' type='ShortText' />
	</Fields>
</ContentListDefinition>
");
            listDefs.Add(@"<?xml version='1.0' encoding='utf-8'?>
<ContentListDefinition xmlns='http://schemas.sensenet.com/SenseNet/ContentRepository/ContentListDefinition'>
	<Fields>
		<ContentListField name='#LF0' type='ShortText' />
		<ContentListField name='#LF1' type='ShortText' />
		<ContentListField name='#LF2' type='ShortText' />
	</Fields>
</ContentListDefinition>
");

            string listName = "List1";
            string listPath = RepositoryPath.Combine(this.TestRoot.Path, listName);

            if (Node.Exists(listPath))
            {
                Node.ForceDelete(listPath);
            }

            ContentList list = new ContentList(this.TestRoot);

            list.Name = listName;
            list.AllowedChildTypes = new ContentType[] { ContentType.GetByName("Car") };

            list.Save();

            Node car = new GenericContent(list, "Car");

            car.Name = "Kispolszki";
            car.Save();
            int carId = car.Id;

            StringBuilder log = new StringBuilder();

            for (int def = 0; def < listDefs.Count; def++)
            {
                Exception ex = null;
                for (var i = 0; i < 10; i++)
                {
                    try
                    {
                        ex   = null;
                        list = Node.Load <ContentList>(listPath);
                        list.ContentListDefinition = listDefs[def];
                        list.Save();
                        break;
                    }
                    catch (Exception e)
                    {
                        ex = e;
                        System.Threading.Thread.Sleep(200);
                        Debug.WriteLine("@> {0}. {1} / {2}", i, def, listDefs.Count);
                    }
                }
                if (ex != null)
                {
                    throw new ApplicationException("Exception after 10 iteration: " + ex.Message, ex);
                }


                car = Node.LoadNode(carId);
                log.Append("Def_").Append(def).Append(": ");
                for (int i = 0; i < 4; i++)
                {
                    var propName = "#String_" + i;
                    if (car.HasProperty(propName))
                    {
                        log.Append("[").Append(propName).Append(" = ").Append(car.PropertyTypes[propName].Mapping).Append("]");
                    }
                }
                log.Append("\r\n");
            }

            string realLog     = log.Replace("\r\n", "").Replace(" ", "").Replace("\t", "").ToString();
            string expectedLog = @"
				Def_0: 
				Def_1: [#String_0 = 800000000][#String_1 = 800000001]
				Def_2: [#String_0 = 800000000]
				Def_3: 
				Def_4: [#String_0 = 800000000][#String_1 = 800000001][#String_2 = 800000002]
				Def_5: [#String_0 = 800000000][#String_2 = 800000002]
				Def_6: [#String_0 = 800000000][#String_1 = 800000001][#String_2 = 800000002]
				Def_7: [#String_2 = 800000002]
				Def_8: [#String_0 = 800000000][#String_1 = 800000001][#String_2 = 800000002]
				Def_9: [#String_0 = 800000000][#String_2 = 800000002][#String_3 = 800000003]
				"                .Replace("\r\n", "").Replace(" ", "").Replace("\t", "");

            Assert.IsTrue(realLog == expectedLog);
        }
コード例 #5
0
ファイル: ContentListTest.cs プロジェクト: vlslavik/SenseNet
        private string CheckListTypeXmlNamespaceCompatibility(string xmlNamespace, string namespaceName, bool featureEnabled)
        {
            var compat = RepositoryConfiguration.BackwardCompatibilityXmlNamespaces;

            SetBackwardCompatibilityXmlNamespaces(featureEnabled);

            var    fieldName = "#ListField1";
            string listDef   = String.Format(@"<ContentListDefinition xmlns='{0}'><Fields>
                <ContentListField name='{1}' type='ShortText' /></Fields></ContentListDefinition>", xmlNamespace, fieldName);

            string listPath = RepositoryPath.Combine(this.TestRoot.Path, "Cars");

            if (Node.Exists(listPath))
            {
                Node.ForceDelete(listPath);
            }

            ContentList list;
            int         listId = 0;

            try
            {
                list      = new ContentList(this.TestRoot);
                list.Name = "Cars";
                list.ContentListDefinition = listDef;
                list.Save();
                listId = list.Id;
                list   = Node.Load <ContentList>(listId);
            }
            catch (Exception e)
            {
                SetBackwardCompatibilityXmlNamespaces(compat);
                return(String.Concat("Cannot create List (", namespaceName, "): ", e.Message));
            }

            var fieldValue = Guid.NewGuid().ToString();
            var content    = Content.CreateNew("Car", list, "XmlNamespaceCompatibilityContent");

            if (!content.Fields.ContainsKey(fieldName))
            {
                SetBackwardCompatibilityXmlNamespaces(compat);
                return(String.Concat("Missing field (", namespaceName, ")"));
            }

            content[fieldName] = fieldValue;

            try
            {
                content.Save();
            }
            catch (Exception e)
            {
                SetBackwardCompatibilityXmlNamespaces(compat);
                var msg = String.Concat("Cannot save a ListItem (", namespaceName, "): ", e.Message, e.StackTrace.Replace("\r", " ").Replace("\n", " "));
                Debug.WriteLine(msg);
                return(msg);
            }

            var id = content.Id;

            try
            {
                content = Content.Load(id);
            }
            catch (Exception e)
            {
                SetBackwardCompatibilityXmlNamespaces(compat);
                return(String.Concat("Cannot load back a ListItem (", namespaceName, "): ", e.Message));
            }

            var loadedValue = (string)content[fieldName];

            //content.Delete();
            Node.ForceDelete(id);

            SetBackwardCompatibilityXmlNamespaces(compat);

            if (loadedValue != fieldValue)
            {
                return(String.Concat("Inconsistent field value (", namespaceName, ")"));
            }

            if (list.ContentListDefinition != listDef)
            {
                return(String.Concat("List definition xml is modified (", namespaceName, ")"));
            }

            return(null);
        }
コード例 #6
0
ファイル: DataProvider.cs プロジェクト: sztomi/sensenet
        internal void SaveNodeData(NodeData nodeData, NodeSaveSettings settings, out int lastMajorVersionId, out int lastMinorVersionId)
        {
            if (nodeData == null)
            {
                throw new ArgumentNullException("nodeData");
            }

            lastMajorVersionId = 0;
            lastMinorVersionId = 0;

            bool isNewNode = nodeData.Id == 0; // shortcut

            var parent = NodeHead.Get(nodeData.ParentId);

            if (parent == null)
            {
                throw new ContentNotFoundException(nodeData.ParentId.ToString());
            }

            var path = RepositoryPath.Combine(parent.Path, nodeData.Name);

            Node.AssertPath(path);

            nodeData.Path = path;

            var writer = this.CreateNodeWriter();

            try
            {
                var savingAlgorithm = settings.GetSavingAlgorithm();

                writer.Open();
                if (settings.NeedToSaveData)
                {
                    SaveNodeBaseData(nodeData, savingAlgorithm, writer, settings, out lastMajorVersionId, out lastMinorVersionId);

                    BenchmarkCounter.IncrementBy(BenchmarkCounter.CounterName.SaveNodeBaseData, nodeData.SavingTimer.ElapsedTicks);
                    nodeData.SavingTimer.Restart();

                    if (!isNewNode && nodeData.PathChanged && nodeData.SharedData != null)
                    {
                        writer.UpdateSubTreePath(nodeData.SharedData.Path, nodeData.Path);
                    }
                    SaveNodeProperties(nodeData, savingAlgorithm, writer, isNewNode);
                }
                else
                {
                    writer.UpdateNodeRow(nodeData);
                }
                writer.Close();

                BenchmarkCounter.IncrementBy(BenchmarkCounter.CounterName.SaveNodeFlatProperties, nodeData.SavingTimer.ElapsedTicks);
                nodeData.SavingTimer.Restart();

                foreach (var versionId in settings.DeletableVersionIds)
                {
                    DeleteVersion(versionId, nodeData, out lastMajorVersionId, out lastMinorVersionId);
                }
            }
            catch // rethrow
            {
                if (isNewNode)
                {
                    // Failed save: set NodeId back to 0
                    nodeData.Id = 0;
                }

                throw;
            }
        }
コード例 #7
0
ファイル: ContentListTest.cs プロジェクト: vlslavik/SenseNet
        public void ContentList_DeleteField()
        {
            string listDef = @"<?xml version='1.0' encoding='utf-8'?>
<ContentListDefinition xmlns='http://schemas.sensenet.com/SenseNet/ContentRepository/ContentListDefinition'>
	<DisplayName>Cars title</DisplayName>
	<Description>Cars description</Description>
	<Icon>automobile.gif</Icon>
	<Fields>
		<ContentListField name='#ListField1' type='ShortText'>
			<DisplayName>ContentListField1</DisplayName>
			<Description>ContentListField1 Description</Description>
			<Icon>icon.gif</Icon>
			<Configuration>
				<MaxLength>100</MaxLength>
			</Configuration>
		</ContentListField>
		<ContentListField name='#ListField2' type='WhoAndWhen'>
			<DisplayName>ContentListField2</DisplayName>
			<Description>ContentListField2 Description</Description>
			<Icon>icon.gif</Icon>
			<Configuration>
			</Configuration>
		</ContentListField>
		<ContentListField name='#ListField3' type='ShortText'>
			<DisplayName>ContentListField3</DisplayName>
			<Description>ContentListField3 Description</Description>
			<Icon>icon.gif</Icon>
			<Configuration>
				<MaxLength>200</MaxLength>
			</Configuration>
		</ContentListField>
	</Fields>
</ContentListDefinition>
";
            string path    = RepositoryPath.Combine(this.TestRoot.Path, "Cars");

            if (Node.Exists(path))
            {
                Node.ForceDelete(path);
            }

            var list = new ContentList(this.TestRoot)
            {
                Name = "Cars",
                ContentListDefinition = listDef,
                AllowedChildTypes     = new ContentType[] { ContentType.GetByName("Car") }
            };

            list.Save();

            Node car = new GenericContent(list, "Car");

            car.Name         = "Kispolszki";
            car["#String_0"] = "ABC 34-78";
            car.Save();

            list = Node.Load <ContentList>(list.Path);
            var fs = Content.Create(car).Fields["#ListField3"].FieldSetting;

            list.DeleteField(fs);

            var cc = Content.Load(car.Path);

            Assert.IsTrue(!cc.Fields.ContainsKey("#ListField3"));
        }
コード例 #8
0
ファイル: PostInfo.cs プロジェクト: vlslavik/SenseNet
        public PostInfo(JournalItem journalItem, string lastPath)
        {
            IsJournal    = true;
            LastPath     = lastPath;
            CreationDate = journalItem.When;
            var backspIndex = journalItem.Who.IndexOf('\\');

            if (backspIndex != -1)
            {
                var domain = journalItem.Who.Substring(0, backspIndex);
                var name   = journalItem.Who.Substring(backspIndex + 1);
                CreatedBy = User.Load(domain, name);
            }

            //var contentName = string.Empty;
            //if (journalItem.Wherewith.StartsWith(contextPath))
            //{
            //    contentName = journalItem.Wherewith.Substring(contextPath.Length).TrimStart('/');
            //    // if workspace relative path is empty, the context path is the workspace itself
            //    if (string.IsNullOrEmpty(contentName))
            //        contentName = RepositoryPath.GetFileName(contextPath);
            //}
            //else
            //{
            //    contentName = RepositoryPath.GetFileName(journalItem.Wherewith);
            //}

            var what    = journalItem.What.ToLower();
            var typeStr = string.Empty;

            // type & type string
            if (what == "created")
            {
                Type    = PostType.JournalCreated;
                typeStr = SNSR.GetString(SNSR.Wall.What_Created);
            }
            else if (what == "modified")
            {
                Type    = PostType.JournalModified;
                typeStr = SNSR.GetString(SNSR.Wall.What_Modified);
            }
            else if (what == "deleted" || what == "deletedphysically")
            {
                Type    = PostType.JournalDeletedPhysically;
                typeStr = SNSR.GetString(SNSR.Wall.What_Deleted);
            }
            else if (what == "moved")
            {
                Type    = PostType.JournalMoved;
                typeStr = SNSR.GetString(SNSR.Wall.What_Moved);
            }
            else if (what == "copied")
            {
                Type    = PostType.JournalCopied;
                typeStr = SNSR.GetString(SNSR.Wall.What_Copied);
            }
            else
            {
                throw new NotImplementedException(String.Format("Processing '{0}' journal type is not implemented", what));
            }

            var displyaName       = SenseNetResourceManager.Current.GetString(journalItem.DisplayName);
            var targetDisplayName = SenseNetResourceManager.Current.GetString(journalItem.TargetDisplayName);

            Text = Type == PostType.JournalCopied || Type == PostType.JournalMoved ?
                   string.Format("{0} <a href='{1}'>{2}</a> {5} <a href='{3}'>{4}</a>", typeStr, "{{path}}", displyaName, journalItem.TargetPath, targetDisplayName, SNSR.GetString(SNSR.Wall.What_To)) :
                   string.Format("{0} <a href='{1}'>{2}</a>", typeStr, "{{path}}", displyaName);

            JournalId = journalItem.Id; // journal's id to leave out item from wall if post already exists
            Id        = journalItem.Id;
            ClientId  = "J" + Id.ToString();
            Path      = lastPath;

            // details
            switch (Type)
            {
            case PostType.JournalModified:
                Details = journalItem.Details;
                break;

            case PostType.JournalMoved:
                Details = string.Format("{2}: <a href='{0}'>{0}</a><br/>{3}: <a href='{1}'>{1}</a>", RepositoryPath.GetParentPath(journalItem.SourcePath), journalItem.TargetPath, SNSR.GetString(SNSR.Wall.Source), SNSR.GetString(SNSR.Wall.Target));
                break;

            case PostType.JournalCopied:
                Details = string.Format("{2}: <a href='{0}'>{0}</a><br/>{3}: <a href='{1}'>{1}</a>", RepositoryPath.GetParentPath(journalItem.Wherewith), journalItem.TargetPath, SNSR.GetString(SNSR.Wall.Source), SNSR.GetString(SNSR.Wall.Target));
                break;

            default:
                break;
            }

            //SharedContent = Node.LoadNode(journalItem.Wherewith);
        }
コード例 #9
0
 public string GetParentPathSafe()
 {
     return(RepositoryPath.GetParentPath(ContentPath));
 }
コード例 #10
0
ファイル: BinaryDataTest.cs プロジェクト: vlslavik/SenseNet
        public void BinaryData_RenameFileNode()
        {
            string rootName = "BinaryTestFolder";
            string rootPath = RepositoryPath.Combine(this.TestRoot.Path, rootName);

            if (Node.Exists(rootPath))
            {
                Node.ForceDelete(rootPath);
            }

            Folder folder = new Folder(this.TestRoot);

            folder.Name = rootName;
            folder.Save();

            Stream stream;

            const int TESTBINARY_SIZE = 512 * 1024; // 512k

            byte[] testBinaryArray = new byte[TESTBINARY_SIZE];
            int    i;

            for (i = 0; i < TESTBINARY_SIZE; i++)
            {
                testBinaryArray[i] = Convert.ToByte(i % 256);
            }

            BinaryData testBinary = new BinaryData();

            testBinary.FileName = "test.txt";
            testBinary.SetStream(new MemoryStream(testBinaryArray));

            File file = new File(folder);

            file.Name   = "OriginalName";
            file.Binary = testBinary;

            file.Save();

            stream = file.Binary.GetStream();

            file = null;

            int readByte;

            i = 0;
            while ((readByte = stream.ReadByte()) != -1)
            {
                Assert.IsTrue(readByte == i % 256);
                i++;
            }
            Assert.IsTrue(i == TESTBINARY_SIZE);

            file      = (File)File.LoadNode(RepositoryPath.Combine(rootPath, "OriginalName"));
            file.Name = "NewName";
            file.Save();

            file   = (File)File.LoadNode(RepositoryPath.Combine(rootPath, "NewName"));
            stream = file.Binary.GetStream();

            file = null;

            i = 0;
            while ((readByte = stream.ReadByte()) != -1)
            {
                Assert.IsTrue(readByte == i % 256);
                i++;
            }

            if (Node.Exists(rootPath))
            {
                Node.ForceDelete(rootPath);
            }

            Assert.IsTrue(i == TESTBINARY_SIZE);
        }
コード例 #11
0
ファイル: BinaryDataTest.cs プロジェクト: vlslavik/SenseNet
        public void BinaryData_RenameNodeWithBinaryData()
        {
            string rootName = "BinaryTestFolder";
            string rootPath = RepositoryPath.Combine(this.TestRoot.Path, rootName);

            if (Node.Exists(rootPath))
            {
                Node.ForceDelete(rootPath);
            }

            Folder binaryTestFolder = new Folder(this.TestRoot);

            binaryTestFolder.Name = rootName;
            binaryTestFolder.Save();

            TestNodeWithBinaryProperty tn1 = new TestNodeWithBinaryProperty(binaryTestFolder);

            tn1.Name = "OriginalName";
            tn1.Note = "This is the first test node. Nice, isn't it?";

            BinaryData firstBinary = new BinaryData();

            firstBinary.SetStream(new MemoryStream(new byte[] { 65, 66, 67, 68, 69 }));
            tn1.FirstBinary          = firstBinary;
            tn1.FirstBinary.FileName = "test";

            BinaryData secondBinary = new BinaryData();

            secondBinary.SetStream(new MemoryStream(new byte[] { 97, 98, 99 }));
            tn1.SecondBinary          = secondBinary;
            tn1.SecondBinary.FileName = "test";
            tn1.Save();

            // Drop the in-memory node and load from the Repository
            int testNodeId = tn1.Id;

            tn1 = null;
            TestNodeWithBinaryProperty loadedNode = (TestNodeWithBinaryProperty)Node.LoadNode(testNodeId);

            Stream firstStream  = loadedNode.FirstBinary.GetStream();
            Stream secondStream = loadedNode.SecondBinary.GetStream();

            byte[] firstBuffer  = new byte[firstStream.Length];
            byte[] secondBuffer = new byte[secondStream.Length];

            firstStream.Read(firstBuffer, 0, (int)firstStream.Length);
            secondStream.Read(secondBuffer, 0, (int)secondStream.Length);

            Assert.IsTrue(System.Text.Encoding.ASCII.GetString(firstBuffer) == "ABCDE", "The first binary had became corrupt after save.");
            Assert.IsTrue(System.Text.Encoding.ASCII.GetString(secondBuffer) == "abc", "The second binary had became corrupt after save.");

            // Close and dispost streams
            firstStream.Close();
            firstStream.Dispose();
            firstStream = null;
            secondStream.Close();
            secondStream.Dispose();
            secondStream = null;

            // The buffers should still hold  the data
            Assert.IsTrue(System.Text.Encoding.ASCII.GetString(firstBuffer) == "ABCDE", "The first binary had became corrupt after save.");
            Assert.IsTrue(System.Text.Encoding.ASCII.GetString(secondBuffer) == "abc", "The second binary had became corrupt after save.");

            firstBuffer  = null;
            secondBuffer = null;

            // Get the stream again
            firstStream  = loadedNode.FirstBinary.GetStream();
            secondStream = loadedNode.SecondBinary.GetStream();

            firstBuffer  = new byte[firstStream.Length];
            secondBuffer = new byte[secondStream.Length];

            firstStream.Read(firstBuffer, 0, (int)firstStream.Length);
            secondStream.Read(secondBuffer, 0, (int)secondStream.Length);

            Assert.IsTrue(System.Text.Encoding.ASCII.GetString(firstBuffer) == "ABCDE", "The first binary had became corrupt after save.");
            Assert.IsTrue(System.Text.Encoding.ASCII.GetString(secondBuffer) == "abc", "The second binary had became corrupt after save.");

            // Close and dispost streams
            firstStream.Close();
            firstStream.Dispose();
            firstStream = null;
            secondStream.Close();
            secondStream.Dispose();
            secondStream = null;

            // The buffers should still hold  the data
            Assert.IsTrue(System.Text.Encoding.ASCII.GetString(firstBuffer) == "ABCDE", "The first binary had became corrupt after save.");
            Assert.IsTrue(System.Text.Encoding.ASCII.GetString(secondBuffer) == "abc", "The second binary had became corrupt after save.");

            // Change the name
            loadedNode.Name = "ModifiedName";
            loadedNode.Save();
            loadedNode = null;

            // Load the node again
            loadedNode = (TestNodeWithBinaryProperty)Node.LoadNode(testNodeId);

            Assert.IsTrue(loadedNode.Name == "ModifiedName");

            // Get the stream again
            firstStream  = loadedNode.FirstBinary.GetStream();
            secondStream = loadedNode.SecondBinary.GetStream();

            firstBuffer  = new byte[firstStream.Length];
            secondBuffer = new byte[secondStream.Length];

            firstStream.Read(firstBuffer, 0, (int)firstStream.Length);
            secondStream.Read(secondBuffer, 0, (int)secondStream.Length);

            Assert.IsTrue(System.Text.Encoding.ASCII.GetString(firstBuffer) == "ABCDE", "The first binary had became corrupt after save.");
            Assert.IsTrue(System.Text.Encoding.ASCII.GetString(secondBuffer) == "abc", "The second binary had became corrupt after save.");


            // Cleanup test nodes
            binaryTestFolder.ForceDelete();
        }
コード例 #12
0
        public static string GetWallPostsMarkup(string contextPath, List <PostInfo> posts)
        {
            if (posts.Count == 0)
            {
                return(string.Empty);
            }

            // create query for comments and likes
            var csb   = new StringBuilder();
            var paths = new List <string>();

            foreach (var postInfo in posts)
            {
                if (postInfo.IsJournal)
                {
                    continue;
                }
                paths.Add(postInfo.Path);
            }

            List <Node> allComments;
            List <Node> allLikes;

            if (paths.Count == 0)    // only non-persisted journal posts are there to show (no comments or likes)
            {
                allComments = new List <Node>();
                allLikes    = new List <Node>();
            }
            else
            {
                var settings = new QuerySettings()
                {
                    EnableAutofilters = FilterStatus.Disabled
                };
                var allCommentsAndLikes = ContentQuery.Query(ContentRepository.SafeQueries.InTreeAndTypeIs, settings,
                                                             paths, new[] { "Comment", "Like" }).Nodes.ToList();

                var commentNodeTypeId = NodeType.GetByName("Comment").Id;
                var likeTypeId        = NodeType.GetByName("Like").Id;

                allComments = allCommentsAndLikes.Where(c => c.NodeTypeId == commentNodeTypeId).ToList();
                allLikes    = allCommentsAndLikes.Where(l => l.NodeTypeId == likeTypeId).ToList();
            }

            var bigPostMarkupStr   = GetBigPostMarkupStr();
            var smallPostMarkupStr = GetSmallPostMarkupStr();
            var commentMarkupStr   = GetCommentMarkupStr();
            var commentSectionStr  = GetCommentSectionMarkupStr();

            PostInfo prevPost = null;
            var      sb       = new StringBuilder();

            foreach (var postInfo in posts)
            {
                // get comments and likes for post
                CommentInfo commentInfo;
                LikeInfo    likeInfo;

                if (postInfo.IsJournal)
                {
                    commentInfo = new CommentInfo();
                    likeInfo    = new LikeInfo();
                }
                else
                {
                    var commentsForPost         = allComments.Where(c => RepositoryPath.GetParentPath(RepositoryPath.GetParentPath(c.Path)) == postInfo.Path).ToList();
                    var likesForPostAndComments = allLikes.Where(l => l.Path.StartsWith(postInfo.Path)).ToList();
                    var likesForPost            = likesForPostAndComments.Where(l => RepositoryPath.GetParentPath(RepositoryPath.GetParentPath(l.Path)) == postInfo.Path).ToList();

                    commentInfo = new CommentInfo(commentsForPost, likesForPostAndComments, commentMarkupStr);
                    likeInfo    = new LikeInfo(likesForPost, postInfo.Id);
                }

                var drawBoundary = (prevPost != null) && (prevPost.Type != PostType.BigPost) && (postInfo.Type == PostType.BigPost);

                var markup = WallHelper.GetPostMarkup(
                    postInfo.Type == PostType.BigPost ? bigPostMarkupStr : smallPostMarkupStr,
                    commentSectionStr,
                    postInfo,
                    contextPath,
                    commentInfo.HiddenCommentsMarkup,
                    commentInfo.CommentsMarkup,
                    commentInfo.CommentCount,
                    likeInfo, drawBoundary);

                prevPost = postInfo;

                sb.Append(markup);
            }
            return(sb.ToString());
        }
コード例 #13
0
 public static IEnumerable <File> GetViewsForContainer(Node container)
 {
     return(Content.All.DisableAutofilters().OfType <File>().Where(c => c.Name.EndsWith(".ascx") && c.InTree(RepositoryPath.Combine(container.Path, VIEWSFOLDERNAME))));
 }
コード例 #14
0
        public void CrossDomain_RenameSubtree()
        {
            DistributedApplication.ClusterChannel.Purge();

            var fileContent = "File text";

            var folder = new Folder(TestRoot);

            folder.Save();
            var folderId   = folder.Id;
            var folderPath = folder.Path;
            var folderName = folder.Name;

            var file = new File(folder);

            file.Binary.SetStream(Tools.GetStreamFromString(fileContent));
            file.Save();
            var fileId   = file.Id;
            var filePath = file.Path;
            var fileName = file.Name;

            var foldersAfterCreate   = AllEngine_LoadNode(folderPath);
            var filesAfterCreate     = AllEngine_LoadNode(filePath);
            var cacheKeysAfterCreate = AllEngine_GetCacheKeys();

            folder      = Node.Load <Folder>(folderId);
            folder.Name = "Renamed";
            folder.Save();
            var newFolderPath = RepositoryPath.Combine(TestRoot.Path, folder.Name);
            var newFilePath   = RepositoryPath.Combine(newFolderPath, file.Name);

            var foldersAfterRenameOld = AllEngine_LoadNode(folderPath);
            var filesAfterRenameOld   = AllEngine_LoadNode(filePath);
            var foldersAfterRenameNew = AllEngine_LoadNode(newFolderPath);
            var filesAfterRenameNew   = AllEngine_LoadNode(newFilePath);
            var cacheKeysAfterRename  = AllEngine_GetCacheKeys();
            var filecontents          = AllEngine_GetFileContents(newFilePath);

            Node.ForceDelete(folderId);

            var foldersAfterDeleteOld = AllEngine_LoadNode(folderPath);
            var filesAfterDeleteOld   = AllEngine_LoadNode(filePath);
            var foldersAfterDeleteNew = AllEngine_LoadNode(folderPath);
            var filesAfterDeleteNew   = AllEngine_LoadNode(filePath);
            var cacheKeysAfterDelete  = AllEngine_GetCacheKeys();

            DistributedApplication.ClusterChannel.Purge();

            Assert.IsTrue(foldersAfterCreate.Distinct().Count() == 1, "#equality1 foldersAfterCreate");
            Assert.IsTrue(foldersAfterCreate.Distinct().First() == folderId, "#value1 foldersAfterCreate");
            Assert.IsTrue(filesAfterCreate.Distinct().Count() == 1, "#equality2 filesAfterCreate");
            Assert.IsTrue(filesAfterCreate.Distinct().First() == fileId, "#value2 filesAfterCreate");

            Assert.IsTrue(foldersAfterRenameOld.Distinct().Count() == 1, "#equality3 foldersAfterRenameOld");
            Assert.IsTrue(foldersAfterRenameOld.Distinct().First() == 0, "#value3 foldersAfterRenameOld");
            Assert.IsTrue(filesAfterRenameOld.Distinct().Count() == 1, "#equality4 filesAfterRenameOld");
            Assert.IsTrue(filesAfterRenameOld.Distinct().First() == 0, "#value4 filesAfterRenameOld");
            Assert.IsTrue(foldersAfterRenameNew.Distinct().Count() == 1, "#equality5 foldersAfterRenameNew");
            Assert.IsTrue(foldersAfterRenameNew.Distinct().First() == folderId, "#value5 foldersAfterRenameNew");
            Assert.IsTrue(filesAfterRenameNew.Distinct().Count() == 1, "#equality6 filesAfterRenameNew");
            Assert.IsTrue(filesAfterRenameNew.Distinct().First() == fileId, "#value6 filesAfterRenameNew");
            Assert.IsTrue(filecontents.Distinct().Count() == 1, "#equality7 filecontents");
            Assert.IsTrue(filecontents.Distinct().First() == fileContent, "#value7 filecontents");

            Assert.IsTrue(foldersAfterDeleteOld.Distinct().Count() == 1, "#equality8 foldersAfterDeleteOld");
            Assert.IsTrue(foldersAfterDeleteOld.Distinct().First() == 0, "#value8 foldersAfterDeleteOld");
            Assert.IsTrue(filesAfterDeleteOld.Distinct().Count() == 1, "#equality9 filesAfterDeleteOld");
            Assert.IsTrue(filesAfterDeleteOld.Distinct().First() == 0, "#value9 filesAfterDeleteOld");
            Assert.IsTrue(foldersAfterDeleteNew.Distinct().Count() == 1, "#equality10 foldersAfterDeleteNew");
            Assert.IsTrue(foldersAfterDeleteNew.Distinct().First() == 0, "#value10 foldersAfterDeleteNew");
            Assert.IsTrue(filesAfterDeleteNew.Distinct().Count() == 1, "#equality11 filesAfterDeleteNew");
            Assert.IsTrue(filesAfterDeleteNew.Distinct().First() == 0, "#value11 filesAfterDeleteNew");
        }
コード例 #15
0
        /// <summary>
        /// Gets the appropriate cache header from the portal settings determined by the given path.
        /// Settings can be different based on content type or extension. A setting is a match for
        /// the provided parameters if all the parameters match the setting criteria.
        /// </summary>
        /// <param name="path">Context path. If it is empty, the caller gets the global setting.</param>
        /// <param name="contentType">Content type name. Can be empty.</param>
        /// <param name="extension">Extension (e.g. js) to load settings for. Can be empty.</param>
        /// <returns></returns>
        public static int?GetCacheHeaderSetting(string path, string contentType, string extension)
        {
            var cacheHeaderSettings = Settings.GetValue <IEnumerable <CacheHeaderSetting> >(PortalSettings.SETTINGSNAME, PortalSettings.SETTINGS_CACHEHEADERS, path);

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

            foreach (var chs in cacheHeaderSettings)
            {
                // Check if one of the criterias does not match. Empty extension or content type
                // will not match if these criterias are provided explicitely in the setting.
                var extMismatch        = !string.IsNullOrEmpty(chs.Extension) && chs.Extension != extension;
                var contentTypeMismach = !string.IsNullOrEmpty(chs.ContentType) && chs.ContentType != contentType;
                var pathMismatch       = !string.IsNullOrEmpty(chs.Path) && !path.StartsWith(RepositoryPath.Combine(chs.Path, RepositoryPath.PathSeparator));

                if (extMismatch || pathMismatch || contentTypeMismach)
                {
                    continue;
                }

                // found a match
                return(chs.MaxAge);
            }

            return(null);
        }
コード例 #16
0
 public string GetParentNameSafe()
 {
     return(RepositoryPath.GetFileNameSafe(RepositoryPath.GetParentPath(ContentPath)));
 }
コード例 #17
0
        private void HandleUrlToWebUrl(HttpContext context)
        {
            var path = context.Request.Form["url"];

            var weburl  = path;
            var fileurl = string.Empty;

            // ie.: /Sites or /Sites/Default_Site/workspace/Document/myws/Document_Library/mydoc.docx
            if (path != "/")
            {
                path   = DwsHelper.GetFullPath(path);
                weburl = path;

                var node = Node.LoadNode(path);
                if (node == null)
                {
                    node = Node.LoadNode(RepositoryPath.GetParentPath(path));
                }

                // searching starts from parentpath
                if (node != null)
                {
                    using (new SystemAccount())
                    {
                        // -----------
                        // Commented out this part to fix the bug that prevented Office clients to open documents
                        // correctly when there was a SPACE in the name of the workspace.
                        // Returning "/" below fixes that bug.
                        // -----------

                        //var doclib = DwsHelper.GetDocumentLibraryForNode(node);
                        //if (doclib != null)
                        //{
                        //    // weburl should be doclibs parent (most of the time currentworkspace)
                        //    // fileurl should be doclib name and doclib relative path
                        //    // this will work for /Sites/MySite/Doclib/document.docx, for /Sites/Mysite/myworkspace/Doclib/document.docx and for /Root/Doclib/document.docx
                        //    weburl = doclib.ParentPath;
                        //    fileurl = (path.Length > doclib.ParentPath.Length) ? path.Substring(doclib.ParentPath.Length + 1) : string.Empty;
                        //}
                        //else
                        //{
                        //    // weburl should be parent's parentpath
                        //    // fileurl should be parentname + name  -> parent will act as a mocked document library
                        //    // this will work for /Root/YourDocuments/document.docx
                        //    if (node.Parent != null)
                        //    {
                        //        weburl = node.Parent.ParentPath;
                        //        fileurl = RepositoryPath.Combine(node.Parent.Name, node.Name);
                        //    }
                        //}
                        weburl  = "/";
                        fileurl = path;
                    }
                }
            }

            var responseStr = GetFormattedString(string.Format(URLTOWEBURLSTR, weburl, fileurl));

            context.Response.Charset     = "";
            context.Response.ContentType = "application/x-vermeer-rpc";
            context.Response.AddHeader("Content-Length", responseStr.Length.ToString());
            context.Response.Write(responseStr);
            context.Response.Flush();
            context.Response.End();
        }
コード例 #18
0
ファイル: FieldControl.cs プロジェクト: pchaozhong/FlexNet
        private void AddGlobalTemplate(string fieldControlName)
        {
            var controlModeName = Enum.GetName(typeof(FieldControlControlMode), this.ControlMode);

            var templateFileName   = String.Concat(controlModeName, "Template.ascx");
            var templateFolderPath = RepositoryPath.Combine(Repository.FieldControlTemplatesPath, fieldControlName);
            var templateFilePath   = SkinManager.Resolve(RepositoryPath.Combine(templateFolderPath, templateFileName));

            var templateFileHead = NodeHead.Get(templateFilePath);

            if (templateFileHead == null)
            {
                return;
            }

            var page = this.Page ?? System.Web.HttpContext.Current.Handler as System.Web.UI.Page;

            System.Diagnostics.Debug.Assert(page != null, "Page property is null. Perhaps, you work with templated controls.");


            // render control with frame
            if (this.FrameMode == FieldControlFrameMode.ShowFrame)
            {
                var frameTemplateFilePath = SkinManager.Resolve(RepositoryPath.Combine(Repository.FieldControlTemplatesPath, FrameTemplateName));
                var frameTemplateFileHead = NodeHead.Get(frameTemplateFilePath);
                if (frameTemplateFileHead == null)
                {
                    return;
                }

                FrameTemplate = page.LoadTemplate(frameTemplateFilePath);
                AddTemplateTo(_container, Controls, FrameTemplate, true);

                var innerContainer = this.FindControlRecursive(FrameControlPlaceHolderName);

                PlaceHolder tempPlaceholder = new PlaceHolder();

                switch (this.ControlMode)
                {
                case FieldControlControlMode.Browse:
                    BrowseTemplate = page.LoadTemplate(templateFilePath);
                    AddTemplateTo(tempPlaceholder, innerContainer.Controls, BrowseTemplate, true);
                    break;

                case FieldControlControlMode.Edit:
                    EditTemplate = page.LoadTemplate(templateFilePath);
                    AddTemplateTo(tempPlaceholder, innerContainer.Controls, EditTemplate, true);
                    break;
                }

                return;
            }

            // render control without frame
            switch (this.ControlMode)
            {
            case FieldControlControlMode.Browse:
                BrowseTemplate = page.LoadTemplate(templateFilePath);
                AddTemplateTo(_container, Controls, BrowseTemplate, true);
                break;

            case FieldControlControlMode.Edit:
                EditTemplate = page.LoadTemplate(templateFilePath);
                AddTemplateTo(_container, Controls, EditTemplate, true);
                break;
            }
        }
コード例 #19
0
        public IDictionary <string, string> to_token_dictionary()
        {
            var tokens = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);

            tokens["AccessToken"] = AccessToken.to_string();
            tokens["AfterMigrationFolderName"] = AfterMigrationFolderName.to_string();
            tokens["AlterDatabaseFolderName"]  = AlterDatabaseFolderName.to_string();
            tokens["Baseline"] = Baseline.to_string();
            tokens["BeforeMigrationFolderName"]  = BeforeMigrationFolderName.to_string();
            tokens["CommandTimeout"]             = CommandTimeout.to_string();
            tokens["CommandTimeoutAdmin"]        = CommandTimeoutAdmin.to_string();
            tokens["ConfigurationFile"]          = ConfigurationFile.to_string();
            tokens["ConnectionString"]           = ConnectionString.to_string();
            tokens["ConnectionStringAdmin"]      = ConnectionStringAdmin.to_string();
            tokens["CreateDatabaseCustomScript"] = CreateDatabaseCustomScript.to_string();
            tokens["DatabaseName"]             = DatabaseName.to_string();
            tokens["DatabaseType"]             = DatabaseType.to_string();
            tokens["Debug"]                    = Debug.to_string();
            tokens["DisableOutput"]            = DisableOutput.to_string();
            tokens["DisableTokenReplacement"]  = DisableTokenReplacement.to_string();
            tokens["DoNotAlterDatabase"]       = DoNotAlterDatabase.to_string();
            tokens["DoNotCreateDatabase"]      = DoNotCreateDatabase.to_string();
            tokens["DoNotStoreScriptsRunText"] = DoNotStoreScriptsRunText.to_string();
            tokens["DownFolderName"]           = DownFolderName.to_string();
            tokens["Drop"]                                     = Drop.to_string();
            tokens["DryRun"]                                   = DryRun.to_string();
            tokens["EnvironmentName"]                          = string.Join(",", EnvironmentNames);
            tokens["EnvironmentNames"]                         = string.Join(",", EnvironmentNames);
            tokens["FunctionsFolderName"]                      = FunctionsFolderName.to_string();
            tokens["IndexesFolderName"]                        = IndexesFolderName.to_string();
            tokens["Initialize"]                               = Initialize.to_string();
            tokens["OutputPath"]                               = OutputPath.to_string();
            tokens["PermissionsFolderName"]                    = PermissionsFolderName.to_string();
            tokens["RecoveryMode"]                             = RecoveryMode.to_string();
            tokens["RepositoryPath"]                           = RepositoryPath.to_string();
            tokens["Restore"]                                  = Restore.to_string();
            tokens["RestoreCustomOptions"]                     = RestoreCustomOptions.to_string();
            tokens["RestoreFromPath"]                          = RestoreFromPath.to_string();
            tokens["RestoreTimeout"]                           = RestoreTimeout.to_string();
            tokens["RunAfterCreateDatabaseFolderName"]         = RunAfterCreateDatabaseFolderName.to_string();
            tokens["RunAfterOtherAnyTimeScriptsFolderName"]    = RunAfterOtherAnyTimeScriptsFolderName.to_string();
            tokens["RunAllAnyTimeScripts"]                     = RunAllAnyTimeScripts.to_string();
            tokens["RunBeforeUpFolderName"]                    = RunBeforeUpFolderName.to_string();
            tokens["RunFirstAfterUpFolderName"]                = RunFirstAfterUpFolderName.to_string();
            tokens["SchemaName"]                               = SchemaName.to_string();
            tokens["ScriptsRunErrorsTableName"]                = ScriptsRunErrorsTableName.to_string();
            tokens["ScriptsRunTableName"]                      = ScriptsRunTableName.to_string();
            tokens["SearchAllSubdirectoriesInsteadOfTraverse"] = SearchAllSubdirectoriesInsteadOfTraverse.to_string();
            tokens["ServerName"]                               = ServerName.to_string();
            tokens["Silent"]                                   = Silent.to_string();
            tokens["SprocsFolderName"]                         = SprocsFolderName.to_string();
            tokens["SqlFilesDirectory"]                        = SqlFilesDirectory.to_string();
            tokens["TriggersFolderName"]                       = TriggersFolderName.to_string();
            tokens["UpFolderName"]                             = UpFolderName.to_string();
            tokens["Version"]                                  = Version.to_string();
            tokens["VersionFile"]                              = VersionFile.to_string();
            tokens["VersionTableName"]                         = VersionTableName.to_string();
            tokens["VersionXPath"]                             = VersionXPath.to_string();
            tokens["ViewsFolderName"]                          = ViewsFolderName.to_string();
            tokens["WarnAndIgnoreOnOneTimeScriptChanges"]      = WarnAndIgnoreOnOneTimeScriptChanges.to_string();
            tokens["WarnOnOneTimeScriptChanges"]               = WarnOnOneTimeScriptChanges.to_string();
            tokens["WithTransaction"]                          = WithTransaction.to_string();

            if (UserTokens != null)
            {
                foreach (var t in UserTokens)
                {
                    tokens[t.Key] = t.Value;
                }
            }

            return(tokens);
        }
コード例 #20
0
        public void OData_ContentQuery()
        {
            Test(() =>
            {
                var folderName = "OData_ContentQuery";
                InstallCarContentType();
                var site         = CreateTestSite();
                var allowedTypes = site.GetAllowedChildTypeNames().ToList();
                allowedTypes.Add("Car");
                site.AllowChildTypes(allowedTypes);
                site.Save();

                var folder = Node.Load <Folder>(RepositoryPath.Combine(site.Path, folderName));
                if (folder == null)
                {
                    folder = new Folder(site)
                    {
                        Name = folderName
                    };
                    folder.Save();
                }

                Content.CreateNewAndParse("Car", site, null, new Dictionary <string, string> {
                    { "Make", "asdf" }, { "Model", "asdf" }
                }).Save();
                Content.CreateNewAndParse("Car", site, null, new Dictionary <string, string> {
                    { "Make", "asdf" }, { "Model", "qwer" }
                }).Save();
                Content.CreateNewAndParse("Car", site, null, new Dictionary <string, string> {
                    { "Make", "qwer" }, { "Model", "asdf" }
                }).Save();
                Content.CreateNewAndParse("Car", site, null, new Dictionary <string, string> {
                    { "Make", "qwer" }, { "Model", "qwer" }
                }).Save();

                Content.CreateNewAndParse("Car", folder, null, new Dictionary <string, string> {
                    { "Make", "asdf" }, { "Model", "asdf" }
                }).Save();
                Content.CreateNewAndParse("Car", folder, null, new Dictionary <string, string> {
                    { "Make", "asdf" }, { "Model", "qwer" }
                }).Save();
                Content.CreateNewAndParse("Car", folder, null, new Dictionary <string, string> {
                    { "Make", "qwer" }, { "Model", "asdf" }
                }).Save();
                Content.CreateNewAndParse("Car", folder, null, new Dictionary <string, string> {
                    { "Make", "qwer" }, { "Model", "qwer" }
                }).Save();

                var expectedQueryGlobal = "asdf AND Type:Car .SORT:Path .AUTOFILTERS:OFF";
                var expectedGlobal      = string.Join(", ", CreateSafeContentQuery(expectedQueryGlobal).Execute().Nodes.Select(n => n.Id.ToString()));

                var expectedQueryLocal = $"asdf AND Type:Car AND InTree:'{folder.Path}' .SORT:Path .AUTOFILTERS:OFF";
                var expectedLocal      = string.Join(", ", CreateSafeContentQuery(expectedQueryLocal).Execute().Nodes.Select(n => n.Id.ToString()));

                var entities = ODataGET <ODataEntities>("/OData.svc/Root", "$select=Id,Path&query=asdf+AND+Type%3aCar+.SORT%3aPath+.AUTOFILTERS%3aOFF");

                var realGlobal = string.Join(", ", entities.Select(e => e.Id));
                Assert.AreEqual(realGlobal, expectedGlobal);

                entities = ODataGET <ODataEntities>("/OData.svc/" + folderName, "$select=Id,Path&query=asdf+AND+Type%3aCar+.SORT%3aPath+.AUTOFILTERS%3aOFF");

                var realLocal = string.Join(", ", entities.Select(e => e.Id));
                Assert.AreEqual(realLocal, expectedLocal);
            });
        }
コード例 #21
0
ファイル: ContentListTest.cs プロジェクト: vlslavik/SenseNet
        public void ContentList_AvailableFields()
        {
            ContentType c = ContentType.GetByName("CT_Root");

            if (c != null)
            {
                ContentTypeInstaller.RemoveContentType(c);
            }
            ContentTypeManager.Reset();

            ContentTypeInstaller installer = ContentTypeInstaller.CreateBatchContentTypeInstaller();

            installer.AddContentType(@"<?xml version='1.0' encoding='utf-8'?>
				<ContentType name='CT_Root' parentType='GenericContent' handler='SenseNet.ContentRepository.GenericContent' xmlns='http://schemas.sensenet.com/SenseNet/ContentRepository/ContentTypeDefinition'>
					<Fields>
						<Field name='InheritanceTest' type='Integer'>
							<Configuration><MinValue>-5</MinValue><MaxValue>7</MaxValue></Configuration>
						</Field>
					</Fields>
				</ContentType>"                );

            installer.AddContentType("<ContentType name='CT_A' parentType='CT_Root' handler='SenseNet.ContentRepository.GenericContent' xmlns='http://schemas.sensenet.com/SenseNet/ContentRepository/ContentTypeDefinition'><Fields><Field name='InheritanceTest' type='Integer'><Configuration><MinValue>0</MinValue><MaxValue>10</MaxValue></Configuration></Field></Fields></ContentType>");
            installer.AddContentType("<ContentType name='CT_A_A' parentType='CT_A' handler='SenseNet.ContentRepository.GenericContent' xmlns='http://schemas.sensenet.com/SenseNet/ContentRepository/ContentTypeDefinition'><Fields><Field name='InheritanceTest' type='Integer'><Configuration><MinValue>1</MinValue><MaxValue>20</MaxValue></Configuration></Field></Fields></ContentType>");
            installer.AddContentType("<ContentType name='CT_B' parentType='CT_Root' handler='SenseNet.ContentRepository.GenericContent' xmlns='http://schemas.sensenet.com/SenseNet/ContentRepository/ContentTypeDefinition'><Fields><Field name='InheritanceTest' type='Integer'><Configuration><MinValue>2</MinValue><MaxValue>30</MaxValue></Configuration></Field></Fields></ContentType>");
            installer.AddContentType("<ContentType name='CT_B_B' parentType='CT_B' handler='SenseNet.ContentRepository.GenericContent' xmlns='http://schemas.sensenet.com/SenseNet/ContentRepository/ContentTypeDefinition'><Fields><Field name='InheritanceTest' type='Integer'><Configuration><MinValue>3</MinValue><MaxValue>40</MaxValue></Configuration></Field></Fields></ContentType>");

            installer.ExecuteBatch();

            string listDef = @"<?xml version='1.0' encoding='utf-8'?>
<ContentListDefinition xmlns='http://schemas.sensenet.com/SenseNet/ContentRepository/ContentListDefinition'>
	<DisplayName>Cars title</DisplayName>
	<Description>Cars description</Description>
	<Icon>automobile.gif</Icon>
	<Fields>
		<ContentListField name='#ListField1' type='ShortText'>
			<DisplayName>ContentListField1</DisplayName>
			<Description>ContentListField1 Description</Description>
			<Icon>icon.gif</Icon>
			<Configuration>
				<MaxLength>100</MaxLength>
			</Configuration>
		</ContentListField>
		<ContentListField name='#ListField2' type='WhoAndWhen'>
			<DisplayName>ContentListField2</DisplayName>
			<Description>ContentListField2 Description</Description>
			<Icon>icon.gif</Icon>
			<Configuration>
			</Configuration>
		</ContentListField>
		<ContentListField name='#ListField3' type='ShortText'>
			<DisplayName>ContentListField3</DisplayName>
			<Description>ContentListField3 Description</Description>
			<Icon>icon.gif</Icon>
			<Configuration>
				<MaxLength>200</MaxLength>
			</Configuration>
		</ContentListField>
	</Fields>
</ContentListDefinition>
";

            var b = new bool[21];

            ContentType  CT_Root = ContentType.GetByName("CT_Root");
            FieldSetting FS_Root = CT_Root.FieldSettings[0];

            ContentType  CT_A   = ContentType.GetByName("CT_A");
            ContentType  CT_B   = ContentType.GetByName("CT_B");
            FieldSetting FS_A   = CT_A.FieldSettings[0];
            ContentType  CT_A_A = ContentType.GetByName("CT_A_A");
            FieldSetting FS_A_A = CT_A_A.FieldSettings[0];

            string path = RepositoryPath.Combine(this.TestRoot.Path, "Cars");

            if (Node.Exists(path))
            {
                Node.ForceDelete(path);
            }

            var list = new ContentList(this.TestRoot);

            list.Name = "Cars";
            list.ContentListDefinition = listDef;
            list.AllowedChildTypes     = new[] { CT_A, CT_B };

            list.Save();

            b[0] = FS_Root.ParentFieldSetting == null;
            b[1] = FS_A.ParentFieldSetting == FS_Root;
            b[2] = FS_A_A.ParentFieldSetting == FS_A;

            var fields = list.GetAvailableFields();
        }
コード例 #22
0
ファイル: GenericScenario.cs プロジェクト: kimduquan/DMIS
        public static IEnumerable <Node> GetNewItemNodes(GenericContent content, ContentType[] contentTypes)
        {
            if (content == null)
            {
                throw new ArgumentNullException("content");
            }

            var templatesAndTypes = new List <Node>();

            if (contentTypes != null && contentTypes.Length == 0)
            {
                return(templatesAndTypes);
            }

            var notAllTypes = contentTypes != null && contentTypes.Length > 0 &&
                              contentTypes.Length < ContentType.GetContentTypes().Length;

            Node site = null;

            try
            {
                site = Node.GetAncestorOfNodeType(content, "Site");
            }
            catch (InvalidOperationException)
            {
                //the user does not have enough permissions for one of the parents
            }

            Node currentWorkspace = null;

            try
            {
                currentWorkspace = Workspace.GetWorkspaceForNode(content);
            }
            catch (InvalidOperationException)
            {
                //the user does not have enough permissions for one of the parents
            }

            var wsTemplatePath             = currentWorkspace == null ? string.Empty : RepositoryPath.Combine(currentWorkspace.Path, Repository.ContentTemplatesFolderName);
            var siteTemplatePath           = site == null ? string.Empty : RepositoryPath.Combine(site.Path, Repository.ContentTemplatesFolderName);
            var currentContentTemplatePath = RepositoryPath.Combine(content.Path, Repository.ContentTemplatesFolderName);

            //the query is built on the assumption that all content
            //templates are placed under a "TypeName" folder in a
            //container called "ContentTemplates", meaning their
            //depth equals the depth of the container +2.
            var sbQueryText = new StringBuilder("+(");

            //add filter for workspace and site templates
            if (!string.IsNullOrEmpty(wsTemplatePath) && wsTemplatePath.CompareTo(currentContentTemplatePath) != 0)
            {
                sbQueryText.AppendFormat("(InTree:\"{0}\" AND Depth:{1}) OR", wsTemplatePath, RepositoryPath.GetDepth(wsTemplatePath) + 2);
            }
            if (!string.IsNullOrEmpty(siteTemplatePath) && siteTemplatePath.CompareTo(currentContentTemplatePath) != 0)
            {
                sbQueryText.AppendFormat(" (InTree:\"{0}\" AND Depth:{1}) OR", siteTemplatePath, RepositoryPath.GetDepth(siteTemplatePath) + 2);
            }

            //add filter for local and global templates
            sbQueryText.AppendFormat(" (InTree:\"{0}\" AND Depth:{1}) OR", currentContentTemplatePath, RepositoryPath.GetDepth(currentContentTemplatePath) + 2);
            sbQueryText.AppendFormat(" (InTree:\"{0}\" AND Depth:{1}))", Repository.ContentTemplateFolderPath, RepositoryPath.GetDepth(Repository.ContentTemplateFolderPath) + 2);

            //content type filter
            if (notAllTypes)
            {
                sbQueryText.AppendFormat(" +Type:({0})", string.Join(" ", contentTypes.Select(ct => ct.Name)));
            }

            sbQueryText.Append(" .REVERSESORT:Depth");

            var templateResult = ContentQuery.Query(sbQueryText.ToString(), new QuerySettings {
                EnableAutofilters = FilterStatus.Disabled, EnableLifespanFilter = FilterStatus.Disabled
            }).Nodes.ToList();
            var templatesNonGlobal = templateResult.Where(ct => !ct.Path.StartsWith(Repository.ContentTemplateFolderPath)).ToList();
            var templatesGlobal    = templateResult.Where(ct => ct.Path.StartsWith(Repository.ContentTemplateFolderPath)).ToList();

            var addedTemplates = new Dictionary <string, List <string> >();

            //add all local and ws/site level templates
            foreach (var localTemplate in templatesNonGlobal)
            {
                //query correction: if the query returned a type that we do not want, skip it
                if (notAllTypes && !contentTypes.Any(ct => ct.Name.CompareTo(localTemplate.ParentName) == 0))
                {
                    continue;
                }

                AddTemplate(templatesAndTypes, localTemplate, addedTemplates);
            }

            //add global templates
            foreach (var globalTemplate in templatesGlobal)
            {
                //query correction: if the query returned a type that we do not want, skip it
                if (notAllTypes && !contentTypes.Any(ct => ct.Name.CompareTo(globalTemplate.ParentName) == 0))
                {
                    continue;
                }

                AddTemplate(templatesAndTypes, globalTemplate, addedTemplates);
            }

            //add content types without a template
            if (contentTypes != null)
            {
                templatesAndTypes.AddRange(contentTypes.Where(contentType => !addedTemplates.ContainsKey(contentType.Name)));
            }

            return(templatesAndTypes);
        }
コード例 #23
0
ファイル: ContentListTest.cs プロジェクト: vlslavik/SenseNet
        public void ContentList_FieldInitialize_Bug2943()
        {
            string listDef = @"<?xml version='1.0' encoding='utf-8'?>
<ContentListDefinition xmlns='http://schemas.sensenet.com/SenseNet/ContentRepository/ContentListDefinition'>
	<Fields>
		<ContentListField name='#ListField1' type='Integer'>
			<Configuration>
				<MinValue>-100</MinValue>
				<MaxValue>100</MaxValue>
			</Configuration>
		</ContentListField>
	</Fields>
</ContentListDefinition>
";
            string path    = RepositoryPath.Combine(this.TestRoot.Path, "Cars");

            if (Node.Exists(path))
            {
                Node.ForceDelete(path);
            }

            ContentList list;
            Content     content;
            var         bb = new List <bool>();

            list      = new ContentList(this.TestRoot);
            list.Name = "Cars";
            list.ContentListDefinition = listDef;
            list.AllowedChildTypes     = new ContentType[] { ContentType.GetByName("Car") };
            list.Save();

            content = Content.CreateNew("Car", list, "TestCar");

            content["#ListField1"] = 0;
            bb.Add(content.IsValid);
            content["#ListField1"] = 10;
            bb.Add(content.IsValid);
            content["#ListField1"] = 0;
            bb.Add(content.IsValid);
            content["#ListField1"] = -10;
            bb.Add(content.IsValid);
            content["#ListField1"] = -100;
            bb.Add(content.IsValid);
            content["#ListField1"] = 100;
            bb.Add(content.IsValid);
            content["#ListField1"] = -101;
            bb.Add(!content.IsValid);
            content["#ListField1"] = 101;
            bb.Add(!content.IsValid);

            content = Content.CreateNew("Car", list, "TestCar1");

            content["#ListField1"] = 0;
            bb.Add(content.IsValid);
            content["#ListField1"] = 10;
            bb.Add(content.IsValid);
            content["#ListField1"] = 0;
            bb.Add(content.IsValid);
            content["#ListField1"] = -10;
            bb.Add(content.IsValid);
            content["#ListField1"] = -101;
            bb.Add(!content.IsValid);
            content["#ListField1"] = 101;
            bb.Add(!content.IsValid);

            var i = 0;

            foreach (var b in bb)
            {
                Assert.IsTrue(b, "#" + i++);
            }
        }
コード例 #24
0
        /// <summary>
        /// Helper method for updating the given <see cref="Content"/> with a model represented by JObject.
        /// The <see cref="Content"/> will not be saved.
        /// </summary>
        /// <param name="content">The <see cref="Content"/> that will be modified. Cannot be null.</param>
        /// <param name="model">The modifier JObject instance. Cannot be null.</param>
        public static void UpdateFields(Content content, JObject model)
        {
            if (content == null)
            {
                throw new ArgumentNullException(nameof(content));
            }
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            var isNew = content.Id == 0;

            foreach (var prop in model.Properties())
            {
                if (string.IsNullOrEmpty(prop.Name) || prop.Name == "__ContentType" || prop.Name == "__ContentTemplate" || prop.Name == "Type" || prop.Name == "ContentType")
                {
                    continue;
                }

                var hasField = content.Fields.TryGetValue(prop.Name, out var field);
                if (!hasField && content.SupportsAddingFieldsOnTheFly && (prop.Value as JValue)?.Value != null)
                {
                    var value        = ((JValue)prop.Value).Value;
                    var fieldSetting = FieldSetting.InferFieldSettingFromType(value.GetType(), prop.Name);
                    var meta         = new FieldMetadata(true, true, prop.Name, prop.Name, fieldSetting);
                    hasField = content.AddFieldsOnTheFly(new[] { meta }) && content.Fields.TryGetValue(prop.Name, out field);
                }

                if (hasField)
                {
                    if (!field.ReadOnly)
                    {
                        if (prop.Value is JValue jValue)
                        {
                            if (field is IntegerField)
                            {
                                field.SetData(Convert.ToInt32(jValue.Value));
                                continue;
                            }
                            if (field is DateTimeField && jValue.Value == null)
                            {
                                continue;
                            }
                            if (isNew && field is ReferenceField && jValue.Value == null)
                            {
                                if (field.Name == "CreatedBy" || field.Name == "ModifiedBy")
                                {
                                    continue;
                                }
                            }
                            if (field is ReferenceField && jValue.Value != null)
                            {
                                var refNode = jValue.Type == JTokenType.Integer
                                    ? Node.LoadNode(Convert.ToInt32(jValue.Value))
                                    : Node.LoadNode(jValue.Value.ToString());

                                field.SetData(refNode);
                                continue;
                            }
                            if (isNew && field.Name == "Name" && jValue.Value != null)
                            {
                                field.SetData(ContentNamingProvider.GetNameFromDisplayName(jValue.Value.ToString()));
                                continue;
                            }

                            field.SetData(jValue.Value);
                            continue;
                        }

                        if (prop.Value is JObject)
                        {
                            //TODO: ODATA: setting field when posted value is JObject.
                            // field.SetData(jValue.Value);
                            continue;
                        }

                        if (prop.Value is JArray aValue)
                        {
                            if (field is ReferenceField)
                            {
                                var refValues = aValue.Values().ToList();
                                if (refValues.Count == 0)
                                {
                                    field.SetData(null);
                                    continue;
                                }

                                var fieldSetting = field.FieldSetting as ReferenceFieldSetting;
                                var nodes        = refValues.Select(rv => rv.Type == JTokenType.Integer ? Node.LoadNode(Convert.ToInt32(rv.ToString())) : Node.LoadNode(rv.ToString()));

                                if (fieldSetting?.AllowMultiple != null && fieldSetting.AllowMultiple.Value)
                                {
                                    field.SetData(nodes);
                                }
                                else
                                {
                                    field.SetData(nodes.First());
                                }
                            }
                            else if (field is ChoiceField)
                            {
                                // ChoiceField expects the value to be of type List<string>
                                var list = new List <string>();
                                foreach (var token in aValue)
                                {
                                    if (token is JValue value)
                                    {
                                        list.Add(value.Value.ToString());
                                    }
                                    else
                                    {
                                        throw new Exception(
                                                  $"Token type {token.GetType().Name} for field {field.Name} (type {field.GetType().Name}) is not supported.");
                                    }
                                }

                                field.SetData(list);
                            }
                            else if (field is AllowedChildTypesField &&
                                     field.Name == "AllowedChildTypes" &&
                                     content.ContentHandler is GenericContent gc)
                            {
                                var types = aValue.Values().Select(rv =>
                                {
                                    switch (rv.Type)
                                    {
                                    case JTokenType.Integer:
                                        return(Node.LoadNode(Convert.ToInt32(rv.ToString())) as ContentType);

                                    default:
                                        var typeId = rv.ToString();
                                        if (RepositoryPath.IsValidPath(typeId) == RepositoryPath.PathResult.Correct)
                                        {
                                            return(Node.LoadNode(typeId) as ContentType);
                                        }
                                        return(ContentType.GetByName(typeId));
                                    }
                                }).Where(ct => ct != null).ToArray();

                                gc.SetAllowedChildTypes(types);
                            }

                            continue;
                        }

                        throw new SnNotSupportedException();
                    }
                }
            }
        }
コード例 #25
0
        public void ProcessRequest(HttpContext context)
        {
            HttpFileCollection uploadedFiles = context.Request.Files;
            var path = string.Empty;

            // actual info: we handle one file
            if (uploadedFiles.Count == 1)
            {
                var postedFile = uploadedFiles[0];
                var parentId   = HttpContext.Current.Request.Form[ParentIdRequestParameterName];

                if (String.IsNullOrEmpty(parentId))
                {
                    parentId = TryToGetParentId(context);
                }

                if (!String.IsNullOrEmpty(parentId))
                {
                    IFolder parentNode   = null;
                    var     parentNodeId = Convert.ToInt32(parentId);
                    parentNode = parentNodeId == 0 ? Repository.Root : Node.LoadNode(parentNodeId) as IFolder;

                    if (parentNode != null)
                    {
                        string fileName = System.IO.Path.GetFileName(postedFile.FileName);
                        path = RepositoryPath.Combine((parentNode as Node).Path, fileName);
                        //PathInfoRemove:
                        //object t = RepositoryPathInfo.GetPathInfo(path);
                        var contentType = UploadHelper.GetContentType(postedFile.FileName, ContentType);
                        var t           = NodeHead.Get(path);
                        if (t == null)
                        {
                            if (!String.IsNullOrEmpty(contentType))
                            {
                                CreateSpecificContent(context, contentType, parentNode, postedFile);
                            }
                            else
                            {
                                SaveNewFile(context, postedFile, parentNode, path);
                            }
                        }
                        else
                        {
                            if (!String.IsNullOrEmpty(contentType))
                            {
                                ModifySpecificContent(parentNode, postedFile, path);
                            }
                            else
                            {
                                ModifyFile(context, postedFile, parentNode, path);
                            }
                        }
                    }
                    else
                    {
                        this.SetError(context, String.Format("Couldn't find parent node with {0} id.", parentId), 500);
                    }
                }
                else
                {
                    this.SetError(context, "Post parameter error: ParentId is null or empty!", 500);
                }
            }

            var backUrl = PortalContext.Current.BackUrl;

            if (!String.IsNullOrEmpty(backUrl))
            {
                context.Response.Redirect(backUrl);
            }

            // everything's fine
            context.Response.StatusCode = 200;
            context.Response.Write(Environment.NewLine);
            context.Response.End();
        }
コード例 #26
0
 private static Node GetExistNode(IFolder folder, string name)
 {
     return(Node.LoadNode(RepositoryPath.Combine(((Node)folder).Path, name)));
 }
コード例 #27
0
        private void ImportDataPath(XmlNode fieldNode)
        {
            var list        = new List <Node>();
            var xmlNodeList = fieldNode.SelectNodes("*");

            foreach (XmlNode refNode in xmlNodeList)
            {
                Node node = null;
                switch (refNode.LocalName)
                {
                case "Path":
                    string path = refNode.InnerXml.Trim();
                    if (path.Length > 0)
                    {
                        if (!path.StartsWith(RepositoryPath.PathSeparator))
                        {
                            path = RepositoryPath.Combine(this.Content.ContentHandler.Path, path);
                        }
                        node = Node.LoadNode(path);
                        if (node == null)
                        {
                            throw new ReferenceNotFoundException("", String.Concat("Path: ", path));
                        }
                        list.Add(node);
                    }
                    break;

                case "Id":
                    string idstring = refNode.InnerXml.Trim();
                    if (idstring.Length > 0)
                    {
                        int id;
                        if (!int.TryParse(refNode.InnerXml, out id))
                        {
                            throw base.InvalidImportDataException("Invalid Id");
                        }
                        node = Node.LoadNode(id);
                        if (node == null)
                        {
                            throw new ReferenceNotFoundException("", String.Concat("Id: ", id));
                        }
                        list.Add(node);
                    }
                    break;

                case "SearchExpression":
                    NodeQuery query  = NodeQuery.Parse(refNode.OuterXml.Trim());
                    var       result = query.Execute();
                    foreach (Node resultNode in result.Nodes)
                    {
                        list.Add(resultNode);
                    }
                    break;

                default:
                    throw base.InvalidImportDataException("Unrecognized reference");
                }
            }
            if (fieldNode.InnerText.Trim().Length > 0 && list.Count == 0)
            {
                throw this.InvalidImportDataException("ReferenceField.InnerText is not supported. Valid NodeContent is empty or <Path> or <Id> or <SearchExpression> element.");
            }

            if (GetHandlerSlot(0) == typeof(IEnumerable))
            {
                this.SetData(list);
            }
            else if (GetHandlerSlot(0) == typeof(Node))
            {
                this.SetData(list.Count == 0 ? null : list[0]);
            }
            else
            {
                throw new NotSupportedException(String.Concat("ReferenceField not supports this conversion: Node or IEnumerable to ", GetHandlerSlot(0).FullName));
            }
        }
コード例 #28
0
 protected object GetUrl(string path)
 {
     return(string.Format("http://localhost/OData.svc/{0}('{1}')", RepositoryPath.GetParentPath(path), RepositoryPath.GetFileName(path)));
 }
コード例 #29
0
        protected override void CreateChildControls()
        {
            Controls.Clear();

            var genericContent = this.ContextNode as GenericContent;

            if (genericContent != null && genericContent.CheckInCommentsMode > CheckInCommentsMode.None && SavingAction.HasCheckIn(genericContent))
            {
                var content = Content.Create(genericContent);

                //we need to reset the comments field before displaying it
                content["CheckInComments"] = string.Empty;

                var contentView = ContentView.Create(content, Page, ViewMode.InlineEdit, RepositoryPath.Combine(Repository.ContentViewFolderName, "CheckIn.ascx"));

                if (contentView != null)
                {
                    contentView.CommandButtonsAction += ContentView_CommandButtonsAction;
                    Controls.Add(contentView);
                }
            }

            ChildControlsCreated = true;
        }
コード例 #30
0
        private void CreateContent(HttpContext context)
        {
            try
            {
                //---- content type

                var contentTypeName = GetRequestParameter("contenttype");
                if (String.IsNullOrEmpty(contentTypeName))
                {
                    WriteError("Parameter 'contenttype' cannot be null or empty.", context);
                    return;
                }

                var contentType = ContentType.GetByName(contentTypeName);
                if (contentType == null)
                {
                    WriteError("Content type not found: " + contentTypeName, context);
                    return;
                }
                //---- create content

                var snPath = GetRequestParameter("snpath");
                if (String.IsNullOrEmpty(snPath))
                {
                    WriteError("Parameter 'snpath' cannot be null or empty.", context);
                    return;
                }

                using (new SenseNet.ContentRepository.Storage.Security.SystemAccount())
                {
                    BenchmarkCounter.Reset();
                    benchmarkTimer = Stopwatch.StartNew();
                    benchmarkTimer.Restart();

                    var parentPath = RepositoryPath.GetParentPath(snPath);

                    BenchmarkCounter.IncrementBy(BenchmarkCounter.CounterName.GetParentPath, benchmarkTimer.ElapsedTicks);
                    benchmarkTimer.Restart();

                    var parent = Node.LoadNode(parentPath);
                    if (parent == null)
                    {
                        WriteError("Cannot load the parent: " + snPath, context);
                        return;
                    }

                    BenchmarkCounter.IncrementBy(BenchmarkCounter.CounterName.LoadParent, benchmarkTimer.ElapsedTicks);
                    benchmarkTimer.Restart();



                    var contentName = RepositoryPath.GetFileName(snPath);
                    var content     = SnContent.CreateNew(contentTypeName, parent, contentName);

                    BenchmarkCounter.IncrementBy(BenchmarkCounter.CounterName.ContentCreate, benchmarkTimer.ElapsedTicks);
                    benchmarkTimer.Restart();

                    //---- create binary

                    if (contentTypeName == "File")
                    {
                        var fsPath = GetRequestParameter("fspath");
                        if (String.IsNullOrEmpty(snPath))
                        {
                            WriteError("Parameter 'fspath' cannot be null or empty if the content type is 'File'.", context);
                            return;
                        }

                        using (var stream = context.Request.InputStream)
                        {
                            var binaryData = new BinaryData();
                            binaryData.FileName = fsPath; //.Replace("$amp;", "&");
                            binaryData.SetStream(stream);

                            content["Binary"] = binaryData;
                            BenchmarkCounter.IncrementBy(BenchmarkCounter.CounterName.BinarySet, benchmarkTimer.ElapsedTicks);
                            benchmarkTimer.Restart();


                            using (new SenseNet.ContentRepository.Storage.Security.SystemAccount())
                                content.Save();
                        }
                    }
                    else
                    {
                        BenchmarkCounter.IncrementBy(BenchmarkCounter.CounterName.BinarySet, benchmarkTimer.ElapsedTicks);
                        benchmarkTimer.Restart();

                        content.Save();
                    }

                    BenchmarkCounter.IncrementBy(BenchmarkCounter.CounterName.FullSave, benchmarkTimer.ElapsedTicks);
                    benchmarkTimer.Restart();
                }
            }
            catch (Exception e)
            {
                //WriteError(String.Concat(e.Message, "\r", e.StackTrace), context);
                Logger.WriteException(e);
                WriteError(e, context);
                return;
            }

            WriteCounters(context);

            context.Response.StatusCode = 200;
            context.Response.Write("ok");
        }