Showing posts with label sharepoint. Show all posts
Showing posts with label sharepoint. Show all posts

Wednesday, October 19, 2011

Second post back problem!!!


Windows SharePoint Services JavaScript has a “form onSubmit wrapper” which is used to override the default form action. This work is put in place to ensure that certain types of URLs, which may contain double byte characters, will fully work across most postback and asynchronous callback scenarios. However, if your scenarios do not involve double byte character URLs, you may successful disable this workaround and gain the ability to use ASP.NET AJAX UpdatePanels.

To do this, you may need to register a client startup script which disables this workaround, in addition to resetting the default form action:



This script may be directly embedded in the page. Or write a function like this:

private void EnsureUpdatePanelFixups()
{
if (this.Page.Form != null)
{
string formOnSubmitAtt = this.Page.Form.Attributes["onsubmit"];
if (formOnSubmitAtt == “return _spFormOnSubmitWrapper();”)
{
this.Page.Form.Attributes["onsubmit"] = “_spFormOnSubmitWrapper();”;
}
}
ScriptManager.RegisterStartupScript(this, typeof(UpdatePanel), “UpdatePanelFixup”, “_spOriginalFormAction = document.forms[0].action; _spSuppressFormOnSubmitWrapper=true;”, true);
}

This solves the second post back problem.



Following is the script for  emulate post back in sharepint.



Page.ClientScript.RegisterStartupScript(Page.GetType(), "msg", "script type='text/javascript'>_spOriginalFormAction = document.forms[0].action; _spSuppressFormOnSubmitWrapper=true;",false);




Friday, July 29, 2011

SharePoint Data View Trick

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.


Wednesday, July 6, 2011

Start Crawling With PowerShell

A while ago I blogged about starting a new crawl with PowerShell in this post, but today I got a bit further, each rollout I do on my dev machine a whole new site collection gets created using PowerShell, after that there is some test content provisioned (also using PowerShell), and finally the search settings are added. It kinda feels like everything is done through PowerShell. The point however is that I not only want to start a new crawl, but make sure that ‘old’ content is deleted. Step by step; I create some Crawled properties, create some Managed Metadata properties, create some scopes and finally delete the old content and crawl the new one.

The first part creating crawled properties and metadata properties i used this blog post. Getting me something like the following, that checks if the crawled property exists and if so gets it, otherwise creates it, then setting it into a metadata property that can be used. Nice to know is that the –propset property even though the documentation says its optional is in fact required!

1: # Get or create SPEnterpriseSearchMetadataCrawledProperty
2: if (Get-SPEnterpriseSearchMetadataCrawledProperty
3: -SearchApplication $searchapp -Name "proptocreate"
4: -ea "silentlycontinue") {
5: $crawlprop = Get-SPEnterpriseSearchMetadataCrawledProperty
6: -SearchApplication $searchapp -Name "proptocreate"
7: } else {
8: $crawlprop = New-SPEnterpriseSearchMetadataCrawledProperty
9: -SearchApplication $searchapp -VariantType 31
10: -Name proptocreate -IsNameEnum $false -PropSet "00130329-0000-0130-c000-000000131346"
11: }
12:
13: if (Get-SPEnterpriseSearchMetadataManagedProperty
14: -SearchApplication $searchapp -Identity "MetadataPorpertyExample"
15: -ea "silentlycontinue") {
16: write-host -f Green "MetaProperty already exists,
17: we delete it so it can be reacreated "
18: $prop = Get-SPEnterpriseSearchMetadataManagedProperty
19: -SearchApplication $searchapp -Identity "PublishingPageContent"
20: $prop.DeleteAllMappings()
21: $prop.Delete()
22: $searchapp.Update()
23: } else {}
24:
25: write-host -f Green "Try to create MetaProperty"
26: $prop = New-SPEnterpriseSearchMetadataManagedProperty
27: -SearchApplication $searchapp -Name "PublishingPageContent" -Type 1
28: $prop.EnabledForScoping = $true
29: $prop.Update()
30:
31: New-SPEnterpriseSearchMetadataMapping -SearchApplication
32: $searchapp -ManagedProperty $prop -CrawledProperty $crawlprop


After that i can create scopes (my colleague Peter found it out), where I check if a scope already exists and if so delete it so it can be recreated again:

1: if (Get-SPEnterpriseSearchQueryScope -SearchApplication $searchapp
2: -Identity "ScopeExample" -ea "silentlycontinue") {
3: write-host -f Green "Scope already exists,
4: we delete it so it can be reacreated "
5: $scope= Get-SPEnterpriseSearchQueryScope -SearchApplication
6: $searchapp -Identity "ScopeExample"
7: $scope.Delete();
8: $searchapp.Update();
9: } else {}
10:
11: # Create "ScopeExample" scope
12: $scope = New-SPEnterpriseSearchQueryScope -Name "ScopeExample"
13: -Description "Doorzoek alle informatie" -SearchApplication $searchapp
14: -DisplayInAdminUI $true
15:
16: New-SPEnterpriseSearchQueryScopeRule -RuleType AllContent
17: -Url $url -scope $scope


And after that in finally can reset my index, and make sure everything is found:

1: Write-Host -f Green "Delete current index ...";
2: $searchapp.Reset($true, $true)
3:
4: Write-Host -f Green "Start indexing and scopecompilation ";
5: $searchapp.StartScopesCompilation()
6:
7: $CrawlContents = Get-SPEnterpriseSearchServiceApplication
8: | Get-SPEnterpriseSearchCrawlContentSource
9:
10: foreach ($crawlcontent in $CrawlContents)
11: { $crawlcontent.StartFullCrawl(); }

Monday, October 26, 2009

Book Review: Professional SharePoint Designer 2007

Finally, a book (and a great one in that) covering SharePoint Designer! I recently finished reading Professional Microsoft Office SharePoint Designer 2007, authored by MVPs Woodrow Windischman, Bryan Phillips, and Asif Rehmani. With Microsoft making SPD 2007 available as a free download, it’s important that users of the product understand how to use it properly.

The authors did an incredible job covering the aspects of SPD from multiple perspectives. I enjoyed how they even included sections on developing solutions with Visual Studio. It was apparent those sections were added with the intent on getting readers familiar with the various options and methods they have available for developing extended functionality outside SPD, so don’t be disappointed if you don’t feel it’s advanced enough – remember that this isn’t a core development book.

The one thing I loved the most about the book was the style of writing; the authors did a great job simplifying walking through the features of SPD without losing my attention. The level of detail and simplicity was balanced very well throughout the book. I learned a lot of things reading this book and I believe any user, no matter how good he/she is with SPD, can learn a new thing or two from reading this book as well.

SharePoint Designer 2007 is a tremendous and powerful software. With Microsoft making it available to download for free, users need to have a strong understanding of how to work with it, and more importantly, how to avoid running into problems with it.

Tuesday, September 8, 2009

Using JQuery (client side JavaScript) to handle an ‘All’ option for SharePoint (edit)form checkboxes

Sometimes there are easy solutions to easy problems. All it takes is a little thinking outside of the box.

Prerequisites/knowledge:

SharePoint: Intermediate
HTML: Advanced
JavaScript: Intermediate/advanced
.Net: None
Scenario:
In a SharePoint entry form the user can select multiple values from a list. This should include an “All” option so in a long list the user can select or de-select all values with one click.

So the interface should look like:
Give this functional design to a SharePoint developer and he/she will come up with either:

This is not possible with SharePoint
This requires developing a new field control
I’ll handle this server-side

Another approach
Let’s take a step back, forget SharePoint and just summarize what actions needs to happen (as if you instructed another human being to perform those actions)

When the All option is clicked do:

Is the All option checked?
Then check all other checkboxes
Else uncheck all other checkboxes
That’s all!

So put on your SharePoint cap again.
These actions need to happen client-side (inside the browser).

We want to attach a click handler to the All checkbox and when clicked it should toggle all the other checkboxes. (Note to self: there can be multiple groups of checkboxes on an entry form)

If you have HTML & JavaScript experience you’re still with me and probably already thinking of a technical solution. Yes we need the _SPBodyOnloadWrapper here. And when you have (more then) some DOM experience you can attach code to the HTML INPUT tags.

We’ll care about the How later. First lets analyze the HTML code SharePoint delivers and see how the checkboxes are defined.

Let’s view the source of the entry/edit form.

The HTML code Sharepoint generates


I tidied the HTML a bit. As you can see every (input) checkbox has a unique id. We can fairly assume that SharePoint generates these so we can’t use hardcoded IDs. Now we need to come up with an approach to ‘execute’ Step 1

“Then check all other checkboxes”

Note that the IDs are all sequentially numbered; so apart from the last 2 digits all IDs (within one group) are the same.

Basically we want to extend the INPUT tag of the All option with an extra JavaScript function



The DOM battle plan:
The Document Object Model is a platform- and language-neutral interface that will allow programs and scripts to dynamically access and update the content, structure and style of documents. The document can be further processed and the results of that processing can be incorporated back into the presented page.

So with the DOM INPUT element for the All option we want to:

IF an All option is clicked we want to:
execute JavaScript code which:

takes the ID of the clicked option

cuts of the last 2 digits

Uses that ID to toggle the other DOM elements.

If you’re a programmer you’re already seeing the complex JavaScript manipulation of HTML DOM elements this takes.

If you are not a programmer you probably don’t have a clue what I’m talking about… but do read on!

Enter JQuery
jQuery is a JavaScript library that helps you keep your code simple and succinct by addressing some of the complexities of Document Object Model (DOM) scripting and Ajax interaction. It helps you get right to the point and express yourself in the fewest possible characters and was initially created by John Resig in early 2006. It comes as a single JavaScript file with optional plugins containing all the common DOM, Event, Effects, and Ajax functions.

With JQuery the JavaScript we have to add to the SharePoint page:

$(”.ms-RadioText[title=’All’] :checkbox”).click(function(){
var otherids = (this.id).substring(0, (this.id).length-2 );
$(”input[id^=’”+otherids+”‘]”).attr( “checked” , (this.checked)?”checked”:”" );
});

YES! That’s all it requires. Sometimes a solution is as simple as the problem. Provided you use the right tools.

This requires the JQuery JavaScript library. But I’m sure you can come up with similar code using MooTools or Sciptalicious. BTW the JQuery library is also used by Google and many other major sites.

It’s (compressed) footprint is only 20k; compare that to the xxxK Microsoft SharePoint itsef loads in various supporting JavaScript libraries and you have to agree it’s a minimal but o so valuable extension to your SharePoint environment.

Step by step
$(”.ms-RadioText[title=’All’] :checkbox”).click(function(){

JQuery selection of DOM objects which apply to the rules:

Is class ms-Radiotext

Which:

Have the tile attribute ‘All’

Which:

Are of type: checkbox

A function is attached to the Click event:

var otherids = (this.id).substring(0, (this.id).length-2 );

chops off the last 2 digits of the clicked (=this) identifier.

$(”input[id^=’”+otherids+”‘]”).attr( “checked” , (this.checked)?”checked”:”" );

The key here is the ^=

This Jquery statement matches all DOM input elements which id attribute start with the given id

It then sets the attribute “checked” to either “checked” or an empty string

});

Closes the function.

Using it in SharePoint
[to be extended]

Add the JQuery.js library to a document library. Note the complte path to it
Create a custom List ‘Vistted Continents’
Create a column ‘continents’ with the values (including ‘All’)
Open a New entry for the list
Add a Content Editor WebPart to the NewForm page (how to: see Adding WebParts to Form pages (to be written))
See: Google: ToolpaneView=2
Paste in the code


//Script Highlighter: http://tohtml.com/jScript/
(The whole JQeury initialisation code can be placed in a MasterPage; that would bring the CEWP code to just the 3 lines of code)

Additional notes:
A SharePoint choice field can only store 255 characters; so the user gets a warning/error when the total number of characters for all selected values exceeds 255 characters!
Must read JQuery references
JQuery homepage
http://www.jquery.com/
Good examples can be found on other sites:

JQuery (chainable events) examples
http://codylindley.com/blogstuff/js/jquery/
Simple JQuery examples
http://markc.renta.net/jquery/
50+ JQuery examples
http://www.noupe.com/jquery/50-amazing-jquery-examples-part1.html
45 even cooler examples
http://outatime.wordpress.com/2008/03/06/45-fresh-out-of-the-oven-jquery-plugins/
Rule library – manipulating CSS attributes
http://flesler.webs.com/jQuery.Rule/

Wednesday, August 26, 2009

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, @"

");
}
}

Thursday, August 20, 2009

Process to define personalization requirements

I'm often asked by customers how SharePoint can be used to personalize content for users. Although there are plenty of features in SharePoint to achieve personalization, you have to be able to come up with the rules that define an audience and then how you will identify the information that is relevant to each audience.

Wouldn't it be great if all information and content mapped to a comprehensive taxonomy and that we could automatically align the taxonomy with groups of people? Because this is not usually a simple thing to achieve, we need to prioritise the work required to start targeting information and content to users based on a number of factors.

Therefore, before we start talking about SharePoint personalization features, we need to identify the audiences, taxonomies, information /content sources, business priorities and the relationships between each of these.



You can start the process from an audience or content perspective (left vs. right). From an audience perspective, membership can be broken down into two types:

Optional (opt in/out)
Fixed (based on business rules)
Active Directory group membership or some other line of business application that manages access to information based on a user's role is a common way of defining audience membership but this often doesn't align to a taxonomy such as an EDRMS file plan.

Some audiences will be broad in scope while others will be very narrow.

There will be more than one taxonomy (internal and external), so look for areas of the taxonomy's that can be linked to audience properties.

Audiences will often not agree on which information is of most value. Prioritized personalization of information based on value to the business vs. level of complexity will help users understand the big picture.

Priority will be based on a number of factors:

Volume of content (architectural impact)
Value of content in helping make informed business decisions
Structure of content (formal taxonomy vs folksonomy or none)
Accessibility of the content (API's, iFilters, federated search etc)
Once all of these requirements have been identified, then we can architect a solution...

Thursday, August 13, 2009

2009 Top 10 Innovators and Influencers

The SharePoint team would like to congratulate Jeff Teper for making Information Week’s 2009 Top 10 Innovators and Influencers list! It’s a very impressive list – for example, President Obama, Sam Ruby (REST), etc. Check out the full article here.

A brief history of his career at Microsoft:

Jeff joined Microsoft in 1992 to work with information technology strategists and corporate developers on early Windows NT deployments. He led the creation of a new business group focused on knowledge management that introduced SharePoint Portal Server in 2001, which has since grown to be the leading portal and collaboration product, with over 10,000 customers and partners.

Fast forward to today: as corporate vice president of the SharePoint Research & Design Group at Microsoft, Jeff is responsible for SharePoint Server and its portal, content management, search and line-of-business integration technologies. His team released the latest version, SharePoint Server 2007, and is working on the next version, SharePoint Server 2010.

Refer:http://blogs.msdn.com/sharepoint/archive/2009/04/15/2009-top-10-innovators-influencers.aspx

Changing redirection in SharePoint with HttpModule and HttpHandler

Hi all,

SharePoint is maintaining some redirection by it’s on like error page, by clicking on user or group it will redirect to profile page and so many other…

In one of our requirement we have to implement custom profile page and custom error page.

So for this we need to over ride default SharePoint navigation.

And that can be implemented using HttpModule and HttpHandler.

To know the concept of HttpModule and HttpHander here is great article from Gustavo Velez

So here we go for changing Error page (check comments between the code for understanding)

class RedirectErrorModule : IHttpModule
{

//Custom error page relative URL
const string errorUrl = "/_layouts/CustomForder/CustomError.aspx";

// implement dispose method to dispose used object
public void Dispose()
{
//dispose you objects
}

public void Init(HttpApplication context)
{
//Define event for application error so that you can override.
context.Error += new EventHandler(context_Error);
}

//implement error event
void context_Error(object sender, EventArgs e)
{
string strURL = string.Empty;

//Current site URL
string strSiteURL = SPContext.Current.Site.Url;

//Current web url
string strWebURL = SPContext.Current.Web.Url;

//Clearing context error
HttpContext.Current.Server.ClearError();

//Clearing the response
HttpContext.Current.Response.Clear();

//redirecting to our custom error page.
HttpContext.Current.Response.Redirect(strWebURL + errorUrl, false);
}

}


After doing this we need to add entry in web.config for the same.

Enter following tag in section of your web.config


Check syntax from existing tags from web.config.

The same way we can implement any redirection with the use of end request Event.
public void Init(HttpApplication context)
{
//end request handler
context.EndRequest += new EventHandler(context_EndRequest);
}

//End request implementation
void context_EndRequest(object sender, EventArgs e)
{
HttpApplication httpApp = sender as HttpApplication;
HttpContext context = httpApp.Context;
string httpUrl = context.Request.Url.ToString();
string strWebURL = string.Empty;
string struserID = string.Empty;
//compare your URL and redirect it to custom one
// this is example to redirecting userdisp page (profile page) to custom page.
if (httpUrl.ToLower().Contains("/_layouts/userdisp.aspx"))
{

//implement business logic and generate url if needed
HttpContext.Current.Server.ClearError();
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Redirect(<>);

}
}


And same can be incorporated in one class no need to create another one.

And remember in web.config enter your module at the end after all SharePoint’s event handler so it will not create any problem. There is not at all problem if you write it before SharePoint’s but better to play safe :)

Search ASPX pages from sub site in SharePoint (MOSS 2007)

Search ASPX pages from sub site in SharePoint (MOSS 2007)

In my site collection I have one root site and 2 other sub sites. I have configured Search on site collection and crawl works successfully. Now when I try to search contents from search center results from root site return where content from sub sites are not returned in search result. I amazed and do lot of search on net finally I come to know for each sub site we need to turn on index all .ASPX pages to crawl the content of that ASPX.

Follow the steps to enable sub site ASPX pages in crawl.

Go to sub site > click site settings > in site administrator there is one option called search visibility


Now click on this search visibility option and click on radio button allow this web to appear in search result? To yes

And middle radio button of second option that is "Always index all ASPX pages on this site"

Crawl the content again. It will work for you


Thanks. Your comments and suggestion are appreciable

For more: refer http://www.sharepointkings.com/2009/07/search-aspx-pages-from-sub-site-in.html

Enable Anonymous access for site published through ISA server

If you want to enable anonymous access for SharePoint site published through ISA server with external URL different from the internal URL, you must enable it using the site internal URL otherwise the anonymous access option will not appear.

How to enable Anonymous access:

Enable anonymous access
Configure anonymous access (Office SharePoint Server)

We have a SharePoint site created with internal URL http://anony:444 then the site published through ISA server using URL http://anonymous.demo.com using SharePoint publishing rule.

To configure anonymous access one of the steps is to enable anonymous access from advanced permissions on the top level site Site Settings (check screen shot below)



This link will not appear unless you access the site with the internal URL, here in our example is http://anony:444

Programmatically creating views for a SharePoint discussion forum

As you can see I'm still working on sites, lists and views and I ran into another challenge.

It started out very basic. I wanted to create a discussion forum list on a site.

// Create new list
listGuid = newWeb.Lists.Add("Forum", "ForumDescription", "Forum", "00BFEA71-6A49-43FA-B535-D15C05500108", 108, "", SPListTemplate.QuickLaunchOptions.Off);
SPList forumList = newWeb.Lists[listGuid];

After succesfully creating the forum list I wanted to add a custom view to the list. That seemed to be easy enough as well.

// Add an extra view to the list
viewFields = new StringCollection();
viewFields.Add("LinkDiscussionTitle");
viewFields.Add("Author");
viewFields.Add("DiscussionLastUpdated");
newView = forumList.Views.Add("Portal View", viewFields, "", 100, true, false);
newView.Update();

Unfortunately creating a view using the code above causes the link on the title takes you to the forum list, instead of taking to the item for which you clicked the title. After doing some investigating via the user interface I found out that the subtle difference can be found in the View settings, under Folders. This setting is specific for the discussion forum. By default the choices "Show items inside folders" and "In all folders" is selected. When you change the second setting (Show this view:) to "In the top-level folder" the link on the title item behaves the way you expect and want it to behave.



Now the next challenge was to find out how to change the Folders settings using the object model. There is no property on the SPList or SPView object to change these settings, but after comparing the xml exports of the list with both settings I found out that there is a ContentTypeId property on the SPView object and that this was the only thing that changed between the two exports.

The way to set the "Show this view" setting to "In the top-level folder" is by using this code. Notice the second to last line, that's the line that I added to achieve this.

// Add an extra view to the list
viewFields = new StringCollection();
viewFields.Add("LinkDiscussionTitle");
viewFields.Add("Author");
viewFields.Add("DiscussionLastUpdated");
newView = forumList.Views.Add("Portal View", viewFields, "", 100, true, false);
newView.ContentTypeId = new SPContentTypeId("0x012001");
newView.Update()

So in the end the code you need to get the right settings for you discussion forum view is not difficult at all, the difficult part was finding out what code to use.


Note:For more refer http://sharepointblogs.com/mirjam/archive/2009/08/13/programmatically-creating-views-for-a-sharepoint-discussion-forum.aspx