protected void updateButton_OnClick(object sender, EventArgs e)
        {
            bool digestOK = SPContext.Current.Web.ValidateFormDigest();

            String callingUserLogin = SPContext.Current.Web.CurrentUser.LoginName;

            if (digestOK)
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (WBRecordsManager manager = new WBRecordsManager(callingUserLogin))
                    {
                        WBRecord record = manager.Libraries.GetRecordByID(RecordID.Text);

                        record.LiveOrArchived            = LiveOrArchived.SelectedValue;
                        record.ProtectiveZone            = ProtectiveZone.SelectedValue;
                        record.SubjectTagsUIControlValue = SubjectTags.Text;

                        record.Update(callingUserLogin, ReasonForChange.Text);
                    }
                });

                CloseDialogAndRefresh();
            }
            else
            {
                returnFromDialogError("The security digest for the request was not OK");
            }

            libraryWeb.Dispose();
            librarySite.Dispose();
        }
        protected void btnSaveReport_Click(object sender, EventArgs e)
        {
            ReportView report = GetReport(ddlReportsOnPage.SelectedItem.Text);

            if (string.IsNullOrEmpty(txtBoxName.Text))
            {
                lblMessage.Text = "Report name cannot be blank.";
            }
            else
            {
                report.Name.Text = txtBoxName.Text;
                if (!string.IsNullOrEmpty(txtBoxDescription.Text))
                {
                    report.Description.Text = txtBoxDescription.Text;
                }
                if (!string.IsNullOrEmpty(txtBoxFolder.Text))
                {
                    report.Folder = txtBoxFolder.Text;
                }
                report.Owner.Login = Page.User.Identity.Name;

                // Clear the report location to save to the selected list.
                report.Location = RepositoryLocation.Empty();

                // Get the URL of the selected list.
                SPSite siteCollection = null;
                SPWeb  site           = null;
                try
                {
                    siteCollection = SPContext.Current.Site;
                    site           = siteCollection.OpenWeb(ddlPerfPointLists.SelectedValue);
                    SPList list    = site.GetList(siteCollection.Url + ddlPerfPointLists.SelectedValue);
                    string listUrl = list.DefaultViewUrl.Remove(list.DefaultViewUrl.LastIndexOf("/") + 1);
                    site.Dispose();
                    siteCollection.Dispose();

                    SaveAsFavorite(listUrl, report);
                }
                finally
                {
                    if (site != null)
                    {
                        site.Dispose();
                    }

                    if (siteCollection != null)
                    {
                        siteCollection.Dispose();
                    }
                }
            }
        }
Esempio n. 3
0
        public SPSite GetSiteCollection()
        {
            if (!IsSiteCollectionProcessValid())
            {
                return(null);
            }
            SPSite siteCollection = null;

            try
            {
                siteCollection = new SPSite(SiteUrl);
            }
            catch (Exception ex)
            {
                var log = new AppEventLog(AppException.ExceptionMessage(ex, "GetSiteCollection", "ClsHelperParent"));
                log.WriteToLog();
            }
            finally
            {
                if (siteCollection != null)
                {
                    siteCollection.Dispose();
                }
            }

            return(siteCollection);
        }
 public void Dispose()
 {
     if (m_site != null)
     {
         m_site.Dispose();
     }
 }
Esempio n. 5
0
        public void execute(SPSite site, string data)
        {
            WebAppId = site.WebApplication.Id;
            try
            {
                using (SqlConnection cn = CreateConnection())
                {
                    TimesheetAPI.CheckNonTeamMemberAllocation(site.RootWeb, base.TSUID.ToString(), cn.ConnectionString, data);

                    if (sErrors != "")
                    {
                        bErrors = true;
                    }
                }
            }
            catch (Exception ex)
            {
                bErrors = true;
                sErrors = "Error: " + ex.Message;
            }
            finally
            {
                if (site != null)
                {
                    site.Dispose();
                }
                data = null;
            }
        }
 public void CleanUp()
 {
     if (ContextSharePoint.VerifyServer(site))
     {
         site.Dispose();
     }
 }
        private void ValidateDocumentLibrary()
        {
            SPSite site = null;
            SPWeb  web  = null;

            try
            {
                site = new SPSite(txtPowerLibraryUrl.Text);
                web  = site.OpenWeb();
                SPFolder folder = web.GetFolder(txtPowerLibraryUrl.Text);
                if (folder.Exists == false)
                {
                    throw new FileNotFoundException();
                }
            }
            catch
            {
                throw new FileNotFoundException(
                          String.Format("Document library at {0} could not be found!"
                                        , txtPowerLibraryUrl.Text));
            }
            finally
            {
                if (web != null)
                {
                    web.Dispose();
                }
                if (site != null)
                {
                    site.Dispose();
                }
            }
        }
Esempio n. 8
0
        /// <summary>
        /// Actualiza el parametro definido para el usuario actual
        /// </summary>
        /// <param name="idParametro"></param>
        /// <param name="nuevoValorParametro"></param>
        /// <param name="properties"></param>
        private void ActualizarParametroCITE(int idParametro, string nuevoValorParametro)
        {
            SPSite sitioAdm = null;
            SPWeb  webAdm   = null;

            try
            {
                string UrlFPC = ConfigurationManager.AppSettings["UrlFPC"];

                SPSecurity.RunWithElevatedPrivileges(delegate()
                {//Como usuario administrador
                    sitioAdm = new SPSite(UrlFPC);
                    webAdm   = sitioAdm.OpenWeb();
                });

                SPList     listaParametros = webAdm.Lists[LISTA_PARAMETROS];
                SPListItem itemParametro   = listaParametros.Items.GetItemById(idParametro);

                itemParametro["Valor parámetro"] = nuevoValorParametro;
                itemParametro.Update();
            }
            finally
            {
                if (webAdm != null)
                {
                    webAdm.Dispose();
                }
                if (sitioAdm != null)
                {
                    sitioAdm.Dispose();
                }
            }
        }
        static void Main(string[] args)
        {
            SPSite site = null;

            try
            {
                site = new SPSite("http://intranet.csu.local");
                Console.WriteLine("Site url: {0}", site.Url);
                Console.WriteLine("Site ID: {0}", site.ID);
                Console.WriteLine("Content database: {0}", site.ContentDatabase.Name);

                Console.WriteLine("");
                Console.WriteLine("List of all webs in the site");
                foreach (SPWeb web in site.AllWebs)
                {
                    Console.WriteLine("{0} ({1})", web.Title, web.Url);
                    web.Dispose();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }
            finally
            {
                Console.ReadKey();
                if (site != null)
                {
                    site.Dispose();
                }
            }
        }
Esempio n. 10
0
 public override void Dispose()
 {
     if (jsonFarmMan != null)
     {
         jsonFarmMan.Dispose();
         jsonFarmMan = null;
     }
     if (jsonSiteMan != null)
     {
         jsonSiteMan.Dispose();
         jsonSiteMan = null;
     }
     if (prodPage != null)
     {
         prodPage.Dispose();
         prodPage = null;
     }
     if (extWeb != null)
     {
         extWeb.Dispose();
         extWeb = null;
     }
     if (extSite != null)
     {
         extSite.Dispose();
         extSite = null;
     }
     base.Dispose();
 }
        private string GetMasterPageContent(MasterPage layout)
        {
            string content = String.Empty;

            //SPSecurity.RunWithElevatedPrivileges(delegate()
            //{

            SPSite site = new SPSite(SPContext.Current.Web.Url);

            SPWeb rootWeb = site.RootWeb;

            SPFile pageLayoutFile = rootWeb.GetFile(layout.UniqueId);

            byte[] binFile = pageLayoutFile.OpenBinary();

            MemoryStream m      = new MemoryStream(binFile);
            StreamReader reader = new StreamReader(m);

            content = reader.ReadToEnd();
            reader.Close();
            //m.Close();

            site.Dispose();
            rootWeb.Dispose();

            //});

            return(content);
        }
Esempio n. 12
0
        public override void Execute(Guid targetInstanceId)
        {
            loga("Iniciando job");

            SPWebApplication webApp = this.Parent as SPWebApplication;
            Configuration    config = WebConfigurationManager.OpenWebConfiguration("/", webApp.Name);

            loga("Crregado config e webapp");
            DataTable dt = SQLConnector.GetDataTable(config.AppSettings.Settings["QueryPessoas"].Value, config.AppSettings.Settings["ConnectionStrPessoas"].Value);

            loga("dt carregado " + dt.Rows.Count.ToString());


            SPSite site = webApp.Sites[0];
            SPWeb  web  = site.RootWeb;

            loga("iniciando erase");
            SPList listPessoas = EraseListPessoas(web);

            loga("fim erase " + listPessoas.Items.Count);


            loga("inicio update");
            listPessoas = UpdateListPessoas(dt, web);

            loga("inicio fill");
            FillListPessoas(dt, listPessoas);

            web.Dispose();
            site.Dispose();
            dt.Dispose();
        }
Esempio n. 13
0
        private SPList GetDocumentLibraryFromUrl(string documentLibraryUrl, string username)
        {
            SPWeb oWeb = null;

            Uri webUrl = new Uri(new Uri(Context.Request.Url.ToString()), documentLibraryUrl);

            oWeb = new SPSite(webUrl.OriginalString).OpenWeb();
            if (!String.IsNullOrEmpty(username))
            {
                SPUserToken userToken = oWeb.SiteUsers[username].UserToken;
                oWeb.Dispose();
                SPSite site = new SPSite(webUrl.OriginalString, userToken);
                oWeb = site.OpenWeb();
            }
            SPList documentLibrary = oWeb.GetList(webUrl.OriginalString);

            if (documentLibrary.BaseType == SPBaseType.DocumentLibrary)
            {
                return(documentLibrary);
            }
            else
            {
                return(null);
            }
        }
Esempio n. 14
0
        /// <summary>
        /// Recupera el valor del parametro segun los valores provistos.
        /// El parametro es retornado como array "ID"|"Valor parametro"
        /// </summary>
        /// <param name="nombreParametro"></param>
        /// <param name="usuarioParametro"></param>
        /// <returns></returns>
        private List <string> RecuperarValorParametroGlobal(string nombreParametro,
                                                            string tipoSalida, SPUser usuarioParametro)
        {
            SPSite sitioAdm = null;
            SPWeb  webAdm   = null;

            List <string> parametro = new List <string>();

            try
            {
                string UrlFPC = ConfigurationManager.AppSettings["UrlFPC"];

                SPSecurity.RunWithElevatedPrivileges(delegate()
                {//Como usuario administrador
                    sitioAdm = new SPSite(UrlFPC);
                    webAdm   = sitioAdm.OpenWeb();
                });

                SPList listaParametros = webAdm.Lists[LISTA_PARAMETROS];

                foreach (SPListItem item in listaParametros.Items)
                {
                    if (item["Usuario parámetro"] != null)
                    {
                        try
                        {
                            int idUsuario = Convert.ToInt16(item["Usuario parámetro"].ToString().Remove(
                                                                item["Usuario parámetro"].ToString().IndexOf(';')));
                            string[] tituloParametro = item.Title.Split('-');

                            if (string.Equals(tituloParametro[0].Trim(), nombreParametro,
                                              StringComparison.CurrentCultureIgnoreCase) &&
                                string.Equals(tituloParametro[1].Trim(), tipoSalida,
                                              StringComparison.CurrentCultureIgnoreCase) &&
                                idUsuario == usuarioParametro.ID)
                            {
                                parametro.Add(item.ID.ToString());
                                parametro.Add(item["Valor parámetro"].ToString().Trim());

                                return(parametro);
                            }
                        }
                        catch { }
                    }
                }

                return(null);
            }
            finally
            {
                if (webAdm != null)
                {
                    webAdm.Dispose();
                }
                if (sitioAdm != null)
                {
                    sitioAdm.Dispose();
                }
            }
        }
 // TODO -  class can´t use IDisposable interface
 public void Ending()
 {
     if (_site != null)
     {
         _site.Dispose();
     }
 }
        private SPWeb safelyGetWeb(string parentWebUrl, string lmNumber)
        {
            // The OpenWeb method has an odd behavior of returning back the first subweb it finds. (which is both dumb and dangerous.)
            // Although a boolean in the second paramerter of the OpenWeb method is supposed to ensure that we return back the desired subweb,
            // it's been problematic with multi-layered subwebs.

            SPWeb web = null;

            try
            {
                web = new SPSite(parentWebUrl + "/" + lmNumber).OpenWeb();
                if (!web.Url.Contains(lmNumber))
                {
                    throw new Microsoft.SharePoint.SPEndpointAddressNotFoundException();
                }
                return(web);
            }
            catch (Exception ex)
            {
                log.addWarning("Attempted to retrieve a site for Litigation Matter " + lmNumber +
                               ", but a corresponding site could not be retrieved.  Update could not be processed. The exception returned was " + ex.ToString());
                if (web != null)
                {
                    web.Dispose();
                }
                return(web);
            }
        }
Esempio n. 17
0
        private void InitializeSiteAtManagedPath(string managedPath)
        {
            var defaultPortWebApp = this.GetDefaultPortWebApp();
            SPContentDatabase testContentDatabase = this.EnsureTestContentDatabase(defaultPortWebApp);

            var prefixCollection = defaultPortWebApp.Prefixes;

            if (!prefixCollection.Contains(managedPath))
            {
                // The hostname-site collection's prefix may still exist
                // if a test run was interrupted previously.
                prefixCollection.Add(managedPath, SPPrefixType.ExplicitInclusion);
            }

            // Flag so dispose will remove the managed path when the site collection is deleted
            this.ManagedPathCreated = managedPath;

            var siteUrl = defaultPortWebApp.GetResponseUri(SPUrlZone.Default) + managedPath;

            SPSiteCollection sites        = testContentDatabase.Sites;
            SPSite           existingSite = sites.FirstOrDefault(site => site.Url == siteUrl);

            if (existingSite != null)
            {
                existingSite.Delete();
                existingSite.Dispose();

                // Refresh Sites collection
                sites = testContentDatabase.Sites;
            }

            var newSite = sites.Add(siteUrl, Environment.UserName, "*****@*****.**");

            this.SiteCollection = newSite;
        }
        // Uncomment the method below to handle the event raised before a feature is deactivated.

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPSite oSite = new SPSite(SPContext.Current.Site.ID);
            SPWebCollection collWebsite = oSite.AllWebs;

            for (int i = 0; i < collWebsite.Count; i++)
            {
                using (SPWeb oWebsite = collWebsite[i])
                {
                    try
                    {
                        SPWeb oWeb = oSite.OpenWeb(oWebsite.ID);
                        oWeb.AllowUnsafeUpdates = true;
                        oWeb.Features.Remove(new Guid(FeatureGUID_InternalMasterwithSearchBox));
                        oWeb.AllowUnsafeUpdates = false;
                    }
                    catch (Exception ex)
                    {
                        SPDiagnosticsService diagSvc = SPDiagnosticsService.Local;
                        diagSvc.WriteTrace(0, new SPDiagnosticsCategory("Kapsch GSA Search Box On All Subsites", TraceSeverity.High, EventSeverity.Error),
                                                                TraceSeverity.Monitorable,
                                                                "Writing to the ULS log:  {0}",
                                                                new object[] { ex.Message }); 
                    }
                }
            }
            oSite.Dispose();
            collWebsite = null;
        }
Esempio n. 19
0
        public SPContentTypeId EnsureContentType(string webUrl, bool removeExcessiveFields)
        {
            SPContentTypeId contentTypeId = SPContentTypeId.Empty;

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                SPSite site = new SPSite(webUrl);
                SPWeb web   = site.OpenWeb();
                try
                {
                    SPContentType cType = EnsureContentTypeExists(ref web);
                    EnsureContentTypeFieldsExist(ref web, ref cType);
                    cType.Update(true, false);

                    if (removeExcessiveFields)
                    {
                        ContentTypeRemoveExcessiveFields(ref cType);
                        cType.Update(true, false);
                    }

                    InvokeOnContentTypeCreated(ref cType);
                    contentTypeId = cType.Id;
                    SetContentTypeId(contentTypeId);
                }
                catch { throw; }
                finally
                {
                    web.Dispose();
                    site.Dispose();
                }
            });
            return(contentTypeId);
        }
Esempio n. 20
0
        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);

            if (!disposing)
            {
                return;
            }

            if (_web != null && (SPContext.Current == null || _web != SPContext.Current.Web))
            {
                try
                {
                    _web.Dispose();
                }
                catch { }
                _web = null;
            }
            if (_site != null && (SPContext.Current == null || _site != SPContext.Current.Site))
            {
                try
                {
                    _site.Dispose();
                }
                catch { }
                _site = null;
            }
        }
        public Hashtable CreateGroup(SPUserCodeWorkflowContext context, string groupName, string siteUrl, string owner, string description, string permissions)
        {
            Hashtable result = new Hashtable();

            SPSite site = null;
            SPWeb  web  = null;

            try
            {
                if (String.IsNullOrEmpty(siteUrl))
                {
                    siteUrl = context.CurrentWebUrl;
                }

                site = new SPSite(siteUrl);
                web  = site.OpenWeb();

                var ownerUser = web.EnsureUser(owner);

                web.SiteGroups.Add(groupName, ownerUser, null, description);

                var group = web.SiteGroups.OfType <SPGroup>().Where(gn => gn.Name == groupName).First();

                if (!String.IsNullOrEmpty(permissions))
                {
                    StringReader permReader = new StringReader(permissions);

                    var roleAssignment = new SPRoleAssignment(group);

                    string perm;
                    while ((perm = permReader.ReadLine()) != null)
                    {
                        var roleDef = web.RoleDefinitions[perm];

                        roleAssignment.RoleDefinitionBindings.Add(roleDef);
                    }

                    web.RoleAssignments.Add(roleAssignment);
                }

                result["error"] = String.Empty;
            }
            catch (Exception ex)
            {
                result["error"] = ex.Message;
            }
            finally
            {
                if (web != null)
                {
                    web.Dispose();
                }
                if (site != null)
                {
                    site.Dispose();
                }
            }

            return(result);
        }
Esempio n. 22
0
        public void execute(SPSite site, SPWeb web, string data)
        {
            EPMData epmdata = null;

            try
            {
                epmdata = new EPMData(site.ID);

                ProcessSecurity.ProcessSecurityGroups(site, epmdata.GetClientReportingConnection, data);
            }
            catch { }
            finally
            {
                if (epmdata != null)
                {
                    epmdata.Dispose();
                }
                if (web != null)
                {
                    web.Dispose();
                }
                if (site != null)
                {
                    site.Dispose();
                }
                data = null;
            }
        }
Esempio n. 23
0
 public static void ClassCleanUp()
 {
     if (testSite != null)
     {
         testSite.Dispose();
     }
 }
        // Uncomment the method below to handle the event raised after a feature has been activated.

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPSite site = null;

            try
            {
                site = new SPSite("http://win-v7htu8u302g/sites/Training");
                SPWeb  web          = site.RootWeb;
                SPList trainersList = web.Lists["Trainers"];

                SPListItem newTrainerAlan = trainersList.Items.Add();
                newTrainerAlan["First Name"]     = "Alan";
                newTrainerAlan["Last Name"]      = "Franklin";
                newTrainerAlan["Full Name"]      = "Alan Franklin";
                newTrainerAlan["Company"]        = "Globomantics";
                newTrainerAlan["Business Phone"] = "800-555-1234";
                newTrainerAlan["Home Phone"]     = "800-555-4321";
                newTrainerAlan["E-mail Address"] = "*****@*****.**";
                newTrainerAlan.Update();
            }

            catch (Exception e)
            {
            }
            finally
            {
                if (site != null)
                {
                    site.Dispose();
                }
                Console.WriteLine("***************************DONE******************");
                Console.WriteLine("Press any key to continue...");
            }
        }
Esempio n. 25
0
        internal static Collection <Microsoft.Office.Server.ActivityFeed.ActivityType> GetInstalledActivityTypes(OutputManager outputManager)
        {
            SPSite           site    = null;
            SPServiceContext context = null;

            try
            {
                site    = SPWebService.AdministrationService.WebApplications.First().Sites.First();
                context = SPServiceContext.GetContext(site);

                var am            = new Microsoft.Office.Server.ActivityFeed.ActivityManager(null, context);
                var activityTypes = am.ActivityTypes;

                return(activityTypes.ToCollection());
            }
            catch (Exception exception)
            {
                if (outputManager != null)
                {
                    outputManager.WriteError(string.Format(CultureInfo.CurrentCulture, Exceptions.ErrorGettingActivityTypes, exception.Message), exception);
                }
            }
            finally
            {
                if (site != null)
                {
                    site.Dispose();
                }
            }

            return(null);
        }
Esempio n. 26
0
        private void InitializeSite(string hostName, string templateName, uint lcid)
        {
            var defaultPortWebApp = this.GetDefaultPortWebApp();
            SPContentDatabase testContentDatabase = this.EnsureTestContentDatabase(defaultPortWebApp);

            SPSiteCollection sites = testContentDatabase.Sites;

            SPSite existingSite = testContentDatabase.Sites.FirstOrDefault(site => site.Url == hostName);

            if (existingSite != null)
            {
                existingSite.Delete();
                existingSite.Dispose();

                // Refresh Sites collection
                sites = testContentDatabase.Sites;
            }

            SPSite newSite = sites.Add(
                hostName,
                "Dynamite Test",
                "Integration test temporary site",
                lcid,
                templateName,
                Environment.UserName,
                "Dynamite Test Agent",
                "*****@*****.**",
                Environment.UserName,
                "Dynamite Test Agent",
                "*****@*****.**",
                true);

            this.SiteCollection = newSite;
        }
Esempio n. 27
0
        /// <summary>
        /// Attempts to retrieve a site at the specified url.
        /// </summary>
        /// <param name="siteUrl"></param>
        /// <param name="site"></param>
        /// <returns></returns>
        public static bool TryGetSPSite(string siteUrl, out SPSite site)
        {
            site = null;

            Uri siteUri;

            if (TryCreateWebAbsoluteUri(siteUrl, out siteUri) == false)
            {
                return(false);
            }

            try
            {
                using (var innerSite = new SPSite(siteUri.ToString(), SPBaristaContext.Current.Site.UserToken))
                {
                    site = innerSite;
                    return(true);
                }
            }
            catch
            {
                if (site != null)
                {
                    site.Dispose();
                }
            }

            site = null;
            return(false);
        }
Esempio n. 28
0
        static void Main(string[] args)
        {
            SPSite site = null;
            try
            {
                site = new SPSite("http://intranet.csu.local");
                Console.WriteLine("Site url: {0}", site.Url);
                Console.WriteLine("Site ID: {0}", site.ID);
                Console.WriteLine("Content database: {0}", site.ContentDatabase.Name);

                Console.WriteLine("");
                Console.WriteLine("List of all webs in the site");
                foreach (SPWeb web in site.AllWebs)
                {
                    Console.WriteLine("{0} ({1})", web.Title, web.Url);
                    web.Dispose();
                }                
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }
            finally
            {
                Console.ReadKey();
                if (site != null) site.Dispose();
            }
        }
Esempio n. 29
0
 public void execute(SPSite site, SPWeb web, string data)
 {
     try
     {
         var wsCon = new WorkspaceController(data);
         wsCon.CreateWorkspace();
     }
     catch (Exception ex)
     {
         bErrors = true;
         sErrors = "General Error: " + ex.Message;
     }
     finally
     {
         if (web != null)
         {
             web.Dispose();
         }
         if (site != null)
         {
             site.Dispose();
         }
         data = null;
     }
 }
 public void CleanUp()
 {
     if (ContextSharePoint.VerifyServer(Site))
     {
         SiteColumn.Delete();
         Site.Dispose();
     }
 }
Esempio n. 31
0
 public void Dispose()
 {
     if (_site != null)
     {
         _site.Dispose();
         _site = null;
     }
 }
Esempio n. 32
0
        /// <summary>
        /// Attempts to retrieve a folder at the specified url.
        /// </summary>
        /// <param name="folderUrl"></param>
        /// <param name="web"></param>
        /// <param name="folder"></param>
        /// <param name="site"></param>
        /// <returns></returns>
        public static bool TryGetSPFolder(string folderUrl, out SPSite site, out SPWeb web, out SPFolder folder)
        {
            site   = null;
            web    = null;
            folder = null;

            Uri folderUri;

            if (TryCreateWebAbsoluteUri(folderUrl, out folderUri) == false)
            {
                return(false);
            }

            try
            {
                site   = new SPSite(folderUri.ToString(), SPBaristaContext.Current.Site.UserToken);
                web    = site.OpenWeb();
                folder = web.GetFolder(folderUri.ToString());
                if (folder != null && folder.Exists)
                {
                    return(true);
                }

                web.Dispose();
                site.Dispose();
                return(false);
            }
            catch
            {
                //Clean up.
                if (site != null)
                {
                    site.Dispose();
                }

                if (web != null)
                {
                    web.Dispose();
                }
            }

            site   = null;
            web    = null;
            folder = null;
            return(false);
        }
Esempio n. 33
0
        public void UploadFile(string srcUrl, string destUrl)
        {
            if (! File.Exists(srcUrl))
            {
                FileErrorLogger _logger = new FileErrorLogger();
                _logger.LogError(String.Format("{0} does not exist", srcUrl), ErrorLogSeverity.SeverityError,
                    ErrorType.TypeApplication, "TeamSiteReports.UploadFile()");
                _logger = null;
            }

            SPWeb site = new SPSite(destUrl).OpenWeb();
            try
            {
                FileStream fStream = File.OpenRead(srcUrl);
                byte[] contents = new byte[fStream.Length];
                fStream.Read(contents, 0, (int)fStream.Length);
                fStream.Close();
                site.Files.Add(destUrl, contents,true);
            }
            catch(SPException spe)
            {
                FileErrorLogger _logger = new FileErrorLogger();
                _logger.LogError(spe.Message+srcUrl, ErrorLogSeverity.SeverityError,
                    ErrorType.TypeApplication, "TeamSiteReports.UploadFile()");
                _logger = null;

            }
            catch(Exception e)
            {
                Object thisLock = new Object();
                lock (thisLock)
                {
                    FileErrorLogger _logger = new FileErrorLogger();
                    _logger.LogError(e.Message+srcUrl, ErrorLogSeverity.SeverityError,
                        ErrorType.TypeApplication, "TeamSiteReports.UploadFile()");
                    _logger = null;
                }
            }
            finally
            {
                if (site !=null)
                    site.Dispose();

            }
        }
        public override void GenerateReport()
        {
            TeamSiteFile tf = new TeamSiteFile();
            string fileName = System.Configuration.ConfigurationSettings.AppSettings["TeamSiteReports.TeamSiteSizeReportLocation"];

            StreamWriter fwriter = File.CreateText( fileName );
            Console.WriteLine("Creating file "+System.Configuration.ConfigurationSettings.AppSettings["TeamSiteReports.TeamSiteSizeReportLocation"]);

            HtmlTextWriter txtWriter=new HtmlTextWriter(fwriter);

            HtmlTable reportHtmlTable = new HtmlTable();
            reportHtmlTable.BgColor = System.Drawing.ColorTranslator.ToHtml(System.Drawing.Color.White);
            reportHtmlTable.Border = 1;
            reportHtmlTable.BorderColor = System.Drawing.ColorTranslator.ToHtml(System.Drawing.Color.LightGray );
            reportHtmlTable.Style.Add("font-family", "Verdana");
            reportHtmlTable.Style.Add("font-size", "9pt");

            HtmlTableRow trMessage = new HtmlTableRow();
            HtmlTableCell tcMessage = new HtmlTableCell();
            tcMessage.ColSpan = 10;
            tcMessage.InnerText = @"Last run: " + System.DateTime.Now.ToString();
            tcMessage.Style.Add("font-style","italic");
            trMessage.Cells.Add(tcMessage);
            reportHtmlTable.Rows.Add(trMessage);

            HtmlTableRow trHeader = new HtmlTableRow();
            trHeader.Style.Add("font-weight","bold");

            //teamsite name
            HtmlTableCell tcHeader1 = new HtmlTableCell();
            tcHeader1.InnerText = "teamsite name";
            trHeader.Cells.Add(tcHeader1);

            //teamsite url
            HtmlTableCell tcHeader2 = new HtmlTableCell();
            tcHeader2.InnerText = "teamsite url";
            trHeader.Cells.Add(tcHeader2);

            //teamsite # docs
            HtmlTableCell tcHeader3 = new HtmlTableCell();
            tcHeader3.InnerText = "#docs";
            trHeader.Cells.Add(tcHeader3);

            //teamsite size Mbytes
            HtmlTableCell tcHeader4 = new HtmlTableCell();
            tcHeader4.InnerText = "filesize (MB)";
            trHeader.Cells.Add(tcHeader4);
            reportHtmlTable.Rows.Add(trHeader);

            Console.WriteLine("Connecting to site...");
            SPSite siteCollection = new SPSite(System.Configuration.ConfigurationSettings.AppSettings["TeamSiteReports.TeamSiteUrl"]);
            SPWebCollection sites = siteCollection.AllWebs;

            try
            {
                foreach (SPWeb site in sites)
                {
                    try
                    {

                        totalFileSize = 0;
                        fileCount = 0;

                        SPFolderCollection folders = site.Folders;
                        traverseFolders(folders);

                        Console.WriteLine( "Summary: " + SPEncode.HtmlEncode(site.Name) + " Number: " + fileCount +
                            " Size: " + totalFileSize);

                        HtmlTableRow trData = new HtmlTableRow();

                        //teamsite name
                        HtmlTableCell tcData1 = new HtmlTableCell();
                        tcData1.InnerText = site.Name;
                        trData.Cells.Add(tcData1);

                        //teamsite url
                        HtmlTableCell tcData2 = new HtmlTableCell();
                        HtmlAnchor ha1 = new HtmlAnchor();
                        ha1.InnerText=site.Url;
                        ha1.HRef=site.Url;
                        tcData2.Controls.Add(ha1);
                        trData.Cells.Add(tcData2);

                        //teamsite # docs
                        HtmlTableCell tcData3 = new HtmlTableCell();
                        tcData3 .InnerText = fileCount.ToString();
                        trData.Cells.Add(tcData3);

                        //teamsite size Mbytes
                        HtmlTableCell tcData4 = new HtmlTableCell();
                        totalFileSize = totalFileSize / 1000000;
                        tcData4.InnerText = totalFileSize.ToString();
                        //tcData4.BgColor = roleStyle;
                        trData.Cells.Add(tcData4);

                        reportHtmlTable.Rows.Add(trData);

                    }
                    catch(Exception ex)
                    {
                        FileErrorLogger _logger = new FileErrorLogger();
                        _logger.LogError(ex.Message, ErrorLogSeverity.SeverityError,
                            ErrorType.TypeApplication, "Intranet.TeamSiteReports.UploadFile()");
                        _logger = null;
                    }
                    finally
                    {
                        site.Dispose();
                    }
                }

            }
            catch (Exception ex)
            {
                FileErrorLogger _logger = new FileErrorLogger();
                _logger.LogError(ex.Message, ErrorLogSeverity.SeverityError,
                    ErrorType.TypeApplication, "Intranet.TeamSiteReports.UploadFile()");
                _logger = null;
            }
            finally
            {
                siteCollection.Dispose();
            }

            reportHtmlTable.RenderControl(txtWriter);

            txtWriter.Close();
            tf.UploadFile(System.Configuration.ConfigurationSettings.AppSettings["TeamSiteReports.TeamSiteSizeReportLocation"],
                System.Configuration.ConfigurationSettings.AppSettings["TeamSiteReports.TeamSiteSizeReportDestination"]);
        }
        /// <summary>
        /// Copies the specified source list to the target URL.
        /// </summary>
        /// <param name="directory">The directory.</param>
        /// <param name="compressFile">if set to <c>true</c> [compress file].</param>
        /// <param name="includeusersecurity">if set to <c>true</c> [includeusersecurity].</param>
        /// <param name="excludeDependencies">if set to <c>true</c> [exclude dependencies].</param>
        /// <param name="haltOnFatalError">if set to <c>true</c> [halt on fatal error].</param>
        /// <param name="haltOnWarning">if set to <c>true</c> [halt on warning].</param>
        /// <param name="versions">The versions.</param>
        /// <param name="updateVersions">The update versions.</param>
        /// <param name="suppressAfterEvents">if set to <c>true</c> [suppress after events].</param>
        /// <param name="copySecurity">if set to <c>true</c> [copy security].</param>
        /// <param name="deleteSource">if set to <c>true</c> [delete source].</param>
        /// <param name="logFile">if set to <c>true</c> [log file].</param>
        /// <param name="quiet">if set to <c>true</c> [quiet].</param>
        internal void Copy(string directory, bool compressFile, int cabSize, bool includeusersecurity, bool excludeDependencies, bool haltOnFatalError, bool haltOnWarning, SPIncludeVersions versions, SPUpdateVersions updateVersions, bool suppressAfterEvents, bool copySecurity, bool deleteSource, bool logFile, bool quiet, SPIncludeDescendants includeDescendents, bool useSqlSnapshot, bool excludeChildren, bool retainObjectIdentity)
        {
            if (string.IsNullOrEmpty(directory))
                directory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
            string filename = directory;
            if (compressFile)
                filename = Path.Combine(directory, "temp.cmp");

            SPExportObject exportObject = new SPExportObject();
            SPExportSettings exportSettings = new SPExportSettings();
            exportSettings.ExcludeDependencies = excludeDependencies;
            SPExport export = new SPExport(exportSettings);

            exportObject.Type = SPDeploymentObjectType.List;
            exportObject.IncludeDescendants = includeDescendents;
            exportObject.ExcludeChildren = excludeChildren;
            StsAdm.OperationHelpers.ExportHelper.SetupExportObjects(exportSettings, cabSize, compressFile, filename, haltOnFatalError, haltOnWarning, includeusersecurity, logFile, true, quiet, versions);

            ExportList.PerformExport(export, exportObject, exportSettings, logFile, quiet, m_sourceUrl, useSqlSnapshot);

            SPImportSettings importSettings = new SPImportSettings();
            SPImport import = new SPImport(importSettings);

            StsAdm.OperationHelpers.ImportHelper.SetupImportObject(importSettings, compressFile, filename, haltOnFatalError, haltOnWarning, includeusersecurity, logFile, quiet, updateVersions, retainObjectIdentity, suppressAfterEvents);

            try
            {
                m_targetSite = new SPSite(m_targetUrl);
                m_targetWeb = m_targetSite.AllWebs[Utilities.GetServerRelUrlFromFullUrl(m_targetUrl)];

                PerformImport(import, importSettings, logFile, m_targetUrl);

                // If the list is a discussion list then attempt to resolve flattened threads.
                //if (m_targetList != null)
                //    SiteCollectionSettings.RepairSiteCollectionImportedFromSubSite.RepairDiscussionList(m_targetSite, m_targetList);

                if (!logFile && !deleteSource)
                {
                    Directory.Delete(directory, true);
                }
                else if (logFile && !deleteSource)
                {
                    foreach (string s in Directory.GetFiles(directory))
                    {
                        FileInfo file = new FileInfo(s);
                        if (file.Extension == ".log")
                            continue;
                        file.Delete();
                    }
                }

                if (deleteSource || copySecurity)
                {
                    using (SPSite sourceSite = new SPSite(m_sourceUrl))
                    using (SPWeb sourceWeb = sourceSite.OpenWeb())
                    {
                        SPList sourceList = Utilities.GetListFromViewUrl(sourceWeb, m_sourceUrl);

                        if (sourceList != null)
                        {
                            // If the user has chosen to include security then assume they mean for all the settings to match
                            // the source - copy those settings using the CopyListSecurity operation.
                            if (copySecurity)
                            {
                                Common.Lists.CopyListSecurity.CopySecurity(sourceList, m_targetList, m_targetWeb, true, quiet);
                            }

                            // If the user wants the source deleted (move operation) then delete using the DeleteList operation.
                            if (deleteSource)
                            {
                                DeleteList.Delete(sourceList, true);
                                Console.WriteLine("Source list deleted.  You can find the exported list here: " +
                                                  directory);
                            }
                        }
                    }
                }
            }
            finally
            {
                if (m_targetSite != null)
                    m_targetSite.Dispose();
                if (m_targetWeb != null)
                    m_targetWeb.Dispose();
            }
        }
        public void PerformImport(bool compressFile, string filename, bool quiet, bool haltOnWarning, bool haltOnFatalError, bool includeusersecurity, bool logFile, bool retainObjectIdentity, bool copySecurity, bool suppressAfterEvents, SPUpdateVersions updateVersions)
        {
            SPImportSettings settings = new SPImportSettings();
            SPImport import = new SPImport(settings);

            StsAdm.OperationHelpers.ImportHelper.SetupImportObject(settings, compressFile, filename, haltOnFatalError, haltOnWarning, includeusersecurity, logFile, quiet, updateVersions, retainObjectIdentity, suppressAfterEvents);

            try
            {
                m_targetSite = new SPSite(m_targetUrl);
                m_targetWeb = m_targetSite.AllWebs[Utilities.GetServerRelUrlFromFullUrl(m_targetUrl)];

                PerformImport(import, settings, logFile, m_targetUrl);

                // If the list is a discussion list then attempt to resolve flattened threads.
                //if (m_targetList != null)
                //    SiteCollectionSettings.RepairSiteCollectionImportedFromSubSite.RepairDiscussionList(m_targetSite, m_targetList);

                if (includeusersecurity && !string.IsNullOrEmpty(m_sourceUrl) && copySecurity)
                {
                    using (SPSite sourceSite = new SPSite(m_sourceUrl))
                    using (SPWeb sourceWeb = sourceSite.OpenWeb())
                    {
                        SPList sourceList = Utilities.GetListFromViewUrl(sourceWeb, m_sourceUrl);

                        if (sourceList != null)
                        {
                            if (m_targetList != null)
                                Common.Lists.CopyListSecurity.CopySecurity(sourceList, m_targetList, m_targetWeb, true, quiet);
                        }
                    }
                }
            }
            finally
            {
                if (m_targetSite != null)
                    m_targetSite.Dispose();
                if (m_targetWeb != null)
                    m_targetWeb.Dispose();
            }
        }
Esempio n. 37
0
        /// <summary>
        /// ���ڣ֣�����ҳ���޷�ȡ����ʵ������
        /// </summary>
        /// <param name="view"></param>
        /// <returns></returns>
        SPView GetRealView(SPView view)
        {
            //return this.GetCurrentSPWeb().GetViewFromUrl(view.Url);

            SPSite site = new SPSite(SPContext.Current.Site.ID);
            SPWeb web = site.OpenWeb(this.GetCurrentSPWeb().ID);
            SPView v = web.GetViewFromUrl(view.Url);
            web.Dispose();
            site.Dispose();
            return v;
        }
        /// <summary>
        /// OnSubmitFile method for the content organizer
        /// </summary>
        /// <param name="contentOrganizerWeb">The web.</param>
        /// <param name="recordSeries">Record series.</param>
        /// <param name="userName">Submitting user name.</param>
        /// <param name="fileContent">File content.</param>
        /// <param name="properties">File properties.</param>
        /// <param name="finalFolder">The final folder.</param>
        /// <param name="resultDetails">Result processing details.</param>
        /// <returns>The CustomRouterResult.</returns>
        public override CustomRouterResult OnSubmitFile(EcmDocumentRoutingWeb contentOrganizerWeb, string recordSeries, string userName, Stream fileContent, RecordsRepositoryProperty[] properties, SPFolder finalFolder, ref string resultDetails)
        {
            this.ResolveDependencies();

                var web = new SPSite(contentOrganizerWeb.DropOffZoneUrl).OpenWeb();

                // Get routed document properties
                var documentProperties = EcmDocumentRouter.GetHashtableForRecordsRepositoryProperties(
                    properties, recordSeries);

                // Example: Get a conventional field (8553196d-ec8d-4564-9861-3dbe931050c8 = FileLeafRef)
                string originalFileName = documentProperties["8553196d-ec8d-4564-9861-3dbe931050c8"].ToString();

                // EncodedAbsUrl field
                string originalFileUrl = documentProperties["7177cfc7-f399-4d4d-905d-37dd51bc90bf"].ToString();

                // Example: Get the SharePoint user who perform the action
                var user = web.EnsureUser(userName);

                // Example: Deal with errors
                if (originalFileName.ToLower().Contains("error"))
                {
                    // Display error message
                    SPUtility.TransferToErrorPage(
                        string.Format(CultureInfo.InvariantCulture, "This is an error message"));

                    // Save the error file in the Drop Off Library
                    this.SaveDocumentToDropOffLibrary(
                        fileContent,
                        documentProperties,
                        contentOrganizerWeb.DropOffZone,
                        originalFileName,
                        contentOrganizerWeb,
                        user);

                    return CustomRouterResult.SuccessCancelFurtherProcessing;
                }

                // Here is the business logic

                // Example: get a taxonomy field from document properties
                string confidentialityTaxValue = documentProperties[MyFields.MyTaxField.InternalName].ToString();
                string confidentiality = new TaxonomyFieldValue(confidentialityTaxValue).Label;

                // Example: Set a new field to the item
                var indexDate =
                    SPUtility.CreateISO8601DateTimeFromSystemDateTime(
                        DateHelper.GetSharePointDateUtc(web, DateTime.Now));

                // Be careful, if you want to add or modify some properties, use internal GUID instead of InternalName
                if (!documentProperties.ContainsKey(MyFields.MyIndexDate.ID.ToString()))
                {
                    documentProperties.Add(MyFields.MyIndexDate.ID.ToString(), indexDate);
                }
                else
                {
                    documentProperties[MyFields.MyIndexDate.ID.ToString()] = indexDate;
                }

                // Save the file in the final destination. You can get the newly created file here and apply further actions.
                var file = EcmDocumentRouter.SaveFileToFinalLocation(
                contentOrganizerWeb,
                finalFolder,
                fileContent,
                originalFileName,
                originalFileUrl,
                documentProperties,
                user,
                true,
                string.Empty);

                web.Dispose();

                return CustomRouterResult.SuccessContinueProcessing;
        }
        protected virtual bool SetSPTrustInCurrentContext(Uri context)
        {
            var webApp = SPWebApplication.Lookup(context);
            if (webApp == null)
            {
                return false;
            }

            SPSite site = null;

            try
            {
                site = new SPSite(context.AbsoluteUri);
            }
            catch (Exception)
            {
                // The root site doesn't exist
                this.associatedSPTrustedLoginProvider = Utils.GetSPTrustAssociatedWithCP(ProviderInternalName);

                if (this.associatedSPTrustedLoginProvider != null &&
                    this.associatedSPTrustedLoginProvider.IdentityClaimTypeInformation != null)
                {
                    this.identifierClaimType = this.associatedSPTrustedLoginProvider.IdentityClaimTypeInformation.InputClaimType;
                }

                return this.associatedSPTrustedLoginProvider != null;
            }

            if (site == null)
            {
                return false;
            }

            SPUrlZone currentZone = site.Zone;
            SPIisSettings iisSettings = webApp.GetIisSettingsWithFallback(currentZone);
            site.Dispose();

            if (!iisSettings.UseTrustedClaimsAuthenticationProvider)
            {
                return false;
            }

            // Get the list of authentication providers associated with the zone
            foreach (SPAuthenticationProvider prov in iisSettings.ClaimsAuthenticationProviders)
            {
                if (prov.GetType() == typeof(Microsoft.SharePoint.Administration.SPTrustedAuthenticationProvider))
                {
                    // Check if the current SPTrustedAuthenticationProvider is associated with the claim provider
                    if (prov.ClaimProviderName == ProviderInternalName)
                    {
                        this.associatedSPTrustedLoginProvider = Utils.GetSPTrustAssociatedWithCP(ProviderInternalName);

                        if (this.associatedSPTrustedLoginProvider != null &&
                            this.associatedSPTrustedLoginProvider.IdentityClaimTypeInformation != null)
                        {
                            this.identifierClaimType = this.associatedSPTrustedLoginProvider.IdentityClaimTypeInformation.InputClaimType;
                        }

                        return this.associatedSPTrustedLoginProvider != null;
                    }
                }
            }

            return false;
        }
        static void BreakInheritance()
        {
            SPSecurity.RunWithElevatedPrivileges(delegate () {

                //Get a list
                SPSite mySite = new SPSite("http://abcuniversity/_layouts/15/start.aspx");
                SPWeb myWeb = mySite.OpenWeb();

                string listUrl = "//abcuniversity/Lists/Chemicals";
                SPList chemicalList = myWeb.GetList(listUrl);

                //Break inheritence:
                chemicalList.BreakRoleInheritance(true);

                /*//add group to list with broken permissions
                SPGroup readersGroup = myWeb.SiteGroups["Readers"];
                chemicalList.RoleAssignments.Add(readersGroup);
                Console.WriteLine("Added {0} group to {1} list!", readersGroup.Name, chemicalList.EntityTypeName);*/

                //Clean up the mess
                myWeb.Dispose();
                mySite.Dispose();

                Console.WriteLine("Permissions Broken.");



            });
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            int LCID = HttpContext.Current.Request.Url.Segments.Contains("fra/") ? 1036 : 1033;
            System.Text.StringBuilder sb = new StringBuilder();
            //Load the images and links from the List
            string smiconList = "SMIcon";
            //Shireeh Added run with elevated to avoid annonymous access issue
            SPSecurity.RunWithElevatedPrivileges(delegate()
                    {
                        using (SPSite site = new SPSite(SPContext.Current.Site.Url))
                        {
                            using (SPWeb web = site.RootWeb)
                            {
                                try
                                {
                                    SPList list = web.Lists.TryGetList(smiconList);
                                    SPQuery oQuery = new SPQuery();
                                    SPListItemCollection collListItems;
                                    oQuery.Query = "<Where><IsNotNull><FieldRef Name='ID'/></IsNotNull></Where>" +
                                                                "<OrderBy><FieldRef Name='ItemOrder' /></OrderBy>";
                                    collListItems = list.GetItems(oQuery);
                                    if (sb != null & list != null && list.Items.Count > 0)
                                    {
                                        sb.Append("<div class= \"SMIconTitleRow\"><h3 class=\"background-accent margin-bottom-medium\" style\"width:100% !important; vertical-align:middle;\">");
                                        sb.Append((LCID == 1033 ? this.SMIConLinksHeaderEn : this.SMIConLinksHeaderFr));
                                        sb.Append("</h3></div><div class=\"SMIconLinkRow\"><div class= \"float-left\">");
                                        sb.Append("&nbsp; &nbsp;");
                                        foreach (SPListItem item in collListItems)
                                        {
                                            string link = LCID == 1036 ? "FraLink" : "ENGLink";
                                            String img = LCID == 1036 ? "FraIcon" : "ENGIcon";
                                            sb.Append("<a id=\"" + item.Title + "\" href=\"" + item[link].ToString().Split(',')[0] + "\" style=\"" + "stylename" + "\">" + "<img ID=\"" + "img" + item.Title + "\" runat=\"server\" src=\"" + item[img].ToString().Split(',')[0] + "\" /></a> ");

                                        }
                                        sb.Append("</div></div>");
                                        sb.Append("<link rel=\"stylesheet\" type=\"text/css\" href=\"/Style Library/SideImageLink/SideImageLink.css\"/>");
                                    }
                                    Literal1.Text = sb.ToString();

                                }//end try
                                catch
                                {

                                }
                                finally
                                {
                                    site.Dispose();
                                    web.Dispose();
                                }

                            }//web
                        }//site
                    });
        }
            /// <summary>
            /// Actually activate/deactivate users specified features on requested site collection list
            /// </summary>
            protected internal override bool Execute()
            {
                if (command == SiteCollectionCommand.Activate)
                {
                    log.Info(CommonUIStrings.logFeatureActivate);
                }
                else
                {
                    log.Info(CommonUIStrings.logFeatureDeactivate);
                }
                ReadOnlyCollection<Guid?> featureIds = InstallConfiguration.FeatureIdList;
                if (featureIds == null || featureIds.Count == 0)
                {
                    log.Warn(CommonUIStrings.logNoFeaturesSpecified);
                    return true;
                }
                if (siteCollectionLocs == null || siteCollectionLocs.Count == 0)
                {
                    // caller responsible for giving message, depending on operation (install, upgrade,...)
                    return true;
                }
                try
                {
                    foreach (SiteLoc siteLoc in siteCollectionLocs)
                    {
                        SPSite siteCollection = null;
                        try
                        {
                            siteCollection = new SPSite(siteLoc.SiteId);
                            foreach (Guid? featureId in siteLoc.featureList)
                            {
                                if (featureId == null) continue;

                                if (command == SiteCollectionCommand.Activate)
                                {
                                    FeatureActivator.ActivateOneFeature(siteCollection.Features, featureId.Value, log);
                                    if (!FeatureActivator.IsFeatureActivatedOnSite(siteCollection, featureId.Value))
                                    {
                                        // do not add to completedLocs, b/c it didn't complete
                                        log.Warn("Activation failed on " + siteCollection.Url + " : " + GetFeatureName(featureId));
                                    }
                                    else
                                    {
                                        completedLocs.Add(siteLoc);
                                        log.Info(siteCollection.Url + " : " + GetFeatureName(featureId));
                                    }
                                }
                                else
                                {
                                    siteCollection.Features.Remove(featureId.Value, true);
                                    completedLocs.Add(siteLoc);
                                    log.Info(siteCollection.Url + " : " + GetFeatureName(featureId));
                                }
                            }
                        }
                        catch (Exception exc)
                        {
                            if (rollback)
                            {
                                // during rollback simply log errors and continue
                                string message;
                                if (command == SiteCollectionCommand.Activate)
                                    message = "Activating feature(s)";
                                else
                                    message = "Deactivating feature(s)";
                                log.Error(message, exc);
                            }
                            else
                            {
                                log.Error(siteCollection.Url);
                                throw exc;
                            }
                        }
                        finally
                        {
                            // guarantee SPSite is released ASAP even in face of exception
                            if (siteCollection != null) siteCollection.Dispose();
                        }
                    }

                    return true;
                }
                catch (Exception exc)
                {
                    if (rollback)
                    {
                        log.Error("Error during rollback", exc);
                        return false;
                    }
                    rollback = true;
                    // rollback work accomplished so far
                    if (command == SiteCollectionCommand.Activate)
                    {
                        DeactivateSiteCollectionFeatureCommand reverseCommand = new DeactivateSiteCollectionFeatureCommand(this.Parent, completedLocs);
                        reverseCommand.Execute();
                    }
                    else
                    {
                        ActivateSiteCollectionFeatureCommand reverseCommand = new ActivateSiteCollectionFeatureCommand(this.Parent, completedLocs);
                        reverseCommand.Execute();
                    }
                    throw exc;
                }
            }
        public override void GenerateReport()
        {
            TeamSiteFile tf = new TeamSiteFile();
            string fileName = System.Configuration.ConfigurationSettings.AppSettings["TeamSiteReports.TeamSiteLastModifiedReportLocation"];
            string lastModified;

            StreamWriter fwriter = File.CreateText( fileName );
            Console.WriteLine("Creating file "+System.Configuration.ConfigurationSettings.AppSettings["TeamSiteReports.TeamSiteLastModifiedReportLocation"]);

            HtmlTextWriter txtWriter=new HtmlTextWriter(fwriter);

            HtmlTable reportHtmlTable = new HtmlTable();
            reportHtmlTable.BgColor = System.Drawing.ColorTranslator.ToHtml(System.Drawing.Color.White);
            reportHtmlTable.Border = 1;
            reportHtmlTable.BorderColor = System.Drawing.ColorTranslator.ToHtml(System.Drawing.Color.LightGray );
            reportHtmlTable.Style.Add("font-family", "Verdana");
            reportHtmlTable.Style.Add("font-size", "9pt");

            HtmlTableRow trMessage = new HtmlTableRow();
            HtmlTableCell tcMessage = new HtmlTableCell();
            tcMessage.ColSpan = 4;
            tcMessage.InnerText = @"Last run: " + System.DateTime.Now.ToString();
            tcMessage.Style.Add("font-style","italic");
            trMessage.Cells.Add(tcMessage);
            reportHtmlTable.Rows.Add(trMessage);

            reportHtmlTable.BgColor = System.Drawing.ColorTranslator.ToHtml(System.Drawing.Color.White);
            reportHtmlTable.Border = 1;
            reportHtmlTable.BorderColor = System.Drawing.ColorTranslator.ToHtml(System.Drawing.Color.LightGray );
            reportHtmlTable.Style.Add("font-family", "Verdana");
            reportHtmlTable.Style.Add("font-size", "9pt");

            HtmlTableRow trHeader = new HtmlTableRow();
            trHeader.Style.Add("font-weight","bold");

            //teamsite name
            HtmlTableCell tcHeader1 = new HtmlTableCell();
            tcHeader1.InnerText = "teamsite name";
            trHeader.Cells.Add(tcHeader1);

            //teamsite url
            HtmlTableCell tcHeader2 = new HtmlTableCell();
            tcHeader2.InnerText = "teamsite url";
            trHeader.Cells.Add(tcHeader2);

            //teamsite brand
            HtmlTableCell tcHeader3 = new HtmlTableCell();
            tcHeader3.InnerText = "brand";
            trHeader.Cells.Add(tcHeader3);

            //teamsite lastModified
            HtmlTableCell tcHeader4 = new HtmlTableCell();
            tcHeader4.InnerText = "last modified";
            trHeader.Cells.Add(tcHeader4);
            reportHtmlTable.Rows.Add(trHeader);

            Console.WriteLine("Connecting to site...");
            SPSite siteCollection = new SPSite(System.Configuration.ConfigurationSettings.AppSettings["TeamSiteReports.TeamSiteUrl"]);
            SPWebCollection sites = siteCollection.AllWebs;
            try
            {
                foreach (SPWeb site in sites)
                {
                    lastModified = "01/01/1900 01:01:01";

                    //go through the lists in the site for the later lastmodified date
                    foreach (SPList list in site.Lists)
                    {
                        if (System.DateTime.Parse(lastModified) < list.LastItemModifiedDate)
                            lastModified = list.LastItemModifiedDate.ToString();
                    }

                    Console.WriteLine("Site:"+site.Name+" last modified:"+lastModified);
                    HtmlTableRow trData = new HtmlTableRow();

                    //teamsite name
                    HtmlTableCell tcData1 = new HtmlTableCell();
                    tcData1.InnerText = site.Name;
                    trData.Cells.Add(tcData1);

                    //teamsite url
                    HtmlTableCell tcData2 = new HtmlTableCell();
                    HtmlAnchor ha1 = new HtmlAnchor();
                    ha1.InnerText=site.Url;
                    ha1.HRef=site.Url;
                    tcData2.Controls.Add(ha1);
                    trData.Cells.Add(tcData2);

                    //teamsite brand
                    HtmlTableCell tcData3 = new HtmlTableCell();
                    string brand = site.Url.ToString();
                    try
                    {
                        string[] ary = brand.Split('/');
                        tcData3.InnerText = ary[3].ToString(); // e.g. http:///blahblah fourth index will contain the brand
                    }
                    catch  //the url may not contain the brand for instance the top level site
                    {
                        tcData3 .InnerText = "na";
                    }
                    trData.Cells.Add(tcData3);

                    //teamsite last modified date
                    HtmlTableCell tcData4 = new HtmlTableCell();
                    tcData4.InnerText = lastModified;
                    trData.Cells.Add(tcData4);

                    reportHtmlTable.Rows.Add(trData);

                    site.Dispose();
                }
            }
            catch (Exception ex)
            {
                FileErrorLogger _logger = new FileErrorLogger();
                _logger.LogError(ex.Message, ErrorLogSeverity.SeverityError,
                    ErrorType.TypeApplication, "TeamSiteReports.UploadFile()");
                _logger = null;
            }
            finally
            {
                siteCollection.Dispose();
            }

            reportHtmlTable.RenderControl(txtWriter);

            txtWriter.Close();
            tf.UploadFile(System.Configuration.ConfigurationSettings.AppSettings["TeamSiteReports.TeamSiteLastModifiedReportLocation"],
                System.Configuration.ConfigurationSettings.AppSettings["TeamSiteReports.TeamSiteLastModifiedReportDestination"]);
        }
 public static bool IsFeatureActivatedOnSite(SPSite sitex, Guid featureId)
 {
     // Create new site object to get updated feature data to check
     SPSite site = null;
     try
     {
         site = new SPSite(sitex.ID);
         return isFeatureActivated(site.Features, featureId);
     }
     finally
     {
         if (site != null)
             site.Dispose();
     }
 }
Esempio n. 45
0
        static void Main(string[] args)
        {
            string site;
            StreamWriter SW;
            try
            {
                if (args.Length == 0)
                {
                    Console.WriteLine("Enter the Web Application URL:");
                    site = Console.ReadLine();
                }
                else
                {
                    site = args[0];
                }

                SPSite tmpRoot = new SPSite(site);
                SPSiteCollection tmpRootColl = tmpRoot.WebApplication.Sites;

                //objects for the CSV file generation
                SW = File.AppendText("c:\\VersioningReport.csv");

                //Write the CSV Header
                SW.WriteLine("Site Name, Library, File Name, File URL, Last Modified, No. of Versions, Latest Version Size -KB,Total Versions Size - MB");

                //Enumerate through each site collection
                foreach (SPSite tmpSite in tmpRootColl)
                {
                    //Enumerate through each sub-site
                    foreach (SPWeb tmpWeb in tmpSite.AllWebs)
                    {
                        //Enumerate through each List
                        foreach (SPList tmpList in tmpWeb.Lists)
                        {
                            //Get only Document Libraries & Exclude specific libraries
                            if (tmpList.BaseType == SPBaseType.DocumentLibrary &  tmpList.Title!="Workflows" & tmpList.Title!= "Master Page Gallery" & tmpList.Title!="Style Library" & tmpList.Title!="Pages")
                            {
                                  foreach (SPListItem tmpSPListItem in tmpList.Items)
                                    {

                                        if (tmpSPListItem.Versions.Count > 5)
                                        {
                                            
                                            SPListItemVersionCollection tmpVerisionCollection = tmpSPListItem.Versions;

                                            //Get the versioning details
                                            foreach (SPListItemVersion tmpVersion in tmpVerisionCollection)
                                             {
                                                int versionID = tmpVersion.VersionId;
                                                string strVersionLabel = tmpVersion.VersionLabel;
                                             }

                                            //Get the versioning Size details
                                            double versionSize = 0;
                                            SPFile tmpFile = tmpWeb.GetFile(tmpWeb.Url + "/" + tmpSPListItem.File.Url);

                                            foreach (SPFileVersion tmpSPFileVersion in tmpFile.Versions)
                                            {
                                                versionSize = versionSize + tmpSPFileVersion.Size;
                                            }
                                            //Convert to MB
                                            versionSize= Math.Round(((versionSize/1024)/1024),2);

                                            string siteName;
                                            if (tmpWeb.IsRootWeb)
                                            {
                                                siteName= tmpWeb.Title +" - Root";
                                            }
                                            else
                                            {
                                                siteName=tmpSite.RootWeb.Title + " - " + tmpWeb.Title;
                                            }

                                            //Log the data to a CSV file where versioning size > 0MB!
                                            if (versionSize > 0)
                                            {
                                                SW.WriteLine(siteName + "," + tmpList.Title + "," + tmpSPListItem.Name + "," + tmpWeb.Url + "/" + tmpSPListItem.Url + "," + tmpSPListItem["Modified"].ToString() + "," + tmpSPListItem.Versions.Count + "," + (tmpSPListItem.File.Length / 1024) + "," + versionSize );
                                            }
                                        }
                                }
                            }
                        }
                     }

                }

                //Close the CSV file object 
                SW.Close();

                //Dispose of the Root Site Object
                tmpRoot.Dispose();
                
                //Just to pause
                Console.WriteLine(@"Versioning Report Generated Successfull at c:\VersioningReport.csv. Press ""Enter"" key to Exit");
                Console.ReadLine();
            }

            catch (Exception ex)
            {
                System.Diagnostics.EventLog.WriteEntry("Get Versioning Report", ex.Message);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="fileInfo"></param>
        /// <param name="deMeta"></param>
        /// <returns></returns>
        public static int UpdateMeta(string[] fileInfo, DictionaryEntry[] deMeta)
        {
            try
            {
                SPSite site = null;
                SPWeb web = null;

                SetUrl(fileInfo);

                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    site = new SPSite(siteUrl);
                    web = site.OpenWeb(webUrl);
                });

                web.AllowUnsafeUpdates = true;//要更新栏位必须写这句

                CheckWebList(web, docLibName);

                SPList list = web.Lists[docLibName]; //文档库中文名
                docLibUrlName = list.RootFolder.Url; //获得文档库英文地址

                Hashtable ht = new Hashtable();
                if (deMeta != null)
                {
                    ht = ConvertToHT(deMeta);
                    CheckListField(list, ht);

                    SPListItemCollection splc = list.Items;
                    int index = GetFileIndex(splc, fileName);
                    if (index > -1)
                    {
                        SPListItem item = splc[index];
                        foreach (object key in ht.Keys)
                        {
                            item[key.ToString()] = ht[key].ToString();
                        }
                        item.Update();
                    }
                }
                web.Dispose();
                site.Dispose();

                return 1;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message + " " + fullUrl);
            }
        }
        private void DoWebActivations()
        {
            string method = string.Format(CommonUIStrings.deactivateWebFeatureMessage
                , requestedLocs.WebFeatures.Count, requestedLocs.WebLocations.Count);
            if (direction == ActivationDirection.Activate)
                method = string.Format(CommonUIStrings.activateWebFeatureMessage
                    , requestedLocs.WebFeatures.Count, requestedLocs.WebLocations.Count);

            string context = method;
            log.Info(context);
            try
            {
                foreach (FeatureLoc floc in requestedLocs.WebLocations)
                {
                    FeatureLoc completedLoc = FeatureLoc.CopyExceptFeatureList(floc);

                    SPSite site = null;
                    SPWeb web = null;
                    try
                    {
                        site = new SPSite(floc.SiteId);
                        web = site.OpenWeb(floc.WebId);
                        string webName = web.Url;

                        foreach (Guid featureId in floc.featureList)
                        {
                            context = method + " feature: " + featureId.ToString();

                            if (direction == ActivationDirection.Activate)
                            {
                                if (IsFeatureActivatedOnWeb(web, featureId))
                                {
                                    string msg = string.Format(CommonUIStrings.ActivatingSkipped_FeatureAlreadyActiveOnWeb
                                        , GetFeatureName(featureId), webName);
                                    log.Warn(msg);
                                }
                                else
                                {
                                    ActivateOneFeature(web.Features, featureId, log);

                                    if (!IsFeatureActivatedOnWeb(web, featureId))
                                    {
                                        // do not add to completedLocs, b/c it didn't complete
                                        log.Warn("Activation failed on web : " + GetFeatureName(featureId));
                                    }
                                    else
                                    {
                                        AddFeatureIdToFeatureLoc(completedLoc, featureId);
                                        log.Info(context + " : " + GetFeatureName(featureId));
                                    }
                                }
                            }
                            else
                            {
                                if (IsFeatureActivatedOnWeb(web, featureId))
                                {
                                    web.Features.Remove(featureId, true);
                                    AddFeatureIdToFeatureLoc(completedLoc, featureId);
                                    log.Info(context + " : " + GetFeatureName(featureId));
                                }
                                else
                                {
                                    string msg = string.Format(CommonUIStrings.DeactivatingSkipped_FeatureAlreadyActiveOnWeb
                                        , GetFeatureName(featureId), webName);
                                    log.Warn(msg);
                                }
                            }
                        }
                        if (completedLoc.featureList != null)
                        {
                            completedLocs.AddFeatureLocation(completedLoc);
                        }
                    }
                    finally
                    {
                        if (web != null)
                        {
                            web.Dispose();
                            web = null;
                        }
                        if (site != null)
                        {
                            site.Dispose();
                            site = null;
                        }
                    }
                }
            }
            catch (Exception exc)
            {
                log.Error(context, exc);
                throw exc;
            }
        }
        /// <summary>
        /// Runs the specified command.
        /// </summary>
        /// <param name="command">The command.</param>
        /// <param name="keyValues">The key values.</param>
        /// <param name="output">The output.</param>
        /// <returns></returns>
        public override int Execute(string command, System.Collections.Specialized.StringDictionary keyValues, out string output)
        {
            output = string.Empty;
            Logger.Verbose = true;

            string url = Params["url"].Value;
            bool force = false; // Params["force"].UserTypedIn;
            string scope = Params["scope"].Value.ToLowerInvariant();
            bool haltOnError = Params["haltonerror"].UserTypedIn;

            switch (scope)
            {
                case "file":
                    using (SPSite site = new SPSite(url))
                    using (SPWeb web = site.OpenWeb())
                    {
                        SPFile file = web.GetFile(url);
                        if (file == null)
                        {
                            throw new FileNotFoundException(string.Format("File '{0}' not found.", url), url);
                        }

                        Common.Pages.ReGhostFile.Reghost(site, web, file, force, haltOnError);
                    }
                    break;
                case "list":
                    using (SPSite site = new SPSite(url))
                    using (SPWeb web = site.OpenWeb())
                    {
                        SPList list = Utilities.GetListFromViewUrl(web, url);
                        Common.Pages.ReGhostFile.ReghostFilesInList(site, web, list, force, haltOnError);
                    }
                    break;
                case "web":
                    bool recurseWebs = Params["recursewebs"].UserTypedIn;
                    using (SPSite site = new SPSite(url))
                    using (SPWeb web = site.AllWebs[Utilities.GetServerRelUrlFromFullUrl(url)])
                    {
                        Common.Pages.ReGhostFile.ReghostFilesInWeb(site, web, recurseWebs, force, haltOnError);
                    }
                    break;
                case "site":
                    using (SPSite site = new SPSite(url))
                    {
                        Common.Pages.ReGhostFile.ReghostFilesInSite(site, force, haltOnError);
                    }
                    break;
                case "webapplication":
                    SPWebApplication webApp = SPWebApplication.Lookup(new Uri(url));
                    Logger.Write("Progress: Analyzing files in web application '{0}'.", url);

                    foreach (SPSite site in webApp.Sites)
                    {
                        try
                        {
                            Common.Pages.ReGhostFile.ReghostFilesInSite(site, force, haltOnError);
                        }
                        finally
                        {
                            site.Dispose();
                        }
                    }
                    break;

            }
            return (int)ErrorCodes.NoError;
        }
            /// <summary>
            /// Actually activate/deactivate users specified features on requested web list
            /// </summary>
            protected internal override bool Execute()
            {
                if (command == WebCommand.Activate)
                {
                    log.Info(CommonUIStrings.logFeatureActivate);
                }
                else
                {
                    log.Info(CommonUIStrings.logFeatureDeactivate);
                }
                ReadOnlyCollection<Guid?> featureIds = InstallConfiguration.FeatureIdList;
                if (featureIds == null || featureIds.Count == 0)
                {
                    log.Warn(CommonUIStrings.logNoFeaturesSpecified);
                    return true;
                }
                if (webLocs == null || webLocs.Count == 0)
                {
                    // caller responsible for giving message, depending on operation (install, upgrade,...)
                    return true;
                }
                try
                {
                    foreach (WebLoc webLoc in webLocs)
                    {
                        SPSite siteCollection = null;
                        SPWeb web = null;
                        try
                        {
                            siteCollection = new SPSite(webLoc.siteInfo.SiteId);
                            web = siteCollection.OpenWeb(webLoc.WebId);

                            foreach (Guid? featureId in webLoc.featureList)
                            {
                                if (featureId == null) continue;

                                if (command == WebCommand.Activate)
                                {
                                    FeatureActivator.ActivateOneFeature(web.Features, featureId.Value, log);
                                    if (!FeatureActivator.IsFeatureActivatedOnWeb(web, featureId.Value))
                                    {
                                        // do not add to completedLocs, b/c it didn't complete
                                        log.Warn("Activation failed on " + web.Url + " : " + GetFeatureName(featureId));
                                    }
                                    else
                                    {
                                        completedLocs.Add(webLoc);
                                        log.Info(web.Url + " : " + GetFeatureName(featureId));
                                    }
                                }
                                else
                                {
                                    web.Features.Remove(featureId.Value, true);
                                    completedLocs.Add(webLoc);
                                    log.Info(web.Url + " : " + GetFeatureName(featureId));
                                }
                            }
                        }
                        catch (Exception exc)
                        {
                            if (rollback)
                            {
                                // during rollback simply log errors and continue
                                string message;
                                if (command == WebCommand.Activate)
                                    message = "Activating feature(s)";
                                else
                                    message = "Deactivating feature(s)";
                                log.Error(message, exc);
                            }
                            else
                            {
                                throw exc;
                            }
                        }
                        finally
                        {
                            // guarantee SPWeb is released ASAP even in face of exception
                            if (web != null) web.Dispose();
                            // guarantee SPSite is released ASAP even in face of exception
                            if (siteCollection != null) siteCollection.Dispose();
                        }
                    }
                }
                catch (Exception ex)
                {
                    log.Error(ex.Message, ex);
                }
                return true;
            }
 private void AddSiteCollectionLinks(IList<SiteLoc> siteCollectionTargets, string relativeLink)
 {
     foreach (SiteLoc siteLoc in siteCollectionTargets)
     {
     SPSite siteCollection = null;
     try
     {
         siteCollection = new SPSite(siteLoc.SiteId);
         string linkText = InstallConfiguration.FormatString(CommonUIStrings.finishedLinkTextSiteCollection, siteCollection.Url);
         AddLink(linkText, 6, 4, siteCollection.Url + relativeLink);
     }
     finally
     {
         // guarantee SPSite is released ASAP even in face of exception
         if (siteCollection != null) siteCollection.Dispose();
     }
     }
 }
 public static bool IsFeatureActivatedOnWeb(SPWeb webx, Guid featureId)
 {
     // Create new site object to get updated feature data to check
     SPSite site = null;
     SPWeb web = null;
     try
     {
         site = new SPSite(webx.Site.ID);
         web = site.OpenWeb(webx.ID);
         return isFeatureActivated(web.Features, featureId);
     }
     finally
     {
         if (web != null)
             web.Dispose();
         if (site != null)
             site.Dispose();
     }
 }
 private void ReportActivations()
 {
     FeatureLocations flocs = InstallProcessControl.GetFeaturedLocations(myOperation);
     myList.View = View.Details;
     myList.Columns.Clear();
     myList.Columns.Add("Scope", 50);
     myList.Columns.Add("WebApp", 100);
     myList.Columns.Add("Site", 100);
     myList.Columns.Add("Web", 100);
     if (InstallConfiguration.FeatureIdList.Count > 1)
     {
         myList.Columns.Add("#Features", 30);
     }
     // Farm
     foreach (FeatureLoc floc in flocs.FarmLocations)
     {
         AddLocationItemToDisplay(SPFeatureScope.Farm, "", "", "", floc.featureList.Count);
     }
     // Web Application
     foreach (FeatureLoc floc in flocs.WebAppLocations)
     {
         SPWebApplication webapp = GetWebAppById(floc.WebAppId);
         if (webapp == null) continue;
         AddLocationItemToDisplay(SPFeatureScope.WebApplication
             , GetWebAppName(webapp), "", "", floc.featureList.Count);
     }
     // Site Collection
     foreach (FeatureLoc floc in flocs.SiteLocations)
     {
         SPSite site = new SPSite(floc.SiteId);
         if (site == null) continue;
         try
         {
             AddLocationItemToDisplay(SPFeatureScope.Site
                 , GetWebAppName(site.WebApplication), site.RootWeb.Title
                 , "", floc.featureList.Count);
         }
         finally
         {
             site.Dispose();
         }
     }
     // Web
     foreach (FeatureLoc floc in flocs.WebLocations)
     {
         SPSite site = new SPSite(floc.SiteId);
         if (site == null) continue;
         try
         {
             SPWeb web = site.OpenWeb(floc.WebId);
             if (web == null) continue;
             try
             {
                 AddLocationItemToDisplay(SPFeatureScope.Web
                     , GetWebAppName(web.Site.WebApplication), web.Site.RootWeb.Title
                     , web.Title, floc.featureList.Count);
             }
             finally
             {
                 web.Dispose();
             }
         }
         finally
         {
             site.Dispose();
         }
     }
 }
Esempio n. 53
0
        // TODO: consider moving this code be moved to WizardDeployment so STSADM command also benefits from it?
        private bool authenticateAgainstSite()
        {
            if (f_traceSwitch.TraceVerbose)
            {
                f_traceHelper.TraceVerbose("authenticateAgainstSite: Entered authenticateAgainstSite().");
            }

            bool bAuthed = false;
            // create SPSite and dispose of it immediately, we just want to check the site is valid..
            SPSite siteForTest = null;

            try
            {
                if (f_traceSwitch.TraceInfo)
                {
                    f_traceHelper.TraceInfo("authenticateAgainstSite: Initialising SPSite object with URL '{0}'.",
                        f_sSiteUrl);
                }

                siteForTest = new SPSite(f_sSiteUrl);

                if (f_traceSwitch.TraceInfo)
                {
                    f_traceHelper.TraceInfo("authenticateAgainstSite: Successfully initialised, setting bAuthed to true.",
                        f_sSiteUrl);
                }

                bAuthed = true;
            }
            catch (FileNotFoundException noFileExc)
            {
                if (f_traceSwitch.TraceWarning)
                {
                    f_traceHelper.TraceWarning("authenticateAgainstSite: Caught FileNotFoundException, indicates unable " +
                        "to find site with this URL - will show validation error MessageBox and set bAuthed to false. Exception details: '{0}'.",
                        noFileExc);
                }

                showValidationError(string.Format("Unable to contact site at address '{0}', please check the URL.",
                    txtSiteUrl.Text), txtSiteUrl);
            }
            catch (UriFormatException uriExc)
            {
                if (f_traceSwitch.TraceWarning)
                {
                    f_traceHelper.TraceWarning("authenticateAgainstSite: Caught UriFormatException, indicates format " +
                        "of URL is invalid - will show validation error MessageBox and set bAuthed to false. Exception details: '{0}'.",
                        uriExc);
                }

                showValidationError("There is a problem with the format of the URL, please check.", txtSiteUrl);
            }
            finally
            {
                if (siteForTest != null)
                {
                    siteForTest.Dispose();
                }
            }

            if (f_traceSwitch.TraceVerbose)
            {
                f_traceHelper.TraceVerbose("authenticateAgainstSite: Returning '{0}'.",
                    bAuthed);
            }

            return bAuthed;
        }
        public override void GenerateReport()
        {
            TeamSiteFile tf = new TeamSiteFile();
            string fileName = System.Configuration.ConfigurationSettings.AppSettings["TeamSiteReports.TeamSiteSubsiteReportLocation"];
            StreamWriter fwriter = File.CreateText( fileName );
            Console.WriteLine("Creating file "+System.Configuration.ConfigurationSettings.AppSettings["TeamSiteReports.TeamSiteSubsiteReportLocation"]);
            HtmlTextWriter txtWriter=new HtmlTextWriter(fwriter);

            HtmlTable reportHtmlTable = new HtmlTable();
            reportHtmlTable.BgColor = System.Drawing.ColorTranslator.ToHtml(System.Drawing.Color.White);
            reportHtmlTable.Border = 1;
            reportHtmlTable.BorderColor = System.Drawing.ColorTranslator.ToHtml(System.Drawing.Color.LightGray );
            reportHtmlTable.Style.Add("font-family", "Verdana");

            reportHtmlTable.Style.Add("font-size", "9pt");

            HtmlTableRow trMessage = new HtmlTableRow();

            HtmlTableCell tcMessage = new HtmlTableCell();
            tcMessage.ColSpan = 10;
            tcMessage.InnerText = @"Last run: " + System.DateTime.Now.ToString();
            tcMessage.Style.Add("font-style","italic");
            trMessage.Cells.Add(tcMessage);
            reportHtmlTable.Rows.Add(trMessage);

            HtmlTableRow trHeader = new HtmlTableRow();
            trHeader.Style.Add("font-weight","bold");

            //teamsite name
            HtmlTableCell tcHeader1 = new HtmlTableCell();
            tcHeader1.InnerText = "teamsite name";
            trHeader.Cells.Add(tcHeader1);

            //teamsite url
            HtmlTableCell tcHeader2 = new HtmlTableCell();
            tcHeader2.InnerText = "teamsite url";
            trHeader.Cells.Add(tcHeader2);

            //teamsite brand
            HtmlTableCell tcHeader3 = new HtmlTableCell();
            tcHeader3.InnerText = "brand";
            trHeader.Cells.Add(tcHeader3);

            //teamsite subsite name
            HtmlTableCell tcHeader4 = new HtmlTableCell();
            tcHeader4.InnerText = "subsite name";
            trHeader.Cells.Add(tcHeader4);

            //teamsite subsite url
            HtmlTableCell tcHeader5 = new HtmlTableCell();
            tcHeader5.InnerText = "subsite url";
            trHeader.Cells.Add(tcHeader5);

            reportHtmlTable.Rows.Add(trHeader);

            SPSite siteCollection = new SPSite(System.Configuration.ConfigurationSettings.AppSettings["TeamSiteReports.TeamSiteUrl"]);
            SPWebCollection sites = siteCollection.AllWebs;

            try
            {
                foreach (SPWeb site in sites)
                {
                    try
                    {
                        //ignore top level brand sites
                        switch (site.Name)
                        {
                            case "":
                                break;
                            case "doh":
                                break;
                            case "Re":
                                break;
                            case "Mi":
                                break;
                            default:
                                SPWebCollection subsites = site.Webs;
                                //if there are subsites log them
                                if(subsites.Count > 0)
                                {
                                    foreach (SPWeb subsite in subsites)
                                    {
                                        try
                                        {
                                            Console.WriteLine("Site:"+site.Name);
                                            Console.WriteLine("\tSubsite:"+subsite.Name);
                                            HtmlTableRow trData = new HtmlTableRow();

                                            //teamsite name
                                            HtmlTableCell tcData1 = new HtmlTableCell();
                                            tcData1.InnerText = site.Name;
                                            trData.Cells.Add(tcData1);

                                            //teamsite url
                                            HtmlTableCell tcData2 = new HtmlTableCell();
                                            HtmlAnchor ha1 = new HtmlAnchor();
                                            ha1.InnerText=site.Url;
                                            ha1.HRef=site.Url;
                                            tcData2.Controls.Add(ha1);
                                            trData.Cells.Add(tcData2);

                                            //teamsite brand
                                            HtmlTableCell tcData3 = new HtmlTableCell();
                                            string brand = site.Url.ToString();
                                            try
                                            {
                                                string[] ary = brand.Split('/');
                                                tcData3.InnerText = ary[3].ToString(); // e.g. http:///blahblah fourth index will contain the brand
                                            }
                                            catch  //the url may not contain the brand for instance the top level site
                                            {
                                                tcData3 .InnerText = "na";
                                            }
                                            trData.Cells.Add(tcData3);

                                            //subsite name
                                            HtmlTableCell tcData4 = new HtmlTableCell();
                                            tcData4.InnerText = subsite.Name;
                                            trData.Cells.Add(tcData4);

                                            //subsite url
                                            HtmlTableCell tcData5 = new HtmlTableCell();
                                            HtmlAnchor ha2 = new HtmlAnchor();
                                            ha2.InnerText=subsite.Url;
                                            ha2.HRef=subsite.Url;
                                            tcData5.Controls.Add(ha2);
                                            trData.Cells.Add(tcData5);

                                            reportHtmlTable.Rows.Add(trData);

                                        }
                                        catch(Exception ex)
                                        {
                                            FileErrorLogger _logger = new FileErrorLogger();
                                            _logger.LogError(ex.Message, ErrorLogSeverity.SeverityError,
                                                ErrorType.TypeApplication, "TeamSiteReports.UploadFile()");
                                            _logger = null;
                                        }
                                        finally
                                        {
                                            subsite.Dispose();
                                        }
                                    }

                                }
                                break;
                        }//switch
                    }//try
                    catch(Exception ex)
                    {
                        FileErrorLogger _logger = new FileErrorLogger();
                        _logger.LogError(ex.Message, ErrorLogSeverity.SeverityError,
                            ErrorType.TypeApplication, "TeamSiteReports.UploadFile()");
                        _logger = null;
                    }
                    finally
                    {
                        site.Dispose();
                    }
                }//foreach
            }//try
            catch(Exception ex)
            {
                FileErrorLogger _logger = new FileErrorLogger();
                _logger.LogError(ex.Message, ErrorLogSeverity.SeverityError,
                    ErrorType.TypeApplication, "TeamSiteReports.UploadFile()");
                _logger = null;
            }
            finally
            {

                siteCollection.Dispose();
            }

            reportHtmlTable.RenderControl(txtWriter);

            txtWriter.Close();
            tf.UploadFile(System.Configuration.ConfigurationSettings.AppSettings["TeamSiteReports.TeamSiteSubsiteReportLocation"],
                System.Configuration.ConfigurationSettings.AppSettings["TeamSiteReports.TeamSiteSubsiteReportDestination"]);
        }
        public override void GenerateReport()
        {
            TeamSiteFile tf = new TeamSiteFile();
            string fileName = System.Configuration.ConfigurationSettings.AppSettings["TeamSiteReports.TeamSiteOwnersReportLocation"];
            string roleStyle;

            StreamWriter fwriter = File.CreateText( fileName );
            Console.WriteLine("Creating file "+System.Configuration.ConfigurationSettings.AppSettings["TeamSiteReports.TeamSiteOwnersReportLocation"]);

            HtmlTextWriter txtWriter=new HtmlTextWriter(fwriter);

            HtmlTable reportHtmlTable = new HtmlTable();
            reportHtmlTable.BgColor = System.Drawing.ColorTranslator.ToHtml(System.Drawing.Color.White);
            reportHtmlTable.Border = 1;
            reportHtmlTable.BorderColor = System.Drawing.ColorTranslator.ToHtml(System.Drawing.Color.LightGray );
            reportHtmlTable.Style.Add("font-family", "Verdana");
            reportHtmlTable.Style.Add("font-size", "9pt");

            HtmlTableRow trMessage = new HtmlTableRow();

            HtmlTableCell tcMessage = new HtmlTableCell();
            tcMessage.ColSpan = 10;
            tcMessage.InnerText = @"Last run: " + System.DateTime.Now.ToString();
            tcMessage.Style.Add("font-style","italic");

            HtmlTableRow trHeader = new HtmlTableRow();
            trHeader.Style.Add("font-weight","bold");

            //teamsite name
            HtmlTableCell tcHeader1 = new HtmlTableCell();
            tcHeader1.InnerText = "teamsite name";
            trHeader.Cells.Add(tcHeader1);

            //teamsite url
            HtmlTableCell tcHeader2 = new HtmlTableCell();
            tcHeader2.InnerText = "teamsite url";
            trHeader.Cells.Add(tcHeader2);

            //teamsite brand
            HtmlTableCell tcHeader3 = new HtmlTableCell();
            tcHeader3.InnerText = "brand";
            trHeader.Cells.Add(tcHeader3);

            //teamsite users fullname
            HtmlTableCell tcHeader4 = new HtmlTableCell();
            tcHeader4.InnerText = "teamsite owners";
            trHeader.Cells.Add(tcHeader4);

            //lanId
            HtmlTableCell tcHeader5 = new HtmlTableCell();
            tcHeader5.InnerText = "lanId" ;
            trHeader.Cells.Add(tcHeader5);

            //email address
            HtmlTableCell tcHeader6 = new HtmlTableCell();
            tcHeader6.InnerText = "email" ;
            trHeader.Cells.Add(tcHeader6);

            //teamsite request for access email address
            HtmlTableCell tcHeader8 = new HtmlTableCell();
            tcHeader8.InnerText = "request for access email";
            trHeader.Cells.Add(tcHeader8);

            //teamsite memebership count
            HtmlTableCell tcHeader9 = new HtmlTableCell();
            tcHeader9.InnerText = "TeamSite Membership";
            trHeader.Cells.Add(tcHeader9);

            //subsites
            HtmlTableCell tcHeader10 = new HtmlTableCell();
            tcHeader10.InnerText = "Subsites";
            trHeader.Cells.Add(tcHeader10);

            reportHtmlTable.Rows.Add(trHeader);

            Console.WriteLine("Connecting to site...");
            SPSite siteCollection = new SPSite(System.Configuration.ConfigurationSettings.AppSettings["TeamSiteReports.TeamSiteUrl"]);
            SPWebCollection sites = siteCollection.AllWebs;

            try
            {
                foreach (SPWeb site in sites)
                {
                    try
                    {
                        SPWebCollection subSites = site.Webs;
                        int subsitesCount = subSites.Count;
                        int roleCount = 0;
                        SPUserCollection users = site.Users;

                        Console.WriteLine("Site: "+site.Name);
                        foreach(SPUser user in users)
                        {
                            SPRoleCollection roles = user.Roles;

                            //we need to count the roles here we count the number of teamsite owners..
                            foreach(SPRole role in roles)
                            {
                                if (role.Name == System.Configuration.ConfigurationSettings.AppSettings["TeamSiteReports.roleExclusiveInclude"].ToString())
                                {
                                    roleCount ++;
                                }
                            }

                        } //user
                        if (roleCount > Convert.ToInt16(System.Configuration.ConfigurationSettings.AppSettings["TeamSiteReports.TeamSiteOwnersCount"]) )
                        {
                            //set the style to flag this on the cell
                            roleStyle = System.Drawing.ColorTranslator.ToHtml(System.Drawing.Color.Orange);
                        }
                        else
                        {
                            roleStyle = System.Drawing.ColorTranslator.ToHtml(System.Drawing.Color.White);
                        }

                        foreach(SPUser user in users)
                        {
                            SPRoleCollection roles = user.Roles;
                            Console.WriteLine("\tUser: "******"TeamSiteReports.roleExclusiveInclude"].ToString())
                                {
                                    string sRole = role.Name.ToString();

                                    SPListCollection lists =  site.Lists;
                                    HtmlTableRow trData = new HtmlTableRow();

                                    //teamsite name
                                    HtmlTableCell tcData1 = new HtmlTableCell();
                                    tcData1.InnerText = site.Name;
                                    trData.Cells.Add(tcData1);

                                    //teamsite url
                                    HtmlTableCell tcData2 = new HtmlTableCell();
                                    HtmlAnchor ha1 = new HtmlAnchor();
                                    ha1.InnerText=site.Url;
                                    ha1.HRef=site.Url;
                                    tcData2.Controls.Add(ha1);
                                    trData.Cells.Add(tcData2);

                                    //teamsite brand
                                    HtmlTableCell tcData3 = new HtmlTableCell();
                                    string brand = site.Url.ToString();
                                    try
                                    {
                                        string[] ary = brand.Split('/');
                                        tcData3.InnerText = ary[3].ToString(); // e.g. http://ts/one fourth index will contain the brand
                                    }
                                    catch  //the url may not contain the brand for instance the top level site
                                    {
                                        tcData3 .InnerText = "na";
                                    }
                                    trData.Cells.Add(tcData3);

                                    //teamsite users fullname
                                    HtmlTableCell tcData4 = new HtmlTableCell();
                                    tcData4.InnerText = user.Name;
                                    tcData4.BgColor = roleStyle;
                                    trData.Cells.Add(tcData4);

                                    //teamsite user lanId
                                    HtmlTableCell tcData5 = new HtmlTableCell();
                                    tcData5.InnerText = user.LoginName;
                                    tcData5.BgColor = roleStyle;
                                    trData.Cells.Add(tcData5);

                                    //teamsite user email address
                                    HtmlTableCell tcData6 = new HtmlTableCell();
                                    HtmlAnchor haEmail = new HtmlAnchor();
                                    haEmail.InnerText="mailto:"+user.Email;
                                    haEmail.HRef=user.Email;
                                    tcData6.Controls.Add(haEmail);
                                    tcData6.InnerText = user.Email ;  //email
                                    trData.Cells.Add(tcData6);

                                    //teamsite request for access email address
                                    HtmlTableCell tcData8 = new HtmlTableCell();
                                    try
                                    {

                                        SPPermissionCollection permsSite = site.Permissions;

                                        if (permsSite.RequestAccess)
                                        {
                                            tcData8.InnerText = permsSite.RequestAccessEmail.ToString();
                                        }
                                        else
                                        {
                                            tcData8.InnerText = "";
                                        }
                                    }
                                    catch //
                                    {
                                        tcData8.BgColor = "#FF0000";
                                        tcData8.InnerText = "permissions error";
                                    }

                                    trData.Cells.Add(tcData8);

                                    //teamsite memebrship count
                                    HtmlTableCell tcData9 = new HtmlTableCell();
                                    tcData9.InnerText = site.Users.Count.ToString();
                                    trData.Cells.Add(tcData9);

                                    //subsites

                                    HtmlTableCell tcData10 = new HtmlTableCell();
                                    tcData10.InnerText = subsitesCount.ToString();
                                    if (subsitesCount>0)
                                        tcData10.BgColor = System.Drawing.ColorTranslator.ToHtml (System.Drawing.Color.Red);
                                    trData.Cells.Add(tcData10);

                                    reportHtmlTable.Rows.Add(trData);

                                }
                            }
                            site.Dispose();
                        }
                    }
                    catch(Exception ex)
                    {
                        FileErrorLogger _logger = new FileErrorLogger();
                        _logger.LogError(ex.Message, ErrorLogSeverity.SeverityError,
                            ErrorType.TypeApplication, "Centrica.Intranet.TeamSiteReports.UploadFile()");
                        _logger = null;					}
                    finally
                    {
                        site.Dispose();
                    }

                }
            }
            catch (Exception ex)
            {
                FileErrorLogger _logger = new FileErrorLogger();
                _logger.LogError(ex.Message, ErrorLogSeverity.SeverityError,
                    ErrorType.TypeApplication, "Centrica.Intranet.TeamSiteReports.UploadFile()");
                _logger = null;
            }
            finally
            {
                siteCollection.Dispose();
            }

            reportHtmlTable.RenderControl(txtWriter);

            txtWriter.Close();
            tf.UploadFile(System.Configuration.ConfigurationSettings.AppSettings["TeamSiteReports.TeamSiteOwnersReportLocation"],
                System.Configuration.ConfigurationSettings.AppSettings["TeamSiteReports.TeamSiteOwnersReportDestination"]);
            Console.WriteLine("Completed");
        }
        public static void DeleteInactiveSites()
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate () {
                    SPSite selectedSite = new SPSite("http://abcuniversity/sitedefinition1");
                    Console.WriteLine("Site pegged for deletion: {0}", selectedSite.RootWeb.GetSubwebsForCurrentUser()[0].Url);
                    selectedSite.RootWeb.GetSubwebsForCurrentUser()[0].Delete();
                    selectedSite.Dispose();


                });
                Console.WriteLine("Site deleted!");
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }