//-- Object service tools private static Atom10FeedFormatter BuildEntry(SNC.Content content, string repositoryId) { var baseUri = GetBaseUri(); var title = content.Name; var description = GenerateAtomContent(content); var lastUpdateTime = new DateTimeOffset(content.ContentHandler.ModificationDate); var linkHref = GetEntryActionUri(baseUri, repositoryId, content.Id, "getEntry"); var feedAlternateLink = new Uri(linkHref); var feedId = linkHref; CmisObject cmisObject = new CmisObject { Properties = BuildCmisProperties(content), AllowableActions = GetAllowableActions(content) }; SyndicationFeed feed = new SyndicationFeed(title, description, feedAlternateLink, feedId, lastUpdateTime); feed.ElementExtensions.Add(cmisObject, new XmlSerializer(typeof(CmisObject))); foreach (var link in BuildLinks(content, baseUri, repositoryId)) { feed.Links.Add(link); } var formatter = new Atom10FeedFormatter(feed); return(formatter); }
private static ListItem[] GetListItems(IEnumerable <ContentType> contentTypes, Node contextNode) { var dict = new SortedDictionary <string, string>(); if (contentTypes == null) { return(new ListItem[0]); } foreach (var contentType in contentTypes) { if (!SavingAction.CheckManageListPermission(contentType.NodeType, contextNode)) { continue; } var ct = Content.Create(contentType); var title = string.IsNullOrEmpty(ct.DisplayName) ? ct.Name : ct.DisplayName; if (!dict.ContainsKey(title)) { dict.Add(title, ct.Name); } } return(dict.Keys.Count == 0 ? new ListItem[0] : dict.Keys.Select(key => new ListItem(key, dict[key])).ToArray()); }
private void UpdateReference(int contentId, string metadataPath) { var contentInfo = new ContentInfo(metadataPath, null); Log(ImportLogLevel.Verbose, " " + contentId + "\t" + contentInfo.Name); SNC.Content content = SNC.Content.Load(contentId); if (content != null) { try { if (!contentInfo.UpdateReferences(content)) { PrintFieldErrors(content, contentInfo.MetaDataPath); } } catch (Exception e) { PrintException(e, contentInfo.MetaDataPath); } } else { Log(ImportLogLevel.Info, "---------- Content does not exist. MetaDataPath: {0}, ContentId: {1}, ContentTypeName: {2}", contentInfo.MetaDataPath, contentInfo.ContentId, contentInfo.ContentTypeName); } }
protected override object GetModel() { string subscriptionCtd; using (new SystemAccount()) { var ctdFile = Node.LoadNode("/Root/System/Schema/ContentTypes/GenericContent/Subscription") as ContentType; if (ctdFile != null) { using (var ctdStream = ctdFile.Binary.GetStream()) { subscriptionCtd = RepositoryTools.GetStreamString(ctdStream); } } else { throw new InvalidOperationException("Subscription CTD not found."); } } var currentSite = PortalContext.Current.Site; var siteUrl = PortalContext.Current.SiteUrl; if (this.User == null) { return(null); } // edit subscription or create new if not exists var subscription = Subscription.GetSubscriptionByUser(this.User.Path, this.ContentPath); if (subscription != null) { IsSubscriptionNew = false; } else { subscription = new Subscription() { ContentPath = this.ContentPath, Frequency = NotificationFrequency.Immediately, IsActive = true, UserEmail = this.User.Email, UserPath = this.User.Path, UserId = this.User.Id, UserName = this.User.Name, Language = "en", SitePath = currentSite?.Path, SiteUrl = siteUrl }; IsSubscriptionNew = true; } var sct = Content.Create(subscription, subscriptionCtd); var rch = sct.ContentHandler as Content.RuntimeContentHandler; rch?.SetIsNew(IsSubscriptionNew); return(sct); }
private static void UpdateReference(int contentId, string metadataPath, bool validate) { var contentInfo = new ContentInfo(metadataPath, null); LogWrite(" "); LogWriteLine(contentInfo.Name); SNC.Content content = SNC.Content.Load(contentId); if (content != null) { try { if (!contentInfo.UpdateReferences(content, validate)) { PrintFieldErrors(content, contentInfo.MetaDataPath); } } catch (Exception e) { PrintException(e, contentInfo.MetaDataPath); } } else { LogWrite("---------- Content does not exist. MetaDataPath: "); LogWrite(contentInfo.MetaDataPath); LogWrite(", ContentId: "); LogWrite(contentInfo.ContentId); LogWrite(", ContentTypeName: "); LogWrite(contentInfo.ContentTypeName); } }
/// <summary> /// Gets the number of participants. /// </summary> /// <param name="item">The CalendarEvent item.</param> /// <returns>Number of approved participants.</returns> private static int GetNumberOfParticipants(Node item) { var regForm = item.GetReference <Node>("RegistrationForm"); if (regForm != null) { var qResult = ContentQuery.Query("+Type:eventregistrationformitem +ParentId:@0", new QuerySettings { EnableAutofilters = FilterStatus.Disabled, EnableLifespanFilter = FilterStatus.Disabled }, regForm.Id); var i = 0; foreach (var node in qResult.Nodes) { var subs = Content.Create(node); var guests = 0; int.TryParse(subs["GuestNumber"].ToString(), out guests); i += (guests + 1); } return(i); } return(0); }
private void BuildAfterSubmitForm_ContentView(SNC.Content formitem) { if (CurrentForm == null) { return; } //FormItem fi = new FormItem(CurrentForm); //_cFormItem = SNC.Content.Create(fi); if (formitem == null && _formItemID != 0) { formitem = Content.Load(_formItemID); } if (formitem != null) { _cFormItem = formitem; _cvFormItem = ContentView.Create(_cFormItem, this.Page, ViewMode.New, AfterSubmitViewPath); _cvFormItem.ID = "cvAfterSubmitFormItem"; //_cvFormItem.Init += new EventHandler(_cvFormItem_Init); _cvFormItem.UserAction += new EventHandler <UserActionEventArgs>(_cvAfterSubmitFormItem_UserAction); this.Controls.Add(_cvFormItem); } else if (!string.IsNullOrEmpty(AfterSubmitViewPath)) { this.Controls.Add(Page.LoadControl(AfterSubmitViewPath)); } }
protected virtual void ProcessRegistration() { if (User.Current.Id != User.Visitor.Id) { WriteErrorMessageOnly(Configuration.AlreadyRegisteredUserMessage); return; } // creates an empty user _content = CreateNewUserContent(Configuration.DefaultDomainPath); if (_content == null) { return; } _content.ContentHandler.Created += ContentHandler_Created; // loads the publicregistration contentviews // and exception raises when registration contentview has not been found.) ChangeToAdminAccount(); try { _contentView = String.IsNullOrEmpty(Configuration.NewRegistrationContentView) ? ContentView.Create(_content, Page, ViewMode.InlineNew) : ContentView.Create(_content, Page, ViewMode.New, Configuration.NewRegistrationContentView); } catch (Exception exc) //logged { Logger.WriteException(exc); WriteErrorMessageOnly(String.Format(HttpContext.GetGlobalResourceObject("PublicRegistrationPortlet", "ErrorCreatingContentView") as string, Configuration.NewRegistrationContentView)); RestoreOriginalUser(); return; } _contentView.UserAction += ContentView_UserAction_New; Controls.Add(_contentView); RestoreOriginalUser(); }
private ValiditySetting GetValiditySetting(SNC.Content content) { ValiditySetting result = new ValiditySetting(); //if (!String.IsNullOrEmpty(this.ValidFromPropertyName)) // result.ValidFromPropertyName = this.ValidFromPropertyName; //if (!String.IsNullOrEmpty(this.ValidTillPropertyName)) // result.ValidTillPropertyName = this.ValidTillPropertyName; // try to fetch PreviewDate value if (content.Security.HasPermission(SenseNet.ContentRepository.Storage.Schema.PermissionType.OpenMinor)) { result.CurrentDateTime = GetPreviewDate(); } // reads property values result.Fill(content); // if error has been occured while parsing property values, returns null. if (!result.IsValid) { return(null); } return(result); }
public static StepResult UpdateReferences(Content content) { try { SnC.Content snContent = SnC.Content.Load(content.Path); //snContent.Save(); if (!SetMetadata(snContent, content, content.IsNewContent, true)) { Logger.LogWarningMessage(PrintFieldErrors(snContent)); return(new StepResult { Kind = StepResultKind.Warning }); } } catch (Exception transferEx) { Logger.LogException(transferEx); return(new StepResult { Kind = StepResultKind.Error }); } return(new StepResult { Kind = StepResultKind.Successful }); }
public ConfigurationWrapper(string path) { if (String.IsNullOrEmpty(path)) throw new ArgumentException("path"); _configContent = SNC.Content.Load(path); }
public void Content_FieldControl() { Node automobileNode = LoadOrCreateAutomobileAndSave(AutomobileHandler.ExtendedCTD, "Automobile12", "Honda", "Gyeby"); SNC.Content automobileContent = SNC.Content.Create(automobileNode); Field manuField = automobileContent.Fields["Manufacturer"]; Field drivField = automobileContent.Fields["Driver"]; ShortText shortText = new ShortText(); ShortTextAccessor shortTextAcc = new ShortTextAccessor(shortText); ShortText shortTextEditor = new ShortText(); ShortTextAccessor shortTextEditorAcc = new ShortTextAccessor(shortTextEditor); //-- contentview szimulacio: RegisterFieldControl shortTextAcc.ConnectToField(manuField); shortTextEditorAcc.ConnectToField(drivField); Assert.IsTrue(shortTextAcc.Text == (string)automobileContent["Manufacturer"], "#01"); Assert.IsTrue(shortTextEditorAcc.InputTextBox.Text == (string)automobileContent["Driver"], "#02"); shortTextEditorAcc.InputTextBox.Text = "Netudki"; //-- contentview szimulacio: PostData drivField.SetData(shortTextEditor.GetData()); // automobileContent.IsValid? string result = (string)automobileContent["Driver"]; Assert.IsTrue(result == "Netudki", "#03"); }
/// <summary> /// Gets the model. /// </summary> /// <returns></returns> protected override object GetModel() { //var manager = Content.Load("/Root/IMS/BuiltIn/Portal/Administrator"); var manager = Content.Load(FirstManager); if (manager == null) { throw new NotSupportedException(SenseNetResourceManager.Current.GetString("OrganizationChart", "NoSuchManagerError")); } var managerStream = manager.GetXml(true); var resultXml = new XmlDocument(); resultXml.Load(managerStream); _usedNodeId = new List <int>(); _usedNodeId.Add(manager.Id); try { GetEmployees(manager, resultXml.SelectSingleNode("/Content"), 1); } catch (Exception ex) { Logger.WriteException(ex); throw new NotSupportedException(ex.Message); } return(resultXml); }
protected override object GetModel() { if (ContextNode == null) { return(null); } var content = Content.Create(ContextNode); var qs = new QuerySettings(); if (EnableAutofilters != FilterStatus.Default) { qs.EnableAutofilters = (EnableAutofilters == FilterStatus.Enabled); } if (EnableLifespanFilter != FilterStatus.Default) { qs.EnableLifespanFilter = (EnableLifespanFilter == FilterStatus.Enabled); } if (Top > 0) { qs.Top = Top; } if (State.Skip > 0) { qs.Skip = State.Skip; } if (!string.IsNullOrEmpty(State.SortColumn)) { qs.Sort = new[] { new SortInfo { FieldName = State.SortColumn, Reverse = State.SortDescending } }; } content.ChildrenQuerySettings = qs; content.ChildrenQueryFilter = GetQueryFilter(); content.XmlWriterExtender = writer => { }; switch (CollectionAxis) { case CollectionAxisMode.Children: return(content); case CollectionAxisMode.VersionHistory: var versionRoot = SearchFolder.Create(content.Versions); return(versionRoot); case CollectionAxisMode.ReferenceProperty: return(content); case CollectionAxisMode.External: return(SearchFolder.Create(RequestNodeList)); } return(null); }
// Invalid View private void AddInvalidView() { var votingNode = ContextNode as Voting; if (votingNode == null) { Controls.Add(new Literal { Text = SenseNetResourceManager.Current.GetString("Voting", "ContextNodeError") }); return; } if (votingNode.InvalidSurveyPage == null) { Controls.Add(new Literal { Text = SenseNetResourceManager.Current.GetString("Voting", "InvalidSurveyPageError") }); return; } var landingContent = Content.Create(votingNode.InvalidSurveyPage); var landingCv = ContentView.Create(landingContent, Page, ViewMode.Browse, "/Root/Global/contentviews/WebContentDemo/Browse.ascx"); if (landingCv == null) { Controls.Add(new Literal { Text = SenseNetResourceManager.Current.GetString("Voting", "ContentViewCreateError") }); return; } Controls.Add(landingCv); }
internal bool UpdateReferences(SNC.Content content) { if (_transferringContext == null) { _transferringContext = new ImportContext(_xmlDoc.SelectNodes("/ContentMetaData/Fields/*"), null, false, true, true); } else { _transferringContext.UpdateReferences = true; } var node = content.ContentHandler; node.ModificationDate = node.ModificationDate; node.VersionModificationDate = node.VersionModificationDate; node.ModifiedBy = node.ModifiedBy; node.VersionModifiedBy = node.VersionModifiedBy; if (!content.ImportFieldData(_transferringContext)) { return(false); } if (!HasPermissions && !HasBreakPermissions) { return(true); } var permissionsNode = _xmlDoc.SelectSingleNode("/ContentMetaData/Permissions"); content.ContentHandler.Security.ImportPermissions(permissionsNode, this._metaDataPath); return(true); }
internal void CreateNewWorkspace() { try { var state = WizardState; var newName = state.WorkspaceNewName; var sourceNodePath = state.SelectedWorkspacePath; var targetNode = PortalContext.Current.ContextNodeHead ?? NodeHead.Get(TargetPath); var sourceNode = Node.LoadNode(sourceNodePath); var contentTypeName = sourceNode.Name; Content workspace = null; workspace = ContentTemplate.HasTemplate(contentTypeName) ? ContentTemplate.CreateTemplated(Node.LoadNode(targetNode.Id), ContentTemplate.GetTemplate(contentTypeName), newName) : Content.CreateNew(contentTypeName, Node.LoadNode(targetNode.Id), newName); workspace.Fields["Description"].SetData(state.WorkspaceNewDescription); workspace.Save(); var newPath = new StringBuilder(PortalContext.Current.OriginalUri.GetLeftPart(UriPartial.Authority)).Append(targetNode.Path).Append("/").Append(newName); NewWorkspaceLink.HRef = newPath.ToString(); } catch (Exception exc) //logged { Logger.WriteException(exc); HasError = true; ErrorMessageControl.Visible = true; ErrorMessageControl.Text = exc.Message; // log exception } }
internal static List <SNC.Content> GetChildren(int contentId, string repositoryId, out SNC.Content folder) { SNC.Content content = null; content = SNC.Content.Load(contentId); if (content == null) { throw new ArgumentException("Object '" + contentId + "' is not exist in '" + repositoryId + "' repository"); } var ifolder = content.ContentHandler as IFolder; if (ifolder == null) { throw new ArgumentException("Object is not a folder (id = '" + contentId + "')"); } var contentList = new List <SNC.Content>(); foreach (var node in ifolder.Children) { contentList.Add(SNC.Content.Create(node)); } folder = content; return(contentList); }
private void AddThankYouPage() { var parent = Content.Load((int)this.Content["ParentId"]); Node landingPage = null; Node landingView = null; // elevation: we do not want to grant Open permission to the user for this technical content using (new SystemAccount()) { if (parent.Fields.ContainsKey("LandingPage") && parent.Fields.ContainsKey("PageContentView")) { landingPage = parent["LandingPage"] as Node; landingView = parent["PageContentView"] as Node; } } if (landingPage == null || landingView == null) { return; } var landingContent = Content.Create(landingPage); var landingCV = ContentView.Create(landingContent, this.Page, ViewMode.Browse, landingView.Path); _wizard.WizardSteps[_wizard.WizardSteps.Count - 1].Controls.Add(landingCV); _wizard.WizardSteps[_wizard.WizardSteps.Count - 2].AllowReturn = false; }
// Constructors //////////////////////////////////////////// public ConfigurationWrapper(SNC.Content configContent) { if (configContent == null) throw new ArgumentNullException("configContent"); _configContent = configContent; }
protected override void CreateChildControls() { var content = Content.Create(ContextNode); var view = ContentView.Create(content, Page, ViewMode.Browse); Controls.Add(view); }
private void ProcessUpdateProfile() { _content = SNC.Content.Load(User.Current.Id); if (_content == null) { return; // todo: could not load current user content. } var currentUserNodeTypeName = ((Node)User.Current).NodeType.Name; if (currentUserNodeTypeName != Configuration.UserTypeName) { this.Controls.Clear(); this.Controls.Add(new LiteralControl(HttpContext.GetGlobalResourceObject("PublicRegistrationPortlet", "UserTypeDoesNotMatch") as string)); return; // todo: update only the correct UserType. It prevents that user updates his/her profile with another user type inlinenew contentview. } this.ChangeToAdminAccount(); try { _contentView = String.IsNullOrEmpty(Configuration.EditProfileContentView) ? ContentView.Create(this._content, this.Page, ViewMode.InlineEdit) : ContentView.Create(this._content, this.Page, ViewMode.InlineEdit, Configuration.EditProfileContentView); } catch (Exception exc) //logged { Logger.WriteException(exc); WriteErrorMessageOnly(String.Format(HttpContext.GetGlobalResourceObject("PublicRegistrationPortlet", "ErrorCreatingContentView") as string, Configuration.EditProfileContentView)); this.RestoreOriginalUser(); return; } this._contentView.UserAction += new EventHandler <UserActionEventArgs>(ContentView_UserAction_Update); this.Controls.Add(this._contentView); this.RestoreOriginalUser(); }
/// <summary> /// Sets the callback URL of the ActionMenu. It represents the service url with correct parameters for the actions. /// </summary> private void SetServiceUrl() { var scParams = GetReplacedScenarioParameters(); var context = UITools.FindContextInfo(this, ContextInfoID); var path = !String.IsNullOrEmpty(ContextInfoID) ? context.Path : NodePath; var encodedReturnUrl = Uri.EscapeDataString(PortalContext.Current.RequestedUri.PathAndQuery); var encodedParams = Uri.EscapeDataString(scParams ?? string.Empty); if (String.IsNullOrEmpty(path)) { path = GetPathFromContentView(this); } if (string.IsNullOrEmpty(path)) { this.Visible = false; return; } this.Content = Content.Load(path); //Pre-check action count. If empty, hide the action menu. if (CheckActionCount) { var sc = ScenarioManager.GetScenario(Scenario, scParams); var actionCount = 0; if (sc != null) { actionCount = sc.GetActions(this.Content, PortalContext.Current.RequestedUri.PathAndQuery).Count(); } if (actionCount < 2 && string.Equals(Scenario, "new", StringComparison.CurrentCultureIgnoreCase)) { ClickDisabled = true; } else if (actionCount == 0) { this.Visible = false; return; } } //Pre-check required permissions var permissions = ActionFramework.GetRequiredPermissions(RequiredPermissions); if (permissions.Count > 0 && !SecurityHandler.HasPermission(NodeHead.Get(path), permissions.ToArray())) { this.Visible = false; return; } var encodedPath = HttpUtility.UrlEncode(path); ServiceUrl = String.Format("/SmartAppHelper.mvc/GetActions?path={0}&scenario={1}&back={2}¶meters={3}", encodedPath, Scenario, encodedReturnUrl, encodedParams); }
public void Content_UsingFieldControls_ReadWriteWithConversion() { Node automobileNode = LoadOrCreateAutomobile(@"<?xml version='1.0' encoding='utf-8'?> <ContentType name='Automobile' parentType='GenericContent' handler='SenseNet.ContentRepository.Tests.ContentHandlers.AutomobileHandler' xmlns='http://schemas.sensenet.com/SenseNet/ContentRepository/ContentTypeDefinition'> <Fields> <Field name='Manufacturer' type='ShortText'> <Configuration> <Compulsory>true</Compulsory> <MaxLength>100</MaxLength> <Format>TitleCase</Format> </Configuration> </Field> <Field name='Driver' type='ShortText'> <Configuration> <Compulsory>true</Compulsory> <MaxLength>100</MaxLength> </Configuration> </Field> <Field name='BodyColor' type='Color'> <Bind property='BodyColor' /> </Field> </Fields> </ContentType> ", "Automobile12", "Trabant", "Netudki"); SNC.Content automobileContent = SNC.Content.Create(automobileNode); automobileContent["BodyColor"] = Color.Red; automobileContent.Save(); automobileContent = SNC.Content.Load(automobileContent.ContentHandler.Id); ColorEditorControl colorControl = new ColorEditorControl(); ColorControlAccessor colorControlAcc = new ColorControlAccessor(colorControl); colorControl.FieldName = "BodyColor"; colorControlAcc.ConnectToField(automobileContent.Fields["BodyColor"]); ShortText manuControl = new ShortText(); ShortTextAccessor manuControlAcc = new ShortTextAccessor(manuControl); manuControl.FieldName = "Manufacturer"; manuControlAcc.ConnectToField(automobileContent.Fields["Manufacturer"]); ShortText driverControl = new ShortText(); ShortTextAccessor driverControlAcc = new ShortTextAccessor(driverControl); driverControl.FieldName = "Driver"; driverControlAcc.ConnectToField(automobileContent.Fields["Driver"]); string colorString = colorControl.textBox1.Text; Color color = colorControl.textBox1.BackColor; string manu = manuControlAcc.Text; string driver = driverControlAcc.Text; Assert.IsTrue(colorString == "#FF0000", "#1"); Assert.IsTrue(color == ColorField.ColorFromString(ColorField.ColorToString(Color.Red)), "#2"); Assert.IsTrue(manu == "Trabant", "#2"); Assert.IsTrue(driver == "Netudki", "#2"); //-- Ha nincs hiba: sikeres }
private static ContentView CreateFromActualPath(SNC.Content content, System.Web.UI.Page aspNetPage, ViewMode viewMode, string viewPath) { if (content == null) { throw new ArgumentNullException("content"); } if (aspNetPage == null) { throw new ArgumentNullException("aspNetPage"); } if (viewPath == null) { throw new ArgumentNullException("viewPath"); } if (viewPath.Length == 0) { throw new ArgumentOutOfRangeException("viewPath", "Parameter 'viewPath' cannot be empty"); } if (viewMode == ViewMode.None) { throw new ArgumentOutOfRangeException("viewMode", "Parameter 'viewMode' cannot be ViewMode.None"); } string path = String.Concat("~", viewPath); ContentView view = GetContentViewFromCache(path); // if not in request cache if (view == null) { var addToCache = false; try { view = aspNetPage.LoadControl(path) as ContentView; addToCache = true; } catch (Exception e) //logged { Logger.WriteException(e); var errorContentViewPath = RepositoryPath.Combine(Repository.ContentViewFolderName, "Error.ascx"); var resolvedErrorContentViewPath = SkinManager.Resolve(errorContentViewPath); path = String.Concat("~", resolvedErrorContentViewPath); view = aspNetPage.LoadControl(path) as ContentView; view.ContentException = e; } if (view == null) { throw new ApplicationException(string.Format("ContentView instantiation via LoadControl for path '{0}' failed.", path)); } if (addToCache) { AddContentViewToCache(path, view); } } view.Initialize(content, viewMode); return(view); }
private void AddSelectedNewContentView(string selectedContentTypeName) { var placeHolder = _currentUserControl.FindControl("ContentViewPlaceHolder") as PlaceHolder; if (placeHolder == null) { return; } var currentContextNode = GetContextNode(); if (_currentContent != null) { _contentView = GetContentView(_currentContent); // backward compatibility: use eventhandler for contentviews using defaultbuttons and not commandbuttons _contentView.UserAction += NewContentViewUserAction; placeHolder.Visible = true; placeHolder.Controls.Clear(); placeHolder.Controls.Add(_contentView); return; } if (String.IsNullOrEmpty(selectedContentTypeName)) { selectedContentTypeName = SelectedContentType; } Content newContent = null; var ctd = ContentType.GetByName(selectedContentTypeName); if (ctd == null) { // // In this case, the selectedContentTypeName contains only the templatePath. It is maybe a security issue because path is rendered into value attribute of html option tag. // string parentPath = currentContextNode.Path; string templatePath = selectedContentTypeName; newContent = ContentTemplate.CreateTemplated(parentPath, templatePath); _contentView = GetContentView(newContent); } else { // // Yes it is a valid contentTypeName // newContent = ContentManager.CreateContentFromRequest(selectedContentTypeName, null, currentContextNode.Path, true); _contentView = GetContentView(newContent); } // backward compatibility: use eventhandler for contentviews using defaultbuttons and not commandbuttons _contentView.UserAction += NewContentViewUserAction; placeHolder.Visible = true; placeHolder.Controls.Clear(); placeHolder.Controls.Add(_contentView); }
// Constructors //////////////////////////////////////////// public ConfigurationWrapper(SNC.Content configContent) { if (configContent == null) { throw new ArgumentNullException("configContent"); } _configContent = configContent; }
public void Content_UsingFieldControls_ReadComplexProperties() { Node automobileNode = CreateNewAutomobileAndSave(@"<?xml version='1.0' encoding='utf-8'?> <ContentType name='Automobile' parentType='GenericContent' handler='SenseNet.ContentRepository.Tests.ContentHandlers.AutomobileHandler' xmlns='http://schemas.sensenet.com/SenseNet/ContentRepository/ContentTypeDefinition'> <Fields> <Field name='Modified' type='WhoAndWhen'> <Bind property='ModifiedBy' /> <Bind property='ModificationDate' /> </Field> <Field name='Manufacturer' type='ShortText'> <Configuration> <Compulsory>true</Compulsory> <MaxLength>100</MaxLength> <Format>TitleCase</Format> </Configuration> </Field> <Field name='Driver' type='ShortText'> <Configuration> <Compulsory>true</Compulsory> <MaxLength>100</MaxLength> </Configuration> </Field> </Fields> </ContentType> ", "Automobile12", "Trabant", "Netudki"); SNC.Content automobileContent = SNC.Content.Create(automobileNode); WhoAndWhen whoAndWhenControl = new WhoAndWhen(); WhoAndWhenAccessor whoAndWhenAcc = new WhoAndWhenAccessor(whoAndWhenControl); whoAndWhenControl.FieldName = "Modified"; whoAndWhenAcc.ConnectToField(automobileContent.Fields["Modified"]); //automobileContent.Fields["Modified"].ConnectToView(whoAndWhenControl); ShortText manuControl = new ShortText(); ShortTextAccessor manuControlAcc = new ShortTextAccessor(manuControl); manuControl.FieldName = "Manufacturer"; manuControlAcc.ConnectToField(automobileContent.Fields["Manufacturer"]); //automobileContent.Fields["Manufacturer"].ConnectToView(manuControl); ShortText driverControl = new ShortText(); ShortTextAccessor driverControlAcc = new ShortTextAccessor(driverControl); driverControl.FieldName = "Driver"; driverControlAcc.ConnectToField(automobileContent.Fields["Driver"]); //automobileContent.Fields["Driver"].ConnectToView(driverControl); string who = whoAndWhenControl.label1.Text; string when = whoAndWhenControl.label2.Text; string manu = manuControlAcc.Text; string driver = driverControlAcc.Text; Assert.IsFalse(String.IsNullOrEmpty(who), "#1"); Assert.IsFalse(String.IsNullOrEmpty(when), "#2"); Assert.IsFalse(String.IsNullOrEmpty(manu), "#3"); Assert.IsFalse(String.IsNullOrEmpty(driver), "#4"); }
// Thank You View private void AddThankYouView() { var votingNode = ContextNode as Voting; if (votingNode == null) { Controls.Add(new Literal { Text = SenseNetResourceManager.Current.GetString("Voting", "ContextNodeError") }); return; } if (votingNode.LandingPage == null) { Controls.Add(new Literal { Text = SenseNetResourceManager.Current.GetString("Voting", "LandingPageError") }); return; } var landingContent = Content.Create(votingNode.LandingPage); if (landingContent == null) { Controls.Add(new Literal { Text = SenseNetResourceManager.Current.GetString("Voting", "ContentCreateError") }); return; } var landingCv = ContentView.Create(landingContent, Page, ViewMode.Browse, votingNode.GetReference <Node>("LandingPageContentView") != null ? votingNode.GetReference <Node>("LandingPageContentView").Path : "/Root/Global/contentviews/WebContentDemo/Browse.ascx"); if (landingCv == null) { Controls.Add(new Literal { Text = SenseNetResourceManager.Current.GetString("Voting", "ContentViewCreateError") }); return; } Controls.Add(landingCv); //if (MoreFilingIsEnabled && UserVoted && VotingPortletMode == PortletMode.VoteAndGotoResult) //{ // var lb = landingCv.FindControl("VotingAndResult") as LinkButton; // if (lb == null) // { // Controls.Add(new Literal { Text = SenseNetResourceManager.Current.GetString("Voting", "CannotFindLink") }); // return; // } // lb.Text = SenseNetResourceManager.Current.GetString("Voting", "GoToResultLink"); // lb.Click += LbClick; // lb.Visible = true; //} }
public ConfigurationWrapper(string path) { if (String.IsNullOrEmpty(path)) { throw new ArgumentException("path"); } _configContent = SNC.Content.Load(path); }
private static string GenerateAtomContent(SNC.Content content) { return(String.Concat( "Name: ", content.Name, ", type: ", String.IsNullOrEmpty(content.ContentType.DisplayName) ? content.ContentType.Name : content.ContentType.DisplayName, content.ContentHandler is IFolder ? ". This object can contain other objects" : "", ". ", String.IsNullOrEmpty(content.ContentType.Description) ? "" : content.ContentType.Description )); }
internal static SNC.Content GetContent(int contentId, string repositoryId) { SNC.Content content = null; content = SNC.Content.Load(contentId); if (content == null) { throw new ArgumentException("Object '" + contentId + "' is not exist in '" + repositoryId + "' repository"); } return(content); }
private void ProcessUpdateProfile() { _content = SNC.Content.Load(User.Current.Id); if (_content == null) return; // todo: could not load current user content. var currentUserNodeTypeName = ((Node)User.Current).NodeType.Name; if (currentUserNodeTypeName != Configuration.UserTypeName) { this.Controls.Clear(); this.Controls.Add(new LiteralControl(HttpContext.GetGlobalResourceObject("PublicRegistrationPortlet", "UserTypeDoesNotMatch") as string)); return; // todo: update only the correct UserType. It prevents that user updates his/her profile with another user type inlinenew contentview. } this.ChangeToAdminAccount(); try { _contentView = String.IsNullOrEmpty(Configuration.EditProfileContentView) ? ContentView.Create(this._content, this.Page, ViewMode.InlineEdit) : ContentView.Create(this._content, this.Page, ViewMode.InlineEdit, Configuration.EditProfileContentView); } catch (Exception exc) //logged { Logger.WriteException(exc); WriteErrorMessageOnly(String.Format(HttpContext.GetGlobalResourceObject("PublicRegistrationPortlet", "ErrorCreatingContentView") as string, Configuration.EditProfileContentView)); this.RestoreOriginalUser(); return; } this._contentView.UserAction += new EventHandler<UserActionEventArgs>(ContentView_UserAction_Update); this.Controls.Add(this._contentView); this.RestoreOriginalUser(); }
protected override ContentView GetContentView(Content newContent) { if (!string.IsNullOrEmpty(ContentViewPath)) return base.GetContentView(newContent); var contentList = ContentList.GetContentListByParentWalk(GetContextNode()); if (contentList != null) { //try to find a content view at /Root/.../MyList/WorkflowTemplates/MyWorkflow.ascx var wfTemplatesPath = RepositoryPath.Combine(contentList.Path, "WorkflowTemplates"); var viewPath = RepositoryPath.Combine(wfTemplatesPath, newContent.Name + ".ascx"); if (Node.Exists(viewPath)) return ContentView.Create(newContent, Page, ViewMode.InlineNew, viewPath); //try to find it by type name, still locally viewPath = RepositoryPath.Combine(wfTemplatesPath, newContent.ContentType.Name + ".ascx"); if (Node.Exists(viewPath)) return ContentView.Create(newContent, Page, ViewMode.InlineNew, viewPath); //last attempt: global view for the workflow type return ContentView.Create(newContent, Page, ViewMode.InlineNew, "StartWorkflow.ascx"); } else { var viewPath = string.Format("{0}/{1}/{2}", Repository.ContentViewFolderName, newContent.ContentType.Name, "StartWorkflow.ascx"); var resolvedPath = string.Empty; if (!SkinManager.TryResolve(viewPath, out resolvedPath)) { resolvedPath = RepositoryPath.Combine(Repository.SkinGlobalFolderPath, SkinManager.TrimSkinPrefix(viewPath)); if (!Node.Exists(resolvedPath)) resolvedPath = string.Empty; } if (!string.IsNullOrEmpty(resolvedPath)) return ContentView.Create(newContent, Page, ViewMode.InlineNew, resolvedPath); } return base.GetContentView(newContent); }
/// <summary> /// Gets the employees. /// </summary> /// <param name="manager">The manager.</param> /// <param name="container">The container.</param> /// <param name="depth">The depth.</param> private void GetEmployees(Content manager, XmlNode container, int depth) { if(depth>DepthLimit) return; var employeesNode = container.OwnerDocument.CreateElement("Employees"); container.AppendChild(employeesNode); var query = SenseNet.Search.LucQuery.Parse(string.Format("+Manager:{0} +Type:User", manager.Id)); var result = query.Execute(); foreach (var lucObject in result) { if (!_usedNodeId.Contains(lucObject.NodeId)) _usedNodeId.Add(lucObject.NodeId); else throw new NotSupportedException(SenseNetResourceManager.Current.GetString("OrganizationChart", "CircularReferenceError")); var employee = Content.Load(lucObject.NodeId); var employeeStream = employee.GetXml(false); var employeeXml = new XmlDocument(); employeeXml.Load(employeeStream); var node = employeesNode.OwnerDocument.ImportNode(employeeXml.DocumentElement,true); employeesNode.AppendChild(node); var employeeNode = employeesNode.SelectSingleNode(string.Format("Content[SelfLink='{0}']", employee.Path)); GetEmployees(employee, employeeNode, depth + 1); } }
public static List<string> GetVisibleFieldNames(Content content, ViewMode viewMode) { var names = new List<string>(); if (content == null) return names; var fields = content.Fields; var fieldNames = SortFieldNames(content); foreach (var fieldName in fieldNames) { var field = fields[fieldName]; var visible = true; switch (viewMode) { case ViewMode.Browse: visible = field.FieldSetting.VisibleBrowse != FieldVisibility.Hide; break; case ViewMode.Edit: case ViewMode.InlineEdit: visible = field.FieldSetting.VisibleEdit != FieldVisibility.Hide; break; case ViewMode.New: case ViewMode.InlineNew: visible = field.FieldSetting.VisibleNew != FieldVisibility.Hide; break; } if (!visible) continue; names.Add(fieldName); } return names; }
private static IEnumerable<string> SortFieldNames(Content content) { var fieldNames = new List<string>(); var mainPath = content.ContentType.Path; var mainFields = new SortedDictionary<string, List<string>>(); var linkedFields = new SortedDictionary<string, List<string>>(); var orderedFields = new List<Field>(); orderedFields.AddRange(from f in content.Fields.Values orderby f.FieldSetting.FieldIndex select f); foreach (var field in orderedFields) { if (field.Name.StartsWith("#")) continue; try { fieldNames.Add(field.Name); } catch { //unknown field } } //add main fields foreach (var fieldList in mainFields.Values) { fieldNames.AddRange(fieldList); } //add linked fields foreach (var fieldList in linkedFields.Values) { fieldNames.AddRange(fieldList); } //list fields fieldNames.AddRange((from f in orderedFields where f.Name.StartsWith("#") select f.Name)); return fieldNames; }
public DefaultQueryBuilder(string originalQuery, Content searchForm,ContentSearchPortlet.EmptyQueryTermHandler emptyTerm) { _originalQuery = originalQuery; _searchForm = searchForm; _emptyTermHandler = emptyTerm; }
protected override void CreateChildControls() { if (this.HiddenPropertyCategories == null) this.HiddenPropertyCategories = new List<string>(); this.HiddenPropertyCategories.Add("Cache"); // this is an administrative portlet we don't need to use Cache functionality. Controls.Clear(); _currentUserControl = LoadUserInterface(Page, GuiPath); // 1st allowed types check: if allowed content types list is empty, only administrators should be able to use this portlet var parentPath = GetParentPath(); if (!AllowCreationForEmptyAllowedContentTypes(parentPath)) { Controls.Add(new LiteralControl("Allowed ContentTypes list is empty!")); return; } if (_currentUserControl != null) { if (this.ContextNode != null && !string.IsNullOrEmpty(parentPath)) { try { _currentContent = ContentManager.CreateContentFromRequest(GetRequestedContentType(), null, parentPath, true); } catch (Exception ex) { Logger.WriteException(ex); } } if (_currentContent != null) { CurrentState = States[1]; } if (ContentTypeIsValid()) { SetControlsByState(); try { Controls.Add(_currentUserControl); } catch (Exception ex) { Logger.WriteException(ex); Controls.Clear(); var message = ex.Message.Contains("does not contain Field") ? string.Format("Content and view mismatch: {0}", ex.Message) : string.Format("Error: {0}", ex.Message); Controls.Add(new LiteralControl(message)); } } else { Controls.Clear(); if (_currentContent != null) { Logger.WriteError(string.Format("Forbidden content type ({0}) under {1}", _currentContent.ContentType.Name,_currentContent.ContentHandler.ParentPath)); Controls.Add(new LiteralControl(string.Format("It is not allowed to add a new {0} here.", _currentContent.ContentType.Name))); } } } ChildControlsCreated = true; }
protected virtual ContentView GetContentView(Content newContent) { return String.IsNullOrEmpty(ContentViewPath) ? ContentView.Create(newContent, Page, ViewMode.InlineNew) : ContentView.Create(newContent, Page, ViewMode.InlineNew, ContentViewPath); }
protected override void CreateChildControls() { base.CreateChildControls(); try { var ctn = ContextNode; } catch (SenseNetSecurityException) { Controls.Add(new Literal { Text = SenseNetResourceManager.Current.GetString("Voting", "ContextNodePermissionError") }); return; } // Check ContextNode is not null if ((ContextNode as Voting) == null) { Controls.Add(new Literal { Text = SenseNetResourceManager.Current.GetString("Voting", "ContextNodeError") }); return; } try { _currentContent = Content.Create(ContextNode); } catch (Exception) { Controls.Add(new Literal { Text = SenseNetResourceManager.Current.GetString("Voting", "BindingError") }); return; } // Check portlets' field to wheter to check validTill and validFrom fields if (this.EnableLifeSpan) { DateTime validFrom = ContextNode.GetProperty<DateTime>("ValidFrom"); DateTime validTill = ContextNode.GetProperty<DateTime>("ValidTill"); if (validTill == DateTime.MinValue) validTill = DateTime.MaxValue; // Check if the voting is valid to fill it if (DateTime.Now < validFrom || DateTime.Now >= validTill) { AddInvalidView(); return; } } // ResultOnly PorletMode if (VotingPortletMode == PortletMode.ResultOnly) { AddResultView(); } // VotingOnly PorletMode else if (VotingPortletMode == PortletMode.VotingOnly) { switch (_myState) { case "VotingView": AddVotingView(); break; case "ThankYouView": AddThankYouView(); break; default: Controls.Add(new Literal { Text = SenseNetResourceManager.Current.GetString("Voting", "VotingOnlyError") }); break; } } // VoteAndGotoResult PorletMode else if (VotingPortletMode == PortletMode.VoteAndGotoResult) { switch (_myState) { case "VotingView": if (MoreFilingIsEnabled || !UserVoted) { AddVotingView(); } else { AddResultView(); } break; case "ResultView": AddResultView(); break; case "ThankYouView": AddThankYouView(); AddResultView(); break; default: Controls.Add(new Literal { Text = SenseNetResourceManager.Current.GetString("Voting", "VoteAndGotoResultError") }); break; } } // ResultAndVoting PorletMode else if (VotingPortletMode == PortletMode.ResultAndVoting) { switch (_myState) { case "VotingView": if (ViewsOrder == ViewOrders.VotingViewFirst) { AddVotingView(); AddResultView(); } else { AddResultView(); AddVotingView(); } break; case "ThankYouView": AddThankYouView(); break; case "ResultView": AddResultView(); break; default: Controls.Add(new Literal { Text = SenseNetResourceManager.Current.GetString("Voting", "ResultAndVotingError") }); break; } } ChildControlsCreated = true; }
protected virtual void ProcessRegistration() { if (User.Current.Id != User.Visitor.Id) { WriteErrorMessageOnly(Configuration.AlreadyRegisteredUserMessage); return; } // creates an empty user _content = CreateNewUserContent(Configuration.DefaultDomainPath); if (_content == null) return; _content.ContentHandler.Created += ContentHandler_Created; // loads the publicregistration contentviews // and exception raises when registration contentview has not been found.) ChangeToAdminAccount(); try { _contentView = String.IsNullOrEmpty(Configuration.NewRegistrationContentView) ? ContentView.Create(_content, Page, ViewMode.InlineNew) : ContentView.Create(_content, Page, ViewMode.New, Configuration.NewRegistrationContentView); } catch (Exception exc) //logged { Logger.WriteException(exc); WriteErrorMessageOnly(String.Format(HttpContext.GetGlobalResourceObject("PublicRegistrationPortlet", "ErrorCreatingContentView") as string, Configuration.NewRegistrationContentView)); RestoreOriginalUser(); return; } _contentView.UserAction += ContentView_UserAction_New; Controls.Add(_contentView); RestoreOriginalUser(); }
private void BuildContentView(string contentTypeName, Node parent, ViewMode viewMode) { var viewPath = string.Empty; #region creates container) if (_container == null) CreateContainer(); else { _container.Controls.Clear(); //this.Controls.Remove(_container); } if (this._container.Parent == null) this.Controls.Add(this._container); #endregion #region creates new content or loads an existing one // when we are in InlineNew creates an empty content if (viewMode == ViewMode.InlineNew) _content = SNC.Content.CreateNew(contentTypeName, parent, string.Empty); // when the portlet is in browse, edit, inlineedit states, loads the content if (viewMode == ViewMode.Browse || viewMode == ViewMode.Edit || viewMode == ViewMode.InlineEdit) { Node node = Node.LoadNode(this.AbsoulteContentPath); // check if can select a single node (ie smartfolderex) ICustomSingleNode singleNode = node as ICustomSingleNode; // select single node if (singleNode != null) node = singleNode.SelectedItem(); if (node == null) _content = null; else _content = SNC.Content.Create(node); //_content = SNC.Content.Load(this.AbsoulteContentPath); } #endregion if (viewMode == ViewMode.InlineEdit || viewMode == ViewMode.Edit) this._displayMode = GetViewModeName(ViewMode.Edit); // if content does not exist stop creating controls. if (_content == null) { this._errorMessage = String.Format(HttpContext.GetGlobalResourceObject("SingleContentPortlet", "PathNotFound") as string,AbsoulteContentPath); return; } #region checks validity // if content is not valid, exit the method, and an empty contol will be shown to the user. if (User.Current.Id == User.Visitor.Id) { if (this.ValidationSetting != ValidationOption.DontCheckValidity) { _validitySetting = GetValiditySetting(_content); if (_validitySetting != null) { // User has been set the ValidationSetting, // and checks the content will be displayed or not. // if the content is not visible, just return (and don't do anything else) // otherwise the content processing will be going on. switch (this.ValidationSetting) { case ValidationOption.ShowAllValid: if (!_validitySetting.ShowAllValidContent) return; break; case ValidationOption.ShowValidButArchived: if (!_validitySetting.ShowValidAndArchived) return; break; case ValidationOption.ShowValidButNotArchived: if (!_validitySetting.ShowValidAndNotArchived) return; break; case ValidationOption.DontCheckValidity: // not used default: break; } } } } #endregion viewPath = GetViewPath(); // try to create ContentView which contains all webcontrols of the content try { if (this.UseUrlPath ) _contentView = ContentView.Create(_content, this.Page, viewMode, String.IsNullOrEmpty(this.ContentViewPath) ? viewPath : this.ContentViewPath); else _contentView = ContentView.Create(_content, this.Page, viewMode, viewPath); _container.Controls.Remove(_contentView); } catch (Exception e) //logged { Logger.WriteException(e); this._errorMessage = String.Format("Message: {0} {1} Source: {2} {3} StackTrace: {4} {5}", e.Message, Environment.NewLine, e.Source, Environment.NewLine, e.StackTrace, Environment.NewLine); return; } _contentView.UserAction += new EventHandler<UserActionEventArgs>(_contentView_UserAction); _container.Controls.Add(_contentView); }