protected override void InternalProcessRecord()
        {
            SPServiceContext context = null;

            if (ParameterSetName == "UPA")
            {
                SPSiteSubscriptionIdentifier subId;
                if (SiteSubscription != null)
                {
                    SPSiteSubscription siteSub = SiteSubscription.Read();
                    subId = siteSub.Id;
                }
                else
                {
                    subId = SPSiteSubscriptionIdentifier.Default;
                }

                SPServiceApplication svcApp = UserProfileServiceApplication.Read();
                context = SPServiceContext.GetContext(svcApp.ServiceApplicationProxyGroup, subId);
            }
            else
            {
                using (SPSite site = ContextSite.Read())
                {
                    context = SPServiceContext.GetContext(site);
                }
            }

            string xml = File.ReadAllText(InputFile);

            Common.Audiences.ImportAudiences.Import(xml, context, DeleteExisting.IsPresent, Compile.IsPresent, MapFile);
        }
        private static string GetTenantPropertyBagValue(string key)
        {
            string value       = string.Empty;
            SPSite currentSite = SPContext.Current.Site;

            SPSiteSubscription sub = currentSite.SiteSubscription;
            Guid tenantAdminSiteId;
            bool isSuccess = SPTenantAdmin.TryGetTenantAdministrationSiteGuid(sub,
                                                                              out tenantAdminSiteId);

            if (isSuccess)
            {
                SPSite tenantAdminSite
                    = sub.GetSites(currentSite.WebApplication).Where(s => s.ID == tenantAdminSiteId) as SPSite;
                //SPSite tenantAdminSite=  currentSite.WebApplication.Sites[tenantAdminSiteId];
                if (null != tenantAdminSite)
                {
                    SPWeb rootWeb = tenantAdminSite.RootWeb;
                    if (rootWeb.AllProperties.ContainsKey(key))
                    {
                        value = Convert.ToString(rootWeb.GetProperty(key));
                    }
                }
            }

            return(value);
        }
        protected override void InternalProcessRecord()
        {
            SPServiceContext context = null;

            if (ParameterSetName == "UPA")
            {
                SPSiteSubscriptionIdentifier subId;
                if (SiteSubscription != null)
                {
                    SPSiteSubscription siteSub = SiteSubscription.Read();
                    subId = siteSub.Id;
                }
                else
                {
                    subId = SPSiteSubscriptionIdentifier.Default;
                }

                SPServiceApplication svcApp = UserProfileServiceApplication.Read();
                context = SPServiceContext.GetContext(svcApp.ServiceApplicationProxyGroup, subId);
            }
            else
            {
                using (SPSite site = ContextSite.Read())
                {
                    context = SPServiceContext.GetContext(site);
                }
            }

            Common.Audiences.AddAudienceRule.AddRules(context, Identity, Rules.OuterXml, Clear.IsPresent, Compile.IsPresent, GroupExisting.IsPresent, AppendOperator.Value);
        }
        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);
        }
Exemplo n.º 5
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();
                }
            }
        }
        protected override void UpdateDataObject()
        {
            SPServiceContext context = null;

            if (ParameterSetName == "UPA")
            {
                SPSiteSubscriptionIdentifier subId;
                if (SiteSubscription != null)
                {
                    SPSiteSubscription siteSub = SiteSubscription.Read();
                    subId = siteSub.Id;
                }
                else
                {
                    subId = SPSiteSubscriptionIdentifier.Default;
                }

                SPServiceApplication svcApp = UserProfileServiceApplication.Read();
                context = SPServiceContext.GetContext(svcApp.ServiceApplicationProxyGroup, subId);
            }
            else
            {
                using (SPSite site = ContextSite.Read())
                {
                    context = SPServiceContext.GetContext(site);
                }
            }

            Common.Audiences.CreateAudience.Create(context, Identity, Description, Membership, Owner, true);
        }
        protected override IEnumerable <AudienceManager> RetrieveDataObjects()
        {
            List <AudienceManager> audienceManagers = new List <AudienceManager>();

            SPServiceContext context = null;

            if (ParameterSetName == "UPA")
            {
                SPSiteSubscriptionIdentifier subId;
                if (SiteSubscription != null)
                {
                    SPSiteSubscription siteSub = SiteSubscription.Read();
                    subId = siteSub.Id;
                }
                else
                {
                    subId = SPSiteSubscriptionIdentifier.Default;
                }

                SPServiceApplication svcApp = UserProfileServiceApplication.Read();
                context = SPServiceContext.GetContext(svcApp.ServiceApplicationProxyGroup, subId);
            }
            else
            {
                using (SPSite site = ContextSite.Read())
                {
                    context = SPServiceContext.GetContext(site);
                }
            }
            AudienceManager manager = new AudienceManager(context);

            audienceManagers.Add(manager);
            return(audienceManagers);
        }
Exemplo n.º 8
0
        public SiteSubscriptionNode(SPSiteSubscriptionCollection parten, SPSiteSubscription siteSubscription)
        {
            this.Tag = siteSubscription;
            this.SPParent = parten;
            this.Nodes.Add("Dummy");

            this.Setup();
        }
        public SiteSubscriptionNode(SPSiteSubscriptionCollection parten, SPSiteSubscription siteSubscription)
        {
            this.Tag      = siteSubscription;
            this.SPParent = parten;
            this.Nodes.Add("Dummy");

            this.Setup();
        }
Exemplo n.º 10
0
        protected override void UpdateDataObject()
        {
            SPServiceContext   context     = null;
            UserProfileManager profManager = null;

            switch (ParameterSetName)
            {
            case "Username_UPA":
                SPSiteSubscriptionIdentifier subId;
                if (SiteSubscription != null)
                {
                    SPSiteSubscription siteSub = SiteSubscription.Read();
                    subId = siteSub.Id;
                }
                else
                {
                    subId = SPSiteSubscriptionIdentifier.Default;
                }

                SPServiceApplication svcApp = UserProfileServiceApplication.Read();
                context     = SPServiceContext.GetContext(svcApp.ServiceApplicationProxyGroup, subId);
                profManager = new UserProfileManager(context);

                if (string.IsNullOrEmpty(Username))
                {
                    Common.UserProfiles.SetPictureUrl.SetPictures(profManager, Path, Overwrite, IgnoreMissingData, ValidateUrl);
                }
                else
                {
                    Common.UserProfiles.SetPictureUrl.SetPicture(profManager, Username, Path, Overwrite, IgnoreMissingData, ValidateUrl);
                }

                break;

            case "Username_SPSite":
                using (SPSite site = ContextSite.Read())
                {
                    context = SPServiceContext.GetContext(site);
                }
                profManager = new UserProfileManager(context);

                if (string.IsNullOrEmpty(Username))
                {
                    Common.UserProfiles.SetPictureUrl.SetPictures(profManager, Path, Overwrite, IgnoreMissingData, ValidateUrl);
                }
                else
                {
                    Common.UserProfiles.SetPictureUrl.SetPicture(profManager, Username, Path, Overwrite, IgnoreMissingData, ValidateUrl);
                }

                break;

            case "UserProfile":
                Common.UserProfiles.SetPictureUrl.SetPicture(UserProfile, Path, Overwrite, IgnoreMissingData, ValidateUrl);
                break;
            }
        }
        protected override IEnumerable <UserProfileChange> RetrieveDataObjects()
        {
            SPServiceContext context = null;

            if (ParameterSetName == "UPA")
            {
                SPSiteSubscriptionIdentifier subId;
                if (SiteSubscription != null)
                {
                    SPSiteSubscription siteSub = SiteSubscription.Read();
                    subId = siteSub.Id;
                }
                else
                {
                    subId = SPSiteSubscriptionIdentifier.Default;
                }

                SPServiceApplication svcApp = UserProfileServiceApplication.Read();
                context = SPServiceContext.GetContext(svcApp.ServiceApplicationProxyGroup, subId);
            }
            else
            {
                using (SPSite site = ContextSite.Read())
                {
                    context = SPServiceContext.GetContext(site);
                }
            }
            UserProfileManager profileManager = new UserProfileManager(context);

            DateTime tokenStart = DateTime.UtcNow.Subtract(TimeSpan.FromMinutes(Interval));
            UserProfileChangeToken changeToken = new UserProfileChangeToken(tokenStart);

            UserProfileChangeQuery changeQuery = new UserProfileChangeQuery(false, true);

            changeQuery.ChangeTokenStart           = changeToken;
            changeQuery.UserProfile                = true;
            changeQuery.SingleValueProperty        = IncludeSingleValuePropertyChanges;
            changeQuery.MultiValueProperty         = IncludeMultiValuePropertyChanges;
            changeQuery.Anniversary                = IncludeAnniversaryChanges;
            changeQuery.Colleague                  = IncludeColleagueChanges;
            changeQuery.OrganizationMembership     = IncludeOrganizationMembershipChanges;
            changeQuery.DistributionListMembership = IncludeDistributionListMembershipChanges;
            changeQuery.PersonalizationSite        = IncludePersonalizationSiteChanges;
            changeQuery.SiteMembership             = IncludeSiteMembershipChanges;

            UserProfileChangeCollection changes = profileManager.GetChanges(changeQuery);

            foreach (UserProfileChange change in changes)
            {
                WriteResult(change);
            }
            return(null);
        }
        protected override IEnumerable <Audience> RetrieveDataObjects()
        {
            List <Audience> audiences = new List <Audience>();

            SPServiceContext context = null;

            if (ParameterSetName == "UPA")
            {
                SPSiteSubscriptionIdentifier subId;
                if (SiteSubscription != null)
                {
                    SPSiteSubscription siteSub = SiteSubscription.Read();
                    subId = siteSub.Id;
                }
                else
                {
                    subId = SPSiteSubscriptionIdentifier.Default;
                }

                SPServiceApplication svcApp = UserProfileServiceApplication.Read();
                context = SPServiceContext.GetContext(svcApp.ServiceApplicationProxyGroup, subId);
            }
            else
            {
                using (SPSite site = ContextSite.Read())
                {
                    context = SPServiceContext.GetContext(site);
                }
            }
            AudienceManager manager = new AudienceManager(context);

            if (!string.IsNullOrEmpty(Identity) && !manager.Audiences.AudienceExist(Identity))
            {
                throw new SPException("Audience name does not exist");
            }
            if (!string.IsNullOrEmpty(Identity))
            {
                audiences.Add(manager.Audiences[Identity]);
                return(audiences);
            }

            foreach (Audience audience in manager.Audiences)
            {
                audiences.Add(audience);
            }
            return(audiences);
        }
        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);
        }
Exemplo n.º 14
0
        protected override void InternalProcessRecord()
        {
            SPServiceContext context = null;

            if (ParameterSetName == "UPA")
            {
                SPSiteSubscriptionIdentifier subId;
                if (SiteSubscription != null)
                {
                    SPSiteSubscription siteSub = SiteSubscription.Read();
                    subId = siteSub.Id;
                }
                else
                {
                    subId = SPSiteSubscriptionIdentifier.Default;
                }

                SPServiceApplication svcApp = UserProfileServiceApplication.Read();
                context = SPServiceContext.GetContext(svcApp.ServiceApplicationProxyGroup, subId);
            }
            else
            {
                using (SPSite site = ContextSite.Read())
                {
                    context = SPServiceContext.GetContext(site);
                }
            }


            string xml = Common.Audiences.EnumAudienceRules.EnumRules(context, Identity, Explicit.IsPresent);

            if (string.IsNullOrEmpty(xml))
            {
                return;
            }

            XmlDocument xmlDoc = new XmlDocument();

            xmlDoc.LoadXml(xml);
            WriteResult(xml);
        }
        protected override void InternalValidate()
        {
            if (ParameterSetName == "UPA")
            {
                SPSiteSubscriptionIdentifier subId;
                if (SiteSubscription != null)
                {
                    SPSiteSubscription siteSub = SiteSubscription.Read();
                    subId = siteSub.Id;
                }
                else
                {
                    subId = SPSiteSubscriptionIdentifier.Default;
                }

                SPServiceApplication svcApp = UserProfileServiceApplication.Read();
                _context = SPServiceContext.GetContext(svcApp.ServiceApplicationProxyGroup, subId);
            }
            else
            {
                using (SPSite site = ContextSite.Read())
                {
                    _context = SPServiceContext.GetContext(site);
                }
            }

            if (!string.IsNullOrEmpty(Identity))
            {
                base.DataObject = Identity;
            }
            if (base.DataObject == null)
            {
                base.WriteError(new PSArgumentException("A valid audience name and service application must be provided."), ErrorCategory.InvalidArgument, null);
                base.SkipProcessCurrentRecord();
            }
        }
        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;
        }
        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;
        }
        internal static SPSite ConvertWebToSite(string sourceurl, string targeturl, SPSiteSubscription siteSubscription, bool suppressAfterEvents,
                                                bool noFileCompression, string exportedFile, bool createSiteInDB, string databaseName, bool createManagedPath,
                                                bool haltOnWarning, bool haltOnFatalError, bool deleteSource, string title, string description, uint nLCID, string ownerName,
                                                string ownerEmail, string ownerLogin, string secondaryContactName, string secondaryContactLogin, string secondaryContactEmail,
                                                string quota, bool useHostHeaderAsSiteName)
        {
            try
            {
                if (!string.IsNullOrEmpty(exportedFile))
                {
                    if (noFileCompression)
                    {
                        if (!Directory.Exists(exportedFile))
                        {
                            throw new SPException(SPResource.GetString("DirectoryNotFoundExceptionMessage", new object[] { exportedFile }));
                        }
                    }
                    else
                    {
                        if (!File.Exists(exportedFile))
                        {
                            throw new SPException(SPResource.GetString("FileNotFoundExceptionMessage", new object[] { exportedFile }));
                        }
                    }
                }

                if (createSiteInDB && string.IsNullOrEmpty(databaseName))
                {
                    throw new SPSyntaxException("databasename is required if creating the site in a new or existing database.");
                }


                using (SPSite sourceSite = new SPSite(sourceurl))
                    using (SPWeb sourceWeb = sourceSite.AllWebs[Utilities.GetServerRelUrlFromFullUrl(sourceurl)])
                    {
                        if (createManagedPath)
                        {
                            Logger.Write("Adding managed path...");
                            AddManagedPath(targeturl, haltOnWarning);
                            Logger.Write("Managed path added.\r\n");
                        }

                        if (string.IsNullOrEmpty(exportedFile))
                        {
                            Logger.Write("Exporting site...");
                            exportedFile = ExportHelper.ExportSite(sourceurl,
                                                                   haltOnWarning,
                                                                   haltOnFatalError,
                                                                   noFileCompression,
                                                                   true, !Logger.Verbose, SPIncludeVersions.All, 0, false, true);
                            Logger.Write("Site exported.\r\n");
                        }

                        Logger.Write("Creating site for import...");

                        SPWebApplicationPipeBind webAppBind = new SPWebApplicationPipeBind(targeturl);
                        SPWebApplication         webApp     = webAppBind.Read(false);


                        SPSite targetSite = CreateSite(webApp, databaseName, siteSubscription, null, title, description, ownerName, ownerEmail, quota, secondaryContactName,
                                                       secondaryContactEmail, useHostHeaderAsSiteName, nLCID, new Uri(targeturl), ownerLogin, secondaryContactLogin);

                        SPWeb targetWeb = targetSite.AllWebs[Utilities.GetServerRelUrlFromFullUrl(targeturl)];
                        Logger.Write("Site created.\r\n");

                        Logger.Write("Importing site...");

                        ImportHelper import = new ImportHelper();
                        import.ImportSite(exportedFile,
                                          targeturl,
                                          haltOnWarning,
                                          haltOnFatalError,
                                          noFileCompression, true, !Logger.Verbose, true,
                                          false, SPUpdateVersions.Append, suppressAfterEvents);

                        Logger.Write("Site imported.\r\n");


#if MOSS
                        Logger.Write("Repairing imported site...");
                        // Need to add a small delay here as the repair seems to fail occassionally due to a timing issue.
                        Common.TimerJobs.ExecAdmSvcJobs.Execute(false, true);
                        int tryCount = 0;
                        while (true)
                        {
                            try
                            {
                                tryCount++;
                                Common.SiteCollections.RepairSiteCollectionImportedFromSubSite.RepairSite(sourceurl, targeturl);
                                break;
                            }
                            catch (InvalidPublishingWebException)
                            {
                                if (haltOnWarning)
                                {
                                    throw;
                                }
                                if (tryCount > 3)
                                {
                                    Logger.WriteWarning("Repair of site collection failed - unable to get Pages library.  Manually run 'repairsitecollectionimportedfromsubsite' command to try again.");
                                    break;
                                }
                                else
                                {
                                    Thread.Sleep(10000);
                                }
                            }
                            catch (OutOfMemoryException)
                            {
                                if (haltOnWarning)
                                {
                                    throw;
                                }

                                Logger.WriteWarning("Server ran out of memory and was not able to complete the repair operation.  Manually run 'repairsitecollectionimportedfromsubsite' command to try again.");
                                break;
                            }
                        }
                        Logger.Write("Imported site repaired.\r\n");
#endif

                        // Upgrade any redirect links if present.
                        if (sourceSite.WebApplication.Id == targetSite.WebApplication.Id)
                        {
                            //Console.WriteLine("Repairing Area upgrade URLs...");
                            // The spsredirect.aspx page which uses the upgrade list only supports server relative urls so
                            // if we change the link to be absolute the redirect won't work so don't bother changing it.
                            // Note that we could get around this if we had a simple redirect page that could take in
                            // a target url - then we could have spsredirect.aspx load the server relative redirect
                            // page which would have the actual url passed into it (unfortunately redirect.aspx does
                            // some funky stuff so we can't use it).
                            //UpdateV2ToV3UpgradeAreaUrlMappings.FixUpgradeAreaUrlMappings(sourceSite.WebApplication,
                            //                                                             sourceWeb.ServerRelativeUrl,
                            //                                                             targetWeb.ServerRelativeUrl);
                            //Console.WriteLine("Area upgrade URLs repaired.\r\n");
                        }

                        if (deleteSource)
                        {
                            Logger.Write("Deleting source web...");
                            if (!sourceWeb.IsRootWeb)
                            {
                                DeleteSubWebs(sourceWeb.Webs);

                                sourceWeb.Delete();
                                Logger.Write("Source web deleted.\r\n");
                                Logger.Write("You can find the exported web at " + exportedFile + "\r\n");
                            }
                            else
                            {
                                Logger.Write("Source web is a root web - cannot delete.");
                            }
                        }
                        return(targetSite);
                    }
            }
            catch (Exception ex)
            {
                Logger.WriteException(new System.Management.Automation.ErrorRecord(ex, null, System.Management.Automation.ErrorCategory.NotSpecified, null));
            }
            return(null);
        }
        protected void BtnCreateSite_Click(object sender, EventArgs e)
        {
            bool               sitefound       = false;
            string             url             = "";
            SPSiteSubscription subscription    = null;
            string             subscriptionUrl = null;

            if (ddlSiteCollections.SelectedIndex > 0)
            {
                using (SPSite site = new SPSite(ddlSiteCollections.SelectedValue))
                {
                    subscriptionUrl = site.Url;
                    subscription    = site.SiteSubscription;
                }
            }
            if (subscriptionUrl != null && chkHostHeader.Checked)
            {
                url = subscriptionUrl + "/epm";
                try
                {
                    using (SPSite existing = new SPSite(url))
                    {
                        sitefound = true;
                    }
                }
                catch
                {
                }
            }
            else
            {
                try
                {
                    if (DdlWildcardInclusion.SelectedValue.Substring(0, 1) == "0")
                    {
                        url = DdlWildcardInclusion.SelectedItem.Text + TxtSiteName.Text;
                        using (SPSite site = new SPSite(HidVirtualServerUrl.Value + DdlWildcardInclusion.SelectedItem.Text + TxtSiteName.Text))
                        {
                            sitefound = true;
                        }
                    }
                    else
                    {
                        url = DdlWildcardInclusion.SelectedItem.Text;
                    }
                }
                catch { }
            }
            if (sitefound)
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "url", "<script language=\"javascript\">alert('That URL is already in use.');</script>");
            }
            else
            {
                bool databasegood = true;
                lblErrorDatabase.Visible = false;
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    try
                    {
                        if (txtDatabaseServer.Text != "")
                        {
                            if (sacccount.Checked)
                            {
                                if (btnNew.Checked)
                                {
                                    using (var sqlConnection = new SqlConnection(
                                               string.Format(
                                                   "Data Source={0};Initial Catalog={1};User Id={2};Password={3};",
                                                   txtDatabaseServer.Text,
                                                   "master",
                                                   username.Text,
                                                   password.Text)))
                                    {
                                        sqlConnection.Open();
                                    }
                                }
                                else
                                {
                                    using (var sqlConnection = new SqlConnection(
                                               string.Format(
                                                   "Data Source={0};Initial Catalog={1};User Id={2};Password={3};",
                                                   txtDatabaseServer.Text,
                                                   txtDatabaseName.Text,
                                                   username.Text,
                                                   password.Text)))
                                    {
                                        sqlConnection.Open();
                                    }
                                }
                            }
                            else
                            {
                                if (btnNew.Checked)
                                {
                                    using (var sqlConnection = new SqlConnection(
                                               string.Format(
                                                   "Data Source={0};Initial Catalog={1};Integrated Security=SSPI",
                                                   txtDatabaseServer.Text,
                                                   "master")))
                                    {
                                        sqlConnection.Open();
                                    }
                                }
                                else
                                {
                                    using (var sqlConnection = new SqlConnection(
                                               string.Format(
                                                   "Data Source={0};Initial Catalog={1};Integrated Security=SSPI",
                                                   txtDatabaseServer.Text,
                                                   txtDatabaseName.Text)))
                                    {
                                        sqlConnection.Open();
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        lblErrorDatabase.Text    = ex.Message;
                        lblErrorDatabase.Visible = true;
                        databasegood             = false;
                    }
                });

                if (databasegood)
                {
                    app = webAppSelector.CurrentItem;

                    string username;
                    string name = ((Microsoft.SharePoint.WebControls.PickerEntity)PickerOwner.ResolvedEntities[0]).DisplayText;

                    if (app.UseClaimsAuthentication)
                    {
                        username = ((Microsoft.SharePoint.WebControls.PickerEntity)PickerOwner.ResolvedEntities[0]).Claim.ToEncodedString();
                    }
                    else
                    {
                        username = ((Microsoft.SharePoint.WebControls.PickerEntity)PickerOwner.ResolvedEntities[0]).Description;
                    }

                    Guid siteguid = Guid.Empty;

                    string error = createSite(url, /*subscription*/ null, TxtCreateSiteTitle.Text, TxtCreateSiteDescription.Text, username, name, "", ddlSolution.SelectedValue, out siteguid, chkHostHeader.Checked);
                    if (error == "")
                    {
                        Response.Redirect("../SiteCreated.aspx?SiteId=" + HttpUtility.UrlEncode(siteguid.ToString()));
                    }
                    else
                    {
                        lblSiteError.Text    = error;
                        lblSiteError.Visible = true;
                    }
                }
            }
        }
        internal static SPSite ConvertWebToSite(string sourceurl, string targeturl, SPSiteSubscription siteSubscription, bool suppressAfterEvents, 
            bool noFileCompression, string exportedFile, bool createSiteInDB, string databaseName, bool createManagedPath, 
            bool haltOnWarning, bool haltOnFatalError, bool deleteSource, string title, string description, uint nLCID, string ownerName, 
            string ownerEmail, string ownerLogin, string secondaryContactName, string secondaryContactLogin, string secondaryContactEmail, 
            string quota, bool useHostHeaderAsSiteName)
        {
            try
            {
                if (!string.IsNullOrEmpty(exportedFile))
                {
                    if (noFileCompression)
                    {
                        if (!Directory.Exists(exportedFile))
                            throw new SPException(SPResource.GetString("DirectoryNotFoundExceptionMessage", new object[] { exportedFile }));
                    }
                    else
                    {
                        if (!File.Exists(exportedFile))
                            throw new SPException(SPResource.GetString("FileNotFoundExceptionMessage", new object[] { exportedFile }));
                    }
                }

                if (createSiteInDB && string.IsNullOrEmpty(databaseName))
                {
                    throw new SPSyntaxException("databasename is required if creating the site in a new or existing database.");
                }

                using (SPSite sourceSite = new SPSite(sourceurl))
                using (SPWeb sourceWeb = sourceSite.AllWebs[Utilities.GetServerRelUrlFromFullUrl(sourceurl)])
                {
                    if (createManagedPath)
                    {
                        Logger.Write("Adding managed path...");
                        AddManagedPath(targeturl, haltOnWarning);
                        Logger.Write("Managed path added.\r\n");
                    }

                    if (string.IsNullOrEmpty(exportedFile))
                    {
                        Logger.Write("Exporting site...");
                        exportedFile = ExportHelper.ExportSite(sourceurl,
                                              haltOnWarning,
                                              haltOnFatalError,
                                              noFileCompression,
                                              true, !Logger.Verbose, SPIncludeVersions.All, 0, false, true);
                        Logger.Write("Site exported.\r\n");
                    }

                    Logger.Write("Creating site for import...");

                    SPWebApplicationPipeBind webAppBind = new SPWebApplicationPipeBind(targeturl);
                    SPWebApplication webApp = webAppBind.Read(false);

                    SPSite targetSite = CreateSite(webApp, databaseName, siteSubscription, null, title, description, ownerName, ownerEmail, quota, secondaryContactName,
                        secondaryContactEmail, useHostHeaderAsSiteName, nLCID, new Uri(targeturl), ownerLogin, secondaryContactLogin);

                    SPWeb targetWeb = targetSite.AllWebs[Utilities.GetServerRelUrlFromFullUrl(targeturl)];
                    Logger.Write("Site created.\r\n");

                    Logger.Write("Importing site...");

                    ImportHelper import = new ImportHelper();
                    import.ImportSite(exportedFile,
                                      targeturl,
                                      haltOnWarning,
                                      haltOnFatalError,
                                      noFileCompression, true, !Logger.Verbose, true,
                                      false, SPUpdateVersions.Append, suppressAfterEvents);

                    Logger.Write("Site imported.\r\n");

            #if MOSS
                    Logger.Write("Repairing imported site...");
                    // Need to add a small delay here as the repair seems to fail occassionally due to a timing issue.
                    Common.TimerJobs.ExecAdmSvcJobs.Execute(false, true);
                    int tryCount = 0;
                    while (true)
                    {
                        try
                        {
                            tryCount++;
                            Common.SiteCollections.RepairSiteCollectionImportedFromSubSite.RepairSite(sourceurl, targeturl);
                            break;
                        }
                        catch (InvalidPublishingWebException)
                        {
                            if (haltOnWarning)
                                throw;
                            if (tryCount > 3)
                            {
                                Logger.WriteWarning("Repair of site collection failed - unable to get Pages library.  Manually run 'repairsitecollectionimportedfromsubsite' command to try again.");
                                break;
                            }
                            else
                                Thread.Sleep(10000);
                        }
                        catch (OutOfMemoryException)
                        {
                            if (haltOnWarning)
                                throw;

                            Logger.WriteWarning("Server ran out of memory and was not able to complete the repair operation.  Manually run 'repairsitecollectionimportedfromsubsite' command to try again.");
                            break;
                        }
                    }
                    Logger.Write("Imported site repaired.\r\n");
            #endif

                    // Upgrade any redirect links if present.
                    if (sourceSite.WebApplication.Id == targetSite.WebApplication.Id)
                    {
                        //Console.WriteLine("Repairing Area upgrade URLs...");
                        // The spsredirect.aspx page which uses the upgrade list only supports server relative urls so
                        // if we change the link to be absolute the redirect won't work so don't bother changing it.
                        // Note that we could get around this if we had a simple redirect page that could take in
                        // a target url - then we could have spsredirect.aspx load the server relative redirect
                        // page which would have the actual url passed into it (unfortunately redirect.aspx does
                        // some funky stuff so we can't use it).
                        //UpdateV2ToV3UpgradeAreaUrlMappings.FixUpgradeAreaUrlMappings(sourceSite.WebApplication,
                        //                                                             sourceWeb.ServerRelativeUrl,
                        //                                                             targetWeb.ServerRelativeUrl);
                        //Console.WriteLine("Area upgrade URLs repaired.\r\n");
                    }

                    if (deleteSource)
                    {
                        Logger.Write("Deleting source web...");
                        if (!sourceWeb.IsRootWeb)
                        {
                            DeleteSubWebs(sourceWeb.Webs);

                            sourceWeb.Delete();
                            Logger.Write("Source web deleted.\r\n");
                            Logger.Write("You can find the exported web at " + exportedFile + "\r\n");
                        }
                        else
                            Logger.Write("Source web is a root web - cannot delete.");
                    }
                    return targetSite;
                }
            }
            catch (Exception ex)
            {
                Logger.WriteException(new System.Management.Automation.ErrorRecord(ex, null, System.Management.Automation.ErrorCategory.NotSpecified, null));
            }
            return null;
        }
        private string createSite(string url, SPSiteSubscription subscription, string title, string description, string user, string fullName, string email, string template, out Guid siteid, bool useHostHeader)
        {
            siteid = Guid.Empty;
            string errors = "";

            try
            {
                SPSite site;
                if (subscription != null)
                {
                    site = app.Sites.Add(subscription, url, title, description, 1033, "", user, fullName, email, null, null, null, useHostHeader);
                }
                else
                {
                    site = app.Sites.Add(url, title, description, 1033, "", user, fullName, email, null, null, null, useHostHeader);
                }
                try
                {                                 //SPSite site = spApp.Sites.Add(bUrl + url, user, email);
                    site.AllowUnsafeUpdates = true;
                    using (SPWeb web = site.OpenWeb())

                    {
                        web.Title = title;
                        web.AllowUnsafeUpdates              = true;
                        web.Site.AllowUnsafeUpdates         = true;
                        web.Site.RootWeb.AllowUnsafeUpdates = true;
                        //SPDocumentLibrary solGallery1 = (SPDocumentLibrary)web.Site.RootWeb.Site.GetCatalog(SPListTemplateType.SolutionCatalog);


                        string[] files   = Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.CommonProgramFiles) + "\\workengine\\templates\\" + template);
                        int      counter = 1;
                        foreach (string file in files)
                        {
                            addfile(Path.GetFileNameWithoutExtension(file), web, file, counter);
                            counter++;
                        }

                        SPWebTemplate webtemplate = null;
                        foreach (SPWebTemplate t in web.GetAvailableWebTemplates((uint)web.Locale.LCID))
                        {
                            if (t.Title == template)
                            {
                                webtemplate = t;
                                break;
                            }
                        }

                        if (webtemplate != null)
                        {
                            web.ApplyWebTemplate(webtemplate);
                        }

                        //web.Update();

                        //web.AllUsers.Add(user, email, fullName, "");
                        ////web.AllUsers.Add(System.Configuration.ConfigurationManager.AppSettings["owner"].ToString(), "", System.Configuration.ConfigurationManager.AppSettings["owner"].ToString(), "");
                        //web.Users[user].Name = fullName;
                        //web.Users[user].Update();

                        //web.Update();
                        SPUser owner = web.AllUsers[user];


                        web.SiteGroups.Add("Administrators", owner, owner, "");

                        //web.Update();
                        web.AssociatedOwnerGroup = GetSiteGroup(web, "Administrators");
                        SPRole roll = web.Roles["Full Control"];
                        roll.AddGroup(web.SiteGroups["Administrators"]);
                        SPMember newOwner = web.SiteGroups["Administrators"];

                        web.SiteGroups.Add("Team Members", newOwner, owner, "");
                        web.SiteGroups.Add("Visitors", newOwner, owner, "");
                        web.SiteGroups.Add("Project Managers", newOwner, owner, "");
                        //web.Update();

                        web.AssociatedVisitorGroup = GetSiteGroup(web, "Visitors");
                        web.AssociatedOwnerGroup   = GetSiteGroup(web, "Administrators");
                        web.AssociatedMemberGroup  = GetSiteGroup(web, "Team Members");
                        // web.Update();

                        //web.SiteGroups["Administrators"].Users[user].Name = fullName;
                        //web.SiteGroups["Project Managers"].Users[user].Name = fullName;
                        //web.SiteGroups["Team Members"].Users[user].Name = fullName;
                        //web.SiteGroups["Visitors"].Users[user].Name = fullName;

                        web.Roles.Add("Contribute2", "Can view, add, update, delete and manage subwebs", web.Roles["Contribute"].PermissionMask | SPRights.ManageSubwebs);

                        roll = web.Roles["Full Control"];
                        roll.AddGroup(web.SiteGroups["Administrators"]);

                        roll = web.Roles["Contribute"];
                        roll.AddGroup(web.SiteGroups["Team Members"]);

                        roll = web.Roles["Read"];
                        roll.AddGroup(web.SiteGroups["Visitors"]);

                        roll = web.Roles["Contribute2"];
                        roll.AddGroup(web.SiteGroups["Project Managers"]);

                        siteid = site.ID;

                        if (txtDatabaseServer.Text != "")
                        {
                            errors = mapReports(site);
                        }
                    }
                }
                catch (Exception ex) { errors = ex.ToString(); }
                finally
                {
                    if (site != null)
                    {
                        site.Dispose();
                    }
                }
            }
            catch (Exception ex)
            {
                errors = ex.Message;
            }

            return(errors);
        }