Wednesday, November 7, 2012

Remove User ID of a People and Group column when exporting SharePoint list to Excel



This is a VBA code to remove the user IDs from the exported spreadsheet. Apply the following code and run the macro to remove all User IDs from the spreadsheet

Sub RemoveUserIDs()
           'run against rows 1 to 10, if you want more change the start and end below
           start_of_range = 2
           end_of_range = ActiveSheet.UsedRange.Rows.Count

           'currently changes cells in colum A if you want B change to 2, C to 3 etc etc
            colum_start = 1

For col = start_of_range To ActiveSheet.UsedRange.Columns.Count
    For t = start_of_range To end_of_range
    newstring = ""
          For i = 1 To Len(Cells(t, col))
               If Not IsNumeric(Mid(Cells(t, col), i, 1)) And Mid(Cells(t, col), i, 1) <> "#" Then
                    newstring = newstring & _
                    Mid(Cells(t, col), i, 1)
               End If
         Next i
     newstring = Replace(newstring, ";;", ", ")
     newstring = Replace(newstring, ";", "")
     Cells(t, col).Value = newstring
    Next t
Next col
    ActiveWorkbook.Save
End Sub

Tuesday, November 6, 2012

Access denied. You do not have permission to perform this action or access this resource.

Error:
Access denied. You do not have permission to perform this action or access this resource.

(and)

<!-- #RENDER FAILED -->

Scenario: 

We have created a Custom List and added the list as a Web Part in the site's home page, grouped by 'Status' column. When the user approves an item under a Status 'Pending Cost Approval', the designer workflow will update the Status column to 'Cost Approved'. The order of action is

1. Select Approve/Reject menu for an item from the Web Part 
2. Select Approve, and click OK 
3. After approval, the page is redirected to the home page.
The issue is, when there is only one item in grouped under 'Pending Cost Approval' and since the item is getting moved to 'Cost Approval' status after approval, we are getting "Access denied. You do not have permission to perform this action or access this resource." error. No issues when there are more items in 'Pending Cost Approval' status. Attached the screen shot. Is there any workaround for this?
Access Denied error

On different version of browser, we received 'Render failed' error.
Render failed error

Resolution
I'm able to resolve this issue with the following workaround.
Set the Groupings to Expanded in the view and add the following script in a content editor web part in the same page.
<script src="/Documents/jquery-1.8.2.min.js" type= "text/javascript">
</script>
<script type="text/javascript">
function collapseGroups() {
$("img[src='/_layouts/images/minus.gif']:visible").parent().click();
}

_spBodyOnLoadFunctionNames.push("collapseGroups");
</script>


Reference: http://www.go4sharepoint.com/Forum/render-failed-error-list-view-2203.aspx

A duplicate name "" was found

Issue: Received an error when creating a site from  a custom site template.

Error: A duplicate name "Responsible" was found.

Resolution:

The issue was with the column names in a list of the site we created a custom template from. I initially created a Text field column with the name 'Responsible', later we created another Responsible column with People and group type after renaming the existing column to 'Contributors'. This actually led to an error when we created a new site using this site template. The issue was identified by renaming the site template from sitename.stp to sitename.cab > extact the cab file > open the manifest file.

Noticed that the internal name of 'Contributor' column was 'Responsible' and the display name of 'Responsible' column was 'Responsible'.

Deleting the 'Contributor' column and recreated with different internal name resolved the issue.

Monday, October 15, 2012

Read Multiple lines of Text field value using JQuery


To read a value of multiple lines of text from a Edit Form or New Form. Assume Comments is the field name

<script  language="javascript" type="text/javascript" >
function PreSaveAction()
{
   var Comments = getTagFromIdentifierAndTitle("textarea","TextField","Comments");  

   var CommentsText = RTE_GetEditorDocument(Comments.id);
   var CommentsTextValue = CommentsText .body.innerText;
}

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>

Additionally, use the following code to read the selected value of a drop down.

var val =  $("select[title='ChoiceFieldName']").val();

Saturday, October 13, 2012

JavaScript date validation in SharePoint form using Designer

Requirement: To validate date fields in Edit form before submitting the form.

Conditions:

  1. Start Date should not be less than End Date
  2. Start Date and End Date should not be less than Today
<asp:Content ContentPlaceHolderId="PlaceHolderMain" runat="server">
Add the following code after above line

<script  language="javascript" type="text/javascript" >
function PreSaveAction()
{
var date1 = $("input[title='Planned Release Start Time']").val(); var date2 = $("input[title='Planned Release End Time']").val(); var today = new Date(); today.setHours(0,0,0,0); if( date1 != "" || date2 != "") { var arrDate1 = date1.split("/"); var useDate1 = new Date(arrDate1[2], arrDate1[0]-1,arrDate1[1] ); var arrDate2 = date2.split("/"); var useDate2 = new Date(arrDate2[2], arrDate2[0]-1,arrDate2[1]); if(useDate1 < today || useDate2 < today) { alert("Planned Release Start Date and End Date should not be earlier than Today"); return false; // Cancel the item save process } if(useDate1 > useDate2) { alert("The Planned Release End Date cannot be earlier than the Planned Release Start Date"); return false; // Cancel the item save process } }
 return true;

}
</script>


Thursday, September 27, 2012

Cannot remove border of a table in Content Editor Web Part

When we add a <table> tag in content editor web part, we cannot customize or remove the cell border even when we set the css styles.

Workaround for this is by overriding the .ms-WPBody TD style in the aspx page where the web part is added.


<asp:Content ContentPlaceHolderId="PlaceHolderTitleAreaClass" runat="server">
<style type="text/css">
.ms-WPBody TD
{
         border:0;
}
</style>
</asp:Content>

Sorting Outline number in MOSS programmatically


To create a calculated field to sort the outline numbers programmatically. Following code helps to create the fields and calculated values on feature activation.

Feature Receiver Code


  string strListName = "Checklist";
        string fieldName = "Outline";
        string strSortFieldname = "CustomOutlineSort";
        string strCalculatedFieldname = "OutlineSorted";
        string OutlineFieldValue = string.Empty;
        string newOutlineFieldValue;

        /// <summary>
        /// FeatureActivated
        /// </summary>
        /// <param name="properties"></param>
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
               {
                   using (SPWeb web = (SPWeb)properties.Feature.Parent)
                   {
                       web.AllowUnsafeUpdates = true;
                       SPList objSPList = web.Lists[strListName];
                       //Create Readonly field 'CustomOutlineSort'
                       objSPList.Fields.Add(strSortFieldname, SPFieldType.Text, false);
                       SPFieldText txtField = (SPFieldText)objSPList.Fields[strSortFieldname];
                       txtField.ReadOnlyField = true;
                       txtField.Update();

                       //Create calculated field 'OutlineSorted'
                       objSPList.Fields.Add(strCalculatedFieldname, SPFieldType.Calculated, false);
                       SPFieldCalculated CalcField = (SPFieldCalculated)objSPList.Fields[strCalculatedFieldname];
                       CalcField.Formula = @"=" + strSortFieldname;
                       CalcField.Update();

                       objSPList.Update();
                       web.AllowUnsafeUpdates = false;

                       CalculateSortValue(properties);
                   }

               });
            }
            catch (Exception ex)
            {
                throw new SPException("An error occured when activating the feature. Make sure that the list 'Checklist' exists in this site.");
            }
        }


private void CalculateSortValue(SPFeatureReceiverProperties properties)
        {
            try
            {
                using (SPWeb oSite = (SPWeb)properties.Feature.Parent)
                {
                    oSite.AllowUnsafeUpdates = true;
                    SPList oList = oSite.Lists[strListName];

                    //Check if Outline, CustomOutlineSort and OutlineSorted fields are created.
                    if (oList.Fields.ContainsField(fieldName) && oList.Fields.ContainsField(strSortFieldname) && oList.Fields.ContainsField(strCalculatedFieldname))
                    {
                        foreach (SPListItem oListItem in oList.Items)
                        {
                            //Check if Outline field value is not empty
                            if (oListItem[fieldName] != null)
                            {
                                newOutlineFieldValue = string.Empty;
                                OutlineFieldValue = oListItem[fieldName].ToString();
                                string[] sections = OutlineFieldValue.Split('.');

                                //loop all the parts splitted with dot and left pad with '0' and make total width as 2 characters.
                                foreach (string section in sections)
                                {
                                    newOutlineFieldValue = newOutlineFieldValue + section.PadLeft(2, '0');
                                }
                                //append '00'to make total of 8 characters
                                for (int i = sections.Length; i < 4; i++)
                                {
                                    newOutlineFieldValue = newOutlineFieldValue + "00";
                                }
                            }
                            //Store the customized value in readonly field 'CustomOutlineSort'.
                            oListItem[strSortFieldname] = newOutlineFieldValue;
                            oListItem.Update();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new SPException("An error occured while calculating sort values for 'Outline' column in 'Checklist' list");
            }
        }



EventHandler code for ItemAdded and ItemUpdated events

//Sorting Outline Numbers in SharePoint list

string listName = "Checklist";
        string fieldName = "Section";
        string strSortFieldname = "CustomSectionSort";
        string strCalculatedFieldname = "SectionSorted";
        string OutlineFieldValue = string.Empty;
        string newOutlineFieldValue;

  /// <summary>
        /// Method to make the outline number sortable. The logic used is, the value will be splitted by dot and left pad
        /// each part with '0' to width of 2. After padding, merge all the parts and save the value in 'CustomOutlineSort' field.
        /// For instance 1.1.1 will be saved as 010101.
        /// </summary>
        /// <param name="properties"></param>
        private void CalculateSortValue(SPItemEventProperties properties)
        {
            try
            {
                SPWeb oSite = properties.OpenWeb();
                SPList oList = oSite.Lists[listName];
                SPListItem oListItem = properties.ListItem;

                //Check if Outline, CustomOutlineSort and OutlineSorted fields are created.
                if (oList.Fields.ContainsField(fieldName) && oList.Fields.ContainsField(strSortFieldname) && oList.Fields.ContainsField(strCalculatedFieldname))
                {
                    if (properties.ListItem[fieldName] != null)
                    {
                        newOutlineFieldValue = string.Empty;
                        OutlineFieldValue = properties.ListItem[fieldName].ToString();
                        string[] sections = OutlineFieldValue.Split('.');

                        foreach (string section in sections)
                        {
                            newOutlineFieldValue = newOutlineFieldValue + section.PadLeft(2, '0');
                        }
                        for (int i = sections.Length; i < 4; i++)
                        {
                            newOutlineFieldValue = newOutlineFieldValue + "00";
                        }
                    }
                    oListItem[strSortFieldname] = newOutlineFieldValue;
                    oListItem.Update();
                    oList.Update();
                }
            }
            catch (Exception ex)
            {
             
            }
        }