예제 #1
0
파일: SfB2015.cs 프로젝트: pasamsin/SolidCP
        /// <summary> Removes domain from allowed list.</summary>
        /// <param name="organizationId"> The organization identifier.</param>
        /// <param name="domainName"> The domain name.</param>
        /// <returns> The result.</returns>
        internal override bool RemoveFederationDomainInternal(string organizationId, string domainName)
        {
            HostedSolutionLog.LogStart("RemoveFederationDomainInternal");
            HostedSolutionLog.DebugInfo("organizationId: {0}", organizationId);
            HostedSolutionLog.DebugInfo("domainName: {0}", domainName);
            Runspace runspace = null;

            try
            {
                runspace = OpenRunspace();
                var command = new Command("Remove-CsAllowedDomain");
                command.Parameters.Add("Identity", domainName);
                ExecuteShellCommand(runspace, command, false);
            }
            catch (Exception ex)
            {
                HostedSolutionLog.LogError("RemoveFederationDomainInternal", ex);
                throw;
            }
            finally
            {
                CloseRunspace(runspace);
            }

            HostedSolutionLog.LogEnd("RemoveFederationDomainInternal");

            return(true);
        }
예제 #2
0
        private void SetUserGeneralSettingsInternal(string instanceId, bool enabledForFederation, bool enabledForPublicIMConectivity, bool archiveInternalCommunications, bool archiveFederatedCommunications, bool enabledForEnhancedPresence)
        {
            HostedSolutionLog.LogStart("SetUserGeneralSettingsInternal");
            try
            {
                if (string.IsNullOrEmpty(instanceId))
                {
                    throw new ArgumentException("instanceId");
                }

                using (ManagementObject userObject = GetUserByInstanceId(instanceId))
                {
                    if (userObject == null)
                    {
                        throw new Exception(string.Format("OCS user {0} not found", instanceId));
                    }

                    userObject["EnabledForFederation"]           = enabledForFederation;
                    userObject["PublicNetworkEnabled"]           = enabledForPublicIMConectivity;
                    userObject["ArchiveInternalCommunications"]  = archiveInternalCommunications;
                    userObject["ArchiveFederatedCommunications"] = archiveFederatedCommunications;
                    if (enabledForEnhancedPresence)
                    {
                        userObject["EnabledForEnhancedPresence"] = true;
                    }
                    userObject.Put();
                }
            }
            catch (Exception ex)
            {
                HostedSolutionLog.LogError("SetUserGeneralSettingsInternal", ex);
                throw;
            }
            HostedSolutionLog.LogEnd("SetUserGeneralSettingsInternal");
        }
예제 #3
0
        public long GetSiteCollectionSize(Uri root, string url)
        {
            WindowsImpersonationContext wic = null;

            try
            {
                wic = WindowsIdentity.GetCurrent().Impersonate();

                SPWebApplication rootWebApplication = SPWebApplication.Lookup(root);
                SPSite           site = rootWebApplication.Sites[url];
                if (site != null)
                {
                    site.RecalculateStorageUsed();
                }
                else
                {
                    throw new ApplicationException(string.Format("SiteCollection {0} does not exist", url));
                }

                return(site.Usage.Storage);
            }
            catch (Exception ex)
            {
                HostedSolutionLog.LogError(ex);
                throw;
            }
            finally
            {
                if (wic != null)
                {
                    wic.Undo();
                }
            }
        }
예제 #4
0
파일: SfBBase.cs 프로젝트: pasamsin/SolidCP
        /// <summary> Rollbacks the transaction.</summary>
        /// <param name="transaction"> The transaction.</param>
        internal void RollbackTransaction(SfBTransaction transaction)
        {
            HostedSolutionLog.LogStart("RollbackTransaction");
            Runspace runspace = null;

            try
            {
                runspace = OpenRunspace();

                for (int i = transaction.Actions.Count - 1; i > -1; i--)
                {
                    try
                    {
                        RollbackAction(transaction.Actions[i], runspace);
                    }
                    catch (Exception ex)
                    {
                        HostedSolutionLog.LogError("Rollback error", ex);
                    }
                }
            }
            catch (Exception ex)
            {
                HostedSolutionLog.LogError("Rollback error", ex);
            }
            finally
            {
                CloseRunspace(runspace);
            }
            HostedSolutionLog.LogEnd("RollbackTransaction");
        }
예제 #5
0
파일: SfB2015.cs 프로젝트: pasamsin/SolidCP
        /// <summary> Gets allowed domains.</summary>
        /// <param name="organizationId"> The organization identifier.</param>
        /// <returns> Allowed domains.</returns>
        internal override SfBFederationDomain[] GetFederationDomainsInternal(string organizationId)
        {
            HostedSolutionLog.LogStart("GetFederationDomainsInternal");
            HostedSolutionLog.DebugInfo("organizationId: {0}", organizationId);
            SfBFederationDomain[] domains;
            Runspace runspace = null;

            try
            {
                runspace = OpenRunspace();
                domains  = GetFederationDomainsInternal(runspace);
            }
            catch (Exception ex)
            {
                HostedSolutionLog.LogError("GetFederationDomainsInternal", ex);
                throw;
            }
            finally
            {
                CloseRunspace(runspace);
            }

            HostedSolutionLog.LogEnd("GetFederationDomainsInternal");

            return(domains);
        }
예제 #6
0
파일: SfB2015.cs 프로젝트: pasamsin/SolidCP
        /// <summary> Deletes user.</summary>
        /// <param name="userUpn"> The user UPN.</param>
        /// <returns> The result.</returns>
        internal override bool DeleteUserInternal(string userUpn)
        {
            HostedSolutionLog.LogStart("DeleteUserInternal");
            HostedSolutionLog.DebugInfo("userUpn: {0}", userUpn);
            Runspace runspace = null;

            try
            {
                runspace = OpenRunspace();
                DeleteUser(runspace, userUpn);

                var command = new Command("Get-CsAdUser");
                command.Parameters.Add("Identity", userUpn);
                ExecuteShellCommand(runspace, command, false);

                command = new Command("Update-CsAddressBook");
                ExecuteShellCommand(runspace, command, false);

                command = new Command("Update-CsUserDatabase");
                ExecuteShellCommand(runspace, command, false);
            }
            catch (Exception ex)
            {
                HostedSolutionLog.LogError("DeleteUserInternal", ex);
                throw;
            }
            finally
            {
                CloseRunspace(runspace);
            }

            HostedSolutionLog.LogEnd("DeleteUserInternal");

            return(true);
        }
예제 #7
0
        public SharePointSiteDiskSpace[] CalculateSiteCollectionDiskSpace(Uri root, string[] urls)
        {
            WindowsImpersonationContext wic = null;

            try
            {
                wic = WindowsIdentity.GetCurrent().Impersonate();

                SPWebApplication rootWebApplication = SPWebApplication.Lookup(root);

                List <SharePointSiteDiskSpace> ret = new List <SharePointSiteDiskSpace>();
                foreach (string url in urls)
                {
                    SharePointSiteDiskSpace siteDiskSpace = new SharePointSiteDiskSpace();
                    rootWebApplication.Sites[url].RecalculateStorageUsed();
                    siteDiskSpace.Url       = url;
                    siteDiskSpace.DiskSpace = (long)Math.Round(rootWebApplication.Sites[url].Usage.Storage / 1024.0 / 1024.0);
                    ret.Add(siteDiskSpace);
                }
                return(ret.ToArray());
            }
            catch (Exception ex)
            {
                HostedSolutionLog.LogError(ex);
                throw;
            }
            finally
            {
                if (wic != null)
                {
                    wic.Undo();
                }
            }
        }
예제 #8
0
        private void AddDomainInternal(string domainName)
        {
            HostedSolutionLog.LogStart("AddDomainInternal");
            HostedSolutionLog.DebugInfo("Domain Name: {0}", domainName);
            try
            {
                if (string.IsNullOrEmpty(domainName))
                {
                    throw new ArgumentException("domainName");
                }

                if (GetDomain(domainName) != null)
                {
                    HostedSolutionLog.LogWarning("OCS internal domain '{0}' already exists", domainName);
                }
                else
                {
                    using (ManagementObject newDomain = Wmi.CreateInstance("MSFT_SIPFederationInternalDomainData"))
                    {
                        newDomain["SupportedInternalDomain"] = domainName;
                        newDomain.Put();
                    }
                }
            }
            catch (Exception ex)
            {
                HostedSolutionLog.LogError("AddDomainInternal", ex);
                throw;
            }
            HostedSolutionLog.LogEnd("AddDomainInternal");
        }
예제 #9
0
        private void DeleteDomainInternal(string domainName)
        {
            HostedSolutionLog.LogStart("DeleteDomainInternal");
            HostedSolutionLog.DebugInfo("Domain Name: {0}", domainName);
            try
            {
                if (string.IsNullOrEmpty(domainName))
                {
                    throw new ArgumentException("domainName");
                }

                using (ManagementObject domainObj = GetDomain(domainName))
                {
                    if (domainObj == null)
                    {
                        HostedSolutionLog.LogWarning("OCS internal domain '{0}' not found", domainName);
                    }
                    else
                    {
                        domainObj.Delete();
                    }
                }
            }
            catch (Exception ex)
            {
                HostedSolutionLog.LogError("DeleteDomainInternal", ex);
                throw;
            }
            HostedSolutionLog.LogEnd("DeleteDomainInternal");
        }
예제 #10
0
        private void DeleteUserInternal(string instanceId)
        {
            HostedSolutionLog.LogStart("DeleteUserInternal");
            try
            {
                if (string.IsNullOrEmpty(instanceId))
                {
                    throw new ArgumentException("instanceId");
                }

                using (ManagementObject userObject = GetUserByInstanceId(instanceId))
                {
                    if (userObject == null)
                    {
                        HostedSolutionLog.LogWarning("OCS user {0} not found", instanceId);
                    }
                    else
                    {
                        userObject.Delete();
                    }
                }
            }
            catch (Exception ex)
            {
                HostedSolutionLog.LogError("DeleteUserInternal", ex);
                throw;
            }
            HostedSolutionLog.LogEnd("DeleteUserInternal");
        }
예제 #11
0
        private void SetUserPrimaryUriInternal(string instanceId, string userUpn)
        {
            HostedSolutionLog.LogStart("SetUserPrimaryUriInternal");
            try
            {
                if (string.IsNullOrEmpty(instanceId))
                {
                    throw new ArgumentException("instanceId");
                }

                if (string.IsNullOrEmpty(userUpn))
                {
                    throw new ArgumentException("userUpn");
                }

                using (ManagementObject userObject = GetUserByInstanceId(instanceId))
                {
                    if (userObject == null)
                    {
                        throw new Exception(string.Format("OCS user {0} not found", instanceId));
                    }
                    string primaryUri = "sip:" + userUpn;
                    userObject["PrimaryURI"] = primaryUri;
                    userObject.Put();
                }
            }
            catch (Exception ex)
            {
                HostedSolutionLog.LogError("SetUserPrimaryUriInternal", ex);
                throw;
            }
            HostedSolutionLog.LogEnd("SetUserPrimaryUriInternal");
        }
예제 #12
0
 /// <summary>Closes runspace.</summary>
 /// <param name="runspace">The runspace.</param>
 private void CloseRunspace(Runspace runspace)
 {
     try
     {
         if (runspace != null && runspace.RunspaceStateInfo.State == RunspaceState.Opened)
         {
             runspace.Close();
         }
     }
     catch (Exception ex)
     {
         HostedSolutionLog.LogError("Runspace error", ex);
     }
 }
예제 #13
0
        public void UpdateQuotas(Uri root, string url, long maxStorage, long warningStorage)
        {
            WindowsImpersonationContext wic = null;

            try
            {
                wic = WindowsIdentity.GetCurrent().Impersonate();

                SPWebApplication rootWebApplication = SPWebApplication.Lookup(root);

                SPQuota quota = new SPQuota();
                if (maxStorage != -1)
                {
                    quota.StorageMaximumLevel = maxStorage * 1024 * 1024;
                }
                else
                {
                    quota.StorageMaximumLevel = 0;
                }


                if (warningStorage != -1 && maxStorage != -1)
                {
                    quota.StorageWarningLevel = Math.Min(warningStorage, maxStorage) * 1024 * 1024;
                }
                else
                {
                    quota.StorageWarningLevel = 0;
                }

                rootWebApplication.GrantAccessToProcessIdentity(WindowsIdentity.GetCurrent().Name);
                rootWebApplication.Sites[url].Quota = quota;
            }
            catch (Exception ex)
            {
                HostedSolutionLog.LogError(ex);
                throw;
            }
            finally
            {
                if (wic != null)
                {
                    wic.Undo();
                }
            }
        }
예제 #14
0
파일: SfB2015.cs 프로젝트: pasamsin/SolidCP
        /// <summary> Gets users general settings.</summary>
        /// <param name="organizationId"> The organization identifier.</param>
        /// <param name="userUpn"> The user UPN.</param>
        /// <returns> User settings.</returns>
        internal override SfBUser GetSfBUserGeneralSettingsInternal(string organizationId, string userUpn)
        {
            HostedSolutionLog.LogStart("GetSfBUserGeneralSettingsInternal");
            HostedSolutionLog.DebugInfo("organizationId: {0}", organizationId);
            HostedSolutionLog.DebugInfo("userUpn: {0}", userUpn);
            var      sfbUser  = new SfBUser();
            Runspace runspace = null;

            try
            {
                runspace = OpenRunspace();

                var command = new Command("Get-CsUser");
                command.Parameters.Add("Identity", userUpn);
                Collection <PSObject> result = ExecuteShellCommand(runspace, command, false);
                PSObject user = result[0];

                sfbUser.DisplayName = (string)GetPSObjectProperty(user, "DisplayName");
                sfbUser.SipAddress  = (string)GetPSObjectProperty(user, "SipAddress");
                sfbUser.LineUri     = (string)GetPSObjectProperty(user, "LineURI");

                sfbUser.SipAddress = sfbUser.SipAddress.ToLower().Replace("sip:", "");
                sfbUser.LineUri    = sfbUser.LineUri.ToLower().Replace("tel:+", "");
                sfbUser.LineUri    = sfbUser.LineUri.ToLower().Replace("tel:", "");
            }
            catch (Exception ex)
            {
                HostedSolutionLog.LogError("GetSfBUserGeneralSettingsInternal", ex);
                throw;
            }
            finally
            {
                CloseRunspace(runspace);
            }

            HostedSolutionLog.LogEnd("GetSfBUserGeneralSettingsInternal");

            return(sfbUser);
        }
예제 #15
0
        /// <summary>Gets SharePoint site collection.</summary>
        /// <param name="rootWebApplicationUri">The root web application uri.</param>
        /// <param name="url">The required site url.</param>
        /// <returns>The SharePoint sites.</returns>
        private SPSite GetSPSiteCollection(Uri rootWebApplicationUri, string url)
        {
            Runspace runspace = null;

            try
            {
                string siteCollectionUrl = String.Format("{0}:{1}", url, rootWebApplicationUri.Port);
                runspace = OpenRunspace();
                var cmd = new Command("Get-SPSite");
                cmd.Parameters.Add("Identity", siteCollectionUrl);
                Collection <PSObject> result = ExecuteShellCommand(runspace, cmd);

                if (result != null && result.Count() == 1)
                {
                    var spSite = result.First().BaseObject as SPSite;

                    if (spSite == null)
                    {
                        throw new ApplicationException(string.Format("SiteCollection {0} does not exist", url));
                    }

                    return(result.First().BaseObject as SPSite);
                }
                else
                {
                    throw new ApplicationException(string.Format("SiteCollection {0} does not exist", url));
                }
            }
            catch (Exception ex)
            {
                HostedSolutionLog.LogError(ex);
                throw;
            }
            finally
            {
                CloseRunspace(runspace);
            }
        }
예제 #16
0
파일: SfB2015.cs 프로젝트: pasamsin/SolidCP
        /// <summary> Adds domain to allowed list.</summary>
        /// <param name="organizationId"> The organization identifier.</param>
        /// <param name="domainName"> The domain name.</param>
        /// <param name="proxyFqdn"> The ProxyFQDN.</param>
        /// <returns> The result.</returns>
        internal override bool AddFederationDomainInternal(string organizationId, string domainName, string proxyFqdn)
        {
            domainName = domainName.ToLower();
            Runspace runspace = null;

            try
            {
                runspace = OpenRunspace();
                var command = new Command("Get-CsAllowedDomain");
                command.Parameters.Add("Identity", domainName);
                Collection <PSObject> result = ExecuteShellCommand(runspace, command, false);

                if (result != null && !result.Any())
                {
                    command = new Command("New-CsAllowedDomain");
                    command.Parameters.Add("Identity", domainName);
                    ExecuteShellCommand(runspace, command, false);

                    command = new Command("Set-CsAllowedDomain");
                    command.Parameters.Add("Identity", domainName);
                    command.Parameters.Add("ProxyFQDN", PoolFQDN);
                    ExecuteShellCommand(runspace, command, false);
                }
            }
            catch (Exception ex)
            {
                HostedSolutionLog.LogError("AddFederationDomainInternal", ex);
                throw;
            }
            finally
            {
                CloseRunspace(runspace);
            }

            HostedSolutionLog.LogEnd("AddFederationDomainInternal");

            return(true);
        }
예제 #17
0
        private OCSUser GetUserGeneralSettingsInternal(string instanceId)
        {
            HostedSolutionLog.LogStart("GetUserGeneralSettingsInternal");
            try
            {
                if (string.IsNullOrEmpty(instanceId))
                {
                    throw new ArgumentException("instanceId");
                }

                using (ManagementObject userObject = GetUserByInstanceId(instanceId))
                {
                    if (userObject == null)
                    {
                        throw new Exception(string.Format("OCS user {0} not found", instanceId));
                    }

                    OCSUser user = new OCSUser();
                    user.InstanceId                     = instanceId;
                    user.PrimaryUri                     = (string)userObject["PrimaryURI"];
                    user.DisplayName                    = (string)userObject["DisplayName"];
                    user.EnabledForFederation           = (bool)userObject["EnabledForFederation"];
                    user.EnabledForPublicIMConectivity  = (bool)userObject["PublicNetworkEnabled"];
                    user.ArchiveInternalCommunications  = (bool)userObject["ArchiveInternalCommunications"];
                    user.ArchiveFederatedCommunications = (bool)userObject["ArchiveFederatedCommunications"];
                    user.EnabledForEnhancedPresence     = (bool)userObject["EnabledForEnhancedPresence"];

                    HostedSolutionLog.LogEnd("GetUserGeneralSettingsInternal");

                    return(user);
                }
            }
            catch (Exception ex)
            {
                HostedSolutionLog.LogError("GetUserGeneralSettingsInternal", ex);
                throw;
            }
        }
예제 #18
0
파일: SfB2015.cs 프로젝트: pasamsin/SolidCP
        /// <summary> Refreshes configuration.</summary>
        internal override void ReloadConfigurationInternal()
        {
            HostedSolutionLog.LogStart("ReloadConfigurationInternal");
            Runspace runspace = null;

            try
            {
                runspace = OpenRunspace();

                var command = new Command("Enable-CsComputer");
                ExecuteShellCommand(runspace, command, false);
            }
            catch (Exception ex)
            {
                HostedSolutionLog.LogError("ReloadConfigurationInternal", ex);
                throw;
            }
            finally
            {
                CloseRunspace(runspace);
            }
            HostedSolutionLog.LogEnd("ReloadConfigurationInternal");
        }
예제 #19
0
        /// <summary>
        /// Creates site collection within predefined root web application.
        /// </summary>
        /// <param name="rootWebApplicationUri">Root web application uri.</param>
        /// <param name="siteCollection">Information about site coolection to be created.</param>
        /// <exception cref="InvalidOperationException">Is thrown in case requested operation fails for any reason.</exception>
        public void CreateSiteCollection(Uri rootWebApplicationUri, SharePointSiteCollection siteCollection)
        {
            WindowsImpersonationContext wic = null;

            HostedSolutionLog.LogStart("CreateSiteCollection");

            try
            {
                wic = WindowsIdentity.GetCurrent().Impersonate();
                SPWebApplication rootWebApplication = SPWebApplication.Lookup(rootWebApplicationUri);
                string           siteCollectionUrl  = String.Format("{0}:{1}", siteCollection.Url, rootWebApplicationUri.Port);

                HostedSolutionLog.DebugInfo("rootWebApplicationUri: {0}", rootWebApplicationUri);
                HostedSolutionLog.DebugInfo("siteCollectionUrl: {0}", siteCollectionUrl);

                SPQuota spQuota;

                SPSite spSite = rootWebApplication.Sites.Add(siteCollectionUrl,
                                                             siteCollection.Title, siteCollection.Description,
                                                             (uint)siteCollection.LocaleId, String.Empty,
                                                             siteCollection.OwnerLogin, siteCollection.OwnerName,
                                                             siteCollection.OwnerEmail,
                                                             null, null, null, true);

                try
                {
                    spQuota = new SPQuota();

                    if (siteCollection.MaxSiteStorage != -1)
                    {
                        spQuota.StorageMaximumLevel = siteCollection.MaxSiteStorage * 1024 * 1024;
                    }

                    if (siteCollection.WarningStorage != -1 && siteCollection.MaxSiteStorage != -1)
                    {
                        spQuota.StorageWarningLevel = Math.Min(siteCollection.WarningStorage, siteCollection.MaxSiteStorage) * 1024 * 1024;
                    }
                }
                catch (Exception)
                {
                    rootWebApplication.Sites.Delete(siteCollectionUrl);
                    throw;
                }

                try
                {
                    rootWebApplication.GrantAccessToProcessIdentity(WindowsIdentity.GetCurrent().Name);
                    spSite.Quota = spQuota;
                }
                catch (Exception)
                {
                    rootWebApplication.Sites.Delete(siteCollectionUrl);
                    DeleteQuotaTemplate(siteCollection.Title);
                    throw;
                }

                rootWebApplication.Update(true);

                try
                {
                    if (siteCollection.RootWebApplicationInteralIpAddress != string.Empty)
                    {
                        string dirPath = FileUtils.EvaluateSystemVariables(@"%windir%\system32\drivers\etc");
                        string path    = dirPath + "\\hosts";

                        if (FileUtils.FileExists(path))
                        {
                            string content = FileUtils.GetFileTextContent(path);
                            content = content.Replace("\r\n", "\n").Replace("\n\r", "\n");
                            string[] contentArr   = content.Split(new char[] { '\n' });
                            bool     bRecordExist = false;
                            foreach (string s in contentArr)
                            {
                                if (s != string.Empty)
                                {
                                    string IPAddr   = string.Empty;
                                    string hostName = string.Empty;
                                    if (s[0] != '#')
                                    {
                                        bool bSeperator = false;
                                        foreach (char c in s)
                                        {
                                            if ((c != ' ') & (c != '\t'))
                                            {
                                                if (bSeperator)
                                                {
                                                    hostName += c;
                                                }
                                                else
                                                {
                                                    IPAddr += c;
                                                }
                                            }
                                            else
                                            {
                                                bSeperator = true;
                                            }
                                        }

                                        if (hostName.ToLower() == siteCollection.RootWebApplicationFQDN.ToLower())
                                        {
                                            bRecordExist = true;
                                            break;
                                        }
                                    }
                                }
                            }

                            if (!bRecordExist)
                            {
                                string outPut = string.Empty;
                                foreach (string o in contentArr)
                                {
                                    if (o != string.Empty)
                                    {
                                        outPut += o + "\r\n";
                                    }
                                }

                                outPut += siteCollection.RootWebApplicationInteralIpAddress + '\t' + siteCollection.RootWebApplicationFQDN + "\r\n";

                                FileUtils.UpdateFileTextContent(path, outPut);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    HostedSolutionLog.LogError(ex);
                }
            }
            catch (Exception ex)
            {
                HostedSolutionLog.LogError(ex);
                throw;
            }
            finally
            {
                if (wic != null)
                {
                    wic.Undo();
                }

                HostedSolutionLog.LogEnd("CreateSiteCollection");
            }
        }
예제 #20
0
파일: SfB2015.cs 프로젝트: pasamsin/SolidCP
        /// <summary> Creates organization. </summary>
        /// <param name="organizationId"> The organization identifier. </param>
        /// <param name="sipDomain"> The sip domain. </param>
        /// <param name="enableConferencingVideo"> True - if conferencing video should be enabled.</param>
        /// <param name="maxConferenceSize"> The max conference size.</param>
        /// <param name="enabledFederation"> True - if federations should be enabled.</param>
        /// <param name="enabledEnterpriseVoice"> True - if enterprise voice should be enabled.</param>
        /// <returns> The tenant identifier. </returns>
        internal override string CreateOrganizationInternal(string organizationId, string sipDomain, bool enableConferencingVideo, int maxConferenceSize, bool enabledFederation, bool enabledEnterpriseVoice)
        {
            sipDomain = sipDomain.ToLower();
            HostedSolutionLog.LogStart("CreateOrganizationInternal");
            HostedSolutionLog.DebugInfo("organizationId: {0}", organizationId);
            HostedSolutionLog.DebugInfo("sipDomain: {0}", sipDomain);
            string         tenantId;
            SfBTransaction transaction = StartTransaction();
            Runspace       runspace    = null;

            try
            {
                runspace = OpenRunspace();
                var command = new Command("New-CsSipDomain");
                command.Parameters.Add("Identity", sipDomain);
                ExecuteShellCommand(runspace, command, false);
                transaction.RegisterNewSipDomain(sipDomain);
                Guid id = Guid.NewGuid();

                AddAdDomainName(organizationId, sipDomain);

                CreateSimpleUrl(runspace, id);
                transaction.RegisterNewSimpleUrl(sipDomain, id.ToString());

                command = new Command("New-CsConferencingPolicy");
                command.Parameters.Add("Identity", organizationId);
                command.Parameters.Add("MaxMeetingSize", ((maxConferenceSize == -1) | (maxConferenceSize > 250)) ? 250 : maxConferenceSize);
                command.Parameters.Add("AllowIPVideo", enableConferencingVideo);
                ExecuteShellCommand(runspace, command, false);
                transaction.RegisterNewConferencingPolicy(organizationId);

                command = new Command("New-CsExternalAccessPolicy");
                command.Parameters.Add("Identity", organizationId);
                command.Parameters.Add("EnableFederationAccess", true);
                command.Parameters.Add("EnableOutsideAccess", true);
                command.Parameters.Add("EnablePublicCloudAccess", false);
                command.Parameters.Add("EnablePublicCloudAudioVideoAccess", false);
                ExecuteShellCommand(runspace, command, false);
                transaction.RegisterNewCsExternalAccessPolicy(organizationId);

                var allowList = new AllowList();
                var domain    = new DomainPattern(sipDomain);
                allowList.AllowedDomain.Add(domain);

                AddFederationDomainInternal("", domain.Domain, PoolFQDN);

                command = new Command("New-CsMobilityPolicy");
                command.Parameters.Add("Identity", organizationId + " EnableOutSideVoice");
                command.Parameters.Add("EnableMobility", true);
                command.Parameters.Add("EnableOutsideVoice", true);
                ExecuteShellCommand(runspace, command, false);
                transaction.RegisterNewCsMobilityPolicy(organizationId + " EnableOutSideVoice");

                command = new Command("New-CsMobilityPolicy");
                command.Parameters.Add("Identity", organizationId + " DisableOutSideVoice");
                command.Parameters.Add("EnableMobility", true);
                command.Parameters.Add("EnableOutsideVoice", false);
                ExecuteShellCommand(runspace, command, false);
                transaction.RegisterNewCsMobilityPolicy(organizationId + " DisableOutSideVoice");

                command = new Command("Invoke-CsManagementStoreReplication");
                ExecuteShellCommand(runspace, command, false);

                tenantId = id.ToString();
            }
            catch (Exception ex)
            {
                HostedSolutionLog.LogError("CreateOrganizationInternal", ex);
                RollbackTransaction(transaction);
                throw;
            }
            finally
            {
                CloseRunspace(runspace);
            }

            HostedSolutionLog.LogEnd("CreateOrganizationInternal");

            return(tenantId);
        }
예제 #21
0
        /// <summary>
        /// Deletes site collection under given url.
        /// </summary>
        /// <param name="rootWebApplicationUri">Root web application uri.</param>
        /// <param name="url">Url that uniquely identifies site collection to be deleted.</param>
        /// <exception cref="InvalidOperationException">Is thrown in case requested operation fails for any reason.</exception>
        public void DeleteSiteCollection(Uri rootWebApplicationUri, SharePointSiteCollection siteCollection)
        {
            try
            {
                WindowsIdentity             identity = WindowsIdentity.GetCurrent();
                WindowsImpersonationContext wic      = identity.Impersonate();

                try
                {
                    SPWebApplication rootWebApplication = SPWebApplication.Lookup(rootWebApplicationUri);
                    string           siteCollectionUrl  = String.Format("{0}:{1}", siteCollection.Url, rootWebApplicationUri.Port);

                    //string args = String.Format("-o deletesite -url {0}", siteCollectionUrl);
                    //string stsadm = @"c:\Program Files\Common Files\Microsoft Shared\web server extensions\12\BIN\STSADM.EXE";

                    //// launch system process
                    //ProcessStartInfo startInfo = new ProcessStartInfo(stsadm, args);
                    //startInfo.WindowStyle = ProcessWindowStyle.Hidden;
                    //startInfo.RedirectStandardOutput = true;
                    //startInfo.UseShellExecute = false;
                    //Process proc = Process.Start(startInfo);

                    //// analyze results
                    //StreamReader reader = proc.StandardOutput;
                    //string output = reader.ReadToEnd();
                    //int exitCode = proc.ExitCode;
                    //reader.Close();


                    rootWebApplication.Sites.Delete(siteCollectionUrl, true);
                    rootWebApplication.Update(true);

                    try
                    {
                        if (siteCollection.RootWebApplicationInteralIpAddress != string.Empty)
                        {
                            string dirPath = FileUtils.EvaluateSystemVariables(@"%windir%\system32\drivers\etc");
                            string path    = dirPath + "\\hosts";

                            if (FileUtils.FileExists(path))
                            {
                                string content = FileUtils.GetFileTextContent(path);
                                content = content.Replace("\r\n", "\n").Replace("\n\r", "\n");
                                string[] contentArr = content.Split(new char[] { '\n' });
                                string   outPut     = string.Empty;
                                foreach (string s in contentArr)
                                {
                                    if (s != string.Empty)
                                    {
                                        string IPAddr   = string.Empty;
                                        string hostName = string.Empty;
                                        if (s[0] != '#')
                                        {
                                            bool bSeperator = false;
                                            foreach (char c in s)
                                            {
                                                if ((c != ' ') & (c != '\t'))
                                                {
                                                    if (bSeperator)
                                                    {
                                                        hostName += c;
                                                    }
                                                    else
                                                    {
                                                        IPAddr += c;
                                                    }
                                                }
                                                else
                                                {
                                                    bSeperator = true;
                                                }
                                            }

                                            if (hostName.ToLower() != siteCollection.RootWebApplicationFQDN.ToLower())
                                            {
                                                outPut += s + "\r\n";
                                            }
                                        }
                                        else
                                        {
                                            outPut += s + "\r\n";
                                        }
                                    }
                                }

                                FileUtils.UpdateFileTextContent(path, outPut);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        HostedSolutionLog.LogError(ex);
                    }
                }
                finally
                {
                    wic.Undo();
                }
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException("Failed to delete site collection.", ex);
            }
        }
예제 #22
0
파일: SfB2015.cs 프로젝트: pasamsin/SolidCP
        /// <summary> Sets users general settings.</summary>
        /// <param name="organizationId"> The organization identifier.</param>
        /// <param name="userUpn"> The user UPN.</param>
        /// <param name="sfbUser"> The sfb user settings.</param>
        /// <returns> The result.</returns>
        internal override bool SetSfBUserGeneralSettingsInternal(string organizationId, string userUpn, SfBUser sfbUser)
        {
            HostedSolutionLog.LogStart("SetSfBUserGeneralSettingsInternal");
            HostedSolutionLog.DebugInfo("organizationId: {0}", organizationId);
            HostedSolutionLog.DebugInfo("userUpn: {0}", userUpn);

            bool           ret         = true;
            Runspace       runspace    = null;
            SfBTransaction transaction = StartTransaction();

            try
            {
                runspace = OpenRunspace();
                Guid     tenantId = GetObjectGuid(organizationId, runspace);
                string[] tmp      = userUpn.Split('@');

                if (tmp.Length < 2)
                {
                    return(false);
                }

                var command = new Command("Get-CsSipDomain");
                Collection <PSObject> sipDomains = ExecuteShellCommand(runspace, command, false);
                bool bSipDomainExists            = sipDomains.Select(domain => (string)GetPSObjectProperty(domain, "Name")).Any(d => d.ToLower() == tmp[1].ToLower());

                if (!bSipDomainExists)
                {
                    command = new Command("New-CsSipDomain");
                    command.Parameters.Add("Identity", tmp[1].ToLower());
                    ExecuteShellCommand(runspace, command, false);

                    transaction.RegisterNewSipDomain(tmp[1].ToLower());

                    string         path      = AddADPrefix(GetOrganizationPath(organizationId));
                    DirectoryEntry ou        = ActiveDirectoryUtils.GetADObject(path);
                    string[]       sipDs     = ActiveDirectoryUtils.GetADObjectPropertyMultiValue(ou, "Url");
                    var            listSipDs = new List <string>();
                    listSipDs.AddRange(sipDs);
                    listSipDs.Add(tmp[1]);

                    ActiveDirectoryUtils.SetADObjectPropertyValue(ou, "Url", listSipDs.ToArray());
                    ou.CommitChanges();

                    CreateSimpleUrl(runspace, tenantId);
                    transaction.RegisterNewSimpleUrl(tmp[1].ToLower(), tenantId.ToString());

                    path = AddADPrefix(GetResultObjectDN(organizationId, runspace));
                    DirectoryEntry user = ActiveDirectoryUtils.GetADObject(path);

                    if (tmp.Length > 0)
                    {
                        string Url = SimpleUrlRoot + tmp[1];
                        ActiveDirectoryUtils.SetADObjectPropertyValue(user, "msRTCSIP-BaseSimpleUrl", Url.ToLower());
                    }

                    user.CommitChanges();
                }

                command = new Command("Set-CsUser");
                command.Parameters.Add("Identity", userUpn);

                if (!string.IsNullOrEmpty(sfbUser.SipAddress))
                {
                    command.Parameters.Add("SipAddress", "SIP:" + sfbUser.SipAddress);
                }

                if (!string.IsNullOrEmpty(sfbUser.LineUri))
                {
                    command.Parameters.Add("LineUri", "TEL:+" + sfbUser.LineUri);
                }
                else
                {
                    command.Parameters.Add("LineUri", null);
                }

                ExecuteShellCommand(runspace, command, false);

                if (!String.IsNullOrEmpty(sfbUser.PIN))
                {
                    command = new Command("Set-CsClientPin");
                    command.Parameters.Add("Identity", userUpn);
                    command.Parameters.Add("Pin", sfbUser.PIN);
                    ExecuteShellCommand(runspace, command, false);
                }

                command = new Command("Update-CsAddressBook");
                ExecuteShellCommand(runspace, command, false);

                command = new Command("Update-CsUserDatabase");
                ExecuteShellCommand(runspace, command, false);
            }
            catch (Exception ex)
            {
                ret = false;
                HostedSolutionLog.LogError("SetSfBUserGeneralSettingsInternal", ex);
                RollbackTransaction(transaction);
            }
            finally
            {
                CloseRunspace(runspace);
            }

            HostedSolutionLog.LogEnd("SetSfBUserGeneralSettingsInternal");

            return(ret);
        }
예제 #23
0
파일: SfB2015.cs 프로젝트: pasamsin/SolidCP
        /// <summary> Sets users sfb plan.</summary>
        /// <param name="organizationId"> The organization identifier.</param>
        /// <param name="userUpn"> The user UPN.</param>
        /// <param name="plan"> The sfb plan.</param>
        /// <param name="runspace"> The runspace.</param>
        /// <returns> The result.</returns>
        internal override bool SetSfBUserPlanInternal(string organizationId, string userUpn, SfBUserPlan plan, Runspace runspace)
        {
            HostedSolutionLog.LogStart("SetSfBUserPlanInternal");
            HostedSolutionLog.DebugInfo("organizationId: {0}", organizationId);
            HostedSolutionLog.DebugInfo("userUpn: {0}", userUpn);
            bool bCloseRunSpace = false;
            bool res            = true;

            try
            {
                if (runspace == null)
                {
                    runspace       = OpenRunspace();
                    bCloseRunSpace = true;
                }

                // EnterpriseVoice
                var command = new Command("Set-CsUser");
                command.Parameters.Add("Identity", userUpn);
                command.Parameters.Add("EnterpriseVoiceEnabled", plan.EnterpriseVoice);
                ExecuteShellCommand(runspace, command, false);

                command = new Command("Grant-CsExternalAccessPolicy");
                command.Parameters.Add("Identity", userUpn);
                command.Parameters.Add("PolicyName", plan.Federation ? organizationId : null);
                ExecuteShellCommand(runspace, command, false);

                command = new Command("Grant-CsConferencingPolicy");
                command.Parameters.Add("Identity", userUpn);
                command.Parameters.Add("PolicyName", plan.Federation ? organizationId : null);
                ExecuteShellCommand(runspace, command, false);

                command = new Command("Grant-CsMobilityPolicy");
                command.Parameters.Add("Identity", userUpn);
                if (plan.Mobility)
                {
                    command.Parameters.Add("PolicyName", plan.MobilityEnableOutsideVoice ? organizationId + " EnableOutSideVoice" : organizationId + " DisableOutSideVoice");
                }
                else
                {
                    command.Parameters.Add("PolicyName", null);
                }
                ExecuteShellCommand(runspace, command, false);

                // ArchivePolicy
                command = new Command("Grant-CsArchivingPolicy");
                command.Parameters.Add("Identity", userUpn);
                command.Parameters.Add("PolicyName", string.IsNullOrEmpty(plan.ArchivePolicy) ? null : plan.ArchivePolicy);
                ExecuteShellCommand(runspace, command, false);

                // DialPlan
                command = new Command("Grant-CsDialPlan");
                command.Parameters.Add("Identity", userUpn);
                command.Parameters.Add("PolicyName", string.IsNullOrEmpty(plan.TelephonyDialPlanPolicy) ? null : plan.TelephonyDialPlanPolicy);
                ExecuteShellCommand(runspace, command, false);

                // VoicePolicy
                command = new Command("Grant-CsVoicePolicy");
                command.Parameters.Add("Identity", userUpn);
                command.Parameters.Add("PolicyName", string.IsNullOrEmpty(plan.TelephonyVoicePolicy) ? null : plan.TelephonyVoicePolicy);
                ExecuteShellCommand(runspace, command, false);

                command = new Command("Update-CsUserDatabase");
                ExecuteShellCommand(runspace, command, false);
            }
            catch (Exception ex)
            {
                res = false;
                HostedSolutionLog.LogError("SetSfBUserPlanInternal", ex);
                throw;
            }
            finally
            {
                if (bCloseRunSpace)
                {
                    CloseRunspace(runspace);
                }
            }

            HostedSolutionLog.LogEnd("SetSfBUserPlanInternal");

            return(res);
        }
        /// <summary>Adds record to hosts file.</summary>
        /// <param name="siteCollection">The site collection object.</param>
        public void AddHostsRecord(SharePointSiteCollection siteCollection)
        {
            try
            {
                if (siteCollection.RootWebApplicationInteralIpAddress != string.Empty)
                {
                    string dirPath = FileUtils.EvaluateSystemVariables(@"%windir%\system32\drivers\etc");
                    string path    = dirPath + "\\hosts";

                    if (FileUtils.FileExists(path))
                    {
                        string content = FileUtils.GetFileTextContent(path);
                        content = content.Replace("\r\n", "\n").Replace("\n\r", "\n");
                        string[] contentArr   = content.Split(new[] { '\n' });
                        bool     bRecordExist = false;

                        foreach (string s in contentArr)
                        {
                            if (s != string.Empty)
                            {
                                string hostName = string.Empty;

                                if (s[0] != '#')
                                {
                                    bool bSeperator = false;

                                    foreach (char c in s)
                                    {
                                        if ((c != ' ') & (c != '\t'))
                                        {
                                            if (bSeperator)
                                            {
                                                hostName += c;
                                            }
                                        }
                                        else
                                        {
                                            bSeperator = true;
                                        }
                                    }

                                    if (hostName.ToLower() == siteCollection.RootWebApplicationFQDN.ToLower())
                                    {
                                        bRecordExist = true;
                                        break;
                                    }
                                }
                            }
                        }

                        if (!bRecordExist)
                        {
                            string outPut = contentArr.Where(o => o != string.Empty).Aggregate(string.Empty, (current, o) => current + (o + "\r\n"));
                            outPut += siteCollection.RootWebApplicationInteralIpAddress + '\t' + siteCollection.RootWebApplicationFQDN + "\r\n";
                            FileUtils.UpdateFileTextContent(path, outPut);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                HostedSolutionLog.LogError(ex);
            }
        }
예제 #25
0
파일: SfB2015.cs 프로젝트: pasamsin/SolidCP
        /// <summary> Creates the user.</summary>
        /// <param name="organizationId"> The organization identifier.</param>
        /// <param name="userUpn"> The user UPN.</param>
        /// <param name="plan"> The SfB user plan.</param>
        /// <returns> The result.</returns>
        internal override bool CreateUserInternal(string organizationId, string userUpn, SfBUserPlan plan)
        {
            HostedSolutionLog.LogStart("CreateUserInternal");
            HostedSolutionLog.DebugInfo("organizationId: {0}", organizationId);
            HostedSolutionLog.DebugInfo("userUpn: {0}", userUpn);
            SfBTransaction transaction = StartTransaction();
            Runspace       runspace    = null;

            try
            {
                runspace = OpenRunspace();
                Guid     guid = GetObjectGuid(organizationId, runspace);
                string[] tmp  = userUpn.Split('@');

                if (tmp.Length < 2)
                {
                    return(false);
                }

                var command = new Command("Get-CsSipDomain");
                Collection <PSObject> sipDomains = ExecuteShellCommand(runspace, command, false);
                bool bSipDomainExists            = sipDomains.Select(domain => (string)GetPSObjectProperty(domain, "Name")).Any(d => d.ToLower() == tmp[1].ToLower());

                string path = string.Empty;
                if (!bSipDomainExists)
                {
                    command = new Command("New-CsSipDomain");
                    command.Parameters.Add("Identity", tmp[1].ToLower());
                    ExecuteShellCommand(runspace, command, false);
                    transaction.RegisterNewSipDomain(tmp[1].ToLower());
                    AddAdDomainName(organizationId, tmp[1].ToLower());
                    CreateSimpleUrl(runspace, guid);
                    transaction.RegisterNewSimpleUrl(tmp[1].ToLower(), guid.ToString());
                }

                command = new Command("Enable-CsUser");
                command.Parameters.Add("Identity", userUpn);
                command.Parameters.Add("RegistrarPool", PoolFQDN);
                command.Parameters.Add("SipAddressType", "UserPrincipalName");
                ExecuteShellCommand(runspace, command, false);
                transaction.RegisterNewCsUser(userUpn);

                command = new Command("Get-CsAdUser");
                command.Parameters.Add("Identity", userUpn);
                Collection <PSObject> result = ExecuteShellCommand(runspace, command, false);

                //set groupingID
                path = AddADPrefix(GetResultObjectDN(result));
                DirectoryEntry user = ActiveDirectoryUtils.GetADObject(path);
                ActiveDirectoryUtils.SetADObjectPropertyValue(user, "msRTCSIP-GroupingID", guid);
                user.CommitChanges();

                command = new Command("Update-CsAddressBook");
                ExecuteShellCommand(runspace, command, false);
                command = new Command("Update-CsUserDatabase");
                ExecuteShellCommand(runspace, command, false);

                int trySleep = 2000; int tryMaxCount = 10; bool PlanSet = false;
                for (int tryCount = 0; (tryCount < tryMaxCount) && (!PlanSet); tryCount++)
                {
                    try
                    {
                        PlanSet = SetSfBUserPlanInternal(organizationId, userUpn, plan, runspace);
                    }
                    catch { }
                    if (!PlanSet)
                    {
                        System.Threading.Thread.Sleep(trySleep);
                    }
                }
            }
            catch (Exception ex)
            {
                HostedSolutionLog.LogError("CreateUserInternal", ex);
                RollbackTransaction(transaction);
                throw;
            }
            finally
            {
                CloseRunspace(runspace);
            }

            HostedSolutionLog.LogEnd("CreateUserInternal");

            return(true);
        }
예제 #26
0
파일: SfB2015.cs 프로젝트: pasamsin/SolidCP
        /// <summary> Deletes organization.</summary>
        /// <param name="organizationId"> The organization identifier.</param>
        /// <param name="sipDomain"> The sip domain.</param>
        /// <returns> The result.</returns>
        internal override bool DeleteOrganizationInternal(string organizationId, string sipDomain)
        {
            HostedSolutionLog.LogStart("DeleteOrganizationInternal");
            HostedSolutionLog.DebugInfo("organizationId: {0}", organizationId);
            HostedSolutionLog.DebugInfo("sipDomain: {0}", sipDomain);
            Runspace runspace = null;

            try
            {
                runspace = OpenRunspace();
                string         path  = AddADPrefix(GetOrganizationPath(organizationId));
                DirectoryEntry ou    = ActiveDirectoryUtils.GetADObject(path);
                string[]       sipDs = ActiveDirectoryUtils.GetADObjectPropertyMultiValue(ou, "Url");

                foreach (string sipD in sipDs)
                {
                    DeleteSipDomain(runspace, sipD);
                }

                try
                {
                    DeleteConferencingPolicy(runspace, organizationId);
                }
                catch (Exception)
                {
                }

                try
                {
                    DeleteExternalAccessPolicy(runspace, organizationId);
                }
                catch (Exception)
                {
                }

                try
                {
                    DeleteMobilityPolicy(runspace, organizationId + " EnableOutSideVoice");
                }
                catch (Exception)
                {
                }

                try
                {
                    DeleteMobilityPolicy(runspace, organizationId + " DisableOutSideVoice");
                }
                catch (Exception)
                {
                }

                var command = new Command("Invoke-CsManagementStoreReplication");
                ExecuteShellCommand(runspace, command, false);
            }
            catch (Exception ex)
            {
                HostedSolutionLog.LogError("DeleteOrganizationInternal", ex);
                throw;
            }
            finally
            {
                CloseRunspace(runspace);
            }

            HostedSolutionLog.LogEnd("DeleteOrganizationInternal");

            return(true);
        }
예제 #27
0
        /// <summary>Removes record from hosts file.</summary>
        /// <param name="siteCollection">The site collection object.</param>
        private void RemoveHostsRecord(SharePointEnterpriseSiteCollection siteCollection)
        {
            try
            {
                if (siteCollection.RootWebApplicationInteralIpAddress != string.Empty)
                {
                    string dirPath = FileUtils.EvaluateSystemVariables(@"%windir%\system32\drivers\etc");
                    string path    = dirPath + "\\hosts";

                    if (FileUtils.FileExists(path))
                    {
                        string content = FileUtils.GetFileTextContent(path);
                        content = content.Replace("\r\n", "\n").Replace("\n\r", "\n");
                        string[] contentArr = content.Split(new[] { '\n' });
                        string   outPut     = string.Empty;

                        foreach (string s in contentArr)
                        {
                            if (s != string.Empty)
                            {
                                string hostName = string.Empty;

                                if (s[0] != '#')
                                {
                                    bool bSeperator = false;

                                    foreach (char c in s)
                                    {
                                        if ((c != ' ') & (c != '\t'))
                                        {
                                            if (bSeperator)
                                            {
                                                hostName += c;
                                            }
                                        }
                                        else
                                        {
                                            bSeperator = true;
                                        }
                                    }

                                    if (hostName.ToLower() != siteCollection.RootWebApplicationFQDN.ToLower())
                                    {
                                        outPut += s + "\r\n";
                                    }
                                }
                                else
                                {
                                    outPut += s + "\r\n";
                                }
                            }
                        }

                        FileUtils.UpdateFileTextContent(path, outPut);
                    }
                }
            }
            catch (Exception ex)
            {
                HostedSolutionLog.LogError(ex);
            }
        }
예제 #28
0
        private string CreateUserInternal(string userUpn, string userDistinguishedName)
        {
            HostedSolutionLog.LogStart("CreateUserInternal");
            HostedSolutionLog.DebugInfo("UPN: {0}", userUpn);
            HostedSolutionLog.DebugInfo("User Distinguished Name: {0}", userDistinguishedName);

            try
            {
                if (string.IsNullOrEmpty(userUpn))
                {
                    throw new ArgumentException("userUpn");
                }

                if (string.IsNullOrEmpty(userDistinguishedName))
                {
                    throw new ArgumentException("userDistinguishedName");
                }

                if (string.IsNullOrEmpty(PoolFQDN))
                {
                    throw new Exception("Pool FQDN is not specified");
                }



                string poolDN = GetPoolDistinguishedName(PoolFQDN);
                if (string.IsNullOrEmpty(poolDN))
                {
                    throw new Exception(string.Format("Pool {0} not found", PoolFQDN));
                }

                if (!string.IsNullOrEmpty(FindUserByDistinguishedName(userDistinguishedName)))
                {
                    throw new Exception(string.Format("User with distinguished name '{0}' already exists", userDistinguishedName));
                }

                string primaryUri = "sip:" + userUpn;

                if (!string.IsNullOrEmpty(FindUserByPrimaryUri(primaryUri)))
                {
                    throw new Exception(string.Format("User with primary URI '{0}' already exists", primaryUri));
                }

                using (ManagementObject newUser = Wmi.CreateInstance("MSFT_SIPESUserSetting"))
                {
                    newUser["PrimaryURI"]               = primaryUri;
                    newUser["UserDN"]                   = userDistinguishedName;
                    newUser["HomeServerDN"]             = poolDN;
                    newUser["Enabled"]                  = true;
                    newUser["EnabledForInternetAccess"] = true;
                    newUser.Put();
                }
                string instanceId = null;
                int    attempts   = 0;
                while (true)
                {
                    instanceId = FindUserByPrimaryUri(primaryUri);
                    if (!string.IsNullOrEmpty(instanceId))
                    {
                        break;
                    }

                    if (attempts > 9)
                    {
                        throw new Exception(
                                  string.Format("Could not find OCS user '{0}'", primaryUri));
                    }

                    attempts++;
                    ExchangeLog.LogWarning("Attempt #{0} to create OCS user failed!", attempts);
                    // wait 30 sec
                    System.Threading.Thread.Sleep(1000);
                }

                HostedSolutionLog.LogEnd("CreateUserInternal");

                return(instanceId);
            }
            catch (Exception ex)
            {
                HostedSolutionLog.LogError("CreateUserInternal", ex);
                throw;
            }
        }