30/11/10

Error de Acceso Denegado accediendo a una audiencia

Es posible que incluso ejecutando código con privilegios elevados os falle el código cuando accedeis a una audiencia para consultar si un usuario pertenece a la misma. El código sería mas o menos el siguiente:

try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(siteName))
{
AudienceManager audManager = new AudienceManager (ServerContext.GetContext( site));
Audience audience = audManager.GetAudience(audienceName);
ArrayList userInfoCollection = audience.GetMembership();

foreach (UserInfo userInfo in userInfoCollection)

{
if (userInfo.Email.ToUpper() == user.Email.ToUpper())
result = true;
}
}
}
});
}
catch (Exception ex)
{
}

Este error en un principio puede deberse a permisos por parte del usuario que está corriendo el pool de aplicaciones. Para validar eso teneis que ir a la seccion de administracion del proveedor de servicios compartidos y comprobar que el usuario tiene permisos para administrar audiencias.

Una vez validado esto, si os sigue fallando podeis probar este codigo que a mi me funcionó sin problemas:

SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(siteName))
{
AudienceManager audManager = new AudienceManager (ServerContext.GetContext( site));
if (audManager.IsMemberOfAudience(user.LoginName, audienceName))
result = true;
}
});

16/11/10

modificar el 'Filenotfoundpage' de la aplicacion web

Es posible que en nuestro entorno nos haga falta establecer una página de fichero no encontrado cuando se inserte una URL a un documento que no se encuentre, evitando la fea pagina de error 404. Para poder hacer esto en Sharepoint no es algo tan trivial y habrá que realizar una serie de pasos:

1.- Crear en /_LAYOUTS el fichero Custom404.html (por ejemplo) con el siguiente código:

2.- Crear la pagina de error en el raíz /home/paginas/error404.aspx:

esta pagina de error podrá tener nuestra master page, nuestro logo corporativo, etc.

3.- Crear el fichero error404.aspx en /_LAYOUTS/3082 con el siguiente código:


Y aquí viene la parte más complicada del proceso. Resulta que las web applications de sharepoint, por defecto tienen el FileNotFoundPage a Null y hay que establecérselo. Para ello hay que crearse una aplicación de consola que cambie eso. Yo la he creado para desmoss pero el EXE habría que lanzarlo en producción. El código es muy simple:


Y con esto tendríamos la página de fichero no encontrado para toda nuestra intranet.


saludos,
Juan

23/5/10

Campos de SharePoint Alert Templates

Cuando trabajamos con alertas de SharePoint hemos de tener claro la información de que disponemos para poder visualizarla correctamente:

AlertFrequency The time interval for sending an alert. Possible values include 0 (immediate), 1 (daily), or 2 (weekly).
EventType The type of event. Possible values include 1 (item added), 2 (item modified), 4 (item deleted), 16 (discussion added), 32 (discussion modified), 64 (discussion deleted), 128 (discussion closed), and 256 (discussion activated).
ItemName The title of the item.
ItemUrl The absolute URL for the item.
ListName The name of the list.
ListUrl The absolute URL for the list.
ModifiedBy The display name of the user who modified the item.
MySubsUrl The absolute URL for the My Alerts on this Site page in Site Settings.
SiteLanguage The locale identifier (LCID) for the language used on the site. For example, 1033 is the LCID for U.S. English.
SiteName The title of the site.
SiteUrl The absolute URL for the site.
TimeLastModified The time at which the item was last modified.

Saludos,
Juan Alcalá

Cambio de usuario a la primera

Cuando se cambia de usuario en MOSS es posible que no podamos tener los datos del nuevo usuario hasta que hagamos un F5 y recarguemos la pagina. Para poder solucionar el problema tenemos que modificar una función que se encuentra en el fichero INIT.JS


function LoginAsAnother(url, bUseSource)
{

document.cookie="loginAsDifferentAttemptCount=0";
if (bUseSource=="1")
{
GoToPage(url);
}
else
{
document.execCommand("ClearAuthenticationCache", false);
var ch=url.indexOf("?") >=0 ? "&" : "?";
url+=ch+"Source="+escapeProperly(window.location.href);
STSNavigate(url);
}
}

saludos,
Juan Alcalá

Ocultar listas en MOSS

A veces puede resultar útil que los usuarios no puedan ver las listas o bibliotecas disponibles. Para ocultarlas podemos utilizar este sencillo código:

using (SPSite site = new SPSite(
{
using (SPWeb web = site.OpenWeb(Site))
{
web.AllowUnsafeUpdates = true;
foreach (SPList list in web.Lists)
{
list.Hidden = false;
list.Update();
}
}
}

En este ejemplo recorremos todas las listas del Site y las ocultamos. Si necesitaramos ocultar sólamente una tendriamos que especificar su nombre o GUID para identificarla.

Saludos,
Juan Alcalá

18/2/10

Modificar el template de una alerta

Para cambiar una alerta en MOSS lo primero que tenemos que hacer es localizar el fichero que las gestiona. Este fichero se encuentra en la ruta "C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\XML\alerttemplates.xml".

Antes de comenzar con la customización de mis alertas lo más recomendable es hacernos una copia del fichero para poder restaurar en caso de ser necesario.

Una vez hecha la copia ya podemos editar nuestra plantilla. El fichero se divide en varios nodos, dependiendo del tipo de contenido que se quiera controlar. Es por ello que tenemos un template para listas, para bibliotecas, para contactos, para eventos, etc, etc.

Cada nodo se divide a su vez en 2 subsecciones: Digest e Inmediate. Digest nos permitirá modificar la plantilla para las alertas que se lancen a diario o semanalmente. Inmediate servirá para modificar la plantilla de las alertas inmediatas.

Una vez hayamos modificado nuestra plantilla tendremos que actualizarla. Para ello lanzaremos el siguiente comando:

stsadm -o updatealerttemplates -url [URL DEL SITE] -f "C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\XML\alerttemplates.xml" -LCID [IDIOMA: 3082(Español) - 1033(Ingles) - etc, etc]

Para probarlo tan sólo tendremos que realizar algun cambio en la biblioteca que nos hayamos suscrito y esperar a que nos llegue la alerta con el nuevo formato.

Hide 'Site Actions' for some users

If you need to hide the 'Site Actions' dropdown for some users but not all of them (administrators must see this dropdown), you've to edit the master page and add a SPSecurityTrimmedControl that contains your SiteActions control:


SharePoint:SPSecurityTrimmedControl ID="spSecurity" runat="server" PermissionsString="ManageWeb">
SharePoint:SiteActions CONTROL
/
SharePoint:SPSecurityTrimmedControl>

datepicker without original style

If you add a SharePoint:datetimecontrol and you have problems woth the render of this control you've to add a link to the datepicker.css class in the iframe.aspx.
This layout is located in the '/layouts' folder of the MOSS installation.


link rel="stylesheet" type="text/css"href="/_layouts/1033/styles/datepicker.css"/

2/12/09

RequiredFieldValidator in a MOSS datetimecontrol

If you want to control data in MOSS datetime controls yo have to specify the control to validate. The structure is similar to this: [columnName]$[columName]'Date'
You have an example in next lines:

<SharePoint:DateTimeControl ID="fechaDoc" runat="server" AutoPostBack="false" DateOnly="true" LocaleId="3082" />

<asp:RequiredFieldValidator ID="RFVFecha" runat="server" ControlToValidate="fechaDoc$fechaDocDate" ErrorMessage="Controles/Imgs/admiracion.gif' alt='Required Field' />" />

<asp:CompareValidator id="CVFecha" runat="server" ForeColor="Red" ControlToValidate="fechaDoc$fechaDocDate" Type="Date" Operator="DataTypeCheck" ErrorMessage="Controles/Imgs/admiracion.gif' alt='Incorrect Data' />" />

25/5/09

Deleting multiple items from a list

When we try to delete multiple items from a list we'll have this error:

Collection was modified; enumeration operation may not execute.

The problem is because we are updating the item collection. The solution is to use a decrementing 'FOR' loop. Before use it, I filter the items with a SPQuery to finish the FOR loop quickly.

Here is my example:

SPList recursos = properties.OpenWeb().Lists["Recursos"];
SPQuery query = new SPQuery();


string filtro = "";
filtro += "";
filtro += "";
filtro += "";
filtro += properties.ListItemId.ToString();
filtro += "";
filtro += "";

if (!string.IsNullOrEmpty(filtro))
{
query.Query += "";
query.Query += filtro;
query.Query += "";
}

SPListItemCollection coleccion = recursos.GetItems(query);

try
{
for (int i = coleccion.Count - 1; i >= 0; i--)
{
coleccion[i].Delete();
}
}
catch(Exception ex)
{
SPUtility.SendEmail(web, false, false, {email}, ex.Message);
}


24/3/09

Sharepoint Edit in Datasheet locks or freezes IE6

In SharePoint, sometimes generates an error when you try to edit in datasheet view some list. Your browser freezes and you have to close it and re-open the site. If this situation happens you can try to solve this applying this solutions:
In my case, these solutions not solved my problem. If you create your own master page it's probably you've created a foot page. This is a common situation but if put an image bigger than 19px of height you couldn't edit your lists in datasheet view in IE6. Try putting an 19px-of-height image in your master page and the problem will solve.

5/3/09

SkyDrive

Tengo un disco duro virtual (skydrive) donde iré compartiendo documentación, ficheros, etc para que los podais descargar. Para empezar he dejado un ZIP con las 40 plantillas de Sharepoint y un BAT que lanza el deploy de todas.
La dirección es: http://cid-7d78739f3e7ea6ee.skydrive.live.com/browse.aspx/.Public

4/3/09

How to configure de Sharepoint Single Sign-On

Sharee has a interting post about this. I think is very interesting and useful.
http://www.shareesblog.com/?cat=8

3/3/09

Alternate Access Mapping

Sometimes it's possible you need other path for your URLs. For example, if your server name is DEMO_SERVER, all your paths will be called http://demo_server:[port]/....
If you want to change this situation you have to create an alternate access mapping in your Central Administration and afterwards you have 2 options: modify your 'hosts' file (not recommended) and the second option is create a new host in you DNS Server.
In my example I have a virtual machine with de MOSS Server and de DNS Server in the same machine, but it's the same situation.

First of all we edit our Alternate Access Mapping, and add an internal URL:








You must have this new link like this:






Now, you only need to add this new URL in the DNS Server to be recognized by all the machines:






















In this example I've used localhost IP but in a normal situation you have to put your DNS IP.

Now you must have a row like this:




If all has gone well, you have to put the new URL in the browser and confirm the new mapping is working ok:










6/2/09

Unique Constraints in SharePoint Lists or Libraries

Sometimes it's necessary to have an unique column with users, locations, etc. SharePoint don't offer this possibility and you have to develop one if you need this functionality.

Codeplex has created a policy for resolve the problem.
You must install and deploy the UniqueColumnPolicy.wsp file. This feature is deployed as a farm-level feature and should be active when you deploy it. If you need to activate or deactivate the policy, go to Operations>>Manage Farm Features in the Central Administration site.






Once you have applied the policy to the column, if you try to insert a repeated user you must see a message like this:









5/2/09

Redirect to other URL when closing an Infopath Form

When we have a web-browser enabled Infopath form you would have the need to redirect after close this form. In fact this possibility is enabled in the submit button, which redirects you to the original library where form is in. If you want to change this URl you must edit the form and copy the original URL. For example:

https://misharepoint/_layouts/FormServer.aspx
XsnLocation=/FormServerTemplates/nombreFormulario.xsn&
Source=https://misharepoint/Paginas/Default.aspx&DefaultItemOpen=1

You must change the URL of the 'Source' attibute and put the new URL:

https://misharepoint/_layouts/FormServer.aspx XsnLocation=/FormServerTemplates/nombreFormulario.xsn& Source=https://misharepoint/sitio/Paginas/prueba.aspx&DefaultItemOpen=1

&DefaultItemOpen=1 is very important. This attribute allows the form to be opened in a web browser.

CASE A:

One of the problem you can find is that this cheat only works in a same Site Collection.
If you want to put a foreign URL (like http://migueltabera.blogspot.com) you must create and ASPX file (
Redirection.aspx) in the path:

C:\Program Files\Common Files\Microsoft Shared\Web server extensions\12\TEMPLATE\LAYOUTS

and add this code:





After add this code you are enable to put this ASPX direction in the 'Source' attribute of the URL Form

https://misharepoint/_layouts/FormServer.aspx XsnLocation=/FormServerTemplates/nombreFormulario.xsn& Source=https://misharepoint/_layouts/redireccion.aspx&DefaultItemOpen=1


CASE B:

If the form is inside a frame you have to change the ASPX 'redirector' and put this javascript code:









Information extracted from the Miguel Tabera's Blog.

WSS 3.0 templates and MOSS 2007 Templates

WSS 3.0 Site Templates

Team Site: This is the standard site template, with some precreated lists and libraries: Shared Documents, Announcements, Calendar, Links, Tasks, and Team Discussions.
Blank Site: The same type of site as a team site, except that there are no precreated lists or libraries. The only thing displayed on this "blank site" is an image Web Part that shows the WSS logotype.
Document Workspace: This is a special type of site that mostly is used by a team to collaborate on a specific document. Mostly, this type of site is created using the quick menu for a document or directly from within MS Office applications.
Wiki Site: This is a new site template for WSS 3.0; use this template to create sites where users can read and add information in a very informal way. Common uses for wiki sites are capturing brainstorming ideas, building a support center knowledge base, and building a general knowledge base.
Blog: A blog is a site where you share your ideas, comments, and often tips and tricks. Usually, there is a single person who is responsible for a blog site, but it may also be used by teams that want to share information with other users.
Basic Meeting Workspace: This type of site is normally used to capture details and information for a meeting. It contains four precreated lists: Objectives, Attendees, Agenda, and Document Library. This type of site is called a workspace, and it is still a common WSS site. This site is most commonly configured when booking a meeting using Outlook 2003 or 2007, although you can create it manually.
Blank Meeting Workspace: This is similar to the basic meeting workspace, except that it only has one precreated list: Attendees. Use this template when you want to create all lists manually. The Attendees list is special, since it will automatically be populated by all users invited to an Outlook meeting.
Decision Meeting Workspace: This site template contains the following precreated lists: Attendees, Objectives, Agenda, Document Library, Tasks, and Decisions.
Social Meeting Workspace: This template has three pages created by default: Home, Discussion, and Photos. This site template also contains these lists: Attendee, Directions, Things to Bring, Discussion Board, and Picture Library. It also displays an image Web Part. This type of site is often used to discuss social events, such as Christmas parties and Birthday celebrations.
Multipage Meeting Workspace: This site template is very similar to the social meeting workspace, with its three pages. The difference is the number of lists: This template only has Attendees, Objectives and Agenda. Two of the three pages are empty, and you are supposed to add lists to them.

MOSS 2007 Site templates

Collaboration Portal (on the Publishing tab): A site template typically used for creating intranet sites. It also creates a number of subsites, such as a Document Center, a News site, a Reports site, a Search Center, and a Site Directory. This site template is only available when creating a top site (a new site collection).
Publishing Portal (on the Publishing tab): A site for Internet-facing web, or an intranet for a large company. This site only contains one subsite: the Press Releases site. This site is also only available when creating a top site.
But there are more site templates that come with MOSS; most of these are the same as the subsites that are automatically created when selecting the Collaboration Portal site template. They can be used when you need to create more News sites, or Document Centers. These site templates include the following:
Document Center (on the Enterprise tab): A site template typically used for creating a site containing documents available to all users in the organization.
Records Center (on the Enterprise tab): A site template used for creating a site where users can store records. A given Records Manager can use a routing table to control where incoming records are stored. This site contains some special features. For example, once a record is stored, it cannot be changed by the user again.
Site Directory (on the Enterprise tab): A site that lists and categorizes links to other SharePoint sites. You can also use it to create links that will be listed by the Tasks and Tools Web Part.
Report Center (on the Enterprise tab): A site template used for creating sites that contain reports, presentations, key performance indicators (KPI), and dashboards. Typically, it is used for presenting Business Intelligence information.
Search Center with Tabs (on the Enterprise tab): A site used for searching information. This site allows you to create extra tabs beyond the default All Sites and People. You can also customize the search Web Parts and the search result Web Parts on this site.
My Site Host (on the Enterprise tab): This site will typically be used to host personal sites for users, also known as My Sites. Note that this site can only be created once per Shared Service Provider.
Search Center (on the Enterprise tab): This site template is similar to the Search Center with Tabs, except that it does not have tabs.

4/2/09

Force execution of "expiration policy" in MOSS 2007

When you develop actions (or workflows) that should be executed when an expiration policy occurs you need to test them, but Expiration Policy job only is scheduled to run once a day.

You can execute this C# code to force the execution of the job:

using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;

using Microsoft.SharePoint.Administration;

namespace RunExpirationPolicy
{
class Program
{
static void Main(string[] args)
{
foreach (SPService srv in SPFarm.Local.Services)
{
foreach (SPJobDefinition job in srv.JobDefinitions)
{
string jobTitle = job.Title;

if (jobTitle == "Expiration policy")
{
job.Execute(Guid.Empty);
}
}
}
}
}
}

You can use it to force any moss job. You only have to change the name of the job in the IF condition.


15/10/08

Script para controlar CSS en Páginas MOSS

Existe un script que nos permite poder ver qué clase está utilizando cada uno de los componentes de la pagina de SharePoint, facilitando mucho la tarea a aquellos que tengan que crear master pages. El script lo podeis descargar aquí.
Lo tenemos que pegar en un "Web part editor de contenido" y automaticamente nos saldrá un Textbox en la parte superior que irá mostrando las diferentes clases que se utilizan en los controles por los que pasamos el ratón.


Este es el resultado:


















Fuente: SharePoint Redemption