Monday, April 11, 2011

Visual Studio & SharePoint: how to create package as part of the build process

In order to build a project and have the package created, this can be added to the project file (csproj, vbproj):

Monday, April 4, 2011

SharePoint 2010: PowerShell to delete a web part from the gallery

param($Identity = "", $Url = "")


$SPSite = New-Object Microsoft.SharePoint.SPSite($Url)

$SPWeb = $SPSite.OpenWeb()
$WebPartGallery = $SPWeb.Lists["Web Part Gallery"]
$gall = $WebPartGallery.Items select Name
$count = $gall.Count
for ($i =0; $i -lt $count;$i++)
if ($gall[$i] -match $Identity)
Write-Host "$Identity deleted"

Wednesday, March 30, 2011

VMWare player: blank full screen on Windows 7

Solution: enable "Accelerate 3D graphics."

Friday, March 4, 2011

BitLocker: get out of recovery mode

Some changes to BIOS will cause bitlocker to enter recovery mode.

One way to get out of this follows:

- enter the 8 groups of 6 digits
- get into Windows
- type "manage-bde -protectors -disable c:" from a admin command prompt
- reboot
- type "manage-bde -protectors -enable c:" from a admin command prompt
- reboot

It shouldn't prompt now.

See here for details.

Thursday, March 3, 2011

SharePoint: list throttling messages

There are two messages that people often get when throttling limits (5K default) is reached.

"Displaying only the newest results below. To view all results, narrow your query by adding a filter.": this is seen when metadata navigation and filtering is enabled for the list.

"This view cannot be displayed because it exceeds the list view threshold (5000 items) enforced by the administrator.": this is seen in all other cases.

Wednesday, February 9, 2011

SharePoint 2010: code for dumping a taxonomy tree

Just customize the data you need from each node type (store, group, set, term).
        private void DumpTaxonomy(string siteUrl)
Stack<string> stack = new Stack<string>();
using (SPSite site = new SPSite(siteUrl))
TaxonomySession session = new TaxonomySession(site, false);
int nts = 0;
foreach (TermStore ts in session.TermStores)
int ng = 0;
foreach (Group g in ts.Groups)
int ns = 0;
foreach (TermSet s in g.TermSets)
int nt = 0;
foreach (Term t in s.Terms)
DumpTerm(t, stack, 4);
stack.Push(ReportNode(3, nt));
stack.Push(ReportNode(2, ns));
stack.Push(ReportNode(1, ng));
stack.Push(ReportNode(0, nts));
while (stack.Count > 0)

private void DumpTerm(Term t, Stack<string> stack, int level)
int nt = 0;
foreach (Term children in t.Terms)
DumpTerm(children, stack, level + 1);
stack.Push(ReportNode(level, t.Name + " " + nt.ToString()));

private string ReportNode(int level, object children)
StringBuilder sb = new StringBuilder();
for(int i = 0; i < level; i++)
return (sb.ToString());

Thursday, February 3, 2011

SharePoint 2010: How to enable developer dashboard

$service = [Microsoft.SharePoint.Administration.SPWebService]::ContentService
$addsetting =$service.DeveloperDashboardSettings
$addsetting.DisplayLevel = [Microsoft.SharePoint.Administration.SPDeveloperDashboardLevel]::OnDemand

SharePoint 2010: how to get SQL rows for a document in a library

Here's the snippet, just change the doc lib name and doc title.

select * from AllDocs d
join AllLists l
on d.ListId = d.ListId
and upper(l.tp_Title) = 'UPPERCASE DOC LIB NAME'
and upper(d.LeafName) = 'UPPERCASE DOC TITLE'
join AllUserData u
on u.tp_DocId = d.Id

Tuesday, February 1, 2011

SharePoint 2010: "Access denied by Business Data Connectivity" when viewing list that accesses external data

Solution: permissions (either to users if delegation is used, or the app pool account is trusted subsystem is used) need to be assigned through Business Data Connectivity Service in Central Administration site.

Friday, January 21, 2011

ASP.Net: OnSelectedIndexChanged event not firing

I had this snippet in a page:

<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<asp:ListBox ID="lst" runat="server" OnSelectedIndexChanged="lst_SelectedIndexChanged"></asp:ListBox>

Problem was that OnSelectedIndexChanged was not firing.

Solution was to set AutoPostBack to true in the list.

SharePoint 2010: Adding taxonomy field to files in a Document Library

Pre-requisite is that a taxonomy structure is set up with a "Term Group" group, a child "Term Set" with a "Term Name" term on it. Other than that, it's just about adapting site and list names to your deployment.

Here's the code:

        private void Test()
// get doc lib
SPWebApplication wa = SPWebApplication.Lookup(new Uri("http://server"));
SPSite site = wa.Sites["/sites/test"];
SPDocumentLibrary dl = site.RootWeb.Lists["DocumentLibrary1"] as SPDocumentLibrary;

// get taxonomy field
TaxonomySession session = new TaxonomySession(site, false);
TermSet set = session.DefaultSiteCollectionTermStore.sGroups["Term Group"].TermSets["Term Set"];
Term term = set.GetTerms("Term Name", 1033, false)[0];
TaxonomyField tf = dl.Fields["Term Field"] as TaxonomyField;

// add files
for (int i = 0; i < 100; i++)
using (FileStream fs = (new FileInfo(@"C:\Content.txt")).OpenRead())
// add item
string name = "Name " + i;
Hashtable ht = new Hashtable();
SPFile file = dl.RootFolder.Files.Add(name, fs, ht, true);
SPListItem item = file.Item;

// set item's taxonomy field value
tf.SetFieldValue(item, term);

// progress
Console.WriteLine("{0} created", name);

Thursday, January 20, 2011

SharePoint: The Taxonomy feature (Feature ID "73EF14B1-13A9-416b-A9B5-ECECA2B0604C") has not been activated.

Taxonomy feature is a hidden feature; it doesn't appear in the Site Collection Features UI. Enable it from SP's Management Shell:

Enable-SPFeature -id "73EF14B1-13A9-416b-A9B5-ECECA2B0604C" -url <site collection Url>

VMWare: blank screen when "use host setting for monitor" is chosen

After booting a virtual box, I started getting a blank screen after the Windows boot progress bar dissapeared. I wasn't sure what may have changed.
Went to edit VM settings in VMWare player, and noticed that if I chose a specific resolution, I didn't get the blank screen. But - the resulting windows was too small.
Solution: ended up deleting all VM files other than .vmx and .vmdk. Booted and worked.
(Not sure what root cause was though.)

Wednesday, January 19, 2011

SharePoint 2010: read & write profile properties

Assuming the property exists and can be read and written, the following code does the job.

            StringBuilder s = new StringBuilder();

// get profile
SPServiceContext context = SPServiceContext.GetContext(SPContext.Current.Site);
UserProfileManager profileManager = new UserProfileManager(context);
UserProfile profile = profileManager.GetUserProfile(SPContext.Current.Web.CurrentUser.Name);

// read & write profile's property
const string testProperty = "TestProperty";
string testValue;
UserProfileValueCollection val = profile[testProperty];
if (val != null && val.Value != null)
testValue = val.Value as string;
testValue = "Empty";
profile[testProperty].Value = DateTime.Now.ToString();
s.Append(profile[PropertyConstants.AccountName] + " = " + testValue);
TestText.Text = s.ToString();

Virtual PC: "the hibernated state is not compatible with the installed version of windows virtual pc"

Problem is that the "virtual saved state" file may contain information of the machine it last booted on (likely, the box virtual was copied from), that not compatible with the machine where virtual is being booted on.
Solution: delete that state file.

Wednesday, January 12, 2011

Cryptography & .NET: Simple encryption & descryption using certificates

Here's a simple toy that describes encryption with a public key by a sender and decryption with a private key by the receiver. Notice that the only object that's sent is the cipher text. Other than that, all entities don't cross boundaries, nor the certificate (which in one case is read from the store, from the file in the other).

First, you have to create a suitable certificate. Only caveats: mark its key for 'Exchange' type, and its private key exportable:

makecert.exe Test.cer -r -n "CN=Test Subject" -sr LocalMachine -ss My -sky Exchange -pe

Then, the code, which is mostly self explanatory. (Keys are accessed through providers that encapsulate calculations performed with them.)

        private void TestSenderReceiver()

// get certificate
var certSender = new X509Certificate2(@"C:\Test.cer");

// encrypt with public key
var providerSender = (RSACryptoServiceProvider)certSender.PublicKey.Key;
var plainSender = Encoding.Default.GetBytes("this is plain text");
var cipher = providerSender.Encrypt(plainSender, false);


// get certificate
var store = new X509Store("MY", StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
var certReceiver = store.Certificates.Find(X509FindType.FindBySubjectName, "Test Subject", false)[0];

// decrypt with private key
var providerReceiver = (RSACryptoServiceProvider)certReceiver.PrivateKey;
var plainReceiver = providerReceiver.Decrypt(cipher, false);

// check they are same
int i;
for (i = 0; i < plainSender.Length && i < plainReceiver.Length; i++)
if(plainSender[i] != plainReceiver[i])
if(i == plainSender.Length && i == plainReceiver.Length)

Sunday, January 9, 2011

Powershell script for fixing subtitles files (.srt)

This script fixes the offset of subtitles files (.srt).

Sample call: .\SrtFixer.ps1 -Path '' -Offset '-00:00:26.700'

Thursday, January 6, 2011

SQL Server service not starting: initerrlog: Could not open error log file ''. Operating system error = 3(The system cannot find the path specified.).

Issue was that the account under which service attempted to run was Network Service, which didn't have enough privileges.
While I set it to Local System and got it working, for security reasons, you should set it to a domain account instead. More info here.

Wednesday, January 5, 2011

Cannot run dcpromo.exe after Certificate Services have been installed

This is because, once a Certificate Authority is installed, its domain membership cannot be changed.
Therefore, install Domain Services role, run dcpromo.exe and then install Certificate Services.