Monthly Archives: January 2014

Microsoft SharePoint: Custom Styles

Themes are sufficient for scenarios that require only the application of colors, but to exercise total control over styling you must create and use custom style sheets. There are a variety of ways to include custom style sheets in your SharePoint pages. Each has advantages and disadvantages.

The first is to include a standard HTML <link> element in a site’s master page, in a single page, or in a control. As this is basic HTML it requires no specific knowledge of SharePoint and it works in both farm and sandbox deployments. The disadvantage to this approach is that it is inflexible—the link URL will not change as you change the site’s location nor does it support any other SharePoint functionality like themes.

Another approach is to set the AlternateCssUrl property of the SPWeb class. This technique works in both farm and sandbox deployments. When the AlternateCssUrl property contains a value, a web control present in the v4.master page, CSSLink, renders an HTML <link> element containing the value of the AlternateCssUrl property after it renders the links for the core SharePoint style sheets.

Because CSSLink renders the AlternateCssUrl after the core styles you can be certain that the browser will apply your styles last. This is important because the order in which style sheets appear in a page determines which rules apply. Because the application of AlternateCssUrl appears after the core styles, you can use it to override and replace individual rules from the core styles.

You can specify any valid URL as the value of AlternateCssUrl. The only disadvantage to this approach is that it applies the target style sheet to every page in your site. Therefore, for styles that affect only a small portion of your site, like an individual control, you may choose a more targeted approach for performance reasons.

The CssRegistration web control provides the ability to add CSS to a page as needed for a given scenario. You can apply the control in both farm and sandbox solutions to any artifact that includes design time markup, i.e., pages and user controls. However, CssRegistration also includes a static method for use by Web Parts. Unfortunately, this is only available in farm deployments. CssRegistration allows the inclusion of CSS from specific locations including:

  • TEMPLATE\LAYOUTS\[LCID]\STYLES
  • Style Library
  • Absolute path

Unless you specify an absolute path, SharePoint automatically accommodates any changes to the site’s location providing flexibility that a <link> element lacks. CssRegistration also allows application of themes to style sheets whereas <link> does not.

It is important to know that the CssRegistration web control does not render anything at runtime. Instead it works in conjunction with the CSSLink control.

CssRegistration and CssLink

As the name implies, the CssRegistration control registers CSS for rendering by CssLink. If multiple items register the same CSS, for example two instances of the same Web Part, CssLink renders a single link. CssLink renders registered CSS in alphabetical order or based on the optional CssRegistration After property.

The After property is a new and welcome addition in SharePoint 2010. Also new is the ability to render links conditionally via the optional ConditionalExpression and RevealToNonIE properties. For example, to render a style sheet for only IE7 you can specify IE 7 as the value for ConditionalExpression.

The CssLink control renders more than just the values specified by CSSRegistration. CssLink renders links in the following order:

  • CssRegistrations
  • Core styles
  • AlternateCssUrl
  • DefaultUrl (Optional CssLink property value)

doug (frame 367 of smile clip)This post is an excerpt from the online courseware for our Microsoft SharePoint 2010 for Developers course written by expert Doug Ware.

Doug Ware is a SharePoint expert and an instructor for many of our SharePoint 2007 and SharePoint 2010 courses. A Microsoft MVP several times over, Doug is the leader of the Atlanta .NET User Group, one of the largest user groups in the Southeast U.S., and is a frequent speaker at code camps and other events. In addition to teaching and writing about SharePoint, Doug stays active as a consultant and has helped numerous organizations implement and customize SharePoint.

Windows Presentation Foundation Using Visual C# 2010: The Resources Dictionary

Every element in your application provides a Resources property (this includes every control and container), which is actually a Dictionary in which the key is a string, and the value is a resource. In other words, every element contains a collection of resources, indexed by a string key name.

Although every element can contain its own defined resources, most of the time it’s easiest to place resources at the window level. Doing that makes the available to all the controls in the window. Every element always has access to all its resources, and the resources of its parents (all the way back up to the application level), so if you want to share resources between elements, the higher you place the resources, the easier it will be to do so.

Imagine that you want to create a LinearGradientBrush instance that you will use as the background for several controls on a page. Rather than defining it in the content of each individual element, you can extract the gradient in the resources collection for the container (in this example, a user control) instead. The sample user control, IntroResource.xaml, includes a very simple resource. The syntax in the sample (displayed in Figure 1) looks like the following:

gradient_figure1Figure 1. The sample gradient.

TIP: Although the examples here are all based on user controls for the purposes of making the demonstration easier to navigate, you can also define resources at any level. Often, in WPF applications, you’ll define resources at the window level, in the Window.Resources element.

The differences between this definition and what you would see if you had defined the gradient brush for each individual element are:

  • The resource appears inside the UserControl.Resources element.
  • The resource includes an x:Key attribute, defining the key for the resource. Remember that the collection of resources is actually a Dictionary, and every item in a dictionary must contain a unique key that identifies it.

NOTE The x: prefix on the Key attribute indicates that it’s in the XAML  namespace, rather than the WPF namespace. You’ll use this key to refer to the resource, whenever you want to use it. It doesn’t matter what you call the resource, as long as you use this Key attribute value to refer to the resource.

TIP: Name your resources based on their functionality, not their contents. The uses won’t change as often as the particular implementation details, and it will be easier to select resources if you name them based on their usage.

To use the resource, you must be able to refer to it. To do this, use a markup extension, delimited with curly braces:

You may have seen the markup extension syntax used when performing property binding, or in other contexts. In general, XAML uses markup extensions whenever it needs to be able to set a property in a non-standard way. In this case, the StaticResource keyword indicates that when XAML needs to retrieve and set the Background property of the Border element, it
should look for a resource whose x:Key attribute is BackgroundBrush, and use
the definition it finds there.

Would you use a resource in a case like this, in which you only consume the resource once? It certainly doesn’t make the XAML any more efficient, or more compact. On the other hand, it does make it easier to isolate the layout details—by placing all the formatting information in one place, it’s easier to keep track of, and maintain, the look of your application.

You may be wondering about the word “Static” in the markup extension. Why Static? Is there a Dynamic resource, as well? WPF provides both static resources, which are applied only once, when you first create the window, and dynamic resources, which are reapplied if the resource changes. Dynamic resources (using the DynamicResource markup extension) use slightly more overhead, but allow you to change the content of the resource at runtime. Static resources are simpler, and provide much of the functionality you’ll need.

NOTE If you programmatically change a feature of an existing static resource at runtime (for example, if you change a color, or some other property of the existing resource), WPF automatically updates the display to match. Dynamic resources allow you to replace the entire resource with another at runtime. In general, static resources provide the functionality you’ll need for most applications.

WARNING! It’s important that you define the static resources before you attempt to use them in the markup. Unlike most modern programming languages, the order of appearance within the source file is a concern—you cannot use a resource before it has been declared. The XAML parser reads content from start to finish, and expects to find the definition for a resource at the time the XAML attempts to use the resource. This isn’t true for dynamic resources, however. You can define dynamic resources after they’re used, and the XAML parse can still find them.

This post is an excerpt from the online courseware Presentation Foundation Using Visual C# 2010 course written by expert Ken Getz and Robert Green.

Ken Getz is a Visual Studio expert with over 25 years of experience as a successful developer and consultant. He is a nationally recognized author and speaker, as well as a featured instructor for LearnNowOnline.

Robert Green is a Visual Studio expert and a featured instructor for several of our Visual Basic and Visual C# courses. He is currently a Technical Evangelist in the Developer Platform and Evangelism (DPE) group at Microsoft. He has also worked for Microsoft on the Developer Tools marketing team and as Community Lead on the Visual Basic team. Robert also has several years of consulting experience focused on developer training, and is a frequent speaker at technology conferences including TechEd, VSLive, VSConnections and Advisor Live.

SQL 2012: Aggregates

One of the more exciting types of SQLCLR code modules is custom aggregates. Earlier versions of SQL Server didn’t offer an easy way to extend the rather short list of T-SQL aggregates, such as SUM, AVG, MAX, MIN, and COUNT. You still can’t use T-SQL to create custom aggregates, but you can write your own in SQLCLR. It’s not something you’ll need to do often, but it can greatly simplify application coding in situations where you need it.

Unlike other SQLCLR code modules, you can define only a single custom aggregate within a class. The class must be public and requires four non-static methods, which SQL Server calls as it processes the data to aggregate:

  • Init initializes storage values. SQL Server calls this once at the beginning of the query that uses the aggregate.
  • Accumulate does the work of combining values. SQL Server calls it once for each row that is aggregated, and it must support multiple instances of the aggregation code that is executing so that SQL Server can utilize multiple threads to make operations more efficient.
  • Merge is called at the end of the operation to merge the aggregations of multiple instances into one final value.
  • Terminate is the last method called and returns the final aggregated value.

You also have to deal with serialization issues because instances of the aggregation class have to be moved between threads. This complicates the code only a little, since the .NET Framework has rich support for serialization. Most commonly, you’ll implement the IBinarySerialize interface to let .NET do all the serialization work, but there are other options if you have a special need.

Consider a sample aggregation. A common requirement in applications is to create a concatenation of strings within a table, delimited by a single character such as a semicolon. Some applications require information in this format for processing. You’ll create a Concatenate aggregation that you can use to concatenate all string values in a field. For example, once you create the aggregation, you could run the following T-SQL code to produce a single string with all product names from the Northwind Products table that have a category ID of 4, which is Dairy Products.

This code produces the following string (with line breaks added to fit on the printed page):

The first part of the SQLCLR code defines the aggregation class and decorates it with Serializable and SqlUserDefinedAggregate attributes. The SqlUserDefinedAggregate attribute needs the following parameters, most of which the query processor uses to perform the aggregation properly.

  • Format specifies the serialization format, either Format.Native or Format.UserDefined. You’ll nearly always need to use UserDefined, although SQL Server has enhanced support for the Native format.
  • IsInvariantToDuplicates indicates whether the aggregation result is the same if any of the items are duplicates. The Concatenate aggregation returns a different result if duplicates exist (they’ll appear multiple times in the resulting string), so set this value to false.
  • IsInvariantToNulls indicates whether the aggregation result is the same if any of the items are nulls. Concatenate ignores null values, so set this value to true because the same string will result whether there are nulls or not.
  • IsNullIfEmpty indicates whether the aggregation result is null if no items were aggregated, such as when the WHERE clause returns no records to aggregate. If no strings exist, Concatenate returns a null, so set this to true.
  • MaxByteSize is required by the UserDefined serialization format and indicates the largest aggregation value that can be returned. This is set to 8000 bytes in Concatenate.

Concatenate is implemented in the following code as a structure and inherits from IBinarySerialize so that SQL Server can properly use multiple instances of the aggregate, using the listed parameters.

SQL Server calls the Init() method before aggregation begins. This is the point where you should initialize any variables used in the aggregation. Concatenate uses a StringBuilder object in an sb variable to hold the aggregated values, so that variable is instantiated here.

SQL Server calls the Accumulate method when it has a new value to add to the aggregation. Concatenate works only on string type data, so the method receives a value of type SqlString. If the value is null, it returns immediately without doing any aggregation task. Otherwise, it calls the Append method of the StringBuilder variable to concatenate the string.

The Merge method is used to aggregate multiple instances of the Concatenate object. In this case it simply concatenates the value passed to it by the SQL Server query processor to the current instance’s aggregation value. The method is passed an object of type Concatenate and reads the object’s StringBuilder’s ToString property to get the current aggregation value.

Often you’ll need to do more work here; for example, when the resulting aggregation needs to be in alphabetical order. In that case, you may want to use a sortable .NET list object to store the strings internally while processing the aggregate. But here a simple append is sufficient, since the order of the items in the final string is not important.

The last of the four required aggregation methods is Terminate. SQL Server calls this after it processes the last value that it aggregates. This method needs to return the final aggregated value, so it first checks whether the current string is of zero length. If it is, it returns a null. Otherwise it strips off the final semicolon and returns the value. It also clears the sb object in case this instance of Concatenate is used for another aggregation.

The aggregation object also has two other methods, required because the object implements the IBinarySerialize interface. The Read method is called when the object is deserialized and restores the value of the sb variable. Write puts the current string value of sb into the serialization object w.

This simple but useful example shows what is necessary to create a SQLCLR aggregate. Other custom aggregates may require more complex code to implement all the required features, and you may have to use multiple classlevel variables to keep track of multiple values during the course of calculation, but it really isn’t all that hard to do once you understand the basic principles. You’ll need to have a good handle on how .NET does serialization. But these techniques really become valuable when you implement your own user-defined types in SQLCLR, which open up whole worlds of possibilities in SQL Server.

ldn-expertdkielyThis post is an excerpt from the online courseware for our Microsoft SQL  Server 2012 Developer course written by expert Don Kiely. 

Don Kiely is a featured instructor on many of our SQL Server and Visual Studio courses. He is a nationally recognized author, instructor and consultant who travels the country sharing his expertise in SQL Server and security.

SharePoint Client Object Model – Microsoft SharePoint

A typical SharePoint site contains much information that is potentially useful to other systems. SharePoint provides a number of APIs that other systems can use to access and manipulate that information. SharePoint Foundation 2010 includes a new set of libraries, the SharePoint client object model, which client applications can use to access SharePoint’s core services.

The SharePoint client object model is a set of managed code and JavaScript libraries that support traditional .NET assemblies and executables, Silverlight, and browser-based JavaScript. In the past, you had to work with SharePoint via SOAP-based Web services. These services consume and emit XML that the client must build and parse. The client object model does not require you to build and parse XML nor is it based on SOAP. Instead you use classes that are very similar to the ones you use when writing SharePoint code on the server.
These classes act as proxies to a WCF service.

Problems Addressed

The client object model is actually a set of client and server proxies to a WCF service. However, you do not have to understand the WCF service because the client object model takes care of all of the tedious details of connecting to and communicating with the WCF service.

This is a major improvement over the *.asmx (SOAP) services found in WSS 2.0 and WSS 3.0. To use the SOAP services you must understand SOAP, build and parse XML, and most importantly, understand the specific service. Since these services consume XML, knowledge of the SharePoint object model is only slightly helpful to understanding a given service. Each of the services is a program with its own rules. Understanding how to write code to add an item to a list doesn’t mean you know the specific SOAP service endpoint or how to
format XML that the service understands.

Apart from being complex, the SOAP services are inefficient. Accomplishing most tasks requires multiple round-trips to the server and multiple service endpoints. Those who use hosted SharePoint and can’t deploy code to the farm have no choice and must use the services if they need integration. However, due to the complexity and learning curve of the traditional services, most people build and deploy custom services that support specific use cases to integrate earlier versions of SharePoint with other applications. The traditional SOAP based services are still supported, but unless you are writing code to target both WSS 3.0 and SharePoint Foundation you should use the client object model.

Client Object Model Overview

When you use the client object model you work with classes and methods. There is still XML, but you don’t see it or work with it. The client object model builds the XML based on your work. When it is time to do work on the server, the client object model passes the XML to the client.svc WCF service endpoint. SharePoint does whatever work is indicated by the XML and returns a JSON (JavaScript Object Notation) encoded response to the client object model which updates the state of any object instances as necessary. Figure 1 shows a conceptual view of the communication between the client and the server.

Sharepoint_Client_object

Figure 1.The client object model and client service handle all communication and message formatting for you.

doug (frame 367 of smile clip)This post is an excerpt from the online courseware for our Microsoft SharePoint 2010 for Developers course written by expert Doug Ware.

Doug Ware is a SharePoint expert and an instructor for many of our SharePoint 2007 and SharePoint 2010 courses. A Microsoft MVP several times over, Doug is the leader of the Atlanta .NET User Group, one of the largest user groups in the Southeast U.S., and is a frequent speaker at code camps and other events. In addition to teaching and writing about SharePoint, Doug stays active as a consultant and has helped numerous organizations implement and customize SharePoint.

Radio Button Control – Visual C#

The RadioButton control works much like the CheckBox control—it provides the same properties, and the same events. The big difference between the RadioButton and CheckBox controls is that RadioButton controls are grouped by their container. Within a single container, you can generally only select one RadioButton control. If you place multiple RadioButton controls into multiple containers, you can select one RadioButton control from each container.

You can override this behavior using the GroupName property of the control. You can set this string value to create more than one group per container, or to create a single group that spans multiple containers. To demonstrate this behavior, select the RadioButton tab in the sample application, shown in Figure 1.

TIP: There’s no need to specify a GroupName property for a RadioButton control unless you want to override the default behavior.

radiobuttoncontrl

Figure 1. RadioButton controls normally allow you to select only one per
container; override the behavior with the GroupName property.

The markup for the sample page looks like the following:

If you try out the demonstration, you’ll see that you can only select a RadioButton control from the group named Group 1, because they’re all in the same container. You can select only a single item from the group named Group 2, again, because they’re in the same container. You can also select one item from the group named Group 3, because these items have their GroupName property set to the same text (the text is arbitrary, and it’s set to
Group3 in the example). Because these controls share the same group name, and because they have a group name set, you can select multiple RadioButton controls within a single container.

In contrast, the right-hand Border control contains multiple CheckBox controls. Nothing keeps you from selecting as many CheckBox controls as you like. That’s the point: When you use RadioButton controls, you intend for users to select only one per group. When you use CheckBox controls, you intend users to select multiple items.

NOTE This sample uses a StackPanel control as the container for the
groups of RadioButton controls. You may also want to investigate
the GroupBox control, which not only groups the controls but
also adds a caption describing the group. The GroupBox control is,
effectively a simple container with a caption added.

This post is an excerpt from the online courseware Windows Presentation Foundation Using Visual C# 2010 course written by expert Ken Getz and Robert Green.

Ken Getz is a Visual Studio expert with over 25 years of experience as a successful developer and consultant. He is a nationally recognized author and speaker, as well as a featured instructor for LearnNowOnline.

Robert Green is a Visual Studio expert and a featured instructor for several of our Visual Basic and Visual C# courses. He is currently a Technical Evangelist in the Developer Platform and Evangelism (DPE) group at Microsoft. He has also worked for Microsoft on the Developer Tools marketing team and as Community Lead on the Visual Basic team. Robert also has several years of consulting experience focused on developer training, and is a frequent speaker at technology conferences including TechEd, VSLive, VSConnections and Advisor Live.

Isolation Levels and Transactions – Microsoft SQL

An isolation level defines how much a transaction is isolated from changes made by other, concurrent transactions. The current isolation level setting determines the side effects that can occur due to uncommitted changes that other transactions make. SQL Server supports all four of the isolation levels defined in the SQL ISO standard as well as two others related to row versioning:

  • The default READ COMMITTED isolation level is in effect with autocommit transactions. This ensures that every transaction meets the requirements of the ACID test without requiring extra code. READ COMMITTED prevents concurrent transactions from reading uncommitted data or interfering with the transaction until it is complete. This level results on locks on resources that could affect concurrency and the volume of transactions that a server can handle.
  • The READ UNCOMMITTED isolation level lets other transactions read changed data that has not yet been committed by other concurrent transactions, called dirty reads. This isolation level does not issue as many locks as READ COMMITTED, so has a lighter touch on resources and allows higher transaction rates.
  • The REAPEATABLE READ isolation level is similar to READ COMMITTED in that the transaction cannot read changed data not yet committed from other transactions. But it goes further: this isolation level prevents other transactions from modifying data read by the current transaction until it completes. The benefit is that a transaction at this isolation level can repeatedly read the data and get the same results, even if there are other transactions pending.
  • The SERIALIZABLE isolation level is similar to the REPEATABLE READ isolation level, but takes it up a notch. The SERIALIZABLE isolation level prevents both updates and inserts. It ensures that if a query is reissued inside the same transaction, existing rows won’t change and new rows won’t suddenly appear. SERIALIZABLE employs a range of locks that prevents edits, deletions, or insertions until the transaction is complete.
  • The SNAPSHOT isolation level essentially saves a snapshot of data at the start of the transaction to ensure that any data read during the life of the transaction will be the same as at the start of the transaction, no matter what changes have been made to the data in the meantime by other transactions (the current transaction will see its own data
    changes). This isolation level generally doesn’t require locks on data until the current transaction attempts to update data.
  • The READ COMMITTED SNAPSHOT isolation level is similar to SNAPSHOT except that instead of providing a snapshot of the data when the transaction started, READ COMMITTED SNAPSHOT provides one when the statement started. The behavior of this isolation level is similar to READ COMMITTED except that it doesn’t acquire shared locks and changes aren’t blocked when resources are exclusively locked.

NOTE Isolation levels are described in the “Isolation Levels in the Database Engine” topic in SQL Server Books Online (BOL). As of this writing, Microsoft has not updated this topic for SQL Server 2012, but the SQL Server 2008 version is still valid. This is the case for some of the other BOL references included in this chapter.

You can set the isolation level of the current session using the SET TRANSACTION ISOLATION LEVEL <isolation level name> statement, as well as with a table hint for a specific query using the WITH clause.

Isolation levels can affect what data your code reads when there are other concurrent transactions executing. The choice of isolation level you make can significantly impact the amount of activity an instance of SQL Server can support, so if you have performance issues on a heavily used database you might want to tweak the isolation levels used by your code.

ldn-expertdkielyThis post is an excerpt from the online courseware for our Microsoft SQL Server 2012 Developer course written by expert Don Kiely. 

Don Kiely is a featured instructor on many of our SQL Server and Visual Studio courses. He is a nationally recognized author, instructor and consultant who travels the country sharing his expertise in SQL Server and security.