Exemple #1
0
        protected override void InternalValidate()
        {
            if (TargetUrl != null)
            {
                TargetUrl = TargetUrl.Trim();
                siteUri   = new Uri(TargetUrl, UriKind.Absolute);
                if (!Uri.UriSchemeHttps.Equals(siteUri.Scheme, StringComparison.OrdinalIgnoreCase) && !Uri.UriSchemeHttp.Equals(siteUri.Scheme, StringComparison.OrdinalIgnoreCase))
                {
                    throw new ArgumentException("The specified target URL is not valid.");
                }
            }
            string serverRelUrlFromFullUrl = Utilities.GetServerRelUrlFromFullUrl(TargetUrl);
            string siteRoot = null;

            if (this.HostHeaderWebApplication == null)
            {
                webApp   = new SPWebApplicationPipeBind(TargetUrl).Read(false);
                siteRoot = Utilities.FindSiteRoot(webApp.Prefixes, serverRelUrlFromFullUrl);
                if ((siteRoot == null) || !siteRoot.Equals(serverRelUrlFromFullUrl, StringComparison.OrdinalIgnoreCase))
                {
                    throw new SPCmdletException("A managed path for the site could not be found.");
                }
            }
            else
            {
                webApp = this.HostHeaderWebApplication.Read();
                useHostHeaderAsSiteName = true;
                SPWebService service = SPFarm.Local.Services.GetValue <SPWebService>();
                if (service == null)
                {
                    throw new InvalidOperationException("A default web service could not be found.");
                }
                siteRoot = Utilities.FindSiteRoot(service.HostHeaderPrefixes, serverRelUrlFromFullUrl);
                if ((siteRoot == null) || !siteRoot.Equals(serverRelUrlFromFullUrl, StringComparison.OrdinalIgnoreCase))
                {
                    throw new SPCmdletException("A managed path for the site could not be found.");
                }
            }
            if (this.ContentDatabase != null)
            {
                this.contentDb = this.ContentDatabase.Read();
                if (null == this.contentDb)
                {
                    throw new SPException("The specified content database could not be found.");
                }
            }
            if (this.QuotaTemplate != null)
            {
                quotaTemplate = this.QuotaTemplate.Read().Name;
            }
            if (this.SiteSubscription != null)
            {
                this.siteSubscription = this.SiteSubscription.Read();
                if (this.siteSubscription == null)
                {
                    base.WriteError(new ArgumentException("The provided site subscription object is invalid."), ErrorCategory.InvalidArgument, this);
                    base.SkipProcessCurrentRecord();
                }
            }
        }
Exemple #2
0
        public static List <AttributeValuePair> GetSPContentDatabaseAttributes(SPContentDatabase contentDatabase)
        {
            List <AttributeValuePair> contentDatabaseAttributes = new List <AttributeValuePair>();

            try
            {
                contentDatabaseAttributes.Add(new AttributeValuePair("Id", contentDatabase.Id.ToString()));
                contentDatabaseAttributes.Add(new AttributeValuePair("DisplayName", contentDatabase.DisplayName));
                contentDatabaseAttributes.Add(new AttributeValuePair("Name", contentDatabase.Name));
                contentDatabaseAttributes.Add(new AttributeValuePair("Server", contentDatabase.Server));
                contentDatabaseAttributes.Add(new AttributeValuePair("ConnectionString", contentDatabase.DatabaseConnectionString));
                contentDatabaseAttributes.Add(new AttributeValuePair("Status", contentDatabase.Status.ToString()));
                contentDatabaseAttributes.Add(new AttributeValuePair("DiskSizeRequired", (contentDatabase.DiskSizeRequired / 1024 / 1024).ToString() + " MB"));
                contentDatabaseAttributes.Add(new AttributeValuePair("CurrentSiteCount", contentDatabase.CurrentSiteCount.ToString()));
                contentDatabaseAttributes.Add(new AttributeValuePair("WarningSiteCount", contentDatabase.WarningSiteCount.ToString()));
                contentDatabaseAttributes.Add(new AttributeValuePair("MaximumSiteCount", contentDatabase.MaximumSiteCount.ToString()));
                if (contentDatabase.Username != null)
                {
                    contentDatabaseAttributes.Add(new AttributeValuePair("Username", contentDatabase.Username));
                    contentDatabaseAttributes.Add(new AttributeValuePair("Password", contentDatabase.Password));
                }
            }
            catch (Exception e)
            {
                contentDatabaseAttributes.Add(new AttributeValuePair("Exception", e.ToString()));
            }
            return(contentDatabaseAttributes);
        }
        private static SPSite CreateSite(SPWebApplication webApp, string dbname, SPSiteSubscription siteSubscription, string webTemplate, string title, string description, string ownerName, string ownerEmail, string quota, string secondaryContactName, string secondaryContactEmail, bool useHostHeaderAsSiteName, uint nLCID, Uri uri, string ownerLogin, string secondaryContactLogin)
        {
            Logger.Write("PROGRESS: Getting content database...");
            SPContentDatabase database = null;

            if (!string.IsNullOrEmpty(dbname))
            {
                foreach (SPContentDatabase tempDB in webApp.ContentDatabases)
                {
                    if (tempDB.Name.ToLower() == dbname.ToLower())
                    {
                        database = tempDB;
                        break;
                    }
                }
                if (database == null)
                {
                    throw new SPException("Content database not found.");
                }
            }

            SPSite site = CreateSite(webApp, siteSubscription, webTemplate, title, description, ownerName, ownerEmail, quota, secondaryContactName, secondaryContactEmail, useHostHeaderAsSiteName, nLCID, uri, ownerLogin, secondaryContactLogin, database);

            if (useHostHeaderAsSiteName && !webApp.IisSettings[SPUrlZone.Default].DisableKerberos)
            {
                Logger.Write(SPResource.GetString("WarnNoDefaultNTLM", new object[0]));
            }

            return(site);
        }
Exemple #4
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;
        }
Exemple #5
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;
        }
Exemple #6
0
        public override void Execute(Guid targetInstanceId)
        {
            base.Execute(targetInstanceId);
            List <string>     emailTo   = new List <string>();
            SPWebApplication  webApp    = this.Parent as SPWebApplication;
            SPContentDatabase contentDB = webApp.ContentDatabases[targetInstanceId];

            if (contentDB == null)
            {
                contentDB = webApp.ContentDatabases[0];
            }
            SPWeb web = contentDB.Sites[0].RootWeb;


            // 取参数,通过Properties可以从外部传递参数,但要求参数可以被序列化和反列化
            string siteUrl = this.Properties["SiteUrl"].ToString();
            //上面的内容没有用到

            string  userName  = "******";
            string  showUrl   = ConfigurationManager.AppSettings["retUrl"];
            int     delayDays = int.Parse(System.Configuration.ConfigurationManager.AppSettings["delayDays"]);
            SPList  oList     = web.Lists.TryGetList("讨论列表");
            SPQuery oQuery    = new SPQuery();

            oQuery.Query = "<Where><And><Eq><FieldRef Name='Author' /><Value Type='User'>" + userName + "</Value></Eq><Geq><FieldRef Name='Created'/><Value Type='DateTime'>" + DateTime.Today.AddDays(-delayDays).ToString("yyyy-MM-dd") + "</Value></Geq></And></Where>";
            SPListItemCollection lstItems = oList.GetItems(oQuery);

            if (lstItems.Count == 0)
            {
            }
        }
        public override void Execute(Guid contentDbId)
        {
            // get a reference to the current site collection's content database

            var webApplication = Parent as SPWebApplication;

            if (webApplication != null)
            {
                SPContentDatabase contentDb = webApplication.ContentDatabases[contentDbId];

                SPWeb objWeb = contentDb.Sites[0].RootWeb;

                DateTime objTiSiteCreationtime = objWeb.Created;

                SPList taskList = contentDb.Sites[0].RootWeb.Lists["Tasks"];


                var objQuery = new SPQuery();

                objQuery.Query = "<Where><Gt><FieldRef Name=\"ID\"/><Value Type=\"Counter\">0</Value></Gt></Where>";

                SPListItemCollection objCollection = taskList.GetItems(objQuery);

                DataTable dtAllLists = objCollection.GetDataTable();

                var objArrayList = new ArrayList();

                if (dtAllLists != null)
                {
                    if (dtAllLists.Rows.Count > 0)
                    {
                        for (int iCnt = 0; iCnt <= dtAllLists.Rows.Count - 1; iCnt++)
                        {
                            objArrayList.Add(Convert.ToString(dtAllLists.Rows[iCnt]["Title"]));
                        }
                    }
                }


                for (int iCnt = 0; iCnt <= objWeb.Lists.Count - 1; iCnt++)
                {
                    if (!objArrayList.Contains(objWeb.Lists[iCnt].Title))
                    {
                        if (objWeb.Lists[iCnt].Created.ToShortDateString()
                            != objTiSiteCreationtime.ToShortDateString())
                        {
                            SPListItem newTask = taskList.Items.Add();

                            newTask["Title"] = objWeb.Lists[iCnt].Title;

                            newTask.Update();
                            //Write a logic to send a mail to admin
                        }
                    }
                }
            }
        }
        protected override bool ProcessWorkItem(SPContentDatabase contentDatabase, SPWorkItemCollection workItems, SPWorkItem workItem, SPJobState jobState)
        {
            using (var site = new SPSite(workItem.SiteId))
            {
                using (SPWeb web = site.OpenWeb(workItem.WebId))
                {
                    workItems.SubCollection(site, web, 0, (uint)workItems.Count).DeleteWorkItem(workItem.Id);
                }
            }

            try
            {
                var stringSeparators = new string[] { "-#####-" };

                string[] cmds = workItem.TextPayload.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);

                SPWebApplication webApp = SPWebApplication.Lookup(new Uri(cmds[0]));

                SPIisSettings iis = webApp.IisSettings[SPUrlZone.Default];

                string port;

                if (iis.ServerBindings.Count > 0)
                {
                    port = iis.ServerBindings[0].Port.ToString();
                }
                else
                {
                    string path = iis.Path.ToString();
                    port = path.Substring(path.LastIndexOf('\\') + 1);
                }

                if (!string.IsNullOrEmpty(port))
                {
                    port = ":" + port;
                }

                var reloadCacheTimerJob = new ReloadCacheTimerJob("Oceanik.ReloadCacheJob" + Guid.NewGuid(), webApp, null, SPJobLockType.None)
                {
                    Schedule = new SPOneTimeSchedule(DateTime.Now)
                };

                string command = "http://localhost" + port + cmds[1];
                reloadCacheTimerJob.Properties.Add("CMD", command);

                reloadCacheTimerJob.Update();

                SPSecurity.RunWithElevatedPrivileges(() => EventLog.WriteEntry("ReloadCacheJobDefinition.ProcessWorkItem.ExecuteCommand", command, EventLogEntryType.Information));
            }
            catch (Exception ex)
            {
                SPSecurity.RunWithElevatedPrivileges(() => EventLog.WriteEntry("ReloadCacheJobDefinition.ProcessWorkItem", ex.Message, EventLogEntryType.Error));
            }

            return(true);
        }
Exemple #9
0
        public SPContentDatabaseInstance(ObjectInstance prototype, SPContentDatabase sPContentDatabase)
            : this(prototype)
        {
            if (sPContentDatabase == null)
            {
                throw new ArgumentNullException("sPContentDatabase");
            }

            m_contentDatabase = sPContentDatabase;
        }
Exemple #10
0
        private SPContentDatabase EnsureTestContentDatabase(SPWebApplication defaultPortWebApp)
        {
            SPContentDatabaseCollection databaseCollection = defaultPortWebApp.ContentDatabases;

            SPContentDatabase defaultWebAppContentDatabase = defaultPortWebApp.ContentDatabases[0];
            SPContentDatabase testContentDb = databaseCollection.Cast <SPContentDatabase>().FirstOrDefault(db => db.Name == TestContentDatabaseName);

            if (testContentDb != null)
            {
                // DB already exists, we gotta figure out if it's getting bloated or not.
                // A typical Content Database will weigh in at a almost 160MB right at the start.
                // After creating a couple of hundred site collection, even if we  delete them
                // everytime, some space gets wasted and the disk size required for a backup
                // grows to more than 200MB.
                const ulong MaxNumberOfMb = 200;
                if (testContentDb.DiskSizeRequired > MaxNumberOfMb * 1024 * 1024)
                {
                    // Repeated site collection recreation has left behind traces
                    // in the content database, time to delete it and start fresh
                    foreach (SPSite site in testContentDb.Sites)
                    {
                        // Delete any straggling site collection (and hope to god no one has
                        // piggybacked onto our content database with an important site collection
                        // of their own - their loss, anyway)
                        site.Delete();
                    }

                    testContentDb.Status = SPObjectStatus.Offline;
                    testContentDb.Unprovision();
                    databaseCollection.Delete(testContentDb.Id);
                    testContentDb = null;
                }
                else
                {
                    // We haven't hit the size limit yet, let's re-use the same content database
                    // ...
                }
            }

            if (testContentDb == null)
            {
                // DB doesn't exist yet (or has just been deleted): we should (re)create it.
                testContentDb = databaseCollection.Add(
                    defaultWebAppContentDatabase.Server,
                    TestContentDatabaseName,
                    defaultWebAppContentDatabase.Username,
                    defaultWebAppContentDatabase.Password,
                    2000,
                    5000,
                    0);       // Status = 0 means the database is READY (instead of OFFLINE, which is Status = 1)
            }

            return(testContentDb);
        }
Exemple #11
0
        // current jobs site guid
        public override void Execute(Guid contentDbId)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                // get a reference to the current site collection's content database
                SPList objList = null;

                SPWebApplication webApplication = this.Parent as SPWebApplication;
                SPContentDatabase contentDb     = webApplication.ContentDatabases[contentDbId];


                // read the source information
                XmlDocument xDocs = new XmlDocument();
                xDocs.Load(@"C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\XML\TimerSource.xml");

                XmlNodeList nodeList;
                XmlNode root = xDocs.DocumentElement;
                nodeList     = root.SelectNodes("descendant::SOURCE/DOCUMENT[@name]");

                // Change the price on the books.
                foreach (XmlNode source in nodeList)
                {
                    //source.Attributes["name"].Value.ToString();
                    //source.Attributes["url"].Value.ToString();
                    //source.Attributes["guid"].Value.ToString();

                    // get a reference to the Document Library in the RootWeb of the first site collection in the content database
                    objList = contentDb.Sites[0].RootWeb.Lists[source.Attributes["name"].Value.ToString()];

                    SPListItemCollection listItems = objList.Items;
                    int itemCount = listItems.Count;

                    // build the output XML

                    XmlDocument xoutDoc = new XmlDocument();
                    XmlElement xoEle    = xoutDoc.CreateElement("DOCUMENTDETAILS");

                    for (int k = 0; k < itemCount; k++)
                    {
                        SPListItem item = listItems[k];

                        xoEle.SetAttribute("Title", item.Title.ToString());
                        xoEle.SetAttribute("Name", item.Name.ToString());
                        xoEle.SetAttribute("URL", item.Url.ToString());
                        xoEle.SetAttribute("Guid", item.UniqueId.ToString());
                        xoEle.SetAttribute("Properties", item.Properties.Values.ToString());
                        xoutDoc.AppendChild(xoEle);
                    }

                    // local path
                    xoutDoc.Save(@"c:/DocumentDetails.xml");
                }
            });
        }
Exemple #12
0
        protected override bool ProcessWorkItem(SPContentDatabase contentDb, SPWorkItemCollection workItems,
                                                SPWorkItem workItem, SPJobState jobState)
        {
            if (workItem == null)
            {
                throw new ArgumentException("workItem is null");
            }
            try
            {
                using (SPSite site = new SPSite(workItem.SiteId))
                {
                    using (SPWeb web = site.OpenWeb(workItem.WebId))
                    {
                        try
                        {
                            //TODO CODE HERE
                            SPList     list     = web.Lists[workItem.ParentId];
                            SPListItem listItem = list.GetItemByUniqueId(workItem.ItemGuid);

                            SPList subList  = web.Lists["SubscriberList"];
                            SPList elements = web.Lists["SubscribeElementList"];
                            //TODO Rewrite to caml
                            for (int i = 0; i < subList.ItemCount; i++)
                            {
                                SPListItem item = subList.Items[i];
                                if (workItem.UserId == (int)item["User"])
                                {
                                    SPListItem newSubItem = elements.Items.Add();
                                    newSubItem["User"]   = workItem.UserId;
                                    newSubItem["NewsID"] = listItem["ID"];
                                    newSubItem["Readed"] = false;
                                    newSubItem.Update();
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            throw e;
                        }
                        finally
                        {
                            workItems.SubCollection(site, web, 0, (uint)workItems.Count).DeleteWorkItem(workItem.Id);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                throw e;
            }

            return(true);
        }
Exemple #13
0
        public override void Execute(Guid contentDbId)
        {
            SPWebApplication  webApplication = Parent as SPWebApplication;
            SPContentDatabase contentDb      = webApplication.ContentDatabases[contentDbId];

            SPWeb  web  = contentDb.Sites[0].RootWeb;
            SPList list = EnsureList(web);

            SPListItem item = list.Items.Add();

            item["Title"] = string.Format("Timer Job was executed at : {0}", DateTime.Now.ToString());
            item.Update();
        }
Exemple #14
0
        protected override bool ProcessWorkItem(SPContentDatabase contentDatabase,
                                                Microsoft.SharePoint.SPWorkItemCollection workItems,
                                                Microsoft.SharePoint.SPWorkItem workItem, SPJobState jobState)
        {
            // process the workItem
            using (var site = new SPSite(workItem.SiteId))
            {
                using (var web = site.OpenWeb(workItem.WebId))
                {
                    //var logEntry = IronLogger.Entry.Base64Deserialize(workItem.TextPayload);

                    if (true)//logEntry.Level <= WebLogLevel(web))
                    {
                        SPDocumentLibrary logLib = null;
                        try
                        {
                            logLib = (SPDocumentLibrary)web.GetList(web.ServerRelativeUrl + "/" + IronConstant.IronLogsListPath);
                        }
                        catch (Exception ex)
                        {
                            throw new SPException("Couldn't find IronLog document library", ex);
                            throw ex;
                        }
                        if (logLib != null)
                        {
                            var logFileCandidates = logLib.GetItems(LogFileQuery(2));
                            if (logFileCandidates.Count > 0)
                            {
                                var logFile = logFileCandidates[0].File;
                                AppendToFile(logFile, workItem.TextPayload);
                            }
                            else
                            {
                                var url = DateTime.Now.ToString("s").Replace(":", "_");
                                url = string.Format("{0}.log", url);

                                logLib.RootFolder.Files.Add(url, GetBytes(workItem.TextPayload));
                            }
                        }
                    }
                    // delete the workItem after we've processed it
                    workItems.SubCollection(site, web, 0,
                                            (uint)workItems.Count).DeleteWorkItem(workItem.Id);
                }
            }

            // returning true allows the timer job to process additional items in the queue
            // returning false will end this occurance of the timer job
            return(true);
        }
Exemple #15
0
        public override void Execute(Guid contentDBID)
        {
            SPWebApplication webApplication = (SPWebApplication)Parent;

            SPContentDatabase contentDb = webApplication.ContentDatabases[contentDBID];

            string url = contentDb.Sites[0].RootWeb.Url;

            WebRequest request = WebRequest.Create(url);

            request.Credentials = CredentialCache.DefaultCredentials;

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        }
        protected override bool ProcessWorkItem(SPContentDatabase contentDatabase,
                                                Microsoft.SharePoint.SPWorkItemCollection workItems,
                                                Microsoft.SharePoint.SPWorkItem workItem, SPJobState jobState)
        {
            // process the workItem
            using (var site = new SPSite(workItem.SiteId))
            {
                using (var web = site.OpenWeb(workItem.WebId))
                {
                    //var logEntry = IronLogger.Entry.Base64Deserialize(workItem.TextPayload);

                    if (true)//logEntry.Level <= WebLogLevel(web))
                    {
                        SPDocumentLibrary logLib = null;
                        try
                        {
                            logLib = (SPDocumentLibrary)web.GetList(web.ServerRelativeUrl + "/" + IronConstant.IronLogsListPath);
                        }
                        catch (Exception ex)
                        {
                            throw new SPException("Couldn't find IronLog document library", ex);
                            throw ex;
                        }
                        if (logLib != null)
                        {
                            var logFileCandidates = logLib.GetItems(LogFileQuery(2));
                            if (logFileCandidates.Count > 0)
                            {
                                var logFile = logFileCandidates[0].File;
                                AppendToFile(logFile, workItem.TextPayload);
                            }
                            else
                            {
                                var url = DateTime.Now.ToString("s").Replace(":", "_");
                                url = string.Format("{0}.log", url);

                                logLib.RootFolder.Files.Add(url, GetBytes(workItem.TextPayload));
                            }
                        }
                    }
                    // delete the workItem after we've processed it
                    workItems.SubCollection(site, web, 0,
                                            (uint) workItems.Count).DeleteWorkItem(workItem.Id);
                }
            }

            // returning true allows the timer job to process additional items in the queue
            // returning false will end this occurance of the timer job
            return true;
        }
        public override void Execute(Guid targetInstanceId)
        {
            SPWebApplication  webapp    = this.Parent as SPWebApplication;
            SPContentDatabase contentDB = webapp.ContentDatabases[targetInstanceId];

            SPList list = contentDB.Sites[0].RootWeb.Lists["MyStatList"];
            SPListItemCollection itemcoll = list.Items;

            for (int i = 0; i < itemcoll.Count; i++)
            {
                SPListItem item = list.GetItemById(itemcoll[i].ID);
                item["Title"] = "The Items's ID is" + item.ID;
                item.SystemUpdate();
            }
            //base.Execute(targetInstanceId);
        }
        /// <summary>
        /// Backups the site.
        /// </summary>
        /// <param name="site">The site.</param>
        private void BackupSiteCore(SPSite site)
        {
            string path = Path.Combine(_path, EncodePath(site.Url.ToString())) + ".bak";

            Logger.Write("Backing up site '{0}' to '{1}'", site.Url, path);

            if (!_useSnapshot)
            {
                bool writeLock = site.WriteLocked;
                if (!_noSiteLock)
                {
                    site.WriteLocked = true;
                }
                try
                {
                    site.WebApplication.Sites.Backup(site.Url, path, _overwrite);
                }
                finally
                {
                    if (!_noSiteLock)
                    {
                        site.WriteLocked = writeLock;
                    }
                }
            }
            else
            {
                SPDatabaseSnapshot snapshot = null;
                try
                {
                    snapshot = site.ContentDatabase.Snapshots.CreateSnapshot();
                    SPContentDatabase database   = SPContentDatabase.CreateUnattachedContentDatabase(snapshot.ConnectionString);
                    string            strSiteUrl = site.HostHeaderIsSiteName ? site.Url.ToString() : site.ServerRelativeUrl;
                    database.Sites.Backup(strSiteUrl, path, _overwrite);
                }
                finally
                {
                    if (snapshot != null)
                    {
                        snapshot.Delete();
                    }
                }
            }
        }
Exemple #19
0
        public override void Execute(Guid targetInstanceId)
        {
            //Get the Web Application in which this Timer Job runs
            SPWebApplication  webApp              = this.Parent as SPWebApplication;
            SPContentDatabase contentDB           = webApp.ContentDatabases[targetInstanceId];
            SPSiteCollection  timerSiteCollection = webApp.ContentDatabases[targetInstanceId].Sites;
            SPList            timerJobList        = null;

            foreach (SPSite site in timerSiteCollection)
            {
                timerJobList = site.RootWeb.Lists.TryGetList("Announcements");
                if (timerJobList != null)
                {
                    SPListItem newItem = timerJobList.Items.Add();
                    newItem["Title"] = "Today is " + getToday();
                    newItem.Update();
                }
            }
        }
        public override void Execute(Guid contentDbId)
        {
            // get a reference to the current site collection's content database

            SPWebApplication webApplication = this.Parent as SPWebApplication;

            SPContentDatabase contentDb = webApplication.ContentDatabases[contentDbId];

            // get a reference to the "ListTimerJob" list in the RootWeb of the first site collection in the content database

            SPList Listjob = contentDb.Sites[0].RootWeb.Lists["ListTimerJob"];

            // create a new list Item, set the Title to the current day/time, and update the item

            SPListItem newList = Listjob.Items.Add();

            newList["Title"] = DateTime.Now.ToString();

            newList.Update();
        }
Exemple #21
0
        public override void Execute(Guid targetInstanceId)
        {
            base.Execute(targetInstanceId);
            List <string>     emailTo   = new List <string>();
            SPWebApplication  webApp    = this.Parent as SPWebApplication;
            SPContentDatabase contentDB = webApp.ContentDatabases[targetInstanceId];

            if (contentDB == null)
            {
                contentDB = webApp.ContentDatabases[0];
            }
            SPWeb web = contentDB.Sites[0].RootWeb;


            // 取参数,通过Properties可以从外部传递参数,但要求参数可以被序列化和反列化
            string siteUrl = this.Properties["SiteUrl"].ToString();
            //上面的内容没有用到

            string  disPlayName = ConfigurationManager.AppSettings["emailDisplayName"];
            string  title       = ConfigurationManager.AppSettings["emailTitle"];
            string  body        = ConfigurationManager.AppSettings["emailBody"];
            string  showUrl     = ConfigurationManager.AppSettings["retUrl"];
            int     delayDays   = int.Parse(System.Configuration.ConfigurationManager.AppSettings["delayDays"]);
            SPList  oList       = web.Lists.TryGetList("讨论列表");
            SPQuery oQuery      = new SPQuery();
            string  userName    = "******";

            emailTo.Add("*****@*****.**");
            oQuery.Query = "<Where><And><Eq><FieldRef Name='Author' /><Value Type='User'>" + userName + "</Value></Eq><Geq><FieldRef Name='Created'/><Value Type='DateTime'>" + DateTime.Today.AddDays(-delayDays).ToString("yyyy-MM-dd") + "</Value></Geq></And></Where>";
            SPListItemCollection lstItems = oList.GetItems(oQuery);

            if (lstItems.Count == 0)
            {
                //实现自己业务逻辑,找出复合条件的并发mail做相关通知。
                bool sendOk = SendMail("*****@*****.**", disPlayName, "110004cc", emailTo.ToArray(), title, body);
            }
        }
        public override void Execute(Guid contentDbId)
        {
            string from        = string.Empty;
            string smtpAddress = string.Empty;
            string to          = "michael.dockray@nerconet";
            string subject     = "Email for MonkeyPants";
            string body        = "<h1> Monkeys Rock !!!! , Email Sending from Testing My Timer Job</h1>";

            SPSecurity.RunWithElevatedPrivileges(delegate() {
                // get a reference to the current site collection's content database
                SPWebApplication webApplication = this.Parent as SPWebApplication;
                SPContentDatabase contentDb     = webApplication.ContentDatabases[contentDbId];

                // get a reference to the "Tasks" list in the RootWeb of the first site collection in the content database
                SPWeb rootWeb = contentDb.Sites[0].RootWeb;

                // Get the DB News Announcements List
                SPList listjob = rootWeb.Lists.TryGetList("Tasks");

                // Get sender address from web application settings
                from = rootWeb.Site.WebApplication.OutboundMailSenderAddress;

                // Get SMTP address from web application settings
                smtpAddress = rootWeb.Site.WebApplication.OutboundMailServiceInstance.Server.Address;

                // Send an email if the news is approved
                bool emailSent = SendMail(smtpAddress, subject, body, true, from, to, null, null);

                if (listjob != null && emailSent)
                {
                    SPListItem newListItem = listjob.Items.Add();
                    newListItem["Title"]   = string.Concat("Email Notification Sent at : ", DateTime.Now.ToString());
                    newListItem.Update();
                }
            });
        }
Exemple #23
0
        /// <summary>
        /// Performs the export.
        /// </summary>
        /// <param name="export">The export.</param>
        /// <param name="exportObject">The export object.</param>
        /// <param name="settings">The settings.</param>
        /// <param name="logFile">if set to <c>true</c> [log file].</param>
        /// <param name="quiet">if set to <c>true</c> [quiet].</param>
        /// <param name="url">The URL.</param>
        internal static void PerformExport(SPExport export, SPExportObject exportObject, SPExportSettings settings, bool logFile, bool quiet, string url, bool useSqlSnapshot)
        {
            SPDatabaseSnapshot snapshot = null;

            using (SPSite site = new SPSite(url))
            {
                ValidateUser(site);

                if (!useSqlSnapshot)
                {
                    settings.SiteUrl = site.Url;
                }
                else
                {
                    snapshot = site.ContentDatabase.Snapshots.CreateSnapshot();
                    SPContentDatabase database2 = SPContentDatabase.CreateUnattachedContentDatabase(snapshot.ConnectionString);
                    settings.UnattachedContentDatabase = database2;
                    settings.SiteUrl = database2.Sites[site.ServerRelativeUrl].Url;
                }

                using (SPWeb web = site.OpenWeb())
                {
                    SPList list = Utilities.GetListFromViewUrl(web, url);

                    if (list == null)
                    {
                        throw new Exception("List not found.");
                    }

                    settings.SiteUrl = web.Url;
                    exportObject.Id  = list.ID;
                }

                settings.ExportObjects.Add(exportObject);


                try
                {
                    export.Run();
                    if (!quiet)
                    {
                        ArrayList dataFiles = settings.DataFiles;
                        if (dataFiles != null)
                        {
                            Console.WriteLine();
                            Console.WriteLine("File(s) generated: ");
                            for (int i = 0; i < dataFiles.Count; i++)
                            {
                                Console.WriteLine("\t{0}", Path.Combine(settings.FileLocation, (string)dataFiles[i]));
                                Console.WriteLine();
                            }
                            Console.WriteLine();
                        }
                    }
                }
                finally
                {
                    if (useSqlSnapshot && (snapshot != null))
                    {
                        snapshot.Delete();
                    }

                    if (logFile)
                    {
                        Console.WriteLine();
                        Console.WriteLine("Log file generated: ");
                        Console.WriteLine("\t{0}", settings.LogFilePath);
                    }
                }
            }
        }
        /// <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, StringDictionary keyValues, out string output)
        {
            output         = string.Empty;
            Logger.Verbose = true;

            if (Params["setmaxsitestocurrent"].UserTypedIn && Params["maxsites"].UserTypedIn)
            {
                throw new SPException(SPResource.GetString("ExclusiveArgs", new object[] { "setmaxsitestocurrent, maxsites" }));
            }

            string dbname = Params["dbname"].Value;

            SPWebApplication  webApp = SPWebApplication.Lookup(new Uri(Params["webapp"].Value));
            SPContentDatabase db     = null;

            foreach (SPContentDatabase tempDB in webApp.ContentDatabases)
            {
                if (tempDB.Name.ToLower() == dbname.ToLower())
                {
                    db = tempDB;
                    break;
                }
            }
            if (db == null)
            {
                throw new Exception("Content database not found.");
            }

            bool modified = false;

            if (Params["status"].UserTypedIn)
            {
                db.Status = (SPObjectStatus)Enum.Parse(typeof(SPObjectStatus), Params["status"].Value, true);
                modified  = true;
            }

            if (Params["maxsites"].UserTypedIn)
            {
                db.MaximumSiteCount = int.Parse(Params["maxsites"].Value);
                modified            = true;
            }
            else if (Params["setmaxsitestocurrent"].UserTypedIn)
            {
                if (db.CurrentSiteCount < db.WarningSiteCount)
                {
                    db.WarningSiteCount = db.CurrentSiteCount - 1;
                }
                db.MaximumSiteCount = db.CurrentSiteCount;

                modified = true;
            }

            if (Params["warningsitecount"].UserTypedIn)
            {
                db.WarningSiteCount = int.Parse(Params["warningsitecount"].Value);
                modified            = true;
            }

            if (Params["searchserver"].UserTypedIn && !string.IsNullOrEmpty(Params["searchserver"].Value))
            {
                // If they specified a search server then we need to try and find a valid
                // matching search server using the server address property.
#if SP2010
                SPSearchService service = SPFarm.Local.Services.GetValue <SPSearchService>("SPSearch");
#elif SP2013
                SPSearchService service = SPFarm.Local.Services.GetValue <SPSearchService>("SPSearch4");
#endif
                SPServiceInstance searchServiceServer = null;
                foreach (SPServiceInstance tempsvc in service.Instances)
                {
                    if (!(tempsvc is SPSearchServiceInstance))
                    {
                        continue;
                    }

                    if (tempsvc.Status != SPObjectStatus.Online)
                    {
                        continue;
                    }

                    if (tempsvc.Server.Address.ToLowerInvariant() == Params["searchserver"].Value.ToLowerInvariant())
                    {
                        // We found a match so bug out of the loop.
                        searchServiceServer = tempsvc;
                        break;
                    }
                }
                if (searchServiceServer != null)
                {
                    db.SearchServiceInstance = searchServiceServer;
                    modified = true;
                }
                else
                {
                    Logger.Write("Search server \"{0}\" not found.", EventLogEntryType.Warning, Params["searchserver"].Value);
                }
            }
            else if (Params["searchserver"].UserTypedIn)
            {
                // The user specified the searchserver switch with no value which is what we use to indicate
                // clearing the value.
                db.SearchServiceInstance = null;
                modified = true;
            }

            if (modified)
            {
                db.Update();
            }

            return((int)ErrorCodes.NoError);
        }
 protected BaseCRUD(SPSite spSite, string databaseName = "")
 {
     this._contentDatabase  = spSite.ContentDatabase;
     this._databaseName     = databaseName;
     this._connectionString = this.GetConnectionString();
 }
 protected BaseCRUD(string databaseName = "")
 {
     this._contentDatabase  = SPContext.Current.Site.ContentDatabase;
     this._databaseName     = databaseName;
     this._connectionString = this.GetConnectionString();
 }
 protected override bool ProcessWorkItems(SPContentDatabase contentDatabase,
     SPWorkItemCollection workItems, SPJobState jobState)
 {
     Progress = 0;
     return base.ProcessWorkItems(contentDatabase, workItems, jobState);
 }
Exemple #28
0
        /// <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, StringDictionary keyValues, out string output)
        {
            output         = string.Empty;
            Logger.Verbose = true;

            string dbserver = Params["dbserver"].Value;
            string dbname   = Params["dbname"].Value;

            if (string.IsNullOrEmpty(dbserver))
            {
                dbserver = SPWebService.ContentService.DefaultDatabaseInstance.NormalizedDataSource;
            }
            SPWebApplication  webApp = SPWebApplication.Lookup(new Uri(Params["webapp"].Value));
            SPContentDatabase db     = null;

            foreach (SPContentDatabase tempDB in webApp.ContentDatabases)
            {
                if (tempDB.Name.ToLower() == dbname.ToLower())
                {
                    db = tempDB;
                    break;
                }
            }
            if (db != null)
            {
                throw new Exception("Content database already exists.");
            }

            SPObjectStatus status = (SPObjectStatus)Enum.Parse(typeof(SPObjectStatus), Params["status"].Value, true);

            db = webApp.ContentDatabases.Add(dbserver, dbname, null, null,
                                             int.Parse(Params["warningsitecount"].Value),
                                             int.Parse(Params["maxsites"].Value), (status == SPObjectStatus.Online?0:1));

            if (Params["searchserver"].UserTypedIn && !string.IsNullOrEmpty(Params["searchserver"].Value))
            {
                // If they specified a search server then we need to try and find a valid
                // matching search server using the server address property.
#if SP2010
                SPSearchService service = SPFarm.Local.Services.GetValue <SPSearchService>("SPSearch");
#elif SP2013
                SPSearchService service = SPFarm.Local.Services.GetValue <SPSearchService>("SPSearch4");
#endif
                SPServiceInstance searchServiceServer = null;
                foreach (SPServiceInstance tempsvc in service.Instances)
                {
                    if (!(tempsvc is SPSearchServiceInstance))
                    {
                        continue;
                    }

                    if (tempsvc.Status != SPObjectStatus.Online)
                    {
                        continue;
                    }

                    if (tempsvc.Server.Address.ToLowerInvariant() == Params["searchserver"].Value.ToLowerInvariant())
                    {
                        // We found a match so bug out of the loop.
                        searchServiceServer = tempsvc;
                        break;
                    }
                }
                if (searchServiceServer != null)
                {
                    db.SearchServiceInstance = searchServiceServer;
                }
                else
                {
                    Logger.Write("Search server \"{0}\" not found.", EventLogEntryType.Warning, Params["searchserver"].Value);
                }
            }
            else if (Params["searchserver"].UserTypedIn)
            {
                // The user specified the searchserver switch with no value which is what we use to indicate
                // clearing the value.
                db.SearchServiceInstance = null;
            }

            db.Update();

            return((int)ErrorCodes.NoError);
        }
Exemple #29
0
        protected override bool ProcessWorkItems(SPContentDatabase contentDatabase, SPWorkItemCollection workItems, SPJobState jobState)
        {
            foreach (SPWorkItem workItem in workItems)
            {
                if (workItem != null)
                {
                    try
                    {
                        SPSite site = new SPSite(workItem.SiteId);
                        IWebSiteControllerModule module = null;
                        WebSiteControllerRule    rule   = null;
                        bool _deleted = false;
                        //int ItemID = workItem.ItemId;

                        if (workItem.ItemId > 0)
                        {
                            rule = WebSiteControllerConfig.GetRule(contentDatabase.WebApplication, workItem.ItemGuid);
                        }
                        else
                        {
                            module = WebSiteControllerConfig.GetModule(contentDatabase.WebApplication, workItem.ItemGuid);
                        }

                        if (rule != null)
                        {
                            WebSiteControllerConfig.RemoveRule(rule.Id);
                            _deleted = true;
                        }

                        if (workItem.ItemId < 0 || _deleted)
                        {
                            string[] data                = workItem.TextPayload.Split(new char[] { '#' });
                            string   parameterRule       = data[0];
                            string   parameterProperties = data[1];
                            string[] rules               = parameterRule.Split(new char[] { ';' });

                            string url      = rules[0];
                            bool   disabled = bool.Parse(rules[1]);
                            bool   ssl      = bool.Parse(rules[2]);
                            int    sequence = int.Parse(rules[3]);

                            WebSiteControllerPrincipalType principalType = WebSiteControllerPrincipalType.None;

                            if (!String.IsNullOrEmpty(rules[4]))
                            {
                                principalType = (WebSiteControllerPrincipalType)Enum.Parse(typeof(WebSiteControllerPrincipalType), rules[4]);
                            }
                            string principal = rules[5];

                            string ruletype = string.Empty;

                            if (module != null || String.IsNullOrEmpty(rule.RuleType))
                            {
                                ruletype = module.RuleType;
                            }
                            else if (rule != null && ruletype == string.Empty)
                            {
                                ruletype = rule.RuleType;
                            }

                            string[]  properties = parameterProperties.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                            Hashtable props      = new Hashtable();

                            foreach (string prop in properties)
                            {
                                try
                                {
                                    if (!string.IsNullOrEmpty(prop))
                                    {
                                        string[] keyval = prop.Split(new char[] { ':' });
                                        props.Add(keyval[0], keyval[1]);
                                    }
                                }
                                catch { };
                            }

                            if (_deleted && workItem.ItemId != 1)
                            {
                                WebSiteControllerConfig.AddRule(contentDatabase.WebApplication,
                                                                site.Url + "/",
                                                                url,
                                                                rule.RuleType,
                                                                rule.Principal,
                                                                rule.PrincipalType,
                                                                disabled,
                                                                ssl,
                                                                sequence,
                                                                props
                                                                );
                            }

                            if (workItem.ItemId == -1)
                            {
                                WebSiteControllerConfig.AddRule(contentDatabase.WebApplication,
                                                                site.Url + "/",
                                                                url,
                                                                ruletype,
                                                                principal,
                                                                principalType,
                                                                disabled,
                                                                ssl,
                                                                sequence,
                                                                props
                                                                );
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        ex.ToString();
                        //throw (ex);
                    }
                    finally
                    {
                        DeleteWorkItem(workItems, workItem);
                        //using (SPSite site = new SPSite(workItem.SiteId))
                        //{

                        //    using (SPWeb web = site.OpenWeb(workItem.WebId))
                        //    {
                        //        SPWorkItemCollection deletableCollection = workItems.SubCollection(site, web, (uint)workItem.i, (uint)itemIndex + 1);
                        //        deletableCollection.DeleteWorkItem(currentItem.Id);

                        //        //workItems.CompleteInProgressWorkItems(workItem.ParentId, workItem.Type, workItem.BatchId);
                        //        //workItems.SubCollection(site, web, 0, (uint)workItems.Count).DeleteWorkItem(workItem.Id);

                        //    }

                        //}

                        ////workItems.DeleteWorkItem(workItem.Id);
                    }
                }
            }
            return(true);
        }
 public SPContentDatabaseEntity(SPContentDatabase cd)
 {
     _underlyingObject = cd;
 }
Exemple #31
0
 protected override bool ProcessWorkItem(SPContentDatabase contentDatabase, SPWorkItemCollection workItems, SPWorkItem workItem, SPJobState jobState)
 {
     tju = new TimerJobUtility(Constants.TimerJobName, jobState);
     return(tju.ProcessWorkItem(workItems, workItem, wiJobState, ProcessWorkItemCore));
 }
        protected override void InternalProcessRecord()
        {
            bool createLogFile = !base.NoLogFile.IsPresent;

            if (!base.NoFileCompression.IsPresent)
            {
                this.ValidateDirectory(base.Path);
            }
            if ((!base.Force.IsPresent) && File.Exists(base.Path))
            {
                throw new SPException(string.Format("PSCannotOverwriteExport,{0}", base.Path));
            }
            SPExportSettings settings = new SPExportSettings();
            SPExport         export   = new SPExport(settings);

            base.SetDeploymentSettings(settings);
            settings.ExportMethod        = SPExportMethodType.ExportAll;
            settings.ExcludeDependencies = !IncludeDependencies.IsPresent;
            SPDatabaseSnapshot snapshot = null;

            if (!this.UseSqlSnapshot.IsPresent)
            {
                settings.SiteUrl = this.SiteUrl;
            }
            else
            {
                snapshot = this.Site.ContentDatabase.Snapshots.CreateSnapshot();
                SPContentDatabase database2 = SPContentDatabase.CreateUnattachedContentDatabase(snapshot.ConnectionString);
                settings.UnattachedContentDatabase = database2;
                settings.SiteUrl = database2.Sites[this.Site.ServerRelativeUrl].Url;
            }
            SPExportObject exportObject = this.ExportObject;

            if (((exportObject.Type != SPDeploymentObjectType.Web) ||
                 base.ShouldProcess(string.Format("ShouldProcessExportWeb,{0},{1}", this.SiteUrl, base.Path))) &&
                ((exportObject.Type != SPDeploymentObjectType.List) ||
                 base.ShouldProcess(string.Format("ShouldProcessExportList,{0},{1}", this.SiteUrl + "/" + this.ItemUrl, base.Path))))
            {
                if (exportObject != null)
                {
                    exportObject.ExcludeChildren    = ExcludeChildren.IsPresent;
                    exportObject.IncludeDescendants = IncludeDescendants;
                    settings.ExportObjects.Add(exportObject);
                }
                settings.IncludeVersions = this.IncludeVersions;
                if (base.IncludeUserSecurity.IsPresent)
                {
                    settings.IncludeSecurity = SPIncludeSecurity.All;
                }
                settings.OverwriteExistingDataFile = (bool)base.Force;
                settings.FileMaxSize = this.CompressionSize;
                try
                {
                    export.Run();
                }
                finally
                {
                    if (base.Verbose && createLogFile)
                    {
                        Console.WriteLine();
                        Console.WriteLine(SPResource.GetString("ExportOperationLogFile", new object[0]));
                        Console.WriteLine("\t{0}", settings.LogFilePath);
                    }
                    if ((this.UseSqlSnapshot.IsPresent) && (snapshot != null))
                    {
                        snapshot.Delete();
                    }
                }
                if (base.Verbose)
                {
                    string    fileLocation = settings.FileLocation;
                    ArrayList dataFiles    = settings.DataFiles;
                    if (dataFiles != null)
                    {
                        if (((fileLocation != null) && (fileLocation.Length > 0)) && (fileLocation[fileLocation.Length - 1] != System.IO.Path.DirectorySeparatorChar))
                        {
                            fileLocation = fileLocation + System.IO.Path.DirectorySeparatorChar;
                        }
                        Console.WriteLine();
                        Console.WriteLine(SPResource.GetString("ExportOperationFilesGenerated", new object[0]));
                        for (int i = 0; i < dataFiles.Count; i++)
                        {
                            Console.WriteLine("\t{0}{1}", fileLocation, dataFiles[i]);
                            Console.WriteLine();
                        }
                        if (base.NoFileCompression.IsPresent)
                        {
                            DirectoryInfo info = new DirectoryInfo(base.Path);
                            Console.WriteLine("\t{0}", info.FullName);
                        }
                        Console.WriteLine();
                    }
                }
            }
        }
        protected override bool ProcessWorkItem(SPContentDatabase contentDatabase, 
            SPWorkItemCollection workItems, SPWorkItem workItem, SPJobState jobState)
        {
            Stopwatch sw = Stopwatch.StartNew(); //used to time how long the export took
            bool processingAlready = false;
            
            try
            {
                if (workItem != null)
                {
                    //process the workItem
                    using (SPSite site = new SPSite(workItem.SiteId))
                    {
                        using (SPWeb web = site.OpenWeb(workItem.WebId))
                        {
                            // processing logic
                            // 1. SET GlymaExport list Item to ExportStatus.Processing
                            // 2. START export based on type in GlymaExport list item
                            // 3. STORE the export in the GlymaExport list against the item as an attachment
                            // 4. SET GlymaExport list item to ExportStatus.Completed
                            SPList exportsList = null;
                            SPListItem exportItem = null;
                            try
                            {
                                exportsList = web.Lists[workItem.ParentId];
                                exportItem = exportsList.GetItemByUniqueId(workItem.ItemGuid);
                                if (exportItem != null)
                                {
                                    string exportStatus = exportItem["ExportStatus"] as string;
                                    if (exportStatus == ExportStatus.Scheduled.ToString())
                                    {
                                        // If the export was still marked as scheduled then set it to processing
                                        WriteExportStatus(workItem, ExportStatus.Processing);

                                        exportItem = exportsList.GetItemByUniqueId(workItem.ItemGuid);

                                        if (exportItem != null)
                                        {
                                            // read the type of export that we should produce
                                            ExportType exportType = (ExportType)Enum.Parse(typeof(ExportType), exportItem["ExportType"] as string);
                                            MapType mapType = (MapType)Enum.Parse(typeof(MapType), exportItem["MapType"] as string);

                                            Dictionary<string, string> exportProperties = null;
                                            string exportPropertiesStr = exportItem["ExportProperties"] as string;
                                            if (!string.IsNullOrEmpty(exportPropertiesStr) && exportPropertiesStr.Trim() != string.Empty)
                                            {
                                                try
                                                {
                                                    ExportPropertiesDictionary exportDict = new ExportPropertiesDictionary(exportPropertiesStr);
                                                    exportProperties = exportDict as Dictionary<string, string>;
                                                }
                                                catch (XmlSchemaValidationException)
                                                {
                                                    exportProperties = null;
                                                }
                                            }

                                            bool useVerboseLogging = false;
                                            if (exportProperties != null)
                                            {
                                                if (exportProperties.ContainsKey("Verbose"))
                                                {
                                                    if (exportProperties["Verbose"].ToLower() == "true")
                                                    {
                                                        useVerboseLogging = true;
                                                    }
                                                }
                                            }

                                            if (useVerboseLogging)
                                            {
                                                LogMessage(workItem, "Creating Map Manager for the web: {0}.", web.Url);
                                            }

                                            // create the appropriate IExportUtility for the ExportType
                                            MapManagerFactory mapManagerFactory = new MapManagerFactory();
                                            IMapManager mapManager = mapManagerFactory.GetMapManager(web);
                                            if (mapManager != null)
                                            {
                                                if (useVerboseLogging)
                                                {
                                                    LogMessage(workItem, "Created Map Manager for the web: {0}.", web.Url);
                                                }

                                                ExportUtilityFactory exportUtilityFactory = new ExportUtilityFactory(mapManager);
                                                IExportUtility exportUtility = exportUtilityFactory.CreateExportUtility(mapType, exportType);

                                                if (exportUtility != null)
                                                {
                                                    if (useVerboseLogging)
                                                    {
                                                        LogMessage(workItem, "Created Export Utility for {0} map type to {1}.", mapType.ToString(), exportType.ToString());
                                                    }

                                                    exportItem = exportsList.GetItemByUniqueId(workItem.ItemGuid);
                                                    if (exportItem != null)
                                                    {
                                                        Guid rootMapUid = Guid.Empty;
                                                        Guid domainUid = Guid.Empty;
                                                        try
                                                        {
                                                            string rootMapUidValue = exportItem["RootMapUid"] as string;
                                                            string domainUidValue = exportItem["DomainUid"] as string;
                                                            domainUid = new Guid(domainUidValue);
                                                            rootMapUid = new Guid(rootMapUidValue);
                                                        }
                                                        catch (Exception ex)
                                                        {
                                                            //The GUIDs were not parsed correctly
                                                        }
                                                        if (rootMapUid != Guid.Empty && domainUid != Guid.Empty)
                                                        {
                                                            //The export utility will do the grunt work and provide a URL to the temp file created
                                                            GlymaExportUserState userState = new GlymaExportUserState(workItem);
                                                            userState.UseVerboseLogging = useVerboseLogging; //store the level of logging to use in the event handlers
                                                            exportUtility.ExportCompleted += exportUtility_ExportCompleted;
                                                            exportUtility.ProgressChanged += exportUtility_ProgressChanged;
                                                            exportUtility.ExceptionRaised += exportUtility_ExceptionRaised;

                                                            if (useVerboseLogging)
                                                            {
                                                                LogMessage(workItem, "Starting export.");
                                                            }

                                                            exportUtility.ExportMap(domainUid, rootMapUid, exportProperties, new List<Guid>(), userState);

                                                            if (useVerboseLogging)
                                                            {
                                                                LogMessage(workItem, "Waiting for export to complete.");
                                                            }

                                                            // Wait for the export to complete (up to the timeout)
                                                            bool signalled = userState.Completed.WaitOne(TIMEOUT_MS);
                                                            if (!signalled)
                                                            {
                                                                if (useVerboseLogging)
                                                                {
                                                                    LogMessage(workItem, "The export timed out after {0}ms", TIMEOUT_MS);
                                                                }
                                                                // The timeout occurred so don't process the completed or progress changed events
                                                                exportUtility.ExportCompleted -= exportUtility_ExportCompleted;
                                                                exportUtility.ProgressChanged -= exportUtility_ProgressChanged;
                                                                exportUtility.ExceptionRaised -= exportUtility_ExceptionRaised;
                                                            }
                                                        }
                                                        else
                                                        {
                                                            throw new Exception(string.Format("The DomainUid and/or RootMapUid were not valid Guid's. DomainUid: {0} RootMapUid: {1}.", domainUid.ToString(), rootMapUid.ToString()));
                                                        }
                                                    }
                                                }
                                                else
                                                {
                                                    throw new Exception(string.Format("Unable to create export utility for the export type: {0}.", exportType.ToString()));
                                                }
                                            }
                                            else
                                            {
                                                throw new Exception(string.Format("Unable to build an IMapManager for the current SPWeb. {0}", mapManagerFactory.ErrorMessage));
                                            }
                                        }
                                    }
                                    else if (exportStatus == ExportStatus.Processing.ToString())
                                    {
                                        //shouldn't do anything unless it's scheduled.
                                        processingAlready = true;
                                    }
                                }
                                else
                                {
                                    throw new Exception("The Export Job did not exist in the list.");
                                }
                            }
                            catch (TargetInvocationException tiex)
                            {
                                if (workItem != null)
                                {
                                    WriteExportStatus(workItem, ExportStatus.Error);
                                    LogMessage(workItem, "Error during export: {0}", tiex.Message);

                                    if (tiex.InnerException != null)
                                    {
                                        LogMessage(workItem, "Inner Exception({0}): {1}.\r\nStackTrace: {2}", tiex.InnerException.GetType().ToString(), tiex.InnerException.Message, tiex.InnerException.StackTrace);
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                //exception handling
                                if (workItem != null)
                                {
                                    WriteExportStatus(workItem, ExportStatus.Error);
                                    LogMessage(workItem, "Error during export: {0}.", ex.Message);
                                }
                            }
                            finally
                            {
                                if (!processingAlready)
                                {
                                    // delete the workItem after we've processed it
                                    workItems.SubCollection(site, web, 0, (uint)workItems.Count).DeleteWorkItem(workItem.Id);
                                }

                                //Update the progress of the timer job
                                Progress += (100 / workItems.Count); //estimate only, some maps will export faster than others and different types may export faster
                                if (Progress > 100)
                                {
                                    Progress = 100;
                                }
                                this.UpdateProgress(Progress); //The base classes timer job's overall progress
                                
                                if (!processingAlready) //this is if the timer job ran and started processing the item that was already being processed
                                {
                                    exportItem = exportsList.GetItemByUniqueId(workItem.ItemGuid);
                                    if (exportItem != null)
                                    {
                                        string exportStatus = exportItem["ExportStatus"] as string;
                                        if (exportStatus == ExportStatus.Processing.ToString())
                                        {
                                            //if it's still processing and at this point then something has failed.
                                            WriteExportStatus(workItem, ExportStatus.Error);
                                            LogMessage(workItem, "The export failed as it was still in a processing state when it had apparently completed.");
                                        }

                                        LogMessage(workItem, "Completed in {0:0.000}s.", sw.Elapsed.TotalSeconds);//add in a metric for how long the export took (successful or failure)
                                    }
                                 }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                //exception handling
                throw new Exception("Failed to while processing Glyma Export Work Item Timer Job.", ex);
            }

            return true;
        }
        private static SPSite CreateSite(SPWebApplication webApp, SPSiteSubscription siteSubscription, string webTemplate, string title, string description, string ownerName, string ownerEmail, string quota, string secondaryContactName, string secondaryContactEmail, bool useHostHeaderAsSiteName, uint nLCID, Uri uri, string ownerLogin, string secondaryContactLogin, SPContentDatabase database)
        {
            if (database != null && database.MaximumSiteCount <= database.CurrentSiteCount)
                throw new SPException("The maximum site count for the specified database has been exceeded.  Increase the maximum site count or specify another database.");

            Logger.Write("PROGRESS: Creating site collection...");
            SPSite site = null;
            if (database != null)
            {
                site = database.Sites.Add(siteSubscription, uri.OriginalString, title, description, nLCID, webTemplate, ownerLogin,
                     ownerName, ownerEmail, secondaryContactLogin, secondaryContactName, secondaryContactEmail,
                     useHostHeaderAsSiteName);
            }
            else
            {
                site = webApp.Sites.Add(siteSubscription, uri.OriginalString, title, description, nLCID, webTemplate, ownerLogin,
                     ownerName, ownerEmail, secondaryContactLogin, secondaryContactName, secondaryContactEmail,
                     useHostHeaderAsSiteName);
            }
            Logger.Write("PROGRESS: Site collection successfully created.");

            if (!string.IsNullOrEmpty(quota))
            {
                Logger.Write("PROGRESS: Associating quota template with site collection...");
                using (SPSiteAdministration administration = new SPSiteAdministration(site.Url))
                {
                    SPFarm farm = SPFarm.Local;
                    SPWebService webService = farm.Services.GetValue<SPWebService>("");

                    SPQuotaTemplateCollection quotaColl = webService.QuotaTemplates;
                    administration.Quota = quotaColl[quota];
                }
            }
            if (!string.IsNullOrEmpty(webTemplate))
            {
                Logger.Write("PROGRESS: Creating default security groups...");
                using (SPWeb web = site.RootWeb)
                {
                    web.CreateDefaultAssociatedGroups(ownerLogin, secondaryContactLogin, string.Empty);
                }
            }

            return site;
        }