예제 #1
0
        /// <summary>
        /// Get a list of all hosts filtered by name
        /// </summary>
        /// <param name="hostName">name to filter on, do not use wildcards</param>
        /// <returns>List of all ESXi hosts</returns>
        public List <HostSystem> GetHostSystems(string hostFilterName)
        {
            List <HostSystem> hostSystems = new List <HostSystem>();

            try {
                Datacenter dataCenter = (Datacenter)vSphereClient.FindEntityView(typeof(Datacenter), null, null, null);
                Folder     folder     = (Folder)vSphereClient.GetView(dataCenter.HostFolder, null);
                foreach (VMware.Vim.ManagedObjectReference mObjR in folder.ChildEntity.Where(x => x.Type == "ComputeResource"))
                {
                    ComputeResource computeResource = (ComputeResource)vSphereClient.GetView(mObjR, null);
                    foreach (VMware.Vim.ManagedObjectReference hostRef in computeResource.Host)
                    {
                        HostSystem hostSystem = (HostSystem)vSphereClient.GetView(hostRef, null);
                        if (hostSystem.Name.Contains(hostFilterName) || hostSystem.Name.Equals(hostFilterName))
                        {
                            hostSystems.Add(hostSystem);
                        }
                    }
                }
            }
            catch {
                throw;
            }
            return(hostSystems);
        }
예제 #2
0
 protected override void InternalProcessRecord()
 {
     TaskLogger.LogEnter();
     try
     {
         LocalizedException ex = null;
         if (!Datacenter.IsMultiTenancyEnabled())
         {
             ex = base.ResetAutomatedCredentialsOnMailboxServer(this.localServer, true);
         }
         if (ex == null)
         {
             base.WriteMonitoringEvent(1000, this.MonitoringEventSource, EventTypeEnumeration.Success, Strings.AllActiveSyncTransactionsSucceeded);
         }
         else if (ex is CasHealthUserNotFoundException)
         {
             base.WriteMonitoringEvent(1008, this.MonitoringEventSource, EventTypeEnumeration.Warning, Strings.InstructResetCredentials(base.ShortErrorMsgFromException(ex)));
         }
         else
         {
             base.WriteMonitoringEvent(1001, this.MonitoringEventSource, EventTypeEnumeration.Error, base.ShortErrorMsgFromException(ex));
         }
     }
     finally
     {
         if (base.MonitoringContext)
         {
             base.WriteMonitoringData();
         }
         TaskLogger.LogExit();
     }
 }
예제 #3
0
        protected override void InternalValidate()
        {
            base.InternalValidate();
            IRMConfiguration dataObject = this.DataObject;

            try
            {
                this.ValidateCommon();
                this.datacenter = (Datacenter.IsMicrosoftHostedOnly(true) || Datacenter.IsPartnerHostedOnly(true));
                if (this.datacenter)
                {
                    this.ValidateForDC(dataObject);
                }
                else
                {
                    this.ValidateForEnterprise(dataObject);
                }
            }
            catch (CannotDetermineExchangeModeException exception)
            {
                base.WriteError(SetIRMConfiguration.GetExceptionInfo(exception), ErrorCategory.InvalidOperation, base.Identity);
            }
            catch (ExchangeConfigurationException exception2)
            {
                base.WriteError(SetIRMConfiguration.GetExceptionInfo(exception2), ErrorCategory.InvalidOperation, base.Identity);
            }
            catch (RightsManagementException exception3)
            {
                base.WriteError(SetIRMConfiguration.GetExceptionInfo(exception3), ErrorCategory.InvalidOperation, base.Identity);
            }
        }
        private void Configure()
        {
            configuration = new Configuration
            {
                Username = "******",
                Password = "******",
            };

            dcApi = new DataCenterApi(configuration);
            lbApi = new LoadBalancerApi(configuration);

            //Create a datacenter.
            if (datacenter == null)
            {
                datacenter = new Datacenter
                {
                    Properties = new DatacenterProperties
                    {
                        Name        = ".Net V2 - Test " + DateTime.Now.ToShortTimeString(),
                        Description = "Unit test for .Net SDK PB REST V2",
                        Location    = "us/lasdev"
                    }
                };

                datacenter = dcApi.Create(datacenter);
            }
        }
예제 #5
0
        public override string ToString()
        {
            var sb    = new StringBuilder("EndpointDetails(");
            int tmp67 = 0;

            if ((Host != null) && __isset.host)
            {
                if (0 < tmp67++)
                {
                    sb.Append(", ");
                }
                sb.Append("Host: ");
                Host.ToString(sb);
            }
            if ((Datacenter != null) && __isset.datacenter)
            {
                if (0 < tmp67++)
                {
                    sb.Append(", ");
                }
                sb.Append("Datacenter: ");
                Datacenter.ToString(sb);
            }
            if ((Rack != null) && __isset.rack)
            {
                if (0 < tmp67++)
                {
                    sb.Append(", ");
                }
                sb.Append("Rack: ");
                Rack.ToString(sb);
            }
            sb.Append(')');
            return(sb.ToString());
        }
예제 #6
0
        // Token: 0x06000DCE RID: 3534 RVA: 0x00029590 File Offset: 0x00027790
        private IEnumerable <T> TryGetObjectsFromDC <T>(ADObjectId rootId, IDirectorySession subTreeSession, OptionalIdentityData optionalData) where T : IConfigurable, new()
        {
            if (rootId != null || this.HasEmptyGuid || Datacenter.GetExchangeSku() != Datacenter.ExchangeSku.Enterprise)
            {
                return(EnumerableWrapper <T> .Empty);
            }
            rootId = subTreeSession.GetRootDomainNamingContext();
            if (rootId != null && optionalData != null && optionalData.RootOrgDomainContainerId != null)
            {
                optionalData.RootOrgDomainContainerId = null;
            }
            bool            useGlobalCatalog = subTreeSession.UseGlobalCatalog;
            IEnumerable <T> exactMatchObjects;

            try
            {
                subTreeSession.UseGlobalCatalog = false;
                exactMatchObjects = base.GetExactMatchObjects <T>(rootId, subTreeSession, optionalData);
            }
            finally
            {
                subTreeSession.UseGlobalCatalog = useGlobalCatalog;
            }
            return(exactMatchObjects);
        }
예제 #7
0
 protected override void InternalValidate()
 {
     if (!base.Fields.IsModified("Path"))
     {
         base.Path = System.IO.Path.Combine(ConfigurationContext.Setup.InstallPath, this.VirtualDirectoryPath);
     }
     base.InternalValidate();
     if (base.HasErrors)
     {
         return;
     }
     base.InternalValidateBasicLiveIdBasic();
     if (string.Empty.Equals(this.AppPoolIdForManagement))
     {
         base.WriteError(new ArgumentException(Strings.ErrorAppPoolIdCannotBeEmpty, "AppPoolIdForManagement"), ErrorCategory.InvalidArgument, this.DataObject.Identity);
     }
     if (Datacenter.IsMicrosoftHostedOnly(true))
     {
         string path = System.IO.Path.Combine(base.Path, "Nego2");
         if (!Directory.Exists(path))
         {
             base.WriteError(new ArgumentException(Strings.ErrorDirectoryManagementWebServiceNotFound(path), "Path"), ErrorCategory.InvalidArgument, this.DataObject.Identity);
         }
     }
 }
예제 #8
0
        // Token: 0x0600067D RID: 1661 RVA: 0x00031744 File Offset: 0x0002F944
        protected override bool QueryIsEnabled()
        {
            if (!Datacenter.IsMultiTenancyEnabled())
            {
                EHAQuotaWarningEnforcer.Tracer.TraceDebug <EHAQuotaWarningEnforcer>((long)this.GetHashCode(), "{0}: All the checks below make sense only for DC and not for enterprise.", this);
                return(false);
            }
            if (!base.MailboxDataForTags.ElcUserInformation.ProcessEhaMigratedMessages)
            {
                EHAQuotaWarningEnforcer.Tracer.TraceDebug <EHAQuotaWarningEnforcer>((long)this.GetHashCode(), "{0}: Organization's ProcessEhaMigratedMessages settings is set to false. This mailbox will not be processed for migration messages", this);
                return(false);
            }
            TransportConfigContainer tenantTransportConfig = EHAQuotaWarningEnforcer.GetTenantTransportConfig(base.MailboxDataForTags.ElcUserTagInformation.ADUser.OrganizationId, this);

            if (tenantTransportConfig != null && !tenantTransportConfig.LegacyArchiveJournalingEnabled)
            {
                EHAQuotaWarningEnforcer.Tracer.TraceDebug <EHAQuotaWarningEnforcer>((long)this.GetHashCode(), "{0}: EHA Migration is already complete for this tenant, Skip Quota enforcer check.", this);
                return(false);
            }
            if (base.MailboxDataForTags.MailboxSession.MailboxOwner.MailboxInfo.IsArchive)
            {
                EHAQuotaWarningEnforcer.Tracer.TraceDebug <EHAQuotaWarningEnforcer>((long)this.GetHashCode(), "{0}: This is archive mailbox. This mailbox will not be processed for migration messages", this);
                return(false);
            }
            if (!this.IsMailboxInteresting())
            {
                EHAQuotaWarningEnforcer.Tracer.TraceDebug <EHAQuotaWarningEnforcer>((long)this.GetHashCode(), "{0}: This is not one of the eha mailboxes : journal ndr or confirmation mailbox. This mailbox will be skipped.", this);
                return(false);
            }
            return(true);
        }
        protected override void InternalValidate()
        {
            base.InternalValidate();
            if (this.Identity == null && this.Server == null)
            {
                this.Server = MailboxServerIdParameter.Parse(Environment.MachineName);
            }
            MailboxServerIdParameter mailboxServerIdParameter = null;

            if (this.Server != null)
            {
                mailboxServerIdParameter = this.Server;
            }
            else if (this.Local)
            {
                mailboxServerIdParameter = MailboxServerIdParameter.Parse(Environment.MachineName);
            }
            if (mailboxServerIdParameter != null)
            {
                this.m_server = (Server)base.GetDataObject <Server>(mailboxServerIdParameter, base.DataSession, null, new LocalizedString?(Strings.ErrorMailboxServerNotFound(mailboxServerIdParameter.ToString())), new LocalizedString?(Strings.ErrorMailboxServerNotUnique(mailboxServerIdParameter.ToString())));
                if (base.HasErrors || this.m_server == null)
                {
                    base.WriteError(new CouldNotFindServerObject(mailboxServerIdParameter.ToString()), ErrorCategory.InvalidOperation, mailboxServerIdParameter);
                    return;
                }
                if (!this.m_server.IsE14OrLater)
                {
                    base.WriteError(new InvalidOperationException(Strings.ErrorServerNotE14OrLater(mailboxServerIdParameter.ToString())), ErrorCategory.InvalidOperation, mailboxServerIdParameter);
                }
                if (!this.m_server.IsMailboxServer)
                {
                    base.WriteError(this.m_server.GetServerRoleError(ServerRole.Mailbox), ErrorCategory.InvalidOperation, mailboxServerIdParameter);
                    return;
                }
                string arg  = (this.Identity == null) ? "*" : this.Identity.DatabaseName;
                string text = string.Format("{0}{1}{2}", arg, '\\', this.m_server.Name);
                if (this.Identity != null && !string.IsNullOrEmpty(this.Identity.ServerName) && this.Identity.ServerName != "*")
                {
                    this.WriteWarning(Strings.GetDbcsOverridingServer(this.Identity.ServerName, this.m_server.Name, text));
                }
                this.Identity = DatabaseCopyIdParameter.Parse(text);
            }
            this.rootId = new DatabasesContainer().Id;
            QueryFilter queryFilter = new OrFilter(new QueryFilter[]
            {
                new NotFilter(new ExistsFilter(DatabaseCopySchema.ParentObjectClass)),
                new TextFilter(DatabaseCopySchema.ParentObjectClass, MailboxDatabase.MostDerivedClass, MatchOptions.FullString, MatchFlags.IgnoreCase)
            });

            if (Datacenter.IsMicrosoftHostedOnly(true))
            {
                queryFilter = QueryFilter.OrTogether(new QueryFilter[]
                {
                    queryFilter,
                    new TextFilter(DatabaseCopySchema.ParentObjectClass, PublicFolderDatabase.MostDerivedClass, MatchOptions.FullString, MatchFlags.IgnoreCase)
                });
            }
            this.Identity.SetAdditionalQueryFilter(queryFilter);
            this.Identity.AllowInvalid = true;
        }
예제 #10
0
 public static void SetIfFederatedDisable(DataRow row, DataTable dataTable, DataObjectStore store)
 {
     if (!Datacenter.IsMultiTenancyEnabled() && store.GetDataObject("FederationTrust") == null)
     {
         dataTable.Rows[0]["FederationDisabled"] = true;
     }
 }
        private static Asset GetValidAsset()
        {
            var datacenter = new Datacenter {
                Id = Guid.NewGuid()
            };
            var rack = new Rack {
                Column = 1, Row = "A", Datacenter = datacenter
            };
            var model = new Model()
            {
                Height = 4
            };
            var asset = new Asset()
            {
                RackPosition = 5, Hostname = "server9", Rack = rack, Model = model
            };
            var otherNoConflict = new Asset()
            {
                RackPosition = 9, Hostname = "server8", Rack = rack, Model = model
            };

            rack.Assets = new List <Asset> {
                asset, otherNoConflict
            };
            model.Assets = new List <Asset> {
                asset, otherNoConflict
            };

            return(asset);
        }
        private static Asset GetAssetWithConflict()
        {
            var datacenter = new Datacenter {
                Id = Guid.NewGuid()
            };
            var rack = new Rack {
                Column = 1, Row = "A", Datacenter = datacenter
            };
            var model = new Model {
                Height = 4
            };
            var asset = new Asset()
            {
                RackPosition = 5, Rack = rack, Model = model
            };
            var conflict = new Asset()
            {
                RackPosition = 3, Rack = rack, Model = model
            };

            rack.Assets = new List <Asset> {
                asset, conflict
            };
            model.Assets = new List <Asset> {
                asset, conflict
            };

            return(asset);
        }
        private static Asset GetAssetThatDoesNotFitInRack()
        {
            var datacenter = new Datacenter {
                Id = Guid.NewGuid()
            };
            var rack = new Rack {
                Column = 1, Row = "A", Datacenter = datacenter
            };
            var model = new Model {
                Height = 4
            };
            var asset = new Asset()
            {
                RackPosition = 40, Rack = rack, Model = model
            };

            rack.Assets = new List <Asset> {
                asset
            };
            model.Assets = new List <Asset> {
                asset
            };

            return(asset);
        }
 private RoleGroupRoleMapping[] GetRoleGroupAssignmentsDefinition()
 {
     if (this.Organization == null)
     {
         if (Datacenter.IsMicrosoftHostedOnly(false))
         {
             return(Datacenter_RoleGroupDefinition.Definition);
         }
         if (Datacenter.IsPartnerHostedOnly(false))
         {
             return(Hosting_RoleGroupDefinition.Definition);
         }
         if (Datacenter.IsDatacenterDedicated(false))
         {
             return(Dedicated_RoleGroupDefinition.Definition);
         }
         return(Enterprise_RoleGroupDefinition.Definition);
     }
     else
     {
         if (Datacenter.IsPartnerHostedOnly(false))
         {
             return(HostedTenant_RoleGroupDefinition.Definition);
         }
         return(Tenant_RoleGroupDefinition.Definition);
     }
 }
예제 #15
0
        public override CapabilityEvaluationResult Evaluate(ADRawEntry adObject)
        {
            if (adObject == null)
            {
                throw new ArgumentNullException("adObject");
            }
            ExTraceGlobals.AccessCheckTracer.TraceDebug <string, string>((long)this.GetHashCode(), "Entering UMFeatureRestrictedCapabilityIdentifierEvaluator.Evaluate('{0}') CapabilityToCheck '{1}'.", adObject.GetDistinguishedNameOrName(), base.Capability.ToString());
            if (!Datacenter.IsMultiTenancyEnabled())
            {
                ExTraceGlobals.AccessCheckTracer.TraceDebug <string, string, string>((long)this.GetHashCode(), "MasteredOnPremiseCapabilityIdentifierEvaluator.Evaluate('{0}') return '{1}'. CapabilityToCheck '{2}' - not datacenter mode.", adObject.GetDistinguishedNameOrName(), CapabilityEvaluationResult.NotApplicable.ToString(), base.Capability.ToString());
                return(CapabilityEvaluationResult.NotApplicable);
            }
            CountryInfo countryInfo = (CountryInfo)adObject[ADRecipientSchema.UsageLocation];

            if (null == countryInfo)
            {
                ExTraceGlobals.AccessCheckTracer.TraceDebug <string, string, string>((long)this.GetHashCode(), "UMFeatureRestrictedCapabilityIdentifierEvaluator.Evaluate('{0}') return '{1}'.  CapabilityToCheck '{2}' - UsageLocation is '<NULL>'.", adObject.GetDistinguishedNameOrName(), CapabilityEvaluationResult.NotApplicable.ToString(), base.Capability.ToString());
                return(CapabilityEvaluationResult.NotApplicable);
            }
            CountryList countryList = CountryListIdCache.Singleton.Get(UMFeatureRestrictedCapabilityIdentifierEvaluator.UMCountryListKey);

            if (countryList == null)
            {
                ExTraceGlobals.AccessCheckTracer.TraceWarning <string, string, string>((long)this.GetHashCode(), "UMFeatureRestrictedCapabilityIdentifierEvaluator.Evaluate('{0}') return '{1}'.  CapabilityToCheck '{2}' - Cache lookup returned '<NULL>'.", adObject.GetDistinguishedNameOrName(), CapabilityEvaluationResult.Yes.ToString(), base.Capability.ToString());
                return(CapabilityEvaluationResult.Yes);
            }
            if (countryList.Countries.Contains(countryInfo))
            {
                ExTraceGlobals.AccessCheckTracer.TraceDebug <string, string, string>((long)this.GetHashCode(), "UMFeatureRestrictedCapabilityIdentifierEvaluator.Evaluate('{0}') return '{1}'.  CapabilityToCheck '{2}'.", adObject.GetDistinguishedNameOrName(), CapabilityEvaluationResult.No.ToString(), base.Capability.ToString());
                return(CapabilityEvaluationResult.No);
            }
            ExTraceGlobals.AccessCheckTracer.TraceDebug <string, string, string>((long)this.GetHashCode(), "UMFeatureRestrictedCapabilityIdentifierEvaluator.Evaluate('{0}') return '{1}'.  CapabilityToCheck '{2}'.", adObject.GetDistinguishedNameOrName(), CapabilityEvaluationResult.Yes.ToString(), base.Capability.ToString());
            return(CapabilityEvaluationResult.Yes);
        }
예제 #16
0
        /// <summary>
        /// Returns the identifier of the datacenter.
        ///
        /// Note: The method assumes that there is only one datacenter with the
        /// specified name
        /// </summary>
        /// <param name="stubFactory">Stub factory for api endpoint</param>
        /// <param name="sessionStubConfig">stub configuration for the current
        ///  session
        /// </param>
        /// <param name="datacenterName">name of the datacenter</param>
        /// <returns>identifier of a datacenter</returns>
        public static String GetDatacenter(
            StubFactory stubFactory, StubConfiguration sessionStubConfig,
            string datacenterName)
        {
            Datacenter datacenterService =
                stubFactory.CreateStub <Datacenter>(sessionStubConfig);
            HashSet <String> datacenterNames = new HashSet <String>
            {
                datacenterName
            };

            DatacenterTypes.FilterSpec dcFilterSpec =
                new DatacenterTypes.FilterSpec();
            dcFilterSpec.SetNames(datacenterNames);
            List <DatacenterTypes.Summary> dcSummaries =
                datacenterService.List(dcFilterSpec);

            if (dcSummaries.Count > 1)
            {
                throw new Exception(String.Format("More than one datacenter" +
                                                  " with the specified name {0} exist", datacenterName));
            }

            if (dcSummaries.Count <= 0)
            {
                throw new Exception(String.Format("Datacenter with name {0}" +
                                                  " not found !", datacenterName));
            }

            return(dcSummaries[0].GetDatacenter());
        }
        private void ResolveTestAccount()
        {
            UserWithCredential testAccount;

            if (this.Identity != null)
            {
                testAccount            = default(UserWithCredential);
                testAccount.User       = this.GetUniqueADObject <ADUser>(this.Identity, this.RecipientSession, true);
                testAccount.Credential = this.MailboxCredential.GetNetworkCredential();
            }
            else
            {
                testAccount = this.GetMonitoringAccount();
            }
            if (SmtpAddress.IsValidSmtpAddress(testAccount.Credential.UserName))
            {
                testAccount.Credential.Domain = null;
            }
            else if (Datacenter.IsMultiTenancyEnabled())
            {
                testAccount.Credential.UserName = string.Format("{0}@{1}", testAccount.Credential.UserName, testAccount.Credential.Domain);
                testAccount.Credential.Domain   = null;
            }
            this.TestAccount = testAccount;
        }
        protected override void InternalProcessMetabase()
        {
            TaskLogger.LogEnter();
            base.InternalProcessMetabase();
            if (base.Role == VirtualDirectoryRole.ClientAccess && Datacenter.IsMicrosoftHostedOnly(false) && ((Environment.OSVersion.Version.Major >= 6 && Environment.OSVersion.Version.Minor >= 1) || Environment.OSVersion.Version.Major >= 7))
            {
                if (DirectoryEntry.Exists(this.DataObject.MetabasePath))
                {
                    TaskLogger.Trace("MultiTenancy mode: installing AuthModuleFilter isapi filter", new object[0]);
                    try
                    {
                        NewAutodiscoverVirtualDirectory.InstallAuthModuleIsapiFilter(this.DataObject);
                        goto IL_DE;
                    }
                    catch (Exception ex)
                    {
                        TaskLogger.Trace("Exception occurred in InstallIsapiFilter(): {0}", new object[]
                        {
                            ex.Message
                        });
                        this.WriteWarning(Strings.AuthModuleFilterMetabaseIsapiInstallFailure);
                        throw;
                    }
                }
                base.WriteError(new InvalidOperationException(Strings.ErrorMetabasePathNotFound(this.DataObject.MetabasePath)), ErrorCategory.InvalidOperation, this.DataObject.Identity);
            }
IL_DE:
            TaskLogger.LogExit();
        }
        private UserWithCredential GetMonitoringAccount()
        {
            UserWithCredential result     = default(UserWithCredential);
            string             datacenter = Datacenter.IsMicrosoftHostedOnly(true) ? ".Datacenter" : string.Empty;
            ADSite             localSite  = this.ConfigSession.GetLocalSite();

            try
            {
                result = CommonTestTasks.GetDefaultTestAccount(new CommonTestTasks.ClientAccessContext
                {
                    Instance             = this,
                    MonitoringContext    = true,
                    ConfigurationSession = this.ConfigSession,
                    RecipientSession     = this.RecipientSession,
                    Site          = localSite,
                    WindowsDomain = localSite.Id.DomainId.ToCanonicalName()
                });
            }
            catch (Exception ex)
            {
                base.WriteError(new TestWebServicesTaskException(Strings.ErrorTestMailboxNotFound(ExchangeSetupContext.ScriptPath, datacenter, ex.ToString())), ErrorCategory.InvalidData, null);
            }
            if (string.IsNullOrEmpty(result.Credential.Password))
            {
                base.WriteError(new TestWebServicesTaskException(Strings.ErrorTestMailboxPasswordNotFound(result.User.Identity.ToString(), ExchangeSetupContext.ScriptPath, datacenter)), ErrorCategory.InvalidData, null);
            }
            return(result);
        }
예제 #20
0
 private static void InitializeOlderLdapFilter()
 {
     CannedAddressListsFilterHelper.ldapFiltersOfOlderAddressList = new Dictionary <string, string[]>();
     CannedAddressListsFilterHelper.ldapFiltersOfOlderAddressList.Add(CannedAddressListsFilterHelper.DefaultAllContacts, new string[]
     {
         "(& (mailnickname=*) (| (&(objectCategory=person)(objectClass=contact)) ))"
     });
     CannedAddressListsFilterHelper.ldapFiltersOfOlderAddressList.Add(CannedAddressListsFilterHelper.DefaultAllDistributionLists, new string[]
     {
         "(& (mailnickname=*) (| (objectCategory=group) ))"
     });
     CannedAddressListsFilterHelper.ldapFiltersOfOlderAddressList.Add(CannedAddressListsFilterHelper.DefaultAllRooms, new string[]
     {
         "(& (mailnickname=*) (| (msExchResourceMetaData=ResourceType:Room) ))",
         "(&(mailnickname=*)(msExchResourceMetaData=ResourceType:Room))"
     });
     CannedAddressListsFilterHelper.ldapFiltersOfOlderAddressList.Add(CannedAddressListsFilterHelper.DefaultAllUsers, new string[]
     {
         "(&(mailnickname=*)(|(&(objectCategory=person)(objectClass=user)(!(homeMDB=*))(!(msExchHomeServerName=*)))(&(objectCategory=person)(objectClass=user)(|(homeMDB=*)(msExchHomeServerName=*)))))"
     });
     CannedAddressListsFilterHelper.ldapFiltersOfOlderAddressList.Add(CannedAddressListsFilterHelper.DefaultAllModernGroups, new string[]
     {
         "(&(!(!objectClass=user)))(objectCategory=person)(mailNickname=*)(msExchHomeServerName=*)(msExchRecipientTypeDetails=1099511627776))"
     });
     if (!Datacenter.IsMultiTenancyEnabled())
     {
         CannedAddressListsFilterHelper.ldapFiltersOfOlderAddressList.Add(CannedAddressListsFilterHelper.DefaultPublicFolders, new string[]
         {
             "(& (mailnickname=*) (| (objectCategory=publicFolder) ))"
         });
     }
 }
예제 #21
0
 private void Awake()
 {
     if (!instance)
     {
         instance = this;
     }
 }
 protected TenantStoreDataProvider(OrganizationId organizationId) : base(new LazilyInitialized <IExchangePrincipal>(() => TenantStoreDataProvider.GetTenantMailbox(organizationId ?? OrganizationId.ForestWideOrgId)), SpecialLogonType.SystemService, OpenAsAdminOrSystemServiceBudgetTypeType.RunAsBackgroundLoad)
 {
     if (organizationId == null && Datacenter.IsMultiTenancyEnabled())
     {
         throw new ArgumentNullException("organizationId", "organizationId can't be null in hosting environment.");
     }
 }
        private RoleGroupCollection GetInvalidRoleGroups()
        {
            bool flag = Datacenter.IsPartnerHostedOnly(false);
            RoleGroupCollection roleGroupCollection = new RoleGroupCollection();
            List <string>       enabledRoleGroupRoleAssignmentFeatures = this.ServicePlanSettings.Organization.GetEnabledRoleGroupRoleAssignmentFeatures();

            using (List <RoleGroupDefinition> .Enumerator enumerator = RoleGroupDefinitions.RoleGroups.GetEnumerator())
            {
                while (enumerator.MoveNext())
                {
                    RoleGroupDefinition  roleGroupDefinition = enumerator.Current;
                    RoleGroupRoleMapping roleGroupRoleMapping;
                    if (flag)
                    {
                        roleGroupRoleMapping = HostedTenant_RoleGroupDefinition.Definition.FirstOrDefault((RoleGroupRoleMapping x) => x.RoleGroup.Equals(roleGroupDefinition.Name, StringComparison.OrdinalIgnoreCase));
                    }
                    else
                    {
                        roleGroupRoleMapping = Tenant_RoleGroupDefinition.Definition.FirstOrDefault((RoleGroupRoleMapping x) => x.RoleGroup.Equals(roleGroupDefinition.Name, StringComparison.OrdinalIgnoreCase));
                    }
                    if (roleGroupRoleMapping != null && roleGroupRoleMapping.GetRolesAssignments(enabledRoleGroupRoleAssignmentFeatures).Count == 0)
                    {
                        roleGroupCollection.Add(new RoleGroupDefinition(roleGroupDefinition));
                    }
                }
            }
            return(roleGroupCollection);
        }
예제 #24
0
 private void UpdateIntegratedMetabase(ADOwaVirtualDirectory dataObject)
 {
     if (Datacenter.IsMultiTenancyEnabled())
     {
         base.WriteError(new TaskException(Strings.IntegratedVDirNotSupported), ErrorCategory.InvalidOperation, null);
         return;
     }
     try
     {
         using (DirectoryEntry directoryEntry = IisUtility.FindWebDirObject(dataObject.MetabasePath, "Integrated"))
         {
             bool flag = false;
             if (dataObject.IntegratedFeaturesEnabled != null && dataObject.IntegratedFeaturesEnabled != null)
             {
                 flag = dataObject.IntegratedFeaturesEnabled.Value;
             }
             if (flag)
             {
                 IisUtility.SetAuthenticationMethod(directoryEntry, MetabasePropertyTypes.AuthFlags.Ntlm, true);
             }
             else
             {
                 IisUtility.SetAuthenticationMethod(directoryEntry, AuthenticationMethodFlags.None, true);
                 this.WriteWarning(Strings.IntegratedVDirDisabledWarning);
             }
             directoryEntry.CommitChanges();
         }
     }
     catch (WebObjectNotFoundException)
     {
         base.WriteError(new TaskException(Strings.IntegratedVDirNotFound), ErrorCategory.InvalidOperation, null);
     }
 }
        public ExchangeConfigurationUnit GetExchangeConfigurationUnitByNameOrAcceptedDomain(string organizationName)
        {
            if (Datacenter.IsMultiTenancyEnabled())
            {
                ExchangeConfigurationUnit exchangeConfigurationUnitByName = this.GetExchangeConfigurationUnitByName(organizationName);
                if (exchangeConfigurationUnitByName != null)
                {
                    return(exchangeConfigurationUnitByName);
                }
            }
            QueryFilter filter = new AndFilter(new QueryFilter[]
            {
                new ComparisonFilter(ComparisonOperator.Equal, AcceptedDomainSchema.DomainName, organizationName),
                new ComparisonFilter(ComparisonOperator.NotEqual, AcceptedDomainSchema.AcceptedDomainType, AcceptedDomainType.ExternalRelay)
            });

            AcceptedDomain[] array = base.Find <AcceptedDomain>(null, QueryScope.SubTree, filter, null, 1);
            if (array == null || array.Length == 0)
            {
                return(null);
            }
            ADObjectId entryId = array[0].Id.AncestorDN(3);

            return(base.Read <ExchangeConfigurationUnit>(entryId));
        }
예제 #26
0
        public CVRDownloadTask(Datacenter dc)
        {
            Target = dc.LocalDirectory;

            _dc        = dc;
            _dc.Ended += _dc_Ended;
        }
예제 #27
0
        private void Configure()
        {
            configuration = new Configuration
            {
                Username = "******",
                Password = "******",
            };

            dcApi     = new DataCenterApi(configuration);
            serverApi = new ServerApi(configuration);
            nicApi    = new NetworkInterfacesApi(configuration);
            lbApi     = new LoadBalancerApi(configuration);

            //Create a datacenter.
            if (datacenter == null)
            {
                datacenter = new Datacenter
                {
                    Properties = new DatacenterProperties
                    {
                        Name        = ".Net V2 - Test " + DateTime.Now.ToShortTimeString(),
                        Description = "Unit test for .Net SDK PB REST V2",
                        Location    = "us/lasdev"
                    }
                };

                datacenter = dcApi.Create(datacenter);
            }

            if (server == null)
            {
                server = new Server
                {
                    Properties = new ServerProperties
                    {
                        Name  = ".Net V2 - Test " + DateTime.Now.ToShortTimeString(),
                        Cores = 1,
                        Ram   = 256
                    }
                };

                server = serverApi.Create(datacenter.Id, server);
                DoWait(server.Request);
            }

            if (lb == null)
            {
                lb = new Loadbalancer
                {
                    Properties = new LoadbalancerProperties {
                        Name = ".Net V2 - Test " + DateTime.Now.ToShortTimeString()
                    }
                };

                lb = lbApi.Create(datacenter.Id, lb);

                DoWait(lb.Request);
            }
        }
예제 #28
0
 protected override string GetRunspaceServerSettingsToken()
 {
     if (Datacenter.IsMultiTenancyEnabled() && RbacPrincipal.Current.IsAdmin && !OrganizationId.ForestWideOrgId.Equals(RbacPrincipal.Current.RbacConfiguration.OrganizationId))
     {
         return(RunspaceServerSettings.GetTokenForOrganization(RbacPrincipal.Current.RbacConfiguration.OrganizationId));
     }
     return(base.GetRunspaceServerSettingsToken());
 }
 protected override IConfigDataProvider CreateSession()
 {
     if (Datacenter.IsMultiTenancyEnabled())
     {
         return(DirectorySessionFactory.Default.CreateTopologyConfigurationSession(base.DomainController, false, ConsistencyMode.PartiallyConsistent, ADSessionSettings.FromRootOrgScopeSet(), 47, "CreateSession", "f:\\15.00.1497\\sources\\dev\\Management\\src\\Management\\Deployment\\InstallRootOrganizationContainer.cs"));
     }
     return(base.CreateSession());
 }
 protected override void InternalValidate()
 {
     base.InternalValidate();
     if (Datacenter.IsMultiTenancyEnabled() && this.DataObject.OrganizationId == OrganizationId.ForestWideOrgId && this.DataObject.AccessLevel != DeviceAccessLevel.Block)
     {
         base.WriteError(new ArgumentException(Strings.ErrorOnlyForestWideBlockIsAllowed), ErrorCategory.InvalidArgument, null);
     }
 }
        public void DataCenterCreate()
        {
            Configure();
            datacenter = new Datacenter
            {
                Properties = new DatacenterProperties
                {
                    Name = ".Net V2 - Test " + DateTime.Now.ToShortTimeString(),
                    Description = "Unit test for .Net SDK PB REST V2" ,
                    Location = "us/lasdev"
                }
            };

            datacenter = dcApi.Create(datacenter);
            Assert.IsNotNull(datacenter);
        }
        private void Configure()
        {
            configuration = new Configuration
            {
                Username = "******",
                Password = "******",
            };

            dcApi = new DataCenterApi(configuration);
            volumeApi = new VolumeApi(configuration);
            snapshotApi = new SnapshotApi(configuration);
            //Create a datacenter.
            if (datacenter == null)
            {
                datacenter = new Datacenter
                {
                    Properties = new DatacenterProperties
                    {
                        Name = ".Net V2 - Test " + DateTime.Now.ToShortTimeString(),
                        Description = "Unit test for .Net SDK PB REST V2",
                        Location = "us/lasdev"
                    }
                };

                datacenter = dcApi.Create(datacenter);
            }

            if (volume == null)
            {
                volume = new Volume
                {
                    Properties = new VolumeProperties
                    {
                        Size = 1,
                        LicenceType = "LINUX",
                        Type = "HDD",
                        Name = ".Net V2 - Test " + DateTime.Now.ToShortTimeString(),
                    }
                };
                volume = volumeApi.Create(datacenter.Id, volume);
                DoWait(volume.Request);
            }
        }
        private void Configure()
        {
            Configuration = new Configuration
            {
                Username = "******",
                Password = "******",

            };

            dcApi = new DataCenterApi(configuration);
            serverApi = new ServerApi(configuration);
            nicApi = new NetworkInterfacesApi(configuration);
            lbApi = new LoadBalancerApi(configuration);
            fwApi = new FirewallRuleApi(configuration);

            //Create a datacenter.
            if (datacenter == null)
            {
                datacenter = new Datacenter
                {
                    Properties = new DatacenterProperties
                    {
                        Name = ".Net V2 - Test " + DateTime.Now.ToShortTimeString(),
                        Description = "Unit test for .Net SDK PB REST V2",
                        Location = "us/lasdev"
                    }
                };

                datacenter = dcApi.Create(datacenter);
            }

            if (server == null)
            {
                server = new Server
                {
                    Properties = new ServerProperties
                    {
                        Name = ".Net V2 - Test " + DateTime.Now.ToShortTimeString(),
                        Cores = 1,
                        Ram = 256
                    }
                };

                server = serverApi.Create(datacenter.Id, server);
                DoWait(server.Request);
            }

            if (nic == null)
            {
                nic = new Nic { Properties = new NicProperties { Lan = 1 } };

                nic = nicApi.Create(datacenter.Id, server.Id, nic);

                DoWait(nic.Request);
            }

            bool isBusy = true;
            while (isBusy == true)
            {
                var temp = dcApi.FindById(datacenter.Id);
                if (temp.Metadata.State != "BUSY") isBusy = false;
                Thread.Sleep(5000);
            }
        }
 /// <summary>
 /// Create a Data Center Virtual data centers are the foundation of the ProfitBricks platform. VDCs act as logical containers for all other objects you will be creating, e.g. servers. You can provision as many data centers as you want. Datacenters have their own private network and are logically segmented from each other to create isolation. You can use this POST method to create a simple datacenter or to create a datacenter with multiple objects under it such as servers and storage volumes.
 /// </summary>
 /// <param name="datacenter">Datacenter to be created</param> 
 /// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param> 
 /// <param name="depth">Controls the details depth of response objects. \nEg. GET /datacenters/[ID]\n	- depth=0: only direct properties are included. Children (servers etc.) are not included\n	- depth=1: direct properties and children references are included\n	- depth=2: direct properties and children properties are included\n	- depth=3: direct properties and children properties and children&#39;s children are included\n	- depth=... and so on</param> 
 /// <returns>Datacenter</returns>
 public Datacenter Create(Datacenter datacenter, bool? parameter = null, int? depth = null)
 {
     ApiResponse<Datacenter> response = CreateWithHttpInfo(datacenter, parameter, depth);
     return response.Data;
 }
        /// <summary>
        /// Create a Data Center Virtual data centers are the foundation of the ProfitBricks platform. VDCs act as logical containers for all other objects you will be creating, e.g. servers. You can provision as many data centers as you want. Datacenters have their own private network and are logically segmented from each other to create isolation. You can use this POST method to create a simple datacenter or to create a datacenter with multiple objects under it such as servers and storage volumes.
        /// </summary>
        /// <param name="datacenter">Datacenter to be created</param>
        /// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param>
        /// <param name="depth">Controls the details depth of response objects. \nEg. GET /datacenters/[ID]\n	- depth=0: only direct properties are included. Children (servers etc.) are not included\n	- depth=1: direct properties and children references are included\n	- depth=2: direct properties and children properties are included\n	- depth=3: direct properties and children properties and children&#39;s children are included\n	- depth=... and so on</param>
        /// <returns>Task of Datacenter</returns>
        public async System.Threading.Tasks.Task<Datacenter> CreateAsync(Datacenter datacenter, bool? parameter = null, int? depth = null)
        {
            ApiResponse<Datacenter> response = await CreateAsyncWithHttpInfo(datacenter, parameter, depth);
            return response.Data;

        }
 /// <summary>
 /// Modify a Data Center You can use update datacenter to re-name the datacenter or update its description
 /// </summary>
 /// <param name="datacenterId">The unique ID of the data center</param> 
 /// <param name="datacenter">Modified Data Center</param> 
 /// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param> 
 /// <param name="depth">Controls the details depth of response objects. \nEg. GET /datacenters/[ID]\n	- depth=0: only direct properties are included. Children (servers etc.) are not included\n	- depth=1: direct properties and children references are included\n	- depth=2: direct properties and children properties are included\n	- depth=3: direct properties and children properties and children&#39;s children are included\n	- depth=... and so on</param> 
 /// <returns>Datacenter</returns>
 public Datacenter Update(string datacenterId, Datacenter datacenter, bool? parameter = null, int? depth = null)
 {
     ApiResponse<Datacenter> response = UpdateWithHttpInfo(datacenterId, datacenter, parameter, depth);
     return response.Data;
 }
        /// <summary>
        /// Modify a Data Center You can use update datacenter to re-name the datacenter or update its description
        /// </summary>
        /// <param name="datacenterId">The unique ID of the data center</param> 
        /// <param name="datacenter">Modified Data Center</param> 
        /// <param name="parameter">Controls whether response is pretty-printed (with indentation and new lines)</param> 
        /// <param name="depth">Controls the details depth of response objects. \nEg. GET /datacenters/[ID]\n	- depth=0: only direct properties are included. Children (servers etc.) are not included\n	- depth=1: direct properties and children references are included\n	- depth=2: direct properties and children properties are included\n	- depth=3: direct properties and children properties and children&#39;s children are included\n	- depth=... and so on</param> 
        /// <returns>ApiResponse of Datacenter</returns>
        public ApiResponse<Datacenter> UpdateWithHttpInfo(string datacenterId, Datacenter datacenter, bool? parameter = null, int? depth = null)
        {

            // verify the required parameter 'datacenterId' is set
            if (datacenterId == null)
                throw new ApiException(400, "Missing required parameter 'datacenterId' when calling DataCenterApi->Update");

            // verify the required parameter 'datacenter' is set
            if (datacenter == null)
                throw new ApiException(400, "Missing required parameter 'datacenter' when calling DataCenterApi->Update");


            var path_ = "/datacenters/{datacenterId}";

            var pathParams = new Dictionary<String, String>();
            var queryParams = new Dictionary<String, String>();
            var headerParams = new Dictionary<String, String>(Configuration.DefaultHeader);
            var formParams = new Dictionary<String, String>();
            var fileParams = new Dictionary<String, FileParameter>();
            Object postBody = null;

            // to determine the Content-Type header
            String[] httpContentTypes = new String[] {
                "application/json", "application/vnd.profitbricks.resource+json"
            };
            String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes);

            // to determine the Accept header
            String[] httpHeaderAccepts = new String[] {
                "application/vnd.profitbricks.resource+json"
            };
            String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts);
            if (httpHeaderAccept != null)
                headerParams.Add("Accept", httpHeaderAccept);

            // set "format" to json by default
            // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
            pathParams.Add("format", "json");
            if (datacenterId != null) pathParams.Add("datacenterId", Configuration.ApiClient.ParameterToString(datacenterId)); // path parameter

            if (parameter != null) queryParams.Add("parameter", Configuration.ApiClient.ParameterToString(parameter)); // query parameter
            if (depth != null) queryParams.Add("depth", Configuration.ApiClient.ParameterToString(depth)); // query parameter



            if (datacenter.GetType() != typeof(byte[]))
            {
                postBody = Configuration.ApiClient.Serialize(datacenter); // http body (model) parameter
            }
            else
            {
                postBody = datacenter; // byte array
            }

            // authentication (basicAuth) required

            // http basic authentication required
            if (!String.IsNullOrEmpty(Configuration.Username) || !String.IsNullOrEmpty(Configuration.Password))
            {
                headerParams["Authorization"] = "Basic " + ApiClient.Base64Encode(Configuration.Username + ":" + Configuration.Password);
            }


            // make the HTTP request
            IRestResponse response = (IRestResponse)Configuration.ApiClient.CallApi(path_,
                Method.PUT, queryParams, postBody, headerParams, formParams, fileParams,
                pathParams, httpContentType);

            int statusCode = (int)response.StatusCode;

            if (statusCode >= 400)
                throw new ApiException(statusCode, "Error calling Update: " + response.Content, response.Content);
            else if (statusCode == 0)
                throw new ApiException(statusCode, "Error calling Update: " + response.ErrorMessage, response.ErrorMessage);

            return new ApiResponse<Datacenter>(statusCode,
                response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
                (Datacenter)Configuration.ApiClient.Deserialize(response, typeof(Datacenter)));

        }
        private void Configure()
        {
            configuration = new Configuration
            {
                Username = "******",
                Password = "******",
            };

            dcApi = new DataCenterApi(configuration);
            serverApi = new ServerApi(configuration);
            volumeApi = new VolumeApi(configuration);
            attachedVolumesApi = new AttachedVolumesApi(configuration);

            //Create a datacenter.
            if (datacenter == null)
            {
                datacenter = new Datacenter
                {
                    Properties = new DatacenterProperties
                    {
                        Name = ".Net V2 - Test " + DateTime.Now.ToShortTimeString(),
                        Description = "Unit test for .Net SDK PB REST V2",
                        Location = "us/lasdev"
                    }
                };

                datacenter = dcApi.Create(datacenter);
            }
            if (server == null)
            {
                server = new Server
                {
                    Properties = new ServerProperties
                    {
                        Name = ".Net V2 - Test " + DateTime.Now.ToShortTimeString(),
                        Cores = 1,
                        Ram = 1024
                    }
                };

                server = serverApi.Create(datacenter.Id, server);

                DoWait(server.Request);
            }
        }
예제 #39
0
        private void Configure()
        {
            configuration = new Configuration
            {
                Username = "******",
                Password = "******",

            };

            dcApi = new DataCenterApi(configuration);

            lanApi = new LanApi(configuration);

            //Create a datacenter.
            if (datacenter == null)
            {
                datacenter = new Datacenter
                {
                    Properties = new DatacenterProperties
                    {
                        Name = ".Net V2 - Test " + DateTime.Now.ToShortTimeString(),
                        Description = "Unit test for .Net SDK PB REST V2",
                        Location = "us/lasdev"
                    }
                };

                datacenter = dcApi.Create(datacenter);
            }
        }
예제 #40
0
        protected List<Network> GetPortGroups(VimClient vimClient, Datacenter selectedDC = null, string pgName = null)
        {
            //
            // Get a list of Portgroups
            //
            List<Network> lstPortGroups = new List<Network>();
            NameValueCollection pgFilter = new NameValueCollection();
            ManagedObjectReference DcMoRef = new ManagedObjectReference();

            if (pgName != null)
            {
                //
                // Name of a specific portgroup
                //
                pgFilter.Add("name", pgName);
            }
            else
            {
                pgFilter = null;
            }

            if (selectedDC != null)
            {
                //
                // A specific datacenter
                //
                DcMoRef = selectedDC.MoRef;
            }
            else
            {
                DcMoRef = null;
            }
            try
            {
                //
                // If DcMoRef and pgFilter are null return all portgroups, otherwise return the selected portgroup
                //
                List<EntityViewBase> appPortGroups = vimClient.FindEntityViews(typeof(Network), DcMoRef, pgFilter, null);
                if (appPortGroups != null)
                {
                    foreach (EntityViewBase appPortGroup in appPortGroups)
                    {
                        Network thisPortGroup = (Network)appPortGroup;
                        lstPortGroups.Add(thisPortGroup);
                    }
                    return lstPortGroups;
                }
                else
                {
                    return null;
                }
            }
            catch (VimException ex)
            {
                //
                // VMware Exception occurred
                //
                txtErrors.Text = "A server fault of type " + ex.MethodFault.GetType().Name + " with message '" + ex.Message + "' occured while performing requested operation.";
                Error_Panel.Visible = true;
                return null;
            }
        }
예제 #41
0
        static void Main(string[] args)
        {
            var configuration = new Configuration
            {
                Username = "******",
                Password = "******",

            };
            var dcApi = new DataCenterApi(configuration);
            var serverApi = new ServerApi(configuration);
            var volumeApi = new VolumeApi(configuration);
            var attachedVolumesApi = new AttachedVolumesApi(configuration);
            var nicApi = new NetworkInterfacesApi(configuration);

            // CreateDataCenterRequest.
            // The only required field is DataCenterName.
            // If location parameter is left empty data center will be created in the default region of the customer
            var datacenter = new Datacenter
            {
                Properties = new DatacenterProperties
                {
                    Name = ".Net V2 - Test " + DateTime.Now.ToShortTimeString(),
                    Description = "Unit test for .Net SDK PB REST V2",
                    Location = "us/lasdev"
                }
            };

            // Response will contain Id of a newly created data center.
            datacenter = dcApi.Create(datacenter);

            // CreateServer.
            // DataCenterId: Defines the data center wherein the server is to be created.
            // AvailabilityZone: Selects the zone in which the server is going to be created (AUTO, ZONE_1, ZONE_2).
            // Cores: Number of cores to be assigned to the specified server. Required field.
            // InternetAccess: Set to TRUE to connect the server to the Internet via the specified LAN ID.
            // OsType: Sets the OS type of the server.
            // Ram: Number of RAM memory (in MiB) to be assigned to the server.
            var server = new Server
            {
                Properties = new ServerProperties
                {
                    Name = ".Net V2 - Test " + DateTime.Now.ToShortTimeString(),
                    Cores = 1,
                    Ram = 256
                }
            };

            // response will contain Id of a newly created server.
            server = serverApi.Create(datacenter.Id, server);

            // UpdateServer
            // ServerId: Id of the server to be updated.
            // ServerName: Renames target virtual server
            // Cores: Updates the amount of cores of the target virtual server
            // Ram: Updates the RAM memory (in MiB) of the target virtual server. The minimum RAM size is 256 MiB
            server = serverApi.PartialUpdate(datacenter.Id, server.Id, new ServerProperties { Name = server.Properties.Name + " -Updated" });

            // CreateVolume
            // DataCenterId: Defines the data center wherein the storage is to be created. If left empty, the storage will be created in a new data center
            // Size: Storage size (in GiB). Required Field.
            // Type: SSD or HDD disk type, Required Field
            var volume = new Volume
            {
                Properties = new VolumeProperties
                {
                    Size = 4,
                    Image = "fbaae2b2-c899-11e5-aa10-52540005ab80",
                    Type = "HDD",
                    Name = ".Net V2 - Test " + DateTime.Now.ToShortTimeString(),
                    SshKeys = new System.Collections.Generic.List<string> { "hQGOEJeFL91EG3+l9TtRbWNjzhDVHeLuL3NWee6bekA=" }
                }
            };

            // Response will contain Id of a newly created volume.
            volume = volumeApi.Create(datacenter.Id, volume);

            // AttachVolume
            // ServerId: Identifier of the target virtual storage. Required field.
            // StorageId: Identifier of the virtual storage to be connected. Required field.
            // BusType: Bus type to which the storage will be connected
            attachedVolumesApi.AttachVolume(datacenter.Id, server.Id, new Volume { Id = volume.Id });

            attachedVolumesApi.DetachVolume(datacenter.Id, server.Id, volume.Id);

            // Fetches list of all Data Centers
            var dcs = dcApi.FindAll(depth: 5);

            // Fetches list of all Servers
            var servers = serverApi.FindAll(datacenter.Id, depth: 5);

            // Fetches list of all Volumes
            var volumes = volumeApi.FindAll(datacenter.Id, depth: 5);

            // CreateNicRequest
            // Identifier of the target virtual server. Required field.
            // Nic: Names the NIC
            // Toggles usage of ProfitBricks DHCP
            // Lan
            var nic = new Nic { Properties = new NicProperties { Lan = 1 , Dhcp = true, Name = "Nic name"} };

            nic = nicApi.Create(datacenter.Id, server.Id, nic);
        }
예제 #42
0
        protected List<VirtualMachine> GetVirtualMachines(VimClient vimClient, Datacenter selectedDC = null, string vmName = null)
        {
            //
            // Get a list of virtual machines
            //
            List<VirtualMachine> lstVirtualMachines = new List<VirtualMachine>();
            NameValueCollection vmFilter = new NameValueCollection();
            ManagedObjectReference DcMoRef = new ManagedObjectReference();

            if (vmName != null)
            {
                //
                // A specific virtual machine
                //
                vmFilter.Add("name", vmName);
            }
            else
            {
                vmFilter = null;
            }

            if (selectedDC != null)
            {
                //
                // A specific datacenter
                //
                DcMoRef = selectedDC.MoRef;
            }
            else
            {
                DcMoRef = null;
            }
            try
            {
                //
                // If DcMoRef and vmFilter are null return all Vm's, otherwise return specific vm's
                //
                List<EntityViewBase> appVirtualMachines = vimClient.FindEntityViews(typeof(VirtualMachine), DcMoRef, vmFilter, null);
                if (appVirtualMachines != null)
                {
                    foreach (EntityViewBase appVirtualMachine in appVirtualMachines)
                    {
                        VirtualMachine thisVirtualMachine = (VirtualMachine)appVirtualMachine;
                        lstVirtualMachines.Add(thisVirtualMachine);
                    }
                    return lstVirtualMachines;
                }
                else
                {
                    return null;
                }
            }
            catch (VimException ex)
            {
                //
                // VMware Exception occurred
                //
                txtErrors.Text = "A server fault of type " + ex.MethodFault.GetType().Name + " with message '" + ex.Message + "' occured while performing requested operation.";
                Error_Panel.Visible = true;
                return null;
            }
        }
예제 #43
0
        private void Configure()
        {
            configuration = new Configuration
            {
                Username = "******",
                Password = "******",

            };

            dcApi = new DataCenterApi(configuration);
            serverApi = new ServerApi(configuration);
            nicApi = new NetworkInterfacesApi(configuration);
            lbApi = new LoadBalancerApi(configuration);

            //Create a datacenter.
            if (datacenter == null)
            {
                datacenter = new Datacenter
                {
                    Properties = new DatacenterProperties
                    {
                        Name = ".Net V2 - Test " + DateTime.Now.ToShortTimeString(),
                        Description = "Unit test for .Net SDK PB REST V2",
                        Location = "us/lasdev"
                    }
                };

                datacenter = dcApi.Create(datacenter);
            }

            if(server == null)
            {
                server = new Server
                {
                    Properties = new ServerProperties
                    {
                        Name = ".Net V2 - Test " + DateTime.Now.ToShortTimeString(),
                        Cores = 1,
                        Ram = 256
                    }
                };

                server = serverApi.Create(datacenter.Id, server);
                DoWait(server.Request);
            }

            if (lb == null)
            {
                lb = new Loadbalancer
                {
                    Properties = new LoadbalancerProperties { Name = ".Net V2 - Test " + DateTime.Now.ToShortTimeString() }
                };

                lb = lbApi.Create(datacenter.Id, lb);

                DoWait(lb.Request);
            }
        }
예제 #44
0
        protected List<Datastore> GetDataStore(VimClient vimClient, Datacenter selectedDC = null, string dsName = null)
        {
            //
            // Get a list of datastores from a specific datacenter
            //
            List<Datastore> lstDatastores = new List<Datastore>();
            NameValueCollection dsFilter = new NameValueCollection();
            ManagedObjectReference DcMoRef = new ManagedObjectReference();

            if (dsName != null)
            {
                //
                // The name of a specific datastore
                //
                dsFilter.Add("name", dsName);
            }
            else
            {
                dsFilter = null;
            }

            if (selectedDC != null)
            {
                //
                // A specific datacenter to get datastores from
                //
                DcMoRef = selectedDC.MoRef;
            }
            else
            {
                DcMoRef = null;
            }
            try
            {
                //
                // if DcMoref and dsFilter are empty return all datastores
                //
                List<EntityViewBase> appDatastores = vimClient.FindEntityViews(typeof(Datastore), DcMoRef, dsFilter, null);
                if (appDatastores != null)
                {
                    foreach (EntityViewBase appDatastore in appDatastores)
                    {
                        Datastore thisDatastore = (Datastore)appDatastore;
                        lstDatastores.Add(thisDatastore);
                    }
                    return lstDatastores;
                }
                else
                {
                    return null;
                }
            }
            catch (VimException ex)
            {
                //
                // VMware Exception occurred
                //
                txtErrors.Text = "A server fault of type " + ex.MethodFault.GetType().Name + " with message '" + ex.Message + "' occured while performing requested operation.";
                Error_Panel.Visible = true;
                return null;
            }
        }