public async Task <Result <List <ESightAppliance> > > LoadAll()
        {
            try
            {
                var getListResult = await OM12ESightApplianceRepo.Instance.All();

                if (!getListResult.Success)
                {
                    LogHelper.Error(getListResult.Cause, getListResult.Message);
                    return(Result <List <ESightAppliance> > .Failed(getListResult.Code, getListResult.Message, getListResult.Cause));
                }
                this.Items = getListResult.Data.Select(x => GetModelFromMpObject(x)).ToList();
                foreach (var appliance in this.Items)
                {
                    if (PingFd(appliance.Host))
                    {
                        appliance.LatestStatus = Constants.ESightConnectionStatus.ONLINE;
                    }
                    else
                    {
                        appliance.LatestStatus = Constants.ESightConnectionStatus.FAILED;
                        LogHelper.Info("Can not connect the remote server.", $"PingFd Error:");
                    }
                }
                Filter();
                return(Result <List <ESightAppliance> > .Done(this.Items));
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex, "LoadAll");
                return(Result <List <ESightAppliance> > .Failed("LoadAll", ex));
            }
        }
        internal async Task <Result> Add(ESightAppliance appliance)
        {
            try
            {
                Result validateResult = Validate(appliance);
                if (!validateResult.Success)
                {
                    return(validateResult);
                }
                var client = new ESightClient(appliance);
                var result = await client.TestCredential();

                if (!result.Success)
                {
                    return(result);
                }
                var addResult = await OM12ESightApplianceRepo.Instance.Add(appliance);

                if (addResult.Success)
                {
                    await this.LoadAll();
                }
                return(addResult);
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex, "Add");
                return(Result.Failed(100, "Add", ex));
            }
        }
        public async Task <Result> Add(ESightAppliance appliance)
        {
            return(await Task.Run(() =>
            {
                try
                {
                    if (OM12Connection.Exsits(ESightAppliance.EntityClassName, $"Host='{appliance.Host}'"))
                    {
                        return Result.Failed(101, $"ESight {appliance.Host} already exsits.");
                    }

                    IncrementalDiscoveryData incrementalDiscoveryData = new IncrementalDiscoveryData();

                    // add appliance record
                    ManagementPackClass MPClass = GetMPClass();
                    CreatableEnterpriseManagementObject EMOAppliance =
                        new CreatableEnterpriseManagementObject(OM12Connection.HuaweiESightMG, MPClass);
                    IDictionary <string, ManagementPackProperty> props =
                        OM12Connection.GetManagementPackProperties(EMOAppliance);
                    EMOAppliance[props["Host"]].Value = appliance.Host;
                    EMOAppliance[props["Port"]].Value = appliance.Port;
                    EMOAppliance[props["AliasName"]].Value = appliance.AliasName;
                    EMOAppliance[props["SystemId"]].Value = appliance.SystemId;
                    EMOAppliance[props["LoginAccount"]].Value = appliance.LoginAccount;
                    EMOAppliance[props["LoginPassword"]].Value = RijndaelManagedCrypto.Instance
                                                                 .EncryptForCS(appliance.LoginPassword);
                    EMOAppliance[props["LastModifiedOn"]].Value = DateTime.UtcNow;
                    EMOAppliance[props["CreatedOn"]].Value = DateTime.UtcNow;

                    EMOAppliance[props["OpenID"]].Value = Guid.NewGuid().ToString("D");
                    EMOAppliance[props["SubscribeID"]].Value = Guid.NewGuid().ToString("D");
                    EMOAppliance[props["SubKeepAliveStatus"]].Value = 0;
                    EMOAppliance[props["SubscriptionAlarmStatus"]].Value = 0;
                    EMOAppliance[props["SubscriptionNeDeviceStatus"]].Value = 0;

                    EMOAppliance[props["SubKeepAliveError"]].Value = string.Empty;
                    EMOAppliance[props["SubscripeAlarmError"]].Value = string.Empty;
                    EMOAppliance[props["SubscripeNeDeviceError"]].Value = string.Empty;
                    //EMOAppliance[props["LatestConnectInfo"]].Value = string.Empty;

                    //EMOAppliance[props["LatestStatus"]].Value = Constants.ESightConnectionStatus.NONE;

                    ManagementPackClass baseEntity = OM12Connection.GetManagementPackClass("System.Entity");
                    EMOAppliance[baseEntity, "DisplayName"].Value = appliance.Host;
                    incrementalDiscoveryData.Add(EMOAppliance);
                    incrementalDiscoveryData.Commit(OM12Connection.HuaweiESightMG);
                    return Result.Done();
                }
                catch (Exception e)
                {
                    return Result.Failed(100, $"Internal error caused by {e.Message}", e);
                }
            }));
        }
        internal async Task <Result> Update(ESightAppliance appliance)
        {
            try
            {
                Result validateResult = Validate(appliance);
                if (!validateResult.Success)
                {
                    return(validateResult);
                }
                if (appliance.UpdateCredential)//修改了密码
                {
                    var client = new ESightClient(appliance);
                    var result = await client.TestCredential();

                    if (!result.Success)
                    {
                        return(result);
                    }
                }
                else
                {
                    var oldESightObj = await OM12ESightApplianceRepo.Instance.FindByHost(appliance.Host);

                    if (oldESightObj.Data == null)
                    {
                        return(Result.Failed(104, $"eSight {appliance.Host} can not find."));
                    }
                    var oldESight = GetModelFromMpObject(oldESightObj.Data);
                    if (oldESight.Port != appliance.Port) //修改了端口
                    {
                        appliance.LoginPassword = oldESight.LoginPassword;
                        var client = new ESightClient(appliance);
                        var result = await client.TestCredential();

                        if (!result.Success)
                        {
                            return(result);
                        }
                    }
                }
                var updateResult = await OM12ESightApplianceRepo.Instance.Update(appliance);

                if (updateResult.Success)
                {
                    await this.LoadAll();
                }
                return(updateResult);
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex, "Update");
                return(Result.Failed(100, "Update", ex));
            }
        }
        public async Task <Result> Update(ESightAppliance appliance)
        {
            return(await Task.Run(async() =>
            {
                try
                {
                    var obj = await this.FindByHost(appliance.Host);
                    var exsitObj = obj.Data;
                    if (exsitObj == null)
                    {
                        return Result.Failed(104, $"ESight {appliance.Host} can not find.");
                    }
                    IncrementalDiscoveryData incrementalDiscoveryData = new IncrementalDiscoveryData();

                    // update appliance record
                    ManagementPackClass MPClass = GetMPClass();
                    EnterpriseManagementObject managementObject = obj.Data;
                    var props = OM12Connection.GetManagementPackProperties(managementObject);
                    managementObject[props["Port"]].Value = appliance.Port;
                    managementObject[props["AliasName"]].Value = appliance.AliasName;
                    string currentSystemId = managementObject[props["SystemId"]].Value as string;
                    bool IsSystemIdChanged = currentSystemId != appliance.SystemId;
                    if (IsSystemIdChanged)
                    {
                        managementObject[props["SystemId"]].Value = appliance.SystemId;
                        managementObject[props["SubscribeID"]].Value = Guid.NewGuid().ToString("D");
                        managementObject[props["SubKeepAliveStatus"]].Value = 0;
                        managementObject[props["SubscriptionAlarmStatus"]].Value = 0;
                        managementObject[props["SubscriptionNeDeviceStatus"]].Value = 0;
                        managementObject[props["SubKeepAliveError"]].Value = string.Empty;
                        managementObject[props["SubscripeAlarmError"]].Value = string.Empty;
                        managementObject[props["SubscripeNeDeviceError"]].Value = string.Empty;
                    }
                    if (appliance.UpdateCredential)
                    {
                        managementObject[props["LoginAccount"]].Value = appliance.LoginAccount;
                        managementObject[props["LoginPassword"]].Value = RijndaelManagedCrypto.Instance
                                                                         .EncryptForCS(appliance.LoginPassword);
                    }
                    managementObject[props["LastModifiedOn"]].Value = DateTime.UtcNow;
                    incrementalDiscoveryData.Add(managementObject);
                    incrementalDiscoveryData.Commit(OM12Connection.HuaweiESightMG);
                    return Result.Done();
                }
                catch (Exception e)
                {
                    return Result.Failed(100, $"Internal error caused by {e.Message}", e);
                }
            }));
        }
 public async Task <Result <EnterpriseManagementObject> > FindByHost(string host)
 {
     return(await Task.Run(() =>
     {
         try
         {
             var objects = OM12Connection.Query <EnterpriseManagementObject>(ESightAppliance.EntityClassName, $"Host='{host}'");
             return Result <EnterpriseManagementObject> .Done(objects.FirstOrDefault());
         }
         catch (Exception e)
         {
             return Result <EnterpriseManagementObject> .Failed(100, $"Internal error caused by {e.Message}", e);
         }
     }));
 }
 public async Task <Result <List <EnterpriseManagementObject> > > All()
 {
     return(await Task.Run(() =>
     {
         try
         {
             var objects = OM12Connection.All <EnterpriseManagementObject>(ESightAppliance.EntityClassName);
             return Result <List <EnterpriseManagementObject> > .Done(objects.ToList());
         }
         catch (Exception e)
         {
             return Result <List <EnterpriseManagementObject> > .Failed("Get List Error", e);
         }
     }));
 }
        public async Task <Result> Delete(ESightAppliance appliance)
        {
            try
            {
                var deleteResult = await OM12ESightApplianceRepo.Instance.Delete(appliance);

                if (deleteResult.Success)
                {
                    await this.LoadAll();
                }
                return(deleteResult);
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex, "Test");
                return(Result.Failed(100, "Test", ex));
            }
        }
 internal async Task <Result> Test(ESightAppliance appliance)
 {
     try
     {
         Result validateResult = Validate(appliance);
         if (!validateResult.Success)
         {
             return(validateResult);
         }
         var client = new ESightClient(appliance);
         return(await client.TestCredential());
     }
     catch (Exception ex)
     {
         LogHelper.Error(ex, "Test");
         return(Result.Failed(100, "Test", ex));
     }
 }
 public async Task <Result> Delete(ESightAppliance appliance)
 {
     return(await Task.Run(async() =>
     {
         IncrementalDiscoveryData incrementalDiscoveryData = new IncrementalDiscoveryData();
         try
         {
             var obj = await this.FindByHost(appliance.Host);
             var exsitObj = obj.Data;
             if (exsitObj == null)
             {
                 return Result.Failed(104, $"{appliance.Host} does not exists, delete failed.");
             }
             incrementalDiscoveryData.Remove(obj.Data);
             incrementalDiscoveryData.Commit(OM12Connection.HuaweiESightMG);
             return Result.Done();
         }
         catch (Exception e)
         {
             return Result.Failed(100, $"Internal error caused by {e.Message}", e);
         }
     }));
 }
 public static Result Failed(String message)
 {
     return(Result.Failed(DEFAULT_FAILIRE_CODE, message));
 }
        public Result Validate(ESightAppliance appliance)
        {
            // host
            if (string.IsNullOrEmpty(appliance.Host))
            {
                return(Result.Failed(1000, "Host should not be null or empty."));
            }


            IPAddress Address;
            bool      isValidIPAddr = IPAddress.TryParse(appliance.Host, out Address);
            bool      isValidDomain = Uri.CheckHostName(appliance.Host) != UriHostNameType.Unknown;

            if (!isValidIPAddr && !isValidDomain)
            {
                return(Result.Failed(1000, "Host should be a valid IP adress or domain name."));
            }
            if (isValidIPAddr)
            {
                if (Address.AddressFamily.Equals(AddressFamily.InterNetwork))
                {
                    if (!Regex.IsMatch(appliance.Host, "^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$"))
                    {
                        return(Result.Failed(1000, "Host should be a valid IP adress or domain name."));
                    }
                }
            }


            // port
            if (string.IsNullOrEmpty(appliance.Port))
            {
                return(Result.Failed(1001, "Port should not be null or empty."));
            }

            int  PortAsInt;
            bool isNumeric = int.TryParse(appliance.Port, out PortAsInt);

            if (isNumeric)
            {
                if (PortAsInt < 1 || PortAsInt > 65535)
                {
                    return(Result.Failed(1001, "Port should be a digits between 1 and 65535."));
                }
            }
            else
            {
                return(Result.Failed(1001, "Port should be a digits between 1 and 65535."));
            }

            // System Id
            if (string.IsNullOrEmpty(appliance.SystemId))
            {
                return(Result.Failed(1001, "SystemId should not be null or empty."));
            }

            if (!Regex.IsMatch(appliance.SystemId, PatternDigits))
            {
                return(Result.Failed(1001, "SystemId should contains 1 to 100 characters, which can include letters, digits, hyphens (-), underscores (_), and periods(.)."));
            }


            if (appliance.UpdateCredential)
            {
                // Login Account
                if (string.IsNullOrEmpty(appliance.LoginAccount))
                {
                    return(Result.Failed(1001, "Account should not be null or empty."));
                }
                if (appliance.LoginAccount.Length > 32 || appliance.LoginAccount.Length < 6)
                {
                    return(Result.Failed(1001, "Account should contains 6 to 32 characters. The following special characters are not allowed: \"#%&'+/;<=>?\\©®"));
                }
                if (Regex.Match(appliance.LoginAccount, PatternAccount).Success)
                {
                    return(Result.Failed(1001, "Account should contains 6 to 32 characters. The following special characters are not allowed: \"#%&'+/;<=>?\\©®"));
                }
                // Login Password
                if (string.IsNullOrEmpty(appliance.LoginPassword))
                {
                    return(Result.Failed(1001, "Password should not be null or empty."));
                }
                if (appliance.LoginPassword.Length > 32 || appliance.LoginPassword.Length < 8)
                {
                    return(Result.Failed(1001, "The password can contain only 8 to 32 characters"));
                }
                char[] charArray = appliance.LoginAccount.ToCharArray();
                Array.Reverse(charArray);
                var reverseAccount = new string(charArray);
                if (Regex.Match(appliance.LoginPassword, appliance.LoginAccount).Success || Regex.Match(appliance.LoginPassword, reverseAccount).Success)
                {
                    return(Result.Failed(1001, "The password cannot contain the user name or the reverse of the user name."));
                }
                var regexPwd = new Regex(@"
(?=.*[0-9])                              #必须包含数字
(?=.*[a-z])                              #必须包含小写字母
(?=.*[A-Z])                              #必须包含大写字母
.{8,32}                                  #至少8个字符,最多32个字符
", RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace);

                if (!regexPwd.IsMatch(appliance.LoginPassword))
                {
                    return(Result.Failed(1001, "The password must contain 1 uppercase letter, 1 lowercase letter, and 1 digit."));
                }
                char[] charArray1 = appliance.LoginPassword.ToCharArray();
                var    count      = charArray1.GroupBy(e => e).OrderByDescending(e => e.Count()).First().ToList().Count();
                if (count > 2)
                {
                    return(Result.Failed(1001, "Each character in the password cannot be used more than 2 times"));
                }
            }
            return(Result.Done());
        }