Sunday, August 30, 2009

SharePoint Data View Tricks

More tricks for the sharepoint data view web part control for MOSS2007.

So often times when making a new data view certain fields are too long to fit in the cell/div that you need it too. So here’s some XSLT I’ve been using to truncate a field.



                <a href="@FileRef”> 

<xsl:variable name="truncate-length” select="40”/>
<xsl:value-of select="substring(@Title,1, $truncate-length)”/>
<xsl:if test="string-length(@Title) > $truncate-length”>
<xsl:text>...xsl:text>
xsl:if>
a>

The above example runs inline, and grabs the URL and Title fields from a list item. It then truncates the Title to the length specified in the truncate-length variable to however many characters you want to use and then appends on ... to the end. Fairly straightforward but can be hard for some to build from scratch.

Next, how to customize the built in [Current Date] field. Every time you make a filter off of [Current Date] an entry for it gets added in the code behind for the data view under the tag “SharePoint:SPDataSource”. The easiest way I’ve found to edit this field is to export it to notepad, or any basic text editor and replace the masked characters in it with the right ones

& lt; = < 

& gt; = >
& quot; = "

That will make it much easier to read

<View>     <Query>         <Where>             <And>                 <Geq>                     <FieldRef Name="EventDate”/>                     <Value Type="Text”>                         <Today/>                     Value>                 Geq>                 <Leq>                     <FieldRef Name="EndDate”/>                     <Value Type="Text”>                         <Today OffsetDays="14”/>                     Value>                 Leq>             And>         Where>         <OrderBy>             <FieldRef Name="EventDate” Ascending="TRUE”/>         OrderBy>     Query> View>

Unfortunately you can’t paste this much more readable code back in to sharepoint designer, but you can at least find where you need to edit it. In this case were looking for the Today tag after EndDate. I added the OffsetDays attribute and gave it a length of 14 days. You can also go negative for this value, so you can see things from previous times rather than future ones.

SharePoint Data View Part Magic and Search

Refer:http://blogs.msdn.com/arpans/archive/2007/07/27/sharepoint-data-view-part-magic-and-search.aspx

Programming SharePoint List

Objective:

In this article, I am going to show how we could work with SharePoint items using object model or in other words using .Net code. I will show you

  1. How to add item into the SharePoint list?
  2. How to retrieve item from the SharePoint list?
  3. How to update item into the SharePoint list?
  4. How to delete item from the SharePoint list?
Assumption:
  1. I have created a custom list called Reader.
  2. There are two columns. One is Reader'sName. This is a single line text column. Second is Reader'sArticle. This is numeric column.
  3. I have put some item also in Reader list.
In SharePoint site, Reader list look like as below,

1.gif

Here, I assume you know how to create a custom list in a SharePoint site and how to put some data into that. If you do not know, read my article on the same here on this site. Now I am going to manipulate the above list through code.

I am going to follow the below steps.
  1. Create a window application
  2. Add reference of Microsoft.SharePoint dll.
  3. Add few controls like buttons and text boxes. I am a bad UI designer. So don't follow my window form here. You design of yours.
  4. Return a site collection using SPSite.
  5. Return particular website where list is added using SPWeb.
  6. Return collection of list items using SPListItemCollection.
  7. Work with a particular list item using SPListItem.
Adding Microsoft.SharePoint dll

2.gif

Design of the Form
  1. There are two text boxes.
  2. Three buttons to add, delete and update.
3.gif

Explanation
  1. I am returning the site collection on the form load.
  2. I am returning the top level site also on form load.
Adding to the List
  1. Readers is name of the list
  2. I am returning the List collection and adding the item into that.
  3. I am reading the items to be added from the textboxes.

private void btnAdd_Click(object sender, EventArgs e)
{
string Name = txtName.Text;
int Numofarticle = Convert.ToInt32(txtNumberofArticle.Text);
_ItemCollection = _MyWeb.Lists["Readers"].Items ;
_MyItem = _ItemCollection.Add();
_MyItem["Reader'sName"] = Name;
_MyItem["Reader'sArticle"] = Numofarticle;
_MyItem.Update();
txtName.Text = "";
txtNumberofArticle.Text = "";
MessageBox.Show("Item Added");

}

Updating to the List

  1. Readers is name of the list

  2. I am returning the List collection and updating the item into that.

  3. I am reading the items to be added from the textboxes.

  4. I am iterating through the collection and searching for the Reader'sName to be updated.

private void btnEdit_Click(object sender, EventArgs e)
{
_ItemCollection = _MyWeb.Lists["Readers"].Items;
int count = _ItemCollection.Count;
for (int i = 0; i < count; i++)
{
SPListItem item = _ItemCollection[i];
if (item["Reader'sName"].ToString() == txtName.Text.ToString())
{
item["Reader'sArticle"] = Convert.ToInt32(txtNumberofArticle.Text);
item.Update();
}
}
MessageBox.Show("Updated");
}

}

Deleting from the List

  1. Readers is name of the list

  2. I am returning the List collection and updating the item into that.

  3. I am reading the items to be added from the textboxes.

  4. I am iterating through the collection and searching for the Reader'sName to be deleted

private void btnDelete_Click(object sender, EventArgs e)
{
_ItemCollection = _MyWeb.Lists["Readers"].Items;
int count = _ItemCollection.Count;
for (int i = 0; i < count; i++)
{
SPListItem item = _ItemCollection[i];
if (item["Reader'sName"].ToString() == txtName.Text.ToString())
{
_ItemCollection.Delete(i);
count--;
}
}
MessageBox.Show("Deleted");

}

For reference the whole code is as below,

using
System;
using
System.Collections.Generic;
using
System.ComponentModel;
using
System.Data;
using
System.Drawing;
using
System.Linq;
using
System.Text;
using
System.Windows.Forms;
using
Microsoft.SharePoint;

namespace ProgrammingList
{
public partial class Form1 : Form
{
SPSite _MySite = null;
SPWeb _MyWeb = null;
SPListItemCollection _ItemCollection = null;
SPListItem _MyItem = null;

public Form1()
{
InitializeComponent();
}
private void btnAdd_Click(object sender, EventArgs e)
{
MessageBox.Show(_MyWeb.Title);
string Name = txtName.Text;
int Numofarticle = Convert.ToInt32(txtNumberofArticle.Text);
_ItemCollection = _MyWeb.Lists["Readers"].Items ;
_MyItem = _ItemCollection.Add();
_MyItem["Reader'sName"] = Name;
_MyItem["Reader'sArticle"] = Numofarticle;
_MyItem.Update();
txtName.Text = "";
txtNumberofArticle.Text = "";
MessageBox.Show("Item Added");
}
private void Form1_Load(object sender, EventArgs e)
{
_MySite = new SPSite("http://adfsaccount:2222/");
// _MyWeb = _MySite.AllWebs["Document Center"];
_MyWeb =_MySite.OpenWeb();
}
private void btnDelete_Click(object sender, EventArgs e)
{
_ItemCollection = _MyWeb.Lists["Readers"].Items;
int count = _ItemCollection.Count;
for (int i = 0; i < count; i++)
{
SPListItem item = _ItemCollection[i];
if (item["Reader'sName"].ToString() == txtName.Text.ToString())
{
_ItemCollection.Delete(i);
count--;
}
}
MessageBox.Show("Deleted");
}
private void btnEdit_Click(object sender, EventArgs e)
{
_ItemCollection = _MyWeb.Lists["Readers"].Items;
int count = _ItemCollection.Count;
for (int i = 0; i < count; i++)
{
SPListItem item = _ItemCollection[i];
if (item["Reader'sName"].ToString() == txtName.Text.ToString())
{
item["Reader'sArticle"] = Convert.ToInt32(txtNumberofArticle.Text);
item.Update();
}
}
MessageBox.Show("Updated");
}
}
}

Conclusion:

In this article, I showed how to manipulate SharePoint list using code. Thanks for reading.

Wednesday, August 26, 2009

Microsoft Office SharePoint Designer 2007 or Not

SharePoint Designer (SPD) is a nifty tool to use to customize SharePoint sites. It is very powerful and allows us to quickly make style, organizational, functional, and content changes quickly and easily. Today, I ran across a post from Joel Oleseon where he shared his professional opinion in response to another post about the tool from Mark Rackley which was motivated in response to Microsoft’s announcement to make the tool available for free. There really is nothing new about the debate as it deals with the advantages and disadvantages of empowering an end user with all of the power the tool has to offer. It has just resurfaced since the tool will be freely available.

So… if the debate is not new, what’s all the fuss about?

Regardless of the stance that you take about allowing SPD to be used in a production SharePoint deployment or not, the real cause of concern is how SPD can impact production environment when used by untrained/uninformed users with appropriate rights. This reminds me of the quote – with great power comes great responsibility… or something like that. I don’t see the need for huge concern. That is assuming people with those rights have already been trained and informed. For the most part, people with contributor or higher permission role assignments can already do plenty of damage to a production environment with only the web browser at hand. Hence, the need and argument for appropriate training, content approval (and publishing) planning and enforcement, and governance plans (especially in Extranet/Internet facing deployments).

Okay… so what should we do?

There shouldn’t be too much to do (assuming training, content approval, governance, etc. has already been addressed). Professionally, I will be making sure to emphasize the role of SPD in SharePoint projects. I will also make sure to encourage the inclusion or addition of SPD training for existing and new SharePoint users (especially “power” users), administrators, and developers.


jQuery and jCarousel in SharePoint

I recently had to integrate jCarousel into a SharePoint web part. Since jCarousel is a plugin for jQuery, it means I also had to get jQuery integrated with SharePoint. In order to accomplish this, I followed some good feature packaging instructions found from a few different blog posts:

After figuring out how to package jCarousel and jQuery using SharePoint delegate controls, I was ready for business with the implementation of the web part.

The web part itself was nothing fancy. I used a Repeater control to generate the list item (LI) elements with the content I needed in the carousel. I wrapped the Repeater in an unordered list (UL) which was wrapped in a DIV tag that had the runat attribute set to server. So basically, I just followed the mark up instructions provided in the jCarousel documentation.

The wrapping DIV tag was used in my webpart code to initialize jCarousel. The code snippet below shows how I implemented it:


protected override void OnLoad(EventArgs e)
{
if (!Page.ClientScript.IsStartupScriptRegistered(this.GetType(), this.ClientID))
{
Page.ClientScript.RegisterStartupScript(this.GetType(), this.ClientID, @"

");
}
}

Monday, August 24, 2009

Making Business Data Searchable: Business Data Catalog or Custom Federated Search Connectors?

Assume that you are a company that has plenty of data locked up in SQL Server databases, Oracle database, or line-of-business (LOB) systems such as SAP, Siebel or Microsoft CRM, and there is the need to make all of that data searchable. What is a good choice? BDC or the newest technology in the search space called custom federated search connectors?

I was asking myself this question during a session of Michal Gideoni I attended yesterday. Michal did a great job explaining in one hour your options (from a dev perspective) with federated search and the extensibility of them. Here are some interesting bullet points I wrote down:

  • Federated search is at this moment only available if you install MSS (Microsoft Search Server) 2008 or MSSX (Microsoft Search Server Express) 2008. It seems there will be a 'rollup' hotfix end of June/early July that will make federated search also available in the MOSS 2007 search centers. You might want to subscribe to the search blog on http://blogs.msdn.com/enterprisesearchto follow-up on this one.
  • She demonstrated the use of patterns in the federated location definition using a nifty little tool calledExpresso. Download a trial here. I like the mashup demo btw.
  • Microsoft released protocol handlers for Documentum and FileNet. Read more here.
  • Plenty of search-related tools, wrappers and docs are available in the Search Community Toolkitavailable on CodePlex.
  • The Web Parts that support the federated search are not sealed, so you can inherit from them and make them do what you want them to do. This is good news, I actually ignored this because all of the other search Web Parts are all sealed (still like to get an explanation on the why for that one).

So in all, a good session. Picked up nice new ideas for new demos. But back to the title of the posting: to BDC or to Custom FSC?

I foresee a great future for custom federated search connectors and it is so easy to build them. Basically a custom federated search connector is a layer (typically an ASPX page) sitting in front of the business data store accepting a query in the form of a template (e.g. http://litware:6500/searchindatabase.aspx?q=contoso). The query will be processed and translated internally in the ASPX and an RSS feed will be returned as output. This output is then picked up by the federated search Web Part and displayed to the user.

If the requirements are quite simple: no worries about ranking the results, well-defined queries (such as look for this in our customer database), no heavy requirements regarding security or caching, this technique of building custom connectors could be quite interesting instead of the heavy infrastructure and configurations you have to do for making that same data searchable via the Business Data Catalog. Of course, once the BDC is configured, you can do so much more with that data, but if it is only for searching... have a look at federated search.

Learn more also here on www.microsoft.com\enterprisesearch . I plan to come up with some additional material on this when I have the time.

Recycling Application Pools in Windows Server 2008

Done it finally: formatted my HP Compaq 8510p and installed Windows Server 2008 64-bit. I did not have any real problems configuring the system to run MOSS 2007 Enterprise, Visual Studio 2008 and the Office products. Had some problems with the wireless but that was my own stupid fault. You need to add the Wireless feature to the server manager. Nice to see that the OS also starts working heavily with features :). A bit of a disappointment is the no-go for doing a standby of your laptop after you have installed hyper-v. Means that I need to be 5 minutes earlier in the classroom to have my machine booted!

Most of the tools (except the Extensions for WSS) work as a charm. Of course, there are a couple of interesting changes. For example, one of the last lines in my little batch files for the deployment and testing of the dev work is very often the call to the iisapp.vbs to recycle a specific application pool. When you run on Windows Server 2008, that one is not available anymore. After a quick G-search I found what I have to include from now on. Here is the line to recycle an application pool (looks cleaner don't you think?):

C:\Windows\System32\inetsrv\appcmd.exe recycle apppool "sp pool"

How to customize permissions on your site

Office Content Publishing

As a Site Owner, you have the ability to choose which permissions are associated with a particular permission level and/or add new permission levels to combine different sets of permissions.

I recently ran into an issue on our internal support site where contributors were accidentally deleting pages and content from the wikis. I wanted our wiki writers to have permissions to view, create and modify as needed. But I wanted to prevent them from deleting any wiki content. In order to accomplish this, I created a custom permission level and removed ‘delete’ as an option. Following are the steps to create a custom permission level and then apply it to a user/group for a site.

PART 1: Create a custom permission level on your site

  1. Click Site Actions, then Site Settings.
  2. Under Users and Permissions, click Advanced Permissions.
  3. Click Settings, and then click Permission levels.

    On the Permission Levels page you can create a new level (where you manually choose all the appropriate fields) OR you can copy from an existing permission level from which you add/remove the specific permissions you want to make available to your users. The following steps show how to COPY from an existing permission level.
  4. Click the link for the existing permission level from which you will copy. (In this example I clicked Contribute).
  5. On the Edit Permission Level page for the group, scroll down to the bottom and click Copy Permission Level.

    The page title should now read “Copy Permission Level … “.
  6. Enter the Name and Description you want to give your new permission level in the corresponding boxes. (For example, I entered Name = Contribute – No Delete in the Name box and Can view, add and update but not delete in the Description box.)
  7. In the Permissions section, review each of the checked boxes and select or deselect any of the check boxes as appropriate for your new permission level. For example, I deselected the check box for Delete Versions - Delete past versions of a list item or document.
  8. When you are done editing the new permission level, click Create.
  9. The new permission level will display in the list (see my example below).

    The new permission level
  10. NEXT… apply your new permission level to specific users/groups on your site.

PART 2: Apply your new permission level to a specific users/groups on your site

  1. Click Site Actions, and then Site Settings.
  2. Under Users and Permissions, select Advanced Permissions.
  3. Locate the User/Group in your list to which you want to apply the newly created permission level and select the check box. (In this example I’ve selected our team site permissions group called SOS Team Site – Contributor Perms.)

    BEFOREBefore
  4. Click Actions, and then click Edit User Permissions.
  5. Locate your new permission level under Choose Permissions and select the check box. Be sure to deselect any other permissions boxes.
  6. Click Okay, which returns you to the Permissions page, and verify the new permissions are associated to your User/Group.

AFTERAfter

Congrats! You’ve now created a new permission level, applied it to a user/group on your site, and have successfully customized your site’s permissions. For more information on managing permissions, see Manage Permission Levels

how to use SharePoint Designer 2007 conditional formatting to format items in a SharePoint (MOSS 2007) list based on item m

his article demonstrates how to use SharePoint Designer 2007 conditional formatting to format items in a SharePoint (MOSS 2007) list based on item metadata.





The example uses a standard SharePoint task list and formats tasks based on the due date. The end result is a list view sorted by due date with item text or background coloured to represent the number of days until the due date.


The Process


In this example I have started with a standard task list and have created a few sample items for testing / demonstration.


From the task list, create a new view, starting from the default “Active Items” view (filtered to only display incomplete tasks). The view created in the example is called “Active – Coloured”





Open the view using SharePoint Designer. Right click on the List View Web Part and select “Convert to XSL Data View”. This will automatically convert settings for the current view into data view parameters.





Once the Web Part has been converted into a Data View Web Part, click the “Title” field if an item in the list to select it. From the Data View menu, select “Conditional Formatting”. To set the background colour of a row using conditional formatting, select the row instead of the “Title” field.





Formatting Conditions:


1/ Set all tasks with a due date more than a week away to be Green


- Start by setting the field to Due Date, greater than (>) the current date [today]




- Important: click in the grey section to deselect condition once set. If this is not done, changes to the advanced expression may not be applied.

- Click “Advanced” to open the “Advanced Condition” dialog.



- Add -7 before the last parenthesis in the start of the expression. See example below, the change is in bold:


number(translate(substring-before(@DueDate,'T'),'-','')-7) > number(translate(substring-before($Today,'T'),'-',''))


- Press “OK”. --> Condition should read "Using advanced expression"


-Press “OK”. --> Modify Style dialog should appear. Set required styles (font color to green in this case)









You may receive a “Site Definition Page Warning” message after customising the data view, or when saving the page. This has been fine in the past for me as I have not detached the masterpage and the style sheet remains linked to the page, so the page layout and any styles remain. If you are not sure, click the “About SharePoint site definitions” link on the dialog to get more information.







Note: To detect if a site has customised pages, SharePoint Designer provides necessary reporting features. To access the features, select “Reports” from the “Site” menu, then “Customised Pages”. For more detailed instructions, see the following article;

SharePoint Designer (2007) - Run reports for all sites programmatically. The article also demonstrates a method of performing reporting using SharePoint Designer for all sites in a site collection.

2/ Set all tasks with a due date less than a week, but more than 3 days away to yellow


- repeat (create new condition for the title field or row background) with less than or equal to -7 as condition. Advanced expression below:


number(translate(substring-before(@DueDate,'T'),'-','')-7) <= number(translate(substring-before($Today,'T'),'-',''))




3/ Set all tasks with a due date less than a week, but more than 3 days away to orange



Repeat with less than or equal to -3 as the condition. Advanced expression below:



number(translate(substring-before(@DueDate,'T'),'-','')-3) <= number(translate(substring-before($Today,'T'),'-',''))



4/ Set all tasks due today (1 day) to red

- Repeat with less than or equal to -1 as condition (include the -1). Advanced expression below:

number(translate(substring-before(@DueDate,'T'),'-','')-1) <= number(translate(substring-before($Today,'T'),'-',''))


5/ Set overdue tasks text to bold (already red from the previous condition)

- No advanced expression is required for this condition. Using the “Condition Criteria” dialog, simply set the field to the due date and the condition to less than the current date ( @DueDate < [Today] ).

The title for each task in the list should now be coloured dynamically based on the due date. The same method can be used to format items based on priority or most other columns.



Create a Data View by using the Data Source Details task pane

When you create a Data View by using the Data Source Details task pane, you first insert a Data View into the page. You then select a data source in the Data Source Library, a task pane that manages available data sources for a SharePoint site. After you select your data source, the Data Source Details task pane opens. In the Data Source Details task pane, you choose the fields that you want to display and then insert them into the Data View.

Data Views are based on ASP.NET 2.0 technology. To create a Data View, you must start with an ASP.NET page (.aspx file). In this example, you will create a new ASP.NET page, and then create a Data View by using the Data Source Details task pane.

  1. On the File menu, click New.
  2. In the New dialog box, double-click ASPX.

    A new page with a FORM tag opens.

    An ASP.NET form tag appears on the page.

  3. On the Data View menu, click Insert Data View.

    An empty Data View is now displayed on the page, and the Data Source Library task pane opens.

    An empty Data View Web Part

    Now that you have inserted the Data View, you are ready to add data.

  4. In the Data Source Library task pane, locate your data source, click it, and then click Show Data.

    In the example, under XML Files, click products.xml, and then click Show Data. If the XML Files heading is collapsed, click the plus sign (+) to expand it.

  5. In the Data Source Details task pane, click the fields that you want to insert in the Data View.

    TIP To select multiple fields, hold down CTRL while you click them.

    In the example, in the ProductsRoot folder, under Products, clickProductName. Press and hold down CTRL while you click UnitsInStock,UnitsOnOrder, and ReorderLevel.

    Fields selected in the Data Source Details task pane

  6. Click Insert Selected Fields as, and then click Multiple Item View to insert the selected data into the Data View.

    NOTE Single Item View displays a single record in a Data View. Multiple Item View displays multiple records, with the fields in columns with headings for each column.

    The fields that you selected in the Data Source Details task pane now appear in a table.

    Products.xml as it appears in a Data View

  7. After you create a Data View, you can use WYSIWIG tools such as the Formattingtoolbar to modify fonts, align text, or apply colors. When you apply new formatting to a data point in your Data View, Office SharePoint Designer 2007 applies the formatting to all of the data at the same level in the XML by modifying the XSLT style sheet attached to the page. For example, in the previous illustration, if you select Chai and then click Bold on the Formatting toolbar, Office SharePoint Designer 2007 applies the same formatting to all of the content that appears in the ProductName field.

    Bold formatting applied to all data in the ProductName field