当前位置: 首页>>代码示例>>C#>>正文


C# SPSite.Dispose方法代码示例

本文整理汇总了C#中SPSite.Dispose方法的典型用法代码示例。如果您正苦于以下问题:C# SPSite.Dispose方法的具体用法?C# SPSite.Dispose怎么用?C# SPSite.Dispose使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在SPSite的用法示例。


在下文中一共展示了SPSite.Dispose方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Main

        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();
            }
        }
开发者ID:SSabet,项目名称:SP2013-Short-Course,代码行数:29,代码来源:Program.cs

示例2: FeatureDeactivating

        // 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;
        }
开发者ID:iohn2000,项目名称:gsa-custom-searchbox.spmaster,代码行数:31,代码来源:InternalGSABoxActivateOnAllSubSites.EventReceiver.cs

示例3: UploadFile

        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();

            }
        }
开发者ID:tristian2,项目名称:SharePointVarious,代码行数:45,代码来源:TeamsiteFile.cs

示例4: OnSubmitFile

        /// <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;
        }
开发者ID:GSoft-SharePoint,项目名称:Dynamite-2010-Example-ContentOrganizer,代码行数:86,代码来源:MyRouter1.cs

示例5: authenticateAgainstSite

        // 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;
        }
开发者ID:vjohnson01,项目名称:Tools,代码行数:69,代码来源:frmContentDeployer.cs

示例6: IsFeatureActivatedOnSite

 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();
     }
 }
开发者ID:CherifSy,项目名称:sharepointinstaller,代码行数:15,代码来源:ActivationCommands.cs

示例7: Execute

            /// <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
//.........这里部分代码省略.........
开发者ID:CherifSy,项目名称:sharepointinstaller,代码行数:101,代码来源:ActivationCommands.cs

示例8: Main

        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);
//.........这里部分代码省略.........
开发者ID:vjohnson01,项目名称:Tools,代码行数:101,代码来源:Program.cs

示例9: GenerateReport


//.........这里部分代码省略.........
            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"]);
        }
开发者ID:tristian2,项目名称:SharePointVarious,代码行数:101,代码来源:ReportTeamSiteLastModified.cs

示例10: GenerateReport


//.........这里部分代码省略.........
            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"]);
        }
开发者ID:tristian2,项目名称:SharePointVarious,代码行数:101,代码来源:ReportTeamSiteSize.cs

示例11: BreakInheritance

        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.");



            });
        }
开发者ID:karayakar,项目名称:MCSD_SharePoint_Applications,代码行数:29,代码来源:Program.cs

示例12: Execute

        /// <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;
        }
开发者ID:GSoft-SharePoint,项目名称:PowerShell-SPCmdlets,代码行数:74,代码来源:ReGhostFile.cs

示例13: UpdateMeta

        /// <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);
            }
        }
开发者ID:BGCX261,项目名称:zhoulijinrong-svn-to-git,代码行数:56,代码来源:DocumentManager.cs

示例14: ReportActivations

 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();
         }
     }
 }
开发者ID:SharePointPog,项目名称:sharepointinstaller,代码行数:68,代码来源:ActivationReporter.cs

示例15: GenerateReport


//.........这里部分代码省略.........
                                    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"]);
        }
开发者ID:tristian2,项目名称:SharePointVarious,代码行数:101,代码来源:ReportTeamSiteSubSite.cs


注:本文中的SPSite.Dispose方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。