I have this question many times and bored while trying to find good solution.
Dont understand why microsoft not include method which can easy determine mode of display page: "normal display" or in "design mode".
It have many advices of check different variables, but it cant uniquely say that page in design on different type of page(webpart page and wiki page) and on postback or not.
Is finally tired me and i write this:
public static bool IsDesignTime()
{
if (SPContext.Current.IsDesignTime) return true;
if (HttpContext.Current.Request.QueryString["DisplayMode"] != null)
return true;
var page = HttpContext.Current.Handler as Page;
if(page == null) return false;
var inDesign = page.Request.Form["MSOLayout_InDesignMode"];
var dispMode = page.Request.Form["MSOSPWebPartManager_DisplayModeName"];
var wikiMode = page.Request.Form["_wikiPageMode"];
var we = page.Request.Form["ctl00$PlaceHolderMain$btnWikiEdit"];
if (inDesign == null & dispMode == null) return false; //normal display
if (we == "edit") return true; //design on wiki pages
if (page is WikiEditPage & page.IsPostBack & inDesign == "" & dispMode == "Browse" & wikiMode == "") return false; //display wiki on postback
if (inDesign == "" & dispMode == "Browse" & (wikiMode == null | wikiMode == "")) return false; //postback in webpart pages in display mode
if (inDesign == "0" & dispMode == "Browse") return false; //exiting design on webpart pages
return true;
}
Does anybody have better solution?
you have 2 case to detect the page mode:
In case you are using a team site :
if (Microsoft.SharePoint.SPContext.Current.FormContext.FormMode == SPControlMode.Edit)
{
ltr.Text = "EditMode2";
}
else
{
ltr.Text = "ViewMode";
}
in case you are using a publishing site:
if (Microsoft.SharePoint.SPContext.Current.FormContext.FormMode == SPControlMode.Display)
{
// your code to support display mode
}
else // Microsoft.SharePoint.SPContext.Current.FormContext.FormMode = SPControlMode.Edit
{
// your code to support edit mode
}
if your work in WebpartPage than below code work for me
WebPartManager mgr = this.WebPartManager;
if (mgr.DisplayMode == WebPartManager.EditDisplayMode)
{
// logic when in Edit Mode
}
else
{
}
I had a hard time getting any of these answers to work in Sharepoint 2013 given all the scenarios. I also couldn't get EditModePanel to work consistently. I found a snippet in this article that seems to work in every scenario I've tried so far.
Note: This does not work in Page_Init but will work in Page_Load
var isPublishing = SPContext.Current.FormContext.FormMode != SPControlMode.Invalid;
var wpDMode = WebPartManager.GetCurrentWebPartManager(Page).DisplayMode.Name;
var isEditing = isPublishing
? SPContext.Current.FormContext.FormMode != SPControlMode.Display
: (wpDMode.Equals("Edit") || wpDMode.Equals("Design"));
Then you can simply check isEditing for your conditions.
please try this code ..
if (Microsoft.SharePoint.SPContext.Current.FormContext.FormMode == SPControlMode.Display)
{
// your code to support display mode
}
else // Microsoft.SharePoint.SPContext.Current.FormContext.FormMode = SPControlMode.Edit
{
// your code to support edit mode
}
Handling SharePoint Page Modes.
This works for me , I resolved my critical issue by using below lines.
if (Microsoft.SharePoint.SPContext.Current.FormContext.FormMode == SPControlMode.Edit)
{
alert.Text = "EditMode2";
}
else
{
alert.Text = "ViewMode";
}
Related
I have this requirment to only index that data, for searching, which is being used in some page. For example if I upload a document it shouldn't be available for search until I use it in some page. I found out this code online
ContentIndexer.Instance.Conventions.ForInstancesOf().ShouldIndex(x =>
{
var contentRepository =
EPiServer.ServiceLocation.ServiceLocator.Current.GetInstance();
var contentSoftLinkRepository =
EPiServer.ServiceLocation.ServiceLocator.Current.GetInstance();
var softLinks = contentSoftLinkRepository.Load(x.ContentLink, true);
try
{
foreach (var softLink in softLinks)
{
if (softLink.SoftLinkType == ReferenceType.ExternalReference ||
softLink.SoftLinkType == ReferenceType.ImageReference)
{
var content =
contentRepository.Get(softLink.OwnerContentLink);
if (!ContentIndexer.Instance.Conventions.ShouldIndexConvention.ShouldIndex(content).Value) // don't index referenced file if content is marked as not indexed
{
continue;
}
// only index if content is published
var publicationStatus =
content.PublishedInLanguage()[softLink.OwnerLanguage.Name];
if (publicationStatus != null &&
(publicationStatus.StartPublish == null ||
publicationStatus.StartPublish < DateTime.Now) &&
(publicationStatus.StopPublish == null ||
DateTime.Now < publicationStatus.StopPublish))
{
return true;
}
}
}
}
catch
{
// ooops something went wrong. Better not index this one ;-)
}
return false;
});
This works when I attach softlinks. But lets say a page has a property called Content type and when I add something in there, lets say a block which has softlinks to that document, it doesn't work. I am stuck in there. Any hints?
Do you have a wildcard * host configured on any of your sites?
Check Admin > Manage websites and go through all sites to see if there is a * configured.
Having a wildcard tells Episerver Find to index standalone content (i.e. globalassets) using the site primary URL that contains the wildcard, regardless of it being referenced. If you don't have a wildcard configured, Episerver Find can't index content that are NOT referenced (i.e. globalassets) because it cannot generate a public URL for it. Global assets that are referenced will be indexed using the domain of the site that references it. Hope this helps.
I'm developing a code gen (VSIX) for my team and I'm intendedly using Roslyn as a fundamental engine after I have struggling with VSIX extensibility framework.
My code gen is currently able generate a new csproj for the solution and able to churn out boilerplate code base based on Templating project from VSIX extensibility. As ambitious I am, I'm trying not to rely on static templating project and use Roslyn to churn out the code instead.
My solution has a list of folders and each folder has a list of csproj.
My Question 1 is I'm trying to use Roslyn Workspace API to detect the current document (.cs) that has been open in code editor or am trying to get the current doc id of the selected cs file I right click from the solution explorer.
I have tried to use AdhocWorkspace which so far have failed as I'm not able to get any.
Question 2: If I were to use AdhocWorkspace, am I able to change the default namespace in the csproj properties? Or was it not part of the functionalities in Roslyn Workspace API at the moment?
Thanks.
For #1 some code I have to do the same thing. I am doing stuff with the cursor so I'm going through caretPosition (cursor). There are other ways but the gist is the same, get the current textview the go from that to Roslyn.
You will need to install Microsoft.CodeAnalysis.EditorFeatures.Text which brings in allot of code analysis packages but allows you to use he GetOpenDocumentInCurrentContextWithChanges extension applied on ITextSnapshot
private IVsEditorAdaptersFactoryService GetEditorAdaptersFactoryService()
{
IComponentModel componentModel =(IComponentModel)GetService(typeof(SComponentModel));
return componentModel.GetService<IVsEditorAdaptersFactoryService>();
}
private Microsoft.VisualStudio.Text.Editor.IWpfTextView GetTextView()
{
IVsTextManager textManager = (IVsTextManager)GetService(typeof(SVsTextManager));
if (textManager == null)
return null;
IVsTextView textView = null;
textManager.GetActiveView(1, null, out textView);
if (textView == null)
return null;
return GetEditorAdaptersFactoryService().GetWpfTextView(textView);
}
//code to get the doc
Microsoft.VisualStudio.Text.Editor.IWpfTextView textView = GetTextView();
if (textView != null)
{
SnapshotPoint caretPosition = textView.Caret.Position.BufferPosition;
Document document = caretPosition.Snapshot.GetOpenDocumentInCurrentContextWithChanges();
//do stuff with Roslyn Document
}
"or am trying to get the current doc id of the selected cs file I right click from the solution explorer."
This is really ugly but what I used from a different SO post (don't remember the author) that does work well.
private static bool IsSingleProjectItemSelection(out IVsHierarchy hierarchy, out uint itemid)
{
hierarchy = null;
itemid = VSConstants.VSITEMID_NIL;
int hr = VSConstants.S_OK;
var monitorSelection = Package.GetGlobalService( typeof( SVsShellMonitorSelection ) ) as IVsMonitorSelection;
var solution = Package.GetGlobalService( typeof( SVsSolution ) ) as IVsSolution;
if (monitorSelection == null || solution == null)
return false;
IVsMultiItemSelect multiItemSelect = null;
IntPtr hierarchyPtr = IntPtr.Zero;
IntPtr selectionContainerPtr = IntPtr.Zero;
try
{
hr = monitorSelection.GetCurrentSelection( out hierarchyPtr, out itemid, out multiItemSelect, out selectionContainerPtr );
if (ErrorHandler.Failed( hr ) || hierarchyPtr == IntPtr.Zero || itemid == VSConstants.VSITEMID_NIL)
return false;
// multiple items are selected
if (multiItemSelect != null)
return false;
// there is a hierarchy root node selected, thus it is not a single item inside a project
if (itemid == VSConstants.VSITEMID_ROOT)
return false;
hierarchy = Marshal.GetObjectForIUnknown( hierarchyPtr ) as IVsHierarchy;
if (hierarchy == null)
return false;
Guid guidProjectID = Guid.Empty;
if (ErrorHandler.Failed( solution.GetGuidOfProject( hierarchy, out guidProjectID ) ))
return false;
// if we got this far then there is a single project item selected
return true;
}
finally
{
if (selectionContainerPtr != IntPtr.Zero)
Marshal.Release( selectionContainerPtr );
if (hierarchyPtr != IntPtr.Zero)
Marshal.Release( hierarchyPtr );
}
}
IVsHierarchy hierarchy = null;
uint itemid = VSConstants.VSITEMID_NIL;
if (!IsSingleProjectItemSelection(out hierarchy, out itemid))
return;
string itemFullPath = null;
((IVsProject)hierarchy).GetMkDocument(itemid, out itemFullPath);
if (itemFullPath.EndsWith(".cs"))
Folks,
I'm doing a post on a web page with emoji / emoticon. But after posted the site does not display the emoticon. Must you use a different Encoding? If so how can I do?
Example have this emoji 👐💓⛪🌇 the site only shows me that ⛪ Other special characters appear.
if (currentElement.GetAttribute("type") == "submit")
if (currentElement.Name == "view_post")
{
string postagem = txtPublicacao.Text;
HtmlElement elea = webBrowser1.Document.GetElementById("u_0_0");
if (elea != null)
elea.SetAttribute("value", postagem);
currentElement.InvokeMember("click");
}
I think you can prevent yourself from experiencing some future grief by ensuring that blocks are enclosed in brackets like so:
if (currentElement.GetAttribute("type") == "submit")
{
if (currentElement.Name == "view_post")
{
string postagem = txtPublicacao.Text;
HtmlElement elea = webBrowser1.Document.GetElementById("u_0_0");
// if condition and response either on one line:
if (elea != null) elea.SetAttribute("value", postagem);
// ...or use "{}" in preparation for possible future additions to the reponse to the if condition
if (elea != null)
{
elea.SetAttribute("value", postagem);
}
currentElement.InvokeMember("click");
}
}
Or better yet, since you have two consecutive "ifs" before code is executed, combine them like so:
if ((currentElement.GetAttribute("type") == "submit") &&
(currentElement.Name == "view_post"))
{
string postagem = txtPublicacao.Text;
HtmlElement elea = webBrowser1.Document.GetElementById("u_0_0");
if (elea != null) elea.SetAttribute("value", postagem);
currentElement.InvokeMember("click");
}
Asked this on the forums as well, but no luck as of yet. What I need to do is set the HTML content of each content block on a given page. It seems that I can set the html value okay, but saving it does not update the actual page.
I'm wondering if it's because there needs to be some sort of save call on the control. There doesn't seem to be any methods available for such an action.
foreach (var c in duplicated.Page.Controls)
{
// go through the properties, se the ID to grab the right text
foreach (var p in c.Properties)
{
if (p.Name == "ID")
{
var content = pageContent.Where(content_pair => content_pair.Key == p.Value).SingleOrDefault();
var control = pageManager.LoadControl(c);
if (control is ContentBlock)
{
var contentBlock = pageManager.LoadControl(c) as ContentBlock;
contentBlock.Html = content.Value;
}
}
}
}
pageManager.SaveChanges(); */
WorkflowManager.MessageWorkflow(duplicated.Id, typeof(PageNode), null, "Publish", false, bag);
The following code may help you achieve what you need.
It will first get the page by its title (I am looking for a page by the title "duplicated" as it's implied by your code).
It generates a new draft of the current page, then go over its controls.
Controls which are detected as content blocks are then iterated in a foreach loop.
As written in the comment inside the foreach loop, you may detect controls by their explicit ID (by the property named "ID") or by their related shared content block (by the property named "SharedContentID") or any other condition (or ignore this condition altogether, which would result in updating all the controls n the page.
Once we have a control to update at hand, you can set its new value depending on the localization settings of your project.
After that the draft is saved and published and optionally a new version is created for it.
PageManager pageManager = PageManager.GetManager();
VersionManager vmanager = VersionManager.GetManager();
PageNode duplicated = pageManager.GetPageNodes().FirstOrDefault(p => p.Title == "duplicate");
if (duplicated != null)
{
var draft = pageManager.EditPage(duplicated.Page.Id, true);
string contentBlockTypeName = typeof(ContentBlock).FullName;
PageDraftControl[] contentBlocks = draft.Controls.Where(contentBlock => contentBlock.ObjectType == contentBlockTypeName).ToArray();
foreach (PageDraftControl contentBlock in contentBlocks)
{
Guid contentBlockId = contentBlock.Id;
//User "SharedContentID" if you are looking up controls which are linked to a shared content block of a specific ID.
//If you you are trying to locate a specific control by its own ID, use the explicit "ID" property instead of "SharedCotentID"
if (contentBlock.Properties.Where(prop => prop.Name == "SharedContentID" && prop.Value.ToString() == contentItemIdstr).FirstOrDefault() != null)
{
ControlProperty htmlProperty = contentBlock.Properties.Where(prop => prop.Control.Id == contentBlockId && prop.Name == "Html").FirstOrDefault();
if (htmlProperty != null)
{
if (AppSettings.CurrentSettings.Multilingual)
{
htmlProperty.GetString("MultilingualValue").SetString(CultureInfo.CurrentUICulture, "New Value");
}
else
{
htmlProperty.Value = "New Value";
}
}
}
}
draft = pageManager.SavePageDraft(draft);
draft.ParentPage.LockedBy = Guid.Empty;
pageManager.PublishPageDraft(draft);
pageManager.DeletePageTempDrafts(draft.ParentPage);
//Use the 2 next lines to create a new version of your page, if you wish.
//Otherwise the content will be updated on the current page version.
vmanager.CreateVersion(draft, draft.ParentPage.Id, true);
vmanager.SaveChanges();
pageManager.SaveChanges();
}
I hope this code helps.
Alon.
I have a problem with images in FCK editor. when i try to upload images it gives me Connector disabled error and the images are not showing in the editor page. i am programming with visual studio 2008. please help
Have a look at the following code:
private bool CheckAuthentication()
{
// WARNING : DO NOT simply return "true". By doing so, you are allowing
// "anyone" to upload and list the files in your server. You must implement
// some kind of session validation here. Even something very simple as...
//
// return ( Session[ "IsAuthorized" ] != null && (bool)Session[ "IsAuthorized" ] == true );
//
// ... where Session[ "IsAuthorized" ] is set to "true" as soon as the
// user logs in your system.
MembershipUser m = Membership.GetUser();
if (m != null)
{
return true;
} else {
return false;
}
//return false;
}
Then update both App and Root files.