AWG Blogs

Monday, January 30, 2012

"There is no Web named..." error

When setting up your web reference in Visual Studio 2008, you must enter http://server/sites/mysitecollection/mysubsite/_vti_bin/Lists.asmx?WSDL including the "WSDL" at the end! Or else, you will get this error in your inner exception, when attempting to access a list, using the GetList(listguidstring) method.

Sunday, January 29, 2012

Sharepoint PowerShell Shortcuts

Command to output sorted site columns:
PS C:\WINDOWS\system32\WindowsPowerShell\v1.0> [void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
PS C:\WINDOWS\system32\WindowsPowerShell\v1.0> set-variable -option constant -name url -value "http://servername/sites/teamsite/"
PS C:\WINDOWS\system32\WindowsPowerShell\v1.0> $site = new-object Microsoft.SharePoint.SPSite($url)
PS C:\WINDOWS\system32\WindowsPowerShell\v1.0> $site.rootweb.Fields | foreach { $fieldValues = @{ "Display Name" = $_.Title; "Internal Name" = $_.InternalName; "Value" = $site.rootweb.AvailableFields.GetFieldByInternalName($_.InternalName) }; New-Object PSObject -Property $fieldValues | Select @("Display Name","Internal Name","Value") } | Sort-Object -Property "Internal Name" | Out-GridView

refs:
http://get-spscripts.com/2010/09/get-all-column-values-from-sharepoint.html

see also: http://blogs.flexnetconsult.co.uk/colinbyrne/2008/02/26/PowerShellSharePointAddAListItem.aspx

Thursday, January 26, 2012

CQWP Bug

[MOSS 2007] Got the following error when I selected "Show items from the following list" and browsed to a doc lib whose display name contained a forward slash (/):
Cannot save the property settings for this Web Part. The list name is not valid. The list name should refer to a list within the specified site..."

So to workaround the inability of this SP component to recognize lists with forward slashes in them, I decided to try to filter by list ID under Additional Filters. No go again. I entered the list's QUID and no data was returned. This appears to be a bug as well.

So I settled for a Data Form Web Part hooked up to an XML Web Service configured in the Data Source Library: Port set to ListsSoap12, Operation: GetListItems; listName=GUID (including curly brackets). Had to tinker with the XSLT to get the display somewhat correct, e.g. to get the doc image to show, use <img src="/_layouts/images/{ddwrt:MapToIcon('',string(@ows_DocIcon))}"/>

Wednesday, January 18, 2012

Adapting the schema.xml

I wanted to add a new field to the base item content type -- i.e. content type ID 0x01. I also wanted to change the display name of title. This is what worked for my schema.xml.

Copy the Schema.xml from FEATURES\CustomList\CustList to my Feature folder named after the Name attribute of the ListTemplate element.

Comment out both ContentTypeRef elements.

Create a ContentType element that likes like:
<ContentType
ID="0x0100DECA7022CD234bb1BE7E9BCFF593552F"
Name="Item"
Group="List Content Types"
Description="Create a new list item.">
<FieldRefs>
<FieldRef ID="{fa564e0f-0c70-4ab9-b863-0177e6ddd247}"
Name="Title"
Required="TRUE"
DisplayName="My Title"
/>
<FieldRef ID="{AA242460-9794-4d45-A726-938D1B8B7D72}"
Name="My Added field"
Required="FALSE"
/>

</FieldRefs>


</ContentType>

NOTE the ContentType ID structure: follows the GUID method from MSDN http://msdn.microsoft.com/en-us/library/ie/aa543822.aspx, MAKE sure to remove any hyphens!!!

Add all modified fields to the Fields element, including Title, LinkFilenameNoMenu, and LinkTitle. You can get samples from a schema.xml that you copy from a list in SharePoint Manager.

Adjust View BaseViewID="1" as needed.

Wednesday, January 11, 2012

SharePoint Workflows on 64bit server

This is a quick start on how to get a functioning workflow compiled, installed, and running to completion. It will simply log a message to the workflow history; that's it.

Assumes Visual Studio 2008 is installed on Windows Server 2003 64bit with WSPBuilder.

File, New Project, WSPBuilder Project with Workflow

Right-click project in Solution Explorer and choose Workflow, Sequential Workflow (code) - note: I tried using Sequential Workflow with definition expressed as Xaml and user code in a separate code file, but I got errors such as "RunWorkflow: System.Workflow.Activities.EventDeliveryFailedException: Event "OnWorkflowActivated" on interface type "Microsoft.SharePoint.Workflow.ISharePointService" for instance id "405ff0ae-d08d-41b8-ab69-be69ae4ccde1" cannot be delivered. ---> System.Workflow.Runtime.QueueException: Event Queue operation failed with MessageQueueErrorCode QueueNotFound for queue 'Message Properties Interface Type:Microsoft.SharePoint.Workflow.ISharePointService Method Name:OnWorkflowActivated CorrelationValues: '. "

Drag a onWorkflowActivated control onto the designer
Set its CorrelationToken property to anything, e.g. "mytoken"; then expand CorrelationToken and for OwnerActivityName, choose Workflow1 (e.g.)

Drag a logToHistoryListActivity onto the canvas under the onWorkflowActivated1 control.
Double click its MethodInvoking property, and enter the following code into the body of the method: var workflowProperties = new Microsoft.SharePoint.Workflow.SPWorkflowActivationProperties();

this.logToHistoryListActivity1.HistoryOutcome = "Here is a comment " + workflowProperties.InitiationData;


Build Solution

Right click property and choose WSPBuilder, Copy to GAC

Create a folder called MyLoggingWorkflowFeature under C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\TEMPLATE\FEATURES\

Create two xml files in this folder:
Feature.xml:
<?xml version="1.0" encoding="utf-8"?>

<Feature Id="genkey id here"
Title="Workflow to create a log something to history"
Description="Logs something to history"
Version="12.0.0.0"
Scope="Site"
xmlns="http://schemas.microsoft.com/sharepoint/">
<ElementManifests>
<ElementManifest Location="workflow.xml" />
</ElementManifests>
</Feature>

workflow.xml:

<?xml version="1.0" encoding="utf-8"?>

<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
<Workflow
Name="New Task Workflow"
Description="Creates a new task"
Id="yourId here from genkey tool"
CodeBesideClass="NewTaskWorkflow.Workflow3"
CodeBesideAssembly="NewTaskWorkflow, Version=1.0.0.1, Culture=neutral, PublicKeyToken=yourkeytokenhere"
></Workflow>

</Elements>

Thursday, December 29, 2011

Style "Newsletter, no line" and the DVWP

Tried converting (via "convert to XSLT Data View" in Sharepoint Designer 2007) a ListViewWebPart whose style was set to "NewsLetter, no line" and it would not work. The resulting XSLT produced mangled HTML tables. So trying my luck I tried converting the plain Newsletter style using the same approach. This had better results, although, there was an odd table cell on the left, which appeared due the condition ddwrt:GetVar('NumColumns')='1' being true. This is odd, because NumColumns in my list view should be four not one. Further searching the code showed that NumColumns is set as the string length of "Columns," i.e. ddwrt:SetVar('NumColumns', string(string-length(ddwrt:GetVar('Columns')))) and Columns is set to a lone period (dot).
After analyzing the CAML of the LVWP, which should be the basis for the XSLT, I found that in the CAML version, the assignment of Columns is set in a Fields element, which according to the View Schema on MSDN contains a loop over the view fields. This explains the difference: At the end of the loop, Columns is set to "....".
So what I did to patch the XSLT was simply replace the single dot with four dots in the assignment of Columns, which took care of the odd cell, and probably some other anomalies.
There is still some more fixing up to do, e.g.:
- delete the header cell for the field that displays on its own line
- setting column headers to be sortable.
- comment out the ms-alternating class assignment because it's applied unevenly to tr tags, unless you want to convert to "No line" (instructions below)
- explicitely set the class for content cells. Designer sets them incorrectly, e.g. TD Class="{$IDACAVMC}, which is a variable that is based on a List View CAML property, which no longer applies, apparently. So, icon cell would be ms-vb-icon; title cell would be set to ms-vb-title, user would be ms-vb-user; and the text cell on its own row has already been hard coded for us by the Designer ListViewWebPart to DataFormWebPart conversion process.

Now, to transform this into a "Newsletter, no line" style, do the following:
- comment out the TR tag containing the TD class="ms-nlline"
- replace the html encoded starting TR tags (all <xsl:text disable-output-escaping="yes">&lt;tr&gt;</xsl:text>) with actual TR tags; note: must add the closing TR tag, because it was not added during conversion. To find out where to insert the closing TR for the main row, select the row in SPD, backtrack to the last <xsl:choose> that is directly above the two repeated field name comments for the field that will appear on its own line. Place the closing TR above the two field name comments.
- add the conditional ms-alternating attribute to those TR tags.
Note: There should be two xsl:text replacements (the second one being in the vicinity of "ms-nlline" below the @Remarks=) and three conditional (if statements)
ms-alternating attributes added based on a four column table with one field on its own line: two are added to the replaced TRs, and one added to the TR above the removed ms-nlline row.

Sunday, December 25, 2011

Copying Discussion Items to Document Libary

The Requirement is to copy discussion items to another document library.

Code ideas borrowed from: http://stackoverflow.com/questions/468469/how-do-you-upload-a-file-to-a-document-library-in-sharepoint, http://sharepoint.stackexchange.com/questions/20216/iterate-through-discussion-list, http://www.sharepoint-tips.com/2011/11/event-handler-to-archive-items-when.html

Sample code containing the general idea:
using System;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Serialization;

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;

namespace WebPart3
{
[Guid("26d38752-d4ce-456e-88f6-496d213627d4")]
public class WebPart3 : System.Web.UI.WebControls.WebParts.WebPart
{
string msg1;
Button saveTitle;
TextBox newTitle;
Label label;

public WebPart3()
{
SPSite site1 = SPContext.Current.Site;

msg1 = "(1.03)" ;

}

public void saveTitle_click(object sender, EventArgs e)
{
//this.Title = newTitle.Text;
string tempprint = "";
SPWeb myweb = SPContext.Current.Web;
SPListCollection lists = myweb.Lists;
SPList mylist;
SPListItem sli;
string labeltext = "";
SPList targetList;

try
{

// SPList targetList = lists["Discussion Archive"];
// SPListItem newItem = targetList.Items.Add();

mylist = lists[newTitle.Text];
targetList = lists["Discussion Archive"];
// targetList = lists["DiscussionDocs"];

// SPQuery query = new SPQuery();
//query.RowLimit = 10;
// SPListItemCollection posts = mylist.GetItems(query);

//this. .SaveProperties = true;
try
{
labeltext += " entering foreach";
foreach (SPListItem item in mylist.Folders)
{
SPListItem newItem = targetList.Items.Add();
//copy the list item to the target
foreach (SPField f in item.Fields)
{
if (!f.ReadOnlyField && newItem.Fields.ContainsField(f.InternalName))
newItem[newItem.Fields.GetFieldByInternalName(f.InternalName).Id] = item[f.Id];
}
//copy "special" read only fields that can be written to
newItem["Created By"] = item["Created By"];
newItem["Modified By"] = item["Modified By"];
newItem["Modified"] = item["Modified"];
newItem["Created"] = item["Created"];
newItem.SystemUpdate(false);
CopyAttachments(item, newItem);


labeltext += item["Body"] + ",";
sli = item;
tempprint = (string)sli["Created By"];
}
labeltext += " existing foreach";
try
{
this.Title = "yo" + mylist.ItemCount + " by: " + tempprint;

}
catch (Exception ex)
{
this.Title = "Error3: " + ex.Message;
label.Text = ex.StackTrace;

}
}
catch (Exception ex)
{

this.Title = "Error2: " + ex.Message;
label.Text = ex.StackTrace;
}
}
catch (Exception ex)
{
this.Title = "Error: " + ex.Message;
label.Text = ex.StackTrace;
}
label.Text += labeltext + "the end";
// this.SetPersonalizationDirty();
}

private void CopyAttachments(SPListItem sourceItem, SPListItem targetItem)
{
SPWeb web = SPContext.Current.Web;

SPFolder myLibrary = web.Folders["DiscussionDocs"];
Boolean replaceExistingFiles = true;

try
{
//get the folder with the attachments for the source item
SPFolder sourceItemAttachmentsFolder = sourceItem.Web.Folders["Lists"].SubFolders[sourceItem.ParentList.Title]
.SubFolders["Attachments"].SubFolders[sourceItem.ID.ToString()];
foreach (SPFile file in sourceItemAttachmentsFolder.Files)
{
byte[] binFile = file.OpenBinary();
targetItem.Attachments.AddNow(file.Name, binFile);
this.label.Text += file.Name + " attached to target ";
SPFile spfile = myLibrary.Files.Add(file.Name, binFile, replaceExistingFiles);
SPListItem newfileitem = spfile.Item;
newfileitem["Created"] = sourceItem["Created"];
newfileitem["Modified By"] = sourceItem["Modified By"];
newfileitem["Modified"] = sourceItem["Modified"];
newfileitem["Created By"] = sourceItem["Created By"];
newfileitem["Title"] = sourceItem["Title"];
//newfileitem.SystemUpdate(false);
newfileitem.Update();

myLibrary.Update();
}
}
catch (Exception ex)
{
this.Title = "Error: " + ex.Message;
}
}

protected override void CreateChildControls()
{
base.CreateChildControls();

// TODO: add custom rendering code here.
label = new Label();
label.Text = "Hello World" + msg1;
this.Controls.Add(label);

//Create text box
newTitle = new TextBox();
newTitle.Text = "myxmdiscuss";
this.Controls.Add(newTitle);

//Create Button
saveTitle = new Button();
saveTitle.Text = "Set Web Partt Title";
saveTitle.Click += new EventHandler(this.saveTitle_click);
Controls.Add(saveTitle);
}
}
}


And here's the Powershell:


$error.clear()

[System.reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")

$site = new-object Microsoft.SharePoint.SPSite("https://site")
$web = $site.OpenWeb()

$lists = $web.Lists;

$lista = $lists['Team Discussion']
$listb = $web.Folders['MyDocLib']

foreach ($item in $lista.Folders)
{
Try
{
$sourceItemAttachmentsFolder = $item.Web.Folders["Lists"].SubFolders[$item.ParentList.Title].SubFolders["Attachments"].SubFolders[$item.ID.ToString()];
foreach ($file in $sourceItemAttachmentsFolder.Files)
{
$binfile = $file.OpenBinary()
"Attached to target " + $item["Title"]
$spfile = $listb.Files.Add($file.Name, $binfile, 1)
$newfileitem = $spfile.Item
foreach ($f in $item.Fields)
{
if (!$f.ReadOnlyField -and $newfileitem.Fields.ContainsField($f.InternalName))
{
$newfileitem[$newfileitem.Fields.GetFieldByInternalName($f.InternalName).Id] = $item[$f.Id];
}

$newfileitem["Created By"] = $item["Created By"];

$newfileitem["Created"] = $item["Created"];

$newfileitem["Modified By"] = $item["Modified By"];

$newfileitem["Modified"] = $item["Modified"];

$newfileitem.Update();

}
}

}
Catch
{

"caught a system exception"
}

$error

}

Note: Minimum permissions to execute the ps1 is local server administrator + Site owner.