No me hago responsable si copiaste mal algún código que sale en las páginas de este sitio.
Ojalá sea de ayuda para más de alguno este sitio.
Se agradece si deja algún comentario.
Mostrando entradas con la etiqueta Visual Studio 2010. Mostrar todas las entradas
Mostrando entradas con la etiqueta Visual Studio 2010. Mostrar todas las entradas

jueves, 2 de diciembre de 2010

Cómo crear EventHandler para una Biblioteca de Documentos SharePoint con VStudio2010

Ref: http://www.sharepointbriefing.com/spcode/article.php/3872616/Using-the-Event-Handler-in-SharePoint-2010.htm

En este ejemplo se creará un evento ItemAdded para la biblioteca upload, que actualizará el campo Document ID (no nativo, sitecolumn personalizado).

1. Abrir Visual Studio 2010, ejecutar como Administrador.
2. Crear un nuevo proyecto de tipo SharePoint Event Receivers. Indicar la URL del sitio y "Deploy as a farm solution".
3. Seleccionar "List Item Events", luego "Document Library" y finalmente "Item is added". Clic en Finish. Esto creará el código y feature o característica que implementará (deploy) este Event Receiver.
4. Editar el archivo .cs
En mi caso el código era así..


using System;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;
using System.Threading;


namespace ABCDocumentIDEvent.ABCNewDocumentAdded
{
     public class ABCNewDocumentAdded : SPItemEventReceiver
    {
     //Cuando el item de la biblioteca ya ha sido subido a la biblioteca de documento
       public override void ItemAdded(SPItemEventProperties properties)
       {
           //Espera 3 segundos. Sin esto, da un error de código horrible. Seguramente choca con otro evento..
           Thread.Sleep(3000);
           //Deshabilita el gatillador de eventos
           this.EventFiringEnabled = false;
           int cont = 0;
        
           try
           {      SPList listaActual = properties.OpenWeb().Lists[properties.ListId];
                   if(null!=listaActual)
                   {
                       //valida que la biblioteca de documentos sea la "upload"
                       if (properties.ListTitle.ToString() == "upload")
                       {                        
                               using (SPSite mysite = new SPSite(properties.SiteId))
                               {
                                   using (SPWeb myweb = mysite.OpenWeb())
                                   {
                                       if (properties.ListItem.Properties["Document ID"] == null)
                                       {
                                           //tengo una lista personalizada llamada "CounterID" que guarda
                                          //en el item con ID=1 el siguiente ID que se debe asignar al nuevo item.
                                           SPListCollection mylistcol = myweb.Lists;
                                           SPList mylist = mylistcol["CounterID"];
                                           foreach (SPListItem unElemento in mylist.Items)
                                           {
                                               if (unElemento.ID.ToString() == "1")
                                               {
                                                  //toma del campo "Counter" de la lista "CounterID" el valor numérico y
                                                  //asigna a cont.
                                                   cont = Int32.Parse(unElemento["Counter"].ToString());
                                               }
                                           }
                                           //asigna a la columna "Document ID"
                                           properties.ListItem["Document_x0020_ID"] = "ABCDEFG-" + cont.ToString();
                                        
                                           string extension = properties.ListItem["Name"].ToString();
                                           extension = extension.Substring(extension.IndexOf("."));
                                           string name=properties.ListItem["Name"].ToString();
                                           name=name.Substring(0,name.IndexOf("."));
                                           //en forma predeterminada el campo Name guarda el nombre del archivo
                                           //que hemos subido. Acá queremos que el tipo de contenido personalizado
                                           //"Document Name" tenga el valor del campo Name, sin extensión de archivo.                                        
                                           if (extension == ".msg" || properties.ListItem["Document Name"] == null ||
                                           properties.ListItem["Document Name"].ToString()=="")
                                           {
                                               properties.ListItem["Document Name"] = name;
                                           }
                                           //actualiza el item de biblioteca. SystemUpdate(false) es para que no cree
                                           //una versión para este update.
                                           properties.ListItem.SystemUpdate(false);
                                           if (properties.ListItem.Properties["Document ID"] != null)
                                           {
                                               foreach (SPListItem unElemento in mylist.Items)
                                               {  //incrementa en 1 el valor del campo "Counter" de la lista "CounterID"
                                                   if (unElemento.ID.ToString() == "1")
                                                   {
                                                       unElemento["Counter"] = cont + 1;
                                                       unElemento.Update();
                                                   }
                                               }
                                           }

                                       }


                                   }
                               }
                        
                       }
                   } //habilita nuevamente gatillador de eventos.
                   this.EventFiringEnabled = true;
               }
           catch (Exception)
           {
           }
       } 
    }
}


5. Presionar F5 o Build y Deploy. Y eso es todo. Estará en la sección "manage site features" o "site collection features" dependiendo de si colocamos "Web" o "Site" en el diseñador del Feature.
En este caso era Web:


Así que para desactivarlo.. desde acá: Site Actions>Site Settings>Manage site features.

Más info: http://experionsharepointsolutions.blogspot.com/

Cómo cambiar el sitio SharePoint en Visual Studio 2010

Ref: http://davidfrette.wordpress.com/2010/03/04/changing-the-sharepoint-site-in-a-visual-studio-2010-sharepoint-2010-project/


Changing the SharePoint Site in a Visual Studio 2010 / SharePoint 2010 project

Posted by David Frette on March 4, 2010
I created a new Visual Studio project and entered in the url of a site that simply didn’t exist. Whoops! I didn’t want to create a new site for just this project, so I wanted to change the URL that Visual Studio 2010 uses to deploy this SharePoint solution.
It’s not located in the project file itself. It’s located in the user config file of the project.
Here is the file:
Once this file is open, you can change the url, save the file, and close it out.
Old setting:
New setting:
After editing this file, you’ll have to reload your project.
It’s not completely obvious where this setting is, but once you’ve done it, you’ll remember that the key is the user configuration file.