-
Categories
- ASP.NET (2)
- C# (4)
- Development (1)
- Kentico CMS (1)
- LINQ (1)
- SharePoint 2010 (7)
- Tools (1)
Dev Links
Author Archives: Samuel
How To: Communication between UserControls
Problem : Allow one UserControl(DepartmentSelectorControl) to communicate /pass a value to another UserControl which will in turn
using System;
using System.Linq;
using System.Web.UI.WebControls;
public partial class Controls_DepartmentSelectorControl : System.Web.UI.UserControl
{
private string selecteddepartment = string.Empty;
public string SelectedDepartment
{
get { return selecteddepartment; }
set
{
selecteddepartment = value;
selecteddepartment = uxDepartments.SelectedItem.Text;
}
}
//Create eventhandler to be consumed by the host page
public event EventHandler SelectDepartment;
protected void Page_Load(object sender, EventArgs e)
{
using (var context = new AdventureWorksEntities())
{
var departments = context.Departments.Select(p => new Department
{
DepartmentID = p.DepartmentID,
GroupName = p.GroupName,
Name = p.Name,
ModifiedDate = p.ModifiedDate
});
foreach (var department in departments)
{
var dItem = new ListItem { Text = department.Name, Value = department.DepartmentID.ToString() };
uxDepartments.Items.Add(dItem);
}
}
}
protected void uxDepartments_SelectedIndexChanged(object sender, EventArgs e)
{
//Set the member variable to what the user has selected
selecteddepartment = uxDepartments.SelectedItem.Text;
if(SelectDepartment != null)
{
//Event is raised and corresponding eventhandler is called to respond to the event
SelectDepartment(this, new EventArgs());
}
}
}
Retrieving Editable Regions in Kentico
Problem : Retrieve contents of editable regions in Kentico
Kentico CMS allows you to use a custom control called CMSEditableRegion. There are times when you might need to check the contents of this region and perform some checks to implement business rules.
Solution : Check for the EditableRegion property on the Current document
Each document has a property called EditableRegions which is basically a key value pair. If an editable region is on the page then the name (in lower case) is stored as a key in Editable Regions.
if (CMSContext.CurrentDocument.DocumentContent.EditableRegions.ContainsKey("uxpagetitle"))
{
content = CMSContext.CurrentDocument.DocumentContent.EditableRegions["uxpagetitle"].ToString();
}
How to generate an iCalendar file
Problem : Generate a iCalendar file which will trigger a calendar application (eg. outlook) to open with an updated event.
The iCalendar file is a fairly common feature which most developers add to enable users to add events to their personalized calendars via a custom calendar application
Solution : Create a web handler which will create a plain text file with the ‘ics’ extension.
using System;
using System.Web;
namespace MyNamespace
{
public class iCalendar: IHttpHandler
{
public bool IsReusable
{
get
{
return true;
}
}
string DateFormat
{
get
{
return "yyyyMMddTHHmmssZ"; // 20060215T092000Z
}
}
public void ProcessRequest(HttpContext context)
{
DateTime startDate = DateTime.Now.AddDays(5);
DateTime endDate = startDate.AddMinutes(35);
string organizer = "foo@bar.com";
string location = "My House";
string summary = "My Event";
string description = "Please come to\\nMy House";
context.Response.ContentType="text/calendar";
context.Response.AddHeader("Content-disposition", "attachment; filename=appointment.ics");
context.Response.Write("BEGIN:VCALENDAR");
context.Response.Write("\nVERSION:2.0");
context.Response.Write("\nMETHOD:PUBLISH");
context.Response.Write("\nBEGIN:VEVENT");
context.Response.Write("\nORGANIZER:MAILTO:" + organizer);
context.Response.Write("\nDTSTART:" + startDate.ToUniversalTime().ToString(DateFormat));
context.Response.Write("\nDTEND:" + endDate.ToUniversalTime().ToString(DateFormat));
context.Response.Write("\nLOCATION:" + location);
context.Response.Write("\nUID:" + DateTime.Now.ToUniversalTime().ToString(DateFormat) + "@mysite.com");
context.Response.Write("\nDTSTAMP:" + DateTime.Now.ToUniversalTime().ToString(DateFormat));
context.Response.Write("\nSUMMARY:" + summary);
context.Response.Write("\nDESCRIPTION:" + description);
context.Response.Write("\nPRIORITY:5");
context.Response.Write("\nCLASS:PUBLIC");
context.Response.Write("\nEND:VEVENT");
context.Response.Write("\nEND:VCALENDAR");
context.Response.End();
}
}
}
Feature Stapling in SharePoint 2010 Part II
At this point Feature 1 is complete and we are ready to deploy to our sharepoint environment. You should have a solution explorer similar to this:
After you deploy, you can verify that everything worked by doing the following. Navigate to Site Actions -> Site Settings -> Site Collection Administration -> Site Collection Features. Search for the feature you deployed. You should find that it’s activated and working as expected.
The second thing we need to check is whether our master page was deployed or not. Navigate to http://[RootSite]/_catalogs/master/Forms/AllItems.aspx in your browser. You should find that Test.master (or whatever the name you gave) is now visible and approved in our master page list.
At this point we have feature 1 fully working. We won’t stop here because we want this master page to be applied whenever a new site collection is provisioned. So we have to create our Stapler (Feature2) which will associate Feature1 with the site definition of My sites.
Step 3: Create Stapler Feature to associate Feature1 with a site Definition
Follows the same steps above to create another Feature called Feature 2. The scope of this feature should be set to Farm level.
Next add an empty element item called Elements.
Your Solution explorer should like this now
The next task is the most important since this involves associating feature with a site definition.
We will need the GUID from Feature1 . You can find this in the manifest.
<?xml version="1.0" encoding="utf-8"?> <Elements xmlns="http://schemas.microsoft.com/sharepoint/"> <FeatureSiteTemplateAssociation TemplateName="SPSMSITEHOST#0" Id="493a82e4-f05b-4244-91df-c99ba69db085"></FeatureSiteTemplateAssociation> <FeatureSiteTemplateAssociation TemplateName="SPSPERS#0" Id="493a82e4-f05b-4244-91df-c99ba69db085"></FeatureSiteTemplateAssociation> </Elements>
Two lines of code were added to make the association between feature and site defintion. The site definition id is encapsulated in the templatename [SPSMITEHOST#0 & SPSPERS#0].
We’ve now successfully created our feature and stapler. Deploy this to your SharePoint instance to see this in action.
Retrieving the current user in SharePoint 2010 object model
This is a really simple code snippet to obtain the current user using the SharePoint object model.
using (SPWeb spweb = SPContext.Current.Web) {
SPUser oUser = spweb.CurrentUser;
string Username = oUser.LoginName;
}
SPUser represents a user in SharePoint services. A new object (oUser) is created from the spweb property, currentUser. We can now access various other properties like LoginName, Name etc.
Free SharePoint Development Tools
Four free SharePoint development tools you should consider using are:
- CAML Builder from U2U (http://www.u2u.be/Res/Tools/CamlQueryBuilder.aspx): Build and test your CAML queries and paste into your code.
- CKS (Community Kit for SharePoint, Tools Edition) (http://cksdev.codeplex.com/ ): Makes the SharePoint development cycle tolerable (almost). Version 2 was released May 2011.
- ULS Viewer (http://archive.msdn.microsoft.com/ULSViewer ) In my opinion, the best.
- SharePoint Manager (http://spm.codeplex.com/). Invaluable for browsing a SharePoint farm, viewing and changing parameters and option.
- SharePoint Diagnostic Studio (http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=20022) is a great tool to help administer and manage SharePoint.
source: nickGrattan
Using Linq to SharePoint – SPLinq
SPlinq allows you to write strongly typed queries against lists. Here are some key points to note:
- SharePoint 2010 exposes list data through a REST service that you can consume in your projects.
- The WCF data service SharePoint exposes is ListData.svc. eg http://sp2010dev/_vti_bin/listdata.svc
- You will need the ADO.NET client runtime installed on your machine
- In order to use the objects returned by listdata.svc service, we’ll need to generate entity classes for the list of objects returned by that service. You can do this by using SPMetal or adding a service reference to your project.
The image above shows listdata.svc displayed in a browser with a view of all the lists available in that site collection.
After adding a service reference , include the ff references in your project:
using System.Net; using Microsoft.SharePoint.Linq
You’re now ready to write a simple program. We want to create a webpart which will display a list of events only created by a particular user.
In the page_Load of our visual webpart we create a new data context by specifiying a URI and credentials by which we will be connecting to the list data.
protected void Page_Load(object sender, EventArgs e)
{
var builder = new StringBuilder();
var context = new POPDataContext(new Uri("http://sp2010dev/_vti_bin/listdata.svc"))
{
Credentials = CredentialCache.DefaultCredentials
};
Next we retrieve the username of the current user and strip away some default characters in the string. The query below then simple selects all events which were created by that user. We loop through all the results and assign them to a string which we display in our label.
SPUser currentUser = SPContext.Current.Web.CurrentUser; String activeDirectoryUsername = currentUser.LoginName; activeDirectoryUsername = activeDirectoryUsername.Substring(3);
var users =context.PopEvents.Where(b => b.CreatedBy.UserName.Equals(activeDirectoryUsername))
.Select(b => new { b.Title,
Username = b. CreatedBy.UserName
});
foreach (var userInformationListItem in users)
{
builder.AppendFormat("{0} posted by {1}", userInformationListItem.Title,
userInformationListItem.Username);
builder.AppendFormat("<br />");
}
uxVacationRequests.Text = builder.ToString();
}
Output:
Sharepoint: Cannot convert type ‘Microsoft.SharePoint.WebControls.ScriptLink’ to ‘System.Web.UI.IAttributeAccessor’
I recently ran into this error which working on a custom page.
Sharepoint: Cannot convert type ‘Microsoft.SharePoint.WebControls.ScriptLink’ to ‘System.Web.UI.IAttributeAccessor’
Whenever you copy a master page from one site to another in SharePoint designer, it converts certain tags to script. The solution is to cut and paste your code into a new masterpage file.
Source: http://www.hexanes.com/?p=448
Feature Stapling in SharePoint 2010 Part I
While working on an internal project recently, I was tasked to implement feature stapling which would enable us to load a custom master page to the My Site (specifically My Content) section. Before we jump into all the details I would like to define some terms just in case there are newbies (like me) who had no idea about how to approach feature stapling.
Feature Stapling:
Feature stapling is a technique used in SharePoint 2010 which allows you to associate a feature (say a custom master page feature) with a site collection or web site (My sites) without modifying the site definition. In this tutorial the custom master page will be deployed to the new site collection whenever it’s provisioned for the first time.
Feature: A SharePoint feature provides additional functionality to SharePoint. This feature can be used once deployed and activated on the SharePoint site. Technically a SharePoint feature is just an XML file (Feature.xml). In our tutorial we will create two features.
- The first feature (Feature1) will define the new master page we want to apply.
- The second feature (Feature2) will establish the relationship between feature 1 and our site definition.
Module: A module is SharePoint template which can be used to deploy files to your SharePoint environment. We’ll create a module to deploy our custom master page.
Summary: Setup project in Visual Studio Create Feature 1 (Custom master page) Create Stapler Feature to associate Feature1 with a site Definition
Step 1: Setup Project
Add a new project to your solution called ‘’MySiteFeatureStapling” and click ok.
Next, select the security level for your site to “Deploy as a farm solution” and click finish. You can choose a sandboxed solution if you so choose. They should both work.
At this point your solution explorer should look something like this.
Step 2: Create Feature 1 (Custom Master Page)
Right click the Features folder and click on “Add Feature”
You will then be provided with the design interface of the feature designer. You can choose to rename your feature to something more meaning if you wish. You should at this point set the scope to “Site” .
Add Module
Next, you need to right click on your project in solution explorer to add a new module. This module will be used to deploy the custom master page. Delete the sample.txt file which is provided by default and add the custom master page (in this case Test.master) you would like to deploy. Update the Elements.xml file to look like this.
<?xml version="1.0" encoding="utf-8"?> <Elements xmlns="http://schemas.microsoft.com/sharepoint/"> <Module Name="Module1" List="116" Url="_catalogs/masterpage"> <File Path="Module1\Test.master" Url="Test.master" /> </Elements> </module>
The URL attribute in the module node specifies where the file will be pushed on your SharePoint server. It’s important to note that you can add any type of file you want to the module. Add Feature Event Receiver : The Next step is to right click feature1 and add an event receiver. A new file Feature1.EventReceiver.cs is created with a bunch of commented out code. Uncomment the methods FeatureActivated & FeatureDeactiving. Modify your code to look like this
[Guid("f5034122-c5af-4327-ad77-b52b1a107667")] public class Feature1EventReceiver : SPFeatureReceiver { // Uncomment the method below to handle the event raised after a feature has been activated. public override void FeatureActivated(SPFeatureReceiverProperties properties) { SPSite site = properties.Feature.Parent as SPSite; SPWeb curWeb = site.RootWeb; //create full master url Uri masterURI = new Uri(curWeb.Url + "/_catalogs/masterpage/Test.master"); //Master page used by all forms and pages on the site that are not published curWeb.MasterUrl = masterURI.AbsolutePath; //master page used by all publishing pages on the site curWeb.CustomMasterUrl = masterURI.AbsolutePath; curWeb.Update(); } // Uncomment the method below to handle the event raised before a feature is deactivated. public override void FeatureDeactivating(SPFeatureReceiverProperties properties) { SPWeb curWeb = null; SPSite curSite = properties.Feature.Parent as SPSite; if (curSite != null) { curWeb = curSite.RootWeb; } if (curWeb != null) { //Create full master url Uri masterUri = new Uri(curWeb.Url + "/_catalogs/masterpage/v4.master"); //master page used by all forms and pages on the site that are not publishing pages curWeb.MasterUrl = masterUri.AbsolutePath; //master page used by all publishing pages on the site curWeb.CustomMasterUrl = masterUri.AbsolutePath; curWeb.Update(); } }
Click below for the next part of this tutorial
Feature Stapling in SharePoint 2010 Part II
Site collection codes in Sharepoint 2010
SharePoint 2010 ships with many in built templates. As a developer, you might come across the need to reference these values somewhere down the line. I’ve provided a list of the codes below. These are also available here .Please note that the Global template value can also be used as just “GLOBAL” instead of “GLOBAL#0″.
Example:
<?xml version="1.0" encoding="utf-8"?> <Elements xmlns="http://schemas.microsoft.com/sharepoint/"> <FeatureSiteTemplateAssociation TemplateName="GLOBAL" Id="944d6e47-db98-431b-a0b4-fcd08ed6bd40"></FeatureSiteTemplateAssociation> </Elements>
Parameter value |
Description |
| GLOBAL#0 | Global template |
| STS#0 | Team Site |
| STS#1 | Blank Site |
| STS#2 | Document Workspace |
| MPS#0 | Basic Meeting Workspace |
| MPS#1 | Blank Meeting Workspace |
| MPS#2 | Decision Meeting Workspace |
| MPS#3 | Social Meeting Workspace |
| MPS#4 | Multipage Meeting Workspace |
| CENTRALADMIN#0 | Central Admin Site |
| WIKI#0 | Wiki Site |
| BLOG#0 | Blog |
| SGS#0 | Group Work Site |
| TENANTADMIN#0 | Tenant Admin Site |
| ACCSRV#0 | Access Services Site |
| ACCSRV#1 | Assets Web Database |
| ACCSRV#3 | Charitable Contributions Web Database |
| ACCSRV#4 | Contacts Web Database |
| ACCSRV#6 | Issues Web Database |
| ACCSRV#5 | Projects Web Database |
| BDR#0 | Document Center |
| OFFILE#0 | (obsolete) Records Center |
| OFFILE#1 | Records Center |
| OSRV#0 | Shared Services Administration Site |
| PPSMASite#0 | PerformancePoint |
| BICenterSite#0 | Business Intelligence Center |
| PWA#0 | Project Web App Site |
| PWS#0 | Microsoft Project Site |
| SPS#0 | SharePoint Portal Server Site |
| SPSPERS#0 | SharePoint Portal Server Personal Space |
| SPSMSITE#0 | Personalization Site |
| SPSTOC#0 | Contents area Template |
| SPSTOPIC#0 | Topic area template |
| SPSNEWS#0 | News Site |
| CMSPUBLISHING#0 | Publishing Site |
| BLANKINTERNET#0 | Publishing Site |
| BLANKINTERNET#1 | Press Releases Site |
| BLANKINTERNET#2 | Publishing Site with Workflow |
| SPSNHOME#0 | News Site |
| SPSSITES#0 | Site Directory |
| SPSCOMMU#0 | Community area template |
| SPSREPORTCENTER#0 | Report Center |
| SPSPORTAL#0 | Collaboration Portal |
| SRCHCEN#0 | Enterprise Search Center |
| PROFILES#0 | Profiles |
| BLANKINTERNETCONT | Publishing Portal |
| SPSMSITEHOST#0 | My Site Host |
| ENTERWIKI#0 | Enterprise Wiki |
| SRCHCENTERLITE#0 | Basic Search Center |
| SRCHCENTERLITE#1 | Basic Search Center |
| SRCHCENTERFAST#0 | FAST Search Center |
| visprus#0 | Visio Process Repository |












