Making DelayActivity Work In SharePoint 2010

Posted by | Filed under , , , ,

In the previous MOSS 2007 version of SharePoint, there was an issue of delay activities in workflows not waking up because of how the SharePoint workflow runtime works.

 Sadly, Microsoft didn't reslove the issue by default with SharePoint 2010. You still have to jump through some hoops to get it running (usually after scratching your head as to why it doesn't work and scouring the internet for solutions).

 It turns out that the way to get things running is to dust off stsadm.exe and run the following commands:

stsadm -o setproperty -pn job-workflow -pv "Every 5 minutes between 0 and 59" -url http://webappurl
stsadm -o setproperty -pn workflow-eventdelivery-throttle -pv "45"

Thanks to StackOverflow for pointing me in the right direction.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Rename the "Title" Field in a SharePoint List Definition

Posted by | Filed under , , , ,

Sometimes you'll want to override the name of the default (required) "Title" field on a SharePoint list definition. At first, it's a bit confusing how to do so, because to make your "Title" rename comprehensive, you have to change not only the "Title" field's display name, but also "LinkTitle" and "LinkTitleNoMenu".

Luckily, doing so isn't difficult. Either find the fields below in your list definition, or add them in the <Fields/> element. From there, simply change the "DisplayName" attribute (not the "Name" or "StaticName", which should remain unchanged).

<Field DisplayName="Custom Title" ID="{fa564e0f-0c70-4ab9-b863-0177e6ddd247}" Type="Text" Name="Title" Required="TRUE" SourceID="http://schemas.microsoft.com/sharepoint/v3" StaticName="Title" FromBaseType="TRUE" />
<
Field DisplayName="Custom Title" ID="{bc91a437-52e7-49e1-8c4e-4698904b2b6d}" ReadOnly="TRUE" Type="Computed" Name="LinkTitleNoMenu" DisplayNameSrcField="Title" AuthoringInfo="(linked to item)" EnableLookup="TRUE" ListItemMenuAllowed="Prohibited" LinkToItemAllowed="Prohibited" SourceID="http://schemas.microsoft.com/sharepoint/v3" StaticName="LinkTitleNoMenu" FromBaseType="TRUE">
   <
FieldRefs>
      <
FieldRef Name="Title" />
      <
FieldRef Name="LinkFilenameNoMenu" />
   </
FieldRefs>
   <
DisplayPattern>
         <IfEqual>
            <Expr1>
                <LookupColumn Name="FSObjType"/>
       </
Expr1>
            <Expr2>1</Expr2>
                 <Then>
            <
Field Name="LinkFilenameNoMenu"/>
                </Then>
         <
Else>
            <
HTML><![CDATA[<a onfocus="OnLink(this)" href="]]></HTML>
            <
URL/>
            <HTML><![CDATA[" onclick="EditLink2(this,]]></HTML>
            <
Counter Type="View" />
            <
HTML><![CDATA[);return false;" target="_self">]]></HTML>
            <
Column HTMLEncode="TRUE" Name="Title" Default="(no title)" />
            <
IfEqual>
               <Expr1>
                 <
GetVar Name="ShowAccessibleIcon" />
               </
Expr1>
               <
Expr2>1</Expr2>
               <Then>
                  <HTML><![CDATA[<img src="/_layouts/images/blank.gif" class="ms-hidden" border="0" width="1" height="1" alt="Use SHIFT+ENTER to open the menu (new window)."/>]]></HTML>
               </Then>
            </
IfEqual>
            <HTML><![CDATA[</a>]]></HTML>
            <
IfNew>
               <HTML><![CDATA[<img src="/_layouts/1033/images/new.gif" alt="]]></HTML>
               <
HTML>New</HTML>
               <
HTML><![CDATA[" class="ms-newgif" />]]></HTML>
            </
IfNew>
         </
Else>
      </IfEqual>
   </DisplayPattern>
</Field>
<Field DisplayName="Custom Title" ID="{82642ec8-ef9b-478f-acf9-31f7d45fbc31}" ReadOnly="TRUE" Type="Computed" Name="LinkTitle" DisplayNameSrcField="Title" ClassInfo="Menu" AuthoringInfo="(linked to item with edit menu)" ListItemMenuAllowed="Required" LinkToItemAllowed="Prohibited" SourceID="http://schemas.microsoft.com/sharepoint/v3" StaticName="LinkTitle" FromBaseType="TRUE">
   <FieldRefs>
      <FieldRef Name="Title" />
      <
FieldRef Name="LinkTitleNoMenu" />
      <
FieldRef Name="_EditMenuTableStart2" />
      <
FieldRef Name="_EditMenuTableEnd" />
   </
FieldRefs>
   <DisplayPattern>
   <FieldSwitch>
      <Expr>
         <GetVar Name="FreeForm" />
      </Expr>
      <Case Value="TRUE">
         <Field Name="LinkTitleNoMenu" />
      </Case>
      <Default>
        <Switch>
          <Expr>
             <GetVar Name="MasterVersion" />
          </
Expr>
          <Case Value="4">
             <
HTML><![CDATA[<div class="ms-vb itx" onmouseover="OnItem(this)" CTXName="ctx]]></HTML>
             <
Field Name="_EditMenuTableStart2" />
             <
HTML><![CDATA[">]]></HTML>
             <Field Name="LinkTitleNoMenu" />
             <HTML><![CDATA[</div>]]></HTML>
             <
HTML><![CDATA[<div class="s4-ctx" onmouseover="OnChildItem(this.parentNode); return false;">]]></HTML>
             <HTML><![CDATA[<span>&nbsp;</span>]]></HTML>
             <HTML><![CDATA[<a onfocus="OnChildItem(this.parentNode.parentNode); return false;" onclick="PopMenuFromChevron(event); return false;" href="javascript:;" title="Open Menu"></a>]]></HTML>
             <
HTML><![CDATA[<span>&nbsp;</span>]]></HTML>
             <HTML><![CDATA[</div>]]></HTML>
          </Case>
          <Default>
             <
HTML><![CDATA[<table height="100%" cellspacing="0" class="ms-unselectedtitle itx" onmouseover="OnItem(this)" CTXName="ctx]]></HTML>
             <Field Name="_EditMenuTableStart2" />
             <HTML><![CDATA["><tr><td width="100%" class="ms-vb">]]></HTML>
             <
SetVar Name="ShowAccessibleIcon" Value="1" />
             <Field Name="LinkTitleNoMenu" />
             <
SetVar Name="ShowAccessibleIcon" Value="0" />
             <HTML><![CDATA[</td><td><img src="/_layouts/images/blank.gif" width="13" style="visibility:hidden" alt=""/></td></tr></table>]]></HTML>
          </Default>
       </Switch>
      </Default>
    </FieldSwitch>
   </DisplayPattern>
</Field>

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Serialize or Deserialize Any .NET Object To and From an XML String

Posted by | Filed under , , , , , , ,

A new and handy feature of C# 3.0 is "extension methods". Extension methods essentially allow you to write methods for classes that you may or may not have written yourself.

Additionally, a great feature of .NET 2.0 is "generics", which allow you to create templates of methods (and classes) for multiple types at once.

Combine extension methods and generics, and you can really cook up some trouble! In terms of XML serialization, you can code a few simple lines to handle all your XML string serialization needs.

Observe:

public static class Extensions
{
   public static string ToXml<T>(this T toSerialize)
   {
 
     var serializer = new XmlSerializer(typeof(T));
      var sb = new StringBuilder();
      using (var writer = new StringWriter(sb))
         serializer.Serialize(writer, toSerialize);
      return sb.ToString();
   }


   public static T DeserializeXmlString<T>(this string xml)
   {
     
var serializer = new XmlSerializer(typeof(T));
      using (var reader = new StringReader(xml))
         return (T)serializer.Deserialize(reader);
   }
}

Observe. After creating the class above and referencing its namespace in your code, the extension method becomes available for use so that you can perform serialization/deserialization trickery like so:

public class MyClass
{

   public
int IntProperty { get; set; }
   public string StringProperty { get; set; }
}

var mc = new MyClass(){ IntProperty = 1, StringProperty = "Test" };
var xml = mc.ToXml();
//output:
//<MyClass>
// <IntProperty>1</IntProperty>
// <StringProperty>Test</StringProperty>
//</MyClass>
var deserializedMc = xml.DeserializeXmlString<MyClass>();

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Getting the Strong Name of an Assembly (Now That Reflector 6.8 Doesn't Seem To)

Posted by | Filed under , , , ,

Red Gate software recently updated their Reflector product to the last free version (6.8). Unfortunately, they also seemed to take away the feature I used the most, namely the ability to get the strong name of an assembly (which is often needed for SharePoint development).

 Luckily, the tool's capability is easy to replace. I simply created a Windows Forms app with a Button, an OpenFileDialog and a TextBox for displaying the strong name. The code to extract the full name of the assembly is as follows, which I added here in the Button.Click event handler. Naturally, button1 is the Button, openFileDialog1 is the OpenFileDialog and textBox1 is the TextBox. You can rename or change the controls however you wish.

private void button1_Click(object sender, EventArgs e)
{

    // Show the open file dialog and get user input.
    DialogResult result = openFileDialog1.ShowDialog();
    if (result == DialogResult.OK)
    {
        // Assuming you pick a .dll, this code will load it and then display
        //the strong name in the TextBox control of the form.

         var
assembly = Assembly.LoadFile(openFileDialog1.FileName);
         textBox1.Text = assembly.FullName;
    }
}

 UPDATE: RedGate fixed the problem and the strong name section is there again if you download the latest version.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

The Very Basics of a Custom ConfigurationSection

Posted by | Filed under , , ,

In my view, the custom configuration API in .NET is one of the most underappreciated tools at a .NET developer's disposal.

 The .NET Framework team made it dirt simple to create configuration extensions that harness the capabilities you're used to. With one simple class, you have all you need to add entries to web.config/app.config and machine.config files, you have rich API's supporting features like XML encryption, and you do it all without any XML parsing logic or file IO!

 At the core, a custom configuration section consists of three pieces:

  1. A class that inherits from System.Configuration.ConfigurationSection (be sure you add a reference to System.Configuration).
  2. A registration of your custom configuration section in configSections element your .NET configuration file.
  3. The XML configuration itself, which you add later in the file.

We'll examine each f these parts seperately, and briefly cover what you need to know about each.

 First, the ConfigurationSection class! In my case, I created an overly simplified section that includes the email address of someone you want to send notifications to.

 In it, you'll want to pay attention to four things. First, data access is handled by ConfigurationManager though of note is that WebConfigurationManager, a web-centric class with extra capabilities, may also be used for web apps. The second thing to note is the path we use to access our configuraiton section, "cSharpConsultant/notifications" in our case. This corresponds to our configuration XML and the configSections entry we make for it.

 Third, notice how we implemented our property via a ConfigurationPropertyAttribute. The "emailAddress" value we use in the attribute works in conjuction with the property getter and setter to access the internally parsed and managed configuraiton value. You'll see later on that "emailAddress" directly relates to an XML attribute in our custom configuration.

 Lastly, see how we can apply validation rules to our property via a RegexStringValidatorAttribute. RegexStringValidator is just one of the many available rules we can apply to our configuration property. The biggest gotcha to note, however, is that the validation rules will run on the default value of a property before they validate the actual value in the configuration file. This means that without a "DefaultValue" set in ConfigurationProperty, our RegexStringValidator would actually run against a blank default value and throw an exception saying "The value does not conform to the validation regex string"!

public class NotificationsConfigurationSection : ConfigurationSection
{
  private const string configPath = "cSharpConsultant/notifications"
  public static NotificationsConfigurationSection GetSection()
  { 
    return (NotificationsConfigurationSection) 
      ConfigurationManager.GetSection(configPath);
  }

  /*This regular expression only accepts a valid email address. */ 
  [RegexStringValidator(@"[\w._%+-]+@[\w.-]+\.\w{2,4}")] 
  /*Here, we register our configuration property with an attribute. 
  Note that the default value is required if we use 
  the property validation attributes, which will unfortunately 
  attempt to validate the initial blank value if a default isn't found*/
  [ConfigurationProperty("emailAddress", DefaultValue=Address@Domain.com)]
  public string EmailAddress
  { 
    get{ return (string)this["emailAddress"]; }
    set{ this["emailAddress"] = value; }
  }
}

 The second part of our setup is to register our configuration class in the file where we want to use the configuration. At the top of all .NET configuration files is a "configSections" element, where we'll register the schema and type of custom ConfigurationSection. Notice how our setup relates to "cSharpConsultant/notifications", the path we used to access our section in the above code.

<configSections> 
  <sectionGroup name="cSharpConsultant">
    <section name="notifications"
        type="ConfigurationSample.NotificationsConfigurationSection,
        ConfigurationSample, Version=1.0.0.0, 
        Culture=neutral, PublicKeyToken=null"/>
</sectionGroup>

Finally, to complete our setup, we need the actual configuration! Notice how the attribute "emailAddress" relates to the ConfigurationProperty value we registered in our custom configuration section's "EmailAddress" property.

<cSharpConsultant>
    <notifications emailAddress="NotifiedPerson@Domain.com"/>
</cSharpConsultant>

 That's it! Now to access our custom configuration, it's as simple as this!

NotificationsConfigurationSection section 
  = NotificationsConfigurationSection.GetSection();
string emailAddress = section.EmailAddress;

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Adding a CSS Style & Class To An ASP.NET Page Header

Posted by | Filed under , ,

 There are a variety of techniques out there for wiring up a CSS class to an ASP.NET Web Form through code. You can register a link to a CSS file via Page.Header.Controls.Add() and ASP.NET 2.0 introduced the robust WebResource framework for registering entire style sheets for a given page, but what about when you want to add a dynamic style to the HTML  header?

Typically, the technique would involve something like this:

Page.Header.Controls.Add(
    new LiteralControl(
        @"<style type='text/css'>
                /*type selector*/
                BODY
                {
                    background: Aqua;
                }
                /*class selector*/
                .myClass
                {
                    background: WhiteSmoke;
                    font-size: 20pt;
                }
                </style>
            "

        )
);

...but there are drawbacks to the approach including the need for verbose "style" tags with each chunk of CSS styles you want to add and the lack of validation on style names and values.

Luckily, there's a more sophisticated and elegant approach supported by .NET Framework 2.0 or higher using Page.Header.Stylesheet and the System.Web.UI.WebControls.Style class. With the approach, instead of having to define your CSS class using a string, you can used strongly-typed objects instead! Additionally, all of the styles you add will get added to one single style attribute in the Page header.

Style typeStyle = new Style();
typeStyle.BackColor = Color.Aqua;
Page.Header.StyleSheet.CreateStyleRule(typeStyle, null, "BODY");

Style classStyle = new Style();
classStyle.BackColor = Color.WhiteSmoke;
classStyle.Font.Size = FontUnit.Parse("20pt");
Page.Header.StyleSheet.CreateStyleRule(classStyle, null, ".MyClass");

There is, however, a drawback to the approach which is the limited number of properties available in the Style base class. For instance, if you wanted to set a value for the "margin" CSS style, you'd need to either use or create a subclass of Style that overrides the AddAttributesToRender() method.

Currently rated 4.5 by 2 people

  • Currently 4.5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5