Accessing Page datafolder data from C# - user-controls

I defined a Page datafolder in the Data view and created data for one of my pages.
How can I access this data from an ASP.NET usercontrol placed on the page?

Here is a small code sample for getting page folder data for a given page folder type. Change the type Martin.MyPageFolder to your type and it should work just fine.
using (DataConnection connection = new DataConnection())
{
var pageFolderData =
from d in connection.Get<Martin.MyPageFolder>()
where d.PageId == SitemapNavigator.CurrentPageId
select d;
foreach (var item in pageFolderData)
{
// Use the item here as you need
}
}

Related

SharePoint JS Link file reference globally

I would like to ask that I have one document library with more than 20 views. I have implemented one JS link file to render required changes in the view.
My query is that is there any way to declare this JS link file globally for all the Document library views instead of adding reference in each view.
Thanks in advance
You could Update JS Link of list views Using PowerShell. Put all view links into an array and then iterating the links.
Sample script:
$webpartPages = "/Lists/Tickets/AllItems.aspx","/document%20li/Forms/1.aspx","/document%20li/Forms/2.aspx","/document%20li/Forms/AllItems.aspx";
$web = Get-SPWeb http://url;
foreach($webpartPage in $webpartPages ){
$file = $web.GetFile($webPartPage)
$file.CheckOut()
$webPartManager = $web.GetLimitedWebPartManager($webPartPage, [System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)
$webpart = $webPartManager.WebParts[0]
$webpart.JSLink = "~sitecollection/SiteAssets/test12.js"#If you have placed your JS inside SiteAssets library of some CHILD site, you should use ~site/SiteAssets/... url.If you have placed your JS inside SiteAssets library of root site of site collection, you should use ~sitecollection/SiteAssets/... url.
$webPartManager.SaveChanges($webpart)
$file.CheckIn("Awesomeness has been delivered")
}
Or you could upload the js file to the SharePoint library, then modify the master page in sharepoint designer, add <script type = "text/javascript" src = "http://url/SiteAssets/test12.js"> </script> to import the js file ,
You need to pay attention to determine whether current view is target view based on the URL in the js file, otherwise it may affect other pages.
Sample script :
if (window.location.href.toLowerCase().indexOf('document%20li') > 0) {
SPClientTemplates.TemplateManager.RegisterTemplateOverrides({
OnPostRender: function (ctx) {
var rows = ctx.ListData.Row;
for (var i = 0; i < rows.length; i++) {
var isApproved = rows[i]["testColumn"] == "Arvind Kushwaha1575353984864";
if (isApproved) {
var rowElementId = GenerateIIDForListItem(ctx, rows[i]);
var tr = document.getElementById(rowElementId);
tr.style.backgroundColor = "#ada";
}
}
}
});
}

Load data in custom form by using Kentico 9

I searched the whole web and I couldn't found any good topic which expose the proper way to do it.
I have a very simple web which I developed using Kentico 9 CMS. This web only contains two subpages and a header to navigate between those.
The "Home" subpage contains a custom form which remains connected to a SQL table which is populated every time you press submit with certain data.
On the other hand, the other page, shows the stored data by using a custom web part which connects to the DB by using BizFormItemProvider and this object is used as a layer to binding the data in a control.
Now is my point. If you see, there is a button to "Edit" a certain row and my intention is to Redirect to "Home" (which contains the form) and sending via QueryString the ID of the row attempted to edit.
I was unable to understand how can you re-fill the form with its data using an ID.
Maybe because I never worked with a CMS before, I'm looking the development such as pure ASP.NET and it could not be the correct one.
Custom
Given that your solution uses a custom form for entering the data, as well as a custom web part for listing the stored data, you will need to use a custom solution to handle the editing of data, as well.
In the custom webpart on the Home page, in a load event, you can retrieve the form data and set the values on the form controls.
protected void Page_Load(object sender, EventArgs e)
{
// Ensure that the form is not being posted back,
// to prevent entered data from being overwritten
if(!IsPostBack)
{
// Get the form item ID from the query string
var personId = QueryHelper.GetInteger("personId", 0);
if(personId > 0)
{
// Get the biz form item, and set form control values
var bizFormItem = BizFormItemProvider.GetItem(personId, "customFormClassName");
txtFirstName.Text = bizFormItem.GetStringValue("FirstName", string.Empty);
}
}
}
Similarly, when Submit is clicked, you can update the existing form item with the new data
protected void btnSubmit_OnClick(object sender, EventArgs e)
{
// Get the form item ID from the query string
var personId = QueryHelper.GetInteger("personId", 0);
if(personId > 0)
{
// Retrieve the existing biz form item,
// and update it from the form control values
var bizFormItem = BizFormItemProvider.GetItem(personId, "customFormClassName");
bizFormItem.SetValue("FirstName", txtFirstName.Text);
bizFormItem.Update();
}
else
{
// Your code for inserting a new form item...
}
}
The Kentico way
You should really consider using the Kentico form engine for accomplishing this task. Instead of using a custom form for entering the data, use the built-in On-line form webpart.
The benefits are numerous, such as:
Ability to set the form layout through the CMS, and use alternative layouts
Automatic confirmation email to the submitter of the form, as well as notification emails to the administrators
To accomplish your task, you can customise the On-line form webpart to support loading of existing data.
In the bizform.ascx.cs file, add code to the SetupControl method:
protected void SetupControl()
{
if (StopProcessing)
{
// Existing code...
}
else
{
// Existing code...
// Get the form item ID from the query string
var personId = QueryHelper.GetInteger("personId", 0);
if(personId > 0)
{
// Get the biz form item, and set form control values
var bizFormItem = BizFormItemProvider.GetItem(personId, "customFormClassName");
if(bizFormItem != null)
{
// Set the item ID
viewBiz.ItemID = bizFormItem.ItemID;
}
}
}
}
This will automagically switch the form to Edit mode, instead of Insert mode, as soon as you set the ItemID property. Clicking the Submit button will save changes on the existing form item.
You will not need to worry about validation in your code, and inserting data will still work.
Is this a contact form that you are using Kenticos built in form application for, or is it a custom form? If it is a custom form you can create a transformation with a link that will contain the ID. If it is a biz form, you can still create a transformation in Page Types (create a new page type and select "The page type is only a container without custom fields"), then write a custom query to get the biz form data, and use a repeater to display the data with that transformation.

Getting document attachments using Kentico API

I created book store site on Kentico i used only their adminstration and display the data from my website using Kentico API's but am strugled in getting attachment files related to specific document i've got document data with no problem using
TreeProvider tree = new TreeProvider(MembershipContext.AuthenticatedUser);
var documents = tree.SelectNodes("CMS.Product");
need also to get related attachment files like book PDFs.. i've tried to use
DocumentAttachment
AttachmentInfo
AttachmentInfoProvider
classes but i couldn't get the data .. I would appreciate if any one help me in that.
Actually am searching about something like GetAttachment().Where("AttachmentFile","Ënglish File")
You can filter the returned attachments based on their values in columns (CMS_Attachment table) by using a code like this:
var attachment = AttachmentInfoProvider.GetAttachments()
.WhereEquals("AttachmentName", "Englishfile")
.And()
.WhereEquals("AttachmentExtension", "jpg")
.TopN(1)
.FirstOrDefault();
if (attachment != null)
{
// attachment was found
}
This code will get one .jpg file where attachment name equals to "EnglishFile"
Solved after using something like
var Attachment = AttachmentInfoProvider.GetAttachments(226, true);
This is from Kentico documentation. This example shows how to add an attachment and modify its metadata. You can ignore that part.You will have to make it generic to work for all examples.
Kentico 9 API Links
// Creates a new instance of the Tree provider
TreeProvider tree = new TreeProvider(MembershipContext.AuthenticatedUser);
// Gets a page
TreeNode page = tree.SelectSingleNode(SiteContext.CurrentSiteName, "/Articles", "en-us");
if (page != null)
{
// Gets an attachment by file name
AttachmentInfo attachment = DocumentHelper.GetAttachment(page, "file.png", tree);
// Edits the attachment's metadata (name, title and description)
attachment.AttachmentName += " - modified";
attachment.AttachmentTitle = "Attachment title";
attachment.AttachmentDescription = "Attachment description.";
// Ensures that the attachment can be updated without supplying its binary data
attachment.AllowPartialUpdate = true;
// Saves the modified attachment into the database
AttachmentInfoProvider.SetAttachmentInfo(attachment);
}

How to get a reference to custom settings in webpart from a page within webpart?

I created a webpart, then I created a second .cs page that will render custom html. It basically just a simple page to show an image. However in the second .cs page, I need to access custom settings in the Web Part. How can I access custom tool pane settings in the main web part when the link to the secondary page is clicked?
The second page is generated from VS 2010 and is in the layouts folder, looks like:
public partial class GetFile : LayoutsPageBase
{
I am thinking I have to inherit something from the web part in order to do this, but really not sure how?
You can access the Web part properties using the SPLimitedWebPartManager class by reading the web part collection and their properties on the page as shown below,
var web = SPContext.Current.Web;
var currentPageURL = "//URL of the page on which the Web part is present";
var page = web.GetFile(currentPageURL);
using (SPLimitedWebPartManager webPartManager = page.GetLimitedWebPartManager(PersonalizationScope.Shared))
{
try
{
var webPartList = from System.Web.UI.WebControls.WebParts.WebPart webPart in webPartManager.WebParts select webPart;
foreach (System.Web.UI.WebControls.WebParts.WebPart webPart in webPartList.ToList())
{
if (webPart.Title.ToLower() == "//Name of the web part for which you want to read the properties")
{
PropertyInfo[] wptProperties = webPart.GetType().GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in wptProperties)
{
if (property.Name == "//Name of the web property which you want to get")
{
// Following code updates the web part property, you can also read it
property.SetValue(webPart, "value to be set", null);
webPartManager.SaveChanges(webPart);
break;
}
}
}
}
Response.Redirect(currentPageURL);
}
finally
{
webPartManager.Web.Dispose();
}
}

How to programmatically add target lists to the what's new web part in Sharepoint (or how to handle undocumented namespaces)

From code I've automatically created a lot of similar sites (SPWeb) in my site collection from a site template (in Sharepoint Foundation). Every site has a home page on which I've added the "what's new" web part (found under "Social collaboration").
Even though the web part has several "target lists" (I'd have called it "source lists") added to it on the template site, this connection is lost on the sites created from the template. So I need to programmatically find all these web parts and add the target lists to them. Looping the web parts is not an issue - I've done that before - but I can't seem to find a word on the net on how to go about modifying this particular web part. All I have is a brief intellisense.
I've found out that it recides in the
Microsoft.SharePoint.Applications.GroupBoard.WebPartPages
namespace, but on the lists provided on MSDN this is one of very few namespaces that doesn't have a link to a reference documentation.
Does anyone have any experience of modifying this web part from code? If not, how would you go about to find out? I can't seem to figure out a method for this..
Here is how I did it. It worked really well. I had a feature that created several list instances and provisioned the What's New web part. In the Feature Receiver, I looped through all of the list instances, indexed the Modified field, and then added the list to the web part:
private void ConfigureLists(SPWeb web, SPFeatureReceiverProperties properties)
{
List<Guid> ids = new List<Guid>();
SPElementDefinitionCollection elements =
properties.Feature.Definition.GetElementDefinitions(new CultureInfo((int)web.Language, false));
foreach (SPElementDefinition element in elements)
{
if ("ListInstance" == element.ElementType)
{
XmlNode node = element.XmlDefinition;
SPList list = web.Lists[node.Attributes["Title"].Value];
SPField field = list.Fields[SPBuiltInFieldId.Modified];
if (!field.Indexed)
{
field.Indexed = true;
field.Update();
}
ids.Add(list.ID);
}
}
string targetConfig = string.Empty;
foreach (Guid id in ids)
{
targetConfig += string.Format("'{0}',''\n", id);
}
SPFile file = web.GetFile("Pages/default.aspx");
file.CheckOut();
using (SPLimitedWebPartManager manager = file.GetLimitedWebPartManager(PersonalizationScope.Shared))
{
WhatsNewWebPart webpart = null;
foreach (System.Web.UI.WebControls.WebParts.WebPart eachWebPart in manager.WebParts)
{
webpart = eachWebPart as WhatsNewWebPart;
if (null != webpart)
{
break;
}
}
if (null != webpart)
{
webpart.TargetConfig = targetConfig;
manager.SaveChanges(webpart);
}
}
file.CheckIn("ConfigureWebParts");
file.Publish("ConfigureWebParts");
file.Approve("ConfigureWebParts");
}
If you are unsure about the property, export the web part from the browser, then open the .webpart/.dwp file with a text editor. Somewhere in the xml will be a reference to the source list.
*.webparts are usually easier to modify, just set the property.
*.dwps are harder because you sometimes have to get the property (eg ViewXML), then load it into an XmlDocument, then replace the property, and write the xml document string value back to ViewXML.

Resources