public static MailAccount GetMailAccount(int itemId)
        {
            // load meta item
            MailAccount item = (MailAccount)PackageController.GetPackageItem(itemId);

            // load service item
            MailServer mail = new MailServer();
            ServiceProviderProxy.Init(mail, item.ServiceId);
            MailAccount account = mail.GetAccount(item.Name);

            // add common properties
            account.Id = item.Id;
            account.PackageId = item.PackageId;
            account.ServiceId = item.ServiceId;

            return account;
        }
        public static MailGroup GetMailGroup(int itemId)
        {
            // load meta item
            MailGroup item = (MailGroup)PackageController.GetPackageItem(itemId);

            // load service item
            MailServer mail = new MailServer();
            ServiceProviderProxy.Init(mail, item.ServiceId);
            MailGroup group = mail.GetGroup(item.Name);

            // add common properties
            group.Id = item.Id;
            group.PackageId = item.PackageId;
            group.ServiceId = item.ServiceId;

            return group;
        }
        public static int UpdateMailForwarding(MailAlias item)
        {
            // check account
            int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);
            if (accountCheck < 0) return accountCheck;

            // load original meta item
            MailAlias origItem = (MailAlias)PackageController.GetPackageItem(item.Id);
            if (origItem == null)
                return BusinessErrorCodes.ERROR_MAIL_FORWARDINGS_PACKAGE_ITEM_NOT_FOUND;

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

            // place log record
            TaskManager.StartTask("MAIL_FORWARDING", "UPDATE", origItem.Name);
            TaskManager.ItemId = item.Id;

            try
            {
                // update forwarding
                MailServer mail = new MailServer();
                ServiceProviderProxy.Init(mail, origItem.ServiceId);
                MailAlias alias = new MailAlias();
                alias.Name = origItem.Name;
                alias.ForwardTo = item.ForwardTo;

                //For MailEnable alias updating
                alias.DeleteOnForward = true;
                alias.ForwardingAddresses = new string[1];
                alias.ForwardingAddresses[0] = item.ForwardTo;
               
                //
                
                // update service item
                mail.UpdateMailAlias(alias);
                return 0;
            }
            catch (Exception ex)
            {
                throw TaskManager.WriteError(ex);
            }
            finally
            {
                TaskManager.CompleteTask();
            }
        }
 public static MailServer GetMailServer(int serviceId)
 {
     MailServer mail = new MailServer();
     ServiceProviderProxy.Init(mail, serviceId);
     return mail;
 }
        public static int DeleteMailList(int itemId)
        {
            // check account
            int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo);
            if (accountCheck < 0) return accountCheck;

            // load original meta item
            MailList origItem = (MailList)PackageController.GetPackageItem(itemId);
            if (origItem == null)
                return BusinessErrorCodes.ERROR_MAIL_LISTS_PACKAGE_ITEM_NOT_FOUND;

            // place log record
            TaskManager.StartTask("MAIL_LIST", "DELETE", origItem.Name);
            TaskManager.ItemId = itemId;

            try
            {
                // get service
                MailServer mail = new MailServer();
                ServiceProviderProxy.Init(mail, origItem.ServiceId);

                // delete service item
                mail.DeleteList(origItem.Name);

                // delete meta item
                PackageController.DeletePackageItem(origItem.Id);
                return 0;
            }
            catch (Exception ex)
            {
                throw TaskManager.WriteError(ex);
            }
            finally
            {
                TaskManager.CompleteTask();
            }
        }
        public static int AddMailDomain(MailDomain item)
        {
            // check package items
            if (PackageController.GetPackageItemByName(item.PackageId, item.Name, typeof(MailDomain)) != null)
                return 0; // OK, domain already exists

            // place log record
            TaskManager.StartTask("MAIL_DOMAIN", "ADD", item.Name);

            // create domain
            try
            {
                // check service items
                MailServer mail = new MailServer();
                ServiceProviderProxy.Init(mail, item.ServiceId);
                if (mail.DomainExists(item.Name))
                    return BusinessErrorCodes.ERROR_MAIL_DOMAIN_EXISTS;

                item.Enabled = true;

                // add service item
                mail.CreateDomain(item);

                // save domain item
                int itemId = PackageController.AddPackageItem(item);

                // update related domain with a new pointer
                DomainInfo domain = ServerController.GetDomain(item.Name);
                if (domain != null)
                {
                    domain.MailDomainId = itemId;
                    ServerController.UpdateDomain(domain);
                }

                // check if instant alias must be added
                if (!String.IsNullOrEmpty(domain.InstantAliasName))
                {
                    // load instant alias
                    DomainInfo instantAlias = ServerController.GetDomainItem(domain.InstantAliasName);
                    if(instantAlias != null)
                    {
                        AddMailDomainPointer(itemId, instantAlias.DomainId);
                    }
                }

                TaskManager.ItemId = itemId;
                return itemId;
            }
            catch (Exception ex)
            {
                throw TaskManager.WriteError(ex);
            }
            finally
            {
                TaskManager.CompleteTask();
            }
        }
		/// <summary>
		/// Verify if mail provider quotas will exceed if we will try to add Mail Domain into Hosting Space
		/// </summary>
		/// <param name="packageId">Hosting Space Id</param>
		/// <param name="mailServer">Mail Server instance which is used to get Mail Domain information from.</param>
		/// <param name="domainName">Name of the domain.</param>
		/// <returns>True, if a quota will exceed. Otherwise, false.</returns>
		protected QuotaLimit IsQuotasWillExceed(int packageId, MailServer mailServer, string domainName)
		{
            QuotaLimit result = new QuotaLimit();

		    bool quotaExceeded = false, skipOsDomains = false;
			
            // Get OS domains that are already in Hosting Space
            List<DomainInfo> spaceDomains = ServerController.GetDomains(packageId);
			// Step #1 - do not count mail domain as OS domain if OS domain with such name as mail domain already present in Hosting Space
            foreach (DomainInfo domain in spaceDomains)
            {
                if (domain.DomainName.Equals(domainName))
                {
                    skipOsDomains = true;
                    break;
                }
            }
             
            // in current scenario of importing we import domains until the quota exceeded
            // in other words let's examine whether quota will be exeeded if we will add +1 domain.
            if (skipOsDomains == false)
            {
                quotaExceeded = VerifyIfQuotaWillBeExceeded(packageId, Quotas.OS_DOMAINS, 1);
                result.IsExceeded = quotaExceeded;
                result.Message = "Mail_Domain";
            }
		    // Step #3
            if (quotaExceeded == false)
            {
                quotaExceeded = VerifyIfQuotaWillBeExceeded(packageId, Quotas.MAIL_ACCOUNTS,mailServer.GetAccounts(domainName).Length);
                result.IsExceeded = quotaExceeded;
                result.Message = "Mail_Account";
            }
		    // Step #4
            if (quotaExceeded == false)
            {
                quotaExceeded = VerifyIfQuotaWillBeExceeded(packageId, Quotas.MAIL_GROUPS,mailServer.GetGroups(domainName).Length);
                result.IsExceeded = quotaExceeded;
                result.Message = "Mail_Group";
            }
		    // Step #5
            if (quotaExceeded == false)
            {
                quotaExceeded = VerifyIfQuotaWillBeExceeded(packageId, Quotas.MAIL_LISTS,mailServer.GetLists(domainName).Length);
                result.IsExceeded = quotaExceeded;
                result.Message = "Mail_List";
            }
		    // Return validation result
			return result;
		}
        public static int UpdateMailList(MailList item)
        {
            // check account
            int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);
            if (accountCheck < 0) return accountCheck;

            // load original meta item
            MailList origItem = (MailList)PackageController.GetPackageItem(item.Id);
            if (origItem == null)
                return BusinessErrorCodes.ERROR_MAIL_LISTS_PACKAGE_ITEM_NOT_FOUND;

            // check package
            int packageCheck = SecurityContext.CheckPackage(origItem.PackageId, DemandPackage.IsActive);
            if (packageCheck < 0) return packageCheck;

            // check recipients number
            if (!CheckRecipientsAllowedNumber(origItem.PackageId, Quotas.MAIL_MAXLISTMEMBERS, item.Members))
                return BusinessErrorCodes.ERROR_MAIL_LISTS_RECIPIENTS_LIMIT;

            // place log record
            TaskManager.StartTask("MAIL_LIST", "UPDATE", origItem.Name);
            TaskManager.ItemId = item.Id;

            try
            {
                // restore original props
                if (item.Password == "")
                    item.Password = CryptoUtils.Decrypt(origItem.Password);

                // get service
                MailServer mail = new MailServer();
                ServiceProviderProxy.Init(mail, origItem.ServiceId);
                item.Name = origItem.Name;
                item.Enabled = true;
				item.Members = RemoveItemNameFromMembersList(
						  item.Name
						, item.Members.Clone() as string[]
					);

                // update service item
                mail.UpdateList(item);

                // update meta item
                item.Password = CryptoUtils.Encrypt(item.Password);
                PackageController.UpdatePackageItem(item);
                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
            MailServer mail = new MailServer();
            ServiceProviderProxy.Init(mail, serviceId);

            if (itemType == typeof(MailDomain))
                items.AddRange(mail.GetDomains());

            return items;
        }
        public void ImportItem(int packageId, int itemTypeId, Type itemType,
			ResourceGroupInfo group, string itemName)
        {
            // get service id
            int serviceId = PackageController.GetPackageServiceId(packageId, group.GroupName);
            if (serviceId == 0)
                return;            
            
            // Mail provider
            MailServer mail = new MailServer();
            ServiceProviderProxy.Init(mail, serviceId);

            if (itemType == typeof(MailDomain))
            {
                QuotaLimit result = IsQuotasWillExceed(packageId, mail, itemName);
				//in case quotas will exceed the space - exit the import function
				if (result.IsExceeded)
				{
				   if (result.Message.Equals("Mail_Domain"))
                    {
                        const string exceededQuota = "number of domains";
                        TaskManager.WriteWarning(
                            String.Format(
                                "Unable to import mail domain '{0}'.\r\nHosting Plan quotas will be exceeded. \r\nVerify the following quotas before importing mail domain: {1}."
                                , itemName, exceededQuota
                                )
                            );
                        return;
                    }
                    if (result.Message.Equals("Mail_Account"))
                    {
                        const string exceededQuota = "number of mail accounts";
                        TaskManager.WriteWarning(
                            String.Format(
                                "Unable to import mail domain '{0}'.\r\nHosting Plan quotas will be exceeded. \r\nVerify the following quotas before importing mail domain: {1}."
                                , itemName, exceededQuota
                                )
                            );
                        return;
                    }
                    if (result.Message.Equals("Mail_Group"))
                    {
                        const string exceededQuota = "number of groups";
                        TaskManager.WriteWarning(
                            String.Format(
                                "Unable to import mail domain '{0}'.\r\nHosting Plan quotas will be exceeded. \r\nVerify the following quotas before importing mail domain: {1}."
                                , itemName, exceededQuota
                                )
                            );
                        return;
                    }
                    if (result.Message.Equals("Mail_List"))
                    {
                        const string exceededQuota = "number of mail lists";
                        TaskManager.WriteWarning(
                            String.Format(
                                "Unable to import mail domain '{0}'.\r\nHosting Plan quotas will be exceeded. \r\nVerify the following quotas before importing mail domain: {1}."
                                , itemName, exceededQuota
                                )
                            );
                        return;
                    }

				}

                List<string> domains = new List<string>();
                domains.Add(itemName);
                try
                {
                    domains.AddRange(mail.GetDomainAliases(itemName));
                }
                catch (Exception ex)
                {
					TaskManager.WriteError(ex, "Error importing mail domain - skipped");
                    return;
                }

                MailDomain mailDomain = new MailDomain();
                mailDomain.Name = itemName;
                mailDomain.ServiceId = serviceId;
                mailDomain.PackageId = packageId;
                int mailDomainId = PackageController.AddPackageItem(mailDomain);

                // restore domains
                RestoreDomainsByMail(domains, packageId, mailDomainId);

                // add mail accounts
                try
                {                 
                    
                    MailAccount[] accounts = mail.GetAccounts(itemName);
                    foreach (MailAccount account in accounts)
                    {
                        account.ServiceId = serviceId;
                        account.PackageId = packageId;
                        //get mail account password
                        account.Password = CryptoUtils.Encrypt(account.Password);
                        PackageController.AddPackageItem(account);
                    }
                }
                catch (Exception ex)
                {
					TaskManager.WriteError(ex, "Error importing mail account");
                }

                //add mail aliases (forwardings)
                try
                {
                    MailAlias[] aliases = mail.GetMailAliases(itemName);
                    foreach (MailAlias alias in aliases)
                    {
                        alias.ServiceId = serviceId;
                        alias.PackageId = packageId;
                        PackageController.AddPackageItem(alias);
                    }
                }
                catch (Exception ex)
                {
                    TaskManager.WriteError(ex, "Error importing mail aliases");
                }

                // add mail groups
                try
                {
                    MailGroup[] groups = mail.GetGroups(itemName);
                    foreach (MailGroup mailGroup in groups)
                    {
                        mailGroup.ServiceId = serviceId;
                        mailGroup.PackageId = packageId;
                        PackageController.AddPackageItem(mailGroup);
                    }
                }
                catch (Exception ex)
                {
                    TaskManager.WriteError(ex, "Error importing mail group");
                }

                // add mail lists
                try
                {
                    MailList[] lists = mail.GetLists(itemName);
                    foreach (MailList list in lists)
                    {
                        list.ServiceId = serviceId;
                        list.PackageId = packageId;
                        PackageController.AddPackageItem(list);
                    }
                }
                catch (Exception ex)
                {
                    TaskManager.WriteError(ex, "Error importing mail list");
                }
            }
        }
        public static int DeleteMailDomainPointer(int itemId, int domainId)
        {
            // check account
            int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo);
            if (accountCheck < 0) return accountCheck;

            // load site item
            MailDomain mailDomain = (MailDomain)PackageController.GetPackageItem(itemId);
            if (mailDomain == null)
                return BusinessErrorCodes.ERROR_MAIL_DOMAIN_PACKAGE_ITEM_NOT_FOUND;

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

            // place log record
            TaskManager.StartTask("MAIL_DOMAIN", "DELETE_POINTER", mailDomain.Name);
            TaskManager.ItemId = itemId;
            TaskManager.WriteParameter("Domain pointer", domain.DomainName);

            try
            {
                // update mail aliases
                MailServer mail = new MailServer();
                ServiceProviderProxy.Init(mail, mailDomain.ServiceId);
                mail.DeleteDomainAlias(mailDomain.Name, domain.DomainName);

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

                return 0;
            }
            catch (Exception ex)
            {
                throw TaskManager.WriteError(ex);
            }
            finally
            {
                TaskManager.CompleteTask();
            }
        }
        public static int DeleteMailDomain(int itemId)
        {
            // check account
            int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo);
            if (accountCheck < 0) return accountCheck;

            // load original meta item
            MailDomain origItem = (MailDomain)PackageController.GetPackageItem(itemId);
            if (origItem == null)
                return BusinessErrorCodes.ERROR_MAIL_DOMAIN_PACKAGE_ITEM_NOT_FOUND;

            // find if account exists under this mail domain
            List<ServiceProviderItem> accounts = PackageController.GetPackageItemsByName(
                origItem.PackageId, "%@" + origItem.Name);

            if (accounts.Count > 0)
                return BusinessErrorCodes.ERROR_MAIL_DOMAIN_IS_NOT_EMPTY; // mail domain is not empty

            // place log record
            TaskManager.StartTask("MAIL_DOMAIN", "DELETE", origItem.Name);
            TaskManager.ItemId = itemId;

            try
            {
                // get service
                MailServer mail = new MailServer();
                ServiceProviderProxy.Init(mail, origItem.ServiceId);

                // delete service item
                mail.DeleteDomain(origItem.Name);

                // delete meta item
                PackageController.DeletePackageItem(origItem.Id);

                // update related domain with a new pointer
                DomainInfo domain = ServerController.GetDomain(origItem.Name);
                if (domain != null)
                {
                    domain.MailDomainId = 0;
                    ServerController.UpdateDomain(domain);
                }

                return 0;
            }
            catch (Exception ex)
            {
                throw TaskManager.WriteError(ex);
            }
            finally
            {
                TaskManager.CompleteTask();
            }
        }
        public static int UpdateMailDomain(MailDomain item)
        {
            // check account
            int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);
            if (accountCheck < 0) return accountCheck;

            // load original meta item
            MailDomain origItem = (MailDomain)PackageController.GetPackageItem(item.Id);
            if (origItem == null)
                return BusinessErrorCodes.ERROR_MAIL_DOMAIN_PACKAGE_ITEM_NOT_FOUND;

            // check package
            int packageCheck = SecurityContext.CheckPackage(origItem.PackageId, DemandPackage.IsActive);
            if (packageCheck < 0) return packageCheck;

            // place log record
            TaskManager.StartTask("MAIL_DOMAIN", "UPDATE", origItem.Name);
            TaskManager.ItemId = item.Id;

            // get service
            MailServer mail = new MailServer();
            ServiceProviderProxy.Init(mail, origItem.ServiceId);
            item.Name = origItem.Name;
            item.Enabled = true;

            try
            {
                // update service item
                mail.UpdateDomain(item);

                // update meta item
                PackageController.UpdatePackageItem(item);
                return 0;
            }
            catch (Exception ex)
            {
                throw TaskManager.WriteError(ex);
            }
            finally
            {
                TaskManager.CompleteTask();
            }
        }
        public static MailList GetMailList(int itemId)
        {
            // load meta item
            MailList item = (MailList)PackageController.GetPackageItem(itemId);

            // load service item
            MailServer mail = new MailServer();
            ServiceProviderProxy.Init(mail, item.ServiceId);
            MailList list = mail.GetList(item.Name);

            // add common properties
            list.Id = item.Id;
            list.PackageId = item.PackageId;
            list.ServiceId = item.ServiceId;

            return list;
        }
        public static int UpdateMailAccount(MailAccount item)
        {
            // check account
            int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);
            if (accountCheck < 0) return accountCheck;

            // load original meta item
            MailAccount origItem = (MailAccount)PackageController.GetPackageItem(item.Id);
            if (origItem == null)
                return BusinessErrorCodes.ERROR_MAIL_ACCOUNTS_PACKAGE_ITEM_NOT_FOUND;

            // check package
            int packageCheck = SecurityContext.CheckPackage(origItem.PackageId, DemandPackage.IsActive);
            if (packageCheck < 0) return packageCheck;

            // place log record
            TaskManager.StartTask("MAIL_ACCOUNT", "UPDATE", origItem.Name);
            TaskManager.ItemId = item.Id;

            try
            {
                // restore original props
                if (item.Password == "")
                    item.Password = CryptoUtils.Decrypt(origItem.Password);

                // get service
                MailServer mail = new MailServer();
                ServiceProviderProxy.Init(mail, origItem.ServiceId);
                item.Name = origItem.Name;
                item.Enabled = true;

                item.MaxMailboxSize = GetMaxMailBoxSize(origItem.PackageId, item);
                                
                if (String.IsNullOrEmpty(item.Password))
                {
                    // get password from the service
                    MailAccount origBox = mail.GetAccount(item.Name);
                    item.Password = origBox.Password;
                }

                // update service item
                mail.UpdateAccount(item);

                // update meta item
                item.Password = CryptoUtils.Encrypt(item.Password);
                PackageController.UpdatePackageItem(item);
                return 0;
            }
            catch (Exception ex)
            {
                throw TaskManager.WriteError(ex);
            }
            finally
            {
                TaskManager.CompleteTask();
            }
        }
        public static int AddMailList(MailList 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
            QuotaValueInfo quota = PackageController.GetPackageQuota(item.PackageId, Quotas.MAIL_LISTS);
            if (quota.QuotaExhausted)
                return BusinessErrorCodes.ERROR_MAIL_LISTS_RESOURCE_QUOTA_LIMIT;

            // check recipients number
            if (!CheckRecipientsAllowedNumber(item.PackageId, Quotas.MAIL_MAXLISTMEMBERS, item.Members))
                return BusinessErrorCodes.ERROR_MAIL_LISTS_RECIPIENTS_LIMIT;

            // check if mail resource is available
            int serviceId = PackageController.GetPackageServiceId(item.PackageId, ResourceGroups.Mail);
            if (serviceId == 0)
                return BusinessErrorCodes.ERROR_MAIL_RESOURCE_UNAVAILABLE;

            // check package items
            if (PackageController.GetPackageItemByName(item.PackageId, item.Name, typeof(MailList)) != null)
                return BusinessErrorCodes.ERROR_MAIL_LISTS_PACKAGE_ITEM_EXISTS;

            // place log record
            TaskManager.StartTask("MAIL_LIST", "ADD", item.Name);
            
            try
            {
                // check service items
                MailServer mail = new MailServer();
                ServiceProviderProxy.Init(mail, serviceId);
                if (mail.ListExists(item.Name))
                    return BusinessErrorCodes.ERROR_MAIL_LISTS_SERVICE_ITEM_EXISTS;

                // add domain if not exists
                string domainName = item.Name.Substring(item.Name.IndexOf("@") + 1);
                int domainResult = AddMailDomain(item.PackageId, serviceId, domainName);
                if (domainResult < 0)
                    return domainResult;

                // create service item
                item.Enabled = true;
				item.Members = RemoveItemNameFromMembersList(
						  item.Name
						, item.Members.Clone() as string[]
					);

                // add service item
                mail.CreateList(item);

                // save item
                item.ServiceId = serviceId;
                item.Password = CryptoUtils.Encrypt(item.Password);
                int itemId = PackageController.AddPackageItem(item);

                TaskManager.ItemId = itemId;

                return itemId;
            }
            catch (Exception ex)
            {
                throw TaskManager.WriteError(ex);
            }
            finally
            {
                TaskManager.CompleteTask();
            }
        }
        public static MailAlias GetMailForwarding(int itemId)
        {
            // load meta item
            MailAlias item = (MailAlias)PackageController.GetPackageItem(itemId);

            // load service item
            MailServer mail = new MailServer();
            ServiceProviderProxy.Init(mail, item.ServiceId);
            MailAlias alias = mail.GetMailAlias(item.Name);

            // add common properties
            if (!String.IsNullOrEmpty(alias.ForwardTo))
            {
                item.ForwardTo = alias.ForwardTo;
            }
            else
            {
                item.ForwardTo = alias.ForwardingAddresses[0];
            }


            return item;
        }
        public static int AddMailAccount(MailAccount 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
            QuotaValueInfo quota = PackageController.GetPackageQuota(item.PackageId, Quotas.MAIL_ACCOUNTS);
            if (quota.QuotaExhausted)
                return BusinessErrorCodes.ERROR_MAIL_ACCOUNTS_RESOURCE_QUOTA_LIMIT;

            // check if mail resource is available
            int serviceId = PackageController.GetPackageServiceId(item.PackageId, ResourceGroups.Mail);
            if (serviceId == 0)
                return BusinessErrorCodes.ERROR_MAIL_RESOURCE_UNAVAILABLE;

            // check package items
            if (PackageController.GetPackageItemByName(item.PackageId, item.Name, typeof(MailAccount)) != null)
                return BusinessErrorCodes.ERROR_MAIL_ACCOUNTS_PACKAGE_ITEM_EXISTS;

            // place log record
            TaskManager.StartTask("MAIL_ACCOUNT", "ADD", item.Name);
            int itemId = 0;
            try
            {

                // check service items
                MailServer mail = new MailServer();
                ServiceProviderProxy.Init(mail, serviceId);
                if (mail.AccountExists(item.Name))
                    return BusinessErrorCodes.ERROR_MAIL_ACCOUNTS_SERVICE_ITEM_EXISTS;

                // add domain if not exists
                string domainName = item.Name.Substring(item.Name.IndexOf("@") + 1);
                int domainResult = AddMailDomain(item.PackageId, serviceId, domainName);
                if (domainResult < 0)
                    return domainResult;

                // create service item
                item.Enabled = true;
                item.MaxMailboxSize = GetMaxMailBoxSize(item.PackageId, item);

                // add service item
                mail.CreateAccount(item);

                // save item
                item.Password = CryptoUtils.Encrypt(item.Password);
                item.ServiceId = serviceId;
                itemId = PackageController.AddPackageItem(item);

                TaskManager.ItemId = itemId;
                                
            }
            catch (Exception ex)
            {
                TaskManager.WriteError(ex);
                if (ex.InnerException != null &&
                    ex.InnerException.Message.Contains("The maximum number of domains allowed has been reached"))
                {
                    return BusinessErrorCodes.ERROR_MAIL_LICENSE_DOMAIN_QUOTA;
                }
                if (ex.Message != null && ex.Message.Contains("The maximum number of users for the server has been reached"))
                {
                    return BusinessErrorCodes.ERROR_MAIL_LICENSE_USERS_QUOTA;
                }
            }
            finally
            {
                TaskManager.CompleteTask();
            }
            return itemId;
        }
        public static int AddMailForwarding(MailAlias 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
            QuotaValueInfo quota = PackageController.GetPackageQuota(item.PackageId, Quotas.MAIL_FORWARDINGS);
            if (quota.QuotaExhausted)
                return BusinessErrorCodes.ERROR_MAIL_FORWARDINGS_RESOURCE_QUOTA_LIMIT;

            // check if mail resource is available
            int serviceId = PackageController.GetPackageServiceId(item.PackageId, ResourceGroups.Mail);
            if (serviceId == 0)
                return BusinessErrorCodes.ERROR_MAIL_RESOURCE_UNAVAILABLE;

            // check package items
            if (PackageController.GetPackageItemByName(item.PackageId, item.Name, typeof(MailAlias)) != null)
                return BusinessErrorCodes.ERROR_MAIL_FORWARDINGS_PACKAGE_ITEM_EXISTS;

            // place log record
            TaskManager.StartTask("MAIL_FORWARDING", "ADD", item.Name);

            try
            {
                // check service items
                MailServer mail = new MailServer();
                ServiceProviderProxy.Init(mail, serviceId);
                if (mail.MailAliasExists(item.Name))
                    return BusinessErrorCodes.ERROR_MAIL_FORWARDINGS_SERVICE_ITEM_EXISTS;

                // add domain if not exists
                string domainName = item.Name.Substring(item.Name.IndexOf("@") + 1);
                int domainResult = AddMailDomain(item.PackageId, serviceId, domainName);
                if (domainResult < 0)
                    return domainResult;

                // create service item
                MailAlias alias = new MailAlias();
                alias.Name = item.Name;
                alias.ForwardTo = item.ForwardTo;
                //for MailEnable alias creation
                alias.DeleteOnForward = true;
                alias.ForwardingAddresses = new string[1];
                alias.ForwardingAddresses[0] = item.ForwardTo;
                alias.Password = Guid.NewGuid().ToString("N").Substring(0, 12);
                alias.Enabled = true;
				
                // add service item
                mail.CreateMailAlias(alias);

                // save item
                item.ServiceId = serviceId;
                int itemId = PackageController.AddPackageItem(item);

                TaskManager.ItemId = itemId;

                return itemId;
            }
            catch (Exception ex)
            {
                throw TaskManager.WriteError(ex);
            }
            finally
            {
                TaskManager.CompleteTask();
            }
        }
        public static MailDomain GetMailDomain(int itemId)
        {
            // load meta item
            MailDomain item = (MailDomain)PackageController.GetPackageItem(itemId);

            // load service item
            MailServer mail = new MailServer();
            ServiceProviderProxy.Init(mail, item.ServiceId);
            MailDomain domain = mail.GetDomain(item.Name);

            // add common properties
            domain.Id = item.Id;
            domain.PackageId = item.PackageId;
            domain.ServiceId = item.ServiceId;

            return domain;
        }
        public static int UpdateMailAccount(MailAccount item)
        {
            // check account
            int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);
            if (accountCheck < 0) return accountCheck;

            // load original meta item
            MailAccount origItem = (MailAccount)PackageController.GetPackageItem(item.Id);
            if (origItem == null)
                return BusinessErrorCodes.ERROR_MAIL_ACCOUNTS_PACKAGE_ITEM_NOT_FOUND;

            // check package
            int packageCheck = SecurityContext.CheckPackage(origItem.PackageId, DemandPackage.IsActive);
            if (packageCheck < 0) return packageCheck;

            // check mailbox account size limit
            if (item.MaxMailboxSize < -1)
                return BusinessErrorCodes.ERROR_MAIL_ACCOUNT_MAX_MAILBOX_SIZE_LIMIT;

            // place log record
            TaskManager.StartTask("MAIL_ACCOUNT", "UPDATE", origItem.Name, item.Id);

            try
            {
                // restore original props
                if (item.Password == "")
                    item.Password = CryptoUtils.Decrypt(origItem.Password);

                // get service
                MailServer mail = new MailServer();
                ServiceProviderProxy.Init(mail, origItem.ServiceId);
                item.Name = origItem.Name;

                item.MaxMailboxSize = GetMaxMailBoxSize(origItem.PackageId, item);

                if (String.IsNullOrEmpty(item.Password))
                {
                    // get password from the service
                    MailAccount origBox = mail.GetAccount(item.Name);
                    item.Password = origBox.Password;
                }

                // update service item
                mail.UpdateAccount(item);

                // update meta item
                item.Password = CryptoUtils.Encrypt(item.Password);
                PackageController.UpdatePackageItem(item);
                return 0;
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("Password doesn't meet complexity") ||
                    ex.Message.Contains("IceWarp password policy denies use of this account") ||
                    ex.Message.Contains("Invalid characters in password"))
                {
                    return BusinessErrorCodes.ERROR_MAIL_ACCOUNT_PASSWORD_NOT_COMPLEXITY;
                }

                throw TaskManager.WriteError(ex);
            }
            finally
            {
                TaskManager.CompleteTask();
            }
        }