public static int DeleteWebSitePointer(int siteItemId, int domainId, bool updateWebSite)
        {
            // check account
            int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);
            if (accountCheck < 0) return accountCheck;

            // load site item
            WebSite siteItem = (WebSite)PackageController.GetPackageItem(siteItemId);
            if (siteItem == null)
                return BusinessErrorCodes.ERROR_WEB_SITE_PACKAGE_ITEM_NOT_FOUND;

            // load domain item
            DomainInfo domain = ServerController.GetDomain(domainId);
            if (domain == null)
                return BusinessErrorCodes.ERROR_DOMAIN_PACKAGE_ITEM_NOT_FOUND;

            // load appropriate zone
            DnsZone zone = (DnsZone)PackageController.GetPackageItem(domain.ZoneItemId);

            // get zone records for the service
            List<GlobalDnsRecord> dnsRecords = ServerController.GetDnsRecordsByService(siteItem.ServiceId);

            // load web site IP address
            IPAddressInfo ip = ServerController.GetIPAddress(siteItem.SiteIPAddressId);

            // place log record
            TaskManager.StartTask("WEB_SITE", "DELETE_POINTER", siteItem.Name);
            TaskManager.ItemId = siteItemId;
            TaskManager.WriteParameter("Domain pointer", domain.DomainName);

            try
            {
                if (zone != null)
                {
                    // change DNS zone
                    string serviceIp = (ip != null) ? ip.ExternalIP : null;

                    List<DnsRecord> resourceRecords = DnsServerController.BuildDnsResourceRecords(
                        dnsRecords, domain.DomainName, serviceIp);

                    try
                    {
                        DNSServer dns = new DNSServer();
                        ServiceProviderProxy.Init(dns, zone.ServiceId);
                        dns.DeleteZoneRecords(zone.Name, resourceRecords.ToArray());
                    }
                    catch(Exception ex1)
                    {
                        TaskManager.WriteError(ex1, "Error deleting DNS records");
                    }
                }

                if (updateWebSite)
                {
                    // get existing web site bindings
                    WebServer web = new WebServer();
                    ServiceProviderProxy.Init(web, siteItem.ServiceId);

                    List<ServerBinding> bindings = new List<ServerBinding>();
                    bindings.AddRange(web.GetSiteBindings(siteItem.SiteId));

                    // check if web site has dedicated IP assigned
                    bool dedicatedIp = bindings.Exists(binding => { return String.IsNullOrEmpty(binding.Host) && binding.IP != "*"; });

                    // update binding only for "shared" ip addresses
                    if (!dedicatedIp)
                    {
                        // remove host headers
                        List<ServerBinding> domainBindings = new List<ServerBinding>();
                        FillWebServerBindings(domainBindings, dnsRecords, "", domain.DomainName);

                        // fill to remove list
                        List<string> headersToRemove = new List<string>();
                        foreach (ServerBinding domainBinding in domainBindings)
                            headersToRemove.Add(domainBinding.Host);

                        // remove bndings
                        bindings.RemoveAll(b => { return headersToRemove.Contains(b.Host) && b.Port == "80"; } );

                        // update bindings
                        web.UpdateSiteBindings(siteItem.SiteId, bindings.ToArray());
                    }
                }

                // update domain
                domain.WebSiteId = 0;
                ServerController.UpdateDomain(domain);

                return 0;
            }
            catch (Exception ex)
            {
                throw TaskManager.WriteError(ex);
            }
            finally
            {
                TaskManager.CompleteTask();
            }
        }
        /// <summary>
        /// Adds SharePoint site collection.
        /// </summary>
        /// <param name="item">Site collection description.</param>
        /// <returns>Created site collection id within metabase.</returns>
        public static int AddSiteCollection(SharePointSiteCollection item)
        {

            // Check account.
            int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);
            if (accountCheck < 0)
            {
                return accountCheck;
            }

            // Check package.
            int packageCheck = SecurityContext.CheckPackage(item.PackageId, DemandPackage.IsActive);
            if (packageCheck < 0)
            {
                return packageCheck;
            }

            // Check quota.
            OrganizationStatistics orgStats = OrganizationController.GetOrganizationStatistics(item.OrganizationId);
            //QuotaValueInfo quota = PackageController.GetPackageQuota(item.PackageId, Quotas.HOSTED_SHAREPOINT_SITES);

            if (orgStats.AllocatedSharePointSiteCollections > -1
                && orgStats.CreatedSharePointSiteCollections >= orgStats.AllocatedSharePointSiteCollections)
            {
                return BusinessErrorCodes.ERROR_SHAREPOINT_RESOURCE_QUOTA_LIMIT;
            }

            // Check if stats resource is available
            int serviceId = PackageController.GetPackageServiceId(item.PackageId, ResourceGroups.SharepointFoundationServer);

            if (serviceId == 0)
            {
                return BusinessErrorCodes.ERROR_SHAREPOINT_RESOURCE_UNAVAILABLE;
            }

            StringDictionary hostedSharePointSettings = ServerController.GetServiceSettings(serviceId);
            QuotaValueInfo quota = PackageController.GetPackageQuota(item.PackageId, Quotas.HOSTED_SHAREPOINT_USESHAREDSSL);
            Uri rootWebApplicationUri = new Uri(hostedSharePointSettings["RootWebApplicationUri"]);
            Organization org = OrganizationController.GetOrganization(item.OrganizationId);
            string siteName = item.Name;

            if (quota.QuotaAllocatedValue == 1)
            {
                string sslRoot = hostedSharePointSettings["SharedSSLRoot"];


                string defaultDomain = org.DefaultDomain;
                string hostNameBase = string.Empty;

                string[] tmp = defaultDomain.Split('.');
                if (tmp.Length == 2)
                {
                    hostNameBase = tmp[0];
                }
                else
                {
                    if (tmp.Length > 2)
                    {
                        hostNameBase = tmp[0] + tmp[1];
                    }
                }

                int counter = 0;
                item.Name = String.Format("{0}://{1}", rootWebApplicationUri.Scheme, hostNameBase + "-" + counter.ToString() + "." + sslRoot);
                siteName = String.Format("{0}", hostNameBase + "-" + counter.ToString() + "." + sslRoot);                

                while  ( DataProvider. CheckServiceItemExists( serviceId,   item. Name,   "WebsitePanel.Providers.SharePoint.SharePointSiteCollection,   WebsitePanel.Providers.Base"))  
                {
                    counter++;
                    item.Name = String.Format("{0}://{1}", rootWebApplicationUri.Scheme, hostNameBase + "-" + counter.ToString() + "." + sslRoot);
                    siteName = String.Format("{0}", hostNameBase + "-" + counter.ToString() + "." + sslRoot);
                }
            }
            else
                item.Name = String.Format("{0}://{1}", rootWebApplicationUri.Scheme, item.Name);

            if (rootWebApplicationUri.Port > 0 && rootWebApplicationUri.Port != 80 && rootWebApplicationUri.Port != 443)
            {
                item.PhysicalAddress = String.Format("{0}:{1}", item.Name, rootWebApplicationUri.Port);
            }
            else
            {
                item.PhysicalAddress = item.Name;
            }

            if (Utils.ParseBool(hostedSharePointSettings["LocalHostFile"], false))
            {
                item.RootWebApplicationInteralIpAddress = hostedSharePointSettings["RootWebApplicationInteralIpAddress"];
                item.RootWebApplicationFQDN = item.Name.Replace(rootWebApplicationUri.Scheme + "://", "");
            }

            item.MaxSiteStorage = RecalculateMaxSize(org.MaxSharePointStorage, (int)item.MaxSiteStorage);
            item.WarningStorage = item.MaxSiteStorage == -1 ? -1 : Math.Min((int)item.WarningStorage, item.MaxSiteStorage);


            // Check package item with given name already exists.
            if (PackageController.GetPackageItemByName(item.PackageId,  item.Name, typeof(SharePointSiteCollection)) != null)
            {
                return BusinessErrorCodes.ERROR_SHAREPOINT_PACKAGE_ITEM_EXISTS;
            }

            // Log operation.
            TaskManager.StartTask("HOSTEDSHAREPOINT", "ADD_SITE_COLLECTION", item.Name);

            try
            {
                // Create site collection on server.
                HostedSharePointServer hostedSharePointServer = GetHostedSharePointServer(serviceId);

                hostedSharePointServer.CreateSiteCollection(item);

                // Make record in metabase.
                item.ServiceId = serviceId;
                int itemId = PackageController.AddPackageItem(item);

                hostedSharePointServer.SetPeoplePickerOu(item.Name, org.DistinguishedName);

                int dnsServiceId = PackageController.GetPackageServiceId(item.PackageId, ResourceGroups.Dns);
                if (dnsServiceId > 0)
                {
                    string[] tmpStr = siteName.Split('.');
                    string hostName = tmpStr[0];
                    string domainName = siteName.Substring(hostName.Length + 1, siteName.Length - (hostName.Length + 1));

                    List<GlobalDnsRecord> dnsRecords = ServerController.GetDnsRecordsByService(serviceId);
                    List<DnsRecord> resourceRecords = DnsServerController.BuildDnsResourceRecords(dnsRecords, hostName, domainName, "");
                    DNSServer dns = new DNSServer();

                    ServiceProviderProxy.Init(dns, dnsServiceId);
                    // add new resource records
                    dns.AddZoneRecords(domainName, resourceRecords.ToArray());
                }

                TaskManager.ItemId = itemId;

                return itemId;
            }
            catch (Exception ex)
            {
                throw TaskManager.WriteError(ex);
            }
            finally
            {
                TaskManager.CompleteTask();
            }
        }
        /// <summary>
        /// Deletes SharePoint site collection with given id.
        /// </summary>
        /// <param name="itemId">Site collection id within metabase.</param>
        /// <returns>?</returns>
        public static int DeleteSiteCollection(int itemId)
        {
            // Check account.
            int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);
            if (accountCheck < 0)
            {
                return accountCheck;
            }

            // Load original meta item
            SharePointSiteCollection origItem = (SharePointSiteCollection)PackageController.GetPackageItem(itemId);
            if (origItem == null)
            {
                return BusinessErrorCodes.ERROR_SHAREPOINT_PACKAGE_ITEM_NOT_FOUND;
            }

            // Get service settings.
            StringDictionary hostedSharePointSettings = ServerController.GetServiceSettings(origItem.ServiceId);
            Uri rootWebApplicationUri = new Uri(hostedSharePointSettings["RootWebApplicationUri"]);
            string siteName = origItem.Name.Replace(String.Format("{0}://", rootWebApplicationUri.Scheme), String.Empty);

            // Log operation.
            TaskManager.StartTask("HOSTEDSHAREPOINT", "DELETE_SITE", origItem.Name, itemId);

            try
            {
                // Delete site collection on server.
                HostedSharePointServer hostedSharePointServer = GetHostedSharePointServer(origItem.ServiceId);
                hostedSharePointServer.DeleteSiteCollection(origItem);
                // Delete record in metabase.
                PackageController.DeletePackageItem(origItem.Id);

                int dnsServiceId = PackageController.GetPackageServiceId(origItem.PackageId, ResourceGroups.Dns);
                if (dnsServiceId > 0)
                {
                    string[] tmpStr = siteName.Split('.');
                    string hostName = tmpStr[0];
                    string domainName = siteName.Substring(hostName.Length + 1, siteName.Length - (hostName.Length + 1));

                    List<GlobalDnsRecord> dnsRecords = ServerController.GetDnsRecordsByService(origItem.ServiceId);
                    List<DnsRecord> resourceRecords = DnsServerController.BuildDnsResourceRecords(dnsRecords, hostName, domainName, "");
                    DNSServer dns = new DNSServer();

                    ServiceProviderProxy.Init(dns, dnsServiceId);
                    // add new resource records
                    dns.DeleteZoneRecords(domainName, resourceRecords.ToArray());
                }

                return 0;
            }
            catch (Exception ex)
            {
                throw TaskManager.WriteError(ex);
            }
            finally
            {
                TaskManager.CompleteTask();
            }
        }
        public List<string> GetImportableItems(int packageId, int itemTypeId, Type itemType, ResourceGroupInfo group)
        {
            List<string> items = new List<string>();

            // get service id
            int serviceId = PackageController.GetPackageServiceId(packageId, group.GroupName);
            if (serviceId == 0)
                return items;

            // Mail provider
            DNSServer dns = new DNSServer();
            ServiceProviderProxy.Init(dns, serviceId);

            // IDN: The list of importable names is populated with unicode names, to make it easier for the user
            var idn = new IdnMapping();

            if (itemType == typeof(DnsZone))
                items.AddRange(dns.GetZones());

            return items;
        }
 private static DNSServer GetDNSServer(int serviceId)
 {
     DNSServer dns = new DNSServer();
     ServiceProviderProxy.Init(dns, serviceId);
     return dns;
 }
        public static int DeleteZone(int zoneItemId)
        {
            // delete DNS zone if applicable
            DnsZone zoneItem = (DnsZone)PackageController.GetPackageItem(zoneItemId);
            //
            if (zoneItem != null)
            {
                TaskManager.StartTask("DNS_ZONE", "DELETE", zoneItem.Name, zoneItemId);
                //
                try
                {
                    // delete DNS zone
                    DNSServer dns = new DNSServer();
                    ServiceProviderProxy.Init(dns, zoneItem.ServiceId);

                    // delete secondary zones
                    StringDictionary primSettings = ServerController.GetServiceSettings(zoneItem.ServiceId);
                    string strSecondaryServices = primSettings["SecondaryDNSServices"];
                    if (!String.IsNullOrEmpty(strSecondaryServices))
                    {
                        string[] secondaryServices = strSecondaryServices.Split(',');
                        foreach (string strSecondaryId in secondaryServices)
                        {
                            try
                            {
                                int secondaryId = Utils.ParseInt(strSecondaryId, 0);
                                if (secondaryId == 0)
                                    continue;

                                DNSServer secDns = new DNSServer();
                                ServiceProviderProxy.Init(secDns, secondaryId);

                                secDns.DeleteZone(zoneItem.Name);
                            }
                            catch (Exception ex1)
                            {
                                // problem when deleting secondary zone
                                TaskManager.WriteError(ex1, "Error deleting secondary DNS zone");
                            }
                        }
                    }

                    try
                    {
                        dns.DeleteZone(zoneItem.Name);
                    }
                    catch (Exception ex2)
                    {
                        TaskManager.WriteError(ex2, "Error deleting primary DNS zone");
                    }

                    // delete service item
                    PackageController.DeletePackageItem(zoneItemId);

                    // Delete also all seconday service items
                    var zoneItems = PackageController.GetPackageItemsByType(zoneItem.PackageId, ResourceGroups.Dns, typeof (SecondaryDnsZone));

                    foreach (var item in zoneItems.Where(z => z.Name == zoneItem.Name))
                    {
                        PackageController.DeletePackageItem(item.Id);
                    }
                }
                catch (Exception ex)
                {
                    TaskManager.WriteError(ex);
                }
                finally
                {
                    TaskManager.CompleteTask();
                }
            }
            //
            return 0;
        }
        public List<string> GetImportableItems(int packageId, int itemTypeId, Type itemType, ResourceGroupInfo group)
        {
            List<string> items = new List<string>();

            // get service id
            int serviceId = PackageController.GetPackageServiceId(packageId, group.GroupName);
            if (serviceId == 0)
                return items;

            // Mail provider
            DNSServer dns = new DNSServer();
            ServiceProviderProxy.Init(dns, serviceId);

            if (itemType == typeof(DnsZone))
                items.AddRange(dns.GetZones());

            return items;
        }
        internal static int AddWebSitePointer(int siteItemId, string hostName, int domainId, bool updateWebSite, bool ignoreGlobalDNSRecords, bool rebuild)
        {
            // check account
            int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);
            if (accountCheck < 0) return accountCheck;

            // load site item
            WebSite siteItem = (WebSite)PackageController.GetPackageItem(siteItemId);
            if (siteItem == null)
                return BusinessErrorCodes.ERROR_WEB_SITE_PACKAGE_ITEM_NOT_FOUND;

            // load domain item
            DomainInfo domain = ServerController.GetDomain(domainId);
            if (domain == null)
                return BusinessErrorCodes.ERROR_DOMAIN_PACKAGE_ITEM_NOT_FOUND;

            // check if the web site already exists
            if (!rebuild)
            {
                if (DataProvider.CheckDomain(domain.PackageId, string.IsNullOrEmpty(hostName) ? domain.DomainName : hostName + "." + domain.DomainName, true) != 0)
                    return BusinessErrorCodes.ERROR_WEB_SITE_ALREADY_EXISTS;
            }

            // get zone records for the service
            List<GlobalDnsRecord> dnsRecords = ServerController.GetDnsRecordsByService(siteItem.ServiceId);

            // load web site IP address
            IPAddressInfo ip = ServerController.GetIPAddress(siteItem.SiteIPAddressId);

            // place log record
            TaskManager.StartTask("WEB_SITE", "ADD_POINTER", siteItem.Name, siteItemId);

            TaskManager.WriteParameter("Domain pointer", domain.DomainName);
            TaskManager.WriteParameter("Host name", hostName);
            TaskManager.WriteParameter("updateWebSite", updateWebSite.ToString());

            try
            {

               
                // load appropriate zone
                DnsZone zone = (DnsZone)PackageController.GetPackageItem(domain.ZoneItemId);
                               

                if (zone != null)
                {
                    // change DNS zone
                    List<GlobalDnsRecord> tmpDnsRecords = new List<GlobalDnsRecord>();

                    string serviceIp = (ip != null) ? ip.ExternalIP : null;

                    if (string.IsNullOrEmpty(serviceIp))
                    {
                        StringDictionary settings = ServerController.GetServiceSettings(siteItem.ServiceId);
                        if (settings["PublicSharedIP"] != null)
                            serviceIp = settings["PublicSharedIP"].ToString();
                    }

                    //filter initiat GlobaDNSRecords list
                    if (ignoreGlobalDNSRecords)
                    {
                        //ignore all other except the host_name record
                        foreach (GlobalDnsRecord r in dnsRecords)
                        {
                            if (r.RecordName == "[host_name]")
                            {
                                tmpDnsRecords.Add(r);
                                break;
                            }
                        }
                    }
                    else
                        tmpDnsRecords = dnsRecords;


                    List<DnsRecord> resourceRecords = DnsServerController.BuildDnsResourceRecords(tmpDnsRecords, hostName, domain.DomainName, serviceIp);

                    if (!rebuild)
                    {
                        foreach (DnsRecord r in resourceRecords)
                        {
                            if (r.RecordName != "*")
                            {
                                // check if the web site already exists
                                if (DataProvider.CheckDomain(domain.PackageId, string.IsNullOrEmpty(r.RecordName) ? domain.DomainName : r.RecordName + "." + domain.DomainName, true) != 0)
                                    return BusinessErrorCodes.ERROR_WEB_SITE_ALREADY_EXISTS;
                            }
                        }
                    }

                    try
                    {
                        DNSServer dns = new DNSServer();
                        ServiceProviderProxy.Init(dns, zone.ServiceId);

                        DnsRecord[] domainRecords = dns.GetZoneRecords(zone.Name);
                        var duplicateRecords = (from zoneRecord in domainRecords
                                                from resRecord in resourceRecords
                                                where zoneRecord.RecordName == resRecord.RecordName
                                                where zoneRecord.RecordType == resRecord.RecordType
                                                select zoneRecord).ToArray();
                        if (duplicateRecords != null && duplicateRecords.Count() > 0)
                        {
                            dns.DeleteZoneRecords(zone.Name, duplicateRecords);
                        }

                        // add new resource records
                        dns.AddZoneRecords(zone.Name, resourceRecords.ToArray());
                    }
                    catch (Exception ex1)
                    {
                        TaskManager.WriteError(ex1, "Error updating DNS records");
                    }
                }

                // update host headers
                List<ServerBinding> bindings = new List<ServerBinding>();

                // get existing web site bindings
                WebServer web = new WebServer();
                ServiceProviderProxy.Init(web, siteItem.ServiceId);
                    
                bindings.AddRange(web.GetSiteBindings(siteItem.SiteId));

                // check if web site has dedicated IP assigned
                bool dedicatedIp = bindings.Exists(binding => { return String.IsNullOrEmpty(binding.Host) && binding.IP != "*"; });

                // update binding only for "shared" ip addresses
                // add new host headers
                string ipAddr = "*";
                if (ip != null)
                    ipAddr = !String.IsNullOrEmpty(ip.InternalIP) ? ip.InternalIP : ip.ExternalIP;

                // fill bindings
                FillWebServerBindings(bindings, dnsRecords, ipAddr, hostName, domain.DomainName, ignoreGlobalDNSRecords);

                //for logging purposes
                foreach (ServerBinding b in bindings)
                {
                    string header = string.Format("{0} {1} {2}", b.Host, b.IP, b.Port);
                    TaskManager.WriteParameter("Add Binding", header);
                }

                // update bindings
                if (updateWebSite)
                    web.UpdateSiteBindings(siteItem.SiteId, bindings.ToArray(), false);

                // update domain
                if (!rebuild)
                {
                    domain.WebSiteId = siteItemId;
                    domain.IsDomainPointer = true;
                    foreach (ServerBinding b in bindings)
                    {
                        //add new domain record
                        if (!string.IsNullOrEmpty(b.Host))
                        {
                            domain.DomainName = b.Host;

                            DomainInfo domainTmp = ServerController.GetDomain(domain.DomainName);
                            if (!((domainTmp != null) && (domainTmp.WebSiteId == siteItemId)))
                            {
                                int domainID = ServerController.AddDomain(domain, domain.IsInstantAlias, false);
                                domainTmp = ServerController.GetDomain(domainID);
                                if (domainTmp != null)
                                {
                                    domainTmp.WebSiteId = siteItemId;
                                    domainTmp.ZoneItemId = domain.ZoneItemId;
                                    domainTmp.DomainItemId = domainId;

                                    ServerController.UpdateDomain(domainTmp);
                                }
                            }
                        }
                    }
                }
                else
                {
                    if (domain.ZoneItemId > 0)
                    {
                        DomainInfo domainTmp = ServerController.GetDomain(string.IsNullOrEmpty(hostName) ? domain.DomainName : hostName + "." + domain.DomainName, true, true);
                        if (domainTmp != null)
                        {
                            domainTmp.ZoneItemId = domain.ZoneItemId;
                            ServerController.UpdateDomain(domainTmp);
                        }
                    }
                }

                return 0;
            }
            catch (Exception ex)
            {
                throw TaskManager.WriteError(ex);
            }
            finally
            {
                TaskManager.CompleteTask();
            }
        }
        public static int DeleteWebSitePointer(int siteItemId, int domainId, bool updateWebSite)
        {
            // check account
            int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);
            if (accountCheck < 0) return accountCheck;

            // load site item
            WebSite siteItem = (WebSite)PackageController.GetPackageItem(siteItemId);
            if (siteItem == null)
                return BusinessErrorCodes.ERROR_WEB_SITE_PACKAGE_ITEM_NOT_FOUND;

            // load domain item
            DomainInfo domain = ServerController.GetDomain(domainId);
            if (domain == null)
                return BusinessErrorCodes.ERROR_DOMAIN_PACKAGE_ITEM_NOT_FOUND;

            // load appropriate zone
            DnsZone zone = (DnsZone)PackageController.GetPackageItem(domain.ZoneItemId);
            //if (zone == null)
            //    return BusinessErrorCodes.ERROR_DNS_PACKAGE_ITEM_NOT_FOUND;

            // get zone records for the service
            List<GlobalDnsRecord> dnsRecords = ServerController.GetDnsRecordsByService(siteItem.ServiceId);

            // change DNS zone
            IPAddressInfo ip = ServerController.GetIPAddress(siteItem.SiteIPAddressId);
            if (ip == null)
                return BusinessErrorCodes.ERROR_WEB_SITE_IP_ADDRESS_NOT_SPECIFIED;

            List<DnsRecord> resourceRecords = DnsServerController.BuildDnsResourceRecords(
                dnsRecords, domain.DomainName, ip.ExternalIP);

            // place log record
            TaskManager.StartTask("WEB_SITE", "DELETE_POINTER", siteItem.Name);
            TaskManager.ItemId = siteItemId;
            TaskManager.WriteParameter("Domain pointer", domain.DomainName);

            try
            {
                if (zone != null)
                {
                    try
                    {
                        DNSServer dns = new DNSServer();
                        ServiceProviderProxy.Init(dns, zone.ServiceId);
                        dns.DeleteZoneRecords(zone.Name, resourceRecords.ToArray());
                    }
                    catch(Exception ex1)
                    {
                        TaskManager.WriteError(ex1, "Error deleting DNS records");
                    }
                }

                // load web settings
                StringDictionary webSettings = ServerController.GetServiceSettings(siteItem.ServiceId);
                int sharedIpId = Utils.ParseInt(webSettings["SharedIP"], 0);

                bool dedicatedIp = (siteItem.SiteIPAddressId != sharedIpId);

                if (updateWebSite && !dedicatedIp)
                {

                    // update host headers
                    WebServer web = new WebServer();
                    ServiceProviderProxy.Init(web, siteItem.ServiceId);

                    List<ServerBinding> bindings = new List<ServerBinding>();
                    bindings.AddRange(web.GetSiteBindings(siteItem.SiteId));

                    // remove host headers
                    List<ServerBinding> domainBindings = new List<ServerBinding>();
                    FillWebServerBindings(domainBindings, dnsRecords, "", domain.DomainName);

                    // fill to remove list
                    List<string> headersToRemove = new List<string>();
                    foreach (ServerBinding domainBinding in domainBindings)
                    {
                        headersToRemove.Add(domainBinding.Host);
                    }

                    int pos = 0;
                    while (pos < bindings.Count)
                    {
                        if (headersToRemove.Contains(bindings[pos].Host))
                        {
                            bindings.RemoveAt(pos);
                            continue;
                        }
                        else
                        {
                            pos++;
                        }
                    }

                    web.UpdateSiteBindings(siteItem.SiteId, bindings.ToArray());
                }

                // update domain
                domain.WebSiteId = 0;
                ServerController.UpdateDomain(domain);

                return 0;
            }
            catch (Exception ex)
            {
                throw TaskManager.WriteError(ex);
            }
            finally
            {
                TaskManager.CompleteTask();
            }
        }
        internal static int AddWebSitePointer(int siteItemId, int domainId, bool updateWebSite)
        {
            // check account
            int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);
            if (accountCheck < 0) return accountCheck;

            // load site item
            WebSite siteItem = (WebSite)PackageController.GetPackageItem(siteItemId);
            if (siteItem == null)
                return BusinessErrorCodes.ERROR_WEB_SITE_PACKAGE_ITEM_NOT_FOUND;

            // load domain item
            DomainInfo domain = ServerController.GetDomain(domainId);
            if (domain == null)
                return BusinessErrorCodes.ERROR_DOMAIN_PACKAGE_ITEM_NOT_FOUND;

            // load appropriate zone
            DnsZone zone = (DnsZone)PackageController.GetPackageItem(domain.ZoneItemId);
            //if (zone == null)
            //    return BusinessErrorCodes.ERROR_DNS_PACKAGE_ITEM_NOT_FOUND;

            // get zone records for the service
            List<GlobalDnsRecord> dnsRecords = ServerController.GetDnsRecordsByService(siteItem.ServiceId);

            // change DNS zone
            IPAddressInfo ip = ServerController.GetIPAddress(siteItem.SiteIPAddressId);
            if (ip == null)
                return BusinessErrorCodes.ERROR_WEB_SITE_IP_ADDRESS_NOT_SPECIFIED;

            List<DnsRecord> resourceRecords = DnsServerController.BuildDnsResourceRecords(
                dnsRecords, domain.DomainName, ip.ExternalIP);

            // place log record
            TaskManager.StartTask("WEB_SITE", "ADD_POINTER", siteItem.Name);
            TaskManager.ItemId = siteItemId;
            TaskManager.WriteParameter("Domain pointer", domain.DomainName);

            try
            {

                if (zone != null)
                {
                    try
                    {
                        DNSServer dns = new DNSServer();
                        ServiceProviderProxy.Init(dns, zone.ServiceId);

						// add new resource records
                        dns.AddZoneRecords(zone.Name, resourceRecords.ToArray());
                    }
                    catch(Exception ex1)
                    {
                        TaskManager.WriteError(ex1, "Error updating DNS records");
                    }
                }

                // update host headers
                if (updateWebSite)
                {
                    // load web settings
                    StringDictionary webSettings = ServerController.GetServiceSettings(siteItem.ServiceId);
                    int sharedIpId = Utils.ParseInt(webSettings["SharedIP"], 0);

                    bool dedicatedIp = (siteItem.SiteIPAddressId != sharedIpId);

                    if (!dedicatedIp)
                    {
                        WebServer web = new WebServer();
                        ServiceProviderProxy.Init(web, siteItem.ServiceId);

                        List<ServerBinding> bindings = new List<ServerBinding>();
                        ServerBinding[] siteBindings = web.GetSiteBindings(siteItem.SiteId);
                        if(siteBindings != null)
                            bindings.AddRange(siteBindings);

                        // add new host headers
                        string ipAddr = ip.InternalIP;
                        if (ipAddr == null || ipAddr == "")
                            ipAddr = ip.ExternalIP;

                        // fill bindings
                        FillWebServerBindings(bindings, dnsRecords, ipAddr, domain.DomainName);

                        // update bindings
                        web.UpdateSiteBindings(siteItem.SiteId, bindings.ToArray());
                    }
                }

                // update domain
                domain.WebSiteId = siteItemId;
                ServerController.UpdateDomain(domain);

                return 0;
            }
            catch (Exception ex)
            {
                throw TaskManager.WriteError(ex);
            }
            finally
            {
                TaskManager.CompleteTask();
            }
        }