7.11.12

The content type is in use

using System;
using System.Collections.Generic;
using Microsoft.SharePoint;

namespace Test
{
   class ConsoleApp
   {
      staticvoid Main(string[] args)
      {
         using (SPSite siteCollection = new SPSite("http://localhost"))
         {
            using (SPWeb webSite = siteCollection.OpenWeb())
            {
               // Get the obsolete content type.
               SPContentType obsolete = webSite.ContentTypes["Test"];

               // We have a content type.if (obsolete != null)
               {
                  IList usages = SPContentTypeUsage.GetUsages(obsolete);

                  // It is in use.if (usages.Count > 0)
                  {
                     Console.WriteLine("The content type is in use in the following locations:");
                     foreach (SPContentTypeUsage usage in usages)
                        Console.WriteLine(usage.Url);
                  }

                  // The content type is not in use.else
                  {

                     // Delete it.
                     Console.WriteLine("Deleting content type {0}...", obsolete.Name);
                     webSite.ContentTypes.Delete(obsolete.Id);
                  }
               }

               // No content type found.else
               {
                  Console.WriteLine("The content type does not exist in this site collection.");
               }
            }
         }
         Console.Write("\nPress ENTER to continue...");
         Console.ReadLine();
      }
   }
}

FBA sharepoint

http://donalconlon.wordpress.com/2010/02/23/configuring-forms-base-authentication-for-sharepoint-2010-using-iis7/
Utenza Database: SPS.Farm.Admin
Nome database: SharePoint_FBA
Membership Provider: FBAMembershipProvider
Role Manager: FBARoleProvider
1. Accededuto al db loggandoci con SPS.Farm.Admin
2. Lanciato c:\windows\microsoft.net\framework\v2.0.50727\aspnet_reqsql.exe e viene aperta la GUI di creazione
3. Creato database con windows auth

1.1 Creazione web application

1. Acceduto alla central admin
2. New web application sulla porta 80
3. Scelta la Claim Based e settati I flag ntlm e fba
4. Settati fba
5. Settato utente app pool
6. Accettati i default tranne service application connections e excel service (scelte le ultime 4)
7. Nome database 0

1.2 Configurazione FBA

1. Seguiti i passi del doc in allegato ed in particolare:
2. Lanciare IIS Manager
3. Selezionare la webapp (e poi rifare l’operazione anche nel central admin site e sottosito securityTockenService (secure store web service)come indicato nel punto 2 del documento allegato)
image
4. Connection string
a. Add
b. Nome: FbaConnectionString
c. Configurati i parametri (use windows security)
5. .net users
6. Selezionati e configurati i .net roles e membership
a. In particolare settato a false require security answer

imageimage
7. Cliccare su .net roles
Settare FBARoleProvider come default
image
8. Creati i ruoli StandardFBAUsers e AdminFBAUsers (no in central admin e in tocken security)
image
9. Creato l’utente SPS.FBA.Admin
image
10. Set Authentication
SharePoint should have done this when you created the web application, but let’s confirm.  From the web application home page in IIS Manager, select Authentication under the IIS section. Confirm that the web application has both Integrated and Forms enabled.
11. ATTENZIONE ALLA NOTA SEGUENTE!!!
Ricordarsi di risettare come default c
12. In order for you to use IIS Manager to manage your SQL users, you need to set the default provider to our Forms provider, i.e. FBAMembershipProvider.  In order for it to work we need to set it to the SharePoint claims provider.  Go back to .NET Users and reset the default provider to “i” which is for the Microsoft.SharePoint.Administration.Claims.SPClaimsAuthMembershipProvider
You should also check the default Role Provider for the web application and ensure that is set to “c”.  If this is set to the SQL provider that you created, you will get an unexpected error after you logon.

13.9.12

DisableLoopbackCheck and SharePoint


Sharepoint access denied with hostname configuration

Add this registry entry by PowerShell

New-ItemProperty HKLM:\System\CurrentControlSet\Control\Lsa -Name "DisableLoopbackCheck" -value "1" -PropertyType dword

REFERENCE

15.6.12

Single Click ASP.Net Button

<asp:button cssclass="”button”" else="" false="" id="”btnUpdate”" onclick="”btnUpdate_Click”" onclientclick="”if(Page_ClientValidate())" return="" runat="”server”" text="“Update”" this.disabled="true;" usesubmitbehavior="”false”" validationgroup="”vgNew”/"></asp:button>

14.6.12

Office Web Apps SharePoint 2010 Error

#If the service application is installed on a DC #Enable Word Web App: $e = Get-SPServiceApplication | where {$_.TypeName.Equals("Application Service d’affichage Word")} $e.WordServerIsSandboxed = $false $e.WordServerIsSandboxed #Enable PowerPoint Web App – you need to answer “Y” for each command: Get-SPPowerPointServiceApplication | Set-SPPowerPointServiceApplication -EnableSandboxedViewing $false Get-SPPowerPointServiceApplication | Set-SPPowerPointServiceApplication -EnableSandboxedEditing $false #Then do a IISRESET /NOFORCE. #Application de service Web Application Excel Services

17.4.12

Workflow with extended status values



Name="Test Workflow"
Description="Workflow process test."
Id="4A7E0789-D1C9-4c85-ADD9-1FE50B1E67A3"
CodeBesideClass="Test.TestWorkflow"
CodeBesideAssembly="Test.TestWorkflow, Version=1.0.0.0, Culture=neutral, PublicKeyToken=32f7f97ab571f0ac"
TaskListContentTypeId="0x01080100C9C9515DE4E24001905074F980F93160"
ModificationUrl="_layouts/ModWrkflIP.aspx"
AssociationUrl="_layouts/CstWrkflIP.aspx"
>



urn:schemas-microsoft-com:office:infopath:AssocForm:-myXSD-2006-12-26T21-51-13

urn:schemas-microsoft-com:office:infopath:DraftForm1:-myXSD-2006-12-12T17-41-23
urn:schemas-microsoft-com:office:infopath:DraftForm2:-myXSD-2006-12-13T14-29-26


_layouts/WrkStat.aspx


1. Shell
2. Draft
3. In Review
4. Submitted
5. Final



18.1.12

Why it returns null (control)TemplateContainer.FindControl("controlId")?

<%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
<%@ Assembly Name="Microsoft.Web.CommandUI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls"
    Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="asp" Namespace="System.Web.UI" Assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>
<%@ Import Namespace="Microsoft.SharePoint" %>
<%@ Register TagPrefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages"
    Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="LookUpProtocolCodeFieldControl.ascx.cs"
    Inherits="LookUpProtocolCodeProject.CONTROLTEMPLATES.LookUpProtocolCodeFieldControl"
%>
<SharePoint:RenderingTemplate runat="server" ID="LookUpProtocolCodeFieldControlTemplate"  >
    <Template>
        <table>
            <tr>
                <td>
                    <asp:DropDownList runat="server" ID="DDLLookUpProtocolCodeId">
                    </asp:DropDownList>
                </td>
            </tr>
        </table>
    </Template>
</SharePoint:RenderingTemplate>


protected override void CreateChildControls()
        {
            try
            {
                if (Field == null && this.ControlMode == SPControlMode.Display)
                { return; }

                base.CreateChildControls();

                DDLLookUpProtocolCode = (DropDownList)TemplateContainer.FindControl("DDLLookUpProtocolCodeId");
                if (DDLLookUpProtocolCode == null)
                    throw new SPException("Error: Cannot load the controls!");

                this.DDLLookUpProtocolCode.SelectedIndexChanged += new EventHandler(DropDownList_SelectedIndexChanged);
          

                DDLLookUpProtocolCode.TabIndex = TabIndex;
                DDLLookUpProtocolCode.CssClass = CssClass;
                DDLLookUpProtocolCode.ToolTip = Field.Title;
                PopulateDropDown();
            }
            catch (Exception ex)
            {
        ..
            }
        }

17.1.12

Writing to the SharePoint ULS Logs

try{
  ...
} catch (Exception ex) {
  SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("MSDN", TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, ex.Message, ex.StackTrace);
}

 

Product column is Unknown. This is the default behavior of the SPDiagnosticsService class

Unfortunately, interacting with a custom SPDiagnosticsService is available only in fully trusted farm solutions and not within sandboxed solutions.

To write to the ULS logs by using theSPDiagnosticsService class from the sandbox, developers can create a full trust proxy that the sandboxed solutions can call into

SPDeveloperDashboardLevel Dashboard SharePoint Display

$contentService = [Microsoft.SharePoint.Administration.SPWebService]::ContentService
$dashboardSetting = $contentService.DeveloperDashboardSettings
$dashboardSetting.DisplayLevel = [Microsoft.SharePoint.Administration.SPDeveloperDashboardLevel]::On
$dashboardSetting.Update()

EventFiringEnabled vs EventFiringEnabled

 

 

 

private static void EventFiringEnabled(bool enabled)

{

Assembly assembly = Assembly.Load("Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c");

Type type = assembly.GetType("Microsoft.SharePoint.SPEventManager");

PropertyInfo pi = type.GetProperty("EventFiringDisabled", System.Reflection.BindingFlags.Static|System.Reflection.BindingFlags.NonPublic);

pi.SetValue(null, !enabled, null);

}

SharePoint and Linq : speed code in visual web part

proxy generation


//in solution folder

set path=%path%;c:\program files\common files\microsoft shared\web server extensions\14\bin

spmetal.exe /web:{url sharepoint site} /namespace:{solution namespace} /code:{codeClassName}.cs


.aspx


<%@ Import Namespace="Microsoft.SharePoint.WebControls" %>
<SharePoint:SPGridView id="spGridView" runat="server" AutoGenerateColumns="false">
  <HeaderStyle HorizontalAlign="Left" ForeColor="Navy" Font-Bold="true" />
  <Columns>
    <SharePoint:SPBoundField  DataField="Title" HeaderText="Title"></SharePoint:SPBoundField>
    <SharePoint:SPBoundField DataField="JobTitle" HeaderText="JobTitle"></SharePoint:SPBoundField>
    <SharePoint:SPBoundField DataField="ProjectTitle" HeaderText="ProjectTitle"></SharePoint:SPBoundField>
    <SharePoint:SPBoundField DataField="DueDate" HeaderText="DueDate"></SharePoint:SPBoundField>
  </Columns>
</SharePoint:SPGridView>


.cs


using Microsoft.SharePoint.Linq;
using Microsoft.SharePoint;
using System.Linq;

{codeClassName} dc = new {codeClassName}(SPContext.Current.Web.Url); 
EntityList<EmployeesItem> Employees = dc.GetList<EmployeesItem>("Employees"); 
var empQuery = from emp in Employees
               where emp.Project.DueDate < DateTime.Now.AddMonths(6)
               select new
               {
                   emp.Title,
                   emp.JobTitle,
                   ProjectTitle = emp.Project.Title,
                   DueDate = emp.Project.DueDate.Value.ToShortDateString()
               }; 
spGridView.DataSource = empQuery;
spGridView.DataBind();

Web Part property attributes

Browsable
Set to false if you don't want to display the custom property in the property pane. Also, if you set the WebPartStorage attribute to Storage.None, your property won't display in the property pane.

Category
The title of the section of the property pane that you want created to display the custom property. If you don't specify the Category attribute or if you specify the Categoryattribute as "Default", your custom property is displayed in the Miscellaneous section of the property pane.

DefaultValue
The default value of the custom property. Specifying the default value minimizes the Web Part's storage requirements by storing the property's value only if it is different from the default.

Description
The contents of the tool tip that appears when you pause the mouse pointer over the custom property in the property pane.

FriendlyNameAttribute
The caption displayed for the custom property in the property pane. If you don't specify this attribute, the actual property name will be displayed in the property pane.

HtmlDesignerAttribute
Used to associate a property builder with the property.

ReadOnly
Set to true if you want the custom property to be read-only in the property pane.

ResourcesAttribute
Used to provide localized names for FriendlyName, Category, and Description in the tool pane for the custom property.

WebPartStorage
Set to Storage.Shared to display the custom property in the property pane when the user is in shared view of the page. Set to Storage.Personal to display the custom property in the property pane when the user is in Shared or Personal view of the page. Set to Storage.None if you don't want the setting to persist for the custom property. The custom property won't be displayed in the property pane.

 

[Category("Custom Properties")]
[DefaultValue(c_MyBoolDefault)]
[WebPartStorage(Storage.Personal)]
[FriendlyNameAttribute("Custom Boolean")]
[Description("Select to set value to True.")]
[Browsable(true)]
[XmlElement(ElementName="MyBoolean")]
// The accessor for this property.
public bool MyBool
{
get
{
return _myBool;
}
set
{
_myBool = value;
}
}

Hidden list SharePoint WebPart

 

Vous vous cacher ou montrer vos listes

 

image

 

Download WebPart

16.1.12

SharePoint and COM and Jquery - example

 

  1. Put JQuery distribution in 14hive\Layouts.
  2. Add Javascript link referral in the AdditionalPageHead place holder:

    <SharePoint:ScriptLink Language="Javascript" Localizable="False" runat="server" Name="jquery-1.4.4.min.js"/>
    <SharePoint:ScriptLink Name="SP.js" runat="server" OnDemand="true" Localizable="false"/>

  3. Add Javascript code and create Client Object Model call to retrieve value in Main conten place holder:

 

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

var spListItems;

function FilterLookup(filterSource, lookupList)
{

//select lookupcontrol
var filterElement = $("select[title='" + filterSource + "'] option:selected");
if(filterElement.length == 0) return;

var selectedFilterText = filterElement.text();
var selectedFilterValue = filterElement.value;

var clientCtx = new SP.ClientContext.get_current();
var spList = clientCtx.get_web().get_lists().getByTitle(lookupList);

var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml('<View><Query><Where><Eq><FieldRef Name=\''+ filterSource +'\'/>' +
'<Value Type=\'Text\'>'+ selectedFilterText +'</Value></Eq></Where></Query></View>');

this.spListItems = spList.getItems(camlQuery);
clientCtx.load(spListItems);
clientCtx.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed) );

} //

function onQuerySucceeded(sender, args) {

alert(this.selectedFilterText);
// Get CityElement Select or Input
var cityElement = $("select[title='City']");
if(cityElement.length == 0) { alert('Unknown'); }

var options = '';
var listItemEnumerator = spListItems.getEnumerator();

while (listItemEnumerator.moveNext()) {
var oListItem = listItemEnumerator.get_current();
options += '<option value="' + oListItem.get_id() + '">' + oListItem.get_item('Title') +'</option>';
}
cityElement.html(options);
}

function onQueryFailed(sender, args) {
alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}


// Attach function on document ready
$(document).ready(
function() {
ExecuteOrDelayUntilScriptLoaded(FilterLookup,"sp.js");
//FilterLookup("Country","City");

// Get CountryElement Select or Input
var countryElement = $("select[title='Country']");
if(countryElement.length == 0)
{
countryElement = $("input[title='Country']");
}
if(countryElement.length != 0) {
if(countryElement[0].optHid) {
$("input[id='" + countryElement[0].optHid + "']").bind("propertychange", function() { FilterCity(); });

} else{
$("select[title='Country']").change(function() { FilterLookup("Country","City"); });

}

}


}); // Document ready

</script>



 





NOTE: example and not complete code

12.1.12

No link to list item lookup

 

  1. sharepoint design 2010
  2. select field
  3. set disable-output-escaping = no link item lookup
  4. set value list item to


<xsl:value-of select="substring-before(substring-after(string($thisNode/@*[name()=current()/@DisplayName]),'&gt;'),'&lt;')" disable-output-escaping="no"></xsl:value-of>

Block Application Pages

All the pages having _layouts before them are application pages. Pages created automatically for various views are called Form Pages. Most often with SharePoint implementation we allow users to access these pages. However we may further want to cut down access of users from the application pages and the form pages.

SharePoint allows this by enabling the feature “ViewFormPagesLockDown”. This feature is activated at the Site Collection scope. All groups / users not having the “View Application Pages” permission will not be able to navigate to pages like “_layouts/viewlsts.aspx” or “pages/forms/allitems.aspx”.
Below are the steps to block access from application pages:

  1. Identify users / group to restrict.
  2. Set their permission to "Restricted Read" or remove the "View Application Pages" from existing assigned permission level.
  3. Enable "ViewFormPagesLockDown" feature using the command - stsadm -o activatefeature -url -filename ViewFormPagesLockDown\feature.xml

The above steps will block all users not having "View Application Pages" permission from accessing the application pages and form pages.