Esempio n. 1
0
        internal static WebPart GetSourceWebPart(string url, string webPartTitle, string webPartId, out string zone)
        {
            using (SPSite site = new SPSite(url))
                using (SPWeb web = site.OpenWeb()) // The url contains a filename so AllWebs[] will not work unless we want to try and parse which we don't
                {
                    bool cleanupContext = false;
                    try
                    {
                        if (HttpContext.Current == null)
                        {
                            cleanupContext = true;
                            HttpRequest httpRequest = new HttpRequest("", web.Url, "");
                            HttpContext.Current = new HttpContext(httpRequest, new HttpResponse(new StringWriter()));
                            SPControl.SetContextWeb(HttpContext.Current, web);
                        }
                        SPLimitedWebPartManager manager = null;
                        try
                        {
                            WebPart webPart = null;
                            if (!string.IsNullOrEmpty(webPartTitle))
                            {
                                webPart = Utilities.GetWebPartByTitle(web, url, webPartTitle, out manager);
                            }
                            else if (!string.IsNullOrEmpty(webPartId))
                            {
                                webPart = Utilities.GetWebPartById(web, url, webPartId, out manager);
                            }

                            if (manager != null)
                            {
                                zone = manager.GetZoneID(webPart);
                            }
                            else
                            {
                                zone = null;
                            }
                            return(webPart);
                        }
                        finally
                        {
                            if (manager != null)
                            {
                                manager.Web.Dispose();
                                manager.Dispose();
                            }
                        }
                    }
                    finally
                    {
                        if (HttpContext.Current != null && cleanupContext)
                        {
                            HttpContext.Current = null;
                        }
                    }
                }
        }
        public bool Insertar(PasantiasPreProfesionales item, out int?id)
        {
            bool   result = false;
            int?   auxId  = 0;
            string strUrl = Properties.UdlaListDefinitions.Default.Url_Sitio;

            try
            {
                if (SPContext.Current != null)
                {
                    HttpContext.Current = null;
                }
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite oSite = new SPSite(strUrl))
                    {
                        using (SPWeb oWeb = oSite.OpenWeb())
                        {
                            HttpRequest httpRequest = new HttpRequest("", oWeb.Url, "");
                            HttpContext.Current     = new HttpContext(httpRequest, new HttpResponse(new System.IO.StringWriter()));
                            SPControl.SetContextWeb(HttpContext.Current, oWeb);
                            using (UdlaEntityDataContext context = new UdlaEntityDataContext(oWeb.Url))
                            {
                                EntityList <ListaPasantiasElemento> pasantias = context.GetList <ListaPasantiasElemento>(Properties.UdlaListDefinitions.Default.Lista_Pasantias);
                                var itemBase = MappeoMoss(item);
                                pasantias.InsertOnSubmit(itemBase);
                                context.SubmitChanges();
                                itemBase.Accion = string.Format(itemBase.Accion, itemBase.Identificador);
                                itemBase.Título = string.Format(itemBase.Título, itemBase.Identificador);
                                context.SubmitChanges();

                                auxId  = itemBase.Identificador;
                                result = true;
                            }
                        }
                    }
                }
                                                     );
            }
            catch (Exception ex)
            {
                auxId = 0;
                Logger.ExLogger(ex);
                throw ex;
            }
            id = auxId;
            return(result);
        }
        public bool Insertar(Actividades item, out int?id)
        {
            bool   result = false;
            int?   auxId  = 0;
            string strUrl = Properties.UdlaListDefinitions.Default.Url_Sitio;

            try
            {
                if (SPContext.Current != null)
                {
                    HttpContext.Current = null;
                }
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite oSite = new SPSite(strUrl))
                    {
                        using (SPWeb oWeb = oSite.OpenWeb())
                        {
                            HttpRequest httpRequest = new HttpRequest("", oWeb.Url, "");
                            HttpContext.Current     = new HttpContext(httpRequest, new HttpResponse(new System.IO.StringWriter()));
                            SPControl.SetContextWeb(HttpContext.Current, oWeb);
                            using (UdlaEntityDataContext context = new UdlaEntityDataContext(oWeb.Url))

                            {
                                EntityList <ListaDeActividadesPorEstudianteElemento> actividades = context.GetList <ListaDeActividadesPorEstudianteElemento>(Properties.UdlaListDefinitions.Default.Lista_Actividades);
                                var itemBase           = MappeoMoss(item);
                                itemBase.Identificador = null;
                                itemBase.IdPasantia    = context.ListaPasantias.Where(x => x.Identificador == item.idPasantia).Take(1).ToList().First();
                                actividades.InsertOnSubmit(itemBase);
                                context.SubmitChanges();
                                auxId  = itemBase.Identificador;
                                result = true;
                            }
                        }
                    }
                }
                                                     );
            }
            catch (Exception ex)
            {
                auxId = 0;
                Logger.ExLogger(ex);
                throw ex;
            }
            id = auxId;
            return(result);
        }
        public PasantiasPreProfesionales Actualizar(PasantiasPreProfesionales item)
        {
            string strUrl = Properties.UdlaListDefinitions.Default.Url_Sitio;
            ListaPasantiasElemento    pasantiasBase = null;
            PasantiasPreProfesionales pasantiaFinal = null;
            HttpContext backupCtxt = HttpContext.Current;

            try
            {
                if (SPContext.Current != null)
                {
                    HttpContext.Current = null;
                }
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite oSite = new SPSite(strUrl))
                    {
                        using (SPWeb oWeb = oSite.OpenWeb())
                        {
                            HttpRequest httpRequest = new HttpRequest("", oWeb.Url, "");
                            HttpContext.Current     = new HttpContext(httpRequest, new HttpResponse(new System.IO.StringWriter()));
                            SPControl.SetContextWeb(HttpContext.Current, oWeb);
                            using (UdlaEntityDataContext context = new UdlaEntityDataContext(oWeb.Url))
                            {
                                EntityList <ListaPasantiasElemento> pasantias = context.GetList <ListaPasantiasElemento>(Properties.UdlaListDefinitions.Default.Lista_Pasantias);
                                pasantiasBase = pasantias.Where(x => x.Identificador == item.Id).Take(1).ToList().First();;
                                if (pasantiasBase != null)
                                {
                                    pasantiasBase = MappeoMoss(item, pasantiasBase);
                                    context.SubmitChanges();
                                    pasantiaFinal = MappeoMoss(pasantiasBase);
                                }
                            }
                        }
                    }
                }
                                                     );
            }
            catch (Exception ex)
            {
                Logger.ExLogger(ex);
                throw ex;
            }
            return(pasantiaFinal);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="id"></param>
        /// <param name="estado"></param>
        /// <param name="esSeleccionado"></param>
        /// <returns></returns>
        public bool CambiarEstadoSeleccionadoAlumnoDocente(int id, string estado, bool esSeleccionado)
        {
            string      strUrl     = Properties.UdlaListDefinitions.Default.Url_Sitio;
            bool        val        = false;
            HttpContext backupCtxt = HttpContext.Current;

            try
            {
                if (SPContext.Current != null)
                {
                    HttpContext.Current = null;
                }
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite oSite = new SPSite(strUrl))
                    {
                        using (SPWeb oWeb = oSite.OpenWeb())
                        {
                            HttpRequest httpRequest = new HttpRequest("", oWeb.Url, "");
                            HttpContext.Current     = new HttpContext(httpRequest, new HttpResponse(new System.IO.StringWriter()));
                            SPControl.SetContextWeb(HttpContext.Current, oWeb);
                            using (UdlaEntityDataContext context = new UdlaEntityDataContext(oWeb.Url))
                            {
                                var pasantiasBase = context.ListaPasantias.Where(x => x.Identificador == id).Take(1).ToList().First();;
                                if (pasantiasBase != null)
                                {
                                    pasantiasBase.EsSeleccionadoPorDocente = esSeleccionado;
                                    pasantiasBase.EsSeleccionado           = esSeleccionado;
                                    pasantiasBase.Estado = estado;
                                    context.SubmitChanges();
                                    val = true;
                                }
                            }
                        }
                    }
                }
                                                     );
            }
            catch (Exception ex)
            {
                Logger.ExLogger(ex);
                throw ex;
            }
            return(val);
        }
Esempio n. 6
0
        public Visitas Actualizar(Visitas item)
        {
            Visitas visita = null;
            string  strUrl = Properties.UdlaListDefinitions.Default.Url_Sitio;

            try
            {
                if (SPContext.Current != null)
                {
                    HttpContext.Current = null;
                }
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite oSite = new SPSite(strUrl))
                    {
                        using (SPWeb oWeb = oSite.OpenWeb())
                        {
                            HttpRequest httpRequest = new HttpRequest("", oWeb.Url, "");
                            HttpContext.Current     = new HttpContext(httpRequest, new HttpResponse(new System.IO.StringWriter()));
                            SPControl.SetContextWeb(HttpContext.Current, oWeb);
                            using (UdlaEntityDataContext context = new UdlaEntityDataContext(oWeb.Url))
                            {
                                EntityList <ListaVisitasElemento> visitas = context.GetList <ListaVisitasElemento>(Properties.UdlaListDefinitions.Default.Lista_Visitas);
                                var visitaBase = visitas.Where(x => x.Identificador == item.Id).Take(1).ToList().First();;
                                if (visitaBase != null)
                                {
                                    visitaBase = MappeoMoss(item, visitaBase);
                                    context.SubmitChanges();
                                    visita = MappeoMoss(visitaBase);
                                }
                            }
                        }
                    }
                }
                                                     );
            }
            catch (Exception ex)
            {
                Logger.ExLogger(ex);
                throw ex;
            }
            return(visita);
        }
        /// <summary>
        /// Adds the web part.
        /// </summary>
        /// <param name="file">The page.</param>
        /// <param name="webPartXml">The web part XML file.</param>
        /// <param name="webPartTitle">The web part title.</param>
        /// <param name="zone">The zone.</param>
        /// <param name="zoneId">The zone id.</param>
        /// <param name="deleteWebPart">if set to <c>true</c> [delete web part].</param>
        /// <param name="customReplaceText">The custom replace text.</param>
        /// <param name="chromeType">Type of the chrome.</param>
        /// <param name="publish">if set to <c>true</c> [publish].</param>
        /// <returns></returns>
        public WebPart AddWebPart(SPFile file, string webPartXml, string assembly, string typeName, string webPartTitle, string zone, int zoneId, bool deleteWebPart, Hashtable customReplaceText, PartChromeType chromeType, bool publish)
        {
            bool cleanupContext = false;
            bool checkBackIn    = false;

            if (file.InDocumentLibrary)
            {
                if (!Utilities.IsCheckedOut(file.Item) || !Utilities.IsCheckedOutByCurrentUser(file.Item))
                {
                    checkBackIn = true;
                    file.CheckOut();
                }
                // If it's checked out by another user then this will throw an informative exception so let it do so.
            }

            if (HttpContext.Current == null)
            {
                cleanupContext = true;
                HttpRequest httpRequest = new HttpRequest("", file.Item.ParentList.ParentWeb.Url, "");
                HttpContext.Current = new HttpContext(httpRequest, new HttpResponse(new StringWriter()));
                SPControl.SetContextWeb(HttpContext.Current, file.Item.ParentList.ParentWeb);
            }

            string url = file.Item.ParentList.ParentWeb.Site.MakeFullUrl(file.ServerRelativeUrl);

            using (SPLimitedWebPartManager manager = file.Item.ParentList.ParentWeb.GetLimitedWebPartManager(url, PersonalizationScope.Shared))
            {
                try
                {
                    WebPart wp;
                    if (!string.IsNullOrEmpty(webPartXml))
                    {
                        wp = AddWebPart(manager, file, webPartXml, customReplaceText);
                    }
                    else
                    {
                        wp = AddWebPart(assembly, typeName);
                    }

                    if (!string.IsNullOrEmpty(webPartTitle))
                    {
                        wp.Title = webPartTitle;
                    }
                    webPartTitle  = wp.Title;
                    wp.ChromeType = chromeType;

                    // Delete existing web part with same title so that we only have the latest version on the page
                    foreach (WebPart wpTemp in manager.WebParts)
                    {
                        try
                        {
                            if (wpTemp.Title == wp.Title)
                            {
                                if (deleteWebPart)
                                {
                                    manager.DeleteWebPart(wpTemp);
                                    break;
                                }
                                else
                                {
                                    continue;
                                }
                            }
                        }
                        finally
                        {
                            wpTemp.Dispose();
                        }
                    }

                    try
                    {
                        manager.AddWebPart(wp, zone, zoneId);
                    }
                    catch (Exception)
                    {
                        System.Net.ServicePointManager.ServerCertificateValidationCallback += delegate { return(true); };

                        // We've not already added the web part so use the web service to do this.
                        using (WebPartPagesWebService.WebPartPagesWebService svc = new WebPartPagesWebService.WebPartPagesWebService())
                        {
                            // We failed adding via the OM so try the web service as a fall back.
                            svc.Url         = manager.Web.Url + "/_vti_bin/WebPartPages.asmx";
                            svc.Credentials = System.Net.CredentialCache.DefaultCredentials;

                            try
                            {
                                // Add the web part to the web service.  We use a web service because many
                                // web parts require the SPContext.Current variables to be set which are
                                // not set when run from a command line.
                                StringBuilder sb        = new StringBuilder();
                                XmlTextWriter xmlWriter = new XmlTextWriter(new StringWriter(sb));
                                xmlWriter.Formatting = Formatting.Indented;
                                manager.ExportWebPart(wp, xmlWriter);
                                xmlWriter.Flush();

                                svc.AddWebPartToZone(url, sb.ToString(), WebPartPagesWebService.Storage.Shared, zone, zoneId);
                            }
                            catch (System.Web.Services.Protocols.SoapException ex)
                            {
                                throw new Exception(ex.Detail.OuterXml);
                            }
                        }
                    }
                    return(wp);
                }
                finally
                {
                    if (cleanupContext)
                    {
                        HttpContext.Current = null;
                    }
                    if (manager != null)
                    {
                        manager.Web.Dispose();
                        manager.Dispose();
                    }

                    if (file.InDocumentLibrary && Utilities.IsCheckedOut(file.Item) && (checkBackIn || publish))
                    {
                        file.CheckIn("Checking in changes to page due to new web part being added: " + webPartTitle);
                    }

                    if (publish && file.InDocumentLibrary && file.Item.ParentList.EnableMinorVersions)
                    {
                        try
                        {
                            file.Publish("Publishing changes to page due to new web part being added: " + webPartTitle);
                            if (file.Item.ModerationInformation != null)
                            {
                                file.Approve("Approving changes to page due to new web part being added: " + webPartTitle);
                            }
                        }
                        catch (Exception ex)
                        {
                            WriteWarning("Unable to publish or approve file: " + ex.Message);
                        }
                    }
                }
            }
        }
Esempio n. 8
0
        internal static void SetWebPart(string url, SetWebPartStateAction action, string webPartId, string webPartTitle, string webPartZone, string webPartZoneIndex, Hashtable props, bool publish)
        {
            using (SPSite site = new SPSite(url))
                using (SPWeb web = site.OpenWeb()) // The url contains a filename so AllWebs[] will not work unless we want to try and parse which we don't
                {
                    bool cleanupContext = false;
                    try
                    {
                        if (HttpContext.Current == null)
                        {
                            cleanupContext = true;
                            HttpRequest httpRequest = new HttpRequest("", web.Url, "");
                            HttpContext.Current = new HttpContext(httpRequest, new HttpResponse(new StringWriter()));
                            SPControl.SetContextWeb(HttpContext.Current, web);
                        }


                        SPFile file = web.GetFile(url);

                        // file.Item will throw "The object specified does not belong to a list." if the url passed
                        // does not correspond to a file in a list.

                        bool checkIn = false;
                        if (file.InDocumentLibrary)
                        {
                            if (!Utilities.IsCheckedOut(file.Item) || !Utilities.IsCheckedOutByCurrentUser(file.Item))
                            {
                                file.CheckOut();
                                checkIn = true;
                                // If it's checked out by another user then this will throw an informative exception so let it do so.
                            }
                        }

                        string  displayTitle            = string.Empty;
                        WebPart wp                      = null;
                        SPLimitedWebPartManager manager = null;
                        try
                        {
                            if (!string.IsNullOrEmpty(webPartId))
                            {
                                wp = Utilities.GetWebPartById(web, url, webPartId, out manager);
                            }
                            else
                            {
                                wp = Utilities.GetWebPartByTitle(web, url, webPartTitle, out manager);
                                if (wp == null)
                                {
                                    throw new SPException(
                                              "Unable to find specified web part using title \"" + webPartTitle + "\". Try specifying the -id parameter instead (use Get-SPWebPartList to get the ID)");
                                }
                            }

                            if (wp == null)
                            {
                                throw new SPException("Unable to find specified web part.");
                            }

                            // Set this so that we can add it to the check-in comment.
                            displayTitle = wp.DisplayTitle;

                            if (action == SetWebPartStateAction.Delete)
                            {
                                manager.DeleteWebPart(wp);
                            }
                            else if (action == SetWebPartStateAction.Close)
                            {
                                manager.CloseWebPart(wp);
                            }
                            else if (action == SetWebPartStateAction.Open)
                            {
                                manager.OpenWebPart(wp);
                            }


                            if (action != SetWebPartStateAction.Delete)
                            {
                                string zoneID    = manager.GetZoneID(wp);
                                int    zoneIndex = wp.ZoneIndex;

                                if (!string.IsNullOrEmpty(webPartZone))
                                {
                                    zoneID = webPartZone;
                                }
                                if (!string.IsNullOrEmpty(webPartZoneIndex))
                                {
                                    zoneIndex = int.Parse(webPartZoneIndex);
                                }

                                manager.MoveWebPart(wp, zoneID, zoneIndex);

                                if (props != null && props.Count > 0)
                                {
                                    SetWebPartProperties(wp, props);
                                }
                                manager.SaveChanges(wp);
                            }
                        }
                        finally
                        {
                            if (manager != null)
                            {
                                manager.Web.Dispose();
                                manager.Dispose();
                            }
                            if (wp != null)
                            {
                                wp.Dispose();
                            }

                            if (checkIn)
                            {
                                file.CheckIn("Checking in changes to page due to state change of web part " + displayTitle);
                            }
                            if (publish && file.InDocumentLibrary)
                            {
                                PublishItems pi = new PublishItems();
                                pi.PublishListItem(file.Item, file.Item.ParentList, false, "Set-SPWebPart", "Checking in changes to page due to state change of web part " + displayTitle, null);
                            }
                        }
                    }
                    finally
                    {
                        if (HttpContext.Current != null && cleanupContext)
                        {
                            HttpContext.Current = null;
                        }
                    }
                }
        }
        public static void Retarget(string url, bool allMatching, string webPartId, string webPartTitle, string listUrl, string listType, string siteUrl, bool publish)
        {
            using (SPSite site = new SPSite(url))
                using (SPWeb web = site.OpenWeb()) // The url contains a filename so AllWebs[] will not work unless we want to try and parse which we don't
                {
                    SPFile file = web.GetFile(url);

                    // file.Item will throw "The object specified does not belong to a list." if the url passed
                    // does not correspond to a file in a list.

                    bool wasCheckedOut = true;
                    if (file.CheckOutStatus == SPFile.SPCheckOutStatus.None)
                    {
                        file.CheckOut();
                        wasCheckedOut = false;
                    }
                    else if (!Utilities.IsCheckedOutByCurrentUser(file.Item))
                    {
                        // We don't want to mess with files that are checked out to other users so exit out.
                        throw new SPException("The file is currently checked out by another user.");
                    }

                    string displayTitle             = string.Empty;
                    bool   modified                 = false;
                    SPLimitedWebPartManager manager = null;
                    try
                    {
                        if (!allMatching)
                        {
                            bool cleanupContext = false;
                            if (HttpContext.Current == null)
                            {
                                HttpRequest request = new HttpRequest("", web.Url, "");
                                HttpContext.Current = new HttpContext(request, new HttpResponse(new StringWriter()));
                                SPControl.SetContextWeb(HttpContext.Current, web);
                                cleanupContext = true;
                            }

                            WebPart wp = null;
                            try
                            {
                                if (!string.IsNullOrEmpty(webPartId))
                                {
                                    wp = Utilities.GetWebPartById(web, url, webPartId, out manager);
                                }
                                else
                                {
                                    wp = Utilities.GetWebPartByTitle(web, url, webPartTitle, out manager);
                                    if (wp == null)
                                    {
                                        throw new SPException(
                                                  "Unable to find specified web part. Try specifying the -ID parameter instead (use enumpagewebparts to get the ID) or use -AllMatching to adjust all web parts that match the specified title.");
                                    }
                                }
                                if (wp == null)
                                {
                                    throw new SPException("Unable to find specified web part.");
                                }

                                AdjustWebPart(web, wp, manager, listUrl, listType, siteUrl);
                                modified = true;

                                // Set this so that we can add it to the check-in comment.
                                displayTitle = wp.DisplayTitle;
                            }
                            finally
                            {
                                if (cleanupContext)
                                {
                                    HttpContext.Current = null;
                                }

                                if (wp != null)
                                {
                                    wp.Dispose();
                                }
                            }
                        }
                        else
                        {
                            manager = web.GetLimitedWebPartManager(url, PersonalizationScope.Shared);
                            foreach (WebPart tempWP in manager.WebParts)
                            {
                                try
                                {
                                    if (!(tempWP is ContentByQueryWebPart))
                                    {
                                        continue;
                                    }

                                    if (tempWP.DisplayTitle.ToLowerInvariant() == webPartTitle.ToLowerInvariant())
                                    {
                                        AdjustWebPart(web, tempWP, manager, listUrl, listType, siteUrl);
                                        displayTitle = tempWP.DisplayTitle;
                                        modified     = true;
                                    }
                                }
                                finally
                                {
                                    tempWP.Dispose();
                                }
                            }
                        }
                    }
                    finally
                    {
                        if (manager != null)
                        {
                            manager.Web.Dispose(); // manager.Dispose() does not dispose of the SPWeb object and results in a memory leak.
                            manager.Dispose();
                        }

                        if (modified)
                        {
                            file.CheckIn("Checking in changes to page layout due to retargeting of content query web part " + displayTitle);
                        }
                        else if (!wasCheckedOut)
                        {
                            file.UndoCheckOut();
                        }

                        if (modified && publish)
                        {
                            file.Publish("Publishing changes to page layout due to retargeting of content query web part " + displayTitle);
                            if (file.Item.ModerationInformation != null)
                            {
                                file.Approve("Approving changes to page layout due to retargeting of content query web part " + displayTitle);
                            }
                        }
                    }
                }
        }
Esempio n. 10
0
        internal static void SetWebPart(string url, Type oldType, Type newType, string title, Hashtable properties, bool publish, bool test)
        {
            using (SPSite site = new SPSite(url))
                using (SPWeb web = site.OpenWeb()) // The url contains a filename so AllWebs[] will not work unless we want to try and parse which we don't
                {
                    bool cleanupContext = false;
                    try
                    {
                        if (HttpContext.Current == null)
                        {
                            cleanupContext = true;
                            HttpRequest httpRequest = new HttpRequest("", web.Url, "");
                            HttpContext.Current = new HttpContext(httpRequest, new HttpResponse(new StringWriter()));
                            SPControl.SetContextWeb(HttpContext.Current, web);
                        }


                        SPFile file = web.GetFile(url);

                        // file.Item will throw "The object specified does not belong to a list." if the url passed
                        // does not correspond to a file in a list.

                        bool checkIn = false;
                        if (file.InDocumentLibrary && !test)
                        {
                            if (!Utilities.IsCheckedOut(file.Item) || !Utilities.IsCheckedOutByCurrentUser(file.Item))
                            {
                                file.CheckOut();
                                checkIn = true;
                                // If it's checked out by another user then this will throw an informative exception so let it do so.
                            }
                        }

                        SPLimitedWebPartManager manager = null;
                        try
                        {
                            List <WebPart> webParts = Utilities.GetWebPartsByType(web, url, oldType, out manager);
                            foreach (var oldWebPart in webParts)
                            {
                                if (oldWebPart.IsClosed)
                                {
                                    continue;
                                }

                                string wpTitle = oldWebPart.Title;
                                if (string.IsNullOrEmpty(wpTitle))
                                {
                                    wpTitle = oldWebPart.DisplayTitle;
                                }

                                if (!string.IsNullOrEmpty(title) &&
                                    (oldWebPart.DisplayTitle.ToLowerInvariant() != title.ToLowerInvariant() &&
                                     oldWebPart.Title.ToLowerInvariant() != title.ToLowerInvariant()))
                                {
                                    continue;
                                }
                                Logger.Write("Replacing web part \"{0}\"...", wpTitle);
                                string  zone       = manager.GetZoneID(oldWebPart);
                                WebPart newWebPart = (WebPart)Activator.CreateInstance(newType);
                                if (SetProperties(oldWebPart, newWebPart, properties))
                                {
                                    Logger.WriteWarning("An error was encountered setting web part properties so try one more time in case the error is the result of a sequencing issue.");
                                    if (SetProperties(oldWebPart, newWebPart, properties))
                                    {
                                        Logger.WriteWarning("Unable to set all properties for web part.");
                                    }
                                }
                                if (!test)
                                {
                                    manager.DeleteWebPart(oldWebPart);
                                }

                                try
                                {
                                    if (!test)
                                    {
                                        manager.AddWebPart(newWebPart, zone, oldWebPart.ZoneIndex);
                                    }
                                }
                                catch (Exception)
                                {
                                    ServicePointManager.ServerCertificateValidationCallback += delegate { return(true); };

                                    // We've not already added the web part so use the web service to do this.
                                    using (WebPartPagesWebService.WebPartPagesWebService svc = new WebPartPagesWebService.WebPartPagesWebService())
                                    {
                                        // We failed adding via the OM so try the web service as a fall back.
                                        svc.Url         = manager.Web.Url + "/_vti_bin/WebPartPages.asmx";
                                        svc.Credentials = CredentialCache.DefaultCredentials;

                                        try
                                        {
                                            // Add the web part to the web service.  We use a web service because many
                                            // web parts require the SPContext.Current variables to be set which are
                                            // not set when run from a command line.
                                            StringBuilder sb        = new StringBuilder();
                                            XmlTextWriter xmlWriter = new XmlTextWriter(new StringWriter(sb));
                                            xmlWriter.Formatting = Formatting.Indented;
                                            manager.ExportWebPart(newWebPart, xmlWriter);
                                            xmlWriter.Flush();

                                            svc.AddWebPartToZone(url, sb.ToString(), Storage.Shared, zone, oldWebPart.ZoneIndex);
                                        }
                                        catch (SoapException ex)
                                        {
                                            throw new Exception(ex.Detail.OuterXml);
                                        }
                                    }
                                }
                                finally
                                {
                                    oldWebPart.Dispose();
                                    newWebPart.Dispose();
                                }
                                if (zone == "wpz" && file.InDocumentLibrary)
                                {
                                    foreach (SPField field in file.Item.Fields)
                                    {
                                        if (!field.ReadOnlyField && field is SPFieldMultiLineText && ((SPFieldMultiLineText)field).WikiLinking && file.Item[field.Id] != null)
                                        {
                                            string content = file.Item[field.Id].ToString();
                                            if (content.Contains(oldWebPart.ID.Replace("_", "-").Substring(2)))
                                            {
                                                Logger.Write("Replacing web part identifier in text field \"{0}\"...", field.InternalName);
                                                if (!test)
                                                {
                                                    file.Item[field.Id] = content.Replace(oldWebPart.ID.Replace("_", "-").Substring(2), newWebPart.ID.Replace("_", "-").Substring(2));
                                                    file.Item.SystemUpdate();
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        finally
                        {
                            if (manager != null)
                            {
                                manager.Web.Dispose();
                                manager.Dispose();
                            }

                            if (!test)
                            {
                                if (checkIn)
                                {
                                    file.CheckIn("Checking in changes to page due to web part being replaced with a different type.");
                                }
                                if (publish && file.InDocumentLibrary)
                                {
                                    PublishItems pi = new PublishItems();
                                    pi.PublishListItem(file.Item, file.Item.ParentList, false, "Replace-SPWebPartType", "Checking in changes to page due to web part being replaced with a different type.", null);
                                }
                            }
                        }
                    }
                    finally
                    {
                        if (HttpContext.Current != null && cleanupContext)
                        {
                            HttpContext.Current = null;
                        }
                    }
                }
        }
Esempio n. 11
0
        internal static void SetWebPart(WebPart sourceWebPart, string targetUrl, string zone, int?zoneIndex, bool publish, bool test)
        {
            if (sourceWebPart.IsClosed)
            {
                sourceWebPart.Dispose();
                throw new Exception("The source web part is closed and cannot be copied.");
            }

            int zoneIndex1 = sourceWebPart.ZoneIndex;

            if (zoneIndex.HasValue)
            {
                zoneIndex1 = zoneIndex.Value;
            }
            Guid   storageKey = Guid.NewGuid();
            string id         = StorageKeyToID(storageKey);

            using (SPSite site = new SPSite(targetUrl))
                using (SPWeb web = site.OpenWeb()) // The url contains a filename so AllWebs[] will not work unless we want to try and parse which we don't
                {
                    bool cleanupContext = false;
                    try
                    {
                        if (HttpContext.Current == null)
                        {
                            cleanupContext = true;
                            HttpRequest httpRequest = new HttpRequest("", web.Url, "");
                            HttpContext.Current = new HttpContext(httpRequest, new HttpResponse(new StringWriter()));
                            SPControl.SetContextWeb(HttpContext.Current, web);
                        }


                        SPFile file = web.GetFile(targetUrl);

                        // file.Item will throw "The object specified does not belong to a list." if the url passed
                        // does not correspond to a file in a list.

                        bool checkIn = false;
                        if (file.InDocumentLibrary && !test)
                        {
                            if (!Utilities.IsCheckedOut(file.Item) || !Utilities.IsCheckedOutByCurrentUser(file.Item))
                            {
                                file.CheckOut();
                                checkIn = true;
                                // If it's checked out by another user then this will throw an informative exception so let it do so.
                            }
                        }

                        SPLimitedWebPartManager manager = file.GetLimitedWebPartManager(PersonalizationScope.Shared);
                        try
                        {
                            string wpTitle = sourceWebPart.Title;
                            if (string.IsNullOrEmpty(wpTitle))
                            {
                                wpTitle = sourceWebPart.DisplayTitle;
                            }

                            Logger.Write("Copying web part \"{0}\"...", wpTitle);
                            WebPart newWebPart = (WebPart)Activator.CreateInstance(sourceWebPart.GetType());
                            if (SPCmdletReplaceWebPartType.SetProperties(sourceWebPart, newWebPart, null))
                            {
                                Logger.WriteWarning("An error was encountered setting web part properties so try one more time in case the error is the result of a sequencing issue.");
                                if (SPCmdletReplaceWebPartType.SetProperties(sourceWebPart, newWebPart, null))
                                {
                                    Logger.WriteWarning("Unable to set all properties for web part.");
                                }
                            }

                            try
                            {
                                if (!test)
                                {
                                    newWebPart.ID = id;

                                    manager.AddWebPart(newWebPart, zone, zoneIndex1);
                                }
                            }
                            catch (Exception)
                            {
                                ServicePointManager.ServerCertificateValidationCallback += delegate { return(true); };

                                // We've not already added the web part so use the web service to do this.
                                using (WebPartPagesWebService.WebPartPagesWebService svc = new WebPartPagesWebService.WebPartPagesWebService())
                                {
                                    // We failed adding via the OM so try the web service as a fall back.
                                    svc.Url         = manager.Web.Url + "/_vti_bin/WebPartPages.asmx";
                                    svc.Credentials = CredentialCache.DefaultCredentials;

                                    try
                                    {
                                        // Add the web part to the web service.  We use a web service because many
                                        // web parts require the SPContext.Current variables to be set which are
                                        // not set when run from a command line.
                                        StringBuilder sb        = new StringBuilder();
                                        XmlTextWriter xmlWriter = new XmlTextWriter(new StringWriter(sb));
                                        xmlWriter.Formatting = Formatting.Indented;
                                        manager.ExportWebPart(newWebPart, xmlWriter);
                                        xmlWriter.Flush();

                                        svc.AddWebPartToZone(targetUrl, sb.ToString(), Storage.Shared, zone, zoneIndex1);
                                    }
                                    catch (SoapException ex)
                                    {
                                        throw new Exception(ex.Detail.OuterXml);
                                    }
                                }
                            }
                            finally
                            {
                                sourceWebPart.Dispose();
                                newWebPart.Dispose();
                            }
                            if (zone == "wpz" && file.InDocumentLibrary)
                            {
                                foreach (SPField field in file.Item.Fields)
                                {
                                    if (!field.ReadOnlyField && field is SPFieldMultiLineText && ((SPFieldMultiLineText)field).WikiLinking)
                                    {
                                        string content = null;
                                        if (file.Item[field.Id] != null)
                                        {
                                            content = file.Item[field.Id].ToString();
                                        }

                                        string div = string.Format(CultureInfo.InvariantCulture, "<div class=\"ms-rtestate-read ms-rte-wpbox\" contentEditable=\"false\"><div class=\"ms-rtestate-read {0}\" id=\"div_{0}\"></div><div style='display:none' id=\"vid_{0}\"/></div>", new object[] { storageKey.ToString("D") });
                                        content += div;
                                        Logger.Write("Adding web part to text field \"{0}\"...", field.InternalName);
                                        if (!test)
                                        {
                                            file.Item[field.Id] = content;
                                            file.Item.SystemUpdate();
                                        }
                                    }
                                }
                            }
                        }
                        finally
                        {
                            if (manager != null)
                            {
                                manager.Web.Dispose();
                                manager.Dispose();
                            }

                            if (!test)
                            {
                                if (checkIn)
                                {
                                    file.CheckIn("Checking in changes to page due to web part being replaced with a different type.");
                                }
                                if (publish && file.InDocumentLibrary)
                                {
                                    PublishItems pi = new PublishItems();
                                    pi.PublishListItem(file.Item, file.Item.ParentList, false, "Copy-SPWebPart", "Checking in changes to page due to web part being copied from another page.", null);
                                }
                            }
                        }
                    }
                    finally
                    {
                        if (HttpContext.Current != null && cleanupContext)
                        {
                            HttpContext.Current = null;
                        }
                    }
                }
        }
Esempio n. 12
0
        internal static string GetWebPartXml(string pageUrl, bool simple)
        {
            using (SPSite site = new SPSite(pageUrl))
                using (SPWeb web = site.OpenWeb()) // The url contains a filename so AllWebs[] will not work unless we want to try and parse which we don't
                {
                    SPLimitedWebPartManager webPartMngr = null;
                    bool cleanupContext = false;
                    try
                    {
                        if (HttpContext.Current == null)
                        {
                            cleanupContext = true;
                            HttpRequest httpRequest = new HttpRequest("", web.Url, "");
                            HttpContext.Current = new HttpContext(httpRequest, new HttpResponse(new StringWriter()));
                            SPControl.SetContextWeb(HttpContext.Current, web);
                        }

                        webPartMngr = web.GetLimitedWebPartManager(pageUrl, PersonalizationScope.Shared);

                        XmlDocument xmlDoc = new XmlDocument();
                        xmlDoc.AppendChild(xmlDoc.CreateElement("WebParts"));
                        xmlDoc.DocumentElement.SetAttribute("page", web.Site.MakeFullUrl(webPartMngr.ServerRelativeUrl));

                        XmlElement shared = xmlDoc.CreateElement("Shared");
                        xmlDoc.DocumentElement.AppendChild(shared);


                        string tempXml = string.Empty;
                        foreach (WebPart wp in webPartMngr.WebParts)
                        {
                            if (!simple)
                            {
                                tempXml += GetWebPartDetails(wp, webPartMngr);
                            }
                            else
                            {
                                tempXml += GetWebPartDetailsSimple(wp, webPartMngr);
                            }
                        }
                        shared.InnerXml = tempXml;

                        XmlElement user = xmlDoc.CreateElement("User");
                        xmlDoc.DocumentElement.AppendChild(user);

                        webPartMngr.Web.Dispose();
                        webPartMngr.Dispose();

                        webPartMngr = web.GetLimitedWebPartManager(pageUrl, PersonalizationScope.User);
                        tempXml     = string.Empty;
                        foreach (WebPart wp in webPartMngr.WebParts)
                        {
                            if (!simple)
                            {
                                tempXml += GetWebPartDetails(wp, webPartMngr);
                            }
                            else
                            {
                                tempXml += GetWebPartDetailsSimple(wp, webPartMngr);
                            }
                        }
                        user.InnerXml = tempXml;
                        return(Utilities.GetFormattedXml(xmlDoc));
                    }
                    finally
                    {
                        if (webPartMngr != null)
                        {
                            webPartMngr.Web.Dispose();
                            webPartMngr.Dispose();
                        }
                        if (HttpContext.Current != null && cleanupContext)
                        {
                            HttpContext.Current = null;
                        }
                    }
                }
        }