Joel's SharePoint Architect Blog

SharePoint 2013 Training, Architecture, Administration and Development

Subscribe Subscribe  View Joel Jeffery's profile on LinkedIn
joelblogs.co.uk | joelj.co.uk | joeljeffery.co.uk | jfdiphoenix.co.uk

Posts Tagged ‘SharePoint Developer’

I was recently asked how to remove the Editor Parts (Appearance, Layout, Advanced, etc) from custom Web Parts.

One strategy is to implement your own Editor Part and mark the built-in ones as not Visible.

Firstly, we need to create our Editor Part class:

class MyEditorPart : EditorPart
{
    protected override void CreateChildControls()
    {
// this line hides the default EditorParts Parent.Controls[2].Visible = false; base.CreateChildControls(); } public override bool ApplyChanges() { // do stuff here return true; } public override void SyncChanges() { // do stuff here } }

And here’s how we invoke our Editor Part from our Web Part:

public class MyWebPart : WebPart
{
    public override EditorPartCollection CreateEditorParts()
    {
        ArrayList aryParts = new ArrayList();

        MyEditorPart myEditor = new MyEditorPart();
        myEditor.ID = this.ID + "_myEditorPart";
        aryParts.Add(myEditor);

        return new EditorPartCollection(aryParts);
    }
    // do more stuff here...
}

Hopefully, when you edit the Web Part it should look something like this:

The next step would be to extend CreateChildControls(), ApplyChanges() and SyncChanges() to get and set any properties you’d like to allow users to edit.

Technorati Tags: Development, SharePoint, SharePoint 2010 Training, SharePoint Developer, SharePoint Development, WebParts

SharePoint 2010 in Visual Studio 2010 has made creating Windows Workflow Foundation (WF) workflows an awful lot easier. There are still one or two areas that can be confusing to new developers

One such region of confusion surrounds the Initiation Form – the form displayed whenever a user launches your workflow, that you can use to prompt for more information required to run your workflow. Similar uncertainty surrounds the Association Form – one that is displayed whenever a list administrator attaches your workflow to their list.

Thanks to the tooling in Visual Studio, it’s now easy to add either of these forms. Right-clicking your Workflow item in Solution Explorer and choosing “Add-> New Item” will give you:

Adding a New SharePoint Item in Visual Studio 2010

Selecting either Initiation Form or Association Form will add the appropriate artefacts to your code and also configures the Element manifest of the Workflow accordingly:

Element Manifest Changes to view Initiation Forms

Let’s say we wanted to ask the user a series of extra questions when they launch our workflow, such as their manager’s First Name, Last Name and Email Address, such that we can have access to that data within our running workflow later on.

We can now edit our new Initiation Form as an aspx page in Visual Studio. Let’s add some text boxes to capture the extra information:

image

The next question is often “how do we get this information to the workflow?” Inside the workflow itself is a SPWorkflowActivationProperties object which exposes two strings: InitiationData and AssociationData, which is respectively the data captured from the user during launch and association phases of the workflow.

The code behind for the Initiation Form has a string method called GetInitiationData(). Whatever string you return here is then available from inside your workflow using workflowProperties.InitiationData. It’s the same principle with Association Forms, GetAssociationData and AssociationData properties.

Clearly, we could go low-rent here and return a semi-colon delimited string or something naff of that ilk.

Alternatively you could store your properties temporarily in a class and then serialise that class to a string and return that. Then later in your workflow you could deserialise that back to an instance of your object.

You could put a lot of effort into this to get it really efficient, but the general principle is why not create a utility class to hold Serialise and Deserialise methods?

I’ve implemented the following candidate code using Generics to show how powerful the technique is:

public static string Serialise<T>(T item)
{
    XmlSerializer ser = new XmlSerializer(item.GetType());
    TextWriter sw = new StringWriter();
    ser.Serialize(sw, item);
    return sw.ToString();
}

public static T Deserialise<T>(string xml) where T : new()
{
    T returnObject = new T();
    XmlSerializer ser = new XmlSerializer(returnObject.GetType());
    XmlTextReader xtr = new XmlTextReader(new StringReader(xml));
    return (T)ser.Deserialize(xtr);
}

So, given a class, for example, to hold contact information:

public class Contact
{
    public string FirstName;
    public string LastName;
    public string Email;
}

You could put the following in your code behind for the Initiation Form:

// This method is called when the user clicks the button to start the workflow.
private string GetInitiationData()
{
    contact.FirstName = firstName.Text;
    contact.LastName = lastName.Text;
    contact.Email = email.Text;
    return Serialise<Contact>(contact);
}

Then in the code beside for your workflow you can get at the data again like this:

private void codeActivity1_ExecuteCode(object sender, EventArgs e)
{
    Contact contact = Deserialise<Contact>(workflowProperties.InitiationData);
    historyDescription = string.Format("Received Contact information: {0} {1} {2}",
        contact.FirstName, contact.LastName, contact.Email);
}

Hopefully this code will save you some searching and typing.

Technorati Tags: SharePoint, SharePoint 2010, SharePoint 2010 Training, SharePoint Developer

If you’re creating or editing a JavaScript file in Visual Studio and you would like some help creating Client Object Model code, you’re not alone.

It’s a little bit cryptic, but we can tell IntelliSense to include any JavaScript libraries you have on your development machine.

Simply place the following two lines at the top of your source code (watch out for line breaks!):

/// <reference path="C:\\Program Files\\Common Files\\Microsoft Shared\\Web Server Extensions\\14\\TEMPLATE\\LAYOUTS\\MicrosoftAjax.js" />
/// <reference path="C:\\Program Files\\Common Files\\Microsoft Shared\\Web Server Extensions\\14\\TEMPLATE\\LAYOUTS\\SP.debug.js" />
/// <reference path="C:\\Program Files\\Common Files\\Microsoft Shared\\Web Server Extensions\\14\\TEMPLATE\\LAYOUTS\\SP.Core.debug.js" />

Then, you can get IntelliSense when you need it the most!

Enabling IntelliSense for the JavaScript Client Object Model in SharePoint 2010

Full article on MSDN available here.

Enjoy!

Technorati Tags: Development, SharePoint 2010, SharePoint 2010 Training, SharePoint Developer, SharePoint Training

Embedding Resources in Sandbox Solutions

Take One – On Premise SharePoint 2010

When you’re deploying User Code / Sandbox Solutions to the SharePoint 2010 Solution Gallery you may want to include things you’d usually distribute in files under the 14 hive.

One of the chief restrictions in the Sandbox is that you cannot access the file system. One approach is to embed the file as a resource.

To accomplish this, select the file in Visual Studio’s Solution Explorer that you’d like to embed:

Selecting an Embedded Resource

Next, you’ll need a method to retrieve the embedded resource from the compiled assembly (and yes, this works in the Sandbox Smile)

/// <summary>

/// Gets the embedded resource as string.

/// </summary>

/// <param name="filename">The filename.</param>

/// <returns></returns>

private string getEmbeddedResourceAsString(string filename)

{

    string resource = "";

    using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(filename))

        using (StreamReader reader = new StreamReader(stream))

            resource = reader.ReadToEnd();

    return resource;

}

The only slightly tricky part is working out the “filename” of the resource inside your assembly. It’s usually in the form: ProjectName.FolderName.Filename.Ext

In my example, I used the following:

string javaScript = getEmbeddedResourceAsString("GoogleMapsWebPart.GoogleMap.GoogleMap.js");

 

Now I can retrieve the contents of the embedded file and use it without needing to deploy any extra resources.

Take Two – SharePoint Online (Office 365) and On Premise SharePoint 2010

The above method fails in the cloud; Office 365 does not like Assembly.GetExecutingAssembly(), so we need an alternative.

First, you need to add a Resource.resx file. You can do this by right-clicking your Visual Studio project node and going to Properties. Then select the Resources tab, and Add Existing File:

Visual Studio Resources: Add Existing File

From there, navigate to your chosen file you’d like to embed.

You need to change your code to use syntax like: <ProjectName>.Properties.Resources.<ResourceName>.

My example looks like this:

string javaScript = GoogleMapsWebPart.Properties.Resources.GoogleMap;

You can now access your resources directly from your code without any Office 365 Sandbox errors.

Technorati Tags: SharePoint, SharePoint 2010, SharePoint Developer

I’m often asked for a list of the IDs of the most common Base Types, List Definitions and Content Types. Especially useful if you’re writing CAML definitions of Lists, List Instances, or Content Types. Here are the lists I’ve gleaned from MSDN.

Base Types

These Base Types come from the SPBaseType enumeration.

Base Type ID
Custom List 0
Document Library 1
Not used 2
Obsolete. Use 0 for discussion boards. 3
Surveys 4
Issues List 5

 

List Definitions

These List Definitions come from the SPListTemplateType enumeration.

Enumeration Name Description ID
InvalidType Not used -1
NoListTemplate unspecified list type 0
GenericList Custom list 100
DocumentLibrary Document library 101
Survey Survey 102
Links Links 103
Announcements Announcements 104
Contacts Contacts 105
Events Calendar 106
Tasks Tasks 107
DiscussionBoard Discussion board 108
PictureLibrary Picture library 109
DataSources Data sources for a site 110
WebTemplateCatalog Site template gallery 111
UserInformation User Information 112
WebPartCatalog Web Part gallery 113
ListTemplateCatalog List Template gallery 114
XMLForm XML Form library 115
MasterPageCatalog Master Page gallery 116
NoCodeWorkflows No Code Workflows 117
WorkflowProcess Custom Workflow Process 118
WebPageLibrary Wiki Page Library 119
CustomGrid Custom grid for a list 120
SolutionCatalog Solutions 121
NoCodePublic No Code Public Workflow 122
ThemeCatalog Themes 123
DataConnectionLibrary Data connection library for sharing information about external data connections 130
WorkflowHistory Workflow History 140
GanttTasks Project Tasks 150
Meetings Meeting Series (Meeting) 200
Agenda Agenda (Meeting) 201
MeetingUser Attendees (Meeting) 202
Decision Decisions (Meeting) 204
MeetingObjective Objectives (Meeting) 207
TextBox Text Box (Meeting) 210
ThingsToBring Things To Bring (Meeting) 211
HomePageLibrary Workspace Pages (Meeting) 212
Posts Posts (Blog) 301
Comments Comments (Blog) 302
Categories Categories (Blog) 303
Facility Facility 402
Whereabouts Whereabouts 403
CallTrack Call Track 404
Circulation Circulation 405
Timecard Timecard 420
Holidays Holidays 421
IMEDic IME (Input Method Editor) Dictionary 499
ExternalList External 600
IssueTracking Issue tracking 1100
AdminTasks Administrator Tasks 1200
HealthRules Health Rules 1220
HealthReports Health Reports 1221

 

Content Types

These content types come from the Content Type ID list.

Content Type ID
System 0x
Item 0×01
Document 0×0101
Event 0×0102
Issue 0×0103
Announcement 0×0104
Link 0×0105
Contact 0×0106
Message 0×0107
Task 0×0108
Workflow History 0×0109
Post 0×0110
Comment 0×0111
East Asia Contact 0×0116
Folder 0×0120

Technorati Tags: SharePoint, SharePoint 2010, SharePoint Developer