Affichage des articles dont le libellé est Sharepoint 2010. Afficher tous les articles
Affichage des articles dont le libellé est Sharepoint 2010. Afficher tous les articles

lundi 6 octobre 2014

Powershell : Modification du SMTP SharePoint 2013

# Adresse du serveur SMTP
$smptServer = 'smtp.server.com'
# Adresse mail d envoi
$fromAddr = 'noreply@mydomaine.com'
# Adresse mail de réponse
$replyAddr = 'noreply@mydomaine.com'


#Ne rien modifier à partir de cette ligne

#serveurs smtp
Add-PSSnapin Microsoft.SharePoint.PowerShell

$SMTPSvr = $smptServer
$FromAddr = $fromAddr
$ReplyAddr = $replyAddr
$Charset = 65001

vendredi 13 décembre 2013

SharePoint 2010 / 2013 Get all groups for SPUser including active directory group

SharePoint don't give you groups for SPUser if the right is given by an active directory group.

You have to merge groups specificied directly using user login in sharepoint groups and active directory groups.


private static List<SPGroup> GetAllUserGroups(SPUser user)
{
    List<SPGroup> groups = new List<SPGroup>();
    //Get groups from SharePoint
    foreach (SPGroup spGroup in user.Groups)
    {
        groups.Add(spGroup);
    }
    string userLogin = user.LoginName;

vendredi 14 juin 2013

SharePoint Get Convivial URL for a specific Term by Label

You can use the following function in order to retrieve the convivial url associated for a specific term if you use the navigation thanks to the termstore in sharepoint 2010 and 2013


        /// Get convivial URL for a specific term using Label
        /// </summary>
        /// <param name="navigation_Group_Name">Navigation group name for the site collection</param>
        /// <param name="navigation_TermSet_Name">Termset name used for termstore navigation</param>
        /// <param name="navigation_Nom_Term">Name of the term you want to retrieve</param>
        /// <param name="navigation_default_url">Default url used if none term match the label filter</param>
        /// <param name="site"></param>
        /// <returns>site relative convival url   /</returns>
        public static string GetUrlConvivialForTerm(
            string navigation_Group_Name,
            string navigation_TermSet_Name, 
            string navigation_Nom_Term, 
            string navigation_default_url,
            SPSite site)
        {
            string url = string.Empty;
            //Utiliser SPContext SPContext.Current.Site
            TaxonomySession session = new TaxonomySession(site, false);
            TermStore store = session.TermStores[0];
            CacheManager cm = new CacheManager();
            TermSet tHE = TermManager.GetTermSet(navigation_Group_Name, navigation_TermSet_Name, site.RootWeb.Url);

            NavigationTermSet navTermSet = NavigationTermSet.GetAsResolvedByWeb(tHE, site.RootWeb,
                           StandardNavigationProviderNames.GlobalNavigationTaxonomyProvider);

            IEnumerable<NavigationTerm> terms = navTermSet.Terms.Where(t => t.GetTaxonomyTerm().Name.Equals(navigation_Nom_Term));
           
            if(terms != null)
            {
                NavigationTerm term = terms.FirstOrDefault();
                if (term != null)
                {
                    url = term.GetWebRelativeFriendlyUrl();
                }
            }

            if(url.Equals(string.Empty))
            {
                return navigation_default_url;
            }
            else
            {
                return url;
            }
        }

vendredi 1 mars 2013

Modify Site Collection URL SharePoint 2010

In order to rename a Site collection in SharePoint 2010 you need to backup the site first and restore it on an new Site collection.
To do that you can use the following PowerShell :
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue 
  
#Get the Source Site Collection URL
$sourceURL = Read-Host “Enter the Source Site Collection URL:”
  
#Get the Target Site Collection URL
$targetURL = Read-Host “Enter the Destination Site Collection URL”
  
#Location for the backup file 
$backupPath = Read-Host “Enter the Backup File name & location (E.g. c:\temp\Source.bak):”
  
#Backup the source site collection
Backup-SPSite $sourceURL -Path $backupPath -force
  
#Delete source Site Collection 
Remove-SPSite -Identity $sourceURL -Confirm:$false
  
#Restore Site Collection to new URL
Restore-SPSite $targetURL -Path $backupPath -Confirm:$false
  
#Remove backup files
Remove-Item $backupPath
  
write-host "Process Completed!"


jeudi 24 janvier 2013

Sort DataTable DataView ascending with null or empty last.


You first need to specify the sorting column in 'param' and replace the original DataTable by 'collection'.

In this example I filter a DataTable with the SelectedValue given by my DropDownList control (ddlFiltre).

In the DataRow array 'nameNotNull' I simply simply the data that are not null for my parameter and sort them.
And in the DataRow array 'nameNull' I select the null data for my parameter.

You just need to merge the two DataRow array and bind it with the GridView

DataTable collection;
//Fill the dataTable
//...
///

protected void ddlFiltre_Change(object sender, EventArgs e){ 
  if (!string.IsNullOrEmpty(ddlFiltre.SelectedValue)) {   
       string param = "Name";
       DataRow[] nameNotNull = collection.Select(string.Format("{0} IS NOT NULL AND {0} <> ''", param),string.Format("{0} ASC", param));
       DataRow[] nameNull = collection.Select(string.Format("{0} IS NULL OR {0} = ''", param));
        DataTable collectionSorted = collection.Clone();
   if (nameNotNull.Length > 0)
   {
      foreach (DataRow dr in nameNotNull)
      {
         DataRow newRow = collectionSorted.NewRow();
         newRow.ItemArray = dr.ItemArray;
         collectionSorted.Rows.Add(newRow);
      }
      if (nameNull.Length > 0)
      {
         foreach (DataRow dr in nameNull)
         {
            DataRow newRow = collectionSorted.NewRow();
            newRow.ItemArray = dr.ItemArray;
            collectionSorted.Rows.Add(newRow);
         }
       }
    }
    else if (nameNull.Length > 0)
    {
       foreach (DataRow dr in nameNull)
       {
          DataRow newRow = collectionSorted.NewRow();
          newRow.ItemArray = dr.ItemArray;
          collectionSorted.Rows.Add(newRow);
       }
    }
    gvItems.DataSource = collectionSorted;
    gvItems.DataBind();
}
}

jeudi 10 janvier 2013

Modifier les pages SharePoint par défaut. (AccessDenied.aspx, Confirmation.aspx, Error.aspx, Login.aspx, RequestAccess.aspx, Signout.aspx, WebDeleted.aspx)

Il est possible d'avoir de modifier l'url des pages suivantes et de les surcharger pour intégrer le design de l'entreprise :
  •  AccessDenied (Specifies AccessDenied.aspx)
  •  Confirmation (Specifies Confirmation.aspx)
  •  Error (Specifies Error.aspx)
  •  Login (Specifies Login.aspx)
  •  RequestAccess (Specifies ReqAcc.aspx)
  •  Signout (Specifies SignOut.aspx)
  •  WebDeleted (Specifies WebDeleted.aspx)
Avec les classes correspondantes se trouvant dans le namespace : 


Microsoft.SharePoint.ApplicationPages



Il est aussi nécéssaire de modifier la masterpage de votre page d'application par :

MasterPageFile="~/_layouts/simple.master"

Et d'hériter la classe correspondante 

UnsecuredLayoutsPageBase pour AccessDenied.aspx par exemple.




La modification de ces pages peut ensuite se faire de deux manières, soit par code C# :

SPWebApplication.UpdateMappedPage(SPWebApplication.SPCustomPage.AccessDenied, 

"_layouts/MyAccessDenied.aspx);


Soit via powershell : 


Set-SPCustomLayoutsPage -Identity "AccessDenied" -RelativePath 

"/_layouts/MyAccessDenied.aspx" -WebApplication http://serveur 

Get-SPCustomLayoutsPage –Identity "AccessDenied" -WebApplication http://serveur 

iisreset


Voici une page complète d'une customisation simple de la page AccessDenied.aspx avec changement du lien 'Retour au site' par défaut : 



<%@ Assembly Name="Name, Version=1.0.0.0, Culture=neutral,PublicKeyToken=092c1c010b5e2820" %>
<%@ Import Namespace="Microsoft.SharePoint.ApplicationPages" %>
<%@ 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" %>
<%@ Assembly Name="Microsoft.Web.CommandUI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AccessDenied.aspx.cs" Inherits="AccessDenied" MasterPageFile="~/_layouts/simple.master" %>

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="Microsoft.SharePoint" %>
<%@ Import Namespace="Microsoft.SharePoint.Publishing" %>
<%@ Import Namespace="System.Web" %>
<%@ Import Namespace="Microsoft.SharePoint.WebControls" %>

<script runat="server">
    protected void Page_Load(object sender, EventArgs e)
    {
        if (SPContext.Current != null && SPContext.Current.Web != null && SPContext.Current.Web.CurrentUser != null)
        {
            LabelUserName.Text = SPContext.Current.Web.CurrentUser.LoginName;
        }
     
        if (SPContext.Current != null && SPContext.Current.Web != null && SPContext.Current.Web.Site != null
            && SPContext.Current.Web.Site.WebApplication != null)
        {
         
            Page.ClientScript.RegisterStartupScript(this.GetType(), "click",
        "modifierRetour('" + SPContext.Current.Web.Site.WebApplication.Sites[0].Url + "');", true);
        }


   //     HLinkLoginAsAnother.Attributes.Add("onclick", "LoginAsAnother('\u002fsites\u002factuariat\u002f_layouts\u002fcloseConnection.aspx?loginasanotheruser=true', 1)");
    //    HLinkLoginAsAnother.NavigateUrl = "http://www.google.com/";
    }
    </script>

<asp:Content ID="PageHead" ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">
    <style type="text/css"></style>
    <script type="text/javascript">
        function modifierRetour() {
            var backbutton = document.getElementById('ctl00_PlaceHolderGoBackLink_idSimpleGoBackToHome');

            if (backbutton != null) {
                backbutton.href = "javascript:history.back()"; // cacherBackToSite.arguments[0];
            }
        }
</script>
</asp:Content>

<asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server">
 
   <table border="0" cellpadding="0">
         <asp:Panel id="PanelUserName" runat="server">
         <tr>
       <td class="ms-sectionheader">
       <%--<img src="/_layouts/images/ListSet.gif" alt="" />--%>
       <SharePoint:EncodedLiteral ID="EncodedLiteral3" runat="server" text="<%$Resources:wss,accessDenied_currentuser%>" EncodeMethod='HtmlEncode'/>
       </td>
         </tr>
         <tr>
       <td valign="top" class="ms-descriptiontext"><SharePoint:EncodedLiteral ID="EncodedLiteral4" runat="server" text="<%$Resources:wss,accessDenied_loggedInAs%>" EncodeMethod='HtmlEncode'/>
       &#160;<b><asp:Label id="LabelUserName" runat="server"/></b>
       </td>
         </tr>
         </asp:Panel>
    </table>
</asp:Content>

<asp:Content ID="PageTitle" ContentPlaceHolderID="PlaceHolderPageTitle" runat="server">
 <SharePoint:EncodedLiteral ID="EncodedLiteral1" runat="server" text="Accès refusé au site demandé" EncodeMethod='HtmlEncode'/>
</asp:Content>

<asp:Content ID="PageTitleInTitleArea" ContentPlaceHolderID="PlaceHolderPageTitleInTitleArea" runat="server" >
    <SharePoint:EncodedLiteral ID="EncodedLiteral2" runat="server" text="Vous n'avez pas le droit de visualiser ce site." EncodeMethod='HtmlEncode'/>
</asp:Content>


 


















vendredi 14 décembre 2012

How to activate custom action based on SharePoint Right

This javascript function is a helper to enable or disable custom action for SharePoint 2010 based on ContentTypeID, Permissions and number of selected element.

You can call this function in the CommandUIHandler EnabledScript attribute

Create a custom action for Ribbon :

  <CustomAction Id="Ribbon.AlertPerso"
              RegistrationType="ContentType"
                 RegistrationId="0x0101002D02DF72FAFB4EAB9446F92337C759AE01"
              Location="CommandUI.Ribbon" Title="Alert Perso">
    <CommandUIExtension>
      <CommandUIDefinitions>
        <CommandUIDefinition Location="Ribbon.Documents.Manage.Controls._children">
          <Button Id="Ribbon.CreerAlerter.Button"
                  LabelText="Créer une alerte personnalisée"
                  TemplateAlias="o2"
                  Image16by16="/_layouts/images/avertir16.png"
                  Image32by32="/_layouts/images/avertir32.png"
                  Sequence="08"
                  Command="AlerteCommandeDoc" />
        </CommandUIDefinition>
      </CommandUIDefinitions>
      <CommandUIHandlers>
        <CommandUIHandler Command="AlerteCommandeDoc"
                          CommandAction="javascript:window.location='votre page cible."
<!-- Replace the first attribute by you content type id, the second one with the SPPermission needed, and the thrid with the number of element that have to be selected (list of sharepoint permission kind : http://msdn.microsoft.com/en-us/library/ee556747(v=office.14).aspx) -->            EnabledScript="javascript:ActiveTypeContenuDroit('0x0101002D02DF72FAFB4EAB9446F92337C759AE01',SP.PermissionKind.,1);"/>
      </CommandUIHandlers>
    </CommandUIExtension>
  </CustomAction>
</Elements>




Ajout de la fonction dans core.js :

//Id of SP.ListItem
var ItemSelectedID;
//Content Type ID
var ItemSelectedContentType;
//SP.ListItem
var ItemSelectedItem;
//Right on the item.
var ItemSelectedRight;

//Check if the custom action is enabled

//ContenuID : Content Type Id that the item must match.
//Permission : Permissions needed, if null the custom action will be enabled.
function ActiveTypeContenuDroit(ContenuID, Permission, TypeAction) {
    var result = false;
    var selectedItems = SP.ListOperation.Selection.getSelectedItems();
    var countItems = CountDictionary(selectedItems);

    //when the action is available for all items.
    if (TypeAction == 0 && countItems == TypeAction) {
        result = true;
    } else {
        //when the action is available when only one item is selected.
        if (countItems == TypeAction && TypeAction == 1) {
            //when the objet is not defined
            if (this.ItemSelectedID == null) {
                var listGuid = SP.ListOperation.Selection.getSelectedList();
                ItemSelectedID = selectedItems[0]['id'];
                ListItemContentTypePermission(this.ItemSelectedID, listGuid);
            }
            //when the charged item is not previous item that was charged
            else if (this.ItemSelectedID != selectedItems[0]['id']) {
                this.ItemSelectedID = selectedItems[0]['id'];
                var listGuid = SP.ListOperation.Selection.getSelectedList();
                ListItemContentTypePermission(this.ItemSelectedID, listGuid);
            }
            //compare with the content type id parameter
            else if (this.ItemSelectedContentType != null) {
                if (ItemSelectedContentType.toString().indexOf(ContenuID.toString()) != -1) {
                    //Check rigth on the object.
                    if (Permission != null && ItemSelectedRight != null) {
                        if (ItemSelectedRight == null) {
                            alert("ItemSelectedRight null");
                        }
                        else {
                            //Check rigth on the object.
                            var permettre = ItemSelectedRight.has(Permission);
                            if (permettre) {
                                { result = true; }
                            }
                        }
                    }
                    else {
                        result = true;
                    }
                }
            }
        }
        else {
            //when more than one selected value is possible
            if (TypeAction > 1) {
                    // .. action when two item selected.
                alert("not defined ActiveTypeContenuDroit " + TypeAction);
                result = false;
            }
        }
    }
    return result;
}

//Initialize SP.ListItem and get the property  Title  ContentTypeId EffectiveBasePermissions
function ListItemContentTypePermission(ItemId, listGuid) {
    var clientContext = new SP.ClientContext();
    var web = clientContext.get_web();
    var lists = web.get_lists();
    var list = lists.getById(listGuid);
    ItemSelectedItem = list.getItemById(ItemId);
    clientContext.load(ItemSelectedItem, 'Title', 'ContentTypeId', 'EffectiveBasePermissions');
    clientContext.executeQueryAsync(onListItemContentTypePermission, failedListItemContentTypePermission);
}

//Get the needed property.
function onListItemContentTypePermission(sender, args) {
    ItemSelectedRight = ItemSelectedItem.get_effectiveBasePermissions();
    ItemSelectedContentType = ItemSelectedItem.get_item('ContentTypeId');
    RefreshCommandUI();
}

function failedListItemContentTypePermission(sender, args) {
    alert('Request failed. \nError: ' + args.get_message() + '\nStackTrace: ' + args.get_stackTrace());
}

mardi 20 novembre 2012

The HTTP service located is too busy / Le service HTTP est trop occupé



Pour provisionner un service trop occupé dans SharePoint 2010, exécuter les commande suivantes :

$sts = Get-SPServiceApplication | ?{$_ -match "nom du service"}  
$sts.Status
$sts.Provision()


Erreur sharepoint lié :
An exception occurred when trying to issue security token: Le service HTTP situé sur ../SecurityTokenServiceApplication/securitytoken.svc/actas est trop occupé.
Exception occured while connecting to WCF endpoint: System.ServiceModel.ServerTooBusyException


mardi 23 octobre 2012

Deactivate "I like" and "Notes" on ListItem for Sharepoint 2010 Ribbon / Désactiver les "J'aime ca" et "Notes" sur SharePoint 2010

Il suffit de désactiver la feature de ferme correspondante avec le code suivant :

Disable-SPFeature -id "756D8A58-4E24-4288-B981-65DC93F9C4E5" -force

Hide top navigation bar for Sharepoint 2010 / Cacher le ruban et la barre de navigation supérieur via code depuis la masterPage


Il ne faut pas oublier de passer les différents div en "runat='server'" pour que le code marche.

private void HideShowElement(bool value)
    {
        if(value) // Administrateur
    {    
    Control haut  = this.FindControl("msWwpselectlink");
//((HtmlControl)haut).Width="0px";
  ((HtmlControl)haut).Attributes.Add("style","display:block;");

Control hautLien  = this.FindControl("topNavgationBar");
  ((HtmlControl)hautLien).Attributes.Add("style","display:block;");


    Control crt = this.FindControl("PanelAdminLeft");
    if(crt!= null)
    {
    crt.Visible = true;
                //Supprime le css pour aligner à gauche.
                Control content = this.FindControl("MSO_ContentTable");
                if(content != null){
                ((HtmlControl)content).Attributes.Add("class","s4-ca s4-ca-dlgNoRibbon");}
    }
    }
    else  // Non administrateur
    {
    Control haut  = this.FindControl("msWwpselectlink");
// haut.Visible = false;
  ((HtmlControl)haut).Attributes.Add("style","display:none;");
  Control hautLien  = this.FindControl("topNavgationBar");
  ((HtmlControl)hautLien).Attributes.Add("style","display:none;");


    Control crt = this.FindControl("PanelAdminLeft");
    if(crt!= null)
    {
    crt.Visible = false;
                //Supprime le css pour aligner à gauche.
                Control content = this.FindControl("MSO_ContentTable");
                if(content != null){
                ((HtmlControl)content).Attributes.Remove("class");}
            }
    }
    }

Hide button in sharepoint 2010 Ribbon / Cacher les boutons du ruban SharePoint 2010


Feature à appliquer sur un type de contenu / template de liste par exemple.

Il suffit ensuite de spécifier la localisation du bouton.

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">

  <CustomAction Id="HideCustomActionDocumentSource"
                Location="CommandUI.Ribbon"
                RegistrationType="ContentType"
                RegistrationId="0x0101002D02DF72FAFB4EAB9446F92337C759AE01">
    <CommandUIExtension>
      <CommandUIDefinitions>
        <CommandUIDefinition Location="Ribbon.Library.ViewFormat.Standard" />
        <CommandUIDefinition Location="Ribbon.Library.ViewFormat.Datasheet" />

        <CommandUIDefinition Location="Ribbon.Library.Datasheet.NewRow" />
        <CommandUIDefinition Location="Ribbon.Library.Datasheet.ShowTaskPane" />
        <CommandUIDefinition Location="Ribbon.Library.Datasheet.ShowTotals" />
        <CommandUIDefinition Location="Ribbon.Library.Datasheet.RefreshData" />

        <CommandUIDefinition Location="Ribbon.Library.CustomViews.CreateView" />
        <CommandUIDefinition Location="Ribbon.Library.CustomViews.ModifyView" />
        <CommandUIDefinition Location="Ribbon.Library.CustomViews.CreateColumn" />
        <CommandUIDefinition Location="Ribbon.Library.CustomViews.NavigateUp" />
        <CommandUIDefinition Location="Ribbon.Library.CustomViews.CurrentView" />
        <CommandUIDefinition Location="Ribbon.Library.CustomViews.DisplayView" />
        <CommandUIDefinition Location="Ribbon.Library.CustomViews.PreviousPage" />
        <CommandUIDefinition Location="Ribbon.Library.CustomViews.CurrentPage" />
        <CommandUIDefinition Location="Ribbon.Library.CustomViews.NextPage" />

        <CommandUIDefinition Location="Ribbon.Library.Share.AlertMe" />
        <CommandUIDefinition Location="Ribbon.Library.Share.ViewRSSFeed" />

        <CommandUIDefinition Location="Ribbon.Library.Actions.TakeOfflineToClient" />
        <CommandUIDefinition Location="Ribbon.Library.Actions.ConnectToClient" />
        <CommandUIDefinition Location="Ribbon.Library.Actions.ExportToSpreadsheet" />
        <CommandUIDefinition Location="Ribbon.Library.Actions.OpenWithExplorer" />
        <CommandUIDefinition Location="Ribbon.Library.Actions.AllMeetings" />

        <CommandUIDefinition Location="Ribbon.Library.CustomizeLibrary.AddButton" />
        <CommandUIDefinition Location="Ribbon.Library.CustomizeLibrary.EditList" />
        <CommandUIDefinition Location="Ribbon.Library.CustomizeLibrary.EditDefaultForms" />

        <CommandUIDefinition Location="Ribbon.Library.Settings.ManageWorkflows" />
        <CommandUIDefinition Location="Ribbon.Library.Settings.LibraryPermissions" />

        <CommandUIDefinition Location="Ribbon.Documents.New.NewFolder" />
        <CommandUIDefinition Location="Ribbon.ListItem.New.NewFolder" />
     
        <CommandUIDefinition Location="Ribbon.Documents.New.NewDocument" />
        <CommandUIDefinition Location="Ribbon.Documents.EditCheckout.CheckOut" />
        <CommandUIDefinition Location="Ribbon.Documents.EditCheckout.CheckIn" />
        <CommandUIDefinition Location="Ribbon.Documents.EditCheckout.DiscardCheckOut" />
 
        <CommandUIDefinition Location="Ribbon.Documents.Manage.ManagePermissions" />

        <CommandUIDefinition Location="Ribbon.Documents.Share.EmailItemLink" />
        <CommandUIDefinition Location="Ribbon.Documents.Share.AlertMe" />

        <CommandUIDefinition Location="Ribbon.Documents.Copies.SendTo" />
        <CommandUIDefinition Location="Ribbon.Documents.Copies.ManageCopies" />
        <CommandUIDefinition Location="Ribbon.Documents.Copies.GoToSourceItem" />
   
        <CommandUIDefinition Location="Ribbon.Documents.Workflow.ViewWorkflows" />
        <CommandUIDefinition Location="Ribbon.Documents.Workflow.Publish" />
        <CommandUIDefinition Location="Ribbon.Documents.Workflow.Unpublish" />
        <CommandUIDefinition Location="Ribbon.Documents.Workflow.Moderate" />
        <CommandUIDefinition Location="Ribbon.Documents.Workflow.CancelApproval" />
   
        <CommandUIDefinition Location="Ribbon.Documents.FormActions.RepairItems" />
        <CommandUIDefinition Location="Ribbon.Documents.FormActions.RepairAllItems" />
        <CommandUIDefinition Location="Ribbon.Documents.FormActions.MergeDocuments" />
      </CommandUIDefinitions>
    </CommandUIExtension>
  </CustomAction>
</Elements>


Liste complète
http://msdn.microsoft.com/en-us/library/ee537543.aspx



vendredi 14 septembre 2012

Comment cacher les actions dans un site SharePoint grâce au Javascript(Session, Site, Liste, Bibliothèques de documents)


L'utilisation du JavaScript est un moyen efficace et peut coûteux en développement pour cacher les différentes actions qui peuvent apparaître sur une page SharePoint.

 


Il est en effet possible grâce à une simple fonction Javascript insérable dans la masterpage, de cacher les différentes actions :
  • Mes paramètres
  • Se connecter en tant qu'utilisateur différent
  • Demander l'accès
  • Se déconnecter
  • Personnaliser cette page
  • Créer
  • Modifier la page
  • Paramètres du site
  • Nouvel élément
  • M'avertir
  • Créer une colonne
  • Créer un affichage
  • Paramètres - Liste
  • Tous les éléments
  • Modifier cet affichage
  • Créer un affichage
  • Télécharger un document
  • Télécharger plusieurs documents  
  • Modifier dans la feuille de données
  • Ouvrir avec l'Explorateur Windows
  • Exporter vers une feuille de calcul
  • Afficher le flux RSS

La fonction javascript est la suivante :

<script type="text/javascript" language="javascript">
function cacherActionPortail()
{
var menuItem;
var menuItemName;
var menuItemIndex=-1;
var menuItemNames=new Array("Mes paramètres",
 "Se connecter en tant qu'utilisateur différent",
 "Demander l'accès",'se déconnecter','Personnaliser cette page','Créer'
 ,"Modifier la page","Paramètres du site","Nouvel élément",
 "M'avertir","Créer une colonne","Créer un affichage",
 "Paramètres - Liste","Tous les éléments",
 "Modifier cet affichage","Créer un affichage",
 "Télécharger un document","Télécharger plusieurs documents","Modifier dans la feuille de données",
 "Ouvrir avec l'Explorateur Windows","undefined","Exporter vers une feuille de calcul","Afficher le flux RSS");

var menuItems = new Array("PersonalInformation",
 "LoginAsDifferentUser","RequestAccess",
 "Logout","PersonalizePage",
 "MenuItem_Create","MenuItem_EditPage",
 "MenuItem_Settings","New0","SubsribeButton",
 "AddColumn","AddView",
 "ListSettings","DefaultView","ModifyView",
 "CreateView","Upload",
 "MultipleUpload","EditInGridButton","OpenInExplorer","OfflineButton",
          "ExportToSpreadsheet","ViewRSS");

var allMenuItems = document.getElementsByTagName('ie:menuitem');

for(var i = 0; i < cacherActionPortail .arguments.length; i++ )
{
menuItemName= cacherActionPortail .arguments[i].toLowerCase();
for (j=0; j < menuItemNames.length; j++)
{
if(menuItemNames[j].toLowerCase()==menuItemName)
{
menuItemIndex = j;
break;
}
}

menuItem=menuItems[menuItemIndex];

for (var l = 0; l < allMenuItems.length; l++)
{
if(menuItemName.indexOf(":")!=-1)
{
menuItemName = menuItemName.split(":")[1];
}
if (allMenuItems[l].id.indexOf(menuItem)!=-1
       && allMenuItems[l].text.toLowerCase() == menuItemName)
{
// For FireFox Compatibility
var parentNodeOfMenuItem = allMenuItems[l].parentNode;
parentNodeOfMenuItem.removeChild(allMenuItems[l]);
break;
}
}
}
}
</script>

Ainsi que l'appel de la fonction depuis le 'Page_Load' de la master page :

protected void Page_Load(object sender, EventArgs e)
{       

   Page.ClientScript.RegisterStartupScript(this.GetType(), "click","cacherActionPortail (\"Afficher le flux RSS\",\"Modifier dans la feuille de données\",\"Exporter vers une feuille de calcul\");", true);
}




mardi 11 septembre 2012

Supprimer les actions sur les documents Excel 'Afficher dans un navigateur web'' et 'Instantané dans Excel'

Si ces deux actions ne vous sont pas utiles et gêne la compréhension des utilisateurs vous pouvez les désactiver avec la commande suivante :

 

stsadm.exe -o deactivatefeature -force -id E4E6A041-BC5B-45cb-BEAB-885A27079F74

Cette fonctionnalités est installée au niveau de votre SPFarm.

Le fichier feature.xml se trouve à l'adresse suivante de votre serveur frontal Sharepoint 2007 :

C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\TEMPLATE\FEATURES\ExcelServer



SPWeb.Groups et SPWeb.SiteGroups


Il existe une différence entre ces deux collections de groupes Sharepoint qui est de taille.

En effet SPWeb.Groups ne retourne que les groupes ayant au moins un niveau d'autorisation associé tandis que SPWeb.SiteGroups renvoi tout les groupes de votre SPWeb.

Une différence de taille si vous utilisez un groupe uniquement à des fins hiérarchique.

Préférez donc utiliser SPWeb.SiteGroups plutôt que SPWeb.Groups.

Et voici une exemple de fonction permettant de récupérer les adresses email de tout les utilisateurs d'un groupe:


public string GetEmailForUserInGroupe(string groupName)
{
     string userMail = string.Empty;
     SPSecurity.RunWithElevatedPrivileges(delegate()
     {
            using (SPSite site = SPContext.Current.Site)
            {
                site.AllowUnsafeUpdates = true;
                using (SPWeb web = site.OpenWeb())
                {
                    web.AllowUnsafeUpdates = true;
                    SPGroupCollection groupColl = web.SiteGroups;
                    int count = groupColl.Count;
                    for (int i = 0; i < count && string.IsNullOrEmpty(userMail); i++)
                    {
                        if (groupColl[i].Name.Equals(groupName))
                        {
                            SPUserCollection userColl = groupColl[i].Users;
                            foreach (SPUser us in userColl)
                            {
                                if (!string.IsNullOrEmpty(us.Email))
                                {
                                    userMail = string.Concat(userMail, us.Email, ';');
                                }
                            }
                        }
                    }
                    web.AllowUnsafeUpdates = false;
                }
                site.AllowUnsafeUpdates = false;
            }
        });
        return userMail;
}    



lundi 25 juin 2012

Installation de l'icone Pdf et indexation des contenu PDF

Tutoriel pour l'installation de iFilter ainsi que l'ajout de l'icone PDF:
  1. Télécharger l'icone depuis le site : http://www.adobe.com/misc/linking.html#pdficon
  2. Ajouter les icones au répertoire : C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\IMAGES
  3. Modifier le fichier DOCICON.XML situé dans le dossier C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\
  4. Ajouter l'entrée suivante au fichier : <Mapping Key="pdf" Value="pdficon_small.png"/>
  5. Effectuer un redémarrage du serveur web : IISRESET
Intrégration des fichiers PDF à la recherche:
Télécharger et installer:

Création Business Connectivity Service (BCS) pour SharePoint Server 2010


Présentation

Le but de ce développement est de permettre d’avoir une vue synthétique sur les utilisateurs des plannings fournit par Microsoft Project Server via SharePoint.

En effet, les données sont stockés dans la base de données SQL Server et donc uniquement accessible via requête SQL.

Ce développement va permettre d’afficher les informations relatives à la saisie des plannings par les utilisateurs via une liste SharePoint.

Plusieurs étapes sont nécessaires à cette réalisation :
  1.  Créer une vue des données à partir de la BDD SQL Server et nécessaire à la liste SharePoint
  2. Créer une entrée dans la Secure Store Service, qui va permettre au service SharePoint de stocker les informations relatives à la connexion avec le serveur de BDD.
  3. Créer un Type de contenu externe via un BCS (Business Connectivity Services) permettant de récupérer les données externes à la base de contenu SharePoint
  4. Attribuer les droits utilisateurs sur le type de contenu
  5. Créer une liste externe qui permettra d’afficher le type de contenu externe crée précédemment.
Rendu final de la liste externe cree via bcs sharepoint 2010
Rendu final de la liste externe cree via bcs sharepoint 2010

Création de la vue

Avec un utilisateur ayant suffisamment de droit sur la base donnée MSProject, se connecter et exécuter le script :


CREATE VIEW [dbo].[V_UTILISATEUR_WITH_DAY_LAST_PUBLISHED_TIMESHEET] AS
   (SELECT res.res_uid as id_utilisateur,
       res.res_name as nom_utilisateur,
       res.WRES_ACCOUNT as account_utilisateur,
       res.wres_email as email_utilisateur,
       max(act.MOD_DATE) as date_last_published,
       DATEDIFF(day,max(act.MOD_DATE),SYSDATETIME()) as nombre_jour_derniere_saisie
       FROM
    [ProjectServer_Published_project_portfolio].[dbo].[MSP_RESOURCES] res,
      [ProjectServer_Published_project_portfolio].[dbo].MSP_TIMESHEETS ts,
      [ProjectServer_Published_project_portfolio].[dbo].MSP_TIMESHEET_LINES line,
      [ProjectServer_Published_project_portfolio].[dbo].MSP_TIMESHEET_ACTUALS act
      WHERE res.WRES_ACCOUNT IS NOT NULL
      AND res.RES_UID = ts.RES_UID AND ts.TS_UID = line.TS_UID
      AND line.TS_LINE_UID = act.TS_LINE_UID
      group by res.res_uid, res.RES_NAME, res.wres_email, res.wres_account)
      UNION
      (
      SELECT res.res_uid as id_utilisateur,
       res.res_name as nom_utilisateur,
       res.WRES_ACCOUNT as account_utilisateur,
       res.wres_email as email_utilisateur,
       null as date_last_published,
       null as nombre_jour_derniere_saisie
       FROM [ProjectServer_Published_project_portfolio].[dbo].[MSP_RESOURCES] res
       WHERE res.WRES_ACCOUNT IS NOT NULL AND
       res.res_uid not in
         (SELECT distinct res.res_uid  FROM
                  [ProjectServer_Published_project_portfolio].[dbo].[MSP_RESOURCES] res,
                  [ProjectServer_Published_project_portfolio].[dbo].MSP_TIMESHEETS ts,
                  [ProjectServer_Published_project_portfolio].[dbo].MSP_TIMESHEET_LINES line,
                  [ProjectServer_Published_project_portfolio].[dbo].MSP_TIMESHEET_ACTUALS act
                  WHERE res.WRES_ACCOUNT IS NOT NULL
                  AND res.RES_UID = ts.RES_UID
                  AND ts.TS_UID = line.TS_UID
                  AND line.TS_LINE_UID = act.TS_LINE_UID) );


Une fois la requête exécutée la vue nouvellement crée apparaitra dans la liste des vues disponible après rafraichissement de la liste.

Création de la Vue Sql Server 2008 sur base de donnees Microsoft Server Project
Création de la Vue Sql Server 2008 sur base de donnees Microsoft Server Project

Création du secure store service

Se rendre dans la console d’administration SharePoint 
 
Puis dans  Application Management - > Manage Service Applications

Et sélectionner le service « Secure Store Service »

Secure store service Sharepoint 2010
Secure store service Sharepoint 2010
Il faut ensuite créer une nouvelle entrée et fournir les informations demandés en respectant bien le « Target Application Type » à « Group ».

Configuration du Secure Store Application pour Sharepoint 2010
Configuration du Secure Store Application pour Sharepoint 2010
 
L’authentification avec SQL Server se fait avec des identifiants Windows il n’est donc pas la peine de changer les champs dans l’écran suivant.

Login credentials pour authentification windows
Login credentials pour authentification windows
 
L’écran suivant permet de spécifier qui pourra administrer et qui sera membres de cette nouvelle entrée.

Attribution des droits sur le secure store service sharepoint 2010
Attribution des droits sur le secure store service sharepoint 2010
 
Ceci fait il ne reste plus qu’à fournir les identifiant de connexion via l’icône de la page principale.

Identifiants de connexion à sql server 2008
Identifiants de connexion à sql server 2008
 
Un temps d’attente pour que le Secure Store Application est nécessaire pour que celui-ci soit pris en compte par le serveur SQL Server (environ 1h, peut dépendre de votre configuration réseau/serveur).

Création du BCS

Grâce à SharePoint Designer, ouvrir le site concerné par la création du type de contenu externe.
Création via Sharepoint 2010 designer du type de contenu externe (external content type)
Création via Sharepoint 2010 designer du type de contenu externe
Et créer le nouveau type de contenu externe : 

Creation of external content types with sharepoint designer 2010
Creation of external content types with sharepoint designer 2010
 
Saisir le nom du nouveau type de contenu et cliquez sur « External System »:
Configuration external content type
 Configuration external content type
 
Ajoutez une connexion, et choisir « SQL Server », puis saisir le nom du serveur, le nom de la base de données, et le nom de l’ID de la Secure Store Application crée précédemment.
database server database name secure store application id
Provide the different informations for Secure Store Application configuration
 
Il suffit ensuite de sélectionner la vue dans l’explorateur d’objet de la base de données et d’ajouter les opérations de lecture d’item et de liste.

creation des operations ne read item operation new read list operation
Création des opérations ,new read item operation, new read list operation
Input parameters configuration new read item operation bcs sharepoint 2010
 Input parameters configuration new read item operation bcs sharepoint 2010

Création de la liste externe

Une fois le type de contenu externe il ne reste plus qu’a créé la liste externe.
creation liste externe external list BDC model
Création de la liste externe à partir du type de contenu externe

Attribution des droits sur le type de contenu

Un réglage au niveau des permissions sur le type de contenu est nécessaire pour permettre aux utilisateurs de consulter la liste.
Se rendre dans la console d’administration SharePoint
Et se rendre dans  Application Management - > Manage Service Applications
Business data connectivity service
Business data connectivity service
 
Sélectionnez le type de contenu nouvellement crée puis cliquez sur le bouton « Set Object Permissions »
Set object permissions on BDC business data connectivity metadata store
Set object permissions on BDC business data connectivity metadata store

Rendu de la liste externe

La liste externe ainsi crée est disponible sur le site et propose la même interface de gestion au niveau droits, vues et paramétrage qu’une liste SharePoint.
Rendu final de la liste externe cree via bcs sharepoint 2010
Rendu final de la liste externe cree via bcs sharepoint 2010


Plus loin avec les Business Connectivity Service (BCS) :  What's New: Business Connectivity Services (BCS) in SharePoint Server 2010
Plus loin avec les type de contenu externe (external content type) : What Are External Content Types?
Plus loin avec Business Data Connectivity (BDC) : Service BDC (Business Data Connectivity)
Plus loin avec le Secure Store Service Application : Configuring the Secure Store Service 
Téléchargement : Microsoft SharePoint Designer 2010