tag:blogger.com,1999:blog-77992381931151236362024-03-13T19:04:09.473+00:00The Simple ProgrammerCode examples and tips for Microsoft development platforms, especially Sharepoint.Unknownnoreply@blogger.comBlogger31125tag:blogger.com,1999:blog-7799238193115123636.post-62223588657357489152015-12-07T19:25:00.004+00:002015-12-07T19:25:50.301+00:00SSRS Open Linked Report In New Window with JavascriptI recently wanted to set op a series of interlinked reports using SQL Server Reporting Services (SSRS) targetting a 2012 instance. I used javascript in a "Custom URL" action on a field to create the link. Everything looked OK, but further testing I noticed the following type of error was often being generated in in the drill through report:<br />
<br />
<pre class="brush:jscript">The report execution xnf441454bs2oh45hqvrkd45 has expired or cannot be found. (rsExecutionNotFound)
</pre>
<br />
The problem was the parameter: I was using a text field to pass through information for the parameter, and this textual information could include an Ampersand (&).<br />
<br />
This is obviously a reserved character, so requires escaping.<br />
<br />
To do this, we must utilise SSRS's commands REPLACE and ESCAPE in the custom action. The easiest way to explain this is in this example: <br />
<br />
<pre class="brush:jscript">="javascript:void window.open('" & Globals!ReportServerUrl & "/ReportServer/Pages/ReportViewer.aspx?%2fPhonebook+Reports%2fDepartment&department="
+Replace(Fields!Team.Value,"&","' + escape('&') + '") & "&location="+Replace(Fields!Location.Value,"&","' + escape('&') + '")
& "&rs:Command=Render=','_blank','')"
</pre>
<br />
Using this format to build the link, I can now open "drill through" reports with a parameter that contains an ampersand, and no longer get the "report execution" error above. Nice.<br />
<br />
<table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: auto; margin-right: auto; text-align: center;"><tbody>
<tr><td style="text-align: center;"><a href="http://www.yngoo.co.uk/top-tens/watches/best-selling-festina-watches/" rel="dofollow" target="_blank">
<img src="http://4.bp.blogspot.com/-wOr73D3_NUY/VmXZMvBRL9I/AAAAAAAAAWc/Tjl_44bIZjI/s1600/Festina%2BLimited%2BEdition%2BChrono%2BBike%2B2015%2BMen%2527s%2BQuartz%2BWatch%2Bwith%2BBrown%2BDial%2BChronograph%2BDisplay%2Band%2BBrown%2BStainless%2BSteel%2BPlated%2BBracelet%2BF16883-1.png" style="margin-left: auto; margin-right: auto;" />
</a>
</td></tr>
<tr><td class="tr-caption" style="text-align: center;">Festina Limited Edition Chrono Bike 2015 Men’s Quartz Watch with Brown Dial F16883/1</td></tr>
</tbody></table>
<a href="http://www.yngoo.co.uk/top-tens/watches/best-selling-festina-watches/" rel="dofollow" target="_blank"></a>
<a href="http://www.yngoo.co.uk/top-tens/watches/best-selling-festina-watches/" rel="dofollow" target="_blank"><br />Click here for a list of the best selling Festina watches this week.</a>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-7799238193115123636.post-73902273698098382962014-12-14T22:06:00.004+00:002015-12-11T16:04:39.333+00:00Using .htaccess file to forbid spammers access to a URLThis is pretty straightforward, but I struggled to find a simple explanation of this and worked it out with trial and error, so thought I might as well post it here in case it helps somebody else :) <br />
<br />
I run another website which I is hosted on Linux/Apache, and for a while I ran a forum on it. However the forum was never used, apart from spam bots, so I removed it.
I later discovered that huge amounts of bandwidth was being taken up by spam bots trying to spam the now non-existent forum, each one being served a nice 404 message and taking up processing time on my site, so I decided to forbid access to it.<br />
<br />
The forum sat at: http://<root of="" site="">/<my site="">/forum/index.php, and both /forum and /forum/index.php were getting lots of traffic. </my></root><br />
<br />
<root of="" site="">To block this I edited the Apache .htaccess file, and added this line:
</root><br />
<pre class="brush:csharp"> </pre>
<pre class="brush:csharp">RewriteRule ^forum($|/) - [F]
</pre>
<br />
This is a rewrite rule, for any path after /forum, that results in the following "403" forbidden message:
<br />
<pre class="brush:csharp"> </pre>
<pre class="brush:csharp">Forbidden
You don't have permission to access /forum on this server.
</pre>
<br />
This is exceptionally lightweight and does not trigger a 404. Problem solved!<br />
<br />
If you want do a simple redirect, perhaps becuase you have changed your structure, this is even more simple. Just use teh "Redirect 301" command as per the example below:<br />
<br />
<pre class="brush:csharp">Redirect 301 /top-tens/bestselling-electronics/bestselling-televisions/bestselling-sony-televisions/ http://www.mysite.co.uk/top-tens/electronic/bestselling-televisions/
Redirect 301 /top-ten/watches/omega/ladies http://www.mysite.co.uk/top-tens/best-selling-omega-watches/
</pre>
<br />
Please note that the "from" URL must be a relative URL, whilst the "to" URL is the full URL including domain.<br />
<br />
<div style="vertical-align: top;">
<a href="http://www.yngoo.com/" target="_blank"><img src="http://2.bp.blogspot.com/-7aTKu3Vq_fI/VEfl6SWbutI/AAAAAAAAAME/DgKGob5mzdQ/s1600/Yngoo_logo_crop.png" />
</a>
<a href="http://www.yngoo.com/tag/consoles/" target="_blank">
Click here for a list of the best selling video game consoles, including bundle deals and this week. Includes PS4 and Xbox One deals.</a>
</div>
<table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: auto; margin-right: auto; text-align: center;"><tbody>
<tr><td style="text-align: center;"><a href="http://www.yngoo.co.uk/top-tens/jewellery" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img alt="Carissima Gold 9 ct Yellow Gold Two-Row Diamond Cut Curb Bracelet of 21 cm 8.5-inch on www.yngoo.co.uk" border="0" src="http://4.bp.blogspot.com/-JgOrbukGHKE/Vmrp7CjdOwI/AAAAAAAAAW8/vSLhnQs8Kbw/s320/Carissima%2BGold%2B9%2Bct%2BYellow%2BGold%2BTwo-Row%2BDiamond%2BCut%2BCurb%2BBracelet%2Bof%2B21%2Bcm%2B8.5-inch.jpg" title="Carissima Gold 9 ct Yellow Gold Two-Row Diamond Cut Curb Bracelet of 21 cm 8.5-inch on www.yngoo.co.uk" /></a></td></tr>
<tr><td class="tr-caption" style="text-align: center;">Carissima Gold 9 ct Yellow Gold Two-Row Diamond Cut Curb Bracelet of 21 cm/8.5-inch</td></tr>
</tbody></table>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-7799238193115123636.post-86562282503131586572014-09-18T21:33:00.001+01:002015-07-27T22:27:50.808+01:00Programatically overriding SharePoint record locks using Records.BypassLocks() in c#<div style="vertical-align: top;">
<a href="http://www.yngoo.com/top-tens/electronic/bestselling-televisions/" target="_blank">
<img src="http://2.bp.blogspot.com/-7aTKu3Vq_fI/VEfl6SWbutI/AAAAAAAAAME/DgKGob5mzdQ/s1600/Yngoo_logo_crop.png" />
</a>
<a href="http://www.yngoo.com/top-tens/electronic/bestselling-televisions/" target="_blank">
Click here for a list of the best selling televisions this week. Samsung, Sony, LG, Philips and Panasonic brands</a>
</div>
Records are good - they are immutable and cannot be changed by users.<br />
<br />
Record Centres are also good - they provide a repository for records that users can submit their documents to, to be transformed into records.<br />
<br />
Event receiver rules that automatically commit as records any document submitted to a list are also good, because as soon as content is placed in that list it becomes a records, and so immutable.<br />
<br />
<b>However...</b><br />
<br />
What if something goes wrong? Perhaps a users submits a document that should not be locked as a record ans should be removed, or perhaps the wrong meta data is attached to the record?<br />
<br />
In these cases an admin has to temporarily suspend the records management features of SharePoint in order to rectify the fault. This is a big deal since SharePoint admins have a different role to server admins, and so normally would not have the authority (or indeed the know-how) to do this, whereas the server admins would not be able to understand the records and content. In my experience the only people who know both how the system works, and what it is supposed to do, are the developers! And we do NOT want to do admin, because among other things they somehow get paid more than we do...<br />
<br />
Furthermore, if you are automatically declaring documents as records when they enter the list, you will not be able to "undeclare" the record from the SharePoint front end without first disabling this feature - quite a risk if you end up having to do this a lot.<br />
<br />
This is why I like to create my own tools to fill the gaps, and in this case we programmers can turn to a little known feature of the Object Model to help us: Records.BypassLocks().<br />
<br />
This neat little method, part of the Microsoft.Office.RecordsManagement.RecordsRepository namespace, allows use to define a delegate function that be be run even on locked down records. Wrap it in a security delegate and you have the makings of a class that can be used to provide users (preferably power users and admins) with tools to manage their records centre WITHOUT suspending record handling functions.<br />
<br />
Remember - this allows you to override records handling, so only use this if you really need to. However if you have found this blog and read this far, you probably really need to!<br />
<br />
Here is a basic method that shows you how to use Records.BypassLocks() in a simple record cancelling scenario. In this example I pass in URL to the offending record, open a security delegate (in order to ensure that the process has permission to perform this task), and then use BypassLocks to edit the meta-data on the document to change the name and title and set the Status to "CANCELLED".<br />
<br />
Please not that I have present this a method inside a class with no constructor - I will leave that up to you (simple copy the methods into whatever class you are working in if this confuses you).<br />
<br />
<pre class="brush:csharp">using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Publishing;
using Microsoft.SharePoint.Utilities;
using Microsoft.Office.RecordsManagement.RecordsRepository; //You are going to need to include the dll in teh references
using System.Web;
namespace BusinessLayer
{
public void Cancelrecord(string documentURL)
{
// Pass in the document URL in a format such as:
//string documentURL = "http://test_reocrds/records/wrong_file.pdf";
//Run this in a security delegate
SPSecurity.RunWithElevatedPrivileges(delegate() {
using (SPSite site = new SPSite(SPContext.Current.Web.Url))
{
using (SPWeb web = site.OpenWeb())
{
web.AllowUnsafeUpdates = true;
try
{
SPListItem target = web.GetListItem(documentURL);
Records.BypassLocks(target, delegate(SPListItem item)
{ //Perform any action on the item.
CancelItem(item);
});
}
catch (Exception ex) // it all throws up to here
{
throw ex;
}
finally
{
web.AllowUnsafeUpdates = false;
}
}
}
});
}
//Set item name to start with CANCELLED and set status to CANCELLED
public void CancelItem(SPListItem item)
{
try
{
// Update the name of the file
item.File.CheckOut();
item.TrySetValue("Name", String.Format("CANCELLED {0}", item.Name));
item.TrySetValue("Title", String.Format("CANCELLED {0}", item.Title));
item.TrySetValue("Status", "CANCELLED"); //
item.Update();
//This records library is set to use check in/out and versioning so it records any updates such as this
item.File.CheckIn("CANCELLED", SPCheckinType.MinorCheckIn);
}
catch (Exception ex)
{
// Permissions failed. Undo checkout
item.File.UndoCheckOut();
throw ex;
}
}
}
}
</pre>
<br />
In my example above I use an Extensions class to add useful methods to SPListItem class to get or set values. Here is the class:<br />
<pre class="brush:csharp">using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
namespace BusinessLayer
{
public static class Extensions
{
public static T TryGetValue(this SPListItem listItem, string fieldInternalName)
{
if (!String.IsNullOrEmpty(fieldInternalName) &amp;&amp;
listItem != null &amp;&amp;
listItem.Fields.ContainsField(fieldInternalName))
{
object untypedValue = listItem[fieldInternalName];
if (untypedValue != null)
{
var value = (T)untypedValue;
return value;
}
}
return default(T);
}
public static bool TrySetValue(this SPListItem listItem, string fieldInternalName, T value)
{
try
{
if (!String.IsNullOrEmpty(fieldInternalName) &amp;&amp;
listItem != null &amp;&amp;
listItem.Fields.ContainsField(fieldInternalName))
{
listItem[fieldInternalName] = value;
}
return true;
}
catch
{
throw;
}
}
}
}
</pre>
<t><t></t></t><br />
<br />
<br />
<br />
<br />
<br />
<iframe align="left" frameborder="0" marginheight="0" marginwidth="0" scrolling="no" src="http://rcm-na.amazon-adsystem.com/e/cm?t=thesim06-20&o=1&p=8&l=bpl&asins=0470529423&fc1=000000&IS2=1&lt1=_blank&m=amazon&lc1=0000FF&bc1=000000&bg1=FFFFFF&f=ifr" style="align: left; height: 245px; padding-right: 10px; padding-top: 5px; width: 131px;"></iframe><iframe align="left" frameborder="0" marginheight="0" marginwidth="0" scrolling="no" src="http://rcm-na.amazon-adsystem.com/e/cm?t=thesim06-20&o=1&p=8&l=bpl&asins=1430227818&fc1=000000&IS2=1&lt1=_blank&m=amazon&lc1=0000FF&bc1=000000&bg1=FFFFFF&f=ifr" style="align: left; height: 245px; padding-right: 10px; padding-top: 5px; width: 131px;"></iframe><iframe align="left" frameborder="0" marginheight="0" marginwidth="0" scrolling="no" src="http://rcm-na.amazon-adsystem.com/e/cm?t=thesim06-20&o=1&p=8&l=bpl&asins=B00413PHRI&fc1=000000&IS2=1&lt1=_blank&m=amazon&lc1=0000FF&bc1=000000&bg1=FFFFFF&f=ifr" style="align: left; height: 245px; padding-right: 10px; padding-top: 5px; width: 131px;"></iframe><iframe align="left" frameborder="0" marginheight="0" marginwidth="0" scrolling="no" src="http://rcm-na.amazon-adsystem.com/e/cm?t=thesim06-20&o=1&p=8&l=bpl&asins=0470888687&fc1=000000&IS2=1&lt1=_blank&m=amazon&lc1=0000FF&bc1=000000&bg1=FFFFFF&f=ifr" style="align: left; height: 245px; padding-right: 10px; padding-top: 5px; width: 131px;"></iframe>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-7799238193115123636.post-5211536413845163342014-01-09T00:17:00.000+00:002015-07-27T22:21:34.317+01:00Hiding the Sharepoint 2010 ribbon from users without losing the scrollbar or title bar area when using a list webpart<div style="vertical-align: top;">
<a href="http://www.yngoo.co.uk/top-tens/watches/best-selling-rolex-watches/" target="_blank">
<img src="http://2.bp.blogspot.com/-7aTKu3Vq_fI/VEfl6SWbutI/AAAAAAAAAME/DgKGob5mzdQ/s1600/Yngoo_logo_crop.png" />
</a>
<a href="http://www.yngoo.co.uk/top-tens/watches/best-selling-rolex-watches/" target="_blank">
Click here for a list of the best selling Rolex watches this week.</a>
</div>
There are many blog posts suggesting techniques to hide the Sharepoint ribbon using security trimmed controls in the Sharepoint masterpage, however I have found that none of them properly address the issue of how Sharepoint processes user clicks with the ribbon: namely that the titlebar area will disappear if the ribbon has been hidden with CSS!<br />
<br />
In my site I use this area to display location specific information taken from a BCS connection, and provide location specific buttons and actions (all using sharepoint delegate controls), so there was no way I could lose this section of the page. I have therefore had to work out how to stop this from happening.<br />
<br />
<br />
In order to solve this we must first implement the standard method of hiding the ribbon with CSS, and use a security trimmed control in order to decide which users
get to access the ribbon and which do not. This has been gone over in detail elsewhere so I will only briefly recap this now.
<br />
First, edit the masterpage and set a style element in the "s4-ribbonrow" div to hide it:
<br />
<pre class="brush: csharp;"><div class="s4-pr s4-ribbonrowhidetitle" id="s4-ribbonrow" style="display: none;"%>
<%--added display:none to hide Ribbon--%>
</pre>
Next, add a security trimmed control to make the ribbon visible for administrators (in my case this is users with delete permission, hence I have used the "DeleteListItems" PermissionsString:
<br />
<pre class="brush: csharp;"><%-- Show the ribbon to power users -->
<sharepoint:spsecuritytrimmedcontrol id="RIBBONHIDE_SPSecurityTrimmedControl3" permissionsstring="DeleteListItems" runat="server">
<script type="text/javascript">
document.getElementById("s4-ribbonrow").style.display = "block";
</script>
</sharepoint:spsecuritytrimmedcontrol>
</pre>
Installing this masterpage and applying it to your site will hide the ribbon from users without delete permission. Hooray!
<br />
<br />
<br />
<u><b>HOWEVER... </b></u><br />
When implementing this techniques you will find a major flaw: if a list webpart is on the page then when a user who has not got the ribbon clicks on the list webpart in a section that would normally cause the ribbon to show, the user will lose the title area at the top of the page. This includes the logo, the breadcrumb trail, and the social icons.
After investigation I determined that this is caused by the Ribbon javascript <u>replacing</u> the title area element with the ribbon, and since you have hidden it, this mean that the whole title area is removed. I've followed this through the whole code and it seems to be related to the custom javascript scrolling function that Sharepoint 2010 uses. <br />
<br />
<br />
<u><b>The fix</b></u>
<br />
<br />
In order to get around this, we have to make changes to a couple of other areas.
<br />
<br />
First, we must update the following javascript fuction "OnRibbonMinimizedChanged" that is found in the standard Sharepoint INIT.JS javascript file in the 14 hive. DO NOT edit the file directly! It can be simply overriden by including another javascript file later on in the masterpage (see below).
To override this function, first create a file called "HideRibbon.js" with the following in it:
<br />
<pre class="brush: js;">var g_spribbon = new Object();
g_spribbon.isMinimized = true;
g_spribbon.isInited = false;
g_spribbon.minimizedHeight = "44px";
g_spribbon.maximizedHeight = "135px";
function OnRibbonMinimizedChanged(ribbonMinimized) {
ULSxSy: ;
var ribbonElement = GetCachedElement("s4-ribbonrow");
var titleElement = GetCachedElement("s4-titlerow");
if (ribbonElement) {
ribbonElement.className = ribbonElement.className.replace("s4-ribbonrowhidetitle", "");
if (titleElement) {
titleElement.className = titleElement.className.replace("s4-titlerowhidetitle", "");
if (ribbonMinimized) {
titleElement.style.display = "block";
}
else {
//titleElement.style.display = "none"; // MODIFICATION - Commented out - do not hide this element, or it will hide the whole title area when it thinks a ribbon is required
}
}
}
var wasInited = g_spribbon.isInited;
g_spribbon.isInited = true;
var lastState = g_spribbon.isMinimized;
g_spribbon.isMinimized = ribbonMinimized;
if (lastState != ribbonMinimized || !wasInited)
FixRibbonAndWorkspaceDimensions();
}
</pre>
Upload this file to your site somewhere (in this example I will use the "Shared Documents" list), and add the following to your masterpage in order to including it:
<br />
<pre class="brush: js;"><asp:scriptmanager enablepagemethods="false" enablepartialrendering="true" enablescriptglobalization="false" enablescriptlocalization="true" id="ScriptManager" runat="server">
<scripts>
<asp:scriptreference path="<% $SPUrl:~sitecollection/Shared%20Documents/HideRibbon.js%>" runat="server"></asp:scriptreference>
</scripts>
</asp:scriptmanager>
</pre>
Put this section after the body element, directly after the form element. I.e. after the following two lines of the masterpage:
<br />
<pre class="brush: js;"><body scroll="no" onload="if (typeof(_spBodyOnLoadWrapper) != 'undefined') _spBodyOnLoadWrapper();" class="v4master">
<form id="Form1" runat="server" onsubmit="if (typeof(_spFormOnSubmitWrapper) != 'undefined') {return _spFormOnSubmitWrapper();} else {return true;}">
</pre>
Now change this line in you masterpage:
<br />
<pre class="brush: csharp;"><div class="s4-pr s4-notdlg s4-titlerowhidetitle " id="s4-titlerow">
</pre>
Change it to <b>this</b> to remove the class that tells the javascript that this is the bit to hide:
<br />
<pre class="brush:csharp;"> <div class="s4-pr s4-notdlg " id="s4-titlerow">
<%-- Changed class to remove to s4-titlerowhidetitle so ribbon does not fire up over top of this --%>
</pre>
Now you should find that the title bar remains active even when the ribbon is active (thus losing some screen real estate), but that restricted users with no ribbon do not lose their title area when they perform an action that would normally have opened the ribbon :)
<br />
Best of luck and happy coding!
<br />
<br />
<iframe align="left" frameborder="0" marginheight="0" marginwidth="0" scrolling="no" src="http://rcm-na.amazon-adsystem.com/e/cm?t=thesim06-20&o=1&p=8&l=bpl&asins=0470529423&fc1=000000&IS2=1&lt1=_blank&m=amazon&lc1=0000FF&bc1=000000&bg1=FFFFFF&f=ifr" style="align: left; height: 245px; padding-right: 10px; padding-top: 5px; width: 131px;"></iframe><iframe align="left" frameborder="0" marginheight="0" marginwidth="0" scrolling="no" src="http://rcm-na.amazon-adsystem.com/e/cm?t=thesim06-20&o=1&p=8&l=bpl&asins=1430227818&fc1=000000&IS2=1&lt1=_blank&m=amazon&lc1=0000FF&bc1=000000&bg1=FFFFFF&f=ifr" style="align: left; height: 245px; padding-right: 10px; padding-top: 5px; width: 131px;"></iframe><iframe align="left" frameborder="0" marginheight="0" marginwidth="0" scrolling="no" src="http://rcm-na.amazon-adsystem.com/e/cm?t=thesim06-20&o=1&p=8&l=bpl&asins=B00413PHRI&fc1=000000&IS2=1&lt1=_blank&m=amazon&lc1=0000FF&bc1=000000&bg1=FFFFFF&f=ifr" style="align: left; height: 245px; padding-right: 10px; padding-top: 5px; width: 131px;"></iframe><iframe align="left" frameborder="0" marginheight="0" marginwidth="0" scrolling="no" src="http://rcm-na.amazon-adsystem.com/e/cm?t=thesim06-20&o=1&p=8&l=bpl&asins=0470888687&fc1=000000&IS2=1&lt1=_blank&m=amazon&lc1=0000FF&bc1=000000&bg1=FFFFFF&f=ifr" style="align: left; height: 245px; padding-right: 10px; padding-top: 5px; width: 131px;"></iframe>
Unknownnoreply@blogger.com3tag:blogger.com,1999:blog-7799238193115123636.post-19045499109835315462013-09-17T21:05:00.001+01:002013-09-17T21:05:31.334+01:00Online tools to convert code between VB and C#Using .Net and the CLR means we have sometimes have to use both VB and C#. If you are anything like me you will forget the more subtle syntactical differences between the two more often than not, a situation I found myself in earlier today when trying to work out how to rewrite an old VB function in C#.<br />
<br />
Rather than doing this myself (I very rarely use VB anymore) I decided to try to use some of the resources on the internet. The following sites will all allow you to convert freely between the two languages by pasting code into a browser control:
<br />
<br />
<a href="http://www.carlosag.net/tools/codetranslator/">CodeTranslator: Code Translation From VB.NET <-> C# - CarlosAG<!-----></-></a> - my favourite - this one managed to convert things the others couldn't.<br />
<br />
<a href="http://www.developerfusion.com/tools/convert/vb-to-csharp/">Convert VB.NET to C# - developerFusion</a><br />
<br />
<a href="http://converter.telerik.com/">Convert VB to C# or C# to VB provided by Telerik</a><br />
<br />
Hope this helps! Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-7799238193115123636.post-64226429100355533702013-06-22T21:18:00.000+01:002013-09-10T15:04:29.666+01:00Changing the name and URL of a document in Sharepoint using c#Changing a document's name in Sharepoint programatically, particularly in a webpart for example, is not a trivial process. In theory, we can use the SPListItem.Item("Name") property and update this. However you may find that non-administrative users can receive "permission denied" error when they save this back to the database (using a web.Update()).<br /><br/>
This is generally because in order to move (rename) a file in Sharepoint, the user must have "delete" permission on list.
<br />
Provided the users have enough permission, then the code below works. The trick here is to use an SPFile object to update the "Name" property, whilst using an SPListItem object to control the files checkin/out status.<br />
<br />
Keen readers will see that I am doing a ValidateFormDigest() in order to prevent the "Page Validation" error if this is caused from a form's POST action, but there is also a "web.AllowUnsafeUpdates = true;" command. I would prefer not to allow unsafe updates and would recommend you keep this line uncommented, but I have left it in in order to give you an option if you find that this still does not work properly in your situation.<br />
<br />
<br />
<pre class="brush:csharp"> using (SPSite site = new SPSite(SPContext.Current.Web.Url))
{
using (SPWeb web = site.OpenWeb())
{
try
{
SPUtility.ValidateFormDigest();
SPListItem target = web.GetListItem(fileUrl); // fileURL should be set to the full path of the document you are changing
if (target.File.CheckOutType == SPFile.SPCheckOutType.None)
{
//web.AllowUnsafeUpdates = true; // Shouldn't need this with the validateformDigest
try
{ target.File.CheckOut();
SPFile filet = web.GetFile(target.Url);
filet.Item["Name"] = newName; // newName is the new name of the file
target.Update();
}
catch (Exception ex)
{
web.AllowUnsafeUpdates = false;
target.File.UndoCheckOut();
ShowErrorMessage("Error validating document: " + ex.Message); // Deal with error
return;
}
target.File.CheckIn("", SPCheckinType.MajorCheckIn); // Make major version
web.Update();
web.AllowUnsafeUpdates = false;
}
catch (Exception ex)
{
ShowErrorMessage("Error: " + ex.Message); //Deal with error
//throw;
}
finally
{
web.AllowUnsafeUpdates = false;
}
}
}
</pre>
<iframe align="left" frameborder="0" marginheight="0" marginwidth="0" scrolling="no" src="http://rcm.amazon.com/e/cm?t=thesim06-20&o=1&p=8&l=bpl&asins=0470529423&fc1=000000&IS2=1&lt1=_blank&m=amazon&lc1=0000FF&bc1=000000&bg1=FFFFFF&f=ifr" style="align: left; height: 245px; padding-right: 10px; padding-top: 5px; width: 131px;"></iframe><iframe align="left" frameborder="0" marginheight="0" marginwidth="0" scrolling="no" src="http://rcm.amazon.com/e/cm?t=thesim06-20&o=1&p=8&l=bpl&asins=1430227818&fc1=000000&IS2=1&lt1=_blank&m=amazon&lc1=0000FF&bc1=000000&bg1=FFFFFF&f=ifr" style="align: left; height: 245px; padding-right: 10px; padding-top: 5px; width: 131px;"></iframe><iframe align="left" frameborder="0" marginheight="0" marginwidth="0" scrolling="no" src="http://rcm.amazon.com/e/cm?t=thesim06-20&o=1&p=8&l=bpl&asins=B00413PHRI&fc1=000000&IS2=1&lt1=_blank&m=amazon&lc1=0000FF&bc1=000000&bg1=FFFFFF&f=ifr" style="align: left; height: 245px; padding-right: 10px; padding-top: 5px; width: 131px;"></iframe><iframe align="left" frameborder="0" marginheight="0" marginwidth="0" scrolling="no" src="http://rcm.amazon.com/e/cm?t=thesim06-20&o=1&p=8&l=bpl&asins=0470888687&fc1=000000&IS2=1&lt1=_blank&m=amazon&lc1=0000FF&bc1=000000&bg1=FFFFFF&f=ifr" style="align: left; height: 245px; padding-right: 10px; padding-top: 5px; width: 131px;"></iframe>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-7799238193115123636.post-5798876338101754292013-03-01T00:52:00.005+00:002014-06-15T17:09:02.638+01:00Essential free tools that that every Sharepoint developer needs<h2 class="separator" style="clear: both; text-align: center;">
<a href="http://spm.codeplex.com/" target="_blank">Sharepoint Manager </a></h2>
<h2 class="separator" style="clear: both; text-align: center;">
</h2>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://spm.codeplex.com/" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img alt="" border="0" src="http://i3.codeplex.com/Download?ProjectName=spm&DownloadId=23663" title="Sharepoint Manager" /></a></div>
<br />
<br />
<br />
<br />
<h2 style="text-align: center;">
<a href="http://www.fiddler2.com/fiddler2/" target="_blank">Fiddler</a></h2>
<h2 style="text-align: center;">
</h2>
<div class="separator" style="clear: both; text-align: center;">
<iframe allowfullscreen="" frameborder="0" height="360" src="//www.youtube.com/embed/gujBKFGwjd4?feature=player_embedded" width="640"></iframe>
</div>
<br />
<br />
<br />
<h2 style="text-align: center;">
<a href="http://www.codeproject.com/Articles/458008/CAML-Query-Builder" target="_blank">CAML Query Builder</a></h2>
<h2 style="text-align: center;">
</h2>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://www.codeproject.com/Articles/458008/CAML-Query-Builder" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://www.codeproject.com/KB/sharepoint/458008/image009.jpg" /></a></div>
<br />Unknownnoreply@blogger.com1tag:blogger.com,1999:blog-7799238193115123636.post-59174248439995995452012-10-19T17:02:00.002+01:002015-12-11T16:04:23.960+00:00SharePoint workflow - Delay activity never ends, workflow waits forever.<table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: auto; margin-right: auto; text-align: center;"><tbody>
<tr><td style="text-align: center;"><a href="http://www.yngoo.com/top-tens/jewelry/" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img alt="Carissima Gold 9 ct Yellow Gold Two-Row Diamond Cut Curb Bracelet of 21 cm 8.5-inch on www.yngoo.com" border="0" src="http://4.bp.blogspot.com/-JgOrbukGHKE/Vmrp7CjdOwI/AAAAAAAAAW8/vSLhnQs8Kbw/s320/Carissima%2BGold%2B9%2Bct%2BYellow%2BGold%2BTwo-Row%2BDiamond%2BCut%2BCurb%2BBracelet%2Bof%2B21%2Bcm%2B8.5-inch.jpg" title="Carissima Gold 9 ct Yellow Gold Two-Row Diamond Cut Curb Bracelet of 21 cm 8.5-inch- see more jewellery bargains on www.yngoo.co.uk" /></a></td></tr>
<tr><td class="tr-caption" style="text-align: center;">Carissima Gold 9 ct Yellow Gold Two-Row Diamond Cut Curb Bracelet of 21 cm/8.5-inch</td></tr>
</tbody></table>
Developing Sharepoint workflows using the Windows Workflow Foundation and Visual Studio can be pretty painful. <br />
<br />
By far the most painful part I have come across is the dreaded delay activity never waking up problem. This occurs when you place a delayActivity object in your workflow in order to wait for something to happen (for example in a while loop). This is pretty fundamental stuff in a workflow, so you would expect this to be a basic requiredment, but for some reason SharePoint has a HUGE flaw in this department: when you are developing your workflows, they seem to get stuck in the delay and never wake up!<br />
<br />
<br />
<table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: auto; margin-right: auto; text-align: center;"><tbody>
<tr><td style="text-align: center;"><a href="http://2.bp.blogspot.com/-6jRkRf_B-E0/UIF3W2ssPZI/AAAAAAAAAKE/Bi453Fhu_I4/s1600/delay+activity+in+workflow.png" imageanchor="1" style="margin-left: auto; margin-right: auto;"><img border="0" height="320" nea="true" src="http://2.bp.blogspot.com/-6jRkRf_B-E0/UIF3W2ssPZI/AAAAAAAAAKE/Bi453Fhu_I4/s320/delay+activity+in+workflow.png" width="192" /></a></td></tr>
<tr><td class="tr-caption" style="text-align: center;">A WWF DelayActivity in a while loop</td></tr>
</tbody></table>
<br />
<br />
<table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: auto; margin-right: auto; text-align: center;"><tbody>
<tr><td style="text-align: center;"><a href="http://3.bp.blogspot.com/-jqFkw3oABso/UIF3ewve8VI/AAAAAAAAAKM/p7AJhFfovjY/s1600/This+workflow+is+waiting+for+ever.png" imageanchor="1" style="margin-left: auto; margin-right: auto;"><img border="0" height="107" nea="true" src="http://3.bp.blogspot.com/-jqFkw3oABso/UIF3ewve8VI/AAAAAAAAAKM/p7AJhFfovjY/s320/This+workflow+is+waiting+for+ever.png" width="320" /></a></td></tr>
<tr><td class="tr-caption" style="text-align: center;">Workflow history - it never wakes up after delay :(</td></tr>
</tbody></table>
<br />
<br />
After much head scratching, I have found a solution. The delayActivity passes control to the SharePoint Services Timer (OWSTIMER.EXE), and this gets confused if you redeploy the wrokflow.<br />
<br />
To fix, follow these instructions.<br />
<br />
First run this command on your farm:<br />
<div>
</div>
stsadm -o setproperty -pn job-workflow -pv "Every 5 minutes between 0 and 59" -url <a href="http://yoursite/">http://yoursite</a><br />
(<a href="http://technet.microsoft.com/en-us/library/cc424946%28v=office.12%29.aspx">http://technet.microsoft.com/en-us/library/cc424946%28v=office.12%29.aspx</a>)<br />
<br />
(note apparently doesn’t like being anything but 5 minutes! )<br />
<br />
I rebooted my dev box after this but this is probably not required.<br />
<br />
<br />
The key part is that now provided I restart the Microsoft Sharepoint Timer service between deploys, it actually completes a delay! So remember to recycle the "Sharepoint 2010 Timer" service before you depoly a new version of the workflow to the farm.<br />
<br />
<br />
<table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: auto; margin-right: auto; text-align: center;"><tbody>
<tr><td style="text-align: center;"><a href="http://4.bp.blogspot.com/-nCF2Tt0MMo4/UIF4_tFRiRI/AAAAAAAAAKU/veeTU2_4h58/s1600/owstimer.png" imageanchor="1" style="margin-left: auto; margin-right: auto;"><img border="0" height="175" nea="true" src="http://4.bp.blogspot.com/-nCF2Tt0MMo4/UIF4_tFRiRI/AAAAAAAAAKU/veeTU2_4h58/s320/owstimer.png" width="320" /></a></td></tr>
<tr><td class="tr-caption" style="text-align: center;">OWSTIMER service</td></tr>
</tbody></table>
<br />
<br />
Note that this was supposedly a bug fixed in 2007 that is back in 2010. See this hotfix for 2007 systems: <a href="http://www.microsoft.com/en-us/download/details.aspx?id=21066">http://www.microsoft.com/en-us/download/details.aspx?id=21066</a><br />
<br />
<br />
<br />
To debug any code that runs after a delay, you have to attach Visual Studio to the timer service (owstimer.exe), not the w3w process. I do this by switching off "auto retract after debugging" in the "Sharepoint" page of the project's properties file and manually attaching to the OWSTIMER.EXE process.<br />
<br />
<iframe align="left" frameborder="0" marginheight="0" marginwidth="0" scrolling="no" src="http://rcm-na.amazon-adsystem.com/e/cm?t=thesim06-20&o=1&p=8&l=bpl&asins=0470529423&fc1=000000&IS2=1&lt1=_blank&m=amazon&lc1=0000FF&bc1=000000&bg1=FFFFFF&f=ifr" style="align: left; height: 245px; padding-right: 10px; padding-top: 5px; width: 131px;"></iframe><iframe align="left" frameborder="0" marginheight="0" marginwidth="0" scrolling="no" src="http://rcm-na.amazon-adsystem.com/e/cm?t=thesim06-20&o=1&p=8&l=bpl&asins=1430227818&fc1=000000&IS2=1&lt1=_blank&m=amazon&lc1=0000FF&bc1=000000&bg1=FFFFFF&f=ifr" style="align: left; height: 245px; padding-right: 10px; padding-top: 5px; width: 131px;"></iframe><iframe align="left" frameborder="0" marginheight="0" marginwidth="0" scrolling="no" src="http://rcm-na.amazon-adsystem.com/e/cm?t=thesim06-20&o=1&p=8&l=bpl&asins=B00413PHRI&fc1=000000&IS2=1&lt1=_blank&m=amazon&lc1=0000FF&bc1=000000&bg1=FFFFFF&f=ifr" style="align: left; height: 245px; padding-right: 10px; padding-top: 5px; width: 131px;"></iframe><iframe align="left" frameborder="0" marginheight="0" marginwidth="0" scrolling="no" src="http://rcm-na.amazon-adsystem.com/e/cm?t=thesim06-20&o=1&p=8&l=bpl&asins=0470888687&fc1=000000&IS2=1&lt1=_blank&m=amazon&lc1=0000FF&bc1=000000&bg1=FFFFFF&f=ifr" style="align: left; height: 245px; padding-right: 10px; padding-top: 5px; width: 131px;"></iframe>Unknownnoreply@blogger.com2tag:blogger.com,1999:blog-7799238193115123636.post-42483955066544564572012-06-08T15:50:00.000+01:002012-10-20T18:42:19.048+01:00Unexpected Error when deploying web part pages using Visual Studio solutionIt is good practice to wrap any Sharepoint web part pages you develop in a feature, and deploy them as a solution using Visual Studio. There are many walkthroughs on how to do this on the net, including this excellent <a href="http://technet.microsoft.com/en-us/library/cc262995.aspx">Microsoft effort</a> so I won't go into the details here.
<br />
<br />
If you follow this technique, the basic steps to developing a deployable feature are:<br />
<ol>
<li>Make your web part page in the Sharepoint front end or Sharepoint designer </li>
<li>Once development complete, export the page to a site solution file </li>
<li>Copy the appropriate section to your Sharepoint deployment soluting project
</li>
</ol>
At this point you will end up with something like this:
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://1.bp.blogspot.com/-YCCm4DrdtuM/T9INzBFIcSI/AAAAAAAAAJc/fmTaGOrzMQc/s1600/Solution%2B1%2B-%2Bfeature.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="324" src="http://1.bp.blogspot.com/-YCCm4DrdtuM/T9INzBFIcSI/AAAAAAAAAJc/fmTaGOrzMQc/s640/Solution%2B1%2B-%2Bfeature.png" width="640" /></a></div>
<br />
<br />
<br />
Note that my solution includes much more than just a web part page - it also has a masterpage, many images, CSS and javascript/jQuery - in other words all the things you need to make a nice custom web part page all in one deployable feature.
<br />
<br />
So everything is fine, but then you deploy the solution, and ARGHH! it throws an error! Worse, it throws an "Unexpected Error". This is the least useful error message you can imagine. So whats the solution?
<br />
<br />
Well after going through all the XML for my features I found the following:
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://2.bp.blogspot.com/-ELQV85I08PY/T9IPJy9eU1I/AAAAAAAAAJo/L3JCLc-BJlM/s1600/Solution%2B2%2B-%2BID.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="288" src="http://2.bp.blogspot.com/-ELQV85I08PY/T9IPJy9eU1I/AAAAAAAAAJo/L3JCLc-BJlM/s640/Solution%2B2%2B-%2BID.png" width="640" /></a></div>
<br />
The highlighted line is:<br />
<br />
<pre class="brush:csharp"><property name="ID" value="11"></property>
</pre>
<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://2.bp.blogspot.com/-FliRIJon-1w/T9IQGVKkAGI/AAAAAAAAAJ0/i4xEg6_OM84/s1600/Solution%2B3%2B-%2BNo%2BID.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><br /></a></div>
<property name="ID" value="11">This is the ID of the web part file <u>WHEN IT WAS EXPORTED.
</u><br /><br />
When you deploy this solution to a site, the ID of the file is whatever the next ID available (it's basically an incremental integer). Therefore by leaving in this piece of declarative XML, we are attempting to force the file to use this ID. This is what is causing the "Unexpected error" on deployment.
<br /><br />
Simply comment out this line and your solution will deploy. </property><br />
<br />
<a href="http://2.bp.blogspot.com/-FliRIJon-1w/T9IQGVKkAGI/AAAAAAAAAJ0/i4xEg6_OM84/s1600/Solution%2B3%2B-%2BNo%2BID.png" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="400" src="http://2.bp.blogspot.com/-FliRIJon-1w/T9IQGVKkAGI/AAAAAAAAAJ0/i4xEg6_OM84/s640/Solution%2B3%2B-%2BNo%2BID.png" width="640" /></a><property name="ID" value="11"> </property>
<iframe align="left" frameborder="0" marginheight="0" marginwidth="0" scrolling="no" src="http://rcm.amazon.com/e/cm?t=thesim06-20&o=1&p=8&l=bpl&asins=0470529423&fc1=000000&IS2=1&lt1=_blank&m=amazon&lc1=0000FF&bc1=000000&bg1=FFFFFF&f=ifr" style="align: left; height: 245px; padding-right: 10px; padding-top: 5px; width: 131px;"></iframe><iframe align="left" frameborder="0" marginheight="0" marginwidth="0" scrolling="no" src="http://rcm.amazon.com/e/cm?t=thesim06-20&o=1&p=8&l=bpl&asins=1430227818&fc1=000000&IS2=1&lt1=_blank&m=amazon&lc1=0000FF&bc1=000000&bg1=FFFFFF&f=ifr" style="align: left; height: 245px; padding-right: 10px; padding-top: 5px; width: 131px;"></iframe><iframe align="left" frameborder="0" marginheight="0" marginwidth="0" scrolling="no" src="http://rcm.amazon.com/e/cm?t=thesim06-20&o=1&p=8&l=bpl&asins=B00413PHRI&fc1=000000&IS2=1&lt1=_blank&m=amazon&lc1=0000FF&bc1=000000&bg1=FFFFFF&f=ifr" style="align: left; height: 245px; padding-right: 10px; padding-top: 5px; width: 131px;"></iframe><iframe align="left" frameborder="0" marginheight="0" marginwidth="0" scrolling="no" src="http://rcm.amazon.com/e/cm?t=thesim06-20&o=1&p=8&l=bpl&asins=0470888687&fc1=000000&IS2=1&lt1=_blank&m=amazon&lc1=0000FF&bc1=000000&bg1=FFFFFF&f=ifr" style="align: left; height: 245px; padding-right: 10px; padding-top: 5px; width: 131px;"></iframe>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-7799238193115123636.post-89353086879227285152011-11-25T01:09:00.001+00:002015-12-11T15:36:32.487+00:00Integration between Word 2003 and SharePoint 2010 using Managed Meta-dataYou cannot check out/edit/check in directly from Word 2003 if you are using managed meta-data in the list. Word 2003 does not seem to integrate properly with managed meta-data columns, and will refuse to check in the document.<br />
<br />
This leaves teh document in an unsaved, checked out state if a user attempts to edit it directly from Sharepoint.<br />
<br />
My only solution to this has been to create a new content type and remove the managed meta-data from it. <br />
<br />
<br />
<table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: auto; margin-right: auto; text-align: center;"><tbody>
<tr><td style="text-align: center;"><a href="http://www.yngoo.co.uk/top-tens/jewellery" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img alt="Carissima Gold 9 ct Yellow Gold Two-Row Diamond Cut Curb Bracelet of 21 cm 8.5-inch on www.yngoo.co.uk" border="0" src="http://4.bp.blogspot.com/-JgOrbukGHKE/Vmrp7CjdOwI/AAAAAAAAAW8/vSLhnQs8Kbw/s320/Carissima%2BGold%2B9%2Bct%2BYellow%2BGold%2BTwo-Row%2BDiamond%2BCut%2BCurb%2BBracelet%2Bof%2B21%2Bcm%2B8.5-inch.jpg" title="Carissima Gold 9 ct Yellow Gold Two-Row Diamond Cut Curb Bracelet of 21 cm 8.5-inch on www.yngoo.co.uk" /></a></td></tr>
<tr><td class="tr-caption" style="text-align: center;">Carissima Gold 9 ct Yellow Gold Two-Row Diamond Cut Curb Bracelet of 21 cm/8.5-inch</td></tr>
</tbody></table>Unknownnoreply@blogger.com1tag:blogger.com,1999:blog-7799238193115123636.post-51709159232540563242011-11-04T21:02:00.000+00:002011-11-04T21:02:55.856+00:00C# function to get the Content Type GUID from a Sharepoint list using web servicesSimple helper function to get the GUID of a list from Sharepoint web services.<br />
<br />
Note that in the code below I have a class level object pointing to the Lists.asmx web service called m_listService already established , but I have left in the code to establish this connection in the comments as an example.<br />
<br />
<pre class="brush:csharp">string GetListContentTypeGuid(string listName, string listID, string contentTypeName)
{
string defaultGuid = "";
try
{
//ListsService.Lists listService = new ListsService.Lists();
//listService.Credentials = System.Net.CredentialCache.DefaultCredentials;
//XmlNode ndList = listService.GetList(fileInfo.m_listInfo.m_listName);
//XmlNode ndVersion = ndList.Attributes["Version"];
XmlNode contentTypes = m_listService.GetListContentTypes(listID, "anything");
// Loop through the fields
foreach (XmlNode node in contentTypes)
{
System.Diagnostics.Debug.Print(node.Attributes["Name"].Value.ToString());
if (node.Attributes["Name"].Value.ToString() == contentTypeName)
{
defaultGuid = node.Attributes["ID"].Value.ToString();
break;
}
}
}
catch (Exception ex)
{
throw new Exception("ERROR: Reading content types from target site.\r\n"
+ ex.Message + "\r\nDetails: " + ex.InnerException + "\r\n" +
"Check the settings file to ensure that the list settings match the target site.", ex);
}
return defaultGuid;
}
</pre>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-7799238193115123636.post-81845864636371205662011-07-20T00:00:00.004+01:002015-07-27T22:25:41.849+01:00Sharepoint 2010 managed meta-data taxonomy field data using web services<iframe align="left" frameborder="0" marginheight="0" marginwidth="0" scrolling="no" src="http://rcm-na.amazon-adsystem.com/e/cm?t=thesim06-20&o=1&p=8&l=bpl&asins=B0040SXV5E&fc1=000000&IS2=1&lt1=_blank&m=amazon&lc1=0000FF&bc1=000000&bg1=FFFFFF&f=ifr" style="align: left; height: 245px; padding-right: 10px; padding-top: 5px; width: 131px;"></iframe>Sharepoint 2010 includes a very useful new concept: managed meta-data. This allows you to build taxonomic hierarchies, and provide document routing based on the meta-data.<br />
<br />
Unfortunately, it seems that using this field type using a web service call is extremely complicated, and hardly seems to be documented at all (this is so typical of Sharepoint stuff...). Microsoft have given us a new web service class ("taxonomyclientservice") but there hardly any documentation on it all (<a href="http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.taxonomy.webservices.taxonomyclientservice.aspx">http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.taxonomy.webservices.taxonomyclientservice.aspx</a>).<br />
<br />
<br />
<br />
Here is an example that I have managed to get working (after MUCH trial and error) that will hopefully help you to do the following:<br />
<ol><li> opens a list using the Lists web service, </li>
<li>iterates through the fields in the default content type for the list (you can remove this bit and just iterate through the fields in the list if you like),</li>
<li>if it finds a "TaxonomyFieldType" field, it then gets the "Shared Service ID" (GUID of managed meta-data service) and Term Set ID (GUID of term set defined on this field) required to run the Taxonomy web service call</li>
<li>sets up the CAML to run the Taxonomy web service call,</li>
<li>retrieves the taxonomy data for that field in XML. </li>
</ol> I do not try to analyse what the taxonomy XML means - that is for another day! <br />
<br />
Note that all my web service proxies are called "ListService" and "Taxonomys".<br />
<br />
<pre class="brush:csharp">//get list data from webservice
ListService.Lists listService = new ListService.Lists();
// Use your own list name
XmlNode list = listService.GetList("My List Name");
// Let's have a look at it
System.Diagnostics.Debug.Print(list.OuterXml);
// Get the content types for this list
//Get our defined content type (see previous post on how to do this - you need your own values here!)
string contentTypeGuid = GetListContentTypeGuid("My List Name", "{GUID}", "My Content Type");
// Now get content type definition
XmlNode contentType = m_listService.GetListContentType(mylistinfo.m_listName, contentTypeGuid);
//Get the fields from the content type
XmlNodeList nodes = RunXPathQuery(contentType, "//sp:Field");
// Loop through the fields in the content type
foreach (XmlNode node in nodes)
{
// This stuff just sets up some variables based on the content type and skips over hidden fields
string Name = node.Attributes["Name"].Value;
if (Name == "ContentType") continue;
string ID = node.Attributes["ID"].Value;
if (string.IsNullOrEmpty(ID) || string.IsNullOrEmpty(Name))
continue;
bool hidden = false;
bool ReadOnly = false;
try { hidden = Convert.ToBoolean(node.Attributes["Hidden"].Value); }
catch { }
try { ReadOnly = Convert.ToBoolean(node.Attributes["ReadOnly"].Value); }
catch { }
if (hidden || ReadOnly)
continue;
string ShowInFileDlg = "";
try { ShowInFileDlg = node.Attributes["ShowInFileDlg"].Value; }
catch { }
if (ShowInFileDlg == "FALSE") continue;
string StaticName = node.Attributes["StaticName"].Value;
string DisplayName = node.Attributes["DisplayName"].Value;
// Now we can check the "Type" attribute
string FieldType = node.Attributes["Type"].Value;
if (FieldType == "TaxonomyFieldType")
{
// WE HAVE A TAXONOMY FIELD!!!
// Lets get the shared service ID and the termset ID from teh List schema
string sharedServiceIds = "";
string termSetId = "";
// jump a few nodes to get the correct bit of the schema (included for clarity)
XmlNode childNode = node.ChildNodes[1];
XmlNode termNodes = childNode.ChildNodes[0];
//Loop through these nodes until we find the information we need
foreach (XmlNode term in termNodes.ChildNodes)
{
System.Diagnostics.Debug.Print("term = " + term.ChildNodes[0].InnerText.ToString());
if (term.ChildNodes.Count > 1)
{
System.Diagnostics.Debug.Print("value = " + term.ChildNodes[1].InnerText.ToString());
if (term.ChildNodes[0].InnerText.ToString() == "SspId")
{
// Get shared services ID from list
sharedServiceIds = term.ChildNodes[1].InnerText.ToString();
}
if (term.ChildNodes[0].InnerText.ToString() == "TermSetId")
{
// Get Term Set ID from list
termSetId = term.ChildNodes[1].InnerText.ToString();
}
}
}
int lcid = System.Globalization.CultureInfo.CurrentUICulture.LCID;
string serverTermSetTimeStampXml = "";
string termStoreIds = "<termStoreIds><termStoreId>" + sharedServiceIds + "</termStoreId></termStoreIds>";
string termSetIds = "<termSetIds><termSetId>" + termSetId + "</termSetId></termSetIds>";
//Always set timestamp to this
string oldtimestamp = "<timeStamps><timeStamp>633992461437070000</timeStamp></timeStamps>";
//Always set version to 1
string clientVersion = "<versions><version>1</version></versions>";
string timeStamp = "";
// Taxonomy web service!!
Taxonomys.Taxonomywebservice taxonomy = new Taxonomys.Taxonomywebservice();
taxonomy.Credentials = System.Net.CredentialCache.DefaultCredentials;
string resultXML = taxonomy.GetTermSets(termStoreIds, termSetIds, lcid, oldtimestamp, clientVersion, out timeStamp);
//Loop through the XML
string termValue = "MHA";
string termGUID = "";
string parentID = "";
XmlDocument termSetXML = new XmlDocument();
termSetXML.LoadXml(resultXML);
XmlNodeList terms = termSetXML.GetElementsByTagName("T");
foreach (XmlNode term in terms)
{
string termName = term.FirstChild.FirstChild.Attributes["a32"].Value;
termGUID = term.Attributes["a9"].Value;
try
{
parentID = term.Attributes["a25"].Value;
}
catch (Exception)
{
parentID = "";
}
System.Diagnostics.Debug.Print("termName = " + termName + ", termGUID = " + termGUID + ", parentID = " + parentID);
}
}
}
</pre><br />
If you would like to know how to analyse the attribute codes returned in the XML, then take a look at this blog entry: <a href="http://blogs.solidq.com/sharepoint/Post.aspx?ID=37&title=SharePoint+2010%2C+Managed+Metadata%2C+TaxonomyClientService+in+depth">http://blogs.solidq.com/sharepoint/Post.aspx?ID=37&title=SharePoint+2010%2C+Managed+Metadata%2C+TaxonomyClientService+in+depth</a><br />
<br />
<iframe align="left" frameborder="0" marginheight="0" marginwidth="0" scrolling="no" src="http://rcm-na.amazon-adsystem.com/e/cm?t=thesim06-20&o=1&p=8&l=bpl&asins=0470529423&fc1=000000&IS2=1&lt1=_blank&m=amazon&lc1=0000FF&bc1=000000&bg1=FFFFFF&f=ifr" style="align: left; height: 245px; padding-right: 10px; padding-top: 5px; width: 131px;"></iframe><iframe align="left" frameborder="0" marginheight="0" marginwidth="0" scrolling="no" src="http://rcm-na.amazon-adsystem.com/e/cm?t=thesim06-20&o=1&p=8&l=bpl&asins=1430227818&fc1=000000&IS2=1&lt1=_blank&m=amazon&lc1=0000FF&bc1=000000&bg1=FFFFFF&f=ifr" style="align: left; height: 245px; padding-right: 10px; padding-top: 5px; width: 131px;"></iframe><iframe align="left" frameborder="0" marginheight="0" marginwidth="0" scrolling="no" src="http://rcm-na.amazon-adsystem.com/e/cm?t=thesim06-20&o=1&p=8&l=bpl&asins=B00413PHRI&fc1=000000&IS2=1&lt1=_blank&m=amazon&lc1=0000FF&bc1=000000&bg1=FFFFFF&f=ifr" style="align: left; height: 245px; padding-right: 10px; padding-top: 5px; width: 131px;"></iframe><iframe align="left" frameborder="0" marginheight="0" marginwidth="0" scrolling="no" src="http://rcm-na.amazon-adsystem.com/e/cm?t=thesim06-20&o=1&p=8&l=bpl&asins=0470888687&fc1=000000&IS2=1&lt1=_blank&m=amazon&lc1=0000FF&bc1=000000&bg1=FFFFFF&f=ifr" style="align: left; height: 245px; padding-right: 10px; padding-top: 5px; width: 131px;"></iframe>Unknownnoreply@blogger.com3tag:blogger.com,1999:blog-7799238193115123636.post-759792607108676822011-06-02T23:34:00.003+01:002011-11-25T01:06:46.635+00:00Mark ContentType as default in Sharepoint Designer 2010<iframe align="left" frameborder="0" marginheight="0" marginwidth="0" scrolling="no" src="http://rcm.amazon.com/e/cm?t=thesim06-20&o=1&p=8&l=bpl&asins=0470643161&fc1=000000&IS2=1&lt1=_blank&m=amazon&lc1=0000FF&bc1=000000&bg1=FFFFFF&f=ifr" style="align: left; height: 245px; padding-right: 10px; padding-top: 5px; width: 131px;"></iframe>This is pretty simple stuff, but I just spent ten minutes looking at Sharepoint Designer trying to figure out where I clicked to change the default content type on a list! I guess I'm just not used to the ribbon :)<br />
<br />
Google didn't help (probably too easy a problem for it) so I thought I would right this up in case anyone else was suffering.<br />
<br />
I've created a content type, here it is associated with a list in Sharepoint Designer:<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://4.bp.blogspot.com/-YxBKvJltFmI/TegOdZcU8gI/AAAAAAAAAIw/gkw7Lfd4Gls/s1600/ContentTypesPanel.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="103" src="http://4.bp.blogspot.com/-YxBKvJltFmI/TegOdZcU8gI/AAAAAAAAAIw/gkw7Lfd4Gls/s320/ContentTypesPanel.png" width="320" /></a></div>
But how do I make it default? I finally spotted the option after clicking through endless options in SP designer - the trick is to highlight the content type (and not click on its name to see the content type editor!) and the look at the ribbon:<br />
<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://3.bp.blogspot.com/-VwBkSHCicjA/TegO3QDye6I/AAAAAAAAAI0/s7kk9AI8fJ0/s1600/ContentTypesSetAsDefault.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="131" src="http://3.bp.blogspot.com/-VwBkSHCicjA/TegO3QDye6I/AAAAAAAAAI0/s7kk9AI8fJ0/s320/ContentTypesSetAsDefault.png" width="320" /></a></div>
Hurray! There it is.<br />
Click on this and we have a new default:<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://1.bp.blogspot.com/-ZAhbJoo7XvM/TegPBoDRSYI/AAAAAAAAAI4/luO6XQukwfQ/s1600/ContentTypesPanelNowDefault.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="120" src="http://1.bp.blogspot.com/-ZAhbJoo7XvM/TegPBoDRSYI/AAAAAAAAAI4/luO6XQukwfQ/s320/ContentTypesPanelNowDefault.png" width="320" /></a></div>
I hope this helps some other Sharepoint 2010 newbie.<br />
<iframe align="left" frameborder="0" marginheight="0" marginwidth="0" scrolling="no" src="http://rcm.amazon.com/e/cm?t=thesim06-20&o=1&p=8&l=bpl&asins=0470529423&fc1=000000&IS2=1&lt1=_blank&m=amazon&lc1=0000FF&bc1=000000&bg1=FFFFFF&f=ifr" style="align: left; height: 245px; padding-right: 10px; padding-top: 5px; width: 131px;"></iframe><iframe align="left" frameborder="0" marginheight="0" marginwidth="0" scrolling="no" src="http://rcm.amazon.com/e/cm?t=thesim06-20&o=1&p=8&l=bpl&asins=1430227060&fc1=000000&IS2=1&lt1=_blank&m=amazon&lc1=0000FF&bc1=000000&bg1=FFFFFF&f=ifr" style="align: left; height: 245px; padding-right: 10px; padding-top: 5px; width: 131px;"></iframe><iframe align="left" frameborder="0" marginheight="0" marginwidth="0" scrolling="no" src="http://rcm.amazon.com/e/cm?t=thesim06-20&o=1&p=8&l=bpl&asins=B00413PHRI&fc1=000000&IS2=1&lt1=_blank&m=amazon&lc1=0000FF&bc1=000000&bg1=FFFFFF&f=ifr" style="align: left; height: 245px; padding-right: 10px; padding-top: 5px; width: 131px;"></iframe><br />
<iframe align="left" frameborder="0" marginheight="0" marginwidth="0" scrolling="no" src="http://rcm.amazon.com/e/cm?t=thesim06-20&o=1&p=8&l=bpl&asins=0735627339&fc1=000000&IS2=1&lt1=_blank&m=amazon&lc1=0000FF&bc1=000000&bg1=FFFFFF&f=ifr" style="align: left; height: 245px; padding-right: 10px; padding-top: 5px; width: 131px;"></iframe>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-7799238193115123636.post-15616227756320511652011-03-10T21:51:00.001+00:002015-12-11T16:04:50.770+00:00VBA code to check in a document to Sharepoint and set meta data
<div style="vertical-align: top;">
<table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: auto; margin-right: auto; text-align: center;"><tbody>
<tr><td style="text-align: center;"><a href="http://www.yngoo.co.uk/top-tens/jewellery" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img alt="Carissima Gold 9 ct Yellow Gold Two-Row Diamond Cut Curb Bracelet of 21 cm 8.5-inch on www.yngoo.co.uk" border="0" src="http://4.bp.blogspot.com/-JgOrbukGHKE/Vmrp7CjdOwI/AAAAAAAAAW8/vSLhnQs8Kbw/s320/Carissima%2BGold%2B9%2Bct%2BYellow%2BGold%2BTwo-Row%2BDiamond%2BCut%2BCurb%2BBracelet%2Bof%2B21%2Bcm%2B8.5-inch.jpg" title="Carissima Gold 9 ct Yellow Gold Two-Row Diamond Cut Curb Bracelet of 21 cm 8.5-inch on www.yngoo.co.uk" /></a></td></tr>
<tr><td class="tr-caption" style="text-align: center;">Carissima Gold 9 ct Yellow Gold Two-Row Diamond Cut Curb Bracelet of 21 cm/8.5-inch</td></tr>
</tbody></table>
</div>
<br />
<br />
The following VBA code will upload a file to Sharepoint 2007 using a web service, and then sest some meta data (the title) for that file in the document library.<br />
Remember, you need to have installed the VBA <a href="http://msdn.microsoft.com/en-us/library/aa192537%28office.11%29.aspx">Microsoft Office 2003 Web Services Toolkit</a> and created a reference to the web service in your project before this will work. See these previous posts for more information on calling Sharepoint web services from VBA:<br />
<ul>
<li> <a href="http://the-simple-programmer.blogspot.com/2010/04/vba-code-to-iterate-through-results-of.html">VBA code to iterate through the results of GetListCollection web service from Sharepoint 2007</a> </li>
<li><a href="http://the-simple-programmer.blogspot.com/2010/03/set-sharepoint-meta-data-from-vba-using.html">Set Sharepoint meta-data from VBA using updatelist web service</a></li>
</ul>
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<pre class="brush: vb">' Change these values to your own
sSourceFile = "C:\mtest.doc" ' File to upload
sTargetFile = "HTTP://my sharepoint site/Shared%20Documents/mytest.doc" ' Target site, document library and file name
' First set up DOM document containing fields
Dim xmlDoc As New MSXML2.DOMDocument30
xmlDoc.async = False
xmlText = "<root>" & _
"<Batch OnError='Continue' ListVersion='" & iVersionNumber & "' PreCalc='TRUE' xmlns=''>" & _
"<Method ID='1' Cmd='Update'>" & _
"<Field Name='ID' />" & _
"<Field Name='FileRef'>" & sTargetFile & "</Field>" & _
"<Field Name='Title'>Uploaded from VBA</Field>" & _
"</Method>" & _
"</Batch>" & _
"</root>"
xmlDoc.LoadXml (xmlText)
Debug.Print xmlText
' This bit is just for testing
If xmlDoc.parseError.errorCode <> 0 Then
Set myErr = xmlDoc.parseError
MsgBox (myErr.reason)
GoTo fnUpload_Error
Else
MsgBox xmlDoc.XML
End If
' Set up IXMLDOMNodeList
Dim myXMLNodeList As MSXML2.IXMLDOMNodeList
Dim root As MSXML2.IXMLDOMElement
Set root = xmlDoc.documentElement
Set myXMLNodeList = root.ChildNodes
' Create an array of IXMLDOMNodeList
Dim ar_Fields(1) As IXMLDOMNodeList
Set ar_Fields(0) = myXMLNodeList
'Debug.Print "ar_Fields(0) = " & ar_Fields(0)
' Now set up an array of strings to hold the URL
Dim ar_URL(1) As String
ar_URL(0) = sTargetFile
Debug.Print "ar_URL(0) = " & ar_URL(0)
' Set up the results object
Dim myresults() As struct_CopyResult
' Set up the byte array and read the source file into it
Dim ar_Stream() As Byte
ar_Stream = ReadFile(sSourceFile)
' NOW CALL WEB SERVICE
' The follwoing comes from the "Microsoft Office 2003 Web Services Toolkit":
'"ar_DestinationUrls" is an array with elements defined as String
'"ar_Fields" is an array with elements defined as IXMLDOMNodeList
'"ar_Stream" is an array with elements defined as Byte
'"ar_Results" is an array with elements defined as struct_CopyResult
'See Complex Types: Arrays in Microsoft Office 2003 Web Services Toolkit Help
'for details on implementing arrays.
documentId = copyws.wsm_CopyIntoItems(sDocumentPath, ar_URL, ar_Fields, ar_Stream, myresults)
Debug.Print "DocumentID = " & documentId
Dim updateReturn As IXMLDOMNodeList
Set updateReturn = listws.wsm_UpdateListItems(sListID, myXMLNodeList)
Dim xmlReturnDoc As New MSXML2.DOMDocument30
If (updateReturn.Length > 0) Then
xmlReturnDoc.LoadXml (updateReturn.Item(0).XML)
Dim errorText As String
errorText = xmlReturnDoc.Text
If (errorText <> "0x00000000") Then
MsgBox ("Error: Cannot upload load file to Sharepoint." & vbCrLf & _
" : " & errorText & vbCrLf & Err.Description & vbCrLf )
End If
End If
' Uncomment for debug information.
'MsgBox ("Return XML = " & xmlReturnDoc.XML)
</pre>
<br />
I use the following VBA to read the target file in as a byte array:<br />
<br />
<pre class="brush: vb">Private Function ReadFile(ByVal strFileName As String, Optional ByVal lngStartPos As Long = 1, Optional ByVal lngFileSize As Long = -1) As Byte()
Dim FilNum As Integer
FilNum = FreeFile
Open strFileName For Binary As #FilNum
If lngFileSize = -1 Then
ReDim ReadFile(LOF(FilNum) - lngStartPos)
Else
ReDim ReadFile(lngFileSize - 1)
End If
Get #FilNum, lngStartPos, ReadFile
Close #FilNum
End Function
</pre>
Unknownnoreply@blogger.com9tag:blogger.com,1999:blog-7799238193115123636.post-51084887803481002562011-02-27T23:34:00.007+00:002011-06-15T12:52:00.906+01:00Deploy Office 2003 VSTO add in to All Users using Visual Studio 2008<iframe align="left" frameborder="0" marginheight="0" marginwidth="0" scrolling="no" src="http://rcm.amazon.com/e/cm?t=thesim06-20&o=1&p=8&l=bpl&asins=B000OZ0NHQ&fc1=000000&IS2=1&lt1=_blank&m=amazon&lc1=0000FF&bc1=000000&bg1=FFFFFF&f=ifr" style="height: 245px; padding-right: 10px; padding-top: 5px; width: 131px;"></iframe>Deploying VSTO add-ins can be a real pain, at least if you are not using 2010. Having just successfully deployed my first add-in, I thought it would be useful to explain how I did and the resources I used.<br />
<br />
Firstly, it is important that you follow the instructions for the appropriate version of Office and Visual Studio that you are using. My example is for a legacy solution using Office 2003, created with VSTO Second Edition (Visual Studio 2008). The general principles are the same for other editions, but the specifics may be subtly different.<br />
<br />
To get started, look at the walkthrough here:<br />
<br />
<a href="http://msdn.microsoft.com/en-us/library/bb332052.aspx">http://msdn.microsoft.com/en-us/library/bb332052.aspx</a><br />
This is another useful collection of resources:<br />
<a href="http://xldennis.wordpress.com/2007/03/04/creating-and-deploying-managed-com-add-ins-with-vsto-2005-se-part-vi/">http://xldennis.wordpress.com/2007/03/04/creating-and-deploying-managed-com-add-ins-with-vsto-2005-se-part-vi/</a><br />
<br />
This explains how to configure a deployment project in Visual Studio 2008 and set up the additional security package required to grant the add-in full trust. I would recommend you follow the steps in here to create a brand new simple package and get that working first. I created a simple Word 2003 add-in package to test, rather than the suggested Outlook.<br />
<br />
The security package can be downloaded from MSDN here:<br />
<a href="http://code.msdn.microsoft.com/VSTO3MSI">http://code.msdn.microsoft.com/VSTO3MSI</a><br />
Unpackage the download and you should find a .SLN file that has everything pre-configured. Copy the "SetSecurity" package from here and add it to your solution as explained in the walkthrough. Configure the Setup project's outputs as described, and you should end up with a package that looks something like this:<br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://lh3.googleusercontent.com/-MQDK2js4oPQ/TWrbqDyY_ZI/AAAAAAAAAIk/NvbFW2EgrKI/s1600/Word2003AddInOutputs.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="175" src="https://lh3.googleusercontent.com/-MQDK2js4oPQ/TWrbqDyY_ZI/AAAAAAAAAIk/NvbFW2EgrKI/s320/Word2003AddInOutputs.png" width="320" /></a></div><br />
<br />
Once you have built your setup package, you can find the .MSI and .EXE files in solution bin/debug (or bin/release) directory. Run the .exe and you should have installed your add-in onto your development machine. Run the appropriate Office application to check that the pop up message appears to confirm this. Your development computer should have all the pre-requisites installed, so if this doesn't work you have probably missed something in the walkthrough, or have perhaps used an incorrect version of the setup project, so go back and double check everything. It is vital that you get a simple version working at this stage, or it will cause you all sorts of problems down the line.<br />
<br />
Once you have a simple install project working you can go about making it available to ALL USERS on the machine. This is not covered in the walkthrough, although there is mention of it for newer versions of Office in this excellent blog here:<br />
<a href="http://blogs.msdn.com/b/mshneer/archive/2008/04/24/deploying-your-vsto-add-in-to-all-users-part-iii.aspx">http://blogs.msdn.com/b/mshneer/archive/2008/04/24/deploying-your-vsto-add-in-to-all-users-part-iii.aspx</a><br />
<br />
In Office 2003, deploying to all users is actually really simple: all we have to do is copy the registry keys that have automatically been generated for us by Visual Studio in the Setup project from HKCU to HKLM. In practice, this mean highlighting your setup project (called Word2003AddInSetup in my example), right click and choose "View" and "Registry":<br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://lh6.googleusercontent.com/-fVEdRRIqMLo/TWrdj96gtJI/AAAAAAAAAIo/njiyW8duo40/s1600/Word2003AddInRegistry.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="152" src="https://lh6.googleusercontent.com/-fVEdRRIqMLo/TWrdj96gtJI/AAAAAAAAAIo/njiyW8duo40/s320/Word2003AddInRegistry.png" width="320" /></a></div>This will open up the registry editor. Now, expand all, and renambe the "Software" key in HKLM to some temporary name (say "SoftwareTESTTESTTEST").<br />
<br />
You can now drag the "Software" key from the HKCU leaf to the HKLM leaf. Once done, drag your renamed "SoftwareTESTTESTTEST" key from HKLM to HKCU, and rename this back to "Software". You should now have something that looks like this:<br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://lh4.googleusercontent.com/-D40jkaezepY/TWreQn1vhWI/AAAAAAAAAIs/o_mZcVPe3-c/s1600/Word2003AddInHKLM.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="174" src="https://lh4.googleusercontent.com/-D40jkaezepY/TWreQn1vhWI/AAAAAAAAAIs/o_mZcVPe3-c/s320/Word2003AddInHKLM.png" width="320" /></a></div>One thing that is not really very well documented at all, and kept me scratching my head for many days, is that you must set the "InstallAllUsers" property on the setup package to "True". This is obvious, but not mentioned anywhere! <br />
<div class="separator" style="clear: both; text-align: center;"><a href="http://4.bp.blogspot.com/-Fam24tre8VE/TficyFkbVtI/AAAAAAAAAI8/tAA9BKuO_ME/s1600/InstallAllUsers.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="320" src="http://4.bp.blogspot.com/-Fam24tre8VE/TficyFkbVtI/AAAAAAAAAI8/tAA9BKuO_ME/s320/InstallAllUsers.png" width="220" /></a></div><br />
<br />
That's it! Build your setup solution and re-install it (you will have to un-install your original version first). You should now find that any user that logs into the machine will have the add in enabled.<br />
<br />
Please note that if you are using Office 2007, this technique does not work - you will have to refer to the blog post linked above to learn how to set up the appropriate registry keys.<br />
<br />
<iframe align="left" frameborder="0" marginheight="0" marginwidth="0" scrolling="no" src="http://rcm.amazon.com/e/cm?t=thesim06-20&o=1&p=8&l=bpl&asins=1598220470&fc1=000000&IS2=1&lt1=_blank&m=amazon&lc1=0000FF&bc1=000000&bg1=FFFFFF&f=ifr" style="height: 245px; padding-right: 10px; padding-top: 5px; width: 131px;"></iframe><iframe align="left" frameborder="0" marginheight="0" marginwidth="0" scrolling="no" src="http://rcm.amazon.com/e/cm?t=thesim06-20&o=1&p=8&l=bpl&asins=0321533216&fc1=000000&IS2=1&lt1=_blank&m=amazon&lc1=0000FF&bc1=000000&bg1=FFFFFF&f=ifr" style="height: 245px; padding-right: 10px; padding-top: 5px; width: 131px;"></iframe>Unknownnoreply@blogger.com1tag:blogger.com,1999:blog-7799238193115123636.post-79866926035344424742011-01-26T00:03:00.000+00:002011-01-26T00:03:41.106+00:00Sharepoint 2007 Batch Update example using web services and CAML<iframe align="left" frameborder="0" marginheight="0" marginwidth="0" scrolling="no" src="http://rcm.amazon.com/e/cm?t=thesim06-20&o=1&p=8&l=bpl&asins=1590594568&fc1=000000&IS2=1&lt1=_blank&m=amazon&lc1=0000FF&bc1=000000&bg1=FFFFFF&f=ifr" style="height: 245px; padding-right: 10px; padding-top: 5px; width: 131px;"></iframe>Here is an example of running a batch update process on Sharepoint 2007 using web services. It was written in C# in Visual Studio 2008.<br />
<br />
In this example, I take the value of a text field "Date_x0020_of_x0020_Birth", turn this into a DateTime value, and then use this to update the the value of a DateTime field "Date_x0020_of_x0020_Birth0". Obviously this section of the code will not be particularly generalisable, however I have left in all the code in order to show you the principles involved, and hopefully you will find it useful in building your own batch routines.<br />
<br />
In order to get it running, you must create a reference to the Sharepoint Lists web service and call it "ListsService". The SDK shows you how to do this, and is available here: <a href="http://www.microsoft.com/downloads/en/details.aspx?FamilyId=6D94E307-67D9-41AC-B2D6-0074D6286FA9&displaylang=en">http://www.microsoft.com/downloads/en/details.aspx?FamilyId=6D94E307-67D9-41AC-B2D6-0074D6286FA9&displaylang=en</a><br />
<br />
The GetListItems() method of the Lists web service is used to query the data, and the UpdateListItems() method is used to update items.<br />
<br />
I used an XPathNavigator object to filter only rows that contain data. You could just loop through the nodes if you prefer.<br />
<br />
CAML is used to query the Sharepoint list and look for items where the "Date_x0020_of_x0020_Birth" is null. Tailor this to your own needs.<br />
For CAML reference, look at the MSDN article here: <a href="http://msdn.microsoft.com/en-us/library/lists.lists.getlistitems%28v=office.12%29.aspx">http://msdn.microsoft.com/en-us/library/lists.lists.getlistitems%28v=office.12%29.aspx</a><br />
<br />
The CAML update command uses owshiddenversion, and so is useful in situations where versioning is enabled. Lists without versioning do not need this field.<br />
<br />
If the UpdateListItems command returns an error, in my experience this is usually caused by using an incorrect internal name for a field. You may need to add the <span class="pBody postableBody">URI prefix "urn:schemas-microsoft-com<wbr></wbr>:office:of<wbr></wbr>fice#" to the field name (e.g. change line 42 to something like: "<Field Name=\"urn:schemas-microsoft-com<wbr></wbr>:office:of<wbr></wbr>fice#{4}\">{5}</Field>").</span><br />
<br />
Full code:<br />
<pre class="brush:csharp">using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using System.IO;
using System.Xml;
using System.Xml.XPath;
using System.Net;
namespace BatchUpdateDOB
{
class Program
{
static string LogFile = "D:\\BatchUpdateLog.txt"; // Log file location
static void Main(string[] args)
{
try
{
StatusMessage("Writing log file to: " + LogFile);
// Set up the variables to be used.
StringBuilder methodBuilder = new StringBuilder();
string batch = string.Empty;
DateTime currentDate = DateTime.Now;
string formattedDate = SPUtility.CreateISO8601DateTimeFromSystemDateTime(currentDate);
string fieldToReference = "Date_x0020_of_x0020_Birth";
string fieldToUpdate = "Date_x0020_of_x0020_Birth0";
string batchFormat = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<ows:Batch OnError=\"Return\">{0}</ows:Batch>";
// CAML update command for web service
string methodFormat = "<Method ID=\"1\" Cmd=\"Update\">" +
"<Field Name=\"ID\">{1}</Field>" +
"<Field Name=\"FileRef\">{2}</Field>" +
"<Field Name=\"owshiddenversion\">{3}</Field>" +
"<Field Name=\"{4}\">{5}</Field>" +
"</Method>";
//UPDATE THESE TWO LINES TO SITE SPECIFIC VALUES
string siteName = "http://<your site root uri here>";
string listName = "<your list name here>";
//string viewName = ""; // No need for viewname
int rowLimit = 10; //The number of items returned per batch (not used)
StatusMessage("Processing " + siteName + ", List: " + listName + "...");
//Web service setup
//ListService should be the name of your web service reference
ListService.Lists listService = new ListService.Lists();
listService.Credentials = System.Net.CredentialCache.DefaultCredentials;
listService.Url = siteName + "/_vti_bin/Lists.asmx";
//Build CAML query to search for records
XmlDocument camlDocument = new XmlDocument();
XmlNode queryNode = camlDocument.CreateElement("Query");
//queryNode.InnerXml = "<Where><IsNull><FieldRef Name='Date_x0020_of_x0020_Birth'/></IsNull></Where>";
//queryNode.InnerXml = "<OrderBy><FieldRef Name='Country' /></OrderBy>";
XmlNode viewFieldsNode = camlDocument.CreateElement("ViewFields");
viewFieldsNode.InnerXml = "<FieldRef Name='Title' />" +
"<FieldRef Name='owshiddenversion' />" +
"<FieldRef Name='" + fieldToReference + "' />" +
"<FieldRef Name='" + fieldToUpdate + "' />" +
"<FieldRef Name='FileRef' />";
XmlNode queryOptionsNode = camlDocument.CreateElement("QueryOptions");
queryOptionsNode.InnerXml = "<ViewAttributes Scope=\"Recursive\" /><IncludeMandatoryColumns>True</IncludeMandatoryColumns>";
// Get the GUID of the list
XmlNode ndListView = listService.GetListAndView(listName, "");
string listGuid = ndListView.ChildNodes[0].Attributes["Name"].Value;
string listVersion = ndListView.ChildNodes[0].Attributes["Version"].Value;
// Run the CAML query
XmlNode resultNode = listService.GetListItems(listGuid, null, queryNode, viewFieldsNode, rowLimit.ToString(), queryOptionsNode, null);
// If you want to put a rowlimit on, then use this command:
//XmlNode resultNode = listService.GetListItems(listGUID, null, queryNode, viewFieldsNode, rowLimit.ToString(), queryOptionsNode, null);
long totalRecords = 0;
//string itemDOB;
string dob;
DateTime dtDOB;
string owsHiddenVersion;
string fullFileRef;
string owsFileRef;
// Create xpath navigator
XPathNavigator navigator = resultNode.CreateNavigator();
// Set up namespace manager for XPath
XmlNamespaceManager ns = new XmlNamespaceManager(navigator.NameTable);
ns.AddNamespace("rs", "urn:schemas-microsoft-com:rowset");
ns.AddNamespace("z", "#RowSetSchema");
// Select only the z:row nodes
XmlNodeList nodes = resultNode.SelectNodes("//*[name()='z:row'] ", ns);
// Iterate through the returned nodes
foreach (XmlNode node in nodes)
{
string itemID = node.Attributes["ows_ID"].InnerText;
try
{
dob = node.Attributes["ows_" + fieldToReference].InnerText;
owsHiddenVersion = node.Attributes["ows_" + "owshiddenversion"].InnerText;
owsFileRef = node.Attributes["ows_" + "FileRef"].InnerText;
// For some reason my data is returned in the format: 2#/listname/path,
// where 2 seems to be an id or version number, and listname/path points to the file in relation to the root site.
// The following strips that out and gets the full path (required for the CAML update)
fullFileRef = siteName + "/" + owsFileRef.Remove(0, owsFileRef.IndexOf("#") + 1);
}
catch(Exception ex)
{
// Ignore this row
//StatusMessage("ERROR: Cannot process: " + node.InnerXml.ToString() + ": " + ex.Message); // If you want to see why, uncomment
continue;
}
if (String.IsNullOrEmpty(dob)) continue; // Ignore list items with no value
dtDOB = Convert.ToDateTime("01/01/1900"); // Set default value for dates before 1900
// Convert date text to DateTime
try
{
dtDOB = Convert.ToDateTime(dob);
}
catch (Exception ex)
{
StatusMessage("Cannot process: " + siteName + "/" + fullFileRef + " DOB: " + dob + ". Setting to 01/01/1900. " + ex.Message);
}
MessageToFile("Processing: " + fullFileRef + ", DOB = " + dob);
methodBuilder.AppendFormat(methodFormat, listGuid, itemID, fullFileRef, owsHiddenVersion, fieldToUpdate, SPUtility.CreateISO8601DateTimeFromSystemDateTime(dtDOB));
// Put the pieces together.
batch = string.Format(batchFormat, methodBuilder.ToString());
//MessageToFile(batch);
//Build CAML command to update using Web service
XmlDocument xmlDoc = new XmlDocument();
XmlElement elBatch = xmlDoc.CreateElement("Batch");
elBatch.SetAttribute("OnError", "Continue");
elBatch.SetAttribute("ListVersion", listVersion.ToString());
elBatch.SetAttribute("ViewName", "");
elBatch.InnerXml = methodBuilder.ToString();
// This line runs the CAML update command
XmlNode updatesResponse = listService.UpdateListItems(listGuid, elBatch);
if (updatesResponse.FirstChild.FirstChild.InnerText != "0x00000000") throw new Exception("Could not update properties.\n\n" + updatesResponse.InnerText + "\n" + updatesResponse.FirstChild.FirstChild.InnerText);
StatusMessage(fullFileRef + " processed...");
totalRecords++;
}
StatusMessage("Completed - " + totalRecords + " processed.");
}
catch (Exception exp)
{
StatusMessage("ERROR: " + exp.Message);
}
}
/// <summary>
/// Display a message
/// </summary>
/// <param name="myMessage"></param>
static void StatusMessage(string myMessage)
{
Console.WriteLine(myMessage.ToString());
MessageToFile(myMessage);
}
/// <summary>
/// Write message to the log file
/// </summary>
/// <param name="myMessage"></param>
static void MessageToFile(string myMessage)
{
using (StreamWriter sw = new StreamWriter(LogFile, true))
{
DateTime now = DateTime.Now;
sw.WriteLine(now.ToString() + ": " + myMessage.ToString());
}
}
}
}
</pre><iframe align="left" frameborder="0" marginheight="0" marginwidth="0" scrolling="no" src="http://rcm.amazon.com/e/cm?t=thesim06-20&o=1&p=8&l=bpl&asins=0672329034&fc1=000000&IS2=1&lt1=_blank&m=amazon&lc1=0000FF&bc1=000000&bg1=FFFFFF&f=ifr" style="height: 245px; padding-right: 10px; padding-top: 5px; width: 131px;"></iframe><iframe align="left" frameborder="0" marginheight="0" marginwidth="0" scrolling="no" src="http://rcm.amazon.com/e/cm?t=thesim06-20&o=1&p=8&l=bpl&asins=0735623201&fc1=000000&IS2=1&lt1=_blank&m=amazon&lc1=0000FF&bc1=000000&bg1=FFFFFF&f=ifr" style="height: 245px; padding-right: 10px; padding-top: 5px; width: 131px;"></iframe>Unknownnoreply@blogger.com2tag:blogger.com,1999:blog-7799238193115123636.post-166764747895415382011-01-11T22:42:00.003+00:002015-07-27T22:26:34.366+01:00Binding a CheckBoxList object to an ordered Sharepoint list of reference values in a web part (c#)<iframe src="http://rcm-na.amazon-adsystem.com/e/cm?t=thesim06-20&o=1&p=8&l=bpl&asins=0470434007&fc1=000000&IS2=1<1=_blank&m=amazon&lc1=0000FF&bc1=000000&bg1=FFFFFF&f=ifr" style="align:left;padding-top:5px;width:131px;height:245px;padding-right:10px;"align="left" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe>It's common when creating database applications to use reference tables to provide lookup values. These tables ofter contain a flag that is used to mark a record as no longer available, and an order column that provides a method of putting the values in an order of importantance, perhaps when using them in a drop down list or list of checkboxes. Sharepoint is NOT a database, however there is no reason why good practice such as this cannot be applied to Sharepoint's list model.<br />
<br />
In the following example I will show you how to set up a reference list and then use the Sharepoint object model to programmatically access this list and bind it to an control (in this case a Sharepoint CheckBoxList control). Once you understand this, you can use the same method to connect to any reference list and bind it to other objects and controls, such as drop down lists. This example has been developed for Sharepoint 2007, but should also work for Sharepoint 2010.<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<span style="font-size: large;">Step 1: Set up a reference list</span><br />
<span style="font-size: large;"><span style="font-size: small;">Create a new list on your Sharepoint site with teh following structure:</span></span><span style="font-size: large;"><span style="font-size: small;"> </span></span><br />
<ul><li><span style="font-size: large;"><span style="font-size: small;">ID - integer (this is a default field) - this will be used as the unique key (lookup value) used to link this reference filed to other lists</span></span></li>
<li><span style="font-size: large;"><span style="font-size: small;">Title - string (this is a default field) - this is used to hold the description of the reference field, and will be the value shown in lookups</span></span></li>
<li><span style="font-size: large;"><span style="font-size: small;">SortOrder - integer, default 1000 - this can be used to sort the list values in lookups and programmatically using CAML </span></span></li>
<li>Enabled - Yes/No field, default Yes - setting to NO will enable you to filter out these values in views and in programmatic lookups in CAML</li>
</ul>You can now enter you reference values into the list, for example here is a list of types of medical record:<br />
<div class="separator" style="clear: both; text-align: center;"><a href="http://2.bp.blogspot.com/_i-bmRB_QqtU/TSzZQ4DVy8I/AAAAAAAAAIY/yPdDB8Y9nDg/s1600/Order-list-cropped.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="287" src="http://2.bp.blogspot.com/_i-bmRB_QqtU/TSzZQ4DVy8I/AAAAAAAAAIY/yPdDB8Y9nDg/s320/Order-list-cropped.png" width="320" /></a></div><br />
<span style="font-size: large;">Step 2: Add method to webpart that use CAML to read and order the list</span><br />
Now for the code that reads the Sharepoint list in a structured manner so we can use it in web parts. First, add the following method to your web part: <br />
<pre class="brush:csharp">/// <summary>
/// Returns a list collection, ordered using a field in the list called "SortOrder"
/// </summary>
/// <param name="listName">The literal string name of the list to query</param>
/// <returns>SPListItemCollection</returns>
private SPListItemCollection ReadOrderedList(string listName)
{
try
{
using (SPWeb configWeb = SPContext.Current.Site.OpenWeb())
{
//Get the list
SPList lookupList = configWeb.Lists[listName];
// Use CAML to order the list
SPQuery query = new SPQuery();
// This CAML where clause searches for only items where the Enabled field is set to "Yes"
query.Query = "<Where><Eq><FieldRef Name=\"Enabled\" /><Value Type=\"Integer\">1</Value></Eq></Where> ";
// This CAML order by claus uses an integer field of "SortOrder"
query.Query += "<OrderBy><FieldRef Name=\"SortOrder\" /></OrderBy>";
SPListItemCollection lookupItems = lookupList.GetItems(query);
return lookupItems;
}
}
catch (Exception ex)
{
ErrorTrap("ReadOrderedList: " + ex.Message + Environment.NewLine + ex.StackTrace.ToString());
throw;
}
} </pre><br />
This method will return the content of the list in a SPListItemCollection object. CAML is use to order the list by the "SortOrder" column, and to ignore values that do not have the boolean field "Enabled" set to true.<br />
<br />
<span style="font-size: large;">Step 3: Bind the list to a control</span><br />
At the class level of your webpart, create the control that you wish to bind to (in this case a CheckBoxList):<br />
<br />
<pre class="brush:csharp">CheckBoxList myCheckList = new CheckBoxList();
</pre><br />
To bind this control to your Sharpoint list, put this code in the CreateChildControls() method. Simply replace "My List" with the real name of your list: <br />
<pre class="brush:csharp">// Set up the Record Section checkboxes list
SPListItemCollection dt = ReadOrderedList("My List");
myCheckList.DataSource = dt;
myCheckList.DataTextField = "Title";
myCheckList.DataValueField = "ID";
myCheckList.DataBind();
</pre><br />
That's it! You now have a Sharepoint object bound to your Sharepoint list of reference values. When rendered, the output will look something like this:<br />
<div class="separator" style="clear: both; text-align: center;"><a href="http://2.bp.blogspot.com/_i-bmRB_QqtU/TSzcu3SQIOI/AAAAAAAAAIc/9NGCU5ppKeY/s1600/CheckBoxList.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="http://2.bp.blogspot.com/_i-bmRB_QqtU/TSzcu3SQIOI/AAAAAAAAAIc/9NGCU5ppKeY/s1600/CheckBoxList.png" /></a></div><br />
<br />
Yyou can use the following method to render the CheckBoxList to the web part. This example puts the CheckBoxList in a DIV that fixes the maximum size of the list with a scrollbar.<br />
<pre class="brush:csharp">/// <summary>
/// render a list of checkboxes to the page
/// </summary>
void RenderCheckBoxes()
{
try
{
// Set up list of checkboxes
myCheckList.EnableViewState = true;
myCheckList.CellSpacing = 0;
myCheckList.CellPadding = 0;
for (int i = 0; i < myCheckList.Items.Count; i++)
{
ListItem li = new ListItem(myCheckList.Items[i].Text, myCheckList.Items[i].Value);
// Set all boxes to selected if not a postback
if (!Page.IsPostBack)
{
myCheckList.Items[i].Selected = true;
}
}
// Give the checklist an ID (can use this in javascript etc)
myCheckList.ID = "RecordSections";
//Add controls to web part
Controls.Add(new LiteralControl(@"<TABLE border='0' bordercolor='red' cellpadding='0' cellspacing='0' valign='top'>"));
Controls.Add(new LiteralControl("<TR>"));
Controls.Add(new LiteralControl("<TD>"));
Controls.Add(new LiteralControl(@"<div class=""ms-frombody""><b>Record Sections</b></div>"));
Controls.Add(new LiteralControl("</TD>"));
Controls.Add(new LiteralControl("</TR>"));
Controls.Add(new LiteralControl("<TR>"));
Controls.Add(new LiteralControl("<TD>\r\n"));
Controls.Add(new LiteralControl(@"<input type=""hidden"" id=""ScrollPos"" runat=""server""/>"));
Controls.Add(new LiteralControl(@"<div id='RecordSectionScroll' style=""OVERFLOW: auto; WIDTH: 247px; TOP: 0px; HEIGHT: 300px"" onscroll=""javascript:document.getElementById('ScrollPos').value = this.scrollTop""> "));
Controls.Add(myCheckList);
Controls.Add(new LiteralControl("</div></TD>"));
Controls.Add(new LiteralControl("</TR>"));
Controls.Add(new LiteralControl("</TABLE>"));
}
catch (Exception ex)
{
ErrorTrap("RenderCheckBoxes" + ex.Message + Environment.NewLine + ex.StackTrace.ToString());
}
}
</pre><br />
Note that I am using literal controls to render the check boxes in a HTML table. This is pretty horrible and I don't recommend it, but it does work.<br />
<br />
Here is the ErrorTrap method. Note that this is just a simple error handling function and is not required to render a checklist bound to a Sharepoint list, but since it appears in the examples I though I would show you what I do.<br />
<pre class="brush:csharp">/// <summary>
/// Give an error message
/// </summary>
/// <param name="myMessage"></param>
void ErrorTrap(string myMessage)
{
Controls.Add(new LiteralControl("<strong>ERROR: " + myMessage.ToString() + "<BR/></strong>"));
ErrorToFile(myMessage);
}
/// <summary>
/// Write errors to the log file
/// </summary>
/// <param name="myMessage"></param>
void ErrorToFile(string myMessage)
{
using (StreamWriter sw = new StreamWriter("D:\\SearchErrorLog.txt"))
{
DateTime now = new DateTime();
sw.Write(now.ToString() + ": " + myMessage.ToString());
}
}
</pre><iframe src="http://rcm-na.amazon-adsystem.com/e/cm?t=thesim06-20&o=1&p=8&l=bpl&asins=1590594568&fc1=000000&IS2=1<1=_blank&m=amazon&lc1=0000FF&bc1=000000&bg1=FFFFFF&f=ifr" style="align:left;padding-top:5px;width:131px;height:245px;padding-right:10px;"align="left" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe><iframe src="http://rcm-na.amazon-adsystem.com/e/cm?t=thesim06-20&o=1&p=8&l=bpl&asins=B0026A6AUG&fc1=000000&IS2=1<1=_blank&m=amazon&lc1=0000FF&bc1=000000&bg1=FFFFFF&f=ifr" style="align:left;padding-top:5px;width:131px;height:245px;padding-right:10px;"align="left" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-7799238193115123636.post-54120111485061160672010-11-16T13:56:00.004+00:002011-01-26T20:57:17.614+00:00Render Content Type fields as a form in Sharepoint Web Part using c#In this blog entry I will give you some example code that will render a simple form in a Sharepoint 2007 web part. The form fields are taken from a pre-defined Sharepoint Content Type. I struggled to find any examples of this on the net, despite it seeming to me to be a fairly ordinary thing to want to do (after all, if you go to all the trouble of defined your own Content Types to organise your data, surely you would want to use them in your own web parts?).<br />
<br />
In order to develop this, I used C# / Visual Studio 2008 and Sharpoint 2007. This should also work in Visual Studio 2005, although you will have to install the web part manually - Visual Studio 2008 has far tighter links to Sharepoint, meaning debugging and deploying is much easier. It should also work in VS2010 / Sharepoint 2010.<br />
<br />
The following method will return a SPContentType object, you only need to pass it a list name and content type name. The SPContentType object can be used later to iterate through its fields in oder to render controls based on the content type's fields.<br />
<br />
<br />
<pre class="brush:csharp">/// <summary>
/// Returns the content type object
/// </summary>
/// <param name="listName"></param>
/// <param name="contentTypeName"></param>
/// <returns></returns>
SPContentType ReadContentType(string listName, string contentTypeName)
{
//get the web
this._web = Microsoft.SharePoint.SPContext.Current.Web;
SPList dirList = this._web.Lists[listName];
SPContentType contentType = dirList.ContentTypes[contentTypeName];
//You could simply iterate here like this if you wish, like this:
//foreach (SPField field in _contentType.Fields)
//{
// string dispName = field.Title;
// SPFieldType type = field.Type;
// object defaultValue = field.DefaultValue;
//}
return contentType;
}
</pre><br />
The following code overrides the "CreateChildControls" Sharepoint method to create our own controls based on the content type. In this example, only text fields and date-times are rendered, but hopefully it straight forward enough for you can see how you could extend this. Simply change: <br />
<pre class="brush:csharp">"Your_List_Name" and "Your_Content_Type_Name" </pre>to your actual values from your Sharepoint site.<br />
I use the "LiteralControl" method to render raw HTML on the page to format the form, which feels really nasty but is efective. <br />
<br />
<pre class="brush:csharp">protected override void CreateChildControls()
{
//Controls.Clear();
//base.CreateChildControls();
// Read in the content type for the target list
SPContentType contentType = ReadContentType("Your_List_Name", "Your_Content_Type_Name");
Controls.Add(new LiteralControl("<TABLE>"));
foreach (SPField field in contentType.Fields)
{
// Ignore hidden or readonly fields
if (field.Hidden) continue;
if (field.ReadOnlyField) continue;
if (field.Type == SPFieldType.Text)
{
string dispName = field.Title;
string staticName = field.StaticName;
SPFieldType type = field.Type;
object defaultValue = field.DefaultValue;
Controls.Add(new LiteralControl("<TR>"));
Controls.Add(new LiteralControl("<TD>"));
Label lbl = new Label();
lbl.Text = dispName;
Controls.Add(lbl);
Controls.Add(new LiteralControl("</TD>"));
// Textbox
TextBox tb = new TextBox();
// I give my controls a unique ID so I can reference them later
tb.ID = "xx_ctl_xx" + dispName;
if(defaultValue != null)
tb.Text = defaultValue.ToString();
Controls.Add(new LiteralControl("<TD>"));
Controls.Add(tb);
Controls.Add(new LiteralControl("</TD>"));
Controls.Add(new LiteralControl("</TR>"));
}
else if (field.Type == SPFieldType.DateTime)
{
string dispName = field.Title;
string staticName = field.StaticName;
SPFieldType type = field.Type;
object defaultValue = field.DefaultValue;
Label lbl = new Label();
lbl.Text = dispName;
Controls.Add(new LiteralControl("<TR>"));
Controls.Add(new LiteralControl("<TD>"));
Controls.Add(lbl);
Controls.Add(new LiteralControl("</TD>"));
// Datetime picker
SPDatePickerControl dtp = new SPDatePickerControl();
dtp.ID = "xx_ctl_xx" + staticName;
if (defaultValue != null)
dtp.SelectedDate = defaultValue.ToString();
Controls.Add(new LiteralControl("<TD>"));
Controls.Add(dtp);
Controls.Add(new LiteralControl("</TD>"));
Controls.Add(new LiteralControl("</TR>"));
}
}
Controls.Add(new LiteralControl("</TABLE>"));
//In my code, I use the controls to perform a custom search. The following code plugs in
//the event handler to do this, based on the values the user puts into the controls rendered above.
//This blog post will not go into the detail of this so I have commented the following lines out.
//cmdSearch = new Button();
//cmdSearch.Text = "Start Search";
//cmdSearch.Click += new EventHandler(cmdSearch_Click);
//this.Controls.Add(cmdSearch);
//lblQueryResult = new Label();
//this.Controls.Add(lblQueryResult);
base.CreateChildControls();
}
</pre><br />
Once deployed, you can add this web part to your site in the normal way using the web front end. Depending on the fields in your content type, it should render something like this (web part highlighted in pink):<br />
<br />
<div class="separator" style="clear: both; text-align: center;"></div><div class="separator" style="clear: both; text-align: center;"><a href="http://1.bp.blogspot.com/_i-bmRB_QqtU/TOKMwOrtAFI/AAAAAAAAAH4/9fvFEZfBd9A/s1600/ContentTypeRenderedAsForm2.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="262" src="http://1.bp.blogspot.com/_i-bmRB_QqtU/TOKMwOrtAFI/AAAAAAAAAH4/9fvFEZfBd9A/s320/ContentTypeRenderedAsForm2.jpg" width="320" /></a></div><div class="separator" style="clear: both; text-align: center;"></div><iframe align="left" frameborder="0" marginheight="0" marginwidth="0" scrolling="no" src="http://rcm.amazon.com/e/cm?t=thesim06-20&o=1&p=8&l=bpl&asins=0972688862&fc1=000000&IS2=1&lt1=_blank&m=amazon&lc1=0000FF&bc1=000000&bg1=FFFFFF&f=ifr" style="height: 245px; padding-right: 10px; padding-top: 5px; width: 131px;"></iframe><iframe align="left" frameborder="0" marginheight="0" marginwidth="0" scrolling="no" src="http://rcm.amazon.com/e/cm?t=thesim06-20&o=1&p=8&l=bpl&asins=0672330504&fc1=000000&IS2=1&lt1=_blank&m=amazon&lc1=0000FF&bc1=000000&bg1=FFFFFF&f=ifr" style="height: 245px; padding-right: 10px; padding-top: 5px; width: 131px;"></iframe><iframe align="left" frameborder="0" marginheight="0" marginwidth="0" scrolling="no" src="http://rcm.amazon.com/e/cm?t=thesim06-20&o=1&p=8&l=bpl&asins=0735625387&fc1=000000&IS2=1&lt1=_blank&m=amazon&lc1=0000FF&bc1=000000&bg1=FFFFFF&f=ifr" style="height: 245px; padding-right: 10px; padding-top: 5px; width: 131px;"></iframe>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-7799238193115123636.post-20022941453528078362010-07-08T00:29:00.004+01:002015-12-11T15:33:40.250+00:00Colour code a RAG column in Sharepoint 2007 list view using Jquery<a href="http://www.yngoo.co.uk/top-tens/best-selling-smart-televisions" target="_blank">To see the best selling SMART televisions visit Yngoo!</a>
<br />
I'm a big fan of Microsoft Sharepoint, even though it really annoys me sometimes. It's amazing that no matter what question a client asks of it, it never can quite answer the question straight out of the box. However, this is not a problem, because Sharepoint is virtually infinately customisable by a competent programmer with enough time to become emersed in the "Sharepoint Way" and no fear of learning new techniques.<br />
An example of this came up for me recently when a client requested that a column on a list would be colour coded depending on the value of the data in that column. The data would be a RAG rating (i.e. a "choice" field containing a set of values that relate to red, amber or green), and therefore it would be nice to colour code the column in eiter red, amber or green to match the rating. Sharepoint does not give you any easy way of doing this unfortunately.<br />
<br />
This is where <a href="http://jquery.com/">Jquery </a>comes in. This terrific library of javascript offers developers a new and consise way of dealing with the internet document object model (DOM). With it developers can quickly and easily scan the object model of the page returned in the browser, and change the page before it is rendered. There is far more to it than this of course, but this is the trick I used to colour code the columns.<br />
<br />
To colour (color) code a coloumn, follow these steps:<br />
<br />
<br />
<br />
<ol>
<li>Download the jquery.js library from teh link above, and upload it to your Sharepoint site in a convenient location (I use the Site Documents Collection in my top level publishing site, but anywhere will do)</li>
<li>Edit the Sharepoint page that the holds the list, and add a Content Editor Web Part (CEWP).<br />
<br />
<br />
<br />
<br />
<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://3.bp.blogspot.com/_i-bmRB_QqtU/TDUK6P-Di8I/AAAAAAAAAHY/f4RvnLXXccU/s1600/site-collection-documents.gif" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="233" src="http://3.bp.blogspot.com/_i-bmRB_QqtU/TDUK6P-Di8I/AAAAAAAAAHY/f4RvnLXXccU/s400/site-collection-documents.gif" width="400" /></a></div>
</li>
<li>Edit the CEWP, choose the "edit source" option, and paste in something like the following code <br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://3.bp.blogspot.com/_i-bmRB_QqtU/TDUL-2aEdHI/AAAAAAAAAHg/Uite8bF4r-g/s1600/CEWPedit.gif" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="400" src="http://3.bp.blogspot.com/_i-bmRB_QqtU/TDUL-2aEdHI/AAAAAAAAAHg/Uite8bF4r-g/s400/CEWPedit.gif" width="320" /></a></div>
</li>
</ol>
<br />
<pre class="brush:jscript"><script type="text/javascript" src="http://<root site>/SiteCollectionDocuments/jquery-1.4.2.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".ms-vb2:contains('<b>1: No Assurance</b>')").each(function(){
$(this).css("background-color", "<b>#FF0000</b>");
//$(this).css("filter", "alpha(opacity=50)");
});
$(".ms-vb2:contains('<b>2: Limited Assurance</b>')").each(function(){
$(this).css("background-color", "<b>#FF9900</b>");
});
$(".ms-vb2:contains('<b>3: Significant Assurance</b>')").each(function(){
$(this).css("background-color", "<b>#FFFF00</b>");
});
$(".ms-vb2:contains('<b>4: Full Assurance</b>')").each(function(){
$(this).css("background-color", "<b>#00CC00</b>");
});
});
<script>
</pre>
<br />
Note that in this example, the Jquery library is located at: http://<root site>/SiteCollectionDocuments/jquery-1.4.2.js. Change this to the URL of your own Jquery library.<br />
<br />
In my example, the RAG rating column can contain the following values:<br />
<ul>
<li>1: No Assurance (RGB #FF0000)</li>
<li>2: Limited Assurance (RBG #FF9900)</li>
<li>3: Significant Assurance (RGB #FFFF00)</li>
<li>4: Full Assurance (RGB #00CC00)</li>
</ul>
<br />
Now to explain what this is actually doing: "ms-vb2" is the standard Sharepoint site template CSS class that is used to identify columns in a list view web part.<br />
What this Jquery script is effectively doing is looking for a DOM item with the class "ms-vb2", and in each case that it this<br />
DOM item contains a specific piece of text ("1: No Assurance", "2: Limited Assurance" etc.), it modifies the CSS of this<br />
particular section of the DOM to add a "background-color" CSS tag.<br />
<br />
Of course your list will have different values, so remember to change the strings in bold to match your own list values!<br />
The colour codes are standard RGB, so you may find <a href="http://www.science.uva.nl/ict/guides/www/guides/colors/index_en.html">this RGB table</a> useful to decide your colours. <br />
<br />
<br />
Your results will look something like this:<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://1.bp.blogspot.com/_i-bmRB_QqtU/TDUK0ijnZoI/AAAAAAAAAHQ/2GuyRwTGt6w/s1600/colouredcolumn.gif" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="308" src="http://1.bp.blogspot.com/_i-bmRB_QqtU/TDUK0ijnZoI/AAAAAAAAAHQ/2GuyRwTGt6w/s640/colouredcolumn.gif" width="640" /></a></div>
Best of luck!<br />
<br />
<table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: auto; margin-right: auto; text-align: center;"><tbody>
<tr><td style="text-align: center;"><a href="http://www.yngoo.co.uk/top-tens/jewellery" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img alt="Carissima Gold 9 ct Yellow Gold Two-Row Diamond Cut Curb Bracelet of 21 cm 8.5-inch on www.yngoo.co.uk" border="0" src="http://4.bp.blogspot.com/-JgOrbukGHKE/Vmrp7CjdOwI/AAAAAAAAAW8/vSLhnQs8Kbw/s320/Carissima%2BGold%2B9%2Bct%2BYellow%2BGold%2BTwo-Row%2BDiamond%2BCut%2BCurb%2BBracelet%2Bof%2B21%2Bcm%2B8.5-inch.jpg" title="Carissima Gold 9 ct Yellow Gold Two-Row Diamond Cut Curb Bracelet of 21 cm 8.5-inch on www.yngoo.co.uk" /></a></td></tr>
<tr><td class="tr-caption" style="text-align: center;">Carissima Gold 9 ct Yellow Gold Two-Row Diamond Cut Curb Bracelet of 21 cm/8.5-inch</td></tr>
</tbody></table>Unknownnoreply@blogger.com1tag:blogger.com,1999:blog-7799238193115123636.post-58050785172443448812010-05-11T23:27:00.007+01:002010-07-22T00:45:59.955+01:00Write lines to a RichTextBox control in different colours (VB .net example)<iframe align="left" frameborder="0" marginheight="0" marginwidth="0" scrolling="no" src="http://rcm.amazon.com/e/cm?t=thesim06-20&o=1&p=8&l=bpl&asins=0470502215&fc1=000000&IS2=1&lt1=_blank&m=amazon&lc1=0000FF&bc1=000000&bg1=FFFFFF&f=ifr" style="height: 245px; padding-right: 10px; padding-top: 5px; width: 131px;"></iframe>I create a lot of back end "processing" software, for example migration or upgrade tools that process documents as they find them on a server. As a standard, I tend to write their progress out to a text file, but I also like the program to show me what is happening as it processes files by writing the log file to the screen. This is particularly useful when debugging the application, but it's also far more satisfying to see something happening on the screen.<br />
<br />
In this situation it is nice to write out warnings or non critical errors in different colours in order to attract the eye.<br />
<br />
To achieve this, create a <a href="http://msdn.microsoft.com/en-us/library/3tdc88y7.aspx">RichTextBox</a> control on your main form (in my example it is called "fInfoBox"), and write to it using the code in the sub routine below.<br />
<br />
<br />
<br />
<br />
<br />
<br />
<pre class="brush: vb">Sub ShowLog(ByVal qFore as Drawing.Color, ByVal sMesg as string)
Dim sDispMess As String
sDispMess = Date.Now()& ": " & sMesg & vbCrLf
With fInfoBox 'This is the name of you RichTextBox control on your form
.SelectionStart = Len(.Text)
.SelectionBullet = True ' This shows the line in bulleted form, comment out if not required
.SelectionColor = qFore
.SelectedText = sDispMess.ToString()
End With
fInfoBox.ScrollToCaret() ' This scrols to the last line of the text box
End Sub
</pre><br />
To display a message with a font colour of blue, call the routine like this:<br />
<pre class="brush: vb">ShowLog(Drawing.Color.Blue, "This message will appear in a font color of blue")
</pre>For a red message, try this:<br />
<pre class="brush: vb">ShowLog(Drawing.Color.Red, "ERROR: This message will display in a font color of red!!")
</pre>This is a very simple example, but I hope it helps someone get started with this sort of thing and gives you some ideas.<br />
<br />
Remember that if you use threading or the backgroundworker class to remove your time consuming processes from the UI (which you should, especially since this is so easy after .Net 2.0), then you will need to use a callback technique for your worker thread to be able to talk to your UI thread.<br />
<iframe align="left" frameborder="0" marginheight="0" marginwidth="0" scrolling="no" src="http://rcm.amazon.com/e/cm?t=thesim06-20&o=1&p=8&l=bpl&asins=159059892X&fc1=000000&IS2=1&lt1=_blank&m=amazon&lc1=0000FF&bc1=000000&bg1=FFFFFF&f=ifr" style="height: 245px; padding-right: 10px; padding-top: 5px; width: 131px;"></iframe>Unknownnoreply@blogger.com1tag:blogger.com,1999:blog-7799238193115123636.post-34261759351268091582010-04-21T22:06:00.016+01:002015-07-27T22:23:15.779+01:00VBA code to iterate through the results of GetListCollection web service from Sharepoint 2007<iframe align="left" frameborder="0" marginheight="0" marginwidth="0" scrolling="no" src="http://rcm-na.amazon-adsystem.com/e/cm?t=thesim06-20&o=1&p=8&l=bpl&asins=0470127287&fc1=000000&IS2=1&lt1=_blank&m=amazon&lc1=0000FF&bc1=000000&bg1=FFFFFF&f=ifr" style="height: 245px; padding-right: 10px; padding-top: 5px; width: 131px;"></iframe><br />
In a <a href="http://the-simple-programmer.blogspot.com/2010_03_01_archive.html">previous post</a> I discussed how to set meta-data in Sharepoint 2007 directly from VBA. I mentioned that the Microsoft documentation for the Sharepoint web services does not appear to be correct, insofar as you cannot address a Sharepoint "list" in the web service using its name, but rather you are forced to use the GUID.<br />
<br />
I have now had to write a function to retrieve the GUID for the list from teh Sharepoint site. This proved to be much harder in practice than I had expected it to be, partly at least because of the problems in working in the VBA IDE with its poor debugging functionality, partly because VBA is a much more limited language than .Net and I have got used to using all the nice constructs such as generics that make life so much easier, and partly because I still find MSXML very "brain" hard to work with. I don't know why I find it so hard, it just always seems that everything ends up being far more complicated than I think it should be. I find the .Net XML model much easier to deal with.<br />
<br />
Anyway, after playing about with XSLT and XPATH in order to extract the ID and VersionNumber attributes from the wsm_GetListCollection web service (and failing miserable), I finally decided to just iterate through the nodes and attributes till I found what I wanted. The code below is a simple function that you can call with three parameters: the name of the list that you need the GUID for (sListName), a string variable in which the GUID will be placed (sListID), and an integer that the list version number will be placed (iListVersion).<br />
<br />
Note: You may also be interested in this post: <a href="http://the-simple-programmer.blogspot.com/2011/03/vba-code-to-check-in-document-to.html">VBA code to check in a document to Sharepoint and set meta data</a>.<br />
<br />
<br />
<pre class="brush: vb">Function GetListCollection(ByVal sListName As String, ByRef sListID As String, ByRef iListVersion As Integer)
' Class created by toolkit to connect to the Web service
Dim ws As New clsws_Lists
' The collection is returned as an XML node list
Dim ListCollectionNodeList As MSXML2.IXMLDOMNodeList
'Root node of the returned list
Dim nod As MSXML2.IXMLDOMNode
' Output string for the XML transformation
Dim strOutput As String
On Error GoTo GetListCollection_OnError
' Retrieve the collection of lists
Set ListCollectionNodeList = ws.wsm_GetListCollection
' Get the root node from the list
Set nod = ListCollectionNodeList.Item(0)
' Iterate nodelist to find details for our named list
Dim bGotNode
bGotNode = False
Dim procNode As MSXML2.IXMLDOMNode
Dim TitleNodeList As MSXML2.IXMLDOMNodeList
Dim IDNodeList As MSXML2.IXMLDOMNodeList
Set TitleNodeList = nod.SelectSingleNode("//Title")
Set IDNodeList = nod.SelectSingleNode("//ID")
Dim ListNode As MSXML2.IXMLDOMNode
Dim ListChildNodes As MSXML2.IXMLDOMNode
Dim oAttr As MSXML2.IXMLDOMAttribute
Dim retID As String
Dim listVersion As Integer
Dim ListName As String
' Iterate through list nodes returned (should only be one)
For Each ListNode In ListCollectionNodeList
'Iterate through the child nodes (each one represents a single Sharepoint list)
For Each ListChildNodes In ListNode.ChildNodes
'See if we have any attributes (we should have!)
If ListChildNodes.Attributes.Length > 0 Then
' For each list, reset our variables
retID = ""
listVersion = 0
' Iterate through the attributes
For Each oAttr In ListChildNodes.Attributes
Debug.Print "Name= " & oAttr.Name
Debug.Print "Value= " & oAttr.nodeTypedValue
'Look for the ID attribute
If oAttr.Name = "ID" Then
' FOund it, so remember it in case this is our list
retID = oAttr.nodeTypedValue
End If
' Look for the "Title" attribute
If oAttr.Name = "Title" Then
If oAttr.nodeTypedValue = sListName Then
' Found our list, so remember it
ListName = oAttr.nodeTypedValue
bGotNode = True
End If
End If
' Look for the "Version" attribute
If oAttr.Name = "Version" Then
' Found our list, so remember it
listVersion = oAttr.nodeTypedValue
End If
' Once we have found a title, ID and version, break
If retID <> "" And listVersion <> 0 And bGotNode = True Then
Exit For
End If
Next oAttr
End If
' Once we have found the data, break out of iteration
If bGotNode = True Then
Exit For
End If
Next
Next
If bGotNode = False Then
Err.Raise 65000, "", "ERROR: Cannot find list named <" & sListName & "> in Sharepoint site.", "", ""
End If
sListName = ListName
sListID = retID
iListVersion = listVersion
Exit Function
GetListCollection_OnError:
MsgBox ("ERROR: Retrieving list collection from Sharepoint." + vbCrLf + _
Err.Number + " - " + Err.Description)
End Function
</pre><br />
Remember, you will have to have installed the <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=fa36018a-e1cf-48a3-9b35-169d819ecf18&DisplayLang=en">Microsoft Web Services Toolkit</a> before this will work, and <a href="http://msdn.microsoft.com/en-us/library/aa192537%28office.11%29.aspx">add a web reference to your Sharepoint site to your VBA project</a>. This has been tested with Office 2003 linking to Sharepoint 2007 and works :).<br />
<br />
<iframe align="left" frameborder="0" marginheight="0" marginwidth="0" scrolling="no" src="http://rcm-na.amazon-adsystem.com/e/cm?t=thesim06-20&o=1&p=8&l=bpl&asins=0596006780&fc1=000000&IS2=1&lt1=_blank&m=amazon&lc1=0000FF&bc1=000000&bg1=FFFFFF&f=ifr" style="height: 245px; padding-right: 10px; padding-top: 5px;"></iframe>Unknownnoreply@blogger.com3tag:blogger.com,1999:blog-7799238193115123636.post-3325491088727699762010-03-10T23:24:00.009+00:002015-07-27T22:24:22.429+01:00Set Sharepoint meta-data from VBA using updatelist web service<iframe align="left" frameborder="0" marginheight="0" marginwidth="0" scrolling="no" src="http://rcm-na.amazon-adsystem.com/e/cm?t=thesim06-20&o=1&p=8&l=bpl&asins=1590594568&fc1=000000&IS2=1&lt1=_blank&m=amazon&lc1=0000FF&bc1=000000&bg1=FFFFFF&f=ifr" style="height: 245px; padding-right: 10px; padding-top: 5px; width: 131px;"></iframe>
<a target="_blank" href="http://www.yngoo.co.uk/top-tens/bestselling-watches/bestselling-rolex-watches/">For the top ten best selling Rolex watches, visit Yngoo!</a><br/>
I've been working on a problem trying to integrate a legacy Microsoft Office 2003 VBA application with Sharepoint 2007. In theory, I should be able to use the SOAP toolkit provided my Microsoft to talk to the Sharepoint (WSS) web services, but in practice there was very little documentation of how to do this, and I could find no resources on the internet aside from the MSDN definitions of the web services, and only a little attached to the SOAP toolkit (available here: <a href="http://msdn.microsoft.com/en-us/library/aa192537%28office.11%29.aspx">Microsoft Office 2003 Web Services Toolkit</a> ).<br />
<br />
The basic problem I was trying to solve was: how do I set meta-data held on a document in Sharepoint from Office 2003 using VBA? <br />
<br />
After much head scratching I finally solved this by making some assumptions based on the MSDN reference documentation, then using the <a href="http://www.fiddler2.com/fiddler2/">Fiddler</a> tool until I had worked out what I was doing wrong. Fiddler allows you to inspect the HTTP calls and responses that you are issuing/receiving. This is very helpful when debugging web services, and well worth looking into if you are doing anything in this area.<br />
<br />
Anyway, through Fiddler I could see the response from the web service, including the error message. This meant that my initial best guess on how to structure the XML was at least nearly correct, because the web service was giving me a proper error message. Eventually I had a properly structured call and everything worked!<br />
<br />
<br />
Remember to install the SOAP toolkit before you try this. You will then be able to add this to your VBA project and add a web reference to your project to the WSS Lists.asmx service as you would if your using .Net. This is all explained in the MSDN link above but drop a comment if you would like me to go into more detail.<br />
<br />
The actual VBA code used structure the call to the web service looks like this:<br />
<br />
<pre class="brush: vb">'Define a new list service web service class
Dim listws As New clsws_Lists
' Set up the batch command used to set the meta data.
' Note that FileRef is set to URL of the file you want to change
'ListVersion is from my test site, you may not need that
' First set up DOM document containing fields
Dim xmlDoc As New MSXML2.DOMDocument30
xmlDoc.async = False
Dim xmlText As String
xmlText = "<root>" + _
"<Batch OnError='Continue' ListVersion='59' PreCalc='TRUE' xmlns=''>" + _
"<Method ID='1' Cmd='Update'>" + _
"<Field Name='ID' />" + _
"<Field Name='FileRef'>http://myservername:1080/sites/mysite/shared documents/TestWebService.doc</Field>" + _
"<Field Name='Title'>Uploaded from VBA</Field>" + _
"<Field Name='Surname'>" + sLastName + "</Field>" + _
"<Field Name='Forename'>" + sFirstName + "</Field>" + _
"<Field Name='Date_x0020_of_x0020_Birth'>" + sDOB + "</Field>" + _
"</Method>" + _
"</Batch>" + _
"</root>"
xmlDoc.LoadXml (xmlText)
' This is a bit of debug that checks the XML is well formed and show you it if it is.
If xmlDoc.parseError.ErrorCode <> 0 Then
Dim myErr
Set myErr = xmlDoc.parseError
MsgBox (myErr.reason)
Else
MsgBox xmlDoc.XML
End If
' Set up IXMLDOMNodeList object
Dim myXMLNodeList As MSXML2.IXMLDOMNodeList
Dim root As MSXML2.IXMLDOMElement
' Now the the XML node list to the batch command we have just constructed above
Set root = xmlDoc.documentElement
Set myXMLNodeList = root.ChildNodes
' Now run the web service to update the meta-data.
' Note that the first parameter is the GUID of the list that holds the data you want to change. I can't get this to take a list name - it only seems to wrok with a GUID.
Dim updateReturn As IXMLDOMNodeList
Set updateReturn = listws.wsm_UpdateListItems("{B768B024-8B98-4918-990A-ECE34691DBBC}", myXMLNodeList)
</pre><br />
If you need to find out the GUID or ListVersion values for your list, use the "GetListCollection" web service and iterate through the XML it returns:<br />
<br />
<pre class="brush: vb">Dim listCollection As IXMLDOMNode
Set listCollection = listws.wsm_GetListCollection
' You can iterate this to find the GUID of our list
</pre>I can post further examples if anybody wants any.<br />
<br />
<b>*Edit*</b> - I have written another blog post on how to find the GUID of lists in VBA here: <a href="http://the-simple-programmer.blogspot.com/2010/04/vba-code-to-iterate-through-results-of.html">http://the-simple-programmer.blogspot.com/2010/04/vba-code-to-iterate-through-results-of.html</a><br />
This simple function will return the version number and the GUID of the Sharepoint list from its name. <br />
<br />
You may also be interested in teh following post: : <a href="http://the-simple-programmer.blogspot.com/2011/03/vba-code-to-check-in-document-to.html">VBA code to check in a document to Sharepoint and set meta data</a>.<br />
<br />
<br />
<br />
<iframe align="left" frameborder="0" marginheight="0" marginwidth="0" scrolling="no" src="http://rcm-na.amazon-adsystem.com/e/cm?t=thesim06-20&o=1&p=8&l=bpl&asins=0764559036&fc1=000000&IS2=1&lt1=_blank&m=amazon&lc1=0000FF&bc1=000000&bg1=FFFFFF&f=ifr" style="height: 245px; padding-right: 10px; padding-top: 5px; width: 131px;"></iframe><iframe align="left" frameborder="0" marginheight="0" marginwidth="0" scrolling="no" src="http://rcm-na.amazon-adsystem.com/e/cm?t=thesim06-20&o=1&p=8&l=bpl&asins=1556222238&fc1=000000&IS2=1&lt1=_blank&m=amazon&lc1=0000FF&bc1=000000&bg1=FFFFFF&f=ifr" style="height: 245px; padding-right: 10px; padding-top: 5px; width: 131px;"></iframe>Unknownnoreply@blogger.com10tag:blogger.com,1999:blog-7799238193115123636.post-90649403823697775552010-02-21T16:32:00.005+00:002010-03-13T16:40:04.023+00:00SQL Server - MySQL 4 integration - openquery does not work for tables with datetime values of 0000-00-00I have been trying copy the contents of an old MySQL 4.0.12 database to SQL Server 2008 in order to archive its contents.<br />
<br />
To archive this, I followed these steps:<br />
<ol><li>Create an database within SQL Server 2008 to hold the data called ARCHIVE_DB. </li>
<li>Download and install ODBC driver for MySQL (<a href="http://www.mysql.com/downloads/connector/odbc/3.51.html#downloads">available here</a>). Note that due to the version of the MySQL database I was unable to use the newer driver (version 5.1.xx), since this requires version 4.1 of MySQL.</li>
<li>Set up a linked server in SQL Server 2008 using this driver to point to the data source. I called this data source MYSQL_ls.</li>
<li>I can now select data from this data source using the "openquery" TSQL syntax, eg:<br />
<br />
<br />
<pre class="brush: sql">SELECT *
FROM openquery([NADT-SQLHOST], 'select * from webdb.episode')
</pre><br />
</li>
<li>I can extend this query using the TSQL "INTO" clause, which will build the SQL table from the source data, eg:<br />
<br />
<br />
<pre class="brush: sql">SELECT * INTO ARCHIVE_DB
FROM openquery([MYSQL_ls], 'select * from mydatabase.mytable')
</pre><br />
</li>
<li>In theory the above will copy all the data from the MySQL database table called <mytable> (in the MySQL database called <mydatabase>) into the SQL Server table <mytable> (SQL Server database <archive_db>). I do not have to create the table schema, this will be created automatically by the INTO clause. </archive_db></mytable></mydatabase></mytable></li>
<li>I can now create an SSIS package that loops through the tables in the MySQL database and runs the SQL statement show in number 5 against each table. This should in theory copy each table across. </li>
</ol>This technique works very well until you come to tables that include datetime values.<br />
<br />
MySQL allows datetime values in the format of "0000-00-00", which is the equivalent of a NULL date in SQL server. Unfortunately the "Select * Into From Openquery..." trick above does not deal with this situation, and you will recieve a version of the following error:<br />
<br />
<pre class="brush: sql">Msg 7342, Level 16, State 1, Line 4
An unexpected NULL value was returned for column "[MSDASQL].enddate" from OLE DB provider "MSDASQL" for linked server "MYSQL_ls". This column cannot be NULL.
</pre><br />
This error is caused by using "openquery". Fortunately there is a very easy work around for this: where tables have datetimes in "0000-00-00" format, you must use an SSIS data flow task to copy the information, rather than the "openquery" described above:<br />
<br />
<ol><li>Set the data pump source to the MySQL table pointed to in the Linked server and click on "preview" and you will notice that it can return data. This is not possible by running a query in the SQL Management studio, so clearly we are getting somewhere. </li>
<li> Now set the data pump target to "<new table="">" and click on "Mappings" and you will notice that each column in the source table will be mapped to an identically named table in the destination table.</new></li>
<li>Save the data pump and run.</li>
</ol><br />
If you run this data flow, the data will be copied across without reporing the datetime mismatch error.Unknownnoreply@blogger.com3tag:blogger.com,1999:blog-7799238193115123636.post-58519139055727620562010-02-17T21:40:00.001+00:002010-02-17T21:40:54.423+00:00Use a variable as a table name in an SSIS Execute SQL TaskI spent quite a while today trying to build an SSIS package that iterated through a dataset that contained a set of table names usign a for-each container, then run a piece of SQL against each table.<br />
<br />
Setting up the for-each loop was relatively simple, but I couldn't get the Execute SQL task to run a simple query of the type:<br />
<pre class="brush: sql">Select count(*) from @table
</pre>Where @table is the name of the parameter generated from the for each loop.<br />
<br />
It appears that this is not possible in SSIS. Eventually I found a solution: use another variable to store the SQL statement and set up the SQL task to use this variable as its input source.<br />
<br />
Assuming that the input parameter is already set up and called [User::TableName], then the steps to achive this are:<br />
<br />
<ol><li>Set up a new variable (say called "SQLStatement"), make this a string type.</li>
<li>In the properties box of the paremeter, Set EvaluateAsExpression to True</li>
<li>In the properties box of the paremeter, click on the elipses (...) of the "Expression" property to build an expression. Type in the SQL you need and drag the variable you want to use from the "variables" tree. </li>
<li>Escape you SQL in this expression wwithin quotation marks. e.g. the count statement above would look like:</li>
<pre class="brush: sql">"Select count(*) from " + @[User:TableName] </pre>
<li> You can use the "Evaluate expression" button to make sure that this evaluates as real SQL. If you are using a "for-each" container then you may want to give your [User::TableName] variable a sensible default value in order to see the results of the evaluated expression in a format you could use for testing.</li>
<li>Drag an "Execute SQL Task" object into your control flow and open its properties page</li>
<li>Set the "SQL Source Type" property to "Variable" to tell it that the SQL will come from a variable, rather from a typed in SQL statement.</li>
<li>Set the "SourceVariable" property to the name of the variable you created in step 1 (in this example it would be "SQLStatement".</li>
</ol>That's it! <br />
<ol></ol>Unknownnoreply@blogger.com3tag:blogger.com,1999:blog-7799238193115123636.post-71643566187494240652010-02-08T21:41:00.006+00:002010-02-10T14:27:33.970+00:00Blogger.com code syntax highlighting, or always remember to save your code before you start playing around with it!I've decided to re-vamp the look of this blog to give it more width and make the code fragments easier to read. I hope you like the new look!<br />
<br />
When doing this I made one of the oldest mistakes in the programmer's book: I didn't save my work!<br />
<br />
This meant I had to add all the site specific code to render the code in syntax-highlighted format, and add Google analytics tracking code back into the HTML, which whilst not the worst job in the world, did take me some time to remember what I had done. <b> <i>REMEMBER TO SAVE YOUR WORK!</i></b><br />
<br />
This does give me the opportunity to thank the author of the fabulous syntax highlighter for Blogger.com that I have used, which can be found here: <a href="http://alexgorbatchev.com/wiki/SyntaxHighlighter">http://alexgorbatchev.com/wiki/SyntaxHighlighter</a>. Thank you very much Alex, it's a superb bit of code!<br />
<br />
The code I used to enable the nifty highlighter for C# should be pasted into the HEAD section of your blog:<br />
<br />
<br />
<pre class="brush: html"><link href='http://alexgorbatchev.com/pub/sh/current/styles/shCore.css' rel='stylesheet' type='text/css'/>
<link href='http://alexgorbatchev.com/pub/sh/current/styles/shThemeDefault.css' rel='stylesheet' type='text/css'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shCore.js' type='text/javascript'></script>
<!-- add brushes here -->
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushJScript.js' type='text/javascript'></script>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushBash.js' type='text/javascript'></script>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushSql.js' type='text/javascript'></script>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushXml.js' type='text/javascript'></script>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushCpp.js' type='text/javascript'></script>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushCSharp.js' type='text/javascript'></script>
<script type='text/javascript'>
SyntaxHighlighter.config.bloggerMode = true;
SyntaxHighlighter.all();
</script>
</pre><br />
To use it, make sure that the code you want to display has been HTML escaped (which can be done using the utility available here: <a href="http://www.string-functions.com/htmlencode.aspx">http://www.string-functions.com/htmlencode.aspx</a>.<br />
<br />
Now, to use this, just paste your escaped code into your blog and wrap it in the following HTML tags:<br />
<pre class="brush:csharp"><pre class="brush:csharp">
...your code here...
</pre>
</pre><br />
Note that this will work for C Sharp code. For other types of code highlighting, simply change the brush type in the <pre> tag, and make sure the appropriate brush is included in the list of brish types defined in the code above in the "!-- add brushes here --" section.Unknownnoreply@blogger.com1