Tuesday, November 22, 2011

SPD Custom Changes with JavaScript

  

This article deals with the SharePoint designer and displays how to add custom java scripts to add new functionalities and UI changes.

 

Once we have our custom page ready we can do some experiments with javascript to change the look and feel. In this post I will show two changes made to a list page.

1.       Colour coding few sections

2.       changing the text of the field name

 

Changes would be made to a list page Newform.aspx of TestJSForm list. We are going to colour code the NewForm.aspx. Fields below 2; between 2-3 and greater than 3 would have three different colours. At the end column 2’s text would be changed.  

 

Once you open the page in the SPD go to the content place holder “PlaceHolderPageTitleInTitleArea”. We are going to write our javascript code inside this content place holder.  See below the code stub.

 

<asp:Content ContentPlaceHolderId="PlaceHolderPageTitleInTitleArea" runat="server">

                <SharePoint:ListProperty Property="LinkTitle" runat="server" id="ID_LinkTitle"/>:

                <SharePoint:ListItemProperty id="ID_ItemProperty" MaxLength=40 runat="server"/>

                <script type="text/javascript" language="javascript">

                _spBodyOnLoadFunctionNames.push('__colorCodeForm');

                function __colorCodeForm()

                {             

                                //alert('Hello world');

Var ParentChildID = document.getElementById('part1').childNodes[2].childNodes[0].childNodes;

//alert (ParentChildID.nodeNames); //alert (ParentChildID.length);

for (i=0; i<ParentChildID.length; i++)

{

                if (i<=2)

                {

                                //ParentChildID[i].childNodes[0].style.backgroundColor = '#ebf3cc';

                                ParentChildID[i].childNodes[1].style.backgroundColor = '#CCFFFF';

                }

                if (i > 2 && i<=3)

                {

                                //ParentChildID[i].childNodes[0].style.backgroundColor = '#ebf3cc';

                                ParentChildID[i].childNodes[1].style.backgroundColor = '#FFFF99';

                }

                if (i > 3)

                {

                                //ParentChildID[i].childNodes[0].style.backgroundColor = '#ebf3cc';

                                ParentChildID[i].childNodes[1].style.backgroundColor = '#FFCC99';

                }

}

//get to the item and change the innertext and html

                var item=ParentChildID[1].childNodes[0];

                //alert(item.innerText);               

                item.innerText="Partha";

                var item2=ParentChildID[1].childNodes[1].childNodes[1];

                //alert(item2.innerHTML);

                var item3=ParentChildID[1].childNodes[1];

                item3.innerHTML = item2.innerHTML + "This Description is being created by JS";

}

</script>

 

 

 

The line document.getElementById('part1').childNodes[2].childNodes[0].childNodes; is very important. This is the node which opens the nested child controls. The logic behind is when the listformview webpart is populated in the browser it get rendered as

<td valign="top"><div WebPartID="c9128cf3-3183-4bf7-8eb5-250fae8ae693" HasPers="false" id="WebPartWPQ2" width="100%" allowDelete="false" style="" >

<SPAN id='part1'>

<table class="ms-formtoolbar" cellpadding="2" cellspacing="0" border="0" id="ctl00_m_g_c9128cf3_3183_4bf7_8eb5_250fae8ae693_ctl00_toolBarTbltop" width="100%" >

  <tr>

 

The JS function traverses the DOM to get to the Span with id part1. Rest all the JS functions would be based on this logic only.

 

Another very important and interesting JS, which gets the element based on the tag name.

<script type="text/javascript">

//this function gets the element with tag name

function getTagFromIdentifierAndTitle(tagName, identifier, title) {

  var len = identifier.length;

  var tags = document.getElementsByTagName(tagName);

  for (var i=0; i < tags.length; i++) {

    var tempString = tags[i].id;

    if (tags[i].title == title && (identifier == "" || tempString.indexOf(identifier) == tempString.length - len)) {

      return tags[i];

    }

  }

  return null;

}

</script>

</asp:Content>

 

The final output will be something similar to

clip_image002[8]

 

 

 Thanks for reading. If you have some other explanation – please post a comment… I’ll be happy to hear.

...HaPpY CoDiNg

Partha (Aurum)

References:

http://office.microsoft.com/en-us/sharepoint-designer-help/CL010082351.aspx?CTT=97

http://office.microsoft.com/en-us/sharepoint-designer-help/create-a-custom-list-form-HA010119111.aspx

 

SPD to Hide list field in NewForm.aspx

 

Hiding few columns from the default view DataFormWebPart webpart.

 

This article would cover the we can change the new from page of any list. Generally we get to see the new form page with application master page, but here I have changed it to default master page.

Additionally we will also see how to hide even mandatory field. However,  except for the title field SharePoint does not enter any default value.

 

I would suggest to add a new page to the list to show  dataformwebpart and then do changes. I won’t go in detail of how to add pages, rather follow the link below to create/know how to add list page in any list from SPD please refer to the below link.

http://office.microsoft.com/en-us/sharepoint-designer-help/create-a-custom-list-form-HA010119111.aspx

 

The SPD code change would look like below. I am not adding whole of the Placeholdermain content place holder but only the html table where the fields are there.

<table border="0" cellspacing="0" width="100%">

<tr><td colspan="2" style="background-color:olive; font-family:Verdana;font-weight:bold; text-align:center">Test of SPD List Page</td></tr>

<tr><td width="190px" valign="top" class="ms-formlabel">

                <H3 class="ms-standardheader">

                <nobr>Title<span class="ms-formvalidation"> *</span>

                </nobr></H3></td>

<td width="400px" valign="top" class="ms-formbody">

<SharePoint:FormField runat="server" id="ff1{$Pos}" ControlMode="New" FieldName="Title" __designer:bind="{ddwrt:DataBind('i',concat('ff1',$Pos),'Value','ValueChanged','ID',ddwrt:EscapeDelims(string(@ID)),'@Title')}"/>

<SharePoint:FieldDescription runat="server" id="ff1description{$Pos}" FieldName="Title" ControlMode="New"/>

</td>

</tr>

<tr><td width="190px" valign="top" class="ms-formlabel">

                <H3 class="ms-standardheader">

                <nobr>Col1</nobr>

                </H3></td>

<td width="400px" valign="top" class="ms-formbody">

<SharePoint:FormField runat="server" id="ff2{$Pos}" ControlMode="New" FieldName="_x0043_ol1" __designer:bind="{ddwrt:DataBind('i',concat('ff2',$Pos),'Value','ValueChanged','ID',ddwrt:EscapeDelims(string(@ID)),'@_x0043_ol1')}"/>

<SharePoint:FieldDescription runat="server" id="ff2description{$Pos}" FieldName="_x0043_ol1" ControlMode="New"/>

</td></tr>

 

<!--<tr>                <td width="190px" valign="top" class="ms-formlabel">

                <H3 class="ms-standardheader">

                <nobr>Col5 <span class="ms-formvalidation"> *</span></nobr>

                </H3></td>

                <td width="400px" valign="top" class="ms-formbody">

                <SharePoint:FormField runat="server" id="ff3{$Pos}" ControlMode="New" FieldName="_x0043_ol5" __designer:bind="{ddwrt:DataBind('i',concat('ff3',$Pos),'Value','ValueChanged','ID',ddwrt:EscapeDelims(string(@ID)),'@_x0043_ol5')}"/>

                <SharePoint:FieldDescription runat="server" id="ff3description{$Pos}" FieldName="_x0043_ol5" ControlMode="New"/>

                </td>

                </tr>-->

               

<tr><td width="190px" valign="top" class="ms-formlabel">

<H3 class="ms-standardheader">

<nobr>Col6</nobr>

</H3>

</td>

<td width="400px" valign="top" class="ms-formbody">

<SharePoint:FormField runat="server" id="ff4{$Pos}" ControlMode="New" FieldName="_x0043_ol6" __designer:bind="{ddwrt:DataBind('i',concat('ff4',$Pos),'Value','ValueChanged','ID',ddwrt:EscapeDelims(string(@ID)),'@_x0043_ol6')}"/>

<SharePoint:FieldDescription runat="server" id="ff4description{$Pos}" FieldName="_x0043_ol6" ControlMode="New"/>

</td></tr>

<xsl:if test="$dvt_1_automode = '1'" ddwrt:cf_ignore="1">

<tr><td colspan="99" class="ms-vb">

<span ddwrt:amkeyfield="ID" ddwrt:amkeyvalue="ddwrt:EscapeDelims(string(@ID))" ddwrt:ammode="view"></span>

</td></tr></xsl:if>

</table>

 

 

The final output would be something

clip_image002

 

 

Thanks for reading. If you have some other explanation – please post a comment… I’ll be happy to hear.

...HaPpY CoDiNg

Partha (Aurum)

References:

http://office.microsoft.com/en-us/sharepoint-designer-help/CL010082351.aspx?CTT=97

http://office.microsoft.com/en-us/sharepoint-designer-help/create-a-custom-list-form-HA010119111.aspx

 

Thursday, November 17, 2011

Trying to use SPWeb object that has been closed or disposed and is no longer valid.

Are you trying to do this:

using (SPWeb spweb = SPContext.Current.Web)
    {

     ....
    }

this will give an above stated exception.

You may never close the objects SPContext.Current.Web or SPContext.Current.Site because these are the instances your sharepoint is running on. On the other hand, if you create your own instances of SPWeb or SPSite, you must dispose of them.

using (SPSite spsite = new SPSite(SPContext.Current.site.url))
    {

     using (SPWeb spweb = spsite.openweb())
    {        ....
    }

  }

There is a tool developed by microsoft (SPDisposeCheck) that checks your disposing habits and gives you a nice report of possible issues: http://archive.msdn.microsoft.com/SPDisposeCheck

You can even see the best practices of Microsoft -There is

http://msdn.microsoft.com/en-us/library/aa973248(v=office.12).aspx

 

Thanks for reading. If you have some other explanation – please post a comment… I’ll be happy to hear.

...HaPpY CoDiNg

Partha (Aurum)

References:

http://msdn.microsoft.com/en-us/library/aa973248(v=office.12).aspx

 

Wednesday, November 16, 2011

Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack

 

I have faced this error on various instances; see below the scenarios and solutions.

 

1.       It seems the error will occur when you have no permission to update the item. Try to run your code in RunWithElevatedPrivileges as below:

SPSecurity.RunWithElevatedPrivileges(delegate()

{

 using (SPSite spSite = new SPSite("http://MyWebApp"))

 {

using (SPWeb spWeb = spSite.OpenWeb())

 {      // insert your code here  }   }});

 

2.       The While using RunWithElevatedPrivileges you got following error.
Error : Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack when use new spsite
Solution: SPSite and SPWeb object should be created inside delegate(), example below. If not you might get the above error.CSS

Wrong Code:

string siteUrl = @" http://MyWebApp"

SPSite site = null ;  

SPWeb web = null

SPSecurity.RunWithElevatedPrivileges(delegate() 

   site = new SPSite(siteUrl); 

   web = SPSDestSite.OpenWeb();       

    // To do ( run code here )       

}); 

web.Close();

site.Close(); 

 

Correct Code:

string siteUrl = @" http://MyWebApp"

SPSecurity.RunWithElevatedPrivileges(delegate() 

using (SPSite site = new SPSite(siteUrl)) 

{

    using (SPWeb web = SPSDestSite.OpenWeb())

    { 

           // To do ( run code here ) 

    } 

}); 

 

Thanks for reading. If you have some other explanation – please post a comment… I’ll be happy to hear.

...HaPpY CoDiNg

Partha (Aurum)

References:

http://sites.wizdim.com/pathikrawal/sharepoint-2010/errorunable-to-evaluate-expression-because-the-code-is-optimized-or-a-native-frame-is-on-top-of-the-call-stack-while-debugging-project-in-visual-studio-2010-for-sharepoint-2010

 

Friday, November 11, 2011

How SharePoint Page Processing and others

 

I know all SharePoint gigs knows what I am stating in this article. To be honest this is more for may quick reference.

ASP.NET Applications vs. SharePoint Sites

Windows SharePoint Services development and traditional ASP.NET development differ in many ways. To help you understand the differences, we can compare ASP.NET applications with Windows SharePoint Services applications.

Figure 1 displays the different components and the interaction flow of a mainstream ASP.NET application.

Figure 1. Components and flow of a mainstream ASP.NET application

clip_image002

Users send requests to the server running Internet Information Services (IIS) for specific resources. These requests are accepted by IIS and delegated to an ISAPI extension DLL for further processing. Typically, resources are retrieved from the file system, such as .config files, .aspx pages, cascading style sheets, custom-built .NET assemblies, and user controls. All of these can act on the final response that is delivered to the user in his or her browser. In many applications, an interaction with a data store is also needed to store and retrieve data that is used to process the request and generate the response. 

So, what is different when we compare Figure 1 with Figure 2, which represents the components and flow for a site based on Windows SharePoint Services?

Figure 2. Components and flow of a Windows SharePoint Services site

 

clip_image004

 

As you can see in Figure 2, Windows SharePoint Services abstracts developers from many of the details of hosting highly scalable, template-driven sites. In many cases, SharePoint administrators and experienced users do not even touch that low-level infrastructure. However, an understanding of it is helpful.

Windows SharePoint Services is a site-provisioning engine that relies heavily on schema definitions for templates of many types of artifacts that are important to its environment. There are definitions for site templates; for infrastructure pages such as the default.aspx, which make up the home page of a team site; for lists and libraries; and for helper pages that enable the interaction among the content that is stored in these different containers.

When starting a request for a Windows SharePoint Services page, there is interaction with the configuration database and the content database that retrieves the details of the request. This includes accessing the many XML files that contain the schema definitions, and accessing building blocks (Web Parts) that each have to execute their code that is encapsulated in a .NET assembly made available via either the global assembly cache or the local bin folder. The Windows SharePoint Services provisioning engine joins all these processes.

When we look at the traditional ASP.NET application again, what happens there if you need more than one application, maybe two, five, or even dozens? Figure 1 starts to look complex because there the same infrastructure is repeated for each additional application. Developers following the best practices and patterns can produce many re-usable building blocks, but much of the infrastructure must still be re-created each time.

By comparison, many Windows SharePoint Services sites—dozens, hundreds, even thousands of collaboration sites—can be delivered with one common provisioning engine. This is the power of using Windows SharePoint Services compared to using ASP.NET applications.

What You Develop for Windows SharePoint Services

Windows SharePoint Services is a solutions platform, which means that it is extensible and ready to run custom solutions. The following sections discuss the solution types that Windows SharePoint Services developers can build.

Assembly-Based Solutions

We can refer to these solutions as code-based solutions. Assembly-based solutions are developed with managed code (a .NET Framework language such as Microsoft Visual C# or Microsoft Visual Basic 2005) and compiled as a .NET assembly (a DLL). You can build different types of these solutions as well. The following table describes only some of the possible assembly-based solutions.

Table 1. Types of assembly-based solutions

Solution Type

Description

Web Parts

Building blocks for a SharePoint Web Part Page that deliver specific functionality to the visitor of the site. Web Parts can deliver data from stores that are not based on Windows SharePoint Services (such as Microsoft SQL Server and Oracle stores); capture data to drive business processes; aggregate or roll up information that is available in the SharePoint sites, or perform many other functions. Many Web Parts are available by default with both Windows SharePoint Services 3.0 and MOSS 2007.

Event handlers

A .NET assembly containing one or more classes that encapsulate code that is executed when certain events (such as adding an item to a list, creating a column for a document library, deleting a site, and so on) occur in SharePoint sites.

Information management policies

A rich policy framework in MOSS that developers can use to build custom policies that enforce certain behavior for content stored and managed in SharePoint sites.

Workflow Activities and templates

A workflow is a collection of activities Windows SharePoint Services or the information workers involved in the workflow must take. Numerous activities are available; however, you can create custom activities compiled in a .NET assembly and deploy them so that experienced users creating workflows in Microsoft Office SharePoint Designer 2007 can use them. Developers can also create workflow templates by using the workflow extensions for Visual Studio 2005 and deploy these as .NET assemblies to the SharePoint servers.

Timer Jobs

Assemblies containing code that can be scheduled and executed by the SharePoint Timer Service. An example is a job scheduled to create a report every evening for the administrator about documents that have been checked out for more than a week.

ASP.NET Resources

Figure 2 showed the infrastructure that Windows SharePoint Services uses to deliver the sites. This infrastructure contains many ASP.NET resources that are directly available and help deliver the simplified development experience you have with Windows SharePoint Services. As a developer, you can create and integrate your own resources. Table 2 describes the possible types of resources you can create.

Table 2. Types of ASP.NET resources

Resource

Description

Site page

An ASP.NET page that is stored in a document library in the site collection itself (and is thus stored in the content database). Can be used to deliver custom functionality (such as reporting or dashboard pages) to the user. Site pages can be dynamically created and offer much flexibility. However, because they are stored in the content database, Windows SharePoint Services applies a strict security policy to these pages, and no inline code is allowed. Additionally, these pages are run in no-compile mode.

Application page

A physical ASP.NET page stored in the \12\Template\Layouts folder. This folder is commonly shared by all Windows SharePoint Services sites that are hosted on the Web server. Application pages are ideal for creating additional administration features for SharePoint sites. Because they are not part of the database, inline code is allowed.

Style sheets and master pages

Together, these define the look and feel of a site, as well as the common functionality that is used by all the pages of a site.

Navigation control

ASP.NET-based navigation controls that deliver an experience based on the ASP.NET provider model. Windows SharePoint Services provides many default ASP.NET-based navigation controls. Custom navigation controls are typically required when delivering public (Internet) facing sites with Windows SharePoint Services.

User control

ASP.NET user control (.ascx file) that can deliver common functionality to the pages in SharePoint sites. Windows SharePoint Services provides several controls in the \12\Template\ControlTemplates folder. Create additional custom user controls, and for example, visualize them within the master pages. User controls can deliver a particular editing experience to the user, such as custom information management policies or custom fields.

Schemas

Schemas are XML-based solutions that use the Collaborative Application Markup Language (CAML). Table 3 describes the features whose delivery you can drive by using schemas.

Table 3. Types of features delivered with schemas

Feature

Description

Site definition

A custom template for sites that are deployed in the \12\Template\SiteTemplate folder. The core file for a custom site definition is Onet.xml, which contains the global definitions for the site along with the possible configurations.

Features

Introduced in Windows SharePoint Services 3.0, a modular approach for delivering custom schemas and functionality to SharePoint sites. Features can activate what you build and deploy. Many of the previously mentioned types of solutions are made available by using Feature definitions. You can find the list of deployed Feature definitions in the \12\Template\Features folder

Custom Lists

The schemas for custom lists and document libraries are also defined via CAML-based files, many times as part of a Feature definition. However, they can also be part of a custom site definition.

Site Columns and Content Types

Schema for re-usable packaged definitions of content that can be stored and managed in SharePoint containers (lists and document libraries). Site columns and content types are delivered through Feature definitions most of the time.

Custom Field Definitions

These CAML-based files, together with a .NET assembly that contains the code-behind, deliver additional field types that users can select from when creating custom metadata in a document library, for example.

Data Manipulation

All of the content that is stored and managed in SharePoint sites, together with all the configuration data, is kept in SQL Server databases that you do not need to interact with directly. Windows SharePoint Services and MOSS have very rich object models that are delivered by a number of .NET assemblies, of which the Microsoft.SharePoint.dll and the Microsoft.Office.Server.dll are the most important.

The server object model is accessible only when the application is deployed to one of the computers that is part of the server farm. If the application accessing Windows SharePoint Services is remotely deployed, use the Web Services APIs instead.

Solutions that directly interact with the SharePoint classes must have access to the SharePoint context of the sites (either the collaboration sites or the administration sites, depending on the type of the solution). Examples are Windows–based applications that are deployed to a server running Windows SharePoint Services, Web Parts that run in the context of Windows SharePoint Services, custom Web services that expose data in a customized way, Windows services that run on the SharePoint server, and more.

Numerous Web services are available in Windows SharePoint Services that expose most of the necessary data manipulation operations. However, when in need of custom functionality, you can always create custom Web services and have Windows SharePoint Services host and integrate them with the built-in Web services.

 

Thanks for reading. Please refer to the links below for more information.

 

HaPpY CoDiNg….

Partha (Aurum)

Reference:

http://msdn.microsoft.com/en-us/library/bb530302(v=office.12).aspx

http://msdn.microsoft.com/en-us/library/bb530301(v=office.12).aspx

http://msdn.microsoft.com/en-us/library/bb687949(v=office.12).aspx