Writing Extension Methods for SharePoint

Extension methods are a formidable programming construct that augment implementation abstraction and modularize segments of code, lending itself well for filling gaps that may be present in a closed API, such as the one that SharePoint provides. Often times there may be a particular method that is desirable on a particular type, however the options for providing it are not available in the shipped API due to sealing and other modifies. Using Extension methods, it is possible to bypass this limitation while maintaining a clean implementation that can avoid deep inheritance tree references.

Extension methods are increasingly important when working with SharePoint code because a majority of objects that would normally mandate customizations of behavior, for example on SPList types, is decorated with a sealed access modified thereby negating possible inheritance. This is most noticeable when you are working with mock objects, which outside of certain frameworks (i.e. TypeMock) require an unsealed class and a default constructor.

As opposed to providing the method definition within the class, an extension method is simply defined by an association and contained in a separate static class supported by partial class constructs (i.e. it must exist in a namespace in the current scope). The method itself is invoked using instance method syntax, allowing some level familiarity in the code constructs. While the method is static, it can be called only on instances as defined in the parameters. In essence, an extension method will allow injection of a method into another class, so it is declared as if it is part of it.

In order to decrease method ambiguity due to extensions methods being defined only by the method name, it is important to take into account the appropriate naming convention (in fact, if the signature is the same the extension will be ignored!). Furthermore, the SharePoint types that will be extended are of course subject to the revisions of the API as released by MSFT. Therefore, when the API changes, there may not be the desired level of backwards compatibility.

The syntax for an extension method is very simple (it is important to note that while VB.NET requires the Extension attribute to be defined, C# does not. However in C# we are forced to create a copy of the object / return value so it evens it out!).

[csharp]
public static class Extensions
{
public static Type DoSomething(this Type type)
{
// let’s get something going!
}
}
[/csharp]

You can see that in the static Extensions class the DoSomething method has its sole parameter decorated with the this keyword modifier, to indicate the type to which this method will extend. So, for example when writing extension methods to extend the SPList class (without any supplementary parameters), our class would like this:

[csharp]
public static class Extensions
{
public static Type DoSomething(this SPList list)
{
// let’s get something going!
}
}
[/csharp]

But that isn’t doing much, so let’s take a more pragmatic example.

In the below, I am assuming that within an application, on SPList objects, I am going to be frequently reordering the current instance SPListItem collection into a descending order by the modified date, and then retrieving the last 5 items.

In the HarvestLastFive, it is noticeable that I am firstly specifying the type to target by using the this keyword with the SPList type. Following, I am building a SPListItemCollection of the SPList.Items, which then uses the LINQ OrderByDescending method in combination with the SPBuiltInFieldId.Modified property to handle the ordering. Lastly, Take returns the first 5 items out of the modified collection. If you just wanted the reordering (a variety of extensions I use daily use such LINQ collection modifiers for enhanced manipulation support) you would just take out the Take statement.
[csharp]

public static class Extensions
{
public static IEnumerable HarvestLastFive(this SPList typeToTarget)
{
try
{
SPListItemCollection collection = typeToTarget.Items;
var finalCollection = tempCollection.OrderByDescending(x => x[SPBuiltInFieldId.Modified]).Take(5);
return finalCollection;
}
catch (Exception exception)
{

}
return null;
}
}[/csharp]

You can see in the members of the Extensions class, that the HarvestLastFive method has a different icon (little down arrow) which specifies it as an extension method.

Using the method in a class is analgous to other methods available on that type. For example, the HarvestLastFive method takes on the form:
[csharp]
public static void TestingExtensionMethod()
{
SPList list = SPContext.Current.Web.Lists[“My List”];
var collection = list.HarvestLastFive();
// Do whatever you want!
}[/csharp]

Within Visual Studio, this method is noted as an extension method on the ToolTip with the prefix (extension).

This should give you enough to get going on extension methods. I will be posting some of my common extension methods that I use with SharePoint shortly, as this was meant to be an introduction.

Share

Implementing Flood Control to Protect Your SharePoint Server

* This article was written in the context of Internet Security and Acceleration (ISA) 2006, a technology now considered deprecated with the introduction of Forefront Threat Management Gateway (TMG). Variations may exist. *

What is Flooding?

Flooding as a malicious computer term is becoming almost a household term, through the media news regarding denial of service attacks on different corporations, in different industries, for different purposes. SharePoint portals are a particularly attractive target since businesses will tend to rely on them for virtual teams, therefore attacking on with a flood attack could cause a disruption of businesses that could prove an exceptional benefit for competitors. A flood attack in general, is a targeted flood of information geared to a certain service or sets of services so that requesting data from an arbitrary resource is not possible.

How are flood attacks triggered?

Floods can be tripped by malicious users in a variety of ways, intentionally or unintentionally. Intentionally flooding is usually performed by using prewritten, language independent applications (however not typically in .NET since languages such as C# or VB.NET do not allow the granularity of threading and managed process execution that is needed for effective flooding applications). There are several that a person can just download, type in a target, and let it execute. Otherwise more talented parties will create a flooding application tiered towards a client to effectively render the targeted network or server obsolete. Unintentional flooding usually happens with a user inadvertently executing a worm or virus within the network that it can propagate across, which will later trip a flooding attack internally against the SharePoint portal.  

Didn’t ISA Server 2004 Have Flood Control?

ISA Server 2004 did have flood control, to a certain extent. In regards to control, ISA server 2004 more provided methods that would allow a person certain mechanisms of protection against certain, defined flooding attacks, however didn’t provide a needed universal solution (quota capability). Within a flood attack, there is certain information that has to be extracted during and after the attack to properly secure a SharePoint environment from future attacks:

  • Is the gateway (ISA) under attack, or is SharePoint directly under attack?
  • What type of flooding attack is it? DDOS? DOS? Worm? Known virus?
  • What service is being attacked?
  • Is the service currently down or under possibility of being brought down?
  • Is forensic analysis possible on the attacked server?
  • How can this attack be prevented in the future?

What does ISA Server 2006 Offer in Terms of Flood Control?

ISA Server introduces a new feature which is called Flood Resiliency, meant to enhance the amount of flood control that you can offer to protect your vital SharePoint assets. This new feature enhances your visibility and control over flood attacks during and after they occur.

The granular flood controls offered by ISA server 2006 are meant to mitigate flood risks to your environment through a variety of mechanisms, mostly be specifying connection limits.

There are several things that it is meant to protect against:

  • Worms and Viruses That Trip Floods
  • Various DOS (Denial of Service) Attacks
  • Various DDOS (Distributed Denial of Service) Attacks (one in which more than one machine is taken over to perform the attack)
  • SYN Flag attacks (spoofing attacks)

Step 1 — Open the ISA Administration Interface

Firstly, you must directly interact with the ISA server by logging onto the ISA Server machine either directly, through MSTSC, RDC, or other remote software such as DameWare, Tilovi, or others.

Start -> All Programs -> Microsoft ISA Server -> ISA Server Management

Step 2 Enter Into The ISA General Configuration Screen

With the ISA main server window:

Select your ISA server -> Select Configuration -> Select General

Step 3 Enter Into the Additional Security Policy Screen and Flood Control Dialog

With the ISA General Configuration Screen;

Scroll Down to Details -> Select Additional Security Policy -> Select Configure Flood Mitigation Settings

Step 4 Setup Flood Control and Additional Options

This is the main dialog for setting up and configuring flood control for your SharePoint environment. The first step is to check the box labeled Enable mitigation for flood attacks and worm propagation. Under this box, you will see a variety of settings related to how ISA server will deal with and handle certain flood attacks:

  • Limit TCP connection requests per minute per IP address
  • Limit TCP concurrent connections per IP address
  • Limit TCP half-open connections
  • HTTP requests per minute, per IP address
  • Non-TCP concurrent sessions per IP address
  • Limit non-TCP new sessions per minute, per rule
  • Limit TCP and non-TCP denied messages
  • Set event trigger for denied packets per minute, per IP address

The last box is logging records that are related to a possible flood attack, allowing forensic insight into attacks after the fact so that they can be properly prevented following. The log can also have limits set on it as well if you are an organization that is attacked very frequently. Because these logs could possibly increase dramatically, throttling the records that are written can be controlled.

Within each of the panes, configure how you believe your flood control should be structured. There is no standardized process to it, since smaller organizations or those within a non competitive industry are not likely to be attacked. Within each of the dialogs, there will be a small description that will allow you to know exactly what is being configured.

For example, the first selection within this flood mitigation dialog is to Limit TCP connection requests per minute per IP address. When you open this dialog, you will see four main things:

  • Mitigation Title In this case, the Mitigation Title is Limits TCP connection requests per minute per IP address.
  • Limit Specify the amount of requests that you wish to set as the threshold, the default is 600
  • Custom Limit (applies to IP exceptions) This is the limit that you wish to apply to all IP’s, the default is set to 6000.
  • Mitigation Description  —  Within in this specific pane, the description is Mitigates work propagations that occur when an infected host scans the network for vulnerable hosts. Also mitigates flood attacks that occur when an attacker send numerous TCP connect messages. This dialog will of course change when you configure or view different settings through the flood control settings.

These settings should not be hastily set because they will determine your overall flood control. Typically, before this dialog is entered, they are discussed with network and security personnel, documented, and then put into effect. These configurations should be documented so that configuration management can take place effectively and that if and when a security incident should occur, intended implementations should be compared to intentional configurations. This can weed out possible internal threats, and ensure that all of your security mechanisms are following corporate standards and guidelines.

Share

Mastering InfoPath Development Series Introduction

Building business forms is an intrinsic part of architecting a serviceable collaboration environment that accentuates user interaction into overall business operations. Forms and the data that is entered into them build the backbone of most internal and external enterprise processes for organizations, regardless of industry background. One of the most frequent requests of any collaborative environment is to procure circumstances where normally endless paper, human-oriented processes are optimized and an environment that procures methodized, controlled, and manageable paper-less forms are introduced to speed user interaction, couple with intuitive workflows, fetch and push data between various types of data sources, and improve custom form time to production. The benefits of leveraging paperless forms are vast, ranging from cost benefits to flexible deployment and usability options. Form distribution fees and production costs are eliminated, capturing and routing become automated by the collaboration environment, forms can be audited for non-repudiation legal purposes, and robust levels of forms storage and pipeline security can be implemented.

 
InfoPath 2007 and Office SharePoint Server 2007 running InfoPath Forms Services, or a separately purchased Microsoft Office Forms Server (OFS 2007) platform, procure a bridge between the Information Worker whom is most aware of the organizational form content and process involvement, to the developer who can enhance and automate form activities, to the systems architect who is responsible for maintaining the form platform and tangible form maintenance.
Angry
Typical business form development can prove tend to be convoluted because a considerable quantity of conventional business forms are specialized in intent, often times the solitary persons whom are aware of how data should be inputted, manipulated, and stored is not an avid member of the development team. Empowering the set of stakeholders involved in the forms development process with the tools to help communicate needs to tangible deliverables, and deliverables to organizational systems will procure numerous benefits for an organization, increasing the overall quality and usability of the end product.
Stakeholders in the Form Development Process
Stakeholder

 

Using Forms Services

 

For The Information Worker

 

Allow an integrated design environment where form controls can be easily added to a layout page, capturing the most beneficial user design while maintaining an uncomplicated, effortless form development and design surface.

 

For The Developer

 

Inherent functionality to bind form controls to various data sources and control basic form behavior. Allowance of backend managed code to tap into new InfoPath Object Model in order to create more complex form behavior using C# or VB.NET through the use of Microsoft Visual Studio Tools for Applications (VSTA) or Microsoft Visual Studio Tools for Office (VSTO). Support for native scripting languages such as Jscript and VBscript through the Microsoft Script Editor (MSE) for customizing other form attributes to be bundled with form template packages.

 

For the Systems Architect

 

Ease control over deploying custom forms to a SharePoint environment with a granular, defined publishing model. Exert forms jurisdiction over pieces that tap into custom business logic by allocating the task of activating such forms as an administrative task. Allow forms to be updated even while SharePoint users are entering in data, decreasing the amounts of service disruptions and increasing quality of data retrieval. Provide forms administration through familiar SharePoint STSADM command line interaction.

 

Throughout this series, I will introduce you to how to construct robust, extendable forms using InfoPath 2007. The constructed forms will then be able to employ InfoPath Forms Services in order to increase the reach of the form through its zero footprint form fill-in technology, allowing even users without the InfoPath Smart Client installed to utilize the InfoPath forms. As you’ll see shortly, you will exploit powerful development approaches that can immediately be put to work in your environment through the native InfoPath design surface and through custom managed code. The presented strategies include several sections of inherent InfoPath functionality as well as demonstrations of how to hook in custom logic written in managed C# code. For those developers who don’t have InfoPath 2007 as a development platform, for those developing forms solely on the Windows SharePoint Services V3 platform or not having the Enterprise Features of MOSS enabled, we will also explore how to use native WebPart development to build forms that can achieve the same goal as developing when using InfoPath 2007.
We will also walk through the architecture of InfoPath forms and InfoPath forms services. You will become familiar with the pieces that build up an InfoPath form and related pieces of technology that are important to an InfoPath forms developer. Since InfoPath FormsServices provides the foundational serving mechanism, we will also examine the core components that construct this service, and how exactly the rendering components of InfoPath Forms Services can expand the reach of custom built forms.
So warm up Visual Studio, strap on your seat belts, and let’s start developing!
Share