Category Archives: .Net

SharePoint 2010 Beta – ConfigurationErrorsException

If you’ve installed the SharePoint 2010 public beta, you’ve likely run into the WCF bug. This following errors occur when provisioning Service Applications or when accessing pages that make service calls.

System.Configuration.ConfigurationErrorsException: Unrecognized attribute ‘allowInsecureTransport’. Note that attribute names are case-sensitive. (C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\WebClients\<Service Area>\client.config line <Line Number>).

The service application proxy “User Profile Service Application” could not be provisioned because of the following error: Unrecognized attribute ‘allowInsecureTransport’. Note that attribute names are case-sensitive. (C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\WebClients\Profile\client.config line 56).

You may see this error in the ULS logs after installing SharePoint 2010, or displayed on the page as an error message when provisioning service applications or accessing SharePoint pages that make WCF service calls.

How To Fix It

This is a known WCF issue when installing SharePoint 2010 on Windows 7, Windows Server 2008, or Windows Server 2008 R2.  It’s, lovingly called the WCF Sharepoint Shared Services Roll-up issue. To fix it, install a WCF OS patch:

KB971831: WCF fix for Windows Server 2008 and Vista only
http://support.microsoft.com/kb/971831

KB976462: WCF fix for Windows 2008 R2 and Windows 7
http://support.microsoft.com/kb/976462 
Note:  This link is not activated yet, but you can download the WCF fix at http://go.microsoft.com/fwlink/?LinkID=166231

If you have already installed Microsoft SharePoint Server 2010 on a server running Microsoft Windows Server 2008 R2 or Microsoft Windows 7, Microsoft SharePoint Server 2010 does not need to be reinstalled. You can install the WCF fix afterward. However, Service Applications that have been provisioned without the update installed may need to be removed and re-provisioned once the update has been successfully applied.

References

SharePoint Team Blog: Installation Notice for the SharePoint Server Public Beta on Microsoft Windows Server 2008 R2 and Microsoft Windows 7

Jie Lie’s GeekWorld: SharePoint 2010 Pre-Requisites Download Links

Get a Distinct List from ADO.Net DataSet Using Linq

There are some sample .Net functions out there to pull a list of distinct items from an ADO.Net DataTable, but none of them I found take advantage of LINQ.  So I thought I would post something I came up with to fill the gap.

In the code sample below, the goal is to pull a list of distinct values from a single column in a DataTable.  There are a few ways to approach this, depending on the end-game.  I listed 4 options, 2 with LINQ syntax and their Lambda expression twins.

// —————————————————————–
// Build a list DataTable to test
// —————————————————————–
DataTable tbl = new DataTable();
tbl.Columns.Add(“Title”, typeof(string));
for (int i = 1; i <= 100; i++)
{
    // Add 1 row
    DataRow row1 = tbl.NewRow();
    row1["Title"] = string.Format(“Title {0}”, i);
    tbl.Rows.Add(row1);

    // Add duplicate row
    DataRow row2 = tbl.NewRow();
    row2["Title"] = string.Format(“Title {0}”, i);
    tbl.Rows.Add(row2);

    // Add null row for testing
    DataRow row3 = tbl.NewRow();
    row3["Title"] = DBNull.Value;
    tbl.Rows.Add(row3);
}

// —————————————————————–
// All four of these examples yield the same results
// Each returns a list of 100 distinct rows
// Pick your poison!
// —————————————————————–

// Sample 1
// —————————————————————–
// Get a distinct list of titles
// Linq syntax against the DataTable using
// This is functionally the same as the 2nd example
List<string> distinctTitles2 =
        (from r in
            (IEnumerable<DataRow>)tbl.AsEnumerable()
            where !string.IsNullOrEmpty(r.Field<string>(“Title”))
            select r.Field<string>(“Title”)).Distinct().ToList();

// Sample 2
// —————————————————————–
// Get a distinct list of titles
// Lambda expression against the DataTable 
// This is functionally the same as the 1st example
List<string> distinctTitles1 = ((IEnumerable<DataRow>)tbl.AsEnumerable())
            .Select<DataRow, string>(r => r.Field<string>(“Title”))
            .Where(title => !string.IsNullOrEmpty(title))
            .Distinct().ToList();

// Sample 3
// —————————————————————–
// Get a distinct list of titles
// On this one, I’m using the tbl.Select() method to get an array of DataRows matching filter criteria
// Linq expression is then used against the DataRow array to get distinct titles
// This is functionally the same as the 4th example
List<string> distinctTitles4 =
        (from r in
        tbl.Select(“Title IS NOT NULL And TRIM(Title) <> ””)
        select r.Field<string>(“Title”))
        .Distinct().ToList();

// Sample 4
// —————————————————————–
// Get a distinct list of title
// On this one, I’m using the tbl.Select() method to get an array of DataRows matching filter criteria
// Lambda expression against the DataRow array to get distinct titles
// This is functionally the same as the 3rd example
List<string> distinctTitles3 = tbl.Select(“Title IS NOT NULL And TRIM(Title) <> ””)
        .Select(r => r.Field<string>(“Title”))
        .Distinct().ToList();

Enjoy!

 

  del.icio.us it! digg it! reddit! technorati! yahoo!

COM Interop – QueryInterface not supported (E-NOINTERFACE)

Problem

Encountering an error when trying to instantiate COM objects through Primarary Interop Assemblies (PIA’s) or Runtime Callable Wrappers (RCW’s) created using the TLBIMP.exe tool. 

When calling the object for the first time, you encounter the following COM exception:

Unable to cast COM object of type ‘xxx to interface type ‘xxx’. This operation failed because the QueryInterface call on the COM component for the interface with IID ‘{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}’ failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)).

You are likely to encounter this problem when developing ASP.Net applications, Windows Console applications, or Windows Services.  You are unlikely to experience this issue when developing Windows Forms applications.

Solution

The problem is that you are attempting to call Single-Threaded Apartment (STA) model COM components from an Multi-Threaded Apartment (MTA) thread.  The primary thread of Windows Forms applications are STA threads, so the components work fine there.  Most other project types, including Console applications and Windows Service applications are run on an MTA thread by default.  When you attempt to instantiate the an STA component, you will get the ubiquitous error described above.

You might try calling System.Threading.Thread.CurrentThread.SetApartmentState(ApartmentState.STA), but this won’t work.  You cannot change the thread execution model on a running thread. 

To fix the problem, you can set the thread execution type on the main application thread before it is started, but this is not optimal.  It is better to set the threading model specifically for the portion of code that needs it.

A better solution is to spin up a new thread for the job at hand, and set the thread execution state on the new thread before executing it.  There are a few different methods to accomplish this depending on what you’re trying to accomplish.  Here’s one to get you started:

using System.Threading;
...

// Setup an object to host the thread entry point
// Start a process on an MTA thread 
MyThreadedJob jobHost = new MyThreadedJob(jobId);
Thread t = new Thread(new ThreadStart(MyThreadedJob.Execute));
t.SetApartmentState(ApartmentState.MTA);

// Start the thread
t.Start();

// Wait for thread to complete (optional)
t.Join();

 

More Gory Details

For more of the gory details and differences between threading models in Windows and COM, you can start here.

 

  del.icio.us it! digg it! reddit! technorati! yahoo!

SharePoint 2007 – Get SPList Object by Url

I want to get a reference to a SPList object associated with a given list url.  This method works with any of the url’s associated with the list, including view page url’s, or list form url’s. 

This should be much easier to achieve by using the object model, in my opinion.  String parsing of the url is not my favorite, but I couldn’t find a better way to accomplish it. 

If you know of an easier way to accomplish this, please leave me a comment.  Otherwise, you can steal this from me, if you want it!

/// <summary>
/// Gets an SPList based on the url to the list
/// </summary>
/// <param name="listUrl">Full url to the list</param>
/// <returns>SPList object, null if list is not found</returns>
public SPList GetListByUrl(string listUrl)
{
    SPList list = null;

    try
    {
        using (SPSite site = new SPSite(listUrl))
        {
            if (site != null)
            {
                // Strip off the site url, leaving the rest
                // We'll use this to open the web
                string webUrl = listUrl.Substring(site.Url.Length);

                // Strip off anything after /forms/
                int formsPos = webUrl.IndexOf("/forms/", 0, StringComparison.InvariantCultureIgnoreCase);
                if (formsPos >= 0)
                {
                    webUrl = webUrl.Substring(0, webUrl.LastIndexOf('/', formsPos));
                }

                // Strip off anything after /lists/
                int listPos = webUrl.IndexOf("/lists/", 0, StringComparison.InvariantCultureIgnoreCase);
                if (listPos >= 0)
                {
                    // Must be a custom list
                    // Strip off anything after /lists/
                    webUrl = webUrl.Substring(0, webUrl.LastIndexOf('/', listPos));
                }
                else
                {
                    // No lists, must be a document library.
                    // Strip off the document library name
                    webUrl = webUrl.Substring(0, webUrl.LastIndexOf('/'));
                }

                // Get the web site
                using (SPWeb web = site.OpenWeb(webUrl))
                {
                    if (web != null)
                    {
                        // Initialize the web (avoids COM exceptions)
                        string title = web.Title;

                        // Strip off the relative list Url
                        // Form the full path to the list
                        //string relativeListUrl = listUrl.Substring(web.Url.Length);
                        //string url = SPUrlUtility.CombineUrl(web.Url, relativeListUrl);

                        // Get the list
                        list = web.GetList(listUrl);
                    }
                }
            }
        }
    }
    catch { }

    return list;
}

Enjoy!

  del.icio.us it!

digg it!

reddit!

technorati!

yahoo!

SharePoint TechFest 2009 – Dallas, TX

I want to thank everyone who attended my session on SharePoint Workflow with Visual Studio at our TechFest event yesterday.  Please feel free to post any comments (good or bad) about my presentation or the event. 

Demo source code is posted on Nakido until the Techfest site is updated with session content.

SharePoint WorkFlow with Visual Studio – Downloads

SharePoint WorkFlow with Visual Studio – References

  del.icio.us it!

digg it!

reddit!

technorati!

yahoo!

Visual Studio 2008 Workflow Project Wizard – SharePoint Not Installed

Problem:

I’m creating a SharePoint Sequential Workflow using Visual Studio 2008 (SP1) with .Net 3.5 SP1 installed.  This is on a Windows 2003 R2 VPC with SharePoint 2007 (MOSS Enterprise) installed on the local machine for development.  A Collaboration Portal is installed on a web site with host headers (portal) assigned to port 80.

When I create a new workflow project, the wizard asks for a path to the SharePoint site.  I type in my url (http://portal in my case), and the project wizard fails, saying “SharePoint server not installed. Please run Microsoft Office SharePoint Server 2007 setup.”  

VS2008WF-SharePointNotInstalled

I’m logged in as the farm administrator.  I thought it might be a permissions issue (my farm admin doesn’t have full rights on the domain), so I went back and gave it full Domain Admin rights in case that was the problem.  Still failing!!

What the hell?

Resolution:

It turns out that the wizard does some funny business behind the scenes, calling the database directly.  When I give my development account (farm admin) account full rights (dbo) to the SharePoint content database for my portal site, bingo!  Works like a champ. 

After only an hour or two spinning my wheels.  Sigh….

  del.icio.us it!

digg it!

reddit!

technorati!

yahoo!

SharePoint – WSPBuilder Workflow Failed On Start

Building a SharePoint 2007 workflow using WSPBuilder and Visual Studio 2008.  Love, love, love the WSPBuilder tool, but the workflow templates could use some work.  Ran into this one today…

Problem

I was receiving “Failed on Start (retrying)” errors.  SharePoint logs showed “The workflow failed validation” exceptions.  This usually means a problem with the .rules files associated with a Declarative Rule Condition.  

I changed my While activities to use code conditions instead, and the problem went away.  But I really wanted to find the source of the issue.  After much trial and error and fruitless searches on the web, I finally found it.  Turns out, it was a missing import target declaration in the .csproj file created by WSPBuilder when I created a workflow project using the “WSPBuilder Workflow with Workflow” project template.

Resolution

To fix the problem, opened up the project file and added the missing import target line (in green), below. Evidently, this line tells studio to include the .rules in the assembly.

     <Import Project=”$(MSBuildBinPath)\Microsoft.CSharp.targets” />
     <Import Project=”$(MSBuildExtensionsPath)\Microsoft\Windows Workflow Foundation\v3.5\Workflow.Targets” />

Reopened the project, recompile, build wsp, redeploy.  Bingo!  Now my workflow works with Declarative Rule Conditions, as it should!

Credits

Thanks to Greg G’s post here that pointed me in the right direction.

: del.icio.us it!

digg it!

reddit!

technorati!

yahoo!

SharePoint 2007 API – How To Change Layout and Publish Page

The hardest part about this (by far) is figuring out how to publish the page after you’ve made your changes.   Every time I need to do it, I have to dig up some old code.

Thought I’d blog it this time, to make it easier on myself next time around.

using Microsoft.SharePoint;
using Microsoft.SharePoint.Publishing;
...

using (SPSite site = new SPSite("http://portal"))
{
    SPWeb web = site.RootWeb;

    // Check to ensure the web has publishing turned on
    if (!PublishingWeb.IsPublishingWeb(web))
    {
        throw new ApplicationException("Web does not have publishing enabled");
    }

    // Get a reference to the publishing web and publishing site    
    PublishingWeb pubWeb = PublishingWeb.GetPublishingWeb(web);
    PublishingSite pubSite = new PublishingSite(web.Site);

    // Get page layout from the page layouts collection    
    PageLayoutCollection siteLayouts = pubSite.GetPageLayouts(false);
    PageLayout myLayout = siteLayouts["/_catalogs/masterpage/MyLayout.aspx"];

    // Get a reference to a publishing page
    PublishingPageCollection pages = pubWeb.GetPublishingPages();
    PublishingPage page = pages["pages/default.aspx"];
    
    // Check out the list item as needed
    bool forceCheckout = page.ListItem.ParentList.ForceCheckout;
    if (forceCheckout)
    {
        // Is the page checked out?
        if (page.ListItem.File.CheckedOutBy != null)
        {
            // Throw an exception if the page is checked out
            string pageCheckedOut = string.Format("Page {0} is checked out by {1}", page.Url, page.ListItem.File.CheckedOutBy);
            throw new SPException(pageCheckedOut);
        }

        // Check out the page
        page.CheckOut();
    }

    // Change the page layout
    page.Layout= myLayout;

    // Update the page and check in changes
    page.Update();

    // Publish the page
    // This handles the page checkin and publishing the draft
    ApprovePublishingPage(page, "Modified page layout");

}

/// <summary>
/// Approves changes to a publishing page
/// </summary>
/// <param name="page">PublishingPage with changes to be published</param>
/// <param name="comment">Comment associated with the change</param>
public void ApprovePublishingPage(PublishingPage page, string comment)
{
    // Check in the page if required
    SPFile pageFile = page.ListItem.File;
    if (pageFile.Level == SPFileLevel.Checkout)
    {
        pageFile.CheckIn(comment, SPCheckinType.MajorCheckIn);
    }

    // Skip these steps if the parent list doesn't support moderation
    if (page.ListItem.ParentList.EnableModeration)
    {
        // If page is in "pending" status, approve it
        SPModerationInformation modInfo = page.ListItem.ModerationInformation;
        if (modInfo.Status == SPModerationStatusType.Pending)
        {
            pageFile.Approve(comment);
        }

        // If page is in draft status, publish it
        if (modInfo.Status == SPModerationStatusType.Draft)
        {
            pageFile.Publish(comment);
        }
    }
}

Enjoy!

  del.icio.us it! digg it! reddit! technorati! yahoo!

WPF XAML Markup – How Do I Preserve Whitespace Characters?

An issue you’re likely to run into in XAML (WPF, XBAP, and SIlverlight applications) is the need to keep whitespace characters intact in your markup.  By default, XML collapses all whitespace, ignoring strings of spaces, tabs, and return characters inside an XML node, which it graciously converts to a single space.

If you want to include a series of spaces in your XML node markup, you can add a xml:space=”preserve” attrbute to your XML elements.  This attribute  is part of the XML standard.  If you turn it on, it preserves all whitespace appearing inside the XML node, including any hard return characters included inside the XML node.

<Button Name="btnSample" xml:space=preserve">Respects my      spaces
and carraige return</Button>
  del.icio.us it! digg it! reddit! technorati! yahoo!

WPF / WF – What Is A Dependency Property?

A new type of property, called a dependency property, was added to the .Net Framework with the release of .Net 3.0.  Dependency properties are used in both Windows Presentation Foundation (WPF) and Workflow Foundations (WF).  They are very similar in both frameworks, but are used for different purposes.

Dependency properties provides the plumbing for property value resolution, change notification, data binding, styling, validation, etc. for properties exposed in Windows Presentation Foundation (WPF) UI elements and Workflow Foundations (WF) custom activities.  Each dependency property is registered with a central repository that handles the change event notifications for you. 

Key Point – The Value of Dependency Properties Are Resolved

The ultimate goal of a dependency property, like any property, is to manage state.  But unlike normal .Net properties, the local property value is not stored in an instance variable. 

Instead, dependency properties are registered with the dependency property framework, and the underlying property value is resolved – meaning the value is determined by the dependency property framework based on rules defined by the property registration.

How To Create A Dependency Property

All WPF UI elements and Workflow Activities are derived from a high-level base classes called DependencyObject, which provides the basic functionality required to implement dependency properties.

public class MySampleControl : Control
{
    // Step 1: Register the dependency property 
    public static readonly DependencyProperty SpecialBrushProperty =
            DependencyProperty.Register("SpecialBrush", typeof(Brush), 
            typeof(MySampleControl));

    // Step 2: Provide set/get accessors for the property
    public Brush SpecialBrush
    {
        // IMPORTANT!!
        // -----------
        // Dependency property accessors should not include custom logic 
        // because the framework may call the base.GetValue() and 
        // SetValue() methods directly
        get { return (Brush)base.GetValue(SpecialBrushProperty); }
        set { base.SetValue(SpecialBrushProperty, value); }
    }
}

As show in the code, there are two steps involved in creating a dependency property:

  1. Create a static field to hold a DependencyProperty object
    • By convention, the field should be named with the normal property name, followed by a “Property” suffix
    • This field will not contain the value of the property.  It simply defines the property that is registered with the dependency system
    • This field should be defined as a public, static, read-only field
      • The property must be available at all times, possibly shared among classes
      • The field is defined with the read-only keyword, meaning it can only be set in the static constructor of the type.
    • The field must be instantiated with a call to the static DependencyPropert.Register() method, passing:
      • The name of the property
      • The type of the property 
      • The type of the class that owns the property
      • Optionally, metadata used to define how the property is treated by the WPF framework
        • Meta-data flags to specify how the property affects the layout of the element (AffectsMeasure, AffectsArrange, AffectsRender, etc.)
        • Callbacks for handling property value changes (PropertyChangedCallback)
        • Callbacks to define custom value logic (CoerceValueCallback) 
        • Callbacks to validate values (ValidateValueCallback)
      • Optionally, metadata used to define how the property is treated by the WF framework
        • Include DependencyPropertyOptions enumerated value to specify additional characteristics for the property (ReadOnly, MetaData, etc.)
  2. Create property accessors (get / set)
    • Call DependencyProperty.SetValue() and GetValue() methods to set local values
    • DependencyObject is a high-level framework base class for WPF UI elements and WF activities
    • DependencyObject exposes the GetValue() and SetValue() methods

Isn’t That A Lot of Code for a Property?

At first glance, yes, this looks like an extremely complicated way to declare a property.  OK, at second glance, it’s still pretty complex.  But once you understand the power of dependency properties provide, especially in the Windows Presentation Framework (WPF), they’ll become a welcome addition to your coding toolbox. 

The convention takes a little getting used to. But after you’ve created a few, it comes quite naturally.  Visual Studio also includes some snippets to help add dependency properties:

  • Insert Snippet > NetFX30 > Define a DependencyProperty
  • Insert Snippet > Other > Workflow > DependencyProperty > Property

Subtle Differences Between in WPF and WF

While WPF and WF both use a similar dependency property frameworks, they are not identical!!

WPF UI elements and WF activities derive from a base DependencyObject class, and use a DependencyProperty class to register properties and get/set property values.  Despite the shared names, they are not the same classes!!

  • DependencyObject and DependencyProperty classes used by WPF reside in the System.Windows namespace
  • DependencyObject and DependencyProperty classes used by WF reside in the System.Workflow.ComponentModel namespace

Though their usage and function are very similar, they are not directly related to one another.

How are Dependency Property Values Resolved?

Property values for dependency properties are resolved automatically by the framework according to the following order of precedence:

  1. Property system coercion
  2. Active animations or animations with a hold behavior (WPF)
  3. Local value
  4. TemplateParent template properties (WPF)
  5. Implicit style (WPF)
  6. Style triggers (WPF)
  7. Template triggers (WPF)
  8. Style setters (WPF)
  9. Default (theme) style (WPF)
  10. Inheritance
  11. Default value from dependency property metadata

Note that the local value is 3rd in the order of precedence.  This means that a property may have a value, even if a local value for the property has never been set.  Also, if a property does have a local value, it may be overridden by higher level precedence items like an animation or data binding.

When Should I Use Dependency Properties In WPF?

Dependency properties are one of the most important concepts within WPF.  In WPF, dependency properties are required to support:

  • Data Binding
  • Animation
  • Styling
  • Value expressions
  • Property invalidation
  • Per-type default values

In short, it makes sense to expose dependency properties any time you expose a property for a custom UI element or control. 

When Should I Use Dependency Properties In WF?

Dependency properties are not used as heavily in Workflow Foundations (WF) as they are in Windows Presentation Foundation (WPF) , but they are still an important part of the WF framework.  They are used primarily when developing custom workflow activities that expose properties to support the following scenarios:

  • Activity Binding
    • This is the most common use of dependency properties in WF
    • Allows activities to expose properties that can be used to bind state to another activity
    • For example, binding the input of one workflow activity to the output of another workflow activity
  • Attached Properties
    • Attached properties are used to create a parent activity that can manage the state of it’s child activities
    • For example, the Conditioned Activity Group can attach a When property to each child
  • Meta Properties
    • Meta properties are defined by including new PropertyMetadata(DependencyPropertyOptions.Metadata) in the DependencyProperty.Register() method call 
    • Meta properties are set at design time and cannot be changed at run-time
    • Meta properties exist to guarantee the integrity of an activity
    • For example, at runtime, you can’t change the InterfaceType of an CallExternalMethod activity because InterfaceType is a meta-property

Sources

  del.icio.us it!

digg it!

reddit!

technorati!

yahoo!