by Andreas

Sharepoint 2010 – get rid of the Windows Security login dialog

When you’re running Sharepoint 2010 in your development environment you probably wont have a domain and Active Directory set up. After all, it is a bit of an overkill when it’s just you and your cat that require a login and a profile. Unfortunately the lack of an Active Directory means you will be prompted to enter your username and password each and every time you open up your Sharepoint site, whether this be during development and debugging or just accessing the intranet you’ve set up (for you and your cat – hey, animals need shared calendars and document libraries too..).

image

“Remember my credentials” doesn’t seem to work in this case, and if you’ve attempted to create a new entry in the Credential Manager you’ll soon find out that it doesn’t help either (which is where “Remember my credentials” should have stored your login info in the first place). So, the trick is to add your Sharepoint site as a local intranet site in Internet Explorer. Go to Internet Options, open the security tab and choose “Local intranet”. Click sites, and in the following dialog box choose Advanced. If you did this while browsing your Sharepoint site the web site address should already be in the input textbox, but if not just add it manually (e.g. “http://localhost”):

image

Close your browser and reopen your Sharepoint site – and you’re automatically logged in.

by Andreas

Visual Studio 2008/2010/2012 error: “The following module was built…”

I just encountered DAE #6 (Daily Annoying Error) when debugging an application:

The following module was built either with optimizations enabled or without debug information

image

This was in a solution with a couple of (signed) Sharepoint webparts, and even though I was attempting to debug a standalone command line app, the assembly in question was one of the webparts. Visual Studio seemed to believe that this code wasn’t “my code” (copyright infringement, anyone?), so by going to Tools –> Options –> Debugging –> General you can disable the “Enable Just My Code” option to fix the problem:

image

You might also want to look at other options, but at least this one worked for me this time.

by Andreas

How to stop all Sharepoint 2010 services

imageRunning the Sharepoint 2010 environment on your Windows 7 laptop sure is convenient rather than depending on Windows Server 2008 R2. Especially for those of us who also develop in several other languages and generally use the computer for non-Sharepoint tasks. Windows Server gets a bit dull and heavyweight for daily use, even though I survived nearly a year with it. But Sharepoint requires a fair bit of CPU and RAM because of all the background processes, including the SQL Server database. It also slowly fills your harddrive up, as described in my earlier post Sharepoint Is Eating Up My Harddrive!.

This made me think of writing an application that could shut down Sharepoint whenever I didn’t need it (especially during my overheating shutdown issues…). Fortunately for me, someone else already did! On Codeplex there is a project called Sharepoint 2010 Service Manager. This little piece of magic allows you to turn off all the Sharepoint related services with a single click of a button – including the database. And you can also choose that Sharepoint doesn’t automatically when Windows starts! Brilliant!

image

by Andreas

Sharepoint 2010 – solution stuck Retracting / Deploying

imageIf you ever experience that your solution never retracts (or deploys), first verify that the Sharepoint Administration Service is running. If it is, restart it and see if that helps.

If your solution is still stuck, start Sharepoint 2010 Management Shell and type in the following command:

stsadm -o enumdeployments

You will see a list of in-progress or pending jobs. Cancel the pending job, either by STS / Powershell commands or through the Solution Management. No point wasting any more time – Sharepoint’s showed you another one of its ugly sides so just run this command to force your solution to be deleted:

Remove-SPSolution -Identity the_name_of_your_solution.wsp -force

There, it’s gone. But now you will most likely get an error message when re-deploying your solution:

image

This is because after forced solution removal, Sharepoint still believes the feature is installed. You’ll therefore have to deploy your solution from SharePoint 2010 Management Shell with the –force attribute:

Install-SPSolution -Identity the_name_of_your_solution.wsp -AllWebApplications -GACDeployment –force

Note: make sure you match the scope (“AllWebApplications”) of your solution.

If your solution is STILL stuck, stop the Sharepoint Administration Service and manually trigger the administration jobs from Sharepoint 2010 Management Shell:

 stsadm.exe -o execadmsvcjobs
by Andreas

ADFS 2.0 / Claims authentication / Sharepoint 2010

You encounter the following error message in your event log:

An operation failed because the following certificate has validation errors: [….] Errors: The root of the certificate chain is not a trusted root authority..

This might seem strange, because this will appear even if you have the CA certificate in your certificate store. The reason is that Sharepoint has it’s own registry of certificates, and you will have to add the CA there as well.

1. Open “ADFS 2.0 Management”
2. Expand Service – Certificates
3. Right click the primary (if more than one) certificate under Token-signing, and select View Certificate
4. Choose the Details tab, and click “Copy to file…”
5. Complete the wizard, saving the certificate as “DER encoded binary” (name it ADFSRoot.cer or something)
6. Copy the .cer file over to your Sharepoint server

Now you have to add this certificate to Sharepoints list of root authorities. You’ll be using the Sharepoint 2010 Management Shell for this operation:
1. Start Sharepoint 2010 Management Shell
2. Run the following two commands (change the path to where your .cer is located):

$root = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("C:TEMPADFSroot.cer")

New-SPTrustedRootAuthority -Name "ADFS Token SigningRoot Authority" -Certificate $root

3. The certificate properties will be listed as a confirmation that the certificate has been added.

If your certificate chain contains more than one certificate, you will have to do this with each one giving them a unique name.

Thanks to Steve Peschka for providing an excellent guide.

by Andreas

Sharepoint 2010 – access site usage statistics

OK, so you made the assumption that Microsofts Sharepoint team would have provided a simple way to access something as common (and not to mention extremely useful!) as site usage statistics. Which pages and resources are accessed

  • at what time
  • for how long
  • how often
  • the browser type
  • http status
  • and last but definately not least: by who.

And not only did you assume this would be easily accessible, you also told a client you’d have it done in a couple of hours. I assume some of you that ended up here either got lucky straight away, or you have already spent way more time than expected and added yet another element to your list of reasons why Sharepoint will make you loose your hair prematurely.

If you assumed that this data should be available somewhere you were right. The trick is to know how to access it from your custom web part. The data is stored in the WSS_Logging database, in a table called RequestUsage. You can run a simple query just to see what’s in there and which fields you have access to:

SELECT *
FROM [RequestUsage] 

Then you can start getting a bit more creative. You see, the RequestUsage table contains statistics for all sorts of requests – like requests to the MetadataWebService. So depending on your needs, filter out the type of document types / extensions / paths you are interested in. I needed just to know the hit count of .aspx pages in a specific sub site, so my query looked somewhat like this:

SELECT distinct(DocumentPath), COUNT(*) as DocCount
    FROM [RequestUsage]
    WHERE DocumentPath LIKE '/Marketing%'
      AND ( DocumentPath LIKE '%.aspx'   )
GROUP BY DocumentPath      

This is not a lesson in SQL, but that query gives me a nice list of all .aspx documents accessed under the Marketing sub site with the corresponding hit count. To get the top 5 out of that result, you’ll end up with something like this:

with cte as (
    SELECT distinct(DocumentPath), COUNT(*) as DocCount
    FROM [RequestUsage]
    WHERE DocumentPath LIKE '/Marketing%'
      AND ( DocumentPath LIKE '%.aspx'   )
    GROUP BY DocumentPath )
select top 5 DocumentPath, DocCount from cte order by DocCount desc

 

So we have a query we would like to run, and then you can display the result in a web part. There are numerous ways to do that, and I won’t cover it here but I’ll show the C# code for running this query. The following code snippet is put together from my actual project, and should give you enough information to piece together a working method. Take note of how the connection string for the WSS_Logging database is retrieved:

// run with elevated privileges
SPSecurity.RunWithElevatedPrivileges(delegate()
{
    string connectionString = SPUsageApplication.DefaultApplication.UsageDatabase.DatabaseConnectionString;
    SqlConnection connection = new SqlConnection(connectionString);

    // build your query
    StringBuilder sb = new StringBuilder();
    sb.Append("with cte ");
    sb.Append("as ");
    sb.Append("( ");
    sb.Append("SELECT distinct(DocumentPath), COUNT(*) as DocCount ");
    sb.Append("FROM [RequestUsage] ");

    // ...
    // add all the WHERE filters you want here
    // ...

    sb.Append(" GROUP BY DocumentPath ");
    sb.Append("");
    sb.Append(") select top " + ItemCount + " DocumentPath, DocCount from cte order by DocCount desc");
    string sql = sb.ToString();

    SqlCommand command = new SqlCommand();
    command.Connection = connection;
    command.CommandText = string.Format(sql, SPContext.Current.Web.ServerRelativeUrl);
    command.CommandType = System.Data.CommandType.Text;
    command.Connection.Open();

    SqlDataReader reader = command.ExecuteReader();
    while (reader.Read())
    {
        // access the fields, for example document name
        string docName = reader["DocumentPath"].ToString().Substring(reader["DocumentPath"].ToString().LastIndexOf('/') + 1);
        docName = HttpUtility.UrlDecode(docName);

        // build an HTML table, add items to a list or whatever you prefer
        // ..
    }

    // close the db connection
    command.Connection.Close();

}

The magic lies in how you build and define the filter to suit your requirements.

by Andreas

Sharepoint 2010 – Rename Contextual Search Label

One of the elements you don’t have control over in a Sharepoint 2010 environment is the label for the contextual search option in the search drop down list (“This Site: “ and the name of the current site):

image

The dynamic nature of the contextual search definition means that wherever you are in your Sharepoint solution where the search drop down list is visible you will have a “This Site: “ option.

In some cases you might want to change this text. One annoying situation is if your solution has a series of sites that share a common prefix, and this prefix is just long enough to take up all the visible real estate of the drop down box. Your users will then see “This Site: Long Site Prefix” for all sites, instead of the last part of the name which is actually unique.

This can be solved by adding some javascript to your page (non-jQuery, so no references required). Add a Content Editor web part and edit the contents by clicking the HTML drop down and selecting “Edit HTML source”:

image

Insert the following javascript:

<script type="text/javascript">
function SearchScDDLInj()
{
    var srhScDDL = document.getElementById("ctl00_PlaceHolderSearchArea_ctl01_SBScopesDDL");
    if (srhScDDL != null)
    {
        srhScDDL.options[0].text = "My custom value";
    }
}

SearchScDDLInj();

</script>

This script will search for the drop down list (identified by ‘ctl00_PlaceHolderSearchArea_ctl01_SBScopesDDL’) and replace the first value with “My custom label”.

Save the webpart and the search drop down list should now display your own value. If not, use something like the developer tools in IE and search for the correct id for the element (not name!). The easiest way is to search for whatever value currently displayed for contextual search (“This Site: Prototyping” in my case”) and then get the ID of the placeholder:

image

 

And there you go:

image

by Andreas

Sharepoint 2010 – display custom properties on Profile page

Tip #1:
Changing the order of properties displayed in the user profile page of MySite is a PITA if doing it through Central Admin (User Profile Service Application –> Manage User Properties). To move the item higher or lower you’ll trigger a postback for each and every single step, which takes a ridiculous amount of time. So download this tool from Codeplex and save yourself a bucketload of time.

Tip #2:
There are a few user profile properties that are shown by default, while the rest are visibly only by clicking the “More information” link. Changing the order of these is either simple (see tip #1) or time consuming and horrendous (use Central Admin). The properties visible by default (typically office and contact information) are not affected by the order you specify in Central Admin so how do you change them? And how do you add more properties? Open up the web application you use for MySite (usually something original like http://mysite) in Sharepoint Designer. Find Profile.aspx under “All files” and “Edit File in Advanced Mode”. Now you can use WYSIWYG editor capabilities to shape and alter the layout, and adding a new property only requires a new div tag with a reference to the property name (get the correct property name from “User Profile Properties” in Central Administration. Edit the details for the property you want to display, and get the “Name” property, e.g. “Pager” in this example):

<div style="padding-left: 20px;" class="ms-contactcardtext3" id="ProfileViewer_ValuePager">
Pager number: <SPSWC:ProfilePropertyValue PropertyName="Pager" dir="ltr" runat="server"/>
</div>

by Andreas

Sharepoint 2010 – how to show error details when debugging

Showing actual error details with the stacktrace is usually a quick change in web.config for any ASP.NET web application. For Sharepoint 2010 a few more steps are required, as there are several web.config files spread around.

In my case, the web.config files to change were:

C:inetpubwwwrootwssVirtualDirectories[your_web_app]
Set <customErrors mode=”On”> to Off
Set <SafeMode .. CallStack=”False”> to True
Set <Compilation batch=”False” to True and <Compilation Debug=”False” to True

C:Program FilesCommon FilesMicrosoft SharedWeb Server Extensions14TEMPLATELAYOUTS
Set <customErrors mode=”On”> to Off
Ensure <compilation batch=”   ”> is Off

C:Program FilesCommon FilesMicrosoft SharedWeb Server Extensions14CONFIG
Set <customErrors mode=”On”> to Off

by Andreas

Sharepoint 2010 – disable client side validation while in edit mode

If your web part uses client side validation you would have experienced how annoying this is when opening the page in Edit Mode. I knew there had to be a way to turn this off, but it wasn’t until today I actually spent a few minutes figuring it out. The solution is to add an IF statement in the Page_PreRender() method to check the current page mode, and then disable the client side script for the validation controls:

protected void Page_PreRender(object sender, EventArgs e)
{
    // determine if page is in Edit mode
    WebPartManager wp = WebPartManager.GetCurrentWebPartManager(Page);
    if (wp.DisplayMode == WebPartManager.EditDisplayMode)
    {
        // disable all client side validation
        RequiredFieldValidator1.EnableClientScript = false;
        RequiredFieldValidator2.EnableClientScript = false;
        ValidationSummary1.EnableClientScript = false;
    }
}