diff --git a/.asf.yaml b/.asf.yaml index be818fda4d3..092e06d9716 100644 --- a/.asf.yaml +++ b/.asf.yaml @@ -59,11 +59,12 @@ github: - abh1sar - rosi-shapeblue - sudo87 + - erikbocks protected_branches: ~ notifications: - commits: commits@cloudstack.apache.org - issues: commits@cloudstack.apache.org + commits: commits@cloudstack.apache.org + issues: commits@cloudstack.apache.org pullrequests: commits@cloudstack.apache.org - discussions: users@cloudstack.apache.org + discussions: users@cloudstack.apache.org diff --git a/.github/ISSUE_TEMPLATE/feature_request.yaml b/.github/ISSUE_TEMPLATE/feature_request.yml similarity index 100% rename from .github/ISSUE_TEMPLATE/feature_request.yaml rename to .github/ISSUE_TEMPLATE/feature_request.yml diff --git a/.github/linters/.markdown-lint.yml b/.github/linters/.markdown-lint.yml index 531c26ace44..6a8a26f4849 100644 --- a/.github/linters/.markdown-lint.yml +++ b/.github/linters/.markdown-lint.yml @@ -18,9 +18,6 @@ # MD001/heading-increment Heading levels should only increment by one level at a time MD001: false -# MD003/heading-style Heading style -MD003: false - # MD004/ul-style Unordered list style MD004: false diff --git a/.github/linters/.yamllint.yml b/.github/linters/.yamllint.yml new file mode 100644 index 00000000000..8a72aee0adb --- /dev/null +++ b/.github/linters/.yamllint.yml @@ -0,0 +1,31 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +--- +extends: relaxed + +rules: + line-length: + max: 400 # Very forgiving for GitHub Actions and infrastructure files + indentation: disable # Disable indentation checking for existing files + comments: disable # Disable comment formatting checks + brackets: disable # Disable bracket spacing checks + colons: + max-spaces-after: -1 # Allow any number of spaces after colon + max-spaces-before: 0 + document-start: disable # Many files don't have --- + truthy: + allowed-values: ['true', 'false', 'on', 'off', 'yes', 'no'] diff --git a/.github/linters/codespell.txt b/.github/linters/codespell.txt index 37b3e6de1cb..7c8e94021b0 100644 --- a/.github/linters/codespell.txt +++ b/.github/linters/codespell.txt @@ -4,6 +4,7 @@ acount actuall acuiring acumulate +addin addreess addtion adminstrator @@ -12,10 +13,8 @@ afrer afterall againt ags -aktive algoritm allo -alloacate allocted alocation alogrithm @@ -65,6 +64,7 @@ bject boardcast bootstraper bu +callin cant capabilites capablity @@ -73,6 +73,7 @@ carrefully cavaet chaing checkd +checkin childs choosen chould @@ -93,7 +94,6 @@ confg configruation configuable conneciton -connexion constrait constraits containg @@ -101,9 +101,7 @@ contex continuesly contro controler -controles controll -convienient convinience coputer correcponding @@ -158,13 +156,13 @@ differnet differnt direcotry directroy -disale disbale discrepency disover dissapper dissassociated divice +dockin doesn' doesnot doesnt @@ -175,7 +173,6 @@ eanbled earch ect elemnt -eles elments emmited enble @@ -183,29 +180,23 @@ encryted enebled enmpty entires -enviornment environmnet equivalant erro erronous -everthing everytime -excetion -excption excute execept execption +exects execut executeable exeeded exisitng exisits -existin existsing -exitting expcted expection -explaination explicitely faield faild @@ -218,7 +209,6 @@ fillled findout fisrt fo -folowing fowarding frist fro @@ -237,6 +227,7 @@ hanling happend hasing hasnt +havin hda hostanme hould @@ -256,18 +247,13 @@ implmeneted implmentation incase includeing -incosistency indecates -indien infor informations informaton -infrastrcuture ingore -inital initalize initator -initilization inspite instace instal @@ -287,12 +273,8 @@ ist klunky lable leve -lief limite -linke listner -lokal -lokales maintainence maintenace maintenence @@ -301,7 +283,6 @@ mambers manaully manuel maxium -mehtod mergable mesage messge @@ -311,7 +292,6 @@ minumum mis modifers mor -mot mulitply multipl multple @@ -325,7 +305,7 @@ nin nodel nome noone -nowe +notin numbe numer occured @@ -378,6 +358,7 @@ propogate provison psudo pyhsical +re-use readabilty readd reccuring @@ -392,11 +373,9 @@ remaning remore remvoing renabling -repeatly reponse reqest reqiured -requieres requried reserv reserverd @@ -414,17 +393,15 @@ retriving retrun retuned returing -re-use rever rocessor +roperty runing runnign sate scalled -scipt scirpt scrip -seconadry seconday seesion sepcified @@ -437,12 +414,10 @@ settig sevices shoul shoule -sie signle simplier singature skiping -snaphsot snpashot specied specifed @@ -453,7 +428,6 @@ standy statics stickyness stil -stip storeage strat streched @@ -462,7 +436,6 @@ succesfull successfull suceessful suces -sucessfully suiteable suppots suppport @@ -495,7 +468,6 @@ uncompressible uneccessarily unexepected unexpect -unknow unkonw unkown unneccessary @@ -503,14 +475,12 @@ unparseable unrecoginized unsupport unxpected -updat uptodate usera usign usin utlization vaidate -valiate valule valus varibles @@ -519,8 +489,6 @@ verfying verifing virutal visable -wakup wil wit -wll wth diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 06f9f424c7f..84020f4a6b0 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -30,17 +30,17 @@ jobs: build: runs-on: ubuntu-22.04 steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 - name: Set up JDK 17 - uses: actions/setup-java@v4 + uses: actions/setup-java@v5 with: distribution: 'temurin' java-version: '17' cache: 'maven' - name: Set up Python - uses: actions/setup-python@v5 + uses: actions/setup-python@v6 with: python-version: '3.10' architecture: 'x64' diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 471e56e3f07..4edd448067a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -29,7 +29,7 @@ permissions: jobs: build: if: github.repository == 'apache/cloudstack' - runs-on: ubuntu-22.04 + runs-on: ubuntu-24.04 strategy: fail-fast: false @@ -216,19 +216,19 @@ jobs: smoke/test_list_volumes"] steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 with: fetch-depth: 0 - name: Set up JDK 17 - uses: actions/setup-java@v4 + uses: actions/setup-java@v5 with: distribution: 'temurin' java-version: '17' cache: 'maven' - name: Set up Python - uses: actions/setup-python@v5 + uses: actions/setup-python@v6 with: python-version: '3.10' architecture: 'x64' @@ -236,7 +236,25 @@ jobs: - name: Install Build Dependencies run: | sudo apt-get update - sudo apt-get install -y git uuid-runtime genisoimage netcat ipmitool build-essential libgcrypt20 libgpg-error-dev libgpg-error0 libopenipmi0 ipmitool libpython3-dev libssl-dev libffi-dev python3-openssl python3-dev python3-setuptools + sudo apt-get install -y git uuid-runtime genisoimage netcat-openbsd ipmitool build-essential libgcrypt20 libgpg-error-dev libgpg-error0 libopenipmi0 ipmitool libpython3-dev libssl-dev libffi-dev python3-openssl python3-dev python3-setuptools + + - name: Setup IPMI Tool for CloudStack + run: | + # Create cloudstack-common directory if it doesn't exist + sudo mkdir -p /usr/share/cloudstack-common + + # Copy ipmitool to cloudstack-common directory if it doesn't exist + if [ ! -f /usr/share/cloudstack-common/ipmitool ]; then + sudo cp /usr/bin/ipmitool /usr/share/cloudstack-common/ipmitool + sudo chmod 755 /usr/share/cloudstack-common/ipmitool + fi + + # Create ipmitool-C3 wrapper script + sudo tee /usr/bin/ipmitool > /dev/null << 'EOF' + #!/bin/bash + /usr/share/cloudstack-common/ipmitool -C3 $@ + EOF + sudo chmod 755 /usr/bin/ipmitool - name: Install Python dependencies run: | @@ -275,7 +293,7 @@ jobs: - name: Setup Simulator Prerequisites run: | sudo python3 -m pip install --upgrade netaddr mysql-connector-python - python3 -m pip install --user --upgrade tools/marvin/dist/Marvin-*.tar.gz + python3 -m pip install --user --upgrade tools/marvin/dist/[mM]arvin-*.tar.gz mvn -q -Pdeveloper -pl developer -Ddeploydb mvn -q -Pdeveloper -pl developer -Ddeploydb-simulator diff --git a/.github/workflows/codecov.yml b/.github/workflows/codecov.yml index c77783746ca..fbd944a758f 100644 --- a/.github/workflows/codecov.yml +++ b/.github/workflows/codecov.yml @@ -32,12 +32,12 @@ jobs: name: codecov runs-on: ubuntu-22.04 steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 with: fetch-depth: 0 - name: Set up JDK 17 - uses: actions/setup-java@v4 + uses: actions/setup-java@v5 with: distribution: 'temurin' java-version: '17' diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml index 85f348b35bf..74e59aa821d 100644 --- a/.github/workflows/codeql-analysis.yml +++ b/.github/workflows/codeql-analysis.yml @@ -35,7 +35,7 @@ jobs: language: ["actions"] steps: - name: Checkout repository - uses: actions/checkout@v4 + uses: actions/checkout@v5 - name: Initialize CodeQL uses: github/codeql-action/init@v3 with: diff --git a/.github/workflows/docker-cloudstack-simulator.yml b/.github/workflows/docker-cloudstack-simulator.yml index 21a09d04e0b..af6cbf49f5e 100644 --- a/.github/workflows/docker-cloudstack-simulator.yml +++ b/.github/workflows/docker-cloudstack-simulator.yml @@ -47,7 +47,7 @@ jobs: - name: Set Docker repository name run: echo "DOCKER_REPOSITORY=apache" >> $GITHUB_ENV - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 - name: Set ACS version run: echo "ACS_VERSION=$(grep '' pom.xml | head -2 | tail -1 | cut -d'>' -f2 |cut -d'<' -f1)" >> $GITHUB_ENV diff --git a/.github/workflows/license-templates/LICENSE.txt b/.github/workflows/license-templates/LICENSE.txt new file mode 100644 index 00000000000..60b675e3101 --- /dev/null +++ b/.github/workflows/license-templates/LICENSE.txt @@ -0,0 +1,16 @@ +Licensed to the Apache Software Foundation (ASF) under one +or more contributor license agreements. See the NOTICE file +distributed with this work for additional information +regarding copyright ownership. The ASF licenses this file +to you under the Apache License, Version 2.0 (the +"License"); you may not use this file except in compliance +with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, +software distributed under the License is distributed on an +"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, either express or implied. See the License for the +specific language governing permissions and limitations +under the License. diff --git a/.github/workflows/main-sonar-check.yml b/.github/workflows/main-sonar-check.yml index dccd7174e54..70cc3fbe19f 100644 --- a/.github/workflows/main-sonar-check.yml +++ b/.github/workflows/main-sonar-check.yml @@ -32,12 +32,12 @@ jobs: name: Main Sonar JaCoCo Build runs-on: ubuntu-22.04 steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 with: fetch-depth: 0 - name: Set up JDK17 - uses: actions/setup-java@v4 + uses: actions/setup-java@v5 with: distribution: 'temurin' java-version: '17' diff --git a/.github/workflows/linter.yml b/.github/workflows/pre-commit.yml similarity index 87% rename from .github/workflows/linter.yml rename to .github/workflows/pre-commit.yml index 0bc87c6cc13..1518cfec014 100644 --- a/.github/workflows/linter.yml +++ b/.github/workflows/pre-commit.yml @@ -32,7 +32,7 @@ jobs: runs-on: ubuntu-22.04 steps: - name: Check Out - uses: actions/checkout@v4 + uses: actions/checkout@v5 - name: Install run: | python -m pip install --upgrade pip @@ -44,4 +44,6 @@ jobs: path: ~/.cache/pre-commit key: pre-commit|${{ env.PY }}|${{ hashFiles('.pre-commit-config.yaml') }} - name: Run pre-commit - run: pre-commit run --all-files + run: pre-commit run --color=always --all-files + - name: Run manual pre-commit hooks + run: pre-commit run --color=always --all-files --hook-stage manual diff --git a/.github/workflows/rat.yml b/.github/workflows/rat.yml index 52ce343841b..d71f4b0852d 100644 --- a/.github/workflows/rat.yml +++ b/.github/workflows/rat.yml @@ -30,9 +30,9 @@ jobs: build: runs-on: ubuntu-22.04 steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 - name: Set up JDK 17 - uses: actions/setup-java@v4 + uses: actions/setup-java@v5 with: java-version: '17' distribution: 'adopt' diff --git a/.github/workflows/sonar-check.yml b/.github/workflows/sonar-check.yml index d31f55980a8..46bfdd7d015 100644 --- a/.github/workflows/sonar-check.yml +++ b/.github/workflows/sonar-check.yml @@ -33,13 +33,13 @@ jobs: name: Sonar JaCoCo Coverage runs-on: ubuntu-22.04 steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 with: ref: "refs/pull/${{ github.event.number }}/merge" fetch-depth: 0 - name: Set up JDK17 - uses: actions/setup-java@v4 + uses: actions/setup-java@v5 with: distribution: 'temurin' java-version: '17' diff --git a/.github/workflows/ui.yml b/.github/workflows/ui.yml index 88d4a70e4c2..56b04a6f9c9 100644 --- a/.github/workflows/ui.yml +++ b/.github/workflows/ui.yml @@ -31,10 +31,10 @@ jobs: runs-on: ubuntu-22.04 steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 - name: Set up Node - uses: actions/setup-node@v3 + uses: actions/setup-node@v5 with: node-version: 16 diff --git a/.markdownlintignore b/.markdownlintignore new file mode 100644 index 00000000000..9fc9e21de77 --- /dev/null +++ b/.markdownlintignore @@ -0,0 +1 @@ +CHANGES.md diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 46db709c3fe..107bd8b94cd 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -25,18 +25,79 @@ repos: hooks: - id: identity - id: check-hooks-apply + - repo: https://github.com/thlorenz/doctoc.git + rev: v2.2.0 + hooks: + - id: doctoc + name: Add TOC for Markdown files + files: ^CONTRIBUTING\.md$|^INSTALL\.md$|^README\.md$ + - repo: https://github.com/oxipng/oxipng + rev: v9.1.5 + hooks: + - id: oxipng + name: run oxipng + description: optimize PNG images with lossless compression + args: ['-o', '4', '--strip', 'safe', '--alpha'] - repo: https://github.com/gitleaks/gitleaks rev: v8.27.2 hooks: - id: gitleaks name: run gitleaks description: detect hardcoded secrets + - repo: https://github.com/Lucas-C/pre-commit-hooks + rev: v1.5.5 + hooks: + - id: chmod + name: set file permissions + args: ['644'] + files: \.md$ + stages: [manual] + - id: insert-license + name: add license for all Markdown files + files: \.md$ + args: + - --comment-style + - '' + - --license-filepath + - .github/workflows/license-templates/LICENSE.txt + - --fuzzy-match-generates-todo + exclude: ^(CHANGES|ISSUE_TEMPLATE|PULL_REQUEST_TEMPLATE)\.md$|^ui/docs/(full|smoke)-test-plan\.template\.md$ + - id: insert-license + name: add license for all Shell files + description: automatically adds a licence header to all Shell files that don't have a license header + files: \.sh$ + args: + - --comment-style + - '|#|' + - --license-filepath + - .github/workflows/license-templates/LICENSE.txt + - --fuzzy-match-generates-todo + - id: insert-license + name: add license for all SQL files + files: \.sql$ + args: + - --comment-style + - '|--|' + - --license-filepath + - .github/workflows/license-templates/LICENSE.txt + - --fuzzy-match-generates-todo + - id: insert-license + name: add license for all YAML files + description: automatically adds a licence header to all YAML files that don't have a license header + files: \.ya?ml$ + args: + - --comment-style + - '|#|' + - --license-filepath + - .github/workflows/license-templates/LICENSE.txt + - --fuzzy-match-generates-todo - repo: https://github.com/pre-commit/pre-commit-hooks - rev: v5.0.0 + rev: v6.0.0 hooks: #- id: check-added-large-files - id: check-case-conflict #- id: check-executables-have-shebangs + - id: check-illegal-windows-names - id: check-merge-conflict - id: check-shebang-scripts-are-executable files: \.sh$ @@ -50,7 +111,7 @@ repos: exclude: > (?x) ^scripts/vm/systemvm/id_rsa\.cloud$| - ^server/src/test/java/org/apache/cloudstack/network/ssl/CertServiceTest.java$| + ^server/src/test/java/org/apache/cloudstack/network/ssl/CertServiceTest\.java$| ^server/src/test/java/com/cloud/keystore/KeystoreTest\.java$| ^server/src/test/resources/certs/dsa_self_signed\.key$| ^server/src/test/resources/certs/non_root\.key$| @@ -61,19 +122,21 @@ repos: ^services/console-proxy/rdpconsole/src/test/doc/rdp-key\.pem$| ^systemvm/agent/certs/localhost\.key$| ^systemvm/agent/certs/realhostip\.key$| - ^test/integration/smoke/test_ssl_offloading.py$ + ^test/integration/smoke/test_ssl_offloading\.py$ - id: end-of-file-fixer - exclude: \.vhd$ + exclude: \.vhd$|\.svg$ + - id: file-contents-sorter + args: [--unique] + files: ^\.github/linters/codespell\.txt$ - id: fix-byte-order-marker - id: forbid-submodules - id: mixed-line-ending - exclude: \.cs$ - id: trailing-whitespace files: \.(bat|cfg|cs|css|gitignore|header|in|install|java|md|properties|py|rb|rc|sh|sql|te|template|txt|ucls|vue|xml|xsl|yaml|yml)$|^cloud-cli/bindir/cloud-tool$|^debian/changelog$ args: [--markdown-linebreak-ext=md] exclude: ^services/console-proxy/rdpconsole/src/test/doc/freerdp-debug-log\.txt$ - repo: https://github.com/codespell-project/codespell - rev: v2.2.6 + rev: v2.4.1 hooks: - id: codespell name: run codespell @@ -94,3 +157,13 @@ repos: args: [--config=.github/linters/.markdown-lint.yml] types: [markdown] files: \.(md|mdown|markdown)$ + - repo: https://github.com/adrienverge/yamllint + rev: v1.37.1 + hooks: + - id: yamllint + name: run yamllint + description: check YAML files with yamllint + args: [--config-file=.github/linters/.yamllint.yml] + types: [yaml] + files: \.ya?ml$ + exclude: ^.*k8s-.*\.ya?ml$ diff --git a/CHANGES.md b/CHANGES.md index 8fea4f3a355..7a670a55a61 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -644,12 +644,12 @@ Bug ID | Description Version 4.2.1 ------------- -Release notes contain the list of [bug fixes](http://cloudstack.apache.org/docs/en-US/Apache_CloudStack/4.2.1/html/Release_Notes/version-4.2.html#issues-fixed-4.2.1) +Release notes contain the list of [bug fixes](https://cloudstack.apache.org/docs/en-US/Apache_CloudStack/4.2.1/html/Release_Notes/version-4.2.html#issues-fixed-4.2.1) Version 4.2.0 ------------- Released on October 1 2013. -Release notes contain the list of [bug fixes](http://cloudstack.apache.org/docs/en-US/Apache_CloudStack/4.2.0/html/Release_Notes/index.html) +Release notes contain the list of [bug fixes](https://cloudstack.apache.org/docs/en-US/Apache_CloudStack/4.2.0/html/Release_Notes/index.html) Version 4.1.0 ------------- diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 17ff4badc97..f0678ed7649 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,31 +1,65 @@ -Contributing to Apache CloudStack (ACS) -======================================= + + +# Contributing to Apache CloudStack (ACS) + +## Summary + + + + +- [Summary](#summary) +- [Bug fixes](#bug-fixes) +- [Developing new features](#developing-new-features) +- [PendingReleaseNotes file](#pendingreleasenotes-file) +- [Fork the code](#fork-the-code) +- [Making changes](#making-changes) +- [Rebase `feature_x` to include updates from `upstream/main`](#rebase-feature_x-to-include-updates-from-upstreammain) +- [Make a GitHub Pull Request to contribute your changes](#make-a-github-pull-request-to-contribute-your-changes) +- [Cleaning up after a successful pull request](#cleaning-up-after-a-successful-pull-request) +- [Release Principles](#release-principles) + + + +## Summary -Summary -------- This document covers how to contribute to the ACS project. ACS uses GitHub PRs to manage code contributions. These instructions assume you have a GitHub.com account, so if you don't have one you will have to create one. Your proposed code changes will be published to your own fork of the ACS project, and you will submit a Pull Request for your changes to be added. _Let's get started!!!_ -Bug fixes ---------- +## Bug fixes It's very important that we can easily track bug fix commits, so their hashes should remain the same in all branches. Therefore, a pull request (PR) that fixes a bug, should be sent against a release branch. This can be either the "current release" or the "previous release", depending on which ones are maintained. Since the goal is a stable main, bug fixes should be "merged forward" to the next branch in order: "previous release" -> "current release" -> main (in other words: old to new) -Developing new features ------------------------ +## Developing new features Development should be done in a feature branch, branched off of main. Send a PR(steps below) to get it into main (2x LGTM applies). PR will only be merged when main is open, will be held otherwise until main is open again. No back porting / cherry-picking features to existing branches! -PendingReleaseNotes file ------------------------- +## PendingReleaseNotes file + When developing a new feature or making a (major) change to an existing feature you are encouraged to append this to the PendingReleaseNotes file so that the Release Manager can use this file as a source of information when compiling the Release Notes for a new release. @@ -33,8 +67,7 @@ When adding information to the PendingReleaseNotes file make sure that you write Updating the PendingReleaseNotes file is preferably a part of the original Pull Request, but that is up to the developers' discretion. -Fork the code -------------- +## Fork the code In your browser, navigate to: [https://github.com/apache/cloudstack](https://github.com/apache/cloudstack) @@ -51,8 +84,7 @@ $ git fetch upstream $ git rebase upstream/main ``` -Making changes --------------- +## Making changes It is important that you create a new branch to make changes on and that you do not change the `main` branch (other than to rebase in changes from `upstream/main`). In this example I will assume you will be making your changes to a branch called `feature_x`. This `feature_x` branch will be created on your local repository and will be pushed to your forked repository on GitHub. Once this branch is on your fork you will create a Pull Request for the changes to be added to the ACS project. @@ -68,8 +100,7 @@ $ git commit -a -m "descriptive commit message for your changes" > The `-b` specifies that you want to create a new branch called `feature_x`. You only specify `-b` the first time you checkout because you are creating a new branch. Once the `feature_x` branch exists, you can later switch to it with only `git checkout feature_x`. -Rebase `feature_x` to include updates from `upstream/main` ------------------------------------------------------------- +## Rebase `feature_x` to include updates from `upstream/main` It is important that you maintain an up-to-date `main` branch in your local repository. This is done by rebasing in the code changes from `upstream/main` (the official ACS project repository) into your local repository. You will want to do this before you start working on a feature as well as right before you submit your changes as a pull request. I recommend you do this process periodically while you work to make sure you are working off the most recent project code. @@ -89,8 +120,7 @@ $ git rebase main > Now your `feature_x` branch is up-to-date with all the code in `upstream/main`. -Make a GitHub Pull Request to contribute your changes ------------------------------------------------------ +## Make a GitHub Pull Request to contribute your changes When you are happy with your changes, and you are ready to contribute them, you will create a Pull Request on GitHub to do so. This is done by pushing your local changes to your forked repository (default remote name is `origin`) and then initiating a pull request on GitHub. @@ -114,8 +144,7 @@ To initiate the pull request, do the following: If you are requested to make modifications to your proposed changes, make the changes locally on your `feature_x` branch, re-push the `feature_x` branch to your fork. The existing pull request should automatically pick up the change and update accordingly. -Cleaning up after a successful pull request -------------------------------------------- +## Cleaning up after a successful pull request Once the `feature_x` branch has been committed into the `upstream/main` branch, your local `feature_x` branch and the `origin/feature_x` branch are no longer needed. If you want to make additional changes, restart the process with a new branch. @@ -129,6 +158,6 @@ $ git branch -D feature_x $ git push origin :feature_x ``` -Release Principles ------------------- +## Release Principles + Detailed information about ACS release principles is available at https://cwiki.apache.org/confluence/display/CLOUDSTACK/Release+principles+for+Apache+CloudStack+4.6+and+up diff --git a/INSTALL.md b/INSTALL.md index efb42678b0a..52f109b0a41 100644 --- a/INSTALL.md +++ b/INSTALL.md @@ -1,15 +1,46 @@ + + # Apache CloudStack Installation basics This document describes how to develop, build, package and install Apache -CloudStack. For more information please refer to the official [documentation](http://docs.cloudstack.apache.org) +CloudStack. For more information please refer to the official [documentation](https://docs.cloudstack.apache.org) or the developer [wiki](https://cwiki.apache.org/confluence/display/CLOUDSTACK/Home). Apache CloudStack developers use various platforms for development, this guide was tested against a CentOS 7 x86_64 setup. -* [Setting up development environment](https://cwiki.apache.org/confluence/display/CLOUDSTACK/Setting+up+CloudStack+Development+Environment) for Apache CloudStack. -* [Building](https://cwiki.apache.org/confluence/display/CLOUDSTACK/How+to+build+CloudStack) Apache CloudStack. -* [Appliance based development](https://github.com/rhtyd/monkeybox) + + + +- [Setting up Development Environment](#setting-up-development-environment) + - [Using jenv and/or pyenv for Version Management](#using-jenv-andor-pyenv-for-version-management) +- [Getting the Source Code](#getting-the-source-code) +- [Building](#building) +- [To bring up CloudStack UI](#to-bring-up-cloudstack-ui) +- [Building with non-redistributable plugins](#building-with-non-redistributable-plugins) +- [Packaging and Installation](#packaging-and-installation) + - [Debian/Ubuntu](#debianubuntu) + - [RHEL/CentOS](#rhelcentos) +- [Notes](#notes) + + ## Setting up Development Environment @@ -41,7 +72,7 @@ Start the MySQL service: ### Using jenv and/or pyenv for Version Management -CloudStack is built using Java and Python. To make selection of these tools versions more consistent and ease installation for developers, optional support for [jenv](http://www.jenv.be/) and [pyenv](https://github.com/yyuu/pyenv) with [virtualenv]|(https://github.com/yyuu/pyenv-virtualenv) is provided. jenv installation instructions are available here and pyenv installation instructions are available here. For users of [oh-my-zsh](http://ohmyz.sh/) there is a pyenv plugin available to trigger configuration of pyenv in a shell session. +CloudStack is built using Java and Python. To make selection of these tools versions more consistent and ease installation for developers, optional support for [jenv](http://www.jenv.be/) and [pyenv](https://github.com/yyuu/pyenv) with [virtualenv]|(https://github.com/yyuu/pyenv-virtualenv) is provided. jenv installation instructions are available here and pyenv installation instructions are available here. For users of [oh-my-zsh](https://ohmyz.sh/) there is a pyenv plugin available to trigger configuration of pyenv in a shell session. Following installation, execute the following commands to configure jenv and pyenv for use with CloudStack development: @@ -171,7 +202,7 @@ All the rpm packages will be created in `dist/rpmbuild/RPMS/x86_64` directory. ## Notes -If you will be using Xen as your hypervisor, please download [vhd-util](http://download.cloudstack.org/tools/vhd-util) +If you will be using Xen as your hypervisor, please download [vhd-util](https://download.cloudstack.org/tools/vhd-util) If management server is installed on RHEL/CentOS, then copy vhd-util into: diff --git a/PRE-COMMIT.md b/PRE-COMMIT.md new file mode 100644 index 00000000000..9b76929d422 --- /dev/null +++ b/PRE-COMMIT.md @@ -0,0 +1,62 @@ + + +# pre-commit + +We run [pre-commit](https://pre-commit.com/) with +[GitHub Actions](https://github.com/apache/cloudstack/blob/main/.github/workflows/linter.yml) so installation on your +local machine is currently optional. + +The `pre-commit` [configuration file](https://github.com/apache/cloudstack/blob/main/.pre-commit-config.yaml) +is in the repository root. Before you can run the hooks, you need to have `pre-commit` installed. `pre-commit` is a +[Python package](https://pypi.org/project/pre-commit/). + +From the repository root run: `pip install -r requirements-dev.txt` to install `pre-commit` and after you install +`pre-commit` you will then need to install the pre-commit hooks by running `pre-commit install`. + +The hooks run when running `git commit` and also from the command line with `pre-commit`. Some of the hooks will auto +fix the code after the hooks fail whilst most will print error messages from the linters. If a hook fails the overall +commit will fail, and you will need to fix the issues or problems and `git add` and `git commit` again. On `git commit` +the hooks will run mostly only against modified files so if you want to test all hooks against all files and when you +are adding a new hook you should always run: + +`pre-commit run --all-files` + +Sometimes you might need to skip a hook to commit because the hook is stopping you from committing or your computer +might not have all the installation requirements for all the hooks. The `SKIP` variable is comma separated for two or +more hooks: + +`SKIP=codespell git commit -m "foo"` + +The same applies when running pre-commit: + +`SKIP=codespell pre-commit run --all-files` + +Occasionally you can have more serious problems when using `pre-commit` with `git commit`. You can use `--no-verify` to +commit and stop `pre-commit` from checking the hooks. For example: + +`git commit --no-verify -m "foo"` + +If you are having major problems using `pre-commit` you can always uninstall it. + +To run a single hook use `pre-commit run --all-files ` + +For example just run the `codespell` hook: + +`pre-commit run --all-files codespell` diff --git a/PULL_REQUEST_TEMPLATE.md b/PULL_REQUEST_TEMPLATE.md index 0bd7a7643ce..be04436d3ff 100644 --- a/PULL_REQUEST_TEMPLATE.md +++ b/PULL_REQUEST_TEMPLATE.md @@ -22,8 +22,8 @@ This PR... - [ ] Bug fix (non-breaking change which fixes an issue) - [ ] Enhancement (improves an existing feature and functionality) - [ ] Cleanup (Code refactoring and cleanup, that may add test cases) -- [ ] build/CI -- [ ] test (unit or integration test code) +- [ ] Build/CI +- [ ] Test (unit or integration test code) ### Feature/Enhancement Scale or Bug Severity diff --git a/README.md b/README.md index 2403b20d652..a5aacb49f6b 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,22 @@ + + # Apache CloudStack [![Build Status](https://github.com/apache/cloudstack/actions/workflows/build.yml/badge.svg?branch=main)](https://github.com/apache/cloudstack/actions/workflows/build.yml) @@ -12,6 +31,24 @@ [![Apache CloudStack](tools/logo/apache_cloudstack.png)](https://cloudstack.apache.org/) + + + +- [Who Uses CloudStack?](#who-uses-cloudstack) +- [Demo](#demo) +- [Getting Started](#getting-started) +- [Getting Source Repository](#getting-source-repository) +- [Documentation](#documentation) +- [News and Events](#news-and-events) +- [Getting Involved and Contributing](#getting-involved-and-contributing) +- [Reporting Security Vulnerabilities](#reporting-security-vulnerabilities) +- [License](#license) +- [Notice of Cryptographic Software](#notice-of-cryptographic-software) +- [Star History](#star-history) +- [Contributors](#contributors) + + + Apache CloudStack is open source software designed to deploy and manage large networks of virtual machines, as a highly available, highly scalable Infrastructure as a Service (IaaS) cloud computing platform. CloudStack is used @@ -31,7 +68,7 @@ OVM and LXC containers. Users can manage their cloud with an easy to use Web interface, command line tools, and/or a full-featured query based API. -For more information on Apache CloudStack, please visit the [website](http://cloudstack.apache.org) +For more information on Apache CloudStack, please visit the [website](https://cloudstack.apache.org) ## Who Uses CloudStack? @@ -88,10 +125,10 @@ via GitHub pull requests. ## Getting Involved and Contributing Interested in helping out with Apache CloudStack? Great! We welcome -participation from anybody willing to work [The Apache Way](http://theapacheway.com) and make a +participation from anybody willing to work [The Apache Way](https://theapacheway.com) and make a contribution. Note that you do not have to be a developer in order to contribute to Apache CloudStack. We need folks to help with documentation, translation, -promotion etc. See our contribution [page](http://cloudstack.apache.org/contribute.html). +promotion etc. See our contribution [page](https://cloudstack.apache.org/contribute.html). If you are a frequent contributors, you can request to be added as collaborators (see https://cwiki.apache.org/confluence/display/INFRA/Git+-+.asf.yaml+features#Git.asf.yamlfeatures-AssigningexternalcollaboratorswiththetriageroleonGitHub) @@ -102,7 +139,7 @@ You may do so by sharing your GitHub users ID or raise a GitHub issue. If you're interested in learning more or participating in the Apache CloudStack project, the mailing lists are the best way to do that. While the project has -several communications channels, the [mailing lists](http://cloudstack.apache.org/mailing-lists.html) are the most active and the +several communications channels, the [mailing lists](https://cloudstack.apache.org/mailing-lists.html) are the most active and the official channels for making decisions about the project itself. Mailing lists: @@ -122,7 +159,7 @@ released version of CloudStack, please report it to `security@apache.org` with details about the vulnerability, how it might be exploited, and any additional information that might be useful. -For more details, please visit our security [page](http://cloudstack.apache.org/security.html). +For more details, please visit our security [page](https://cloudstack.apache.org/security.html). ## License diff --git a/agent/conf/agent.properties b/agent/conf/agent.properties index 2a083de6fe5..0dc5b8211e0 100644 --- a/agent/conf/agent.properties +++ b/agent/conf/agent.properties @@ -451,3 +451,9 @@ iscsi.session.cleanup.enabled=false # If set to true, creates VMs as full clones of their templates on KVM hypervisor. Creates as linked clones otherwise. # create.full.clone=false + +# Instance conversion TMPDIR env var +#convert.instance.env.tmpdir= + +# Instance conversion VIRT_V2V_TMPDIR env var +#convert.instance.env.virtv2v.tmpdir= diff --git a/agent/pom.xml b/agent/pom.xml index 0fd7d35823e..5ab6cfe17c1 100644 --- a/agent/pom.xml +++ b/agent/pom.xml @@ -24,7 +24,7 @@ org.apache.cloudstack cloudstack - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT diff --git a/agent/src/main/java/com/cloud/agent/Agent.java b/agent/src/main/java/com/cloud/agent/Agent.java index e86557e9681..0d63f669028 100644 --- a/agent/src/main/java/com/cloud/agent/Agent.java +++ b/agent/src/main/java/com/cloud/agent/Agent.java @@ -613,7 +613,7 @@ public class Agent implements HandlerFactory, IAgentControl, AgentStatusUpdater } protected String getAgentArch() { - String arch = Script.runSimpleBashScript(Script.getExecutableAbsolutePath("arch"), 1000); + String arch = Script.runSimpleBashScript(Script.getExecutableAbsolutePath("arch"), 2000); logger.debug("Arch for agent: {} found: {}", _name, arch); return arch; } diff --git a/agent/src/main/java/com/cloud/agent/properties/AgentProperties.java b/agent/src/main/java/com/cloud/agent/properties/AgentProperties.java index 57dc607b920..3364f9708cf 100644 --- a/agent/src/main/java/com/cloud/agent/properties/AgentProperties.java +++ b/agent/src/main/java/com/cloud/agent/properties/AgentProperties.java @@ -117,7 +117,7 @@ public class AgentProperties{ /** * Local storage path.
- * This property allows multiple values to be entered in a single String. The differente values must be separated by commas.
+ * This property allows multiple values to be entered in a single String. The different values must be separated by commas.
* Data type: String.
* Default value: /var/lib/libvirt/images/ */ @@ -134,7 +134,7 @@ public class AgentProperties{ /** * MANDATORY: The UUID for the local storage pool.
- * This property allows multiple values to be entered in a single String. The differente values must be separated by commas.
+ * This property allows multiple values to be entered in a single String. The different values must be separated by commas.
* Data type: String.
* Default value: null */ @@ -794,6 +794,20 @@ public class AgentProperties{ */ public static final Property VIRTV2V_VERBOSE_ENABLED = new Property<>("virtv2v.verbose.enabled", false); + /** + * Set env TMPDIR var for virt-v2v Instance Conversion from VMware to KVM + * Data type: String.
+ * Default value: null + */ + public static final Property CONVERT_ENV_TMPDIR = new Property<>("convert.instance.env.tmpdir", null, String.class); + + /** + * Set env VIRT_V2V_TMPDIR var for virt-v2v Instance Conversion from VMware to KVM + * Data type: String.
+ * Default value: null + */ + public static final Property CONVERT_ENV_VIRTV2V_TMPDIR = new Property<>("convert.instance.env.virtv2v.tmpdir", null, String.class); + /** * BGP controll CIDR * Data type: String.
diff --git a/api/pom.xml b/api/pom.xml index 6270eb2dead..c80c3559345 100644 --- a/api/pom.xml +++ b/api/pom.xml @@ -24,7 +24,7 @@ org.apache.cloudstack cloudstack - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT diff --git a/api/src/main/java/com/cloud/agent/api/to/VirtualMachineMetadataTO.java b/api/src/main/java/com/cloud/agent/api/to/VirtualMachineMetadataTO.java new file mode 100644 index 00000000000..5b22afdedd5 --- /dev/null +++ b/api/src/main/java/com/cloud/agent/api/to/VirtualMachineMetadataTO.java @@ -0,0 +1,182 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.agent.api.to; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class VirtualMachineMetadataTO { + // VM details + private final String name; + private final String internalName; + private final String displayName; + private final String instanceUuid; + private final Integer cpuCores; + private final Integer memory; + private final Long created; + private final Long started; + + // Owner details + private final String ownerDomainUuid; + private final String ownerDomainName; + private final String ownerAccountUuid; + private final String ownerAccountName; + private final String ownerProjectUuid; + private final String ownerProjectName; + + // Host and service offering + private final String serviceOfferingName; + private final List serviceOfferingHostTags; + + // zone, pod, and cluster details + private final String zoneName; + private final String zoneUuid; + private final String podName; + private final String podUuid; + private final String clusterName; + private final String clusterUuid; + + // resource tags + private final Map resourceTags; + + public VirtualMachineMetadataTO( + String name, String internalName, String displayName, String instanceUuid, Integer cpuCores, Integer memory, Long created, Long started, + String ownerDomainUuid, String ownerDomainName, String ownerAccountUuid, String ownerAccountName, String ownerProjectUuid, String ownerProjectName, + String serviceOfferingName, List serviceOfferingHostTags, + String zoneName, String zoneUuid, String podName, String podUuid, String clusterName, String clusterUuid, Map resourceTags) { + /* + * Something failed in the metadata shall not be a fatal error, the VM can still be started + * Thus, the unknown fields just get an explicit "unknown" value so it can be fixed in case + * there are bugs on some execution paths. + * */ + + this.name = (name != null) ? name : "unknown"; + this.internalName = (internalName != null) ? internalName : "unknown"; + this.displayName = (displayName != null) ? displayName : "unknown"; + this.instanceUuid = (instanceUuid != null) ? instanceUuid : "unknown"; + this.cpuCores = (cpuCores != null) ? cpuCores : -1; + this.memory = (memory != null) ? memory : -1; + this.created = (created != null) ? created : 0; + this.started = (started != null) ? started : 0; + this.ownerDomainUuid = (ownerDomainUuid != null) ? ownerDomainUuid : "unknown"; + this.ownerDomainName = (ownerDomainName != null) ? ownerDomainName : "unknown"; + this.ownerAccountUuid = (ownerAccountUuid != null) ? ownerAccountUuid : "unknown"; + this.ownerAccountName = (ownerAccountName != null) ? ownerAccountName : "unknown"; + this.ownerProjectUuid = (ownerProjectUuid != null) ? ownerProjectUuid : "unknown"; + this.ownerProjectName = (ownerProjectName != null) ? ownerProjectName : "unknown"; + this.serviceOfferingName = (serviceOfferingName != null) ? serviceOfferingName : "unknown"; + this.serviceOfferingHostTags = (serviceOfferingHostTags != null) ? serviceOfferingHostTags : new ArrayList<>(); + this.zoneName = (zoneName != null) ? zoneName : "unknown"; + this.zoneUuid = (zoneUuid != null) ? zoneUuid : "unknown"; + this.podName = (podName != null) ? podName : "unknown"; + this.podUuid = (podUuid != null) ? podUuid : "unknown"; + this.clusterName = (clusterName != null) ? clusterName : "unknown"; + this.clusterUuid = (clusterUuid != null) ? clusterUuid : "unknown"; + + this.resourceTags = (resourceTags != null) ? resourceTags : new HashMap<>(); + } + + public String getName() { + return name; + } + + public String getInternalName() { + return internalName; + } + + public String getDisplayName() { + return displayName; + } + + public String getInstanceUuid() { + return instanceUuid; + } + + public Integer getCpuCores() { + return cpuCores; + } + + public Integer getMemory() { + return memory; + } + + public Long getCreated() { return created; } + + public Long getStarted() { + return started; + } + + public String getOwnerDomainUuid() { + return ownerDomainUuid; + } + + public String getOwnerDomainName() { + return ownerDomainName; + } + + public String getOwnerAccountUuid() { + return ownerAccountUuid; + } + + public String getOwnerAccountName() { + return ownerAccountName; + } + + public String getOwnerProjectUuid() { + return ownerProjectUuid; + } + + public String getOwnerProjectName() { + return ownerProjectName; + } + + public String getserviceOfferingName() { + return serviceOfferingName; + } + + public List getserviceOfferingHostTags() { + return serviceOfferingHostTags; + } + + public String getZoneName() { + return zoneName; + } + + public String getZoneUuid() { + return zoneUuid; + } + + public String getPodName() { + return podName; + } + + public String getPodUuid() { + return podUuid; + } + + public String getClusterName() { + return clusterName; + } + + public String getClusterUuid() { + return clusterUuid; + } + + public Map getResourceTags() { return resourceTags; } +} diff --git a/api/src/main/java/com/cloud/agent/api/to/VirtualMachineTO.java b/api/src/main/java/com/cloud/agent/api/to/VirtualMachineTO.java index cffb9874080..e26cc1e9f02 100644 --- a/api/src/main/java/com/cloud/agent/api/to/VirtualMachineTO.java +++ b/api/src/main/java/com/cloud/agent/api/to/VirtualMachineTO.java @@ -89,6 +89,7 @@ public class VirtualMachineTO { private DeployAsIsInfoTO deployAsIsInfo; private String metadataManufacturer; private String metadataProductName; + private VirtualMachineMetadataTO metadata; public VirtualMachineTO(long id, String instanceName, VirtualMachine.Type type, int cpus, Integer speed, long minRam, long maxRam, BootloaderType bootloader, String os, boolean enableHA, boolean limitCpuUse, String vncPassword) { @@ -494,6 +495,14 @@ public class VirtualMachineTO { this.metadataProductName = metadataProductName; } + public VirtualMachineMetadataTO getMetadata() { + return metadata; + } + + public void setMetadata(VirtualMachineMetadataTO metadata) { + this.metadata = metadata; + } + @Override public String toString() { return String.format("VM {id: \"%s\", name: \"%s\", uuid: \"%s\", type: \"%s\"}", id, name, uuid, type); diff --git a/api/src/main/java/com/cloud/configuration/ConfigurationService.java b/api/src/main/java/com/cloud/configuration/ConfigurationService.java index 32e31519ea7..438283136d2 100644 --- a/api/src/main/java/com/cloud/configuration/ConfigurationService.java +++ b/api/src/main/java/com/cloud/configuration/ConfigurationService.java @@ -108,36 +108,22 @@ public interface ConfigurationService { /** * Updates a service offering * - * @param serviceOfferingId - * @param userId - * @param name - * @param displayText - * @param offerHA - * @param useVirtualNetwork - * @param tags * @return updated service offering */ ServiceOffering updateServiceOffering(UpdateServiceOfferingCmd cmd); /** * Deletes a service offering - * - * @param userId - * @param serviceOfferingId */ boolean deleteServiceOffering(DeleteServiceOfferingCmd cmd); /** * Retrieve ID of domains for a service offering - * - * @param serviceOfferingId */ List getServiceOfferingDomains(Long serviceOfferingId); /** * Retrieve ID of domains for a service offering - * - * @param serviceOfferingId */ List getServiceOfferingZones(Long serviceOfferingId); @@ -147,7 +133,6 @@ public interface ConfigurationService { * @param cmd * - the command specifying diskOfferingId, name, description, tags * @return updated disk offering - * @throws */ DiskOffering updateDiskOffering(UpdateDiskOfferingCmd cmd); @@ -157,34 +142,22 @@ public interface ConfigurationService { * @param cmd * - the command specifying disk offering id * @return true or false - * @throws */ boolean deleteDiskOffering(DeleteDiskOfferingCmd cmd); /** * Creates a new disk offering - * - * @param domainId - * @param name - * @param description - * @param numGibibytes - * @param mirrored - * @param size * @return ID */ DiskOffering createDiskOffering(CreateDiskOfferingCmd cmd); /** * Retrieve ID of domains for a disk offering - * - * @param diskOfferingId */ List getDiskOfferingDomains(Long diskOfferingId); /** * Retrieve ID of domains for a disk offering - * - * @param diskOfferingId */ List getDiskOfferingZones(Long diskOfferingId); @@ -207,8 +180,6 @@ public interface ConfigurationService { * TODO * @param storageAccessGroups * @return the new pod if successful, null otherwise - * @throws - * @throws */ Pod createPod(long zoneId, String name, String startIp, String endIp, String gateway, String netmask, String allocationState, List storageAccessGroups); @@ -228,8 +199,7 @@ public interface ConfigurationService { /** * Updates a mutually exclusive IP range in the pod. * @param cmd - The command specifying pod ID, current Start IP, current End IP, new Start IP, new End IP. - * @throws com.cloud.exception.ConcurrentOperationException - * @return Success + * @throws com.cloud.exception.ConcurrentOperationException when this pod is already being accessed */ void updatePodIpRange(UpdatePodManagementNetworkIpRangeCmd cmd) throws ConcurrentOperationException; @@ -250,9 +220,6 @@ public interface ConfigurationService { /** * Edits a pod in the database. Will not allow you to edit pods that are being used anywhere in the system. - * - * @param UpdatePodCmd - * api command */ Pod editPod(UpdatePodCmd cmd); @@ -262,17 +229,12 @@ public interface ConfigurationService { * @param cmd * - the command containing podId * @return true or false - * @throws , */ boolean deletePod(DeletePodCmd cmd); /** * Creates a new zone - * - * @param cmd * @return the zone if successful, null otherwise - * @throws - * @throws */ DataCenter createZone(CreateZoneCmd cmd); @@ -295,22 +257,7 @@ public interface ConfigurationService { * Adds a VLAN to the database, along with an IP address range. Can add three types of VLANs: (1) zone-wide VLANs on * the * virtual public network (2) pod-wide direct attached VLANs (3) account-specific direct attached VLANs - * - * @param userId - * @param vlanType - * - either "DomR" (VLAN for a virtual public network) or "DirectAttached" (VLAN for IPs that will be - * directly - * attached to UserVMs) - * @param zoneId - * @param accountId - * @param podId - * @param add - * @param vlanId - * @param gateway - * @param startIP - * @param endIP * @throws ResourceAllocationException TODO - * @throws * @return The new Vlan object */ Vlan createVlanAndPublicIpRange(CreateVlanIpRangeCmd cmd) throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException, @@ -325,9 +272,6 @@ public interface ConfigurationService { /** * Marks the account with the default zone-id. * - * @param accountName - * @param domainId - * @param defaultZoneId * @return The new account object */ Account markDefaultZone(String accountName, long domainId, long defaultZoneId); @@ -349,14 +293,12 @@ public interface ConfigurationService { /** * Retrieve ID of domains for a network offering * - * @param networkOfferingId */ List getNetworkOfferingDomains(Long networkOfferingId); /** * Retrieve ID of domains for a network offering * - * @param networkOfferingId */ List getNetworkOfferingZones(Long networkOfferingId); diff --git a/api/src/main/java/com/cloud/event/EventTypes.java b/api/src/main/java/com/cloud/event/EventTypes.java index be21f13267b..38e601c790a 100644 --- a/api/src/main/java/com/cloud/event/EventTypes.java +++ b/api/src/main/java/com/cloud/event/EventTypes.java @@ -27,6 +27,7 @@ import org.apache.cloudstack.api.response.ClusterResponse; import org.apache.cloudstack.api.response.HostResponse; import org.apache.cloudstack.api.response.PodResponse; import org.apache.cloudstack.api.response.ZoneResponse; +import org.apache.cloudstack.backup.BackupRepositoryService; import org.apache.cloudstack.config.Configuration; import org.apache.cloudstack.datacenter.DataCenterIpv4GuestSubnet; import org.apache.cloudstack.extension.Extension; @@ -852,6 +853,10 @@ public class EventTypes { // Custom Action public static final String EVENT_CUSTOM_ACTION = "CUSTOM.ACTION"; + // Backup Repository + public static final String EVENT_BACKUP_REPOSITORY_ADD = "BACKUP.REPOSITORY.ADD"; + public static final String EVENT_BACKUP_REPOSITORY_UPDATE = "BACKUP.REPOSITORY.UPDATE"; + static { // TODO: need a way to force author adding event types to declare the entity details as well, with out braking @@ -1385,6 +1390,10 @@ public class EventTypes { entityEventDetails.put(EVENT_EXTENSION_CUSTOM_ACTION_ADD, ExtensionCustomAction.class); entityEventDetails.put(EVENT_EXTENSION_CUSTOM_ACTION_UPDATE, ExtensionCustomAction.class); entityEventDetails.put(EVENT_EXTENSION_CUSTOM_ACTION_DELETE, ExtensionCustomAction.class); + + // Backup Repository + entityEventDetails.put(EVENT_BACKUP_REPOSITORY_ADD, BackupRepositoryService.class); + entityEventDetails.put(EVENT_BACKUP_REPOSITORY_UPDATE, BackupRepositoryService.class); } public static boolean isNetworkEvent(String eventType) { diff --git a/api/src/main/java/com/cloud/kubernetes/cluster/KubernetesCluster.java b/api/src/main/java/com/cloud/kubernetes/cluster/KubernetesCluster.java index 571d993c7a1..ce905b293ff 100644 --- a/api/src/main/java/com/cloud/kubernetes/cluster/KubernetesCluster.java +++ b/api/src/main/java/com/cloud/kubernetes/cluster/KubernetesCluster.java @@ -88,6 +88,8 @@ public interface KubernetesCluster extends ControlledEntity, com.cloud.utils.fsm s_fsm.addTransition(State.Stopping, Event.OperationFailed, State.Alert); s_fsm.addTransition(State.Stopped, Event.StartRequested, State.Starting); + s_fsm.addTransition(State.Stopped, Event.OperationSucceeded, State.Stopped); + s_fsm.addTransition(State.Running, Event.OperationSucceeded, State.Running); s_fsm.addTransition(State.Running, Event.FaultsDetected, State.Alert); @@ -170,4 +172,5 @@ public interface KubernetesCluster extends ControlledEntity, com.cloud.utils.fsm Long getEtcdNodeCount(); Long getCniConfigId(); String getCniConfigDetails(); + boolean isCsiEnabled(); } diff --git a/api/src/main/java/com/cloud/network/PhysicalNetworkTrafficType.java b/api/src/main/java/com/cloud/network/PhysicalNetworkTrafficType.java index 9676badb4e9..d3804cd29da 100644 --- a/api/src/main/java/com/cloud/network/PhysicalNetworkTrafficType.java +++ b/api/src/main/java/com/cloud/network/PhysicalNetworkTrafficType.java @@ -41,4 +41,6 @@ public interface PhysicalNetworkTrafficType extends InternalIdentity, Identity { String getHypervNetworkLabel(); String getOvm3NetworkLabel(); + + String getVlan(); } diff --git a/api/src/main/java/com/cloud/network/RouterHealthCheckResult.java b/api/src/main/java/com/cloud/network/RouterHealthCheckResult.java index eb65ae9088e..22a46ce9ecd 100644 --- a/api/src/main/java/com/cloud/network/RouterHealthCheckResult.java +++ b/api/src/main/java/com/cloud/network/RouterHealthCheckResult.java @@ -26,7 +26,7 @@ public interface RouterHealthCheckResult { String getCheckType(); - boolean getCheckResult(); + VirtualNetworkApplianceService.RouterHealthStatus getCheckResult(); Date getLastUpdateTime(); diff --git a/api/src/main/java/com/cloud/network/VirtualNetworkApplianceService.java b/api/src/main/java/com/cloud/network/VirtualNetworkApplianceService.java index cb92739d283..a60f1d49336 100644 --- a/api/src/main/java/com/cloud/network/VirtualNetworkApplianceService.java +++ b/api/src/main/java/com/cloud/network/VirtualNetworkApplianceService.java @@ -87,4 +87,8 @@ public interface VirtualNetworkApplianceService { Pair performRouterHealthChecks(long routerId); void collectNetworkStatistics(T router, Nic nic); + + enum RouterHealthStatus{ + SUCCESS, FAILED, WARNING, UNKNOWN; + } } diff --git a/api/src/main/java/com/cloud/network/as/AutoScaleService.java b/api/src/main/java/com/cloud/network/as/AutoScaleService.java index ceca4de6842..4aef10f8de9 100644 --- a/api/src/main/java/com/cloud/network/as/AutoScaleService.java +++ b/api/src/main/java/com/cloud/network/as/AutoScaleService.java @@ -70,6 +70,8 @@ public interface AutoScaleService { Counter createCounter(CreateCounterCmd cmd); + Counter getCounter(long counterId); + boolean deleteCounter(long counterId) throws ResourceInUseException; List listCounters(ListCountersCmd cmd); diff --git a/api/src/main/java/com/cloud/network/lb/LoadBalancingRulesService.java b/api/src/main/java/com/cloud/network/lb/LoadBalancingRulesService.java index 3fc6028b977..0bf06be15d8 100644 --- a/api/src/main/java/com/cloud/network/lb/LoadBalancingRulesService.java +++ b/api/src/main/java/com/cloud/network/lb/LoadBalancingRulesService.java @@ -41,13 +41,23 @@ import com.cloud.utils.net.Ip; public interface LoadBalancingRulesService { /** * Create a load balancer rule from the given ipAddress/port to the given private port + * @param xId an existing UUID for this rule (for instance a device generated one) + * @param name + * @param description + * @param srcPortStart + * @param srcPortEnd + * @param defPortStart + * @param defPortEnd + * @param ipAddrId + * @param protocol + * @param algorithm + * @param networkId + * @param lbOwnerId * @param openFirewall - * TODO - * @param forDisplay TODO - * @param cmd - * the command specifying the ip address, public port, protocol, private port, and algorithm - * + * @param lbProtocol + * @param forDisplay * @return the newly created LoadBalancerVO if successful, null otherwise + * @throws NetworkRuleConflictException * @throws InsufficientAddressCapacityException */ LoadBalancer createPublicLoadBalancerRule(String xId, String name, String description, int srcPortStart, int srcPortEnd, int defPortStart, int defPortEnd, diff --git a/api/src/main/java/com/cloud/offering/DiskOffering.java b/api/src/main/java/com/cloud/offering/DiskOffering.java index e1c41f77cbf..d74f5703cc9 100644 --- a/api/src/main/java/com/cloud/offering/DiskOffering.java +++ b/api/src/main/java/com/cloud/offering/DiskOffering.java @@ -37,7 +37,7 @@ public interface DiskOffering extends InfrastructureEntity, Identity, InternalId State getState(); enum DiskCacheMode { - NONE("none"), WRITEBACK("writeback"), WRITETHROUGH("writethrough"); + NONE("none"), WRITEBACK("writeback"), WRITETHROUGH("writethrough"), HYPERVISOR_DEFAULT("hypervisor_default"); private final String _diskCacheMode; @@ -69,6 +69,8 @@ public interface DiskOffering extends InfrastructureEntity, Identity, InternalId boolean isCustomized(); + boolean isShared(); + void setDiskSize(long diskSize); long getDiskSize(); @@ -99,7 +101,6 @@ public interface DiskOffering extends InfrastructureEntity, Identity, InternalId Long getBytesReadRateMaxLength(); - void setBytesWriteRate(Long bytesWriteRate); Long getBytesWriteRate(); @@ -112,7 +113,6 @@ public interface DiskOffering extends InfrastructureEntity, Identity, InternalId Long getBytesWriteRateMaxLength(); - void setIopsReadRate(Long iopsReadRate); Long getIopsReadRate(); @@ -133,7 +133,6 @@ public interface DiskOffering extends InfrastructureEntity, Identity, InternalId Long getIopsWriteRateMax(); - void setIopsWriteRateMaxLength(Long iopsWriteRateMaxLength); Long getIopsWriteRateMaxLength(); diff --git a/api/src/main/java/com/cloud/server/ManagementService.java b/api/src/main/java/com/cloud/server/ManagementService.java index f7b2456ce5c..d2a987bb078 100644 --- a/api/src/main/java/com/cloud/server/ManagementService.java +++ b/api/src/main/java/com/cloud/server/ManagementService.java @@ -20,7 +20,6 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; -import com.cloud.user.UserData; import org.apache.cloudstack.api.command.admin.cluster.ListClustersCmd; import org.apache.cloudstack.api.command.admin.config.ListCfgGroupsByCmd; import org.apache.cloudstack.api.command.admin.config.ListCfgsByCmd; @@ -72,6 +71,7 @@ import org.apache.cloudstack.api.command.user.vm.GetVMPasswordCmd; import org.apache.cloudstack.api.command.user.vmgroup.UpdateVMGroupCmd; import org.apache.cloudstack.config.Configuration; import org.apache.cloudstack.config.ConfigurationGroup; +import org.apache.cloudstack.framework.config.ConfigKey; import com.cloud.alert.Alert; import com.cloud.capacity.Capacity; @@ -91,6 +91,7 @@ import com.cloud.storage.GuestOSHypervisor; import com.cloud.storage.GuestOsCategory; import com.cloud.storage.StoragePool; import com.cloud.user.SSHKeyPair; +import com.cloud.user.UserData; import com.cloud.utils.Pair; import com.cloud.utils.Ternary; import com.cloud.vm.InstanceGroup; @@ -104,6 +105,14 @@ import com.cloud.vm.VirtualMachine.Type; public interface ManagementService { static final String Name = "management-server"; + ConfigKey JsInterpretationEnabled = new ConfigKey<>("Hidden" + , Boolean.class + , "js.interpretation.enabled" + , "false" + , "Enable/Disable all JavaScript interpretation related functionalities to create or update Javascript rules." + , false + , ConfigKey.Scope.Global); + /** * returns the a map of the names/values in the configuration table * @@ -509,4 +518,6 @@ public interface ManagementService { boolean removeManagementServer(RemoveManagementServerCmd cmd); + void checkJsInterpretationAllowedIfNeededForParameterValue(String paramName, boolean paramValue); + } diff --git a/api/src/main/java/com/cloud/server/ResourceManagerUtil.java b/api/src/main/java/com/cloud/server/ResourceManagerUtil.java index 9a3b51a70d5..f5081cbe307 100644 --- a/api/src/main/java/com/cloud/server/ResourceManagerUtil.java +++ b/api/src/main/java/com/cloud/server/ResourceManagerUtil.java @@ -18,6 +18,7 @@ package com.cloud.server; public interface ResourceManagerUtil { long getResourceId(String resourceId, ResourceTag.ResourceObjectType resourceType); + long getResourceId(String resourceId, ResourceTag.ResourceObjectType resourceType, boolean checkAccess); String getUuid(String resourceId, ResourceTag.ResourceObjectType resourceType); ResourceTag.ResourceObjectType getResourceType(String resourceTypeStr); void checkResourceAccessible(Long accountId, Long domainId, String exceptionMessage); diff --git a/api/src/main/java/com/cloud/storage/Storage.java b/api/src/main/java/com/cloud/storage/Storage.java index 1ad3731b9ea..5b3e97698fd 100644 --- a/api/src/main/java/com/cloud/storage/Storage.java +++ b/api/src/main/java/com/cloud/storage/Storage.java @@ -128,7 +128,7 @@ public class Storage { public static enum TemplateType { ROUTING, // Router template SYSTEM, /* routing, system vm template */ - BUILTIN, /* buildin template */ + BUILTIN, /* builtin template */ PERHOST, /* every host has this template, don't need to install it in secondary storage */ USER, /* User supplied template/iso */ VNF, /* VNFs (virtual network functions) template */ diff --git a/api/src/main/java/com/cloud/storage/VolumeApiService.java b/api/src/main/java/com/cloud/storage/VolumeApiService.java index 4140d51a800..19c2ebe455a 100644 --- a/api/src/main/java/com/cloud/storage/VolumeApiService.java +++ b/api/src/main/java/com/cloud/storage/VolumeApiService.java @@ -180,6 +180,8 @@ public interface VolumeApiService { */ boolean doesStoragePoolSupportDiskOfferingTags(StoragePool destPool, String diskOfferingTags); + boolean validateConditionsToReplaceDiskOfferingOfVolume(Volume volume, DiskOffering newDiskOffering, StoragePool destPool); + Volume destroyVolume(long volumeId, Account caller, boolean expunge, boolean forceExpunge); void destroyVolume(long volumeId); diff --git a/api/src/main/java/com/cloud/storage/snapshot/SnapshotApiService.java b/api/src/main/java/com/cloud/storage/snapshot/SnapshotApiService.java index 67afd6aa4e2..d52e645ec79 100644 --- a/api/src/main/java/com/cloud/storage/snapshot/SnapshotApiService.java +++ b/api/src/main/java/com/cloud/storage/snapshot/SnapshotApiService.java @@ -85,7 +85,7 @@ public interface SnapshotApiService { * the command that specifies the volume criteria * @return list of snapshot policies */ - Pair, Integer> listPoliciesforVolume(ListSnapshotPoliciesCmd cmd); + Pair, Integer> listSnapshotPolicies(ListSnapshotPoliciesCmd cmd); boolean deleteSnapshotPolicies(DeleteSnapshotPoliciesCmd cmd); diff --git a/api/src/main/java/com/cloud/storage/snapshot/SnapshotPolicy.java b/api/src/main/java/com/cloud/storage/snapshot/SnapshotPolicy.java index 22d5dfb9c1b..13009a9808a 100644 --- a/api/src/main/java/com/cloud/storage/snapshot/SnapshotPolicy.java +++ b/api/src/main/java/com/cloud/storage/snapshot/SnapshotPolicy.java @@ -16,11 +16,12 @@ // under the License. package com.cloud.storage.snapshot; +import org.apache.cloudstack.acl.ControlledEntity; import org.apache.cloudstack.api.Displayable; import org.apache.cloudstack.api.Identity; import org.apache.cloudstack.api.InternalIdentity; -public interface SnapshotPolicy extends Identity, InternalIdentity, Displayable { +public interface SnapshotPolicy extends ControlledEntity, Identity, InternalIdentity, Displayable { long getVolumeId(); diff --git a/api/src/main/java/com/cloud/vm/UserVmService.java b/api/src/main/java/com/cloud/vm/UserVmService.java index 6f1aba4613d..01f11b73cd4 100644 --- a/api/src/main/java/com/cloud/vm/UserVmService.java +++ b/api/src/main/java/com/cloud/vm/UserVmService.java @@ -64,6 +64,7 @@ import com.cloud.storage.StoragePool; import com.cloud.template.VirtualMachineTemplate; import com.cloud.user.Account; import com.cloud.uservm.UserVm; +import com.cloud.utils.Pair; import com.cloud.utils.exception.ExecutionException; public interface UserVmService { @@ -507,16 +508,41 @@ public interface UserVmService { void collectVmNetworkStatistics (UserVm userVm); - UserVm importVM(final DataCenter zone, final Host host, final VirtualMachineTemplate template, final String instanceName, final String displayName, final Account owner, final String userData, final Account caller, final Boolean isDisplayVm, final String keyboard, + /** + * Import VM into CloudStack + * @param zone importing zone + * @param host importing host + * @param template template for the imported VM + * @param instanceNameInternal set to null to CloudStack to autogenerate from the next available VM ID on database + * @param displayName display name for the imported VM + * @param owner owner of the imported VM + * @param userData user data for the imported VM + * @param caller caller account + * @param isDisplayVm true to display the imported VM + * @param keyboard keyboard distribution for the imported VM + * @param accountId account ID + * @param userId user ID + * @param serviceOffering service offering for the imported VM + * @param sshPublicKey ssh key for the imported VM + * @param hostName the name for the imported VM + * @param hypervisorType hypervisor type for the imported VM + * @param customParameters details for the imported VM + * @param powerState power state of the imported VM + * @param networkNicMap network to nic mapping + * @return the imported VM + * @throws InsufficientCapacityException in case of errors + */ + UserVm importVM(final DataCenter zone, final Host host, final VirtualMachineTemplate template, final String instanceNameInternal, final String displayName, final Account owner, final String userData, final Account caller, final Boolean isDisplayVm, final String keyboard, final long accountId, final long userId, final ServiceOffering serviceOffering, final String sshPublicKey, final String hostName, final HypervisorType hypervisorType, final Map customParameters, final VirtualMachine.PowerState powerState, final LinkedHashMap> networkNicMap) throws InsufficientCapacityException; /** * Unmanage a guest VM from CloudStack - * @return true if the VM is successfully unmanaged, false if not. + * + * @return (true if successful, false if not, hostUuid) if the VM is successfully unmanaged. */ - boolean unmanageUserVM(Long vmId); + Pair unmanageUserVM(Long vmId, Long targetHostId); UserVm allocateVMFromBackup(CreateVMFromBackupCmd cmd) throws InsufficientCapacityException, ResourceAllocationException, ResourceUnavailableException; diff --git a/api/src/main/java/com/cloud/vm/VirtualMachineProfile.java b/api/src/main/java/com/cloud/vm/VirtualMachineProfile.java index c67ee4eabc2..5c78d6bedd6 100644 --- a/api/src/main/java/com/cloud/vm/VirtualMachineProfile.java +++ b/api/src/main/java/com/cloud/vm/VirtualMachineProfile.java @@ -78,6 +78,7 @@ public interface VirtualMachineProfile { public static final Param BootIntoSetup = new Param("enterHardwareSetup"); public static final Param PreserveNics = new Param("PreserveNics"); public static final Param ConsiderLastHost = new Param("ConsiderLastHost"); + public static final Param ReturnAfterVolumePrepare = new Param("ReturnAfterVolumePrepare"); private String name; diff --git a/api/src/main/java/com/cloud/vm/snapshot/VMSnapshotService.java b/api/src/main/java/com/cloud/vm/snapshot/VMSnapshotService.java index 84a56aaedd3..754e463e710 100644 --- a/api/src/main/java/com/cloud/vm/snapshot/VMSnapshotService.java +++ b/api/src/main/java/com/cloud/vm/snapshot/VMSnapshotService.java @@ -19,6 +19,7 @@ package com.cloud.vm.snapshot; import java.util.List; +import com.cloud.utils.fsm.NoTransitionException; import org.apache.cloudstack.api.command.user.vmsnapshot.ListVMSnapshotCmd; import com.cloud.exception.ConcurrentOperationException; @@ -53,4 +54,6 @@ public interface VMSnapshotService { * @param id vm id */ boolean deleteVMSnapshotsFromDB(Long vmId, boolean unmanage); + + void updateOperationFailed(VMSnapshot vmSnapshot) throws NoTransitionException; } diff --git a/api/src/main/java/org/apache/cloudstack/api/AbstractGetUploadParamsCmd.java b/api/src/main/java/org/apache/cloudstack/api/AbstractGetUploadParamsCmd.java index 083a1be00f5..028aab24757 100644 --- a/api/src/main/java/org/apache/cloudstack/api/AbstractGetUploadParamsCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/AbstractGetUploadParamsCmd.java @@ -81,6 +81,34 @@ public abstract class AbstractGetUploadParamsCmd extends BaseCmd { return projectId; } + public void setName(String name) { + this.name = name; + } + + public void setFormat(String format) { + this.format = format; + } + + public void setZoneId(Long zoneId) { + this.zoneId = zoneId; + } + + public void setChecksum(String checksum) { + this.checksum = checksum; + } + + public void setAccountName(String accountName) { + this.accountName = accountName; + } + + public void setDomainId(Long domainId) { + this.domainId = domainId; + } + + public void setProjectId(Long projectId) { + this.projectId = projectId; + } + public GetUploadParamsResponse createGetUploadParamsResponse(UUID id, URL postURL, String metadata, String timeout, String signature) { return new GetUploadParamsResponse(id, postURL, metadata, timeout, signature); } diff --git a/api/src/main/java/org/apache/cloudstack/api/ApiConstants.java b/api/src/main/java/org/apache/cloudstack/api/ApiConstants.java index 489d737b5bb..8fca652518f 100644 --- a/api/src/main/java/org/apache/cloudstack/api/ApiConstants.java +++ b/api/src/main/java/org/apache/cloudstack/api/ApiConstants.java @@ -27,6 +27,7 @@ public class ApiConstants { public static final String ACTIVATION_RULE = "activationrule"; public static final String ACTIVITY = "activity"; public static final String ADAPTER_TYPE = "adaptertype"; + public static final String ADDITONAL_CONFIG_ENABLED = "additionalconfigenabled"; public static final String ADDRESS = "address"; public static final String ALGORITHM = "algorithm"; public static final String ALIAS = "alias"; @@ -63,6 +64,7 @@ public class ApiConstants { public static final String BACKUP_STORAGE_LIMIT = "backupstoragelimit"; public static final String BACKUP_STORAGE_TOTAL = "backupstoragetotal"; public static final String BACKUP_VM_OFFERING_REMOVED = "vmbackupofferingremoved"; + public static final String IS_BACKUP_VM_EXPUNGED = "isbackupvmexpunged"; public static final String BACKUP_TOTAL = "backuptotal"; public static final String BASE64_IMAGE = "base64image"; public static final String BGP_PEERS = "bgppeers"; @@ -80,6 +82,7 @@ public class ApiConstants { public static final String BYTES_WRITE_RATE_MAX = "byteswriteratemax"; public static final String BYTES_WRITE_RATE_MAX_LENGTH = "byteswriteratemaxlength"; public static final String BYPASS_VLAN_OVERLAP_CHECK = "bypassvlanoverlapcheck"; + public static final String CALLER = "caller"; public static final String CAPACITY = "capacity"; public static final String CATEGORY = "category"; public static final String CAN_REVERT = "canrevert"; @@ -132,6 +135,7 @@ public class ApiConstants { public static final String CNI_CONFIG_ID = "cniconfigurationid"; public static final String CNI_CONFIG_DETAILS = "cniconfigdetails"; public static final String CNI_CONFIG_NAME = "cniconfigname"; + public static final String CSI_ENABLED = "csienabled"; public static final String COMPONENT = "component"; public static final String CPU = "CPU"; public static final String CPU_CORE_PER_SOCKET = "cpucorepersocket"; @@ -139,6 +143,7 @@ public class ApiConstants { public static final String CPU_SPEED = "cpuspeed"; public static final String CPU_LOAD_AVERAGE = "cpuloadaverage"; public static final String CREATED = "created"; + public static final String CROSS_ZONE_INSTANCE_CREATION = "crosszoneinstancecreation"; public static final String CTX_ACCOUNT_ID = "ctxaccountid"; public static final String CTX_DETAILS = "ctxDetails"; public static final String CTX_USER_ID = "ctxuserid"; @@ -211,6 +216,7 @@ public class ApiConstants { public static final String DURATION = "duration"; public static final String ELIGIBLE = "eligible"; public static final String EMAIL = "email"; + public static final String ENABLE_CSI = "enablecsi"; public static final String END_ASN = "endasn"; public static final String END_DATE = "enddate"; public static final String END_IP = "endip"; @@ -222,6 +228,7 @@ public class ApiConstants { public static final String EVENT_TYPE = "eventtype"; public static final String EXPIRES = "expires"; public static final String EXTRA_CONFIG = "extraconfig"; + public static final String EXTRA_PARAMS = "extraparams"; public static final String EXTRA_DHCP_OPTION = "extradhcpoption"; public static final String EXTRA_DHCP_OPTION_NAME = "extradhcpoptionname"; public static final String EXTRA_DHCP_OPTION_CODE = "extradhcpoptioncode"; @@ -240,6 +247,8 @@ public class ApiConstants { public static final String FIRSTNAME = "firstname"; public static final String FORCED = "forced"; public static final String FORCED_DESTROY_LOCAL_STORAGE = "forcedestroylocalstorage"; + public static final String FORCE_CONVERT_TO_POOL = "forceconverttopool"; + public static final String FORCE_DELETE_HOST = "forcedeletehost"; public static final String FORCE_MS_TO_IMPORT_VM_FILES = "forcemstoimportvmfiles"; public static final String FORCE_UPDATE_OS_TYPE = "forceupdateostype"; @@ -575,6 +584,7 @@ public class ApiConstants { public static final String SUITABLE_FOR_VM = "suitableforvirtualmachine"; public static final String SUPPORTS_STORAGE_SNAPSHOT = "supportsstoragesnapshot"; public static final String TARGET_IQN = "targetiqn"; + public static final String TASKS_FILTER = "tasksfilter"; public static final String TEMPLATE_FILTER = "templatefilter"; public static final String TEMPLATE_ID = "templateid"; public static final String TEMPLATE_IDS = "templateids"; @@ -1154,6 +1164,7 @@ public class ApiConstants { public static final String OVM3_CLUSTER = "ovm3cluster"; public static final String OVM3_VIP = "ovm3vip"; public static final String CLEAN_UP_DETAILS = "cleanupdetails"; + public static final String CLEAN_UP_EXTERNAL_DETAILS = "cleanupexternaldetails"; public static final String CLEAN_UP_PARAMETERS = "cleanupparameters"; public static final String VIRTUAL_SIZE = "virtualsize"; public static final String NETSCALER_CONTROLCENTER_ID = "netscalercontrolcenterid"; diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/autoscale/CreateCounterCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/autoscale/CreateCounterCmd.java index 7fa66ffff1f..013d0f966dd 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/autoscale/CreateCounterCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/autoscale/CreateCounterCmd.java @@ -17,6 +17,7 @@ package org.apache.cloudstack.api.command.admin.autoscale; +import org.apache.cloudstack.context.CallContext; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiCommandResourceType; @@ -89,9 +90,6 @@ public class CreateCounterCmd extends BaseAsyncCreateCmd { if (ctr != null) { this.setEntityId(ctr.getId()); this.setEntityUuid(ctr.getUuid()); - CounterResponse response = _responseGenerator.createCounterResponse(ctr); - response.setResponseName(getCommandName()); - this.setResponseObject(response); } else { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to create Counter with name " + getName()); } @@ -99,6 +97,11 @@ public class CreateCounterCmd extends BaseAsyncCreateCmd { @Override public void execute() { + CallContext.current().setEventDetails("Counter ID: " + getEntityId()); + Counter ctr = _autoScaleService.getCounter(getEntityId()); + CounterResponse response = _responseGenerator.createCounterResponse(ctr); + response.setResponseName(getCommandName()); + this.setResponseObject(response); } @Override diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/host/UpdateHostCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/host/UpdateHostCmd.java index 9baea58b7b5..86f002b9b7d 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/host/UpdateHostCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/host/UpdateHostCmd.java @@ -72,6 +72,14 @@ public class UpdateHostCmd extends BaseCmd { @Parameter(name = ApiConstants.EXTERNAL_DETAILS, type = CommandType.MAP, description = "Details in key/value pairs using format externaldetails[i].keyname=keyvalue. Example: externaldetails[0].endpoint.url=urlvalue", since = "4.21.0") protected Map externalDetails; + @Parameter(name = ApiConstants.CLEAN_UP_EXTERNAL_DETAILS, + type = CommandType.BOOLEAN, + description = "Optional boolean field, which indicates if external details should be cleaned up or not " + + "(If set to true, external details removed for this host, externaldetails field ignored; " + + "if false or not set, no action)", + since = "4.22.0") + protected Boolean cleanupExternalDetails; + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -112,6 +120,10 @@ public class UpdateHostCmd extends BaseCmd { return convertExternalDetailsToMap(externalDetails); } + public boolean isCleanupExternalDetails() { + return Boolean.TRUE.equals(cleanupExternalDetails); + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/offering/CreateDiskOfferingCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/offering/CreateDiskOfferingCmd.java index c46e4cd6b44..557c76d63c3 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/offering/CreateDiskOfferingCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/offering/CreateDiskOfferingCmd.java @@ -151,7 +151,7 @@ public class CreateDiskOfferingCmd extends BaseCmd { @Parameter(name = ApiConstants.CACHE_MODE, type = CommandType.STRING, required = false, - description = "the cache mode to use for this disk offering. none, writeback or writethrough", + description = "the cache mode to use for this disk offering. none, writeback, writethrough or hypervisor default. If the hypervisor default cache mode is used on other hypervisors than KVM, it will fall back to none cache mode", since = "4.14") private String cacheMode; diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/offering/CreateServiceOfferingCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/offering/CreateServiceOfferingCmd.java index 3d20ed50a5d..ec109a2a4f3 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/offering/CreateServiceOfferingCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/offering/CreateServiceOfferingCmd.java @@ -190,7 +190,7 @@ public class CreateServiceOfferingCmd extends BaseCmd { @Parameter(name = ApiConstants.CACHE_MODE, type = CommandType.STRING, required = false, - description = "the cache mode to use for this disk offering. none, writeback or writethrough", + description = "the cache mode to use for this disk offering. none, writeback, writethrough or hypervisor default. If the hypervisor default cache mode is used on other hypervisors than KVM, it will fall back to none cache mode", since = "4.14") private String cacheMode; diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/offering/UpdateServiceOfferingCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/offering/UpdateServiceOfferingCmd.java index 7f66ac7058a..9d973dfc524 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/offering/UpdateServiceOfferingCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/offering/UpdateServiceOfferingCmd.java @@ -101,6 +101,14 @@ public class UpdateServiceOfferingCmd extends BaseCmd { since = "4.21.0") private Map externalDetails; + @Parameter(name = ApiConstants.CLEAN_UP_EXTERNAL_DETAILS, + type = CommandType.BOOLEAN, + description = "Optional boolean field, which indicates if external details should be cleaned up or not " + + "(If set to true, external details removed for this offering, externaldetails field ignored; " + + "if false or not set, no action)", + since = "4.22.0") + protected Boolean cleanupExternalDetails; + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -205,6 +213,10 @@ public class UpdateServiceOfferingCmd extends BaseCmd { return convertExternalDetailsToMap(externalDetails); } + public boolean isCleanupExternalDetails() { + return Boolean.TRUE.equals(cleanupExternalDetails); + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/UpdateStoragePoolCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/UpdateStoragePoolCmd.java index f2d7bbeb189..6f522fe1e8c 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/UpdateStoragePoolCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/storage/UpdateStoragePoolCmd.java @@ -153,6 +153,8 @@ public class UpdateStoragePoolCmd extends BaseCmd { if (ObjectUtils.anyNotNull(name, capacityIops, capacityBytes, url, isTagARule, tags) || MapUtils.isNotEmpty(details)) { result = _storageService.updateStoragePool(this); + } else { + result = _storageService.getStoragePool(getId()); } if (enabled != null) { diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/usage/ListTrafficTypesCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/usage/ListTrafficTypesCmd.java index d106a736fca..c204c67d465 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/usage/ListTrafficTypesCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/usage/ListTrafficTypesCmd.java @@ -26,14 +26,13 @@ import org.apache.cloudstack.api.BaseListCmd; import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.response.ListResponse; import org.apache.cloudstack.api.response.PhysicalNetworkResponse; -import org.apache.cloudstack.api.response.ProviderResponse; import org.apache.cloudstack.api.response.TrafficTypeResponse; import com.cloud.network.PhysicalNetworkTrafficType; import com.cloud.user.Account; import com.cloud.utils.Pair; -@APICommand(name = "listTrafficTypes", description = "Lists traffic types of a given physical network.", responseObject = ProviderResponse.class, since = "3.0.0", +@APICommand(name = "listTrafficTypes", description = "Lists traffic types of a given physical network.", responseObject = TrafficTypeResponse.class, since = "3.0.0", requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) public class ListTrafficTypesCmd extends BaseListCmd { diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/vm/ImportVmCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/vm/ImportVmCmd.java index db43b53ab9a..f7940460d6c 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/vm/ImportVmCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/vm/ImportVmCmd.java @@ -159,6 +159,18 @@ public class ImportVmCmd extends ImportUnmanagedInstanceCmd { description = "(only for importing VMs from VMware to KVM) optional - if true, forces MS to export OVF from VMware to temporary storage, else uses KVM Host if ovftool is available, falls back to MS if not.") private Boolean forceMsToImportVmFiles; + @Parameter(name = ApiConstants.EXTRA_PARAMS, + type = CommandType.STRING, + since = "4.22", + description = "(only for importing VMs from VMware to KVM) optional - extra parameters to be passed on the virt-v2v command, if allowed by the administrator") + private String extraParams; + + @Parameter(name = ApiConstants.FORCE_CONVERT_TO_POOL, + type = CommandType.BOOLEAN, + since = "4.22", + description = "(only for importing VMs from VMware to KVM) optional - if true, forces virt-v2v conversions to write directly on the provided storage pool (avoid using temporary conversion pool).") + private Boolean forceConvertToPool; + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -248,6 +260,14 @@ public class ImportVmCmd extends ImportUnmanagedInstanceCmd { return EventTypes.EVENT_VM_IMPORT; } + public String getExtraParams() { + return extraParams; + } + + public boolean getForceConvertToPool() { + return BooleanUtils.toBooleanDefaultIfNull(forceConvertToPool, false); + } + @Override public String getEventDescription() { String vmName = getName(); diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/vm/ListImportVMTasksCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/vm/ListImportVMTasksCmd.java new file mode 100644 index 00000000000..94b547ff426 --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/vm/ListImportVMTasksCmd.java @@ -0,0 +1,116 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.api.command.admin.vm; + +import com.cloud.exception.ConcurrentOperationException; +import com.cloud.exception.InsufficientCapacityException; +import com.cloud.exception.NetworkRuleConflictException; +import com.cloud.exception.ResourceAllocationException; +import com.cloud.exception.ResourceUnavailableException; +import com.cloud.user.Account; +import org.apache.cloudstack.acl.RoleType; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ResponseObject; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.AccountResponse; +import org.apache.cloudstack.api.response.HostResponse; +import org.apache.cloudstack.api.response.ImportVMTaskResponse; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.ZoneResponse; +import org.apache.cloudstack.context.CallContext; +import org.apache.cloudstack.vm.ImportVmTasksManager; + +import javax.inject.Inject; + +@APICommand(name = "listImportVmTasks", + description = "List running import virtual machine tasks from a unmanaged hosts into CloudStack", + responseObject = ImportVMTaskResponse.class, + responseView = ResponseObject.ResponseView.Full, + requestHasSensitiveInfo = false, + authorized = {RoleType.Admin}, + since = "4.22") +public class ListImportVMTasksCmd extends BaseListCmd { + + @Inject + public ImportVmTasksManager importVmTasksManager; + + @Parameter(name = ApiConstants.ZONE_ID, + type = CommandType.UUID, + entityType = ZoneResponse.class, + required = true, + description = "the zone ID") + private Long zoneId; + + @Parameter(name = ApiConstants.ACCOUNT_ID, + type = CommandType.UUID, + entityType = AccountResponse.class, + description = "the ID of the Account") + private Long accountId; + + @Parameter(name = ApiConstants.VCENTER, + type = CommandType.STRING, + description = "The name/ip of vCenter. Make sure it is IP address or full qualified domain name for host running vCenter server.") + private String vcenter; + + @Parameter(name = ApiConstants.CONVERT_INSTANCE_HOST_ID, + type = CommandType.UUID, + entityType = HostResponse.class, + description = "Conversion host of the importing task") + private Long convertHostId; + + @Parameter(name = ApiConstants.TASKS_FILTER, type = CommandType.STRING, description = "Filter tasks by state, valid options are: All, Running, Completed, Failed") + private String tasksFilter; + + public Long getZoneId() { + return zoneId; + } + + public Long getAccountId() { + return accountId; + } + + public String getVcenter() { + return vcenter; + } + + public Long getConvertHostId() { + return convertHostId; + } + + public String getTasksFilter() { + return tasksFilter; + } + + @Override + public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException, NetworkRuleConflictException { + ListResponse response = importVmTasksManager.listImportVMTasks(this); + response.setResponseName(getCommandName()); + setResponseObject(response); + } + + @Override + public long getEntityOwnerId() { + Account account = CallContext.current().getCallingAccount(); + if (account != null) { + return account.getId(); + } + return Account.ACCOUNT_ID_SYSTEM; + } +} diff --git a/api/src/main/java/org/apache/cloudstack/api/command/admin/vm/UnmanageVMInstanceCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/admin/vm/UnmanageVMInstanceCmd.java index bbcb8840f66..2c60b574126 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/admin/vm/UnmanageVMInstanceCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/admin/vm/UnmanageVMInstanceCmd.java @@ -27,6 +27,7 @@ import com.cloud.exception.ResourceAllocationException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.user.Account; import com.cloud.uservm.UserVm; +import com.cloud.utils.Pair; import com.cloud.vm.VirtualMachine; import org.apache.cloudstack.acl.RoleType; import org.apache.cloudstack.api.APICommand; @@ -36,10 +37,12 @@ import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.BaseAsyncCmd; import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.HostResponse; import org.apache.cloudstack.api.response.UnmanageVMInstanceResponse; import org.apache.cloudstack.api.response.UserVmResponse; import org.apache.cloudstack.context.CallContext; import org.apache.cloudstack.vm.UnmanagedVMsManager; +import org.apache.commons.lang3.BooleanUtils; import javax.inject.Inject; @@ -65,6 +68,20 @@ public class UnmanageVMInstanceCmd extends BaseAsyncCmd { description = "The ID of the virtual machine to unmanage") private Long vmId; + @Parameter(name = ApiConstants.HOST_ID, type = CommandType.UUID, + entityType = HostResponse.class, required = false, + description = "ID of the host which will be used for unmanaging the Instance. " + + "Applicable only for KVM hypervisor and stopped Instances. Domain XML will be stored on this host.", + since = "4.22.0") + private Long hostId; + + @Parameter(name = ApiConstants.FORCED, + type = CommandType.BOOLEAN, + required = false, + description = "Force unmanaging Instance with config drive. Applicable only for KVM Hypervisor.", + since = "4.22.0") + private Boolean forced; + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -83,6 +100,18 @@ public class UnmanageVMInstanceCmd extends BaseAsyncCmd { return "unmanaging VM. VM ID = " + vmId; } + public Long getHostId() { + return hostId; + } + + public void setHostId(Long hostId) { + this.hostId = hostId; + } + + public Boolean isForced() { + return BooleanUtils.isTrue(forced); + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -93,9 +122,10 @@ public class UnmanageVMInstanceCmd extends BaseAsyncCmd { UnmanageVMInstanceResponse response = new UnmanageVMInstanceResponse(); try { CallContext.current().setEventDetails("VM ID = " + vmId); - boolean result = unmanagedVMsManager.unmanageVMInstance(vmId); - response.setSuccess(result); - if (result) { + Pair result = unmanagedVMsManager.unmanageVMInstance(vmId, hostId, isForced()); + if (result.first()) { + response.setSuccess(true); + response.setHostId(result.second()); response.setDetails("VM unmanaged successfully"); } } catch (Exception e) { @@ -124,5 +154,4 @@ public class UnmanageVMInstanceCmd extends BaseAsyncCmd { public Long getApiResourceId() { return vmId; } - } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/backup/ListBackupScheduleCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/backup/ListBackupScheduleCmd.java index fa6e3ea5d45..d68e4a9296e 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/backup/ListBackupScheduleCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/backup/ListBackupScheduleCmd.java @@ -24,7 +24,7 @@ import org.apache.cloudstack.acl.RoleType; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.ApiErrorCode; -import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.BaseListProjectAndAccountResourcesCmd; import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.response.BackupScheduleResponse; @@ -39,7 +39,6 @@ import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.NetworkRuleConflictException; import com.cloud.exception.ResourceAllocationException; import com.cloud.exception.ResourceUnavailableException; -import com.cloud.utils.exception.CloudRuntimeException; import java.util.ArrayList; import java.util.List; @@ -48,10 +47,10 @@ import java.util.List; description = "List backup schedule of a VM", responseObject = BackupScheduleResponse.class, since = "4.14.0", authorized = {RoleType.Admin, RoleType.ResourceAdmin, RoleType.DomainAdmin, RoleType.User}) -public class ListBackupScheduleCmd extends BaseCmd { +public class ListBackupScheduleCmd extends BaseListProjectAndAccountResourcesCmd { @Inject - private BackupManager backupManager; + BackupManager backupManager; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// @@ -60,10 +59,16 @@ public class ListBackupScheduleCmd extends BaseCmd { @Parameter(name = ApiConstants.VIRTUAL_MACHINE_ID, type = CommandType.UUID, entityType = UserVmResponse.class, - required = true, description = "ID of the VM") private Long vmId; + @Parameter(name = ApiConstants.ID, + type = CommandType.UUID, + entityType = BackupScheduleResponse.class, + description = "the ID of the backup schedule", + since = "4.22.0") + private Long id; + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -72,6 +77,10 @@ public class ListBackupScheduleCmd extends BaseCmd { return vmId; } + public Long getId() { + return id; + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -79,19 +88,18 @@ public class ListBackupScheduleCmd extends BaseCmd { @Override public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException, NetworkRuleConflictException { try{ - List schedules = backupManager.listBackupSchedule(getVmId()); + List schedules = backupManager.listBackupSchedules(this); ListResponse response = new ListResponse<>(); List scheduleResponses = new ArrayList<>(); + if (!CollectionUtils.isNullOrEmpty(schedules)) { for (BackupSchedule schedule : schedules) { scheduleResponses.add(_responseGenerator.createBackupScheduleResponse(schedule)); } - response.setResponses(scheduleResponses, schedules.size()); - response.setResponseName(getCommandName()); - setResponseObject(response); - } else { - throw new CloudRuntimeException("No backup schedule exists for the VM"); } + response.setResponses(scheduleResponses, schedules.size()); + response.setResponseName(getCommandName()); + setResponseObject(response); } catch (Exception e) { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, e.getMessage()); } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/backup/repository/AddBackupRepositoryCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/backup/repository/AddBackupRepositoryCmd.java index 5d0c838bc37..64998a74954 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/backup/repository/AddBackupRepositoryCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/backup/repository/AddBackupRepositoryCmd.java @@ -63,12 +63,14 @@ public class AddBackupRepositoryCmd extends BaseCmd { type = CommandType.UUID, entityType = ZoneResponse.class, required = true, - description = "ID of the zone where the backup repository is to be added") + description = "ID of the zone where the backup repository is to be added for taking backups") private Long zoneId; @Parameter(name = ApiConstants.CAPACITY_BYTES, type = CommandType.LONG, description = "capacity of this backup repository") private Long capacityBytes; + @Parameter(name = ApiConstants.CROSS_ZONE_INSTANCE_CREATION, type = CommandType.BOOLEAN, description = "backups on this repository can be used to create Instances on all Zones", since = "4.22.0") + private Boolean crossZoneInstanceCreation; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// @@ -109,6 +111,10 @@ public class AddBackupRepositoryCmd extends BaseCmd { return capacityBytes; } + public Boolean crossZoneInstanceCreationEnabled() { + return crossZoneInstanceCreation; + } + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/backup/repository/UpdateBackupRepositoryCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/backup/repository/UpdateBackupRepositoryCmd.java new file mode 100644 index 00000000000..5ffd79e497e --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/backup/repository/UpdateBackupRepositoryCmd.java @@ -0,0 +1,116 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package org.apache.cloudstack.api.command.user.backup.repository; + +import org.apache.cloudstack.acl.RoleType; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiErrorCode; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.BackupRepositoryResponse; +import org.apache.cloudstack.backup.BackupRepository; +import org.apache.cloudstack.backup.BackupRepositoryService; +import org.apache.cloudstack.context.CallContext; + +import javax.inject.Inject; + +@APICommand(name = "updateBackupRepository", + description = "Update a backup repository", + responseObject = BackupRepositoryResponse.class, since = "4.22.0", + authorized = {RoleType.Admin}) +public class UpdateBackupRepositoryCmd extends BaseCmd { + + @Inject + private BackupRepositoryService backupRepositoryService; + + ///////////////////////////////////////////////////// + //////////////// API parameters ///////////////////// + ///////////////////////////////////////////////////// + + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, required = true, entityType = BackupRepositoryResponse.class, description = "ID of the backup repository") + private Long id; + + @Parameter(name = ApiConstants.NAME, type = CommandType.STRING, description = "name of the backup repository") + private String name; + + @Parameter(name = ApiConstants.ADDRESS, type = CommandType.STRING, description = "address of the backup repository") + private String address; + + @Parameter(name = ApiConstants.MOUNT_OPTIONS, type = CommandType.STRING, description = "shared storage mount options") + private String mountOptions; + + @Parameter(name = ApiConstants.CROSS_ZONE_INSTANCE_CREATION, type = CommandType.BOOLEAN, description = "backups in this repository can be used to create Instances on all Zones") + private Boolean crossZoneInstanceCreation; + + ///////////////////////////////////////////////////// + /////////////////// Accessors /////////////////////// + ///////////////////////////////////////////////////// + + public BackupRepositoryService getBackupRepositoryService() { + return backupRepositoryService; + } + + public Long getId() { + return id; + } + + public String getName() { + return name; + } + + public String getAddress() { + return address; + } + + public String getMountOptions() { + return mountOptions == null ? "" : mountOptions; + } + + public Boolean crossZoneInstanceCreationEnabled() { + return crossZoneInstanceCreation; + } + + ///////////////////////////////////////////////////// + ///////////////////////////////////////////////////// + /////////////////// Accessors /////////////////////// + ///////////////////////////////////////////////////// + + @Override + public void execute() { + try { + BackupRepository result = backupRepositoryService.updateBackupRepository(this); + if (result != null) { + BackupRepositoryResponse response = _responseGenerator.createBackupRepositoryResponse(result); + response.setResponseName(getCommandName()); + this.setResponseObject(response); + } else { + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to update the backup repository"); + } + } catch (Exception ex4) { + throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex4.getMessage()); + } + + } + + @Override + public long getEntityOwnerId() { + return CallContext.current().getCallingAccount().getId(); + } +} diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/config/ListCapabilitiesCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/config/ListCapabilitiesCmd.java index e73bb97a21b..ed1bd7b063b 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/config/ListCapabilitiesCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/config/ListCapabilitiesCmd.java @@ -75,6 +75,7 @@ public class ListCapabilitiesCmd extends BaseCmd { response.setInstanceLeaseEnabled((Boolean) capabilities.get(ApiConstants.INSTANCE_LEASE_ENABLED)); response.setExtensionsPath((String)capabilities.get(ApiConstants.EXTENSIONS_PATH)); response.setDynamicScalingEnabled((Boolean) capabilities.get(ApiConstants.DYNAMIC_SCALING_ENABLED)); + response.setAdditionalConfigEnabled((Boolean) capabilities.get(ApiConstants.ADDITONAL_CONFIG_ENABLED)); response.setObjectName("capability"); response.setResponseName(getCommandName()); this.setResponseObject(response); diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/consoleproxy/CreateConsoleEndpointCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/consoleproxy/CreateConsoleEndpointCmd.java index 63b47e163b6..b84f8ce3489 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/consoleproxy/CreateConsoleEndpointCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/consoleproxy/CreateConsoleEndpointCmd.java @@ -35,6 +35,7 @@ import org.apache.cloudstack.consoleproxy.ConsoleAccessManager; import org.apache.cloudstack.context.CallContext; import org.apache.cloudstack.utils.consoleproxy.ConsoleAccessUtils; import org.apache.commons.collections.MapUtils; +import org.apache.commons.lang3.ObjectUtils; import javax.inject.Inject; import java.util.Map; @@ -86,6 +87,10 @@ public class CreateConsoleEndpointCmd extends BaseCmd { } private ConsoleEndpointWebsocketResponse createWebsocketResponse(ConsoleEndpoint endpoint) { + if (ObjectUtils.allNull(endpoint.getWebsocketHost(), endpoint.getWebsocketPort(), endpoint.getWebsocketPath(), + endpoint.getWebsocketToken(), endpoint.getWebsocketExtra())) { + return null; + } ConsoleEndpointWebsocketResponse wsResponse = new ConsoleEndpointWebsocketResponse(); wsResponse.setHost(endpoint.getWebsocketHost()); wsResponse.setPort(endpoint.getWebsocketPort()); diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/iso/GetUploadParamsForIsoCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/iso/GetUploadParamsForIsoCmd.java index 01a47f22b72..d52e53d3bb4 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/iso/GetUploadParamsForIsoCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/iso/GetUploadParamsForIsoCmd.java @@ -104,6 +104,29 @@ public class GetUploadParamsForIsoCmd extends AbstractGetUploadParamsCmd { return osTypeId; } + public void setBootable(Boolean bootable) { + this.bootable = bootable; + } + + public void setDisplayText(String displayText) { + this.displayText = displayText; + } + + public void setFeatured(Boolean featured) { + this.featured = featured; + } + + public void setPublicIso(Boolean publicIso) { + this.publicIso = publicIso; + } + + public void setExtractable(Boolean extractable) { + this.extractable = extractable; + } + + public void setOsTypeId(Long osTypeId) { + this.osTypeId = osTypeId; + } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/UpdateLBHealthCheckPolicyCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/UpdateLBHealthCheckPolicyCmd.java index fdd98fc3a0a..8609c87d8f1 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/UpdateLBHealthCheckPolicyCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/UpdateLBHealthCheckPolicyCmd.java @@ -63,7 +63,7 @@ public class UpdateLBHealthCheckPolicyCmd extends BaseAsyncCustomIdCmd{ @Override public String getEventDescription() { - return "Update load balancer health check policy ID= " + id; + return "Update load balancer health check policy ID = " + id; } @Override diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/UpdateLBStickinessPolicyCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/UpdateLBStickinessPolicyCmd.java index b2137cf262d..21c18d584ab 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/UpdateLBStickinessPolicyCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/loadbalancer/UpdateLBStickinessPolicyCmd.java @@ -62,7 +62,7 @@ public class UpdateLBStickinessPolicyCmd extends BaseAsyncCustomIdCmd{ @Override public String getEventDescription() { - return "Update load balancer stickiness policy ID= " + id; + return "Update load balancer stickiness policy ID = " + id; } @Override diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/network/ListNetworksCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/network/ListNetworksCmd.java index 0e8425b14b4..0eb5ddc5ebe 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/network/ListNetworksCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/network/ListNetworksCmd.java @@ -53,6 +53,9 @@ public class ListNetworksCmd extends BaseListRetrieveOnlyResourceCountCmd implem @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = NetworkResponse.class, description = "list networks by ID") private Long id; + @Parameter(name = ApiConstants.NAME, type = CommandType.STRING, description = "list networks by name", since = "4.22.0") + private String name; + @Parameter(name = ApiConstants.ZONE_ID, type = CommandType.UUID, entityType = ZoneResponse.class, description = "the zone ID of the network") private Long zoneId; @@ -125,6 +128,10 @@ public class ListNetworksCmd extends BaseListRetrieveOnlyResourceCountCmd implem return id; } + public String getName() { + return name; + } + public Long getZoneId() { return zoneId; } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/snapshot/ListSnapshotPoliciesCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/snapshot/ListSnapshotPoliciesCmd.java index 126a4080e6d..f4dfbe58cf2 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/snapshot/ListSnapshotPoliciesCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/snapshot/ListSnapshotPoliciesCmd.java @@ -23,7 +23,7 @@ import org.apache.cloudstack.acl.RoleType; import org.apache.cloudstack.api.APICommand; import org.apache.cloudstack.api.ApiConstants; -import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.BaseListProjectAndAccountResourcesCmd; import org.apache.cloudstack.api.Parameter; import org.apache.cloudstack.api.response.ListResponse; import org.apache.cloudstack.api.response.SnapshotPolicyResponse; @@ -34,7 +34,7 @@ import com.cloud.utils.Pair; @APICommand(name = "listSnapshotPolicies", description = "Lists snapshot policies.", responseObject = SnapshotPolicyResponse.class, requestHasSensitiveInfo = false, responseHasSensitiveInfo = false) -public class ListSnapshotPoliciesCmd extends BaseListCmd { +public class ListSnapshotPoliciesCmd extends BaseListProjectAndAccountResourcesCmd { ///////////////////////////////////////////////////// @@ -69,13 +69,14 @@ public class ListSnapshotPoliciesCmd extends BaseListCmd { public Long getId() { return id; } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @Override public void execute() { - Pair, Integer> result = _snapshotService.listPoliciesforVolume(this); + Pair, Integer> result = _snapshotService.listSnapshotPolicies(this); ListResponse response = new ListResponse(); List policyResponses = new ArrayList(); for (SnapshotPolicy policy : result.first()) { diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/template/GetUploadParamsForTemplateCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/template/GetUploadParamsForTemplateCmd.java index 330224a6055..2472a03b890 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/template/GetUploadParamsForTemplateCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/template/GetUploadParamsForTemplateCmd.java @@ -104,6 +104,11 @@ public class GetUploadParamsForTemplateCmd extends AbstractGetUploadParamsCmd { description = "if true, the templates would be available for deploying CKS clusters", since = "4.21.0") protected Boolean forCks; + @Parameter(name = ApiConstants.TEMPLATE_TYPE, type = CommandType.STRING, + description = "the type of the template. Valid options are: USER/VNF (for all users) and SYSTEM/ROUTING/BUILTIN (for admins only).", + since = "4.22.0") + private String templateType; + public String getDisplayText() { return StringUtils.isBlank(displayText) ? getName() : displayText; } @@ -181,6 +186,10 @@ public class GetUploadParamsForTemplateCmd extends AbstractGetUploadParamsCmd { return CPU.CPUArch.fromType(arch); } + public String getTemplateType() { + return templateType; + } + @Override public void execute() throws ServerApiException { validateRequest(); diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/AddVpnUserCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/AddVpnUserCmd.java index 59ba7e94b04..781edff52e3 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/AddVpnUserCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/AddVpnUserCmd.java @@ -28,7 +28,6 @@ import org.apache.cloudstack.api.response.ProjectResponse; import org.apache.cloudstack.api.response.VpnUsersResponse; import org.apache.cloudstack.context.CallContext; -import com.cloud.domain.Domain; import com.cloud.event.EventTypes; import com.cloud.network.VpnUser; import com.cloud.user.Account; @@ -110,7 +109,6 @@ public class AddVpnUserCmd extends BaseAsyncCreateCmd { @Override public void execute() { VpnUser vpnUser = _entityMgr.findById(VpnUser.class, getEntityId()); - Account account = _entityMgr.findById(Account.class, vpnUser.getAccountId()); try { if (!_ravService.applyVpnUsers(vpnUser.getAccountId(), userName)) { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add vpn user"); @@ -118,24 +116,10 @@ public class AddVpnUserCmd extends BaseAsyncCreateCmd { } catch (Exception ex) { throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, ex.getMessage()); } - - VpnUsersResponse vpnResponse = new VpnUsersResponse(); - vpnResponse.setId(vpnUser.getUuid()); - vpnResponse.setUserName(vpnUser.getUsername()); - vpnResponse.setAccountName(account.getAccountName()); // re-retrieve the vpnuser, as the call to `applyVpnUsers` might have changed the state vpnUser = _entityMgr.findById(VpnUser.class, getEntityId()); - vpnResponse.setState(vpnUser.getState().toString()); - - Domain domain = _entityMgr.findById(Domain.class, account.getDomainId()); - if (domain != null) { - vpnResponse.setDomainId(domain.getUuid()); - vpnResponse.setDomainName(domain.getName()); - vpnResponse.setDomainPath(domain.getPath()); - } - + VpnUsersResponse vpnResponse = _responseGenerator.createVpnUserResponse(vpnUser); vpnResponse.setResponseName(getCommandName()); - vpnResponse.setObjectName("vpnuser"); setResponseObject(vpnResponse); } diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/UpdateVpnConnectionCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/UpdateVpnConnectionCmd.java index 62dd6167b75..efa809a2d78 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/UpdateVpnConnectionCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/UpdateVpnConnectionCmd.java @@ -66,7 +66,7 @@ public class UpdateVpnConnectionCmd extends BaseAsyncCustomIdCmd { @Override public String getEventDescription() { - return "Updating site-to-site VPN connection id= " + id; + return "Updating site-to-site VPN connection ID = " + id; } @Override diff --git a/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/UpdateVpnGatewayCmd.java b/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/UpdateVpnGatewayCmd.java index 9fe5ae0480f..e614920d8de 100644 --- a/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/UpdateVpnGatewayCmd.java +++ b/api/src/main/java/org/apache/cloudstack/api/command/user/vpn/UpdateVpnGatewayCmd.java @@ -63,7 +63,7 @@ public class UpdateVpnGatewayCmd extends BaseAsyncCustomIdCmd { @Override public String getEventDescription() { - return "Update site-to-site VPN gateway id= " + id; + return "Update site-to-site VPN gateway ID = " + id; } @Override diff --git a/api/src/main/java/org/apache/cloudstack/api/response/AccountResponse.java b/api/src/main/java/org/apache/cloudstack/api/response/AccountResponse.java index 3c99e2cbec6..a09ef89f1b6 100644 --- a/api/src/main/java/org/apache/cloudstack/api/response/AccountResponse.java +++ b/api/src/main/java/org/apache/cloudstack/api/response/AccountResponse.java @@ -569,7 +569,7 @@ public class AccountResponse extends BaseResponse implements ResourceLimitAndCou @Override public void setVpcLimit(String vpcLimit) { - this.vpcLimit = networkLimit; + this.vpcLimit = vpcLimit; } @Override diff --git a/api/src/main/java/org/apache/cloudstack/api/response/BackupOfferingResponse.java b/api/src/main/java/org/apache/cloudstack/api/response/BackupOfferingResponse.java index 0e895fa4e96..4120f68d9da 100644 --- a/api/src/main/java/org/apache/cloudstack/api/response/BackupOfferingResponse.java +++ b/api/src/main/java/org/apache/cloudstack/api/response/BackupOfferingResponse.java @@ -61,6 +61,10 @@ public class BackupOfferingResponse extends BaseResponse { @Param(description = "zone name") private String zoneName; + @SerializedName(ApiConstants.CROSS_ZONE_INSTANCE_CREATION) + @Param(description = "the backups with this offering can be used to create Instances on all Zones", since = "4.22.0") + private Boolean crossZoneInstanceCreation; + @SerializedName(ApiConstants.CREATED) @Param(description = "the date this backup offering was created") private Date created; @@ -97,6 +101,10 @@ public class BackupOfferingResponse extends BaseResponse { this.zoneName = zoneName; } + public void setCrossZoneInstanceCreation(Boolean crossZoneInstanceCreation) { + this.crossZoneInstanceCreation = crossZoneInstanceCreation; + } + public void setCreated(Date created) { this.created = created; } diff --git a/api/src/main/java/org/apache/cloudstack/api/response/BackupRepositoryResponse.java b/api/src/main/java/org/apache/cloudstack/api/response/BackupRepositoryResponse.java index 0db51f04034..327bbae0051 100644 --- a/api/src/main/java/org/apache/cloudstack/api/response/BackupRepositoryResponse.java +++ b/api/src/main/java/org/apache/cloudstack/api/response/BackupRepositoryResponse.java @@ -61,6 +61,10 @@ public class BackupRepositoryResponse extends BaseResponse { @Param(description = "capacity of the backup repository") private Long capacityBytes; + @SerializedName(ApiConstants.CROSS_ZONE_INSTANCE_CREATION) + @Param(description = "the backups in this repository can be used to create Instances on all Zones") + private Boolean crossZoneInstanceCreation; + @SerializedName("created") @Param(description = "the date and time the backup repository was added") private Date created; @@ -132,6 +136,14 @@ public class BackupRepositoryResponse extends BaseResponse { this.capacityBytes = capacityBytes; } + public Boolean getCrossZoneInstanceCreation() { + return crossZoneInstanceCreation; + } + + public void setCrossZoneInstanceCreation(Boolean crossZoneInstanceCreation) { + this.crossZoneInstanceCreation = crossZoneInstanceCreation; + } + public Date getCreated() { return created; } diff --git a/api/src/main/java/org/apache/cloudstack/api/response/BackupResponse.java b/api/src/main/java/org/apache/cloudstack/api/response/BackupResponse.java index 0ae558ac803..b9eca67d9a8 100644 --- a/api/src/main/java/org/apache/cloudstack/api/response/BackupResponse.java +++ b/api/src/main/java/org/apache/cloudstack/api/response/BackupResponse.java @@ -123,6 +123,10 @@ public class BackupResponse extends BaseResponse { @Param(description = "The backup offering corresponding to this backup was removed from the VM", since = "4.21.0") private Boolean vmOfferingRemoved; + @SerializedName(ApiConstants.IS_BACKUP_VM_EXPUNGED) + @Param(description = "Indicates whether the VM from which the backup was taken is expunged or not", since = "4.22.0") + private Boolean isVmExpunged; + public String getId() { return id; } @@ -306,4 +310,8 @@ public class BackupResponse extends BaseResponse { public void setVmOfferingRemoved(Boolean vmOfferingRemoved) { this.vmOfferingRemoved = vmOfferingRemoved; } + + public void setVmExpunged(Boolean isVmExpunged) { + this.isVmExpunged = isVmExpunged; + } } diff --git a/api/src/main/java/org/apache/cloudstack/api/response/CapabilitiesResponse.java b/api/src/main/java/org/apache/cloudstack/api/response/CapabilitiesResponse.java index eb0daf75148..d2c71b5f352 100644 --- a/api/src/main/java/org/apache/cloudstack/api/response/CapabilitiesResponse.java +++ b/api/src/main/java/org/apache/cloudstack/api/response/CapabilitiesResponse.java @@ -149,6 +149,10 @@ public class CapabilitiesResponse extends BaseResponse { @Param(description = "true if dynamically scaling for instances is enabled", since = "4.21.0") private Boolean dynamicScalingEnabled; + @SerializedName(ApiConstants.ADDITONAL_CONFIG_ENABLED) + @Param(description = "true if additional configurations or extraconfig can be passed to Instances", since = "4.20.2") + private Boolean additionalConfigEnabled; + public void setSecurityGroupsEnabled(boolean securityGroupsEnabled) { this.securityGroupsEnabled = securityGroupsEnabled; } @@ -272,4 +276,8 @@ public class CapabilitiesResponse extends BaseResponse { public void setDynamicScalingEnabled(Boolean dynamicScalingEnabled) { this.dynamicScalingEnabled = dynamicScalingEnabled; } + + public void setAdditionalConfigEnabled(Boolean additionalConfigEnabled) { + this.additionalConfigEnabled = additionalConfigEnabled; + } } diff --git a/api/src/main/java/org/apache/cloudstack/api/response/GetUploadParamsResponse.java b/api/src/main/java/org/apache/cloudstack/api/response/GetUploadParamsResponse.java index b9be06ecc8f..00f7e7740c2 100644 --- a/api/src/main/java/org/apache/cloudstack/api/response/GetUploadParamsResponse.java +++ b/api/src/main/java/org/apache/cloudstack/api/response/GetUploadParamsResponse.java @@ -62,6 +62,10 @@ public class GetUploadParamsResponse extends BaseResponse { setObjectName("getuploadparams"); } + public UUID getId() { + return id; + } + public void setId(UUID id) { this.id = id; } diff --git a/api/src/main/java/org/apache/cloudstack/api/response/ImportVMTaskResponse.java b/api/src/main/java/org/apache/cloudstack/api/response/ImportVMTaskResponse.java new file mode 100644 index 00000000000..aa85554f567 --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/api/response/ImportVMTaskResponse.java @@ -0,0 +1,257 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// +package org.apache.cloudstack.api.response; + +import com.cloud.serializer.Param; +import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseResponse; + +import java.util.Date; + +public class ImportVMTaskResponse extends BaseResponse { + + @SerializedName(ApiConstants.ID) + @Param(description = "the ID of importing task") + private String id; + + @SerializedName(ApiConstants.ZONE_ID) + @Param(description = "the Zone ID") + private String zoneId; + + @SerializedName(ApiConstants.ZONE_NAME) + @Param(description = "the Zone name") + private String zoneName; + + @SerializedName(ApiConstants.ACCOUNT) + @Param(description = "the account name") + private String accountName; + + @SerializedName(ApiConstants.ACCOUNT_ID) + @Param(description = "the ID of account") + private String accountId; + + @SerializedName(ApiConstants.VIRTUAL_MACHINE_ID) + @Param(description = "the ID of the imported VM (after task is completed)") + private String virtualMachineId; + + @SerializedName(ApiConstants.DISPLAY_NAME) + @Param(description = "the display name of the importing VM") + private String displayName; + + @SerializedName(ApiConstants.STATE) + @Param(description = "the state of the importing VM task") + private String state; + + @SerializedName(ApiConstants.VCENTER) + @Param(description = "the vcenter name of the importing VM task") + private String vcenter; + + @SerializedName(ApiConstants.DATACENTER_NAME) + @Param(description = "the datacenter name of the importing VM task") + private String datacenterName; + + @SerializedName("sourcevmname") + @Param(description = "the source VM name") + private String sourceVMName; + + @SerializedName("step") + @Param(description = "the current step on the importing VM task") + private String step; + + @SerializedName("stepduration") + @Param(description = "the duration of the current step") + private String stepDuration; + + @SerializedName(ApiConstants.DURATION) + @Param(description = "the total task duration") + private String duration; + + @SerializedName(ApiConstants.DESCRIPTION) + @Param(description = "the current step description on the importing VM task") + private String description; + + @SerializedName(ApiConstants.CONVERT_INSTANCE_HOST_ID) + @Param(description = "the ID of the host on which the instance is being converted") + private String convertInstanceHostId; + + @SerializedName("convertinstancehostname") + @Param(description = "the name of the host on which the instance is being converted") + private String convertInstanceHostName; + + @SerializedName(ApiConstants.CREATED) + @Param(description = "the create date of the importing task") + private Date created; + + @SerializedName(ApiConstants.LAST_UPDATED) + @Param(description = "the last updated date of the importing task") + private Date lastUpdated; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getZoneId() { + return zoneId; + } + + public void setZoneId(String zoneId) { + this.zoneId = zoneId; + } + + public String getZoneName() { + return zoneName; + } + + public void setZoneName(String zoneName) { + this.zoneName = zoneName; + } + + public String getAccountName() { + return accountName; + } + + public void setAccountName(String accountName) { + this.accountName = accountName; + } + + public String getAccountId() { + return accountId; + } + + public void setAccountId(String accountId) { + this.accountId = accountId; + } + + public String getVirtualMachineId() { + return virtualMachineId; + } + + public void setVirtualMachineId(String virtualMachineId) { + this.virtualMachineId = virtualMachineId; + } + + public String getDisplayName() { + return displayName; + } + + public void setDisplayName(String displayName) { + this.displayName = displayName; + } + + public String getVcenter() { + return vcenter; + } + + public void setVcenter(String vcenter) { + this.vcenter = vcenter; + } + + public String getDatacenterName() { + return datacenterName; + } + + public void setDatacenterName(String datacenterName) { + this.datacenterName = datacenterName; + } + + public String getSourceVMName() { + return sourceVMName; + } + + public void setSourceVMName(String sourceVMName) { + this.sourceVMName = sourceVMName; + } + + public String getStep() { + return step; + } + + public void setStep(String step) { + this.step = step; + } + + public String getStepDuration() { + return stepDuration; + } + + public void setStepDuration(String stepDuration) { + this.stepDuration = stepDuration; + } + + public String getDuration() { + return duration; + } + + public void setDuration(String duration) { + this.duration = duration; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getConvertInstanceHostId() { + return convertInstanceHostId; + } + + public void setConvertInstanceHostId(String convertInstanceHostId) { + this.convertInstanceHostId = convertInstanceHostId; + } + + public String getConvertInstanceHostName() { + return convertInstanceHostName; + } + + public void setConvertInstanceHostName(String convertInstanceHostName) { + this.convertInstanceHostName = convertInstanceHostName; + } + + public Date getCreated() { + return created; + } + + public void setCreated(Date created) { + this.created = created; + } + + public Date getLastUpdated() { + return lastUpdated; + } + + public void setLastUpdated(Date lastUpdated) { + this.lastUpdated = lastUpdated; + } + + public String getState() { + return state; + } + + public void setState(String state) { + this.state = state; + } +} diff --git a/api/src/main/java/org/apache/cloudstack/api/response/RouterHealthCheckResultResponse.java b/api/src/main/java/org/apache/cloudstack/api/response/RouterHealthCheckResultResponse.java index 00f1e4e3bb0..96364d0190c 100644 --- a/api/src/main/java/org/apache/cloudstack/api/response/RouterHealthCheckResultResponse.java +++ b/api/src/main/java/org/apache/cloudstack/api/response/RouterHealthCheckResultResponse.java @@ -19,6 +19,7 @@ package org.apache.cloudstack.api.response; import java.util.Date; +import com.cloud.network.VirtualNetworkApplianceService.RouterHealthStatus; import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.BaseResponse; @@ -35,9 +36,13 @@ public class RouterHealthCheckResultResponse extends BaseResponse { private String checkType; @SerializedName(ApiConstants.SUCCESS) - @Param(description = "result of the health check") + @Param(description = "result of the health check if available") private boolean result; + @SerializedName(ApiConstants.STATUS) + @Param(description = "the result of the health check in enum form: {SUCCESS, FAILURE, WARNING, UNKNOWN}") + private RouterHealthStatus state; + @SerializedName(ApiConstants.LAST_UPDATED) @Param(description = "the date this VPC was created") private Date lastUpdated; @@ -54,10 +59,14 @@ public class RouterHealthCheckResultResponse extends BaseResponse { return checkType; } - public boolean getResult() { + public Boolean getResult() { return result; } + public RouterHealthStatus getState() { + return state; + } + public Date getLastUpdated() { return lastUpdated; } @@ -74,10 +83,14 @@ public class RouterHealthCheckResultResponse extends BaseResponse { this.checkType = checkType; } - public void setResult(boolean result) { + public void setResult(Boolean result) { this.result = result; } + public void setState(RouterHealthStatus state) { + this.state = state; + } + public void setLastUpdated(Date lastUpdated) { this.lastUpdated = lastUpdated; } diff --git a/api/src/main/java/org/apache/cloudstack/api/response/ServiceOfferingResponse.java b/api/src/main/java/org/apache/cloudstack/api/response/ServiceOfferingResponse.java index 4565a878b34..69f80b54010 100644 --- a/api/src/main/java/org/apache/cloudstack/api/response/ServiceOfferingResponse.java +++ b/api/src/main/java/org/apache/cloudstack/api/response/ServiceOfferingResponse.java @@ -197,7 +197,7 @@ public class ServiceOfferingResponse extends BaseResponseWithAnnotations { private Boolean isCustomized; @SerializedName("cacheMode") - @Param(description = "the cache mode to use for this disk offering. none, writeback or writethrough", since = "4.14") + @Param(description = "the cache mode to use for this disk offering. none, writeback, writethrough or hypervisor default", since = "4.14") private String cacheMode; @SerializedName("vspherestoragepolicy") diff --git a/api/src/main/java/org/apache/cloudstack/api/response/SnapshotPolicyResponse.java b/api/src/main/java/org/apache/cloudstack/api/response/SnapshotPolicyResponse.java index 4ce77cfdf6e..998d6af871d 100644 --- a/api/src/main/java/org/apache/cloudstack/api/response/SnapshotPolicyResponse.java +++ b/api/src/main/java/org/apache/cloudstack/api/response/SnapshotPolicyResponse.java @@ -37,6 +37,10 @@ public class SnapshotPolicyResponse extends BaseResponseWithTagInformation { @Param(description = "the ID of the disk volume") private String volumeId; + @SerializedName("volumename") + @Param(description = "the name of the disk volume") + private String volumeName; + @SerializedName("schedule") @Param(description = "time the snapshot is scheduled to be taken.") private String schedule; @@ -87,6 +91,10 @@ public class SnapshotPolicyResponse extends BaseResponseWithTagInformation { this.volumeId = volumeId; } + public void setVolumeName(String volumeName) { + this.volumeName = volumeName; + } + public String getSchedule() { return schedule; } diff --git a/api/src/main/java/org/apache/cloudstack/api/response/StoragePoolResponse.java b/api/src/main/java/org/apache/cloudstack/api/response/StoragePoolResponse.java index abc674ff0f9..7867c685bba 100644 --- a/api/src/main/java/org/apache/cloudstack/api/response/StoragePoolResponse.java +++ b/api/src/main/java/org/apache/cloudstack/api/response/StoragePoolResponse.java @@ -77,19 +77,24 @@ public class StoragePoolResponse extends BaseResponseWithAnnotations { @Param(description = "the name of the cluster for the storage pool") private String clusterName; + @SerializedName(ApiConstants.CAPACITY_BYTES) + @Param(description = "bytes CloudStack can provision from this storage pool", since = "4.22.0") + private Long capacityBytes; + + @Deprecated(since = "4.22.0") @SerializedName("disksizetotal") @Param(description = "the total disk size of the storage pool") private Long diskSizeTotal; @SerializedName("disksizeallocated") - @Param(description = "the host's currently allocated disk size") + @Param(description = "the pool's currently allocated disk size") private Long diskSizeAllocated; @SerializedName("disksizeused") - @Param(description = "the host's currently used disk size") + @Param(description = "the pool's currently used disk size") private Long diskSizeUsed; - @SerializedName("capacityiops") + @SerializedName(ApiConstants.CAPACITY_IOPS) @Param(description = "IOPS CloudStack can provision from this storage pool") private Long capacityIops; @@ -288,6 +293,14 @@ public class StoragePoolResponse extends BaseResponseWithAnnotations { this.clusterName = clusterName; } + public Long getCapacityBytes() { + return capacityBytes; + } + + public void setCapacityBytes(Long capacityBytes) { + this.capacityBytes = capacityBytes; + } + public Long getDiskSizeTotal() { return diskSizeTotal; } diff --git a/api/src/main/java/org/apache/cloudstack/api/response/TrafficTypeResponse.java b/api/src/main/java/org/apache/cloudstack/api/response/TrafficTypeResponse.java index 9a79b072465..281ed6736ee 100644 --- a/api/src/main/java/org/apache/cloudstack/api/response/TrafficTypeResponse.java +++ b/api/src/main/java/org/apache/cloudstack/api/response/TrafficTypeResponse.java @@ -56,6 +56,14 @@ public class TrafficTypeResponse extends BaseResponse { @Param(description = "The network name label of the physical device dedicated to this traffic on a HyperV host") private String hypervNetworkLabel; + @SerializedName(ApiConstants.VLAN) + @Param(description = "The VLAN id to be used for Management traffic by VMware host") + private String vlan; + + @SerializedName(ApiConstants.ISOLATION_METHODS) + @Param(description = "isolation methods for the physical network traffic") + private String isolationMethods; + @SerializedName(ApiConstants.OVM3_NETWORK_LABEL) @Param(description = "The network name of the physical device dedicated to this traffic on an OVM3 host") private String ovm3NetworkLabel; @@ -128,4 +136,20 @@ public class TrafficTypeResponse extends BaseResponse { public void setOvm3Label(String ovm3Label) { this.ovm3NetworkLabel = ovm3Label; } + + public String getIsolationMethods() { + return isolationMethods; + } + + public void setIsolationMethods(String isolationMethods) { + this.isolationMethods = isolationMethods; + } + + public String getVlan() { + return vlan; + } + + public void setVlan(String vlan) { + this.vlan = vlan; + } } diff --git a/api/src/main/java/org/apache/cloudstack/api/response/UnmanageVMInstanceResponse.java b/api/src/main/java/org/apache/cloudstack/api/response/UnmanageVMInstanceResponse.java index e9d45cb506a..bd95ecee5ae 100644 --- a/api/src/main/java/org/apache/cloudstack/api/response/UnmanageVMInstanceResponse.java +++ b/api/src/main/java/org/apache/cloudstack/api/response/UnmanageVMInstanceResponse.java @@ -32,6 +32,10 @@ public class UnmanageVMInstanceResponse extends BaseResponse { @Param(description = "details of the unmanage VM operation") private String details; + @SerializedName(ApiConstants.HOST_ID) + @Param(description = "The ID of the host used for unmanaged Instance") + private String hostId; + public UnmanageVMInstanceResponse() { } @@ -55,4 +59,12 @@ public class UnmanageVMInstanceResponse extends BaseResponse { public void setDetails(String details) { this.details = details; } + + public String getHostId() { + return hostId; + } + + public void setHostId(String hostId) { + this.hostId = hostId; + } } diff --git a/api/src/main/java/org/apache/cloudstack/api/response/UpgradeRouterTemplateResponse.java b/api/src/main/java/org/apache/cloudstack/api/response/UpgradeRouterTemplateResponse.java index d89631ae428..dbe990c6dbd 100644 --- a/api/src/main/java/org/apache/cloudstack/api/response/UpgradeRouterTemplateResponse.java +++ b/api/src/main/java/org/apache/cloudstack/api/response/UpgradeRouterTemplateResponse.java @@ -16,27 +16,10 @@ // under the License. package org.apache.cloudstack.api.response; -import com.google.gson.annotations.SerializedName; - -import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.BaseResponse; import org.apache.cloudstack.api.EntityReference; import org.apache.cloudstack.jobs.JobInfo; -import com.cloud.serializer.Param; - @EntityReference(value = JobInfo.class) -@SuppressWarnings("unused") public class UpgradeRouterTemplateResponse extends BaseResponse { - @SerializedName(ApiConstants.JOB_ID) - @Param(description = "the id of AsyncJob") - private String asyncJobId; - - public String getAsyncJobId() { - return asyncJobId; - } - - public void setAsyncJobId(String asyncJobId) { - this.asyncJobId = asyncJobId; - } } diff --git a/api/src/main/java/org/apache/cloudstack/api/response/UserVmResponse.java b/api/src/main/java/org/apache/cloudstack/api/response/UserVmResponse.java index ca5bd09a9aa..29681b5e38f 100644 --- a/api/src/main/java/org/apache/cloudstack/api/response/UserVmResponse.java +++ b/api/src/main/java/org/apache/cloudstack/api/response/UserVmResponse.java @@ -41,7 +41,7 @@ import com.google.gson.annotations.SerializedName; @SuppressWarnings("unused") @EntityReference(value = {VirtualMachine.class, UserVm.class, VirtualRouter.class}) -public class UserVmResponse extends BaseResponseWithTagInformation implements ControlledEntityResponse, SetResourceIconResponse { +public class UserVmResponse extends BaseResponseWithTagInformation implements ControlledViewEntityResponse, SetResourceIconResponse { @SerializedName(ApiConstants.ID) @Param(description = "the ID of the virtual machine") private String id; diff --git a/api/src/main/java/org/apache/cloudstack/backup/BackupManager.java b/api/src/main/java/org/apache/cloudstack/backup/BackupManager.java index c4b92fc9e05..db051313d96 100644 --- a/api/src/main/java/org/apache/cloudstack/backup/BackupManager.java +++ b/api/src/main/java/org/apache/cloudstack/backup/BackupManager.java @@ -28,6 +28,7 @@ import org.apache.cloudstack.api.command.user.backup.CreateBackupCmd; import org.apache.cloudstack.api.command.user.backup.CreateBackupScheduleCmd; import org.apache.cloudstack.api.command.user.backup.DeleteBackupScheduleCmd; import org.apache.cloudstack.api.command.user.backup.ListBackupOfferingsCmd; +import org.apache.cloudstack.api.command.user.backup.ListBackupScheduleCmd; import org.apache.cloudstack.api.command.user.backup.ListBackupsCmd; import org.apache.cloudstack.api.response.BackupResponse; import org.apache.cloudstack.framework.config.ConfigKey; @@ -55,7 +56,7 @@ public interface BackupManager extends BackupService, Configurable, PluggableSer ConfigKey BackupProviderPlugin = new ConfigKey<>("Advanced", String.class, "backup.framework.provider.plugin", "dummy", - "The backup and recovery provider plugin.", true, ConfigKey.Scope.Zone, BackupFrameworkEnabled.key()); + "The backup and recovery provider plugin. Valid plugin values: dummy, veeam, networker and nas", true, ConfigKey.Scope.Zone, BackupFrameworkEnabled.key()); ConfigKey BackupSyncPollingInterval = new ConfigKey<>("Advanced", Long.class, "backup.framework.sync.interval", @@ -174,7 +175,7 @@ public interface BackupManager extends BackupService, Configurable, PluggableSer * @param vmId * @return */ - List listBackupSchedule(Long vmId); + List listBackupSchedules(ListBackupScheduleCmd cmd); /** * Deletes VM backup schedule for a VM @@ -205,6 +206,8 @@ public interface BackupManager extends BackupService, Configurable, PluggableSer Boolean canCreateInstanceFromBackup(Long backupId); + Boolean canCreateInstanceFromBackupAcrossZones(Long backupId); + /** * Restore a backup to a new Instance */ diff --git a/api/src/main/java/org/apache/cloudstack/backup/BackupProvider.java b/api/src/main/java/org/apache/cloudstack/backup/BackupProvider.java index 1eb36f89556..32a714370df 100644 --- a/api/src/main/java/org/apache/cloudstack/backup/BackupProvider.java +++ b/api/src/main/java/org/apache/cloudstack/backup/BackupProvider.java @@ -23,6 +23,8 @@ import com.cloud.vm.VirtualMachine; public interface BackupProvider { + Boolean crossZoneInstanceCreationEnabled(BackupOffering backupOffering); + /** * Returns the unique name of the provider * @return returns provider name @@ -85,7 +87,7 @@ public interface BackupProvider { */ boolean deleteBackup(Backup backup, boolean forced); - boolean restoreBackupToVM(VirtualMachine vm, Backup backup, String hostIp, String dataStoreUuid); + Pair restoreBackupToVM(VirtualMachine vm, Backup backup, String hostIp, String dataStoreUuid); /** * Restore VM from backup diff --git a/api/src/main/java/org/apache/cloudstack/backup/BackupRepository.java b/api/src/main/java/org/apache/cloudstack/backup/BackupRepository.java index be539a0eb04..886d13c13f9 100644 --- a/api/src/main/java/org/apache/cloudstack/backup/BackupRepository.java +++ b/api/src/main/java/org/apache/cloudstack/backup/BackupRepository.java @@ -28,9 +28,12 @@ public interface BackupRepository extends InternalIdentity, Identity { String getType(); String getAddress(); String getMountOptions(); + void setMountOptions(String mountOptions); void setUsedBytes(Long usedBytes); Long getCapacityBytes(); Long getUsedBytes(); void setCapacityBytes(Long capacityBytes); + Boolean crossZoneInstanceCreationEnabled(); + void setCrossZoneInstanceCreation(Boolean crossZoneInstanceCreation); Date getCreated(); } diff --git a/api/src/main/java/org/apache/cloudstack/backup/BackupRepositoryService.java b/api/src/main/java/org/apache/cloudstack/backup/BackupRepositoryService.java index ae71053e400..875fc3b3d90 100644 --- a/api/src/main/java/org/apache/cloudstack/backup/BackupRepositoryService.java +++ b/api/src/main/java/org/apache/cloudstack/backup/BackupRepositoryService.java @@ -23,11 +23,13 @@ import com.cloud.utils.Pair; import org.apache.cloudstack.api.command.user.backup.repository.AddBackupRepositoryCmd; import org.apache.cloudstack.api.command.user.backup.repository.DeleteBackupRepositoryCmd; import org.apache.cloudstack.api.command.user.backup.repository.ListBackupRepositoriesCmd; +import org.apache.cloudstack.api.command.user.backup.repository.UpdateBackupRepositoryCmd; import java.util.List; public interface BackupRepositoryService { BackupRepository addBackupRepository(AddBackupRepositoryCmd cmd); + BackupRepository updateBackupRepository(UpdateBackupRepositoryCmd cmd); boolean deleteBackupRepository(DeleteBackupRepositoryCmd cmd); Pair, Integer> listBackupRepositories(ListBackupRepositoriesCmd cmd); diff --git a/api/src/main/java/org/apache/cloudstack/backup/BackupSchedule.java b/api/src/main/java/org/apache/cloudstack/backup/BackupSchedule.java index b5138d34de1..44fdf70c4c1 100644 --- a/api/src/main/java/org/apache/cloudstack/backup/BackupSchedule.java +++ b/api/src/main/java/org/apache/cloudstack/backup/BackupSchedule.java @@ -19,11 +19,12 @@ package org.apache.cloudstack.backup; import java.util.Date; +import org.apache.cloudstack.acl.ControlledEntity; import org.apache.cloudstack.api.InternalIdentity; import com.cloud.utils.DateUtil; -public interface BackupSchedule extends InternalIdentity { +public interface BackupSchedule extends ControlledEntity, InternalIdentity { Long getVmId(); DateUtil.IntervalType getScheduleType(); String getSchedule(); diff --git a/api/src/main/java/org/apache/cloudstack/userdata/UserDataManager.java b/api/src/main/java/org/apache/cloudstack/userdata/UserDataManager.java index b4bede24890..7e718413118 100644 --- a/api/src/main/java/org/apache/cloudstack/userdata/UserDataManager.java +++ b/api/src/main/java/org/apache/cloudstack/userdata/UserDataManager.java @@ -22,6 +22,8 @@ import org.apache.cloudstack.framework.config.Configurable; import com.cloud.utils.component.Manager; +import java.io.IOException; + public interface UserDataManager extends Manager, Configurable { String VM_USERDATA_MAX_LENGTH_STRING = "vm.userdata.max.length"; ConfigKey VM_USERDATA_MAX_LENGTH = new ConfigKey<>("Advanced", Integer.class, VM_USERDATA_MAX_LENGTH_STRING, "32768", @@ -29,4 +31,14 @@ public interface UserDataManager extends Manager, Configurable { String concatenateUserData(String userdata1, String userdata2, String userdataProvider); String validateUserData(String userData, BaseCmd.HTTPMethod httpmethod); + + /** + * This method validates the user data uuid for system VMs and returns the user data + * after compression and base64 encoding for the system VM to consume. + * + * @param userDataUuid + * @return a String containing the user data after compression and base64 encoding + * @throws IOException + */ + String validateAndGetUserDataForSystemVM(String userDataUuid) throws IOException; } diff --git a/api/src/main/java/org/apache/cloudstack/vm/ImportVmTask.java b/api/src/main/java/org/apache/cloudstack/vm/ImportVmTask.java new file mode 100644 index 00000000000..5bb51dfcbcb --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/vm/ImportVmTask.java @@ -0,0 +1,41 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.cloudstack.vm; + +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; + +public interface ImportVmTask extends Identity, InternalIdentity { + enum Step { + Prepare, CloningInstance, ConvertingInstance, Importing, Completed + } + + enum TaskState { + Running, Completed, Failed; + + public static TaskState getValue(String state) { + for (TaskState s : TaskState.values()) { + if (s.name().equalsIgnoreCase(state)) { + return s; + } + } + throw new IllegalArgumentException("Invalid task state: " + state); + } + } +} diff --git a/api/src/main/java/org/apache/cloudstack/vm/ImportVmTasksManager.java b/api/src/main/java/org/apache/cloudstack/vm/ImportVmTasksManager.java new file mode 100644 index 00000000000..233511fbce8 --- /dev/null +++ b/api/src/main/java/org/apache/cloudstack/vm/ImportVmTasksManager.java @@ -0,0 +1,38 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.vm; + +import com.cloud.dc.DataCenter; +import com.cloud.host.Host; +import com.cloud.user.Account; +import org.apache.cloudstack.api.command.admin.vm.ListImportVMTasksCmd; +import org.apache.cloudstack.api.response.ImportVMTaskResponse; +import org.apache.cloudstack.api.response.ListResponse; + +public interface ImportVmTasksManager { + + ListResponse listImportVMTasks(ListImportVMTasksCmd cmd); + + ImportVmTask createImportVMTaskRecord(DataCenter zone, Account owner, long userId, String displayName, + String vcenter, String datacenterName, String sourceVMName, + Host convertHost, Host importHost); + + void updateImportVMTaskStep(ImportVmTask importVMTaskVO, DataCenter zone, Account owner, Host convertHost, + Host importHost, Long vmId, ImportVmTask.Step step); + + void updateImportVMTaskErrorState(ImportVmTask importVMTaskVO, ImportVmTask.TaskState state, String errorMsg); +} diff --git a/api/src/main/java/org/apache/cloudstack/vm/UnmanageVMService.java b/api/src/main/java/org/apache/cloudstack/vm/UnmanageVMService.java index 2315e5f2e95..70d8795f305 100644 --- a/api/src/main/java/org/apache/cloudstack/vm/UnmanageVMService.java +++ b/api/src/main/java/org/apache/cloudstack/vm/UnmanageVMService.java @@ -17,11 +17,14 @@ package org.apache.cloudstack.vm; +import com.cloud.utils.Pair; + public interface UnmanageVMService { /** * Unmanage a guest VM from CloudStack - * @return true if the VM is successfully unmanaged, false if not. + * + * @return (true if successful, false if not, hostUuid) if the VM is successfully unmanaged. */ - boolean unmanageVMInstance(long vmId); + Pair unmanageVMInstance(long vmId, Long paramHostId, boolean isForced); } diff --git a/api/src/test/java/org/apache/cloudstack/api/command/user/backup/ListBackupScheduleCmdTest.java b/api/src/test/java/org/apache/cloudstack/api/command/user/backup/ListBackupScheduleCmdTest.java new file mode 100644 index 00000000000..a0d88bbc84e --- /dev/null +++ b/api/src/test/java/org/apache/cloudstack/api/command/user/backup/ListBackupScheduleCmdTest.java @@ -0,0 +1,98 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.api.command.user.backup; + +import com.cloud.exception.InsufficientCapacityException; +import com.cloud.exception.NetworkRuleConflictException; +import com.cloud.exception.ResourceAllocationException; +import com.cloud.exception.ResourceUnavailableException; +import com.cloud.user.Account; +import org.apache.cloudstack.api.ResponseGenerator; +import org.apache.cloudstack.api.response.BackupScheduleResponse; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.backup.BackupManager; +import org.apache.cloudstack.backup.BackupSchedule; +import org.apache.cloudstack.context.CallContext; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; + +import java.util.ArrayList; +import java.util.List; + +@RunWith(MockitoJUnitRunner.class) +public class ListBackupScheduleCmdTest { + + @Mock + private BackupManager backupManager; + + @Mock + private ResponseGenerator responseGenerator; + + private ListBackupScheduleCmd cmd; + + @Before + public void setUp() { + cmd = new ListBackupScheduleCmd(); + cmd.backupManager = backupManager; + cmd._responseGenerator = responseGenerator; + } + + @Test + public void testExecuteWithSchedules() throws ResourceUnavailableException, InsufficientCapacityException, ResourceAllocationException, NetworkRuleConflictException { + BackupSchedule schedule = Mockito.mock(BackupSchedule.class); + BackupScheduleResponse scheduleResponse = Mockito.mock(BackupScheduleResponse.class); + List schedules = new ArrayList<>(); + schedules.add(schedule); + + Mockito.when(backupManager.listBackupSchedules(cmd)).thenReturn(schedules); + Mockito.when(responseGenerator.createBackupScheduleResponse(schedule)).thenReturn(scheduleResponse); + + Account mockAccount = Mockito.mock(Account.class); + CallContext callContext = Mockito.mock(CallContext.class); + try (org.mockito.MockedStatic mocked = Mockito.mockStatic(CallContext.class)) { + cmd.execute(); + } + + ListResponse response = (ListResponse) cmd.getResponseObject(); + Assert.assertNotNull(response); + Assert.assertEquals(1, response.getResponses().size()); + Assert.assertEquals(scheduleResponse, response.getResponses().get(0)); + } + + @Test + public void testExecuteWithNoSchedules() { + Mockito.when(backupManager.listBackupSchedules(cmd)).thenReturn(new ArrayList<>()); + CallContext callContext = Mockito.mock(CallContext.class); + + try (org.mockito.MockedStatic mocked = Mockito.mockStatic(CallContext.class)) { + mocked.when(CallContext::current).thenReturn(callContext); + cmd.execute(); + } catch (ResourceUnavailableException | InsufficientCapacityException | ResourceAllocationException | + NetworkRuleConflictException e) { + throw new RuntimeException(e); + } + + ListResponse response = (ListResponse) cmd.getResponseObject(); + Assert.assertNotNull(response); + Assert.assertEquals(0, response.getResponses().size()); + } +} diff --git a/api/src/test/java/org/apache/cloudstack/api/command/user/snapshot/ListSnapshotPoliciesCmdTest.java b/api/src/test/java/org/apache/cloudstack/api/command/user/snapshot/ListSnapshotPoliciesCmdTest.java new file mode 100644 index 00000000000..36cfcf5cb9a --- /dev/null +++ b/api/src/test/java/org/apache/cloudstack/api/command/user/snapshot/ListSnapshotPoliciesCmdTest.java @@ -0,0 +1,79 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package org.apache.cloudstack.api.command.user.snapshot; + +import com.cloud.storage.snapshot.SnapshotApiService; +import com.cloud.storage.snapshot.SnapshotPolicy; +import com.cloud.utils.Pair; +import org.apache.cloudstack.api.ResponseGenerator; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.SnapshotPolicyResponse; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; + +import java.util.ArrayList; +import java.util.List; + +public class ListSnapshotPoliciesCmdTest { + private ListSnapshotPoliciesCmd cmd; + private SnapshotApiService snapshotService; + private ResponseGenerator responseGenerator; + + @Before + public void setUp() { + cmd = new ListSnapshotPoliciesCmd(); + snapshotService = Mockito.mock(SnapshotApiService.class); + responseGenerator = Mockito.mock(ResponseGenerator.class); + + cmd._snapshotService = snapshotService; + cmd._responseGenerator = responseGenerator; + } + + @Test + public void testExecuteWithPolicies() { + SnapshotPolicy policy = Mockito.mock(SnapshotPolicy.class); + SnapshotPolicyResponse policyResponse = Mockito.mock(SnapshotPolicyResponse.class); + List policies = new ArrayList<>(); + policies.add(policy); + + Mockito.when(snapshotService.listSnapshotPolicies(cmd)) + .thenReturn(new Pair<>(policies, 1)); + Mockito.when(responseGenerator.createSnapshotPolicyResponse(policy)) + .thenReturn(policyResponse); + + cmd.execute(); + + ListResponse response = (ListResponse) cmd.getResponseObject(); + Assert.assertNotNull(response); + Assert.assertEquals(1, response.getResponses().size()); + Assert.assertEquals(policyResponse, response.getResponses().get(0)); + } + + @Test + public void testExecuteWithNoPolicies() { + Mockito.when(snapshotService.listSnapshotPolicies(cmd)) + .thenReturn(new Pair<>(new ArrayList<>(), 0)); + + cmd.execute(); + + ListResponse response = (ListResponse) cmd.getResponseObject(); + Assert.assertNotNull(response); + Assert.assertTrue(response.getResponses().isEmpty()); + } +} diff --git a/client/pom.xml b/client/pom.xml index 72181442b43..6ef335e94e4 100644 --- a/client/pom.xml +++ b/client/pom.xml @@ -25,7 +25,7 @@ org.apache.cloudstack cloudstack - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT diff --git a/core/pom.xml b/core/pom.xml index e4cd84357d1..f91a330b7ba 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -24,7 +24,7 @@ org.apache.cloudstack cloudstack - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT diff --git a/core/src/main/java/com/cloud/agent/api/ConvertInstanceCommand.java b/core/src/main/java/com/cloud/agent/api/ConvertInstanceCommand.java index f938d0ac55d..24336747ccf 100644 --- a/core/src/main/java/com/cloud/agent/api/ConvertInstanceCommand.java +++ b/core/src/main/java/com/cloud/agent/api/ConvertInstanceCommand.java @@ -23,30 +23,37 @@ import com.cloud.hypervisor.Hypervisor; public class ConvertInstanceCommand extends Command { private RemoteInstanceTO sourceInstance; + private String originalVMName; private Hypervisor.HypervisorType destinationHypervisorType; private DataStoreTO conversionTemporaryLocation; private String templateDirOnConversionLocation; private boolean checkConversionSupport; private boolean exportOvfToConversionLocation; private int threadsCountToExportOvf = 0; + private String extraParams; public ConvertInstanceCommand() { } public ConvertInstanceCommand(RemoteInstanceTO sourceInstance, Hypervisor.HypervisorType destinationHypervisorType, DataStoreTO conversionTemporaryLocation, - String templateDirOnConversionLocation, boolean checkConversionSupport, boolean exportOvfToConversionLocation) { + String templateDirOnConversionLocation, boolean checkConversionSupport, boolean exportOvfToConversionLocation, String sourceVMName) { this.sourceInstance = sourceInstance; this.destinationHypervisorType = destinationHypervisorType; this.conversionTemporaryLocation = conversionTemporaryLocation; this.templateDirOnConversionLocation = templateDirOnConversionLocation; this.checkConversionSupport = checkConversionSupport; this.exportOvfToConversionLocation = exportOvfToConversionLocation; + this.originalVMName = sourceVMName; } public RemoteInstanceTO getSourceInstance() { return sourceInstance; } + public String getOriginalVMName() { + return originalVMName; + } + public Hypervisor.HypervisorType getDestinationHypervisorType() { return destinationHypervisorType; } @@ -75,6 +82,14 @@ public class ConvertInstanceCommand extends Command { this.threadsCountToExportOvf = threadsCountToExportOvf; } + public String getExtraParams() { + return extraParams; + } + + public void setExtraParams(String extraParams) { + this.extraParams = extraParams; + } + @Override public boolean executeInSequence() { return false; diff --git a/core/src/main/java/com/cloud/agent/api/GetExternalConsoleAnswer.java b/core/src/main/java/com/cloud/agent/api/GetExternalConsoleAnswer.java new file mode 100644 index 00000000000..e913d6f0d3a --- /dev/null +++ b/core/src/main/java/com/cloud/agent/api/GetExternalConsoleAnswer.java @@ -0,0 +1,68 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package com.cloud.agent.api; + +public class GetExternalConsoleAnswer extends Answer { + + private String url; + private String host; + private Integer port; + @LogLevel(LogLevel.Log4jLevel.Off) + private String password; + private String protocol; + private boolean passwordOneTimeUseOnly; + + public GetExternalConsoleAnswer(Command command, String details) { + super(command, false, details); + } + + public GetExternalConsoleAnswer(Command command, String url, String host, Integer port, String password, + boolean passwordOneTimeUseOnly, String protocol) { + super(command, true, ""); + this.url = url; + this.host = host; + this.port = port; + this.password = password; + this.passwordOneTimeUseOnly = passwordOneTimeUseOnly; + this.protocol = protocol; + } + + public String getUrl() { + return url; + } + + public String getHost() { + return host; + } + + public Integer getPort() { + return port; + } + + public String getPassword() { + return password; + } + + public String getProtocol() { + return protocol; + } + + public boolean isPasswordOneTimeUseOnly() { + return passwordOneTimeUseOnly; + } +} diff --git a/core/src/main/java/com/cloud/agent/api/GetExternalConsoleCommand.java b/core/src/main/java/com/cloud/agent/api/GetExternalConsoleCommand.java new file mode 100644 index 00000000000..fc2134f631f --- /dev/null +++ b/core/src/main/java/com/cloud/agent/api/GetExternalConsoleCommand.java @@ -0,0 +1,53 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package com.cloud.agent.api; + +import com.cloud.agent.api.to.VirtualMachineTO; + +public class GetExternalConsoleCommand extends Command { + String vmName; + VirtualMachineTO vm; + protected boolean executeInSequence; + + public GetExternalConsoleCommand(String vmName, VirtualMachineTO vm) { + this.vmName = vmName; + this.vm = vm; + this.executeInSequence = false; + } + + public String getVmName() { + return this.vmName; + } + + public void setVirtualMachine(VirtualMachineTO vm) { + this.vm = vm; + } + + public VirtualMachineTO getVirtualMachine() { + return vm; + } + + @Override + public boolean executeInSequence() { + return executeInSequence; + } + + public void setExecuteInSequence(boolean executeInSequence) { + this.executeInSequence = executeInSequence; + } +} diff --git a/core/src/main/java/com/cloud/agent/api/ImportConvertedInstanceCommand.java b/core/src/main/java/com/cloud/agent/api/ImportConvertedInstanceCommand.java index 9d50e852ced..eadfa6556f8 100644 --- a/core/src/main/java/com/cloud/agent/api/ImportConvertedInstanceCommand.java +++ b/core/src/main/java/com/cloud/agent/api/ImportConvertedInstanceCommand.java @@ -27,17 +27,20 @@ public class ImportConvertedInstanceCommand extends Command { private List destinationStoragePools; private DataStoreTO conversionTemporaryLocation; private String temporaryConvertUuid; + private boolean forceConvertToPool; public ImportConvertedInstanceCommand() { } public ImportConvertedInstanceCommand(RemoteInstanceTO sourceInstance, List destinationStoragePools, - DataStoreTO conversionTemporaryLocation, String temporaryConvertUuid) { + DataStoreTO conversionTemporaryLocation, String temporaryConvertUuid, + boolean forceConvertToPool) { this.sourceInstance = sourceInstance; this.destinationStoragePools = destinationStoragePools; this.conversionTemporaryLocation = conversionTemporaryLocation; this.temporaryConvertUuid = temporaryConvertUuid; + this.forceConvertToPool = forceConvertToPool; } public RemoteInstanceTO getSourceInstance() { @@ -56,6 +59,10 @@ public class ImportConvertedInstanceCommand extends Command { return temporaryConvertUuid; } + public boolean isForceConvertToPool() { + return forceConvertToPool; + } + @Override public boolean executeInSequence() { return false; diff --git a/core/src/main/java/com/cloud/agent/api/RunCustomActionCommand.java b/core/src/main/java/com/cloud/agent/api/RunCustomActionCommand.java index 36489ad4fa5..113073ac5ee 100644 --- a/core/src/main/java/com/cloud/agent/api/RunCustomActionCommand.java +++ b/core/src/main/java/com/cloud/agent/api/RunCustomActionCommand.java @@ -21,10 +21,12 @@ package com.cloud.agent.api; import java.util.Map; +import com.cloud.agent.api.to.VirtualMachineTO; + public class RunCustomActionCommand extends Command { String actionName; - Long vmId; + VirtualMachineTO vmTO; Map parameters; public RunCustomActionCommand(String actionName) { @@ -36,12 +38,12 @@ public class RunCustomActionCommand extends Command { return actionName; } - public Long getVmId() { - return vmId; + public VirtualMachineTO getVmTO() { + return vmTO; } - public void setVmId(Long vmId) { - this.vmId = vmId; + public void setVmTO(VirtualMachineTO vmTO) { + this.vmTO = vmTO; } public Map getParameters() { diff --git a/core/src/main/java/com/cloud/agent/api/UnmanageInstanceAnswer.java b/core/src/main/java/com/cloud/agent/api/UnmanageInstanceAnswer.java new file mode 100644 index 00000000000..39a35d49990 --- /dev/null +++ b/core/src/main/java/com/cloud/agent/api/UnmanageInstanceAnswer.java @@ -0,0 +1,27 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package com.cloud.agent.api; + +public class UnmanageInstanceAnswer extends Answer { + + public UnmanageInstanceAnswer(UnmanageInstanceCommand cmd, boolean success, String details) { + super(cmd, success, details); + } +} diff --git a/core/src/main/java/com/cloud/agent/api/UnmanageInstanceCommand.java b/core/src/main/java/com/cloud/agent/api/UnmanageInstanceCommand.java new file mode 100644 index 00000000000..dd504b9ea26 --- /dev/null +++ b/core/src/main/java/com/cloud/agent/api/UnmanageInstanceCommand.java @@ -0,0 +1,61 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package com.cloud.agent.api; + +import com.cloud.agent.api.to.VirtualMachineTO; + +/** + */ +public class UnmanageInstanceCommand extends Command { + String instanceName; + boolean executeInSequence = false; + VirtualMachineTO vm; + boolean isConfigDriveAttached; + + @Override + public boolean executeInSequence() { + return executeInSequence; + } + + public UnmanageInstanceCommand(VirtualMachineTO vm) { + this.vm = vm; + this.instanceName = vm.getName(); + } + + public UnmanageInstanceCommand(String instanceName) { + this.instanceName = instanceName; + } + + public String getInstanceName() { + return instanceName; + } + + public VirtualMachineTO getVm() { + return vm; + } + + public boolean isConfigDriveAttached() { + return isConfigDriveAttached; + } + + public void setConfigDriveAttached(boolean configDriveAttached) { + isConfigDriveAttached = configDriveAttached; + } +} diff --git a/core/src/main/java/com/cloud/storage/resource/StorageProcessor.java b/core/src/main/java/com/cloud/storage/resource/StorageProcessor.java index b7cd5b8eb5e..dd8e2abcd64 100644 --- a/core/src/main/java/com/cloud/storage/resource/StorageProcessor.java +++ b/core/src/main/java/com/cloud/storage/resource/StorageProcessor.java @@ -21,7 +21,7 @@ package com.cloud.storage.resource; import org.apache.cloudstack.agent.directdownload.DirectDownloadCommand; import org.apache.cloudstack.storage.command.AttachCommand; -import org.apache.cloudstack.storage.command.CheckDataStoreStoragePolicyComplainceCommand; +import org.apache.cloudstack.storage.command.CheckDataStoreStoragePolicyComplianceCommand; import org.apache.cloudstack.storage.command.CopyCommand; import org.apache.cloudstack.storage.command.CreateObjectCommand; import org.apache.cloudstack.storage.command.DeleteCommand; @@ -82,7 +82,7 @@ public interface StorageProcessor { Answer copyVolumeFromPrimaryToPrimary(CopyCommand cmd); - public Answer checkDataStoreStoragePolicyCompliance(CheckDataStoreStoragePolicyComplainceCommand cmd); + public Answer checkDataStoreStoragePolicyCompliance(CheckDataStoreStoragePolicyComplianceCommand cmd); public Answer syncVolumePath(SyncVolumePathCommand cmd); } diff --git a/core/src/main/java/com/cloud/storage/resource/StorageSubsystemCommandHandlerBase.java b/core/src/main/java/com/cloud/storage/resource/StorageSubsystemCommandHandlerBase.java index 58885210120..318c069b0b0 100644 --- a/core/src/main/java/com/cloud/storage/resource/StorageSubsystemCommandHandlerBase.java +++ b/core/src/main/java/com/cloud/storage/resource/StorageSubsystemCommandHandlerBase.java @@ -21,7 +21,7 @@ package com.cloud.storage.resource; import org.apache.cloudstack.agent.directdownload.DirectDownloadCommand; import org.apache.cloudstack.storage.command.AttachCommand; -import org.apache.cloudstack.storage.command.CheckDataStoreStoragePolicyComplainceCommand; +import org.apache.cloudstack.storage.command.CheckDataStoreStoragePolicyComplianceCommand; import org.apache.cloudstack.storage.command.CopyCommand; import org.apache.cloudstack.storage.command.CreateObjectAnswer; import org.apache.cloudstack.storage.command.CreateObjectCommand; @@ -79,8 +79,8 @@ public class StorageSubsystemCommandHandlerBase implements StorageSubsystemComma return processor.resignature((ResignatureCommand) command); } else if (command instanceof DirectDownloadCommand) { return processor.handleDownloadTemplateToPrimaryStorage((DirectDownloadCommand) command); - } else if (command instanceof CheckDataStoreStoragePolicyComplainceCommand) { - return processor.checkDataStoreStoragePolicyCompliance((CheckDataStoreStoragePolicyComplainceCommand) command); + } else if (command instanceof CheckDataStoreStoragePolicyComplianceCommand) { + return processor.checkDataStoreStoragePolicyCompliance((CheckDataStoreStoragePolicyComplianceCommand) command); } else if (command instanceof SyncVolumePathCommand) { return processor.syncVolumePath((SyncVolumePathCommand) command); } else if (command instanceof QuerySnapshotZoneCopyCommand) { diff --git a/core/src/main/java/org/apache/cloudstack/backup/RestoreBackupCommand.java b/core/src/main/java/org/apache/cloudstack/backup/RestoreBackupCommand.java index f447fbe3d00..8e68f4f1e41 100644 --- a/core/src/main/java/org/apache/cloudstack/backup/RestoreBackupCommand.java +++ b/core/src/main/java/org/apache/cloudstack/backup/RestoreBackupCommand.java @@ -22,6 +22,7 @@ package org.apache.cloudstack.backup; import com.cloud.agent.api.Command; import com.cloud.agent.api.LogLevel; import com.cloud.vm.VirtualMachine; +import org.apache.cloudstack.storage.to.PrimaryDataStoreTO; import java.util.List; @@ -31,11 +32,13 @@ public class RestoreBackupCommand extends Command { private String backupRepoType; private String backupRepoAddress; private List backupVolumesUUIDs; + private List restoreVolumePools; private List restoreVolumePaths; private String diskType; private Boolean vmExists; private String restoreVolumeUUID; private VirtualMachine.State vmState; + private Integer mountTimeout; protected RestoreBackupCommand() { super(); @@ -73,6 +76,14 @@ public class RestoreBackupCommand extends Command { this.backupRepoAddress = backupRepoAddress; } + public List getRestoreVolumePools() { + return restoreVolumePools; + } + + public void setRestoreVolumePools(List restoreVolumePools) { + this.restoreVolumePools = restoreVolumePools; + } + public List getRestoreVolumePaths() { return restoreVolumePaths; } @@ -136,4 +147,12 @@ public class RestoreBackupCommand extends Command { public void setBackupVolumesUUIDs(List backupVolumesUUIDs) { this.backupVolumesUUIDs = backupVolumesUUIDs; } + + public Integer getMountTimeout() { + return this.mountTimeout == null ? 0 : this.mountTimeout; + } + + public void setMountTimeout(Integer mountTimeout) { + this.mountTimeout = mountTimeout; + } } diff --git a/core/src/main/java/org/apache/cloudstack/backup/TakeBackupCommand.java b/core/src/main/java/org/apache/cloudstack/backup/TakeBackupCommand.java index ecebd57a178..5402b6b2476 100644 --- a/core/src/main/java/org/apache/cloudstack/backup/TakeBackupCommand.java +++ b/core/src/main/java/org/apache/cloudstack/backup/TakeBackupCommand.java @@ -21,6 +21,7 @@ package org.apache.cloudstack.backup; import com.cloud.agent.api.Command; import com.cloud.agent.api.LogLevel; +import org.apache.cloudstack.storage.to.PrimaryDataStoreTO; import java.util.List; @@ -29,6 +30,7 @@ public class TakeBackupCommand extends Command { private String backupPath; private String backupRepoType; private String backupRepoAddress; + private List volumePools; private List volumePaths; private Boolean quiesce; @LogLevel(LogLevel.Log4jLevel.Off) @@ -80,6 +82,14 @@ public class TakeBackupCommand extends Command { this.mountOptions = mountOptions; } + public List getVolumePools() { + return volumePools; + } + + public void setVolumePools(List volumePools) { + this.volumePools = volumePools; + } + public List getVolumePaths() { return volumePaths; } diff --git a/core/src/main/java/org/apache/cloudstack/storage/command/CheckDataStoreStoragePolicyComplainceCommand.java b/core/src/main/java/org/apache/cloudstack/storage/command/CheckDataStoreStoragePolicyComplianceCommand.java similarity index 93% rename from core/src/main/java/org/apache/cloudstack/storage/command/CheckDataStoreStoragePolicyComplainceCommand.java rename to core/src/main/java/org/apache/cloudstack/storage/command/CheckDataStoreStoragePolicyComplianceCommand.java index f9544b873ef..4544e98451f 100644 --- a/core/src/main/java/org/apache/cloudstack/storage/command/CheckDataStoreStoragePolicyComplainceCommand.java +++ b/core/src/main/java/org/apache/cloudstack/storage/command/CheckDataStoreStoragePolicyComplianceCommand.java @@ -21,12 +21,12 @@ package org.apache.cloudstack.storage.command; import com.cloud.agent.api.to.StorageFilerTO; -public class CheckDataStoreStoragePolicyComplainceCommand extends StorageSubSystemCommand { +public class CheckDataStoreStoragePolicyComplianceCommand extends StorageSubSystemCommand { String storagePolicyId; private StorageFilerTO storagePool; - public CheckDataStoreStoragePolicyComplainceCommand(String storagePolicyId, StorageFilerTO storagePool) { + public CheckDataStoreStoragePolicyComplianceCommand(String storagePolicyId, StorageFilerTO storagePool) { super(); this.storagePolicyId = storagePolicyId; diff --git a/core/src/main/java/org/apache/cloudstack/storage/to/VolumeObjectTO.java b/core/src/main/java/org/apache/cloudstack/storage/to/VolumeObjectTO.java index 92f9ee497a4..827403ac5ef 100644 --- a/core/src/main/java/org/apache/cloudstack/storage/to/VolumeObjectTO.java +++ b/core/src/main/java/org/apache/cloudstack/storage/to/VolumeObjectTO.java @@ -116,8 +116,8 @@ public class VolumeObjectTO extends DownloadableObjectTO implements DataTO { iopsWriteRate = volume.getIopsWriteRate(); iopsWriteRateMax = volume.getIopsWriteRateMax(); iopsWriteRateMaxLength = volume.getIopsWriteRateMaxLength(); - cacheMode = volume.getCacheMode(); hypervisorType = volume.getHypervisorType(); + setCacheMode(volume.getCacheMode()); setDeviceId(volume.getDeviceId()); this.migrationOptions = volume.getMigrationOptions(); this.directDownload = volume.isDirectDownload(); @@ -343,6 +343,10 @@ public class VolumeObjectTO extends DownloadableObjectTO implements DataTO { } public void setCacheMode(DiskCacheMode cacheMode) { + if (DiskCacheMode.HYPERVISOR_DEFAULT.equals(cacheMode) && !Hypervisor.HypervisorType.KVM.equals(hypervisorType)) { + this.cacheMode = DiskCacheMode.NONE; + return; + } this.cacheMode = cacheMode; } diff --git a/debian/changelog b/debian/changelog index ace6697a09e..02251137e9d 100644 --- a/debian/changelog +++ b/debian/changelog @@ -1,6 +1,12 @@ -cloudstack (4.22.0.0-SNAPSHOT) unstable; urgency=low +cloudstack (4.23.0.0-SNAPSHOT) unstable; urgency=low - * Update the version to 4.22.0.0-SNAPSHOT + * Update the version to 4.23.0.0-SNAPSHOT + + -- the Apache CloudStack project Thu, 30 Oct 2025 19:23:55 +0530 + +cloudstack (4.23.0.0-SNAPSHOT-SNAPSHOT) unstable; urgency=low + + * Update the version to 4.23.0.0-SNAPSHOT-SNAPSHOT -- the Apache CloudStack project Thu, Aug 28 11:58:36 2025 +0530 diff --git a/debian/cloudstack-management.install b/debian/cloudstack-management.install index b2a32bd93c1..befc7049c30 100644 --- a/debian/cloudstack-management.install +++ b/debian/cloudstack-management.install @@ -24,6 +24,7 @@ /etc/cloudstack/management/config.json /etc/cloudstack/extensions/Proxmox/proxmox.sh /etc/cloudstack/extensions/HyperV/hyperv.py +/etc/cloudstack/extensions/MaaS/maas.py /etc/default/cloudstack-management /etc/security/limits.d/cloudstack-limits.conf /etc/sudoers.d/cloudstack diff --git a/developer/pom.xml b/developer/pom.xml index c11415e04fa..e2fd782fd25 100644 --- a/developer/pom.xml +++ b/developer/pom.xml @@ -25,7 +25,7 @@ org.apache.cloudstack cloudstack - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT diff --git a/engine/api/pom.xml b/engine/api/pom.xml index 9dcdb8e8f52..cb50ef0cd46 100644 --- a/engine/api/pom.xml +++ b/engine/api/pom.xml @@ -24,7 +24,7 @@ org.apache.cloudstack cloud-engine - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT ../pom.xml diff --git a/engine/api/src/main/java/com/cloud/vm/VirtualMachineManager.java b/engine/api/src/main/java/com/cloud/vm/VirtualMachineManager.java index c05c29add55..70240454689 100644 --- a/engine/api/src/main/java/com/cloud/vm/VirtualMachineManager.java +++ b/engine/api/src/main/java/com/cloud/vm/VirtualMachineManager.java @@ -106,6 +106,9 @@ public interface VirtualMachineManager extends Manager { ConfigKey VmSyncPowerStateTransitioning = new ConfigKey<>("Advanced", Boolean.class, "vm.sync.power.state.transitioning", "true", "Whether to sync power states of the transitioning and stalled VMs while processing VM power reports.", false); + ConfigKey SystemVmEnableUserData = new ConfigKey<>(Boolean.class, "systemvm.userdata.enabled", "Advanced", "false", + "Enable user data for system VMs. When enabled, the CPVM, SSVM, and Router system VMs will use the values from the global settings console.proxy.vm.userdata, secstorage.vm.userdata, and virtual.router.userdata, respectively, to provide cloud-init user data to the VM.", + true, ConfigKey.Scope.Zone, null); interface Topics { String VM_POWER_STATE = "vm.powerstate"; @@ -274,7 +277,7 @@ public interface VirtualMachineManager extends Manager { * - Remove the references of the VM and its volumes, nics, IPs from database * - Keep the VM as it is on the hypervisor */ - boolean unmanage(String vmUuid); + Pair unmanage(String vmUuid, Long paramHostId); UserVm restoreVirtualMachine(long vmId, Long newTemplateId, Long rootDiskOfferingId, boolean expunge, Map details) throws ResourceUnavailableException, InsufficientCapacityException, ResourceAllocationException; diff --git a/engine/api/src/main/java/org/apache/cloudstack/engine/orchestration/service/NetworkOrchestrationService.java b/engine/api/src/main/java/org/apache/cloudstack/engine/orchestration/service/NetworkOrchestrationService.java index adce5f2f8b4..31b08429cc4 100644 --- a/engine/api/src/main/java/org/apache/cloudstack/engine/orchestration/service/NetworkOrchestrationService.java +++ b/engine/api/src/main/java/org/apache/cloudstack/engine/orchestration/service/NetworkOrchestrationService.java @@ -76,44 +76,52 @@ public interface NetworkOrchestrationService { */ Long RVRHandoverTime = 10000L; - ConfigKey MinVRVersion = new ConfigKey(String.class, MinVRVersionCK, "Advanced", "4.10.0", + ConfigKey MinVRVersion = new ConfigKey<>(String.class, MinVRVersionCK, "Advanced", "4.10.0", "What version should the Virtual Routers report", true, ConfigKey.Scope.Zone, null); - ConfigKey NetworkLockTimeout = new ConfigKey(Integer.class, NetworkLockTimeoutCK, "Network", "600", - "Lock wait timeout (seconds) while implementing network", true, Scope.Global, null); + ConfigKey NetworkLockTimeout = new ConfigKey<>(Integer.class, NetworkLockTimeoutCK, "Network", "600", + "Lock wait timeout (seconds) while implementing network", true, Scope.Global, null); - ConfigKey DeniedRoutes = new ConfigKey(String.class, "denied.routes", "Network", "", + ConfigKey DeniedRoutes = new ConfigKey<>(String.class, "denied.routes", "Network", "", "Routes that are denied, can not be used for Static Routes creation for the VPC Private Gateway", true, ConfigKey.Scope.Zone, null); - ConfigKey GuestDomainSuffix = new ConfigKey(String.class, GuestDomainSuffixCK, "Network", "cloud.internal", - "Default domain name for vms inside virtualized networks fronted by router", true, ConfigKey.Scope.Zone, null); + ConfigKey GuestDomainSuffix = new ConfigKey<>(String.class, GuestDomainSuffixCK, "Network", "cloud.internal", + "Default domain name for vms inside virtualized networks fronted by router", true, ConfigKey.Scope.Zone, null); - ConfigKey NetworkThrottlingRate = new ConfigKey("Network", Integer.class, NetworkThrottlingRateCK, "200", - "Default data transfer rate in megabits per second allowed in network.", true, ConfigKey.Scope.Zone); + ConfigKey NetworkThrottlingRate = new ConfigKey<>("Network", Integer.class, NetworkThrottlingRateCK, "200", + "Default data transfer rate in megabits per second allowed in network.", true, ConfigKey.Scope.Zone); - ConfigKey PromiscuousMode = new ConfigKey("Advanced", Boolean.class, "network.promiscuous.mode", "false", + ConfigKey PromiscuousMode = new ConfigKey<>("Advanced", Boolean.class, "network.promiscuous.mode", "false", "Whether to allow or deny promiscuous mode on nics for applicable network elements such as for vswitch/dvswitch portgroups.", true); - ConfigKey MacAddressChanges = new ConfigKey("Advanced", Boolean.class, "network.mac.address.changes", "true", + ConfigKey MacAddressChanges = new ConfigKey<>("Advanced", Boolean.class, "network.mac.address.changes", "true", "Whether to allow or deny mac address changes on nics for applicable network elements such as for vswitch/dvswitch porgroups.", true); - ConfigKey ForgedTransmits = new ConfigKey("Advanced", Boolean.class, "network.forged.transmits", "true", + ConfigKey ForgedTransmits = new ConfigKey<>("Advanced", Boolean.class, "network.forged.transmits", "true", "Whether to allow or deny forged transmits on nics for applicable network elements such as for vswitch/dvswitch portgroups.", true); - ConfigKey MacLearning = new ConfigKey("Advanced", Boolean.class, "network.mac.learning", "false", + ConfigKey MacLearning = new ConfigKey<>("Advanced", Boolean.class, "network.mac.learning", "false", "Whether to allow or deny MAC learning on nics for applicable network elements such as for dvswitch portgroups.", true); - ConfigKey RollingRestartEnabled = new ConfigKey("Advanced", Boolean.class, "network.rolling.restart", "true", + ConfigKey RollingRestartEnabled = new ConfigKey<>("Advanced", Boolean.class, "network.rolling.restart", "true", "Whether to allow or deny rolling restart of network routers.", true); - static final ConfigKey TUNGSTEN_ENABLED = new ConfigKey<>(Boolean.class, "tungsten.plugin.enable", "Advanced", "false", + ConfigKey TUNGSTEN_ENABLED = new ConfigKey<>(Boolean.class, "tungsten.plugin.enable", "Advanced", "false", "Indicates whether to enable the Tungsten plugin", false, ConfigKey.Scope.Zone, null); - static final ConfigKey NSX_ENABLED = new ConfigKey<>(Boolean.class, "nsx.plugin.enable", "Advanced", "false", + ConfigKey NSX_ENABLED = new ConfigKey<>(Boolean.class, "nsx.plugin.enable", "Advanced", "false", "Indicates whether to enable the NSX plugin", false, ConfigKey.Scope.Zone, null); ConfigKey NETRIS_ENABLED = new ConfigKey<>(Boolean.class, "netris.plugin.enable", "Advanced", "false", "Indicates whether to enable the Netris plugin", false, ConfigKey.Scope.Zone, null); + ConfigKey NETWORK_LB_HAPROXY_MAX_CONN = new ConfigKey<>( + "Network", + Integer.class, + "network.loadbalancer.haproxy.max.conn", + "4096", + "Load Balancer(haproxy) maximum number of concurrent connections(global max)", + true, + Scope.Global); List setupNetwork(Account owner, NetworkOffering offering, DeploymentPlan plan, String name, String displayText, boolean isDefault) throws ConcurrentOperationException; @@ -129,7 +137,7 @@ public interface NetworkOrchestrationService { * configures the provided dhcp options on the given nic. * @param network of the nic * @param nicId - * @param extraDhcpOptions + * @param extraDhcpOptions a map of rank:value pairs */ void configureExtraDhcpOptions(Network network, long nicId, Map extraDhcpOptions); @@ -158,16 +166,15 @@ public interface NetworkOrchestrationService { Pair implementNetwork(long networkId, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException; - Map getExtraDhcpOptions(long nicId); - /** * Returns all extra dhcp options which are set on the provided nic * @param nicId * @return map which maps the dhcp value on it's option code */ + Map getExtraDhcpOptions(long nicId); + /** * prepares vm nic change for migration - * * This method will be called in migration transaction before the vm migration. * @param vm * @param dest @@ -176,7 +183,6 @@ public interface NetworkOrchestrationService { /** * commit vm nic change for migration - * * This method will be called in migration transaction after the successful * vm migration. * @param src @@ -186,7 +192,6 @@ public interface NetworkOrchestrationService { /** * rollback vm nic change for migration - * * This method will be called in migaration transaction after vm migration * failure. * @param src @@ -266,7 +271,7 @@ public interface NetworkOrchestrationService { void releaseNic(VirtualMachineProfile vmProfile, Nic nic) throws ConcurrentOperationException, ResourceUnavailableException; NicProfile createNicForVm(Network network, NicProfile requested, ReservationContext context, VirtualMachineProfile vmProfile, boolean prepare) - throws InsufficientVirtualNetworkCapacityException, InsufficientAddressCapacityException, ConcurrentOperationException, InsufficientCapacityException, + throws ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException; NetworkProfile convertNetworkToNetworkProfile(long networkId); @@ -277,7 +282,7 @@ public interface NetworkOrchestrationService { boolean shutdownNetworkElementsAndResources(ReservationContext context, boolean b, Network network); void implementNetworkElementsAndResources(DeployDestination dest, ReservationContext context, Network network, NetworkOffering findById) - throws ConcurrentOperationException, InsufficientAddressCapacityException, ResourceUnavailableException, InsufficientCapacityException; + throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException; Map finalizeServicesAndProvidersForNetwork(NetworkOffering offering, Long physicalNetworkId); diff --git a/engine/api/src/main/java/org/apache/cloudstack/engine/orchestration/service/VolumeOrchestrationService.java b/engine/api/src/main/java/org/apache/cloudstack/engine/orchestration/service/VolumeOrchestrationService.java index ccb5bba1c0a..168822c21eb 100644 --- a/engine/api/src/main/java/org/apache/cloudstack/engine/orchestration/service/VolumeOrchestrationService.java +++ b/engine/api/src/main/java/org/apache/cloudstack/engine/orchestration/service/VolumeOrchestrationService.java @@ -23,6 +23,7 @@ import java.util.Map; import java.util.Set; import com.cloud.exception.ResourceAllocationException; +import com.cloud.storage.Storage; import com.cloud.utils.Pair; import org.apache.cloudstack.engine.subsystem.api.storage.DataObject; import org.apache.cloudstack.engine.subsystem.api.storage.DataStore; @@ -182,10 +183,10 @@ public interface VolumeOrchestrationService { */ DiskProfile importVolume(Type type, String name, DiskOffering offering, Long sizeInBytes, Long minIops, Long maxIops, Long zoneId, HypervisorType hypervisorType, VirtualMachine vm, VirtualMachineTemplate template, - Account owner, Long deviceId, Long poolId, String path, String chainInfo); + Account owner, Long deviceId, Long poolId, Storage.StoragePoolType poolType, String path, String chainInfo); DiskProfile updateImportedVolume(Type type, DiskOffering offering, VirtualMachine vm, VirtualMachineTemplate template, - Long deviceId, Long poolId, String path, String chainInfo, DiskProfile diskProfile); + Long deviceId, Long poolId, Storage.StoragePoolType poolType, String path, String chainInfo, DiskProfile diskProfile); /** * Unmanage VM volumes diff --git a/engine/api/src/main/java/org/apache/cloudstack/engine/subsystem/api/storage/ClusterScope.java b/engine/api/src/main/java/org/apache/cloudstack/engine/subsystem/api/storage/ClusterScope.java index b0ed7d7d52b..68c7ed40d8f 100644 --- a/engine/api/src/main/java/org/apache/cloudstack/engine/subsystem/api/storage/ClusterScope.java +++ b/engine/api/src/main/java/org/apache/cloudstack/engine/subsystem/api/storage/ClusterScope.java @@ -19,6 +19,7 @@ package org.apache.cloudstack.engine.subsystem.api.storage; import com.cloud.storage.ScopeType; +import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils; public class ClusterScope extends AbstractScope { private ScopeType type = ScopeType.CLUSTER; @@ -51,4 +52,9 @@ public class ClusterScope extends AbstractScope { return this.zoneId; } + @Override + public String toString() { + return String.format("ClusterScope %s", ReflectionToStringBuilderUtils.reflectOnlySelectedFields( + this, "zoneId", "clusterId", "podId")); + } } diff --git a/engine/api/src/main/java/org/apache/cloudstack/engine/subsystem/api/storage/HostScope.java b/engine/api/src/main/java/org/apache/cloudstack/engine/subsystem/api/storage/HostScope.java index 6e0bc618bfe..7e6ffe7d4f7 100644 --- a/engine/api/src/main/java/org/apache/cloudstack/engine/subsystem/api/storage/HostScope.java +++ b/engine/api/src/main/java/org/apache/cloudstack/engine/subsystem/api/storage/HostScope.java @@ -19,8 +19,10 @@ package org.apache.cloudstack.engine.subsystem.api.storage; import com.cloud.storage.ScopeType; +import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils; public class HostScope extends AbstractScope { + private ScopeType type = ScopeType.HOST; private Long hostId; private Long clusterId; private Long zoneId; @@ -34,7 +36,7 @@ public class HostScope extends AbstractScope { @Override public ScopeType getScopeType() { - return ScopeType.HOST; + return this.type; } @Override @@ -49,4 +51,10 @@ public class HostScope extends AbstractScope { public Long getZoneId() { return zoneId; } + + @Override + public String toString() { + return String.format("HostScope %s", ReflectionToStringBuilderUtils.reflectOnlySelectedFields( + this, "zoneId", "clusterId", "hostId")); + } } diff --git a/engine/api/src/main/java/org/apache/cloudstack/engine/subsystem/api/storage/PrimaryDataStoreLifeCycle.java b/engine/api/src/main/java/org/apache/cloudstack/engine/subsystem/api/storage/PrimaryDataStoreLifeCycle.java index 54f3c63f8d7..1acaccf09df 100644 --- a/engine/api/src/main/java/org/apache/cloudstack/engine/subsystem/api/storage/PrimaryDataStoreLifeCycle.java +++ b/engine/api/src/main/java/org/apache/cloudstack/engine/subsystem/api/storage/PrimaryDataStoreLifeCycle.java @@ -24,8 +24,8 @@ import com.cloud.hypervisor.Hypervisor; import com.cloud.storage.StoragePool; public interface PrimaryDataStoreLifeCycle extends DataStoreLifeCycle { - public static final String CAPACITY_BYTES = "capacityBytes"; - public static final String CAPACITY_IOPS = "capacityIops"; + String CAPACITY_BYTES = "capacityBytes"; + String CAPACITY_IOPS = "capacityIops"; void updateStoragePool(StoragePool storagePool, Map details); void enableStoragePool(DataStore store); diff --git a/engine/api/src/main/java/org/apache/cloudstack/engine/subsystem/api/storage/SnapshotDataFactory.java b/engine/api/src/main/java/org/apache/cloudstack/engine/subsystem/api/storage/SnapshotDataFactory.java index 2a2db4af3e5..d318707a29a 100644 --- a/engine/api/src/main/java/org/apache/cloudstack/engine/subsystem/api/storage/SnapshotDataFactory.java +++ b/engine/api/src/main/java/org/apache/cloudstack/engine/subsystem/api/storage/SnapshotDataFactory.java @@ -21,6 +21,7 @@ package org.apache.cloudstack.engine.subsystem.api.storage; import java.util.List; import com.cloud.storage.DataStoreRole; +import com.cloud.utils.fsm.NoTransitionException; public interface SnapshotDataFactory { SnapshotInfo getSnapshot(long snapshotId, DataStore store); @@ -42,4 +43,6 @@ public interface SnapshotDataFactory { List listSnapshotOnCache(long snapshotId); SnapshotInfo getReadySnapshotOnCache(long snapshotId); + + void updateOperationFailed(long snapshotId) throws NoTransitionException; } diff --git a/engine/api/src/main/java/org/apache/cloudstack/engine/subsystem/api/storage/VMSnapshotStrategy.java b/engine/api/src/main/java/org/apache/cloudstack/engine/subsystem/api/storage/VMSnapshotStrategy.java index 6372aa3bd94..2939342ec27 100644 --- a/engine/api/src/main/java/org/apache/cloudstack/engine/subsystem/api/storage/VMSnapshotStrategy.java +++ b/engine/api/src/main/java/org/apache/cloudstack/engine/subsystem/api/storage/VMSnapshotStrategy.java @@ -18,6 +18,7 @@ */ package org.apache.cloudstack.engine.subsystem.api.storage; +import com.cloud.utils.fsm.NoTransitionException; import com.cloud.vm.snapshot.VMSnapshot; public interface VMSnapshotStrategy { @@ -44,4 +45,6 @@ public interface VMSnapshotStrategy { * @return true if vm snapshot removed from DB, false if not. */ boolean deleteVMSnapshotFromDB(VMSnapshot vmSnapshot, boolean unmanage); + + void updateOperationFailed(VMSnapshot vmSnapshot) throws NoTransitionException; } diff --git a/engine/api/src/main/java/org/apache/cloudstack/engine/subsystem/api/storage/ZoneScope.java b/engine/api/src/main/java/org/apache/cloudstack/engine/subsystem/api/storage/ZoneScope.java index a0d75b5cc7c..fa704d05b1a 100644 --- a/engine/api/src/main/java/org/apache/cloudstack/engine/subsystem/api/storage/ZoneScope.java +++ b/engine/api/src/main/java/org/apache/cloudstack/engine/subsystem/api/storage/ZoneScope.java @@ -19,6 +19,7 @@ package org.apache.cloudstack.engine.subsystem.api.storage; import com.cloud.storage.ScopeType; +import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils; public class ZoneScope extends AbstractScope { private ScopeType type = ScopeType.ZONE; @@ -39,4 +40,9 @@ public class ZoneScope extends AbstractScope { return this.zoneId; } + @Override + public String toString() { + return String.format("ZoneScope %s", ReflectionToStringBuilderUtils.reflectOnlySelectedFields( + this, "zoneId")); + } } diff --git a/engine/components-api/pom.xml b/engine/components-api/pom.xml index ed67de2e0d8..49d41d36f83 100644 --- a/engine/components-api/pom.xml +++ b/engine/components-api/pom.xml @@ -24,7 +24,7 @@ org.apache.cloudstack cloud-engine - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT ../pom.xml diff --git a/engine/components-api/src/main/java/com/cloud/configuration/ConfigurationManager.java b/engine/components-api/src/main/java/com/cloud/configuration/ConfigurationManager.java index eebf764289d..5909d098db8 100644 --- a/engine/components-api/src/main/java/com/cloud/configuration/ConfigurationManager.java +++ b/engine/components-api/src/main/java/com/cloud/configuration/ConfigurationManager.java @@ -56,10 +56,10 @@ import com.cloud.utils.net.NetUtils; */ public interface ConfigurationManager { - public static final String MESSAGE_CREATE_POD_IP_RANGE_EVENT = "Message.CreatePodIpRange.Event"; - public static final String MESSAGE_DELETE_POD_IP_RANGE_EVENT = "Message.DeletePodIpRange.Event"; - public static final String MESSAGE_CREATE_VLAN_IP_RANGE_EVENT = "Message.CreateVlanIpRange.Event"; - public static final String MESSAGE_DELETE_VLAN_IP_RANGE_EVENT = "Message.DeleteVlanIpRange.Event"; + String MESSAGE_CREATE_POD_IP_RANGE_EVENT = "Message.CreatePodIpRange.Event"; + String MESSAGE_DELETE_POD_IP_RANGE_EVENT = "Message.DeletePodIpRange.Event"; + String MESSAGE_CREATE_VLAN_IP_RANGE_EVENT = "Message.CreateVlanIpRange.Event"; + String MESSAGE_DELETE_VLAN_IP_RANGE_EVENT = "Message.DeleteVlanIpRange.Event"; public static final ConfigKey AllowNonRFC1918CompliantIPs = new ConfigKey<>(Boolean.class, "allow.non.rfc1918.compliant.ips", "Advanced", "false", @@ -72,8 +72,9 @@ public interface ConfigurationManager { true, ConfigKey.Scope.Global); /** - * @param offering - * @return + * Is this for a VPC + * @param offering the offering to check + * @return true or false */ boolean isOfferingForVpc(NetworkOffering offering); @@ -83,80 +84,12 @@ public interface ConfigurationManager { /** * Updates a configuration entry with a new value - * @param userId - * @param name - * @param category - * @param value - * @param scope - * @param id */ String updateConfiguration(long userId, String name, String category, String value, ConfigKey.Scope scope, Long id); -// /** -// * Creates a new service offering -// * -// * @param name -// * @param cpu -// * @param ramSize -// * @param speed -// * @param displayText -// * @param localStorageRequired -// * @param offerHA -// * @param domainId -// * @param volatileVm -// * @param hostTag -// * @param networkRate -// * @param id -// * @param useVirtualNetwork -// * @param deploymentPlanner -// * @param details -// * @param bytesReadRate -// * @param bytesWriteRate -// * @param iopsReadRate -// * @param iopsWriteRate -// * @return ID -// */ -// ServiceOfferingVO createServiceOffering(long userId, boolean isSystem, VirtualMachine.Type vm_typeType, String name, int cpu, int ramSize, int speed, String displayText, boolean localStorageRequired, -// boolean offerHA, boolean limitResourceUse, boolean volatileVm, String tags, Long domainId, String hostTag, Integer networkRate, String deploymentPlanner, Map details, -// Long bytesReadRate, Long bytesWriteRate, Long iopsReadRate, Long iopsWriteRate); - -// /** -// * Creates a new disk offering -// * -// * @param domainId -// * @param name -// * @param description -// * @param numGibibytes -// * @param tags -// * @param isCustomized -// * @param localStorageRequired -// * @param isDisplayOfferingEnabled -// * @param isCustomizedIops (is admin allowing users to set custom iops?) -// * @param minIops -// * @param maxIops -// * @param bytesReadRate -// * @param bytesWriteRate -// * @param iopsReadRate -// * @param iopsWriteRate -// * @return newly created disk offering -// */ -// DiskOfferingVO createDiskOffering(Long domainId, String name, String description, Long numGibibytes, String tags, boolean isCustomized, -// boolean localStorageRequired, boolean isDisplayOfferingEnabled, Boolean isCustomizedIops, Long minIops, Long maxIops, -// Long bytesReadRate, Long bytesWriteRate, Long iopsReadRate, Long iopsWriteRate); - /** * Creates a new pod - * - * @param userId - * @param podName - * @param zone - * @param gateway - * @param cidr - * @param startIp - * @param endIp - * @param allocationState * @param skipGatewayOverlapCheck (true if it is ok to not validate that gateway IP address overlap with Start/End IP of the POD) - * @param storageAccessGroups * @return Pod */ HostPodVO createPod(long userId, String podName, DataCenter zone, String gateway, String cidr, String startIp, String endIp, String allocationState, @@ -164,7 +97,6 @@ public interface ConfigurationManager { /** * Creates a new zone - * * @param userId * @param zoneName * @param dns1 @@ -172,16 +104,18 @@ public interface ConfigurationManager { * @param internalDns1 * @param internalDns2 * @param guestCidr + * @param domain + * @param domainId * @param zoneType * @param allocationState * @param networkDomain * @param isSecurityGroupEnabled + * @param isLocalStorageEnabled * @param ip6Dns1 * @param ip6Dns2 + * @param isEdge * @param storageAccessGroups * @return - * @throws - * @throws */ DataCenterVO createZone(long userId, String zoneName, String dns1, String dns2, String internalDns1, String internalDns2, String guestCidr, String domain, Long domainId, NetworkType zoneType, String allocationState, String networkDomain, boolean isSecurityGroupEnabled, boolean isLocalStorageEnabled, String ip6Dns1, @@ -191,9 +125,7 @@ public interface ConfigurationManager { * Deletes a VLAN from the database, along with all of its IP addresses. Will not delete VLANs that have allocated * IP addresses. * - * @param userId - * @param vlanDbId - * @param caller + * @param caller TODO * @return success/failure */ VlanVO deleteVlanAndPublicIpRange(long userId, long vlanDbId, Account caller); @@ -204,31 +136,39 @@ public interface ConfigurationManager { /** * Creates a new network offering - * * @param name * @param displayText * @param trafficType * @param tags * @param specifyVlan + * @param availability * @param networkRate * @param serviceProviderMap * @param isDefault * @param type * @param systemOnly * @param serviceOfferingId - * @param conserveMode ; + * @param conserveMode + * @param serviceCapabilityMap * @param specifyIpRanges - * @param isPersistent ; + * @param isPersistent * @param details + * @param egressDefaultPolicy + * @param maxconn + * @param enableKeepAlive * @param forVpc * @param forTungsten * @param forNsx * @param forNetris + * @param networkMode * @param domainIds * @param zoneIds - * @return network offering object + * @param enableOffering + * @param internetProtocol + * @param routingMode + * @param specifyAsNumber + * @return the network offering */ - NetworkOfferingVO createNetworkOffering(String name, String displayText, TrafficType trafficType, String tags, boolean specifyVlan, Availability availability, Integer networkRate, Map> serviceProviderMap, boolean isDefault, Network.GuestType type, boolean systemOnly, Long serviceOfferingId, boolean conserveMode, Map> serviceCapabilityMap, boolean specifyIpRanges, boolean isPersistent, @@ -245,7 +185,6 @@ public interface ConfigurationManager { /** * Release dedicated virtual ip ranges of a domain. * - * @param domainId * @return success/failure */ boolean releaseDomainSpecificVirtualRanges(Domain domain); @@ -253,7 +192,6 @@ public interface ConfigurationManager { /** * Release dedicated virtual ip ranges of an account. * - * @param accountId * @return success/failure */ boolean releaseAccountSpecificVirtualRanges(Account account); @@ -261,16 +199,7 @@ public interface ConfigurationManager { /** * Edits a pod in the database. Will not allow you to edit pods that are being used anywhere in the system. * - * @param id - * @param name - * @param startIp - * @param endIp - * @param gateway - * @param netmask - * @param allocationState * @return Pod - * @throws - * @throws */ Pod editPod(long id, String name, String startIp, String endIp, String gateway, String netmask, String allocationState); diff --git a/engine/components-api/src/main/java/com/cloud/hypervisor/ExternalProvisioner.java b/engine/components-api/src/main/java/com/cloud/hypervisor/ExternalProvisioner.java index a22ea421113..c574a8be017 100644 --- a/engine/components-api/src/main/java/com/cloud/hypervisor/ExternalProvisioner.java +++ b/engine/components-api/src/main/java/com/cloud/hypervisor/ExternalProvisioner.java @@ -18,6 +18,8 @@ package com.cloud.hypervisor; import java.util.Map; +import com.cloud.agent.api.GetExternalConsoleAnswer; +import com.cloud.agent.api.GetExternalConsoleCommand; import com.cloud.agent.api.HostVmStateReportEntry; import com.cloud.agent.api.PrepareExternalProvisioningAnswer; import com.cloud.agent.api.PrepareExternalProvisioningCommand; @@ -57,5 +59,7 @@ public interface ExternalProvisioner extends Manager { Map getHostVmStateReport(long hostId, String extensionName, String extensionRelativePath); + GetExternalConsoleAnswer getInstanceConsole(String hostGuid, String extensionName, String extensionRelativePath, GetExternalConsoleCommand cmd); + RunCustomActionAnswer runCustomAction(String hostGuid, String extensionName, String extensionRelativePath, RunCustomActionCommand cmd); } diff --git a/engine/components-api/src/main/java/com/cloud/storage/StorageManager.java b/engine/components-api/src/main/java/com/cloud/storage/StorageManager.java index d3a6d4525a5..77e97b00c1e 100644 --- a/engine/components-api/src/main/java/com/cloud/storage/StorageManager.java +++ b/engine/components-api/src/main/java/com/cloud/storage/StorageManager.java @@ -182,7 +182,7 @@ public interface StorageManager extends StorageService { ConfigKey MountDisabledStoragePool = new ConfigKey<>(Boolean.class, "mount.disabled.storage.pool", "Storage", - "false", + Boolean.TRUE.toString(), "Mount all zone-wide or cluster-wide disabled storage pools after node reboot", true, ConfigKey.Scope.Cluster, @@ -230,7 +230,7 @@ public interface StorageManager extends StorageService { /** * should we execute in sequence not involving any storages? - * @return tru if commands should execute in sequence + * @return true if commands should execute in sequence */ static boolean shouldExecuteInSequenceOnVmware() { return shouldExecuteInSequenceOnVmware(null, null); @@ -302,6 +302,8 @@ public interface StorageManager extends StorageService { Answer sendToPool(StoragePool pool, long[] hostIdsToTryFirst, Command cmd) throws StorageUnavailableException; + void updateStoragePoolHostVOAndBytes(StoragePool pool, long hostId, ModifyStoragePoolAnswer mspAnswer); + CapacityVO getSecondaryStorageUsedStats(Long hostId, Long zoneId); CapacityVO getStoragePoolUsedStats(Long poolId, Long clusterId, Long podId, Long zoneId); diff --git a/engine/components-api/src/main/java/com/cloud/template/TemplateManager.java b/engine/components-api/src/main/java/com/cloud/template/TemplateManager.java index 28f41c677cb..f363deffc1f 100644 --- a/engine/components-api/src/main/java/com/cloud/template/TemplateManager.java +++ b/engine/components-api/src/main/java/com/cloud/template/TemplateManager.java @@ -57,6 +57,13 @@ public interface TemplateManager { + "will validate if the provided URL is resolvable during the register of templates/ISOs before persisting them in the database.", true); + ConfigKey TemplateDeleteFromPrimaryStorage = new ConfigKey("Advanced", + Boolean.class, + "template.delete.from.primary.storage", "true", + "Template when deleted will be instantly deleted from the Primary Storage", + true, + ConfigKey.Scope.Global); + static final String VMWARE_TOOLS_ISO = "vmware-tools.iso"; static final String XS_TOOLS_ISO = "xs-tools.iso"; @@ -104,6 +111,8 @@ public interface TemplateManager { */ List getUnusedTemplatesInPool(StoragePoolVO pool); + void evictTemplateFromStoragePoolsForZones(Long templateId, List zoneId); + /** * Deletes a template in the specified storage pool. * diff --git a/engine/components-api/src/main/java/com/cloud/vm/snapshot/VMSnapshotManager.java b/engine/components-api/src/main/java/com/cloud/vm/snapshot/VMSnapshotManager.java index a01d4ee5cae..6478469f190 100644 --- a/engine/components-api/src/main/java/com/cloud/vm/snapshot/VMSnapshotManager.java +++ b/engine/components-api/src/main/java/com/cloud/vm/snapshot/VMSnapshotManager.java @@ -42,7 +42,7 @@ public interface VMSnapshotManager extends VMSnapshotService, Manager { boolean deleteAllVMSnapshots(long id, VMSnapshot.Type type); /** - * Sync VM snapshot state when VM snapshot in reverting or snapshoting or expunging state + * Sync VM snapshot state when VM snapshot in reverting or snapshotting or expunging state * Used for fullsync after agent connects * * @param vm, the VM in question @@ -54,5 +54,4 @@ public interface VMSnapshotManager extends VMSnapshotService, Manager { boolean hasActiveVMSnapshotTasks(Long vmId); RestoreVMSnapshotCommand createRestoreCommand(UserVmVO userVm, List vmSnapshotVOs); - } diff --git a/engine/orchestration/pom.xml b/engine/orchestration/pom.xml index c5040b6382b..fda63d2558b 100755 --- a/engine/orchestration/pom.xml +++ b/engine/orchestration/pom.xml @@ -24,7 +24,7 @@ org.apache.cloudstack cloud-engine - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT ../pom.xml diff --git a/engine/orchestration/src/main/java/com/cloud/vm/VirtualMachineManagerImpl.java b/engine/orchestration/src/main/java/com/cloud/vm/VirtualMachineManagerImpl.java index 3a6e1b62277..b3e672e2c17 100755 --- a/engine/orchestration/src/main/java/com/cloud/vm/VirtualMachineManagerImpl.java +++ b/engine/orchestration/src/main/java/com/cloud/vm/VirtualMachineManagerImpl.java @@ -71,6 +71,7 @@ import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreProviderManag import org.apache.cloudstack.engine.subsystem.api.storage.PrimaryDataStoreDriver; import org.apache.cloudstack.engine.subsystem.api.storage.StoragePoolAllocator; import org.apache.cloudstack.engine.subsystem.api.storage.VolumeDataFactory; +import org.apache.cloudstack.engine.subsystem.api.storage.VolumeInfo; import org.apache.cloudstack.framework.ca.Certificate; import org.apache.cloudstack.framework.config.ConfigKey; import org.apache.cloudstack.framework.config.Configurable; @@ -150,11 +151,13 @@ import com.cloud.agent.api.StopAnswer; import com.cloud.agent.api.StopCommand; import com.cloud.agent.api.UnPlugNicAnswer; import com.cloud.agent.api.UnPlugNicCommand; +import com.cloud.agent.api.UnmanageInstanceCommand; import com.cloud.agent.api.UnregisterVMCommand; import com.cloud.agent.api.VmDiskStatsEntry; import com.cloud.agent.api.VmNetworkStatsEntry; import com.cloud.agent.api.VmStatsEntry; import com.cloud.agent.api.routing.NetworkElementCommand; +import com.cloud.agent.api.to.DataTO; import com.cloud.agent.api.to.DiskTO; import com.cloud.agent.api.to.DpdkTO; import com.cloud.agent.api.to.GPUDeviceTO; @@ -1482,6 +1485,21 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac volumeMgr.prepare(vmProfile, dest); } + if (params != null) { + Boolean returnAfterVolumePrepare = (Boolean) params.get(VirtualMachineProfile.Param.ReturnAfterVolumePrepare); + if (Boolean.TRUE.equals(returnAfterVolumePrepare)) { + logger.info("Returning from VM start command execution for VM {} as requested. Volumes are prepared and ready.", vm.getUuid()); + + if (!changeState(vm, Event.AgentReportStopped, destHostId, work, Step.Done)) { + logger.error("Unable to transition to a new state. VM uuid: {}, VM oldstate: {}, Event: {}", vm, vm.getState(), Event.AgentReportStopped); + throw new ConcurrentOperationException(String.format("Failed to deploy VM %s", vm)); + } + + logger.debug("Volume preparation completed for VM {} (VM state set to Stopped)", vm); + return; + } + } + if (!reuseVolume) { reuseVolume = true; } @@ -2001,7 +2019,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } @Override - public boolean unmanage(String vmUuid) { + public Pair unmanage(String vmUuid, Long paramHostId) { VMInstanceVO vm = _vmDao.findByUuid(vmUuid); if (vm == null || vm.getRemoved() != null) { throw new CloudRuntimeException("Could not find VM with id = " + vmUuid); @@ -2014,6 +2032,10 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac throw new ConcurrentOperationException(msg); } + Long agentHostId = vm.getHostId(); + if (HypervisorType.KVM.equals(vm.getHypervisorType())) { + agentHostId = persistDomainForKVM(vm, paramHostId); + } Boolean result = Transaction.execute(new TransactionCallback() { @Override public Boolean doInTransaction(TransactionStatus status) { @@ -2037,21 +2059,66 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac return true; } }); + HostVO host = ApiDBUtils.findHostById(agentHostId); + if (host == null) { + return new Pair<>(result, null); + } + logger.debug("Selected host UUID: {} to unmanage Instance: {}.", host.getUuid(), vm.getName()); + ActionEventUtils.onActionEvent(User.UID_SYSTEM, Account.ACCOUNT_ID_SYSTEM, Domain.ROOT_DOMAIN, EventTypes.EVENT_VM_UNMANAGE, + String.format("Successfully unmanaged Instance: %s (ID: %s) on host ID: %s", vm.getName(), vm.getUuid(), host.getUuid()), + vm.getId(), ApiCommandResourceType.VirtualMachine.toString()); + return new Pair<>(result, host.getUuid()); + } - return BooleanUtils.isTrue(result); + Long persistDomainForKVM(VMInstanceVO vm, Long paramHostId) { + Long agentHostId = vm.getHostId(); + String vmName = vm.getName(); + UnmanageInstanceCommand unmanageInstanceCommand; + if (State.Stopped.equals(vm.getState())) { + if (paramHostId == null) { + Pair clusterAndHostId = findClusterAndHostIdForVm(vm, false); + agentHostId = clusterAndHostId.second(); + if (agentHostId == null) { + String errorMsg = "No available host to persist domain XML for Instance: " + vmName; + logger.debug(errorMsg); + throw new CloudRuntimeException(errorMsg); + } + } else { + agentHostId = paramHostId; + } + unmanageInstanceCommand = new UnmanageInstanceCommand(prepVmSpecForUnmanageCmd(vm.getId(), agentHostId)); // reconstruct vmSpec for stopped instance + } else { + unmanageInstanceCommand = new UnmanageInstanceCommand(vmName); + unmanageInstanceCommand.setConfigDriveAttached(vmInstanceDetailsDao.findDetail(vm.getId(), VmDetailConstants.CONFIG_DRIVE_LOCATION) != null); + } + + logger.debug("Selected host ID: {} to persist domain XML for Instance: {}.", agentHostId, vmName); + try { + Answer answer = _agentMgr.send(agentHostId, unmanageInstanceCommand); + if (!answer.getResult()) { + String errorMsg = "Failed to persist domain XML for Instance: " + vmName + " on host ID: " + agentHostId; + logger.debug(errorMsg); + throw new CloudRuntimeException(errorMsg); + } + } catch (AgentUnavailableException | OperationTimedoutException e) { + String errorMsg = "Failed to send command to persist domain XML for Instance: " + vmName + " on host ID: " + agentHostId; + logger.error(errorMsg, e); + throw new CloudRuntimeException(errorMsg); + } + return agentHostId; } /** * Clean up VM snapshots (if any) from DB */ - private void unmanageVMSnapshots(VMInstanceVO vm) { + void unmanageVMSnapshots(VMInstanceVO vm) { _vmSnapshotMgr.deleteVMSnapshotsFromDB(vm.getId(), true); } /** * Clean up volumes for a VM to be unmanaged from CloudStack */ - private void unmanageVMVolumes(VMInstanceVO vm) { + void unmanageVMVolumes(VMInstanceVO vm) { final Long hostId = vm.getHostId() != null ? vm.getHostId() : vm.getLastHostId(); if (hostId != null) { volumeMgr.revokeAccess(vm.getId(), hostId); @@ -2069,7 +2136,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac * - If 'unmanage.vm.preserve.nics' = true: then the NICs are not removed but still Allocated, to preserve MAC addresses * - If 'unmanage.vm.preserve.nics' = false: then the NICs are removed while unmanaging */ - private void unmanageVMNics(VirtualMachineProfile profile, VMInstanceVO vm) { + void unmanageVMNics(VirtualMachineProfile profile, VMInstanceVO vm) { logger.debug("Cleaning up NICs of {}.", vm.toString()); Boolean preserveNics = UnmanagedVMsManager.UnmanageVMPreserveNic.valueIn(vm.getDataCenterId()); if (BooleanUtils.isTrue(preserveNics)) { @@ -2792,6 +2859,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac } volume.setPath(result.getPath()); volume.setPoolId(pool.getId()); + volume.setPoolType(pool.getPoolType()); if (result.getChainInfo() != null) { volume.setChainInfo(result.getChainInfo()); } @@ -4004,6 +4072,62 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac vmTo.setEnterHardwareSetup(enterSetup == null ? false : enterSetup); } + /** + * This method helps constructing vmSpec for Unmanage operation for Stopped Instance + * @param vmId + * @param hostId + * @return VirtualMachineTO + */ + protected VirtualMachineTO prepVmSpecForUnmanageCmd(Long vmId, Long hostId) { + final VMInstanceVO vm = _vmDao.findById(vmId); + final Account owner = _entityMgr.findById(Account.class, vm.getAccountId()); + final ServiceOfferingVO offering = _offeringDao.findById(vm.getId(), vm.getServiceOfferingId()); + final VirtualMachineTemplate template = _entityMgr.findByIdIncludingRemoved(VirtualMachineTemplate.class, vm.getTemplateId()); + Host host = _hostDao.findById(hostId); + VirtualMachineProfileImpl vmProfile = new VirtualMachineProfileImpl(vm, template, offering, owner, null); + updateOverCommitRatioForVmProfile(vmProfile, host.getClusterId()); + final List nics = _nicsDao.listByVmId(vmProfile.getId()); + Collections.sort(nics, (nic1, nic2) -> { + Long nicId1 = Long.valueOf(nic1.getDeviceId()); + Long nicId2 = Long.valueOf(nic2.getDeviceId()); + return nicId1.compareTo(nicId2); + }); + + for (final NicVO nic : nics) { + final Network network = _networkModel.getNetwork(nic.getNetworkId()); + final NicProfile nicProfile = + new NicProfile(nic, network, nic.getBroadcastUri(), nic.getIsolationUri(), null, _networkModel.isSecurityGroupSupportedInNetwork(network), + _networkModel.getNetworkTag(vmProfile.getHypervisorType(), network)); + vmProfile.addNic(nicProfile); + } + + List volumes = _volsDao.findUsableVolumesForInstance(vmId); + for (VolumeVO vol: volumes) { + VolumeInfo volumeInfo = volumeDataFactory.getVolume(vol.getId()); + DataTO dataTO = volumeInfo.getTO(); + DiskTO disk = storageMgr.getDiskWithThrottling(dataTO, vol.getVolumeType(), vol.getDeviceId(), vol.getPath(), vm.getServiceOfferingId(), vol.getDiskOfferingId()); + vmProfile.addDisk(disk); + } + + Map details = vmInstanceDetailsDao.listDetailsKeyPairs(vmId, + List.of(VirtualMachineProfile.Param.BootType.getName(), VirtualMachineProfile.Param.BootMode.getName(), + VirtualMachineProfile.Param.UefiFlag.getName())); + + if (details.containsKey(VirtualMachineProfile.Param.BootType.getName())) { + vmProfile.getParameters().put(VirtualMachineProfile.Param.BootType, details.get(VirtualMachineProfile.Param.BootType.getName())); + } + + if (details.containsKey(VirtualMachineProfile.Param.BootMode.getName())) { + vmProfile.getParameters().put(VirtualMachineProfile.Param.BootMode, details.get(VirtualMachineProfile.Param.BootMode.getName())); + } + + if (details.containsKey(VirtualMachineProfile.Param.UefiFlag.getName())) { + vmProfile.getParameters().put(VirtualMachineProfile.Param.UefiFlag, details.get(VirtualMachineProfile.Param.UefiFlag.getName())); + } + + return toVmTO(vmProfile); + } + protected VirtualMachineTO getVmTO(Long vmId) { final VMInstanceVO vm = _vmDao.findById(vmId); final VirtualMachineProfile profile = new VirtualMachineProfileImpl(vm); @@ -5121,7 +5245,7 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac VmConfigDriveLabel, VmConfigDriveOnPrimaryPool, VmConfigDriveForceHostCacheUse, VmConfigDriveUseHostCacheOnUnsupportedPool, HaVmRestartHostUp, ResourceCountRunningVMsonly, AllowExposeHypervisorHostname, AllowExposeHypervisorHostnameAccountLevel, SystemVmRootDiskSize, AllowExposeDomainInMetadata, MetadataCustomCloudName, VmMetadataManufacturer, VmMetadataProductName, - VmSyncPowerStateTransitioning + VmSyncPowerStateTransitioning, SystemVmEnableUserData }; } @@ -6170,8 +6294,9 @@ public class VirtualMachineManagerImpl extends ManagerBase implements VirtualMac host = host == null ? _hostDao.findById(hostId) : host; if (host != null) { clusterId = host.getClusterId(); + return new Pair<>(clusterId, hostId); } - return new Pair<>(clusterId, hostId); + return findClusterAndHostIdForVmFromVolumes(vm.getId()); } private Pair findClusterAndHostIdForVm(VirtualMachine vm) { diff --git a/engine/orchestration/src/main/java/org/apache/cloudstack/engine/orchestration/NetworkOrchestrator.java b/engine/orchestration/src/main/java/org/apache/cloudstack/engine/orchestration/NetworkOrchestrator.java index 146643bae22..ae07c4c7bc4 100644 --- a/engine/orchestration/src/main/java/org/apache/cloudstack/engine/orchestration/NetworkOrchestrator.java +++ b/engine/orchestration/src/main/java/org/apache/cloudstack/engine/orchestration/NetworkOrchestrator.java @@ -454,7 +454,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra SearchBuilder AssignIpAddressSearch; SearchBuilder AssignIpAddressFromPodVlanSearch; - HashMap _lastNetworkIdsToFree = new HashMap(); + HashMap _lastNetworkIdsToFree = new HashMap<>(); private void updateRouterDefaultDns(final VirtualMachineProfile vmProfile, final NicProfile nicProfile) { if (!Type.DomainRouter.equals(vmProfile.getType()) || !nicProfile.isDefaultNic()) { @@ -492,8 +492,8 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra @DB public boolean configure(final String name, final Map params) throws ConfigurationException { // populate providers - final Map> defaultSharedNetworkOfferingProviders = new HashMap>(); - final Set defaultProviders = new HashSet(); + final Map> defaultSharedNetworkOfferingProviders = new HashMap<>(); + final Set defaultProviders = new HashSet<>(); final Set tungstenProvider = new HashSet<>(); defaultProviders.add(Network.Provider.VirtualRouter); @@ -512,11 +512,11 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra defaultIsolatedNetworkOfferingProviders.put(Service.PortForwarding, defaultProviders); defaultIsolatedNetworkOfferingProviders.put(Service.Vpn, defaultProviders); - final Map> defaultSharedSGEnabledNetworkOfferingProviders = new HashMap>(); + final Map> defaultSharedSGEnabledNetworkOfferingProviders = new HashMap<>(); defaultSharedSGEnabledNetworkOfferingProviders.put(Service.Dhcp, defaultProviders); defaultSharedSGEnabledNetworkOfferingProviders.put(Service.Dns, defaultProviders); defaultSharedSGEnabledNetworkOfferingProviders.put(Service.UserData, defaultProviders); - final Set sgProviders = new HashSet(); + final Set sgProviders = new HashSet<>(); sgProviders.add(Provider.SecurityGroupProvider); defaultSharedSGEnabledNetworkOfferingProviders.put(Service.SecurityGroup, sgProviders); @@ -529,7 +529,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra defaultTungstenSharedSGEnabledNetworkOfferingProviders.put(Service.SecurityGroup, tungstenProvider); - final Map> defaultIsolatedSourceNatEnabledNetworkOfferingProviders = new HashMap>(); + final Map> defaultIsolatedSourceNatEnabledNetworkOfferingProviders = new HashMap<>(); defaultProviders.clear(); defaultProviders.add(Network.Provider.VirtualRouter); defaultIsolatedSourceNatEnabledNetworkOfferingProviders.put(Service.Dhcp, defaultProviders); @@ -543,7 +543,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra defaultIsolatedSourceNatEnabledNetworkOfferingProviders.put(Service.PortForwarding, defaultProviders); defaultIsolatedSourceNatEnabledNetworkOfferingProviders.put(Service.Vpn, defaultProviders); - final Map> defaultVPCOffProviders = new HashMap>(); + final Map> defaultVPCOffProviders = new HashMap<>(); defaultProviders.clear(); defaultProviders.add(Network.Provider.VPCVirtualRouter); defaultVPCOffProviders.put(Service.Dhcp, defaultProviders); @@ -560,11 +560,11 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra Transaction.execute(new TransactionCallbackNoReturn() { @Override public void doInTransactionWithoutResult(final TransactionStatus status) { - NetworkOfferingVO offering = null; + NetworkOfferingVO offering; //#1 - quick cloud network offering if (_networkOfferingDao.findByUniqueName(NetworkOffering.QuickCloudNoServices) == null) { offering = _configMgr.createNetworkOffering(NetworkOffering.QuickCloudNoServices, "Offering for QuickCloud with no services", TrafficType.Guest, null, true, - Availability.Optional, null, new HashMap>(), true, Network.GuestType.Shared, false, null, true, null, true, + Availability.Optional, null, new HashMap<>(), true, Network.GuestType.Shared, false, null, true, null, true, false, null, false, null, true, false, false, false, false, null, null, null, true, null, null, false); } @@ -622,11 +622,11 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra } //#8 - network offering with internal lb service - final Map> internalLbOffProviders = new HashMap>(); - final Set defaultVpcProvider = new HashSet(); + final Map> internalLbOffProviders = new HashMap<>(); + final Set defaultVpcProvider = new HashSet<>(); defaultVpcProvider.add(Network.Provider.VPCVirtualRouter); - final Set defaultInternalLbProvider = new HashSet(); + final Set defaultInternalLbProvider = new HashSet<>(); defaultInternalLbProvider.add(Network.Provider.InternalLbVm); internalLbOffProviders.put(Service.Dhcp, defaultVpcProvider); @@ -646,12 +646,12 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra _networkOfferingDao.update(offering.getId(), offering); } - final Map> netscalerServiceProviders = new HashMap>(); - final Set vrProvider = new HashSet(); + final Map> netscalerServiceProviders = new HashMap<>(); + final Set vrProvider = new HashSet<>(); vrProvider.add(Provider.VirtualRouter); - final Set sgProvider = new HashSet(); + final Set sgProvider = new HashSet<>(); sgProvider.add(Provider.SecurityGroupProvider); - final Set nsProvider = new HashSet(); + final Set nsProvider = new HashSet<>(); nsProvider.add(Provider.Netscaler); netscalerServiceProviders.put(Service.Dhcp, vrProvider); netscalerServiceProviders.put(Service.Dns, vrProvider); @@ -660,10 +660,10 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra netscalerServiceProviders.put(Service.StaticNat, nsProvider); netscalerServiceProviders.put(Service.Lb, nsProvider); - final Map> serviceCapabilityMap = new HashMap>(); - final Map elb = new HashMap(); + final Map> serviceCapabilityMap = new HashMap<>(); + final Map elb = new HashMap<>(); elb.put(Capability.ElasticLb, "true"); - final Map eip = new HashMap(); + final Map eip = new HashMap<>(); eip.put(Capability.ElasticIp, "true"); serviceCapabilityMap.put(Service.Lb, elb); serviceCapabilityMap.put(Service.StaticNat, eip); @@ -726,11 +726,6 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra return true; } - @Override - public boolean stop() { - return true; - } - protected NetworkOrchestrator() { setStateMachine(); } @@ -772,7 +767,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra } } - final List networks = new ArrayList(); + final List networks = new ArrayList<>(); long related = -1; @@ -895,7 +890,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra Arrays.fill(deviceIds, false); List> profilesList = getOrderedNetworkNicProfileMapping(networks); - final List nics = new ArrayList(size); + final List nics = new ArrayList<>(size); NicProfile defaultNic = null; Network nextNetwork = null; for (Pair networkNicPair : profilesList) { @@ -972,16 +967,16 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra for (final Map.Entry> network : networks.entrySet()) { List requestedProfiles = network.getValue(); if (requestedProfiles == null) { - requestedProfiles = new ArrayList(); + requestedProfiles = new ArrayList<>(); } if (requestedProfiles.isEmpty()) { requestedProfiles.add(null); } for (final NicProfile requested : requestedProfiles) { - profilesList.add(new Pair(network.getKey(), requested)); + profilesList.add(new Pair<>(network.getKey(), requested)); } } - profilesList.sort(new Comparator>() { + profilesList.sort(new Comparator<>() { @Override public int compare(Pair pair1, Pair pair2) { int profile1Order = Integer.MAX_VALUE; @@ -1064,7 +1059,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra } private NicVO persistNicAfterRaceCheck(final NicVO nic, final Long networkId, final NicProfile profile, int deviceId) { - return Transaction.execute(new TransactionCallback() { + return Transaction.execute(new TransactionCallback<>() { @Override public NicVO doInTransaction(TransactionStatus status) { NicVO vo = _nicDao.findNonPlaceHolderByIp4AddressAndNetworkId(profile.getIPv4Address(), networkId); @@ -1085,7 +1080,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra logger.debug("Allocating nic for vm {} in network {} with requested profile {}", vm.getVirtualMachine(), network, requested); final NetworkGuru guru = AdapterBase.getAdapterByName(networkGurus, ntwkVO.getGuruName()); - NicVO vo = null; + NicVO vo; boolean retryIpAllocation; do { retryIpAllocation = false; @@ -1161,7 +1156,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra _nicDao.update(vo.getId(), vo); setMtuInVRNicProfile(networks, network.getTrafficType(), vmNic); } - return new Pair(vmNic, Integer.valueOf(deviceId)); + return new Pair<>(vmNic, Integer.valueOf(deviceId)); } private boolean isNicAllocatedForProviderPublicNetworkOnVR(Network network, NicProfile requested, VirtualMachineProfile vm, Provider provider) { @@ -1443,7 +1438,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra Pair implementNetwork(final long networkId, final DeployDestination dest, final ReservationContext context, final boolean isRouter) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException { - Pair implemented = null; + Pair implemented; if (!isRouter) { implemented = implementNetwork(networkId, dest, context); } else { @@ -1454,7 +1449,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra // in issues. In order to avoid it, implementNetwork() call for VR is replaced with below code. final NetworkVO network = _networksDao.findById(networkId); final NetworkGuru guru = AdapterBase.getAdapterByName(networkGurus, network.getGuruName()); - implemented = new Pair(guru, network); + implemented = new Pair<>(guru, network); } return implemented; } @@ -1542,7 +1537,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra @DB public Pair implementNetwork(final long networkId, final DeployDestination dest, final ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException { - final Pair implemented = new Pair(null, null); + final Pair implemented = new Pair<>(null, null); NetworkVO network = _networksDao.findById(networkId); final NetworkGuru guru = AdapterBase.getAdapterByName(networkGurus, network.getGuruName()); @@ -1609,10 +1604,10 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra return implemented; } catch (final NoTransitionException e) { logger.error(e.getMessage()); - return new Pair(null, null); + return new Pair<>(null, null); } catch (final CloudRuntimeException | OperationTimedoutException e) { logger.error("Caught exception: {}", e.getMessage()); - return new Pair(null, null); + return new Pair<>(null, null); } finally { if (implemented.first() == null) { logger.debug("Cleaning up because we're unable to implement the network {}", network); @@ -1656,7 +1651,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra && (_networkModel.areServicesSupportedInNetwork(network.getId(), Service.SourceNat) || _networkModel.areServicesSupportedInNetwork(network.getId(), Service.Gateway)) && (network.getGuestType() == Network.GuestType.Isolated || network.getGuestType() == Network.GuestType.Shared && zone.getNetworkType() == NetworkType.Advanced)) { - List ips = null; + List ips; final Account owner = _entityMgr.findById(Account.class, network.getAccountId()); if (network.getVpcId() != null) { ips = _ipAddressDao.listByAssociatedVpc(network.getVpcId(), true); @@ -2145,7 +2140,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra // we have to implement default nics first - to ensure that default network elements start up first in multiple //nics case // (need for setting DNS on Dhcp to domR's Ip4 address) - Collections.sort(nics, new Comparator() { + Collections.sort(nics, new Comparator<>() { @Override public int compare(final NicVO nic1, final NicVO nic2) { @@ -2183,7 +2178,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra final NetworkGuru guru = AdapterBase.getAdapterByName(networkGurus, network.getGuruName()); final NicVO nic = _nicDao.findById(nicId); - NicProfile profile = null; + NicProfile profile; if (nic.getReservationStrategy() == Nic.ReservationStrategy.Start) { nic.setState(Nic.State.Reserving); nic.setReservationId(context.getReservationId()); @@ -2344,7 +2339,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra vm.addNic(profile); } - final List addedURIs = new ArrayList(); + final List addedURIs = new ArrayList<>(); if (guestNetworkId != null) { final List publicIps = _ipAddressDao.listByAssociatedNetwork(guestNetworkId, null); for (final IPAddressVO userIp : publicIps) { @@ -2992,7 +2987,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra final String networkDomainFinal = networkDomain; final String vlanIdFinal = vlanId; final Boolean subdomainAccessFinal = subdomainAccess; - final Network network = Transaction.execute(new TransactionCallback() { + final Network network = Transaction.execute(new TransactionCallback<>() { @Override public Network doInTransaction(final TransactionStatus status) { Long physicalNetworkId = null; @@ -3097,7 +3092,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra userNetwork.setNetworkCidrSize(networkCidrSize); final List networks = setupNetwork(owner, ntwkOff, userNetwork, plan, name, displayText, true, domainId, aclType, subdomainAccessFinal, vpcId, isDisplayNetworkEnabled); - Network network = null; + Network network; if (networks == null || networks.isEmpty()) { throw new CloudRuntimeException("Fail to create a network"); } else { @@ -3226,10 +3221,10 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra final boolean success = shutdownNetworkElementsAndResources(context, cleanupElements, network); final NetworkVO networkFinal = network; - final boolean result = Transaction.execute(new TransactionCallback() { + final boolean result = Transaction.execute(new TransactionCallback<>() { @Override public Boolean doInTransaction(final TransactionStatus status) { - boolean result = false; + boolean result; if (success) { logger.debug("Network {} is shutdown successfully, cleaning up corresponding resources now.", networkFinal); @@ -3447,7 +3442,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra final NetworkVO networkFinal = network; try { - final List deletedVlanRangeToPublish = Transaction.execute(new TransactionCallback>() { + final List deletedVlanRangeToPublish = Transaction.execute(new TransactionCallback<>() { @Override public List doInTransaction(TransactionStatus status) { final NetworkGuru guru = AdapterBase.getAdapterByName(networkGurus, networkFinal.getGuruName()); @@ -3503,7 +3498,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra publishDeletedVlanRanges(deletedVlanRangeToPublish); if (_networksDao.findById(network.getId()) == null) { // remove its related ACL permission - final Pair, Long> networkMsg = new Pair, Long>(Network.class, networkFinal.getId()); + final Pair, Long> networkMsg = new Pair<>(Network.class, networkFinal.getId()); _messageBus.publish(_name, EntityManager.MESSAGE_REMOVE_ENTITY_EVENT, PublishScope.LOCAL, networkMsg); } UsageEventUtils.publishNetworkDeletion(network); @@ -3586,9 +3581,9 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra public void reallyRun() { try { - final List shutdownList = new ArrayList(); + final List shutdownList = new ArrayList<>(); final long currentTime = System.currentTimeMillis() / 1000; - final HashMap stillFree = new HashMap(); + final HashMap stillFree = new HashMap<>(); final List networkIds = _networksDao.findNetworksToGarbageCollect(); final int netGcWait = NumbersUtil.parseInt(_configDao.getValue(NetworkGcWait.key()), 60); @@ -3958,7 +3953,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra @Override public List listVmNics(final long vmId, final Long nicId, final Long networkId, String keyword) { - List result = null; + List result; if (keyword == null || keyword.isEmpty()) { if (nicId == null && networkId == null) { @@ -4001,8 +3996,8 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra if (dc.getNetworkType() == NetworkType.Basic) { final List nics = _nicDao.listByVmId(vmInstance.getId()); final NetworkVO network = _networksDao.findById(nics.get(0).getNetworkId()); - final LinkedHashMap> profiles = new LinkedHashMap>(); - profiles.put(network, new ArrayList()); + final LinkedHashMap> profiles = new LinkedHashMap<>(); + profiles.put(network, new ArrayList<>()); Transaction.execute(new TransactionCallbackWithExceptionNoReturn() { @Override @@ -4136,7 +4131,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra // Mark all static rules as revoked and apply them on the backend (not in the DB) final List firewallStaticNatRules = _firewallDao.listByNetworkAndPurpose(network.getId(), Purpose.StaticNat); - final List staticNatRules = new ArrayList(); + final List staticNatRules = new ArrayList<>(); logger.debug("Releasing {} static nat rules for network {} as a part of shutdownNetworkRules", firewallStaticNatRules.size(), network); for (final FirewallRuleVO firewallStaticNatRule : firewallStaticNatRules) { @@ -4258,7 +4253,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra // Get all ip addresses, mark as releasing and release them on the backend final List userIps = _ipAddressDao.listByAssociatedNetwork(network.getId(), null); - final List publicIpsToRelease = new ArrayList(); + final List publicIpsToRelease = new ArrayList<>(); if (userIps != null && !userIps.isEmpty()) { for (final IPAddressVO userIp : userIps) { userIp.setState(IpAddress.State.Releasing); @@ -4307,7 +4302,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra final String dataCenter = startup.getDataCenter(); - long dcId = -1; + long dcId; DataCenterVO dc = _dcDao.findByName(dataCenter); if (dc == null) { try { @@ -4324,7 +4319,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra logger.debug("Host's hypervisorType is: {}", hypervisorType); - final List networkInfoList = new ArrayList(); + final List networkInfoList = new ArrayList<>(); // list all physicalnetworks in the zone & for each get the network names final List physicalNtwkList = _physicalNetworkDao.listByZone(dcId); @@ -4403,8 +4398,8 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra @Override public Map finalizeServicesAndProvidersForNetwork(final NetworkOffering offering, final Long physicalNetworkId) { - final Map svcProviders = new HashMap(); - final Map> providerSvcs = new HashMap>(); + final Map svcProviders = new HashMap<>(); + final Map> providerSvcs = new HashMap<>(); final List servicesMap = _ntwkOfferingSrvcDao.listByNetworkOfferingId(offering.getId()); final boolean checkPhysicalNetwork = physicalNetworkId != null ? true : false; @@ -4434,7 +4429,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra svcProviders.put(service, provider); List l = providerSvcs.get(provider); if (l == null) { - providerSvcs.put(provider, l = new ArrayList()); + providerSvcs.put(provider, l = new ArrayList<>()); } l.add(service); } @@ -4444,7 +4439,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra private List getNetworkProviders(final long networkId) { final List providerNames = _ntwkSrvcDao.getDistinctProviders(networkId); - final List providers = new ArrayList(); + final List providers = new ArrayList<>(); for (final String providerName : providerNames) { providers.add(Network.Provider.getProvider(providerName)); } @@ -4539,7 +4534,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra @Override public List getNicProfiles(final Long vmId, HypervisorType hypervisorType) { final List nics = _nicDao.listByVmId(vmId); - final List profiles = new ArrayList(); + final List profiles = new ArrayList<>(); if (nics != null) { for (final Nic nic : nics) { @@ -4605,12 +4600,12 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra } private Map> getServiceProvidersMap(final long networkId) { - final Map> map = new HashMap>(); + final Map> map = new HashMap<>(); final List nsms = _ntwkSrvcDao.getServicesInNetwork(networkId); for (final NetworkServiceMapVO nsm : nsms) { Set providers = map.get(Service.getService(nsm.getService())); if (providers == null) { - providers = new HashSet(); + providers = new HashSet<>(); } providers.add(Provider.getProvider(nsm.getProvider())); map.put(Service.getService(nsm.getService()), providers); @@ -4622,14 +4617,14 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra public List getProvidersForServiceInNetwork(final Network network, final Service service) { final Map> service2ProviderMap = getServiceProvidersMap(network.getId()); if (service2ProviderMap.get(service) != null) { - final List providers = new ArrayList(service2ProviderMap.get(service)); + final List providers = new ArrayList<>(service2ProviderMap.get(service)); return providers; } return null; } protected List getElementForServiceInNetwork(final Network network, final Service service) { - final List elements = new ArrayList(); + final List elements = new ArrayList<>(); final List providers = getProvidersForServiceInNetwork(network, service); //Only support one provider now if (providers == null) { @@ -4663,7 +4658,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra final List lbElements = getElementForServiceInNetwork(network, Service.Lb); NetworkElement lbElement = null; if (lbElements.size() > 1) { - String providerName = null; + String providerName; //get network offering details final NetworkOffering off = _entityMgr.findById(NetworkOffering.class, network.getNetworkOfferingId()); if (lbScheme == Scheme.Public) { @@ -4751,7 +4746,7 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra } } final String finalSelectedIp = selectedIp; - final NicVO vo = Transaction.execute(new TransactionCallback() { + final NicVO vo = Transaction.execute(new TransactionCallback<>() { @Override public NicVO doInTransaction(TransactionStatus status) { if (StringUtils.isBlank(macAddress)) { @@ -4804,6 +4799,18 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra } }); + if (selectedIp != null && GuestType.Shared.equals(network.getGuestType())) { + IPAddressVO ipAddressVO = _ipAddressDao.findByIpAndSourceNetworkId(network.getId(), selectedIp); + if (ipAddressVO != null && IpAddress.State.Free.equals(ipAddressVO.getState())) { + ipAddressVO.setState(IPAddressVO.State.Allocated); + ipAddressVO.setAllocatedTime(new Date()); + Account account = _accountDao.findById(vm.getAccountId()); + ipAddressVO.setAllocatedInDomainId(account.getDomainId()); + ipAddressVO.setAllocatedToAccountId(account.getId()); + _ipAddressDao.update(ipAddressVO.getId(), ipAddressVO); + } + } + final Integer networkRate = _networkModel.getNetworkRate(network.getId(), vm.getId()); final NicProfile vmNic = new NicProfile(vo, network, vo.getBroadcastUri(), vo.getIsolationUri(), networkRate, _networkModel.isSecurityGroupSupportedInNetwork(network), _networkModel.getNetworkTag(vm.getHypervisorType(), network)); @@ -4815,15 +4822,15 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra if (network.getGuestType() == GuestType.L2) { return null; } - return dataCenter.getNetworkType() == NetworkType.Basic ? - getSelectedIpForNicImportOnBasicZone(ipAddresses.getIp4Address(), network, dataCenter): + return GuestType.Shared.equals(network.getGuestType()) ? + getSelectedIpForNicImportOnSharedNetwork(ipAddresses.getIp4Address(), network, dataCenter): _ipAddrMgr.acquireGuestIpAddress(network, ipAddresses.getIp4Address()); } - protected String getSelectedIpForNicImportOnBasicZone(String requestedIp, Network network, DataCenter dataCenter) { + protected String getSelectedIpForNicImportOnSharedNetwork(String requestedIp, Network network, DataCenter dataCenter) { IPAddressVO ipAddressVO = StringUtils.isBlank(requestedIp) ? _ipAddressDao.findBySourceNetworkIdAndDatacenterIdAndState(network.getId(), dataCenter.getId(), IpAddress.State.Free): - _ipAddressDao.findByIp(requestedIp); + _ipAddressDao.findByIpAndSourceNetworkId(network.getId(), requestedIp); if (ipAddressVO == null || ipAddressVO.getState() != IpAddress.State.Free) { String msg = String.format("Cannot find a free IP to assign to VM NIC on network %s", network.getName()); logger.error(msg); @@ -4901,9 +4908,9 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra return NetworkOrchestrationService.class.getSimpleName(); } - public static final ConfigKey NetworkGcWait = new ConfigKey(Integer.class, "network.gc.wait", "Advanced", "600", + public static final ConfigKey NetworkGcWait = new ConfigKey<>(Integer.class, "network.gc.wait", "Advanced", "600", "Time (in seconds) to wait before shutting down a network that's not in used", false, Scope.Global, null); - public static final ConfigKey NetworkGcInterval = new ConfigKey(Integer.class, "network.gc.interval", "Advanced", "600", + public static final ConfigKey NetworkGcInterval = new ConfigKey<>(Integer.class, "network.gc.interval", "Advanced", "600", "Seconds to wait before checking for networks to shutdown", true, Scope.Global, null); @Override @@ -4911,6 +4918,6 @@ public class NetworkOrchestrator extends ManagerBase implements NetworkOrchestra return new ConfigKey[]{NetworkGcWait, NetworkGcInterval, NetworkLockTimeout, DeniedRoutes, GuestDomainSuffix, NetworkThrottlingRate, MinVRVersion, PromiscuousMode, MacAddressChanges, ForgedTransmits, MacLearning, RollingRestartEnabled, - TUNGSTEN_ENABLED, NSX_ENABLED, NETRIS_ENABLED }; + TUNGSTEN_ENABLED, NSX_ENABLED, NETRIS_ENABLED, NETWORK_LB_HAPROXY_MAX_CONN}; } } diff --git a/engine/orchestration/src/main/java/org/apache/cloudstack/engine/orchestration/VolumeOrchestrator.java b/engine/orchestration/src/main/java/org/apache/cloudstack/engine/orchestration/VolumeOrchestrator.java index 7af9b6b8492..2b759235ac8 100644 --- a/engine/orchestration/src/main/java/org/apache/cloudstack/engine/orchestration/VolumeOrchestrator.java +++ b/engine/orchestration/src/main/java/org/apache/cloudstack/engine/orchestration/VolumeOrchestrator.java @@ -1423,7 +1423,7 @@ public class VolumeOrchestrator extends ManagerBase implements VolumeOrchestrati String volumeToString = getVolumeIdentificationInfos(volume); VolumeInfo vol = volFactory.getVolume(volume.getId()); - if (vol == null){ + if (vol == null) { throw new CloudRuntimeException(String.format("Volume migration failed because volume [%s] is null.", volumeToString)); } if (destPool == null) { @@ -2308,6 +2308,7 @@ public class VolumeOrchestrator extends ManagerBase implements VolumeOrchestrati StoragePoolVO pool = _storagePoolDao.findByUuid(updatedDataStoreUUID); if (pool != null) { vol.setPoolId(pool.getId()); + vol.setPoolType(pool.getPoolType()); } } _volsDao.update(volumeId, vol); @@ -2317,7 +2318,7 @@ public class VolumeOrchestrator extends ManagerBase implements VolumeOrchestrati @Override public DiskProfile importVolume(Type type, String name, DiskOffering offering, Long sizeInBytes, Long minIops, Long maxIops, Long zoneId, HypervisorType hypervisorType, VirtualMachine vm, VirtualMachineTemplate template, Account owner, - Long deviceId, Long poolId, String path, String chainInfo) { + Long deviceId, Long poolId, Storage.StoragePoolType poolType, String path, String chainInfo) { if (sizeInBytes == null) { sizeInBytes = offering.getDiskSize(); } @@ -2358,6 +2359,7 @@ public class VolumeOrchestrator extends ManagerBase implements VolumeOrchestrati vol.setFormat(getSupportedImageFormatForCluster(hypervisorType)); vol.setPoolId(poolId); + vol.setPoolType(poolType); vol.setPath(path); vol.setChainInfo(chainInfo); vol.setState(Volume.State.Ready); @@ -2367,7 +2369,7 @@ public class VolumeOrchestrator extends ManagerBase implements VolumeOrchestrati @Override public DiskProfile updateImportedVolume(Type type, DiskOffering offering, VirtualMachine vm, VirtualMachineTemplate template, - Long deviceId, Long poolId, String path, String chainInfo, DiskProfile diskProfile) { + Long deviceId, Long poolId, Storage.StoragePoolType poolType, String path, String chainInfo, DiskProfile diskProfile) { VolumeVO vol = _volsDao.findById(diskProfile.getVolumeId()); if (vm != null) { @@ -2401,6 +2403,7 @@ public class VolumeOrchestrator extends ManagerBase implements VolumeOrchestrati vol.setFormat(getSupportedImageFormatForCluster(vm.getHypervisorType())); vol.setPoolId(poolId); + vol.setPoolType(poolType); vol.setPath(path); vol.setChainInfo(chainInfo); vol.setSize(diskProfile.getSize()); diff --git a/engine/orchestration/src/test/java/com/cloud/vm/VirtualMachineManagerImplTest.java b/engine/orchestration/src/test/java/com/cloud/vm/VirtualMachineManagerImplTest.java index 4f6329f81cb..a07870d09af 100644 --- a/engine/orchestration/src/test/java/com/cloud/vm/VirtualMachineManagerImplTest.java +++ b/engine/orchestration/src/test/java/com/cloud/vm/VirtualMachineManagerImplTest.java @@ -19,14 +19,18 @@ package com.cloud.vm; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyList; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; @@ -36,6 +40,8 @@ import static org.mockito.Mockito.when; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; +import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -43,15 +49,29 @@ import java.util.Random; import java.util.UUID; import java.util.stream.Collectors; +import com.cloud.agent.api.UnmanageInstanceAnswer; +import com.cloud.agent.api.UnmanageInstanceCommand; +import com.cloud.agent.api.to.DataTO; +import com.cloud.agent.api.to.DiskTO; +import com.cloud.api.ApiDBUtils; +import com.cloud.event.ActionEventUtils; +import com.cloud.exception.ConcurrentOperationException; +import com.cloud.ha.HighAvailabilityManager; +import com.cloud.network.Network; +import com.cloud.network.NetworkModel; import com.cloud.resource.ResourceManager; import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.context.CallContext; import org.apache.cloudstack.engine.subsystem.api.storage.StoragePoolAllocator; +import org.apache.cloudstack.engine.subsystem.api.storage.VolumeDataFactory; +import org.apache.cloudstack.engine.subsystem.api.storage.VolumeInfo; import org.apache.cloudstack.framework.config.ConfigKey; import org.apache.cloudstack.framework.config.impl.ConfigDepotImpl; import org.apache.cloudstack.framework.extensions.dao.ExtensionDetailsDao; import org.apache.cloudstack.framework.extensions.manager.ExtensionsManager; import org.apache.cloudstack.framework.extensions.vo.ExtensionDetailsVO; +import org.apache.cloudstack.framework.jobs.dao.VmWorkJobDao; +import org.apache.cloudstack.framework.jobs.impl.VmWorkJobVO; import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao; import org.apache.cloudstack.storage.datastore.db.StoragePoolVO; import org.apache.cloudstack.storage.to.VolumeObjectTO; @@ -61,6 +81,7 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; import org.mockito.InOrder; import org.mockito.InjectMocks; import org.mockito.Mock; @@ -167,6 +188,9 @@ public class VirtualMachineManagerImplTest { private PrimaryDataStoreDao storagePoolDaoMock; @Mock private VMInstanceVO vmInstanceMock; + @Mock + private VmWorkJobDao _workJobDao; + private long vmInstanceVoMockId = 1L; @Mock @@ -181,6 +205,9 @@ public class VirtualMachineManagerImplTest { private long hostMockId = 1L; private long clusterMockId = 2L; private long zoneMockId = 3L; + private final String vmMockUuid = UUID.randomUUID().toString(); + private final String hostUuid = UUID.randomUUID().toString(); + @Mock private HostVO hostMock; @Mock @@ -192,6 +219,7 @@ public class VirtualMachineManagerImplTest { private StoragePoolVO storagePoolVoMock; private long storagePoolVoMockId = 11L; private long storagePoolVoMockClusterId = 234L; + private String vmName = "vm1"; @Mock private VolumeVO volumeVoMock; @@ -254,6 +282,16 @@ public class VirtualMachineManagerImplTest { NicDao _nicsDao; @Mock NetworkService networkService; + @Mock + NetworkModel networkModel; + @Mock + VolumeDataFactory volumeDataFactoryMock; + @Mock + StorageManager storageManager; + @Mock + private HighAvailabilityManager _haMgr; + @Mock + VirtualMachineGuru guru; private ConfigDepotImpl configDepotImpl; private boolean updatedConfigKeyDepot = false; @@ -263,6 +301,7 @@ public class VirtualMachineManagerImplTest { ReflectionTestUtils.getField(VirtualMachineManager.VmMetadataManufacturer, "s_depot"); virtualMachineManagerImpl.setHostAllocators(new ArrayList<>()); + when(vmInstanceMock.getName()).thenReturn(vmName); when(vmInstanceMock.getId()).thenReturn(vmInstanceVoMockId); when(vmInstanceMock.getServiceOfferingId()).thenReturn(2L); when(hostMock.getId()).thenReturn(hostMockId); @@ -1361,7 +1400,7 @@ public class VirtualMachineManagerImplTest { Mockito.doReturn(HypervisorType.KVM).when(vmInstanceMock).getHypervisorType(); Mockito.doReturn(List.of(new VolumeObjectTO())).when(virtualMachineManagerImpl).getVmVolumesWithCheckpointsToRecreate(Mockito.any()); - Mockito.doThrow(new AgentUnavailableException(0)).when(agentManagerMock).send(Mockito.anyLong(), (Command) any()); + doThrow(new AgentUnavailableException(0)).when(agentManagerMock).send(Mockito.anyLong(), (Command) any()); Mockito.doNothing().when(snapshotManagerMock).endSnapshotChainForVolume(Mockito.anyLong(), Mockito.any()); virtualMachineManagerImpl.recreateCheckpointsKvmOnVmAfterMigration(vmInstanceMock, 0); @@ -1374,7 +1413,7 @@ public class VirtualMachineManagerImplTest { Mockito.doReturn(HypervisorType.KVM).when(vmInstanceMock).getHypervisorType(); Mockito.doReturn(List.of(new VolumeObjectTO())).when(virtualMachineManagerImpl).getVmVolumesWithCheckpointsToRecreate(Mockito.any()); - Mockito.doThrow(new OperationTimedoutException(null, 0, 0, 0, false)).when(agentManagerMock).send(Mockito.anyLong(), (Command) any()); + doThrow(new OperationTimedoutException(null, 0, 0, 0, false)).when(agentManagerMock).send(Mockito.anyLong(), (Command) any()); Mockito.doNothing().when(snapshotManagerMock).endSnapshotChainForVolume(Mockito.anyLong(), Mockito.any()); virtualMachineManagerImpl.recreateCheckpointsKvmOnVmAfterMigration(vmInstanceMock, 0); @@ -1641,4 +1680,278 @@ public class VirtualMachineManagerImplTest { virtualMachineManagerImpl.processPrepareExternalProvisioning(true, host, vmProfile, mock(DataCenter.class)); verify(agentManagerMock).send(anyLong(), any(Command.class)); } + + @Test + public void testPrepVMSpecForUnmanageInstance() { + // Arrange + final Long accountId = 1L; + final Long offeringId = 1L; + final Long templateId = 1L; + + // Mock vm + VMInstanceVO vm = Mockito.mock(VMInstanceVO.class); + when(vm.getId()).thenReturn(vmInstanceVoMockId); + when(vm.getAccountId()).thenReturn(accountId); + when(vm.getServiceOfferingId()).thenReturn(offeringId); + when(vm.getTemplateId()).thenReturn(templateId); + when(vm.getHypervisorType()).thenReturn(HypervisorType.KVM); + when(vmInstanceDaoMock.findById(vmInstanceVoMockId)).thenReturn(vm); + + // Mock owner + AccountVO owner = Mockito.mock(AccountVO.class); + when(_entityMgr.findById(Account.class, accountId)).thenReturn(owner); + + ServiceOfferingVO offering = Mockito.mock(ServiceOfferingVO.class); + when(serviceOfferingDaoMock.findById(vmInstanceVoMockId, offeringId)).thenReturn(offering); + + VMTemplateVO template = Mockito.mock(VMTemplateVO.class); + when(_entityMgr.findByIdIncludingRemoved(VirtualMachineTemplate.class, templateId)).thenReturn(template); + + when(hostMock.getClusterId()).thenReturn(clusterMockId); + + // Mock cpuOvercommitRatio and ramOvercommitRatio + ClusterDetailsVO cpuOvercommitRatio = Mockito.mock(ClusterDetailsVO.class); + when(cpuOvercommitRatio.getValue()).thenReturn("1.0"); + when(_clusterDetailsDao.findDetail(clusterMockId, VmDetailConstants.CPU_OVER_COMMIT_RATIO)).thenReturn(cpuOvercommitRatio); + ClusterDetailsVO ramOvercommitRatio = Mockito.mock(ClusterDetailsVO.class); + when(ramOvercommitRatio.getValue()).thenReturn("1.0"); + when(_clusterDetailsDao.findDetail(clusterMockId, VmDetailConstants.MEMORY_OVER_COMMIT_RATIO)).thenReturn(ramOvercommitRatio); + + // Mock NICs + List nics = new ArrayList<>(); + NicVO nic1 = Mockito.mock(NicVO.class); + when(nic1.getDeviceId()).thenReturn(1); + nics.add(nic1); + NicVO nic2 = Mockito.mock(NicVO.class); + when(nic2.getDeviceId()).thenReturn(0); + nics.add(nic2); + when(_nicsDao.listByVmId(vmInstanceVoMockId)).thenReturn(nics); + + Network networkMock = Mockito.mock(Network.class); + when(networkModel.getNetwork(anyLong())).thenReturn(networkMock); + + when(volumeVoMock.getVolumeType()).thenReturn(Volume.Type.ROOT); + when(volumeVoMock.getDeviceId()).thenReturn(0L); + when(volumeVoMock.getPath()).thenReturn("/"); + when(volumeVoMock.getDiskOfferingId()).thenReturn(1L); + when(volumeDaoMock.findUsableVolumesForInstance(vmInstanceVoMockId)).thenReturn(List.of(volumeVoMock)); + + VolumeInfo volumeInfo = mock(VolumeInfo.class); + DataTO dataTO = mock(DataTO.class); + when(volumeInfo.getTO()).thenReturn(dataTO); + when(volumeDataFactoryMock.getVolume(anyLong())).thenReturn(volumeInfo); + when(storageManager.getDiskWithThrottling(any(), any(), anyLong(), anyString(), anyLong(), anyLong())).thenReturn(Mockito.mock(DiskTO.class)); + + Map details = new HashMap<>(); + details.put(VirtualMachineProfile.Param.BootType.getName(), "BIOS"); + details.put(VirtualMachineProfile.Param.BootMode.getName(), "LEGACY"); + details.put(VirtualMachineProfile.Param.UefiFlag.getName(), "Yes"); + when(vmInstanceDetailsDao.listDetailsKeyPairs(anyLong(), anyList())).thenReturn(details); + + com.cloud.hypervisor.HypervisorGuru guru = Mockito.mock(com.cloud.hypervisor.HypervisorGuru.class); + when(_hvGuruMgr.getGuru(HypervisorType.KVM)).thenReturn(guru); + VirtualMachineTO vmTO = new VirtualMachineTO() {}; + when(guru.implement(any(VirtualMachineProfile.class))).thenAnswer((Answer) invocation -> { + VirtualMachineProfile profile = invocation.getArgument(0); + assertEquals("BIOS", profile.getParameter(VirtualMachineProfile.Param.BootType)); + return vmTO; + }); + + // Act + VirtualMachineTO result = virtualMachineManagerImpl.prepVmSpecForUnmanageCmd(vmInstanceVoMockId, hostMockId); + + // Assert + assertNotNull(result); + assertEquals(vmTO, result); + verify(_clusterDetailsDao, times(2)).findDetail(eq(clusterMockId), anyString()); + verify(vmInstanceDetailsDao).listDetailsKeyPairs(anyLong(), anyList()); + } + + @Test + public void testPersistDomainForKvmForRunningVmSuccess() throws AgentUnavailableException, OperationTimedoutException { + when(vmInstanceMock.getState()).thenReturn(VirtualMachine.State.Running); + when(vmInstanceMock.getHostId()).thenReturn(hostMockId); + UnmanageInstanceAnswer successAnswer = new UnmanageInstanceAnswer(null, true, "success"); + when(agentManagerMock.send(anyLong(), any(Command.class))).thenReturn(successAnswer); + virtualMachineManagerImpl.persistDomainForKVM(vmInstanceMock, null); + ArgumentCaptor hostIdCaptor = ArgumentCaptor.forClass(Long.class); + ArgumentCaptor commandCaptor = ArgumentCaptor.forClass(UnmanageInstanceCommand.class); + verify(agentManagerMock).send(hostIdCaptor.capture(), commandCaptor.capture()); + assertEquals(hostMockId, hostIdCaptor.getValue().longValue()); + } + + @Test + public void testPersistDomainForKvmForStoppedVmSuccess() throws AgentUnavailableException, OperationTimedoutException { + when(vmInstanceMock.getState()).thenReturn(VirtualMachine.State.Stopped); + VirtualMachineTO vmTO = new VirtualMachineTO() {}; + vmTO.setName(vmName); + doReturn(vmTO).when(virtualMachineManagerImpl).prepVmSpecForUnmanageCmd(vmInstanceVoMockId, 1L); + UnmanageInstanceAnswer successAnswer = new UnmanageInstanceAnswer(null, true, "success"); + when(agentManagerMock.send(anyLong(), any(UnmanageInstanceCommand.class))).thenReturn(successAnswer); + when(virtualMachineManagerImpl.findClusterAndHostIdForVm(vmInstanceMock, false)).thenReturn(new Pair<>(clusterMockId, hostMockId)); + virtualMachineManagerImpl.persistDomainForKVM(vmInstanceMock, null); + ArgumentCaptor hostIdCaptor = ArgumentCaptor.forClass(Long.class); + ArgumentCaptor commandCaptor = ArgumentCaptor.forClass(UnmanageInstanceCommand.class); + verify(agentManagerMock).send(hostIdCaptor.capture(), commandCaptor.capture()); + assertEquals(1L, hostIdCaptor.getValue().longValue()); + UnmanageInstanceCommand sentCommand = commandCaptor.getValue(); + assertNotNull(sentCommand.getVm()); + assertEquals(vmTO, sentCommand.getVm()); + assertEquals(vmName, sentCommand.getInstanceName()); + verify(virtualMachineManagerImpl).prepVmSpecForUnmanageCmd(vmInstanceVoMockId, 1L); + } + + + @Test + public void testPersistDomainForKvmForStoppedVmNoHost() { + when(vmInstanceMock.getState()).thenReturn(VirtualMachine.State.Stopped); + VirtualMachineTO vmTO = new VirtualMachineTO() {}; + vmTO.setName(vmName); + when(virtualMachineManagerImpl.findClusterAndHostIdForVm(vmInstanceMock, false)).thenReturn(new Pair<>(clusterMockId, null)); + CloudRuntimeException exception = assertThrows(CloudRuntimeException.class, () -> virtualMachineManagerImpl.persistDomainForKVM(vmInstanceMock, null)); + assertEquals("No available host to persist domain XML for Instance: " + vmName, exception.getMessage()); + } + + @Test + public void testPersistDomainForKvmForRunningVmAgentFailure() throws AgentUnavailableException, OperationTimedoutException { + when(vmInstanceMock.getState()).thenReturn(VirtualMachine.State.Running); + when(vmInstanceMock.getHostId()).thenReturn(hostMockId); + UnmanageInstanceAnswer failureAnswer = new UnmanageInstanceAnswer(null, false, "failure"); + when(agentManagerMock.send(anyLong(), any(UnmanageInstanceCommand.class))).thenReturn(failureAnswer); + CloudRuntimeException exception = assertThrows(CloudRuntimeException.class, () -> virtualMachineManagerImpl.persistDomainForKVM(vmInstanceMock, null)); + assertEquals("Failed to persist domain XML for Instance: " + vmName + " on host ID: " + hostMockId, exception.getMessage()); + } + + @Test + public void testPersistDomainForKvmAgentUnavailable() throws AgentUnavailableException, OperationTimedoutException { + when(vmInstanceMock.getState()).thenReturn(VirtualMachine.State.Running); + when(vmInstanceMock.getHostId()).thenReturn(hostMockId); + doThrow(new AgentUnavailableException("Agent down", hostMockId)).when(agentManagerMock).send(anyLong(), any(UnmanageInstanceCommand.class)); + CloudRuntimeException exception = assertThrows(CloudRuntimeException.class, () -> virtualMachineManagerImpl.persistDomainForKVM(vmInstanceMock, null)); + assertEquals("Failed to send command to persist domain XML for Instance: " + vmName + " on host ID: " + hostMockId, exception.getMessage()); + } + + @Test(expected = ConcurrentOperationException.class) + public void testUnmanagePendingHaWork() { + when(vmInstanceDaoMock.findByUuid(vmMockUuid)).thenReturn(vmInstanceMock); + when(_workJobDao.listPendingWorkJobs(VirtualMachine.Type.Instance, vmInstanceVoMockId)).thenReturn(Collections.emptyList()); + when(_haMgr.hasPendingHaWork(vmInstanceVoMockId)).thenReturn(true); + virtualMachineManagerImpl.unmanage(vmMockUuid, null); + } + + @Test + public void testPersistDomainForKvmOperationTimedOut() throws AgentUnavailableException, OperationTimedoutException { + when(vmInstanceMock.getState()).thenReturn(VirtualMachine.State.Running); + when(vmInstanceMock.getHostId()).thenReturn(hostMockId); + doThrow(new OperationTimedoutException(null, hostMockId, 123L, 60, false)).when(agentManagerMock).send(anyLong(), any(UnmanageInstanceCommand.class)); + CloudRuntimeException exception = assertThrows(CloudRuntimeException.class, () -> virtualMachineManagerImpl.persistDomainForKVM(vmInstanceMock, null)); + assertEquals("Failed to send command to persist domain XML for Instance: " + vmName + " on host ID: " + hostMockId, exception.getMessage()); + } + + @Test(expected = CloudRuntimeException.class) + public void testUnmanageVmRemoved() { + when(vmInstanceMock.getRemoved()).thenReturn(new Date()); + when(vmInstanceDaoMock.findByUuid(vmMockUuid)).thenReturn(vmInstanceMock); + virtualMachineManagerImpl.unmanage(vmMockUuid, null); + } + + @Test(expected = ConcurrentOperationException.class) + public void testUnmanagePendingWorkJobs() { + when(vmInstanceDaoMock.findByUuid(vmMockUuid)).thenReturn(vmInstanceMock); + List pendingJobs = new ArrayList<>(); + VmWorkJobVO vmWorkJobVO = mock(VmWorkJobVO.class); + pendingJobs.add(vmWorkJobVO); + when(_workJobDao.listPendingWorkJobs(VirtualMachine.Type.Instance, vmInstanceVoMockId)).thenReturn(pendingJobs); + virtualMachineManagerImpl.unmanage(vmMockUuid, null); + } + + @Test + public void testUnmanageHostNotFoundAfterTransaction() { + when(vmInstanceMock.getHostId()).thenReturn(hostMockId); + when(vmInstanceDaoMock.findByUuid(vmMockUuid)).thenReturn(vmInstanceMock); + when(_workJobDao.listPendingWorkJobs(any(), anyLong())).thenReturn(Collections.emptyList()); + when(_haMgr.hasPendingHaWork(anyLong())).thenReturn(false); + doReturn(guru).when(virtualMachineManagerImpl).getVmGuru(vmInstanceMock); + doNothing().when(virtualMachineManagerImpl).unmanageVMSnapshots(vmInstanceMock); + doNothing().when(virtualMachineManagerImpl).unmanageVMNics(any(VirtualMachineProfile.class), any(VMInstanceVO.class)); + doNothing().when(virtualMachineManagerImpl).unmanageVMVolumes(vmInstanceMock); + doNothing().when(guru).finalizeUnmanage(vmInstanceMock); + try (MockedStatic ignored = Mockito.mockStatic(ApiDBUtils.class)) { + when(ApiDBUtils.findHostById(hostMockId)).thenReturn(null); + Pair result = virtualMachineManagerImpl.unmanage(vmMockUuid, null); + assertNull(result.second()); + } + } + + @Test + public void testUnmanageSuccessNonKvm() { + when(vmInstanceMock.getHostId()).thenReturn(hostMockId); + when(hostMock.getUuid()).thenReturn(hostUuid); + when(vmInstanceDaoMock.findByUuid(vmMockUuid)).thenReturn(vmInstanceMock); + when(_workJobDao.listPendingWorkJobs(any(), anyLong())).thenReturn(Collections.emptyList()); + when(_haMgr.hasPendingHaWork(anyLong())).thenReturn(false); + doReturn(guru).when(virtualMachineManagerImpl).getVmGuru(vmInstanceMock); + doNothing().when(virtualMachineManagerImpl).unmanageVMSnapshots(vmInstanceMock); + doNothing().when(virtualMachineManagerImpl).unmanageVMNics(any(VirtualMachineProfile.class), any(VMInstanceVO.class)); + doNothing().when(virtualMachineManagerImpl).unmanageVMVolumes(vmInstanceMock); + doNothing().when(guru).finalizeUnmanage(vmInstanceMock); + try (MockedStatic ignored = Mockito.mockStatic(ApiDBUtils.class)) { + when(ApiDBUtils.findHostById(hostMockId)).thenReturn(hostMock); + try (MockedStatic actionUtil = Mockito.mockStatic(ActionEventUtils.class)) { + actionUtil.when(() -> ActionEventUtils.onActionEvent( + anyLong(), anyLong(), anyLong(), + anyString(), anyString(), + anyLong(), anyString() + )).thenReturn(1L); + + Pair result = virtualMachineManagerImpl.unmanage(vmMockUuid, null); + assertNotNull(result); + assertTrue(result.first()); + assertEquals(hostUuid, result.second()); + + verify(virtualMachineManagerImpl, never()).persistDomainForKVM(any(VMInstanceVO.class), anyLong()); + verify(virtualMachineManagerImpl, times(1)).unmanageVMSnapshots(vmInstanceMock); + verify(virtualMachineManagerImpl, times(1)).unmanageVMNics(any(VirtualMachineProfile.class), any(VMInstanceVO.class)); + verify(virtualMachineManagerImpl, times(1)).unmanageVMVolumes(vmInstanceMock); + verify(guru, times(1)).finalizeUnmanage(vmInstanceMock); + } + } + } + + @Test + public void testUnmanageSuccessKvm() throws Exception { + when(vmInstanceMock.getHostId()).thenReturn(hostMockId); + when(hostMock.getUuid()).thenReturn(hostUuid); + when(vmInstanceMock.getHypervisorType()).thenReturn(HypervisorType.KVM); + when(vmInstanceDaoMock.findByUuid(vmMockUuid)).thenReturn(vmInstanceMock); + when(_workJobDao.listPendingWorkJobs(any(), anyLong())).thenReturn(Collections.emptyList()); + when(_haMgr.hasPendingHaWork(anyLong())).thenReturn(false); + doReturn(guru).when(virtualMachineManagerImpl).getVmGuru(vmInstanceMock); + doNothing().when(virtualMachineManagerImpl).unmanageVMSnapshots(vmInstanceMock); + doNothing().when(virtualMachineManagerImpl).unmanageVMNics(any(VirtualMachineProfile.class), any(VMInstanceVO.class)); + doNothing().when(virtualMachineManagerImpl).unmanageVMVolumes(vmInstanceMock); + doNothing().when(guru).finalizeUnmanage(vmInstanceMock); + try (MockedStatic ignored = Mockito.mockStatic(ApiDBUtils.class)) { + when(ApiDBUtils.findHostById(hostMockId)).thenReturn(hostMock); + try (MockedStatic actionUtil = Mockito.mockStatic(ActionEventUtils.class)) { + actionUtil.when(() -> ActionEventUtils.onActionEvent( + anyLong(), anyLong(), anyLong(), + anyString(), anyString(), + anyLong(), anyString() + )).thenReturn(1L); + UnmanageInstanceAnswer successAnswer = new UnmanageInstanceAnswer(null, true, "success"); + when(agentManagerMock.send(anyLong(), any(UnmanageInstanceCommand.class))).thenReturn(successAnswer); + Pair result = virtualMachineManagerImpl.unmanage(vmMockUuid, null); + assertNotNull(result); + assertTrue(result.first()); + assertEquals(hostUuid, result.second()); + verify(virtualMachineManagerImpl, times(1)).persistDomainForKVM(vmInstanceMock, null); + verify(virtualMachineManagerImpl, times(1)).unmanageVMSnapshots(vmInstanceMock); + verify(virtualMachineManagerImpl, times(1)).unmanageVMNics(any(VirtualMachineProfile.class), any(VMInstanceVO.class)); + verify(virtualMachineManagerImpl, times(1)).unmanageVMVolumes(vmInstanceMock); + verify(guru, times(1)).finalizeUnmanage(vmInstanceMock); + } + } + } + } diff --git a/engine/orchestration/src/test/java/org/apache/cloudstack/engine/orchestration/NetworkOrchestratorTest.java b/engine/orchestration/src/test/java/org/apache/cloudstack/engine/orchestration/NetworkOrchestratorTest.java index 064ca44c69a..a95f0e36475 100644 --- a/engine/orchestration/src/test/java/org/apache/cloudstack/engine/orchestration/NetworkOrchestratorTest.java +++ b/engine/orchestration/src/test/java/org/apache/cloudstack/engine/orchestration/NetworkOrchestratorTest.java @@ -822,7 +822,7 @@ public class NetworkOrchestratorTest extends TestCase { Mockito.when(network.getId()).thenReturn(networkId); Mockito.when(dataCenter.getId()).thenReturn(dataCenterId); Mockito.when(ipAddresses.getIp4Address()).thenReturn(requestedIp); - Mockito.when(testOrchestrator._ipAddressDao.findByIp(requestedIp)).thenReturn(ipAddressVO); + Mockito.when(testOrchestrator._ipAddressDao.findByIpAndSourceNetworkId(networkId, requestedIp)).thenReturn(ipAddressVO); String ipAddress = testOrchestrator.getSelectedIpForNicImport(network, dataCenter, ipAddresses); Assert.assertEquals(requestedIp, ipAddress); } diff --git a/engine/orchestration/src/test/java/org/apache/cloudstack/engine/orchestration/VolumeOrchestratorTest.java b/engine/orchestration/src/test/java/org/apache/cloudstack/engine/orchestration/VolumeOrchestratorTest.java index 817ff02ef74..b4a26c17e2e 100644 --- a/engine/orchestration/src/test/java/org/apache/cloudstack/engine/orchestration/VolumeOrchestratorTest.java +++ b/engine/orchestration/src/test/java/org/apache/cloudstack/engine/orchestration/VolumeOrchestratorTest.java @@ -241,7 +241,7 @@ public class VolumeOrchestratorTest { volumeOrchestrator.importVolume(volumeType, name, diskOffering, sizeInBytes, null, null, zoneId, hypervisorType, null, null, owner, - deviceId, poolId, path, chainInfo); + deviceId, poolId, Storage.StoragePoolType.NetworkFilesystem, path, chainInfo); VolumeVO volume = volumeVOMockedConstructionConstruction.constructed().get(0); Mockito.verify(volume, Mockito.never()).setInstanceId(Mockito.anyLong()); diff --git a/engine/pom.xml b/engine/pom.xml index b771138dc8c..2de84eab85a 100644 --- a/engine/pom.xml +++ b/engine/pom.xml @@ -25,7 +25,7 @@ org.apache.cloudstack cloudstack - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT ../pom.xml diff --git a/engine/schema/pom.xml b/engine/schema/pom.xml index 2f216884c8b..654cd14a25d 100644 --- a/engine/schema/pom.xml +++ b/engine/schema/pom.xml @@ -24,7 +24,7 @@ org.apache.cloudstack cloud-engine - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT ../pom.xml diff --git a/engine/schema/src/main/java/com/cloud/host/dao/HostDetailsDao.java b/engine/schema/src/main/java/com/cloud/host/dao/HostDetailsDao.java index 5d8bd0a0a3a..b72ec5239ff 100644 --- a/engine/schema/src/main/java/com/cloud/host/dao/HostDetailsDao.java +++ b/engine/schema/src/main/java/com/cloud/host/dao/HostDetailsDao.java @@ -33,6 +33,8 @@ public interface HostDetailsDao extends GenericDao { List findByName(String name); + void removeExternalDetails(long hostId); + void replaceExternalDetails(long hostId, Map details); } diff --git a/engine/schema/src/main/java/com/cloud/host/dao/HostDetailsDaoImpl.java b/engine/schema/src/main/java/com/cloud/host/dao/HostDetailsDaoImpl.java index 3eb9faeb1c1..0f8e8623506 100644 --- a/engine/schema/src/main/java/com/cloud/host/dao/HostDetailsDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/host/dao/HostDetailsDaoImpl.java @@ -39,6 +39,7 @@ public class HostDetailsDaoImpl extends GenericDaoBase implement protected final SearchBuilder HostSearch; protected final SearchBuilder DetailSearch; protected final SearchBuilder DetailNameSearch; + protected final SearchBuilder ExternalDetailSearch; public HostDetailsDaoImpl() { HostSearch = createSearchBuilder(); @@ -53,6 +54,11 @@ public class HostDetailsDaoImpl extends GenericDaoBase implement DetailNameSearch = createSearchBuilder(); DetailNameSearch.and("name", DetailNameSearch.entity().getName(), SearchCriteria.Op.EQ); DetailNameSearch.done(); + + ExternalDetailSearch = createSearchBuilder(); + ExternalDetailSearch.and("hostId", ExternalDetailSearch.entity().getHostId(), SearchCriteria.Op.EQ); + ExternalDetailSearch.and("name", ExternalDetailSearch.entity().getName(), SearchCriteria.Op.LIKE); + ExternalDetailSearch.done(); } @Override @@ -133,6 +139,17 @@ public class HostDetailsDaoImpl extends GenericDaoBase implement return listBy(sc); } + @Override + public void removeExternalDetails(long hostId) { + TransactionLegacy txn = TransactionLegacy.currentTxn(); + txn.start(); + SearchCriteria sc = ExternalDetailSearch.create(); + sc.setParameters("hostId", hostId); + sc.setParameters("name", VmDetailConstants.EXTERNAL_DETAIL_PREFIX + "%"); + remove(sc); + txn.commit(); + } + @Override public void replaceExternalDetails(long hostId, Map details) { if (details.isEmpty()) { @@ -149,11 +166,7 @@ public class HostDetailsDaoImpl extends GenericDaoBase implement } detailVOs.add(new DetailVO(hostId, name, value)); } - SearchBuilder sb = createSearchBuilder(); - sb.and("hostId", sb.entity().getHostId(), SearchCriteria.Op.EQ); - sb.and("name", sb.entity().getName(), SearchCriteria.Op.LIKE); - sb.done(); - SearchCriteria sc = sb.create(); + SearchCriteria sc = ExternalDetailSearch.create(); sc.setParameters("hostId", hostId); sc.setParameters("name", VmDetailConstants.EXTERNAL_DETAIL_PREFIX + "%"); remove(sc); diff --git a/engine/schema/src/main/java/com/cloud/network/as/dao/CounterDao.java b/engine/schema/src/main/java/com/cloud/network/as/dao/CounterDao.java index 4c9df8e749f..372dc930b68 100644 --- a/engine/schema/src/main/java/com/cloud/network/as/dao/CounterDao.java +++ b/engine/schema/src/main/java/com/cloud/network/as/dao/CounterDao.java @@ -24,6 +24,7 @@ import com.cloud.utils.db.Filter; import com.cloud.utils.db.GenericDao; public interface CounterDao extends GenericDao { + CounterVO findByNameProviderValue(String name, String value, String provider); public List listCounters(Long id, String name, String source, String provider, String keyword, Filter filter); } diff --git a/engine/schema/src/main/java/com/cloud/network/as/dao/CounterDaoImpl.java b/engine/schema/src/main/java/com/cloud/network/as/dao/CounterDaoImpl.java index 2d3906b8341..0badbe449ac 100644 --- a/engine/schema/src/main/java/com/cloud/network/as/dao/CounterDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/network/as/dao/CounterDaoImpl.java @@ -32,6 +32,7 @@ import com.cloud.utils.db.SearchCriteria.Op; @Component public class CounterDaoImpl extends GenericDaoBase implements CounterDao { final SearchBuilder AllFieldsSearch; + final SearchBuilder CounterValueSearch; protected CounterDaoImpl() { AllFieldsSearch = createSearchBuilder(); @@ -40,6 +41,21 @@ public class CounterDaoImpl extends GenericDaoBase implements C AllFieldsSearch.and("source", AllFieldsSearch.entity().getSource(), Op.EQ); AllFieldsSearch.and("provider", AllFieldsSearch.entity().getProvider(), Op.EQ); AllFieldsSearch.done(); + + CounterValueSearch = createSearchBuilder(); + CounterValueSearch.and("name", CounterValueSearch.entity().getName(), Op.EQ); + CounterValueSearch.and("value", CounterValueSearch.entity().getValue(), Op.EQ); + CounterValueSearch.and("provider", CounterValueSearch.entity().getProvider(), Op.EQ); + CounterValueSearch.done(); + } + + @Override + public CounterVO findByNameProviderValue(String name, String value, String provider) { + SearchCriteria sc = CounterValueSearch.create(); + sc.setParameters("name", name); + sc.setParameters("value", value); + sc.setParameters("provider", provider); + return findOneBy(sc); } @Override diff --git a/engine/schema/src/main/java/com/cloud/network/dao/NetworkDao.java b/engine/schema/src/main/java/com/cloud/network/dao/NetworkDao.java index 0861a424ebb..fdca6e43f00 100644 --- a/engine/schema/src/main/java/com/cloud/network/dao/NetworkDao.java +++ b/engine/schema/src/main/java/com/cloud/network/dao/NetworkDao.java @@ -18,6 +18,7 @@ package com.cloud.network.dao; import java.util.List; import java.util.Map; +import java.util.Set; import com.cloud.network.Network; import com.cloud.network.Network.GuestType; @@ -47,6 +48,12 @@ public interface NetworkDao extends GenericDao, StateDao listByNetworkDomains(Set uniqueNtwkDomains); + + List listByNetworkDomainsAndAccountIds(Set uniqueNtwkDomains, Set accountIds); + + List listByNetworkDomainsAndDomainIds(Set uniqueNtwkDomains, Set domainIds); + /** * Retrieves the next available mac address in this network configuration. * diff --git a/engine/schema/src/main/java/com/cloud/network/dao/NetworkDaoImpl.java b/engine/schema/src/main/java/com/cloud/network/dao/NetworkDaoImpl.java index 0aae532eac5..4b299085612 100644 --- a/engine/schema/src/main/java/com/cloud/network/dao/NetworkDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/network/dao/NetworkDaoImpl.java @@ -86,6 +86,7 @@ public class NetworkDaoImpl extends GenericDaoBaseimplements Ne GenericSearchBuilder GarbageCollectedSearch; SearchBuilder PrivateNetworkSearch; + SearchBuilder NetworkDomainSearch; @Inject ResourceTagDao _tagsDao; @@ -198,6 +199,12 @@ public class NetworkDaoImpl extends GenericDaoBaseimplements Ne PersistentNetworkSearch.join("persistent", persistentNtwkOffJoin, PersistentNetworkSearch.entity().getNetworkOfferingId(), persistentNtwkOffJoin.entity().getId(), JoinType.INNER); PersistentNetworkSearch.done(); + NetworkDomainSearch = createSearchBuilder(); + NetworkDomainSearch.and("networkDomains", NetworkDomainSearch.entity().getNetworkDomain(), Op.IN); + NetworkDomainSearch.and("accounts", NetworkDomainSearch.entity().getAccountId(), Op.IN); + NetworkDomainSearch.and("domains", NetworkDomainSearch.entity().getDomainId(), Op.IN); + NetworkDomainSearch.done(); + PhysicalNetworkSearch = createSearchBuilder(); PhysicalNetworkSearch.and("physicalNetworkId", PhysicalNetworkSearch.entity().getPhysicalNetworkId(), Op.EQ); PhysicalNetworkSearch.done(); @@ -428,6 +435,29 @@ public class NetworkDaoImpl extends GenericDaoBaseimplements Ne return search(sc, null); } + @Override + public List listByNetworkDomains(Set uniqueNtwkDomains) { + SearchCriteria sc = NetworkDomainSearch.create(); + sc.setParameters("networkDomains", uniqueNtwkDomains.toArray()); + return search(sc, null); + } + + @Override + public List listByNetworkDomainsAndAccountIds(Set uniqueNtwkDomains, Set accountIds) { + SearchCriteria sc = NetworkDomainSearch.create(); + sc.setParameters("networkDomains", uniqueNtwkDomains.toArray()); + sc.setParameters("accounts", accountIds.toArray()); + return search(sc, null); + } + + @Override + public List listByNetworkDomainsAndDomainIds(Set uniqueNtwkDomains, Set domainIds) { + SearchCriteria sc = NetworkDomainSearch.create(); + sc.setParameters("networkDomains", uniqueNtwkDomains.toArray()); + sc.setParameters("domains", domainIds.toArray()); + return search(sc, null); + } + @Override public String getNextAvailableMacAddress(final long networkConfigId, Integer zoneMacIdentifier) { final SequenceFetcher fetch = SequenceFetcher.getInstance(); diff --git a/engine/schema/src/main/java/com/cloud/network/dao/RouterHealthCheckResultVO.java b/engine/schema/src/main/java/com/cloud/network/dao/RouterHealthCheckResultVO.java index 9803ccb6a4b..204ef2d1538 100644 --- a/engine/schema/src/main/java/com/cloud/network/dao/RouterHealthCheckResultVO.java +++ b/engine/schema/src/main/java/com/cloud/network/dao/RouterHealthCheckResultVO.java @@ -29,6 +29,7 @@ import javax.persistence.Temporal; import javax.persistence.TemporalType; import com.cloud.network.RouterHealthCheckResult; +import com.cloud.network.VirtualNetworkApplianceService; import com.cloud.utils.StringUtils; @Entity @@ -49,7 +50,7 @@ public class RouterHealthCheckResultVO implements RouterHealthCheckResult { private String checkType; @Column(name = "check_result") - private boolean checkResult; + private VirtualNetworkApplianceService.RouterHealthStatus checkResult; @Temporal(TemporalType.TIMESTAMP) @Column(name = "last_update", updatable = true, nullable = true) @@ -87,7 +88,7 @@ public class RouterHealthCheckResultVO implements RouterHealthCheckResult { } @Override - public boolean getCheckResult() { + public VirtualNetworkApplianceService.RouterHealthStatus getCheckResult() { return checkResult; } @@ -105,7 +106,7 @@ public class RouterHealthCheckResultVO implements RouterHealthCheckResult { return checkDetails; } - public void setCheckResult(boolean checkResult) { + public void setCheckResult(VirtualNetworkApplianceService.RouterHealthStatus checkResult) { this.checkResult = checkResult; } diff --git a/engine/schema/src/main/java/com/cloud/storage/DiskOfferingVO.java b/engine/schema/src/main/java/com/cloud/storage/DiskOfferingVO.java index 79f5bcb5157..7f6b6d8adf0 100644 --- a/engine/schema/src/main/java/com/cloud/storage/DiskOfferingVO.java +++ b/engine/schema/src/main/java/com/cloud/storage/DiskOfferingVO.java @@ -577,11 +577,11 @@ public class DiskOfferingVO implements DiskOffering { @Override public void setEncrypt(boolean encrypt) { this.encrypt = encrypt; } + @Override public boolean isShared() { return !useLocalStorage; } - public boolean getDiskSizeStrictness() { return diskSizeStrictness; } diff --git a/engine/schema/src/main/java/com/cloud/storage/SnapshotPolicyVO.java b/engine/schema/src/main/java/com/cloud/storage/SnapshotPolicyVO.java index f57d9d3dccf..299c6380ab6 100644 --- a/engine/schema/src/main/java/com/cloud/storage/SnapshotPolicyVO.java +++ b/engine/schema/src/main/java/com/cloud/storage/SnapshotPolicyVO.java @@ -59,6 +59,12 @@ public class SnapshotPolicyVO implements SnapshotPolicy { @Column(name = "uuid") String uuid; + @Column(name = "account_id") + long accountId; + + @Column(name = "domain_id") + long domainId; + @Column(name = "display", updatable = true, nullable = false) protected boolean display = true; @@ -66,7 +72,7 @@ public class SnapshotPolicyVO implements SnapshotPolicy { this.uuid = UUID.randomUUID().toString(); } - public SnapshotPolicyVO(long volumeId, String schedule, String timezone, IntervalType intvType, int maxSnaps, boolean display) { + public SnapshotPolicyVO(long volumeId, String schedule, String timezone, IntervalType intvType, int maxSnaps, long accountId, long domainId, boolean display) { this.volumeId = volumeId; this.schedule = schedule; this.timezone = timezone; @@ -75,6 +81,8 @@ public class SnapshotPolicyVO implements SnapshotPolicy { this.active = true; this.display = display; this.uuid = UUID.randomUUID().toString(); + this.accountId = accountId; + this.domainId = domainId; } @Override @@ -160,4 +168,32 @@ public class SnapshotPolicyVO implements SnapshotPolicy { public void setDisplay(boolean display) { this.display = display; } + + @Override + public long getAccountId() { + return accountId; + } + + public void setAccountId(long accountId) { + this.accountId = accountId; + } + + @Override + public long getDomainId() { + return domainId; + } + + public void setDomainId(long domainId) { + this.domainId = domainId; + } + + @Override + public Class getEntityType() { + return SnapshotPolicy.class; + } + + @Override + public String getName() { + return null; + } } diff --git a/engine/schema/src/main/java/com/cloud/storage/StoragePoolHostVO.java b/engine/schema/src/main/java/com/cloud/storage/StoragePoolHostVO.java index 53c08322e0c..73a11b02c05 100644 --- a/engine/schema/src/main/java/com/cloud/storage/StoragePoolHostVO.java +++ b/engine/schema/src/main/java/com/cloud/storage/StoragePoolHostVO.java @@ -28,6 +28,7 @@ import javax.persistence.Temporal; import javax.persistence.TemporalType; import com.cloud.utils.db.GenericDaoBase; +import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils; /** * Join table for storage pools and hosts @@ -100,4 +101,9 @@ public class StoragePoolHostVO implements StoragePoolHostAssoc { this.localPath = localPath; } + @Override + public String toString() { + return ReflectionToStringBuilderUtils.reflectOnlySelectedFields(this, "hostId", "poolId"); + } + } diff --git a/engine/schema/src/main/java/com/cloud/storage/dao/DiskOfferingDao.java b/engine/schema/src/main/java/com/cloud/storage/dao/DiskOfferingDao.java index f726bca3c5d..9beea003744 100644 --- a/engine/schema/src/main/java/com/cloud/storage/dao/DiskOfferingDao.java +++ b/engine/schema/src/main/java/com/cloud/storage/dao/DiskOfferingDao.java @@ -31,6 +31,8 @@ public interface DiskOfferingDao extends GenericDao { List listAllBySizeAndProvisioningType(long size, Storage.ProvisioningType provisioningType); List findCustomDiskOfferings(); + List listByStorageTag(String tag); + List listAllActiveAndNonComputeDiskOfferings(); } diff --git a/engine/schema/src/main/java/com/cloud/storage/dao/DiskOfferingDaoImpl.java b/engine/schema/src/main/java/com/cloud/storage/dao/DiskOfferingDaoImpl.java index 93e74766277..4ca3fe9f12a 100644 --- a/engine/schema/src/main/java/com/cloud/storage/dao/DiskOfferingDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/storage/dao/DiskOfferingDaoImpl.java @@ -26,6 +26,7 @@ import java.util.List; import javax.inject.Inject; import javax.persistence.EntityExistsException; +import com.cloud.offering.DiskOffering; import org.apache.cloudstack.resourcedetail.dao.DiskOfferingDetailsDao; import org.springframework.stereotype.Component; @@ -45,6 +46,8 @@ public class DiskOfferingDaoImpl extends GenericDaoBase im protected DiskOfferingDetailsDao detailsDao; protected final SearchBuilder UniqueNameSearch; + protected final SearchBuilder ActiveAndNonComputeSearch; + private final String SizeDiskOfferingSearch = "SELECT * FROM disk_offering WHERE " + "disk_size = ? AND provisioning_type = ? AND removed IS NULL"; @@ -56,6 +59,11 @@ public class DiskOfferingDaoImpl extends GenericDaoBase im UniqueNameSearch.and("name", UniqueNameSearch.entity().getUniqueName(), SearchCriteria.Op.EQ); UniqueNameSearch.done(); + ActiveAndNonComputeSearch = createSearchBuilder(); + ActiveAndNonComputeSearch.and("state", ActiveAndNonComputeSearch.entity().getState(), SearchCriteria.Op.EQ); + ActiveAndNonComputeSearch.and("computeOnly", ActiveAndNonComputeSearch.entity().isComputeOnly(), SearchCriteria.Op.EQ); + ActiveAndNonComputeSearch.done(); + _computeOnlyAttr = _allAttributes.get("computeOnly"); } @@ -164,4 +172,12 @@ public class DiskOfferingDaoImpl extends GenericDaoBase im sc.setParameters("tagEndLike", "%," + tag); return listBy(sc); } + + @Override + public List listAllActiveAndNonComputeDiskOfferings() { + SearchCriteria sc = ActiveAndNonComputeSearch.create(); + sc.setParameters("state", DiskOffering.State.Active); + sc.setParameters("computeOnly", false); + return listBy(sc); + } } diff --git a/engine/schema/src/main/java/com/cloud/storage/dao/VMTemplatePoolDao.java b/engine/schema/src/main/java/com/cloud/storage/dao/VMTemplatePoolDao.java index a3ce03a74c3..a208590e23a 100644 --- a/engine/schema/src/main/java/com/cloud/storage/dao/VMTemplatePoolDao.java +++ b/engine/schema/src/main/java/com/cloud/storage/dao/VMTemplatePoolDao.java @@ -35,6 +35,8 @@ public interface VMTemplatePoolDao extends GenericDao listByPoolIdAndState(long poolId, ObjectInDataStoreStateMachine.State state); + List listByPoolIdsAndTemplate(List poolIds, Long templateId); + List listByTemplateStatus(long templateId, VMTemplateStoragePoolVO.Status downloadState); List listByTemplateStatus(long templateId, VMTemplateStoragePoolVO.Status downloadState, long poolId); diff --git a/engine/schema/src/main/java/com/cloud/storage/dao/VMTemplatePoolDaoImpl.java b/engine/schema/src/main/java/com/cloud/storage/dao/VMTemplatePoolDaoImpl.java index 5a2ec1163fb..5dfc138d8e1 100644 --- a/engine/schema/src/main/java/com/cloud/storage/dao/VMTemplatePoolDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/storage/dao/VMTemplatePoolDaoImpl.java @@ -150,6 +150,16 @@ public class VMTemplatePoolDaoImpl extends GenericDaoBase listByPoolIdsAndTemplate(List poolIds, Long templateId) { + SearchCriteria sc = PoolTemplateSearch.create(); + if (CollectionUtils.isNotEmpty(poolIds)) { + sc.setParameters("pool_id", poolIds.toArray()); + } + sc.setParameters("template_id", templateId); + return listBy(sc); + } + @Override public List listByTemplateStatus(long templateId, VMTemplateStoragePoolVO.Status downloadState) { SearchCriteria sc = TemplateStatusSearch.create(); diff --git a/engine/schema/src/main/java/com/cloud/storage/dao/VolumeDaoImpl.java b/engine/schema/src/main/java/com/cloud/storage/dao/VolumeDaoImpl.java index f8b6bb3ed68..6814636bc66 100644 --- a/engine/schema/src/main/java/com/cloud/storage/dao/VolumeDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/storage/dao/VolumeDaoImpl.java @@ -822,6 +822,7 @@ public class VolumeDaoImpl extends GenericDaoBase implements Vol if (volume.getState() != Volume.State.Destroy) { volume.setState(Volume.State.Destroy); volume.setPoolId(null); + volume.setPoolType(null); volume.setInstanceId(null); update(volume.getId(), volume); remove(volume.getId()); diff --git a/engine/schema/src/main/java/com/cloud/upgrade/DatabaseUpgradeChecker.java b/engine/schema/src/main/java/com/cloud/upgrade/DatabaseUpgradeChecker.java index c211b3e9728..ee8055f5c56 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/DatabaseUpgradeChecker.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/DatabaseUpgradeChecker.java @@ -33,11 +33,10 @@ import java.util.List; import javax.inject.Inject; -import com.cloud.utils.FileUtil; import org.apache.cloudstack.utils.CloudStackVersion; import org.apache.commons.lang3.StringUtils; -import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import com.cloud.upgrade.dao.DbUpgrade; import com.cloud.upgrade.dao.DbUpgradeSystemVmTemplate; @@ -90,9 +89,10 @@ import com.cloud.upgrade.dao.Upgrade41900to41910; import com.cloud.upgrade.dao.Upgrade41910to42000; import com.cloud.upgrade.dao.Upgrade42000to42010; import com.cloud.upgrade.dao.Upgrade42010to42100; -import com.cloud.upgrade.dao.Upgrade42100to42200; import com.cloud.upgrade.dao.Upgrade420to421; +import com.cloud.upgrade.dao.Upgrade42100to42200; import com.cloud.upgrade.dao.Upgrade421to430; +import com.cloud.upgrade.dao.Upgrade42200to42300; import com.cloud.upgrade.dao.Upgrade430to440; import com.cloud.upgrade.dao.Upgrade431to440; import com.cloud.upgrade.dao.Upgrade432to440; @@ -121,6 +121,7 @@ import com.cloud.upgrade.dao.VersionDao; import com.cloud.upgrade.dao.VersionDaoImpl; import com.cloud.upgrade.dao.VersionVO; import com.cloud.upgrade.dao.VersionVO.Step; +import com.cloud.utils.FileUtil; import com.cloud.utils.component.SystemIntegrityChecker; import com.cloud.utils.crypt.DBEncryptionUtil; import com.cloud.utils.db.GlobalLock; @@ -236,6 +237,7 @@ public class DatabaseUpgradeChecker implements SystemIntegrityChecker { .next("4.20.0.0", new Upgrade42000to42010()) .next("4.20.1.0", new Upgrade42010to42100()) .next("4.21.0.0", new Upgrade42100to42200()) + .next("4.22.0.0", new Upgrade42200to42300()) .build(); } diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41810to41900.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41810to41900.java index e2b1ae1399b..28cf91ec6b0 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41810to41900.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade41810to41900.java @@ -159,7 +159,7 @@ public class Upgrade41810to41900 extends DbUpgradeAbstractImpl implements DbUpgr try (PreparedStatement pstmt = conn.prepareStatement(createNewColumn)) { pstmt.execute(); } catch (SQLException e) { - String message = String.format("Unable to crate new backups' column date due to [%s].", e.getMessage()); + String message = String.format("Unable to create new backups' column date due to [%s].", e.getMessage()); logger.error(message, e); throw new CloudRuntimeException(message, e); } diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade42100to42200.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade42100to42200.java index c2cfd02c15c..5138d51bb1b 100644 --- a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade42100to42200.java +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade42100to42200.java @@ -16,6 +16,14 @@ // under the License. package com.cloud.upgrade.dao; +import com.cloud.utils.exception.CloudRuntimeException; + +import java.io.InputStream; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; + public class Upgrade42100to42200 extends DbUpgradeAbstractImpl implements DbUpgrade, DbUpgradeSystemVmTemplate { @Override @@ -27,4 +35,69 @@ public class Upgrade42100to42200 extends DbUpgradeAbstractImpl implements DbUpgr public String getUpgradedVersion() { return "4.22.0.0"; } + + @Override + public InputStream[] getPrepareScripts() { + final String scriptFile = "META-INF/db/schema-42100to42200.sql"; + final InputStream script = Thread.currentThread().getContextClassLoader().getResourceAsStream(scriptFile); + if (script == null) { + throw new CloudRuntimeException("Unable to find " + scriptFile); + } + + return new InputStream[] {script}; + } + + @Override + public void performDataMigration(Connection conn) { + updateSnapshotPolicyOwnership(conn); + updateBackupScheduleOwnership(conn); + } + + protected void updateSnapshotPolicyOwnership(Connection conn) { + // set account_id and domain_id in snapshot_policy table from volume table + String selectSql = "SELECT sp.id, v.account_id, v.domain_id FROM snapshot_policy sp, volumes v WHERE sp.volume_id = v.id AND (sp.account_id IS NULL AND sp.domain_id IS NULL)"; + String updateSql = "UPDATE snapshot_policy SET account_id = ?, domain_id = ? WHERE id = ?"; + + try (PreparedStatement selectPstmt = conn.prepareStatement(selectSql); + ResultSet rs = selectPstmt.executeQuery(); + PreparedStatement updatePstmt = conn.prepareStatement(updateSql)) { + + while (rs.next()) { + long policyId = rs.getLong(1); + long accountId = rs.getLong(2); + long domainId = rs.getLong(3); + + updatePstmt.setLong(1, accountId); + updatePstmt.setLong(2, domainId); + updatePstmt.setLong(3, policyId); + updatePstmt.executeUpdate(); + } + } catch (SQLException e) { + throw new CloudRuntimeException("Unable to update snapshot_policy table with account_id and domain_id", e); + } + } + + protected void updateBackupScheduleOwnership(Connection conn) { + // Set account_id and domain_id in backup_schedule table from vm_instance table + String selectSql = "SELECT bs.id, vm.account_id, vm.domain_id FROM backup_schedule bs, vm_instance vm WHERE bs.vm_id = vm.id AND (bs.account_id IS NULL AND bs.domain_id IS NULL)"; + String updateSql = "UPDATE backup_schedule SET account_id = ?, domain_id = ? WHERE id = ?"; + + try (PreparedStatement selectPstmt = conn.prepareStatement(selectSql); + ResultSet rs = selectPstmt.executeQuery(); + PreparedStatement updatePstmt = conn.prepareStatement(updateSql)) { + + while (rs.next()) { + long scheduleId = rs.getLong(1); + long accountId = rs.getLong(2); + long domainId = rs.getLong(3); + + updatePstmt.setLong(1, accountId); + updatePstmt.setLong(2, domainId); + updatePstmt.setLong(3, scheduleId); + updatePstmt.executeUpdate(); + } + } catch (SQLException e) { + throw new CloudRuntimeException("Unable to update backup_schedule table with account_id and domain_id", e); + } + } } diff --git a/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade42200to42300.java b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade42200to42300.java new file mode 100644 index 00000000000..0ea04c1a216 --- /dev/null +++ b/engine/schema/src/main/java/com/cloud/upgrade/dao/Upgrade42200to42300.java @@ -0,0 +1,30 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.upgrade.dao; + +public class Upgrade42200to42300 extends DbUpgradeAbstractImpl implements DbUpgrade, DbUpgradeSystemVmTemplate { + + @Override + public String[] getUpgradableVersionRange() { + return new String[]{"4.22.0.0", "4.23.0.0"}; + } + + @Override + public String getUpgradedVersion() { + return "4.23.0.0"; + } +} diff --git a/engine/schema/src/main/java/com/cloud/usage/dao/UsageBackupDaoImpl.java b/engine/schema/src/main/java/com/cloud/usage/dao/UsageBackupDaoImpl.java index e5b46b02a59..3f852b0cfb5 100644 --- a/engine/schema/src/main/java/com/cloud/usage/dao/UsageBackupDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/usage/dao/UsageBackupDaoImpl.java @@ -68,7 +68,7 @@ public class UsageBackupDaoImpl extends GenericDaoBase impl pstmt.setString(1, DateUtil.getDateDisplayString(TimeZone.getTimeZone("GMT"), eventDate)); pstmt.setLong(2, accountId); pstmt.setLong(3, vmId); - pstmt.setLong(3, backupOfferingId); + pstmt.setLong(4, backupOfferingId); pstmt.executeUpdate(); } } catch (SQLException e) { diff --git a/engine/schema/src/main/java/com/cloud/vm/ImportVMTaskVO.java b/engine/schema/src/main/java/com/cloud/vm/ImportVMTaskVO.java new file mode 100644 index 00000000000..9a8a769f0a5 --- /dev/null +++ b/engine/schema/src/main/java/com/cloud/vm/ImportVMTaskVO.java @@ -0,0 +1,270 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// +package com.cloud.vm; + +import org.apache.cloudstack.vm.ImportVmTask; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; +import java.util.Date; +import java.util.UUID; + +@Entity +@Table(name = "import_vm_task") +public class ImportVMTaskVO implements ImportVmTask { + + public ImportVMTaskVO(long zoneId, long accountId, long userId, String displayName, + String vcenter, String datacenter, String sourceVMName, long convertHostId, long importHostId) { + this.zoneId = zoneId; + this.accountId = accountId; + this.userId = userId; + this.displayName = displayName; + this.vcenter = vcenter; + this.datacenter = datacenter; + this.sourceVMName = sourceVMName; + this.step = Step.Prepare; + this.uuid = UUID.randomUUID().toString(); + this.convertHostId = convertHostId; + this.importHostId = importHostId; + } + + public ImportVMTaskVO() { + } + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private long id; + + @Column(name = "uuid") + private String uuid; + + @Column(name = "zone_id") + private long zoneId; + + @Column(name = "account_id") + private long accountId; + + @Column(name = "user_id") + private long userId; + + @Column(name = "vm_id") + private Long vmId; + @Column(name = "display_name") + private String displayName; + + @Column(name = "vcenter") + private String vcenter; + + @Column(name = "datacenter") + private String datacenter; + + @Column(name = "source_vm_name") + private String sourceVMName; + + @Column(name = "convert_host_id") + private long convertHostId; + + @Column(name = "import_host_id") + private long importHostId; + + @Column(name = "step") + private Step step; + + @Column(name = "state") + private TaskState state; + + @Column(name = "description") + private String description; + + @Column(name = "duration") + private Long duration; + + @Column(name = "created") + @Temporal(value = TemporalType.TIMESTAMP) + private Date created; + + @Column(name = "updated") + @Temporal(value = TemporalType.TIMESTAMP) + private Date updated; + + @Column(name = "removed") + @Temporal(value = TemporalType.TIMESTAMP) + private Date removed; + + @Override + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + @Override + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + public long getZoneId() { + return zoneId; + } + + public void setZoneId(long zoneId) { + this.zoneId = zoneId; + } + + public long getAccountId() { + return accountId; + } + + public void setAccountId(long accountId) { + this.accountId = accountId; + } + + public long getUserId() { + return userId; + } + + public void setUserId(long userId) { + this.userId = userId; + } + + public Long getVmId() { + return vmId; + } + + public void setVmId(Long vmId) { + this.vmId = vmId; + } + + public String getDisplayName() { + return displayName; + } + + public void setDisplayName(String displayName) { + this.displayName = displayName; + } + + public String getVcenter() { + return vcenter; + } + + public void setVcenter(String vcenter) { + this.vcenter = vcenter; + } + + public String getDatacenter() { + return datacenter; + } + + public void setDatacenter(String datacenter) { + this.datacenter = datacenter; + } + + public String getSourceVMName() { + return sourceVMName; + } + + public void setSourceVMName(String sourceVMName) { + this.sourceVMName = sourceVMName; + } + + public long getConvertHostId() { + return convertHostId; + } + + public void setConvertHostId(long convertHostId) { + this.convertHostId = convertHostId; + } + + public long getImportHostId() { + return importHostId; + } + + public void setImportHostId(long importHostId) { + this.importHostId = importHostId; + } + + public Step getStep() { + return step; + } + + public void setStep(Step step) { + this.step = step; + } + + public TaskState getState() { + return state; + } + + public void setState(TaskState state) { + this.state = state; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public Long getDuration() { + return duration; + } + + public void setDuration(Long duration) { + this.duration = duration; + } + + public Date getCreated() { + return created; + } + + public void setCreated(Date created) { + this.created = created; + } + + public Date getUpdated() { + return updated; + } + + public void setUpdated(Date updated) { + this.updated = updated; + } + + public Date getRemoved() { + return removed; + } + + public void setRemoved(Date removed) { + this.removed = removed; + } +} diff --git a/engine/schema/src/main/java/com/cloud/vm/dao/ImportVMTaskDao.java b/engine/schema/src/main/java/com/cloud/vm/dao/ImportVMTaskDao.java new file mode 100644 index 00000000000..a4f0a155da4 --- /dev/null +++ b/engine/schema/src/main/java/com/cloud/vm/dao/ImportVMTaskDao.java @@ -0,0 +1,31 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// +package com.cloud.vm.dao; + +import com.cloud.utils.Pair; +import com.cloud.utils.db.GenericDao; +import com.cloud.vm.ImportVMTaskVO; +import org.apache.cloudstack.vm.ImportVmTask; +import java.util.List; + +public interface ImportVMTaskDao extends GenericDao { + + Pair, Integer> listImportVMTasks(Long zoneId, Long accountId, String vcenter, Long convertHostId, + ImportVmTask.TaskState state, Long startIndex, Long pageSizeVal); +} diff --git a/engine/schema/src/main/java/com/cloud/vm/dao/ImportVMTaskDaoImpl.java b/engine/schema/src/main/java/com/cloud/vm/dao/ImportVMTaskDaoImpl.java new file mode 100644 index 00000000000..da9c391af9d --- /dev/null +++ b/engine/schema/src/main/java/com/cloud/vm/dao/ImportVMTaskDaoImpl.java @@ -0,0 +1,74 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.vm.dao; + +import com.cloud.utils.Pair; +import com.cloud.utils.db.Filter; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; +import com.cloud.vm.ImportVMTaskVO; +import org.apache.cloudstack.vm.ImportVmTask; +import org.apache.commons.lang3.StringUtils; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; +import java.util.List; + +@Component +public class ImportVMTaskDaoImpl extends GenericDaoBase implements ImportVMTaskDao { + + private SearchBuilder AllFieldsSearch; + + public ImportVMTaskDaoImpl() { + } + + @PostConstruct + void init() { + AllFieldsSearch = createSearchBuilder(); + AllFieldsSearch.and("zoneId", AllFieldsSearch.entity().getZoneId(), SearchCriteria.Op.EQ); + AllFieldsSearch.and("accountId", AllFieldsSearch.entity().getAccountId(), SearchCriteria.Op.EQ); + AllFieldsSearch.and("vcenter", AllFieldsSearch.entity().getVcenter(), SearchCriteria.Op.EQ); + AllFieldsSearch.and("convertHostId", AllFieldsSearch.entity().getConvertHostId(), SearchCriteria.Op.EQ); + AllFieldsSearch.and("state", AllFieldsSearch.entity().getState(), SearchCriteria.Op.EQ); + AllFieldsSearch.done(); + } + + + @Override + public Pair, Integer> listImportVMTasks(Long zoneId, Long accountId, String vcenter, Long convertHostId, + ImportVmTask.TaskState state, Long startIndex, Long pageSizeVal) { + SearchCriteria sc = AllFieldsSearch.create(); + if (zoneId != null) { + sc.setParameters("zoneId", zoneId); + } + if (accountId != null) { + sc.setParameters("accountId", accountId); + } + if (StringUtils.isNotBlank(vcenter)) { + sc.setParameters("vcenter", vcenter); + } + if (convertHostId != null) { + sc.setParameters("convertHostId", convertHostId); + } + if (state != null) { + sc.setParameters("state", state); + } + Filter filter = new Filter(ImportVMTaskVO.class, "created", false, startIndex, pageSizeVal); + return searchAndCount(sc, filter); + } +} diff --git a/engine/schema/src/main/java/com/cloud/vm/dao/UserVmDaoImpl.java b/engine/schema/src/main/java/com/cloud/vm/dao/UserVmDaoImpl.java index 41bcb3155e5..d3775fe3540 100644 --- a/engine/schema/src/main/java/com/cloud/vm/dao/UserVmDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/vm/dao/UserVmDaoImpl.java @@ -782,7 +782,7 @@ public class UserVmDaoImpl extends GenericDaoBase implements Use result.add(new Ternary(rs.getInt(1), rs.getInt(2), rs.getInt(3))); } } catch (Exception e) { - logger.warn("Error counting vms by size for dcId= " + dcId, e); + logger.warn("Error counting vms by size for Data Center ID = " + dcId, e); } return result; } diff --git a/engine/schema/src/main/java/com/cloud/vm/dao/VMInstanceDaoImpl.java b/engine/schema/src/main/java/com/cloud/vm/dao/VMInstanceDaoImpl.java index 2f19d36c37a..339573c10fa 100755 --- a/engine/schema/src/main/java/com/cloud/vm/dao/VMInstanceDaoImpl.java +++ b/engine/schema/src/main/java/com/cloud/vm/dao/VMInstanceDaoImpl.java @@ -116,17 +116,17 @@ public class VMInstanceDaoImpl extends GenericDaoBase implem protected Attribute _updateTimeAttr; - private static final String ORDER_CLUSTERS_NUMBER_OF_VMS_FOR_ACCOUNT_PART1 = "SELECT host.cluster_id, SUM(IF(vm.state='Running' AND vm.account_id = ?, 1, 0)) " + + private static final String ORDER_CLUSTERS_NUMBER_OF_VMS_FOR_ACCOUNT_PART1 = "SELECT host.cluster_id, SUM(IF(vm.state IN ('Running', 'Starting') AND vm.account_id = ?, 1, 0)) " + "FROM `cloud`.`host` host LEFT JOIN `cloud`.`vm_instance` vm ON host.id = vm.host_id WHERE "; private static final String ORDER_CLUSTERS_NUMBER_OF_VMS_FOR_ACCOUNT_PART2 = " AND host.type = 'Routing' AND host.removed is null GROUP BY host.cluster_id " + "ORDER BY 2 ASC "; - private static final String ORDER_PODS_NUMBER_OF_VMS_FOR_ACCOUNT = "SELECT pod.id, SUM(IF(vm.state='Running' AND vm.account_id = ?, 1, 0)) FROM `cloud`.`" + + private static final String ORDER_PODS_NUMBER_OF_VMS_FOR_ACCOUNT = "SELECT pod.id, SUM(IF(vm.state IN ('Running', 'Starting') AND vm.account_id = ?, 1, 0)) FROM `cloud`.`" + "host_pod_ref` pod LEFT JOIN `cloud`.`vm_instance` vm ON pod.id = vm.pod_id WHERE pod.data_center_id = ? AND pod.removed is null " + " GROUP BY pod.id ORDER BY 2 ASC "; private static final String ORDER_HOSTS_NUMBER_OF_VMS_FOR_ACCOUNT = - "SELECT host.id, SUM(IF(vm.state='Running' AND vm.account_id = ?, 1, 0)) FROM `cloud`.`host` host LEFT JOIN `cloud`.`vm_instance` vm ON host.id = vm.host_id " + + "SELECT host.id, SUM(IF(vm.state IN ('Running', 'Starting') AND vm.account_id = ?, 1, 0)) FROM `cloud`.`host` host LEFT JOIN `cloud`.`vm_instance` vm ON host.id = vm.host_id " + "WHERE host.data_center_id = ? AND host.type = 'Routing' AND host.removed is null "; private static final String ORDER_HOSTS_NUMBER_OF_VMS_FOR_ACCOUNT_PART2 = " GROUP BY host.id ORDER BY 2 ASC "; @@ -886,7 +886,7 @@ public class VMInstanceDaoImpl extends GenericDaoBase implem return rs.getLong(1); } } catch (Exception e) { - logger.warn(String.format("Error counting vms by host tag for dcId= %s, hostTag= %s", dcId, hostTag), e); + logger.warn(String.format("Error counting vms by host tag for dcId = %s, hostTag = %s", dcId, hostTag), e); } return 0L; } diff --git a/engine/schema/src/main/java/com/cloud/vm/snapshot/dao/VMSnapshotDao.java b/engine/schema/src/main/java/com/cloud/vm/snapshot/dao/VMSnapshotDao.java index 4045af58d4b..39ae3d4f2fd 100644 --- a/engine/schema/src/main/java/com/cloud/vm/snapshot/dao/VMSnapshotDao.java +++ b/engine/schema/src/main/java/com/cloud/vm/snapshot/dao/VMSnapshotDao.java @@ -42,6 +42,8 @@ public interface VMSnapshotDao extends GenericDao, StateDao< VMSnapshotVO findByName(Long vmId, String name); List listByAccountId(Long accountId); + List searchByVms(List vmIds); + List searchRemovedByVms(List vmIds, Long batchSize); } diff --git a/engine/schema/src/main/java/org/apache/cloudstack/backup/BackupRepositoryVO.java b/engine/schema/src/main/java/org/apache/cloudstack/backup/BackupRepositoryVO.java index 98efa94ceca..1764496a6c0 100644 --- a/engine/schema/src/main/java/org/apache/cloudstack/backup/BackupRepositoryVO.java +++ b/engine/schema/src/main/java/org/apache/cloudstack/backup/BackupRepositoryVO.java @@ -67,6 +67,9 @@ public class BackupRepositoryVO implements BackupRepository { @Column(name = "capacity_bytes", nullable = true) private Long capacityBytes; + @Column(name = "cross_zone_instance_creation") + private Boolean crossZoneInstanceCreation; + @Column(name = "created") @Temporal(value = TemporalType.TIMESTAMP) private Date created; @@ -79,7 +82,7 @@ public class BackupRepositoryVO implements BackupRepository { this.uuid = UUID.randomUUID().toString(); } - public BackupRepositoryVO(final long zoneId, final String provider, final String name, final String type, final String address, final String mountOptions, final Long capacityBytes) { + public BackupRepositoryVO(final long zoneId, final String provider, final String name, final String type, final String address, final String mountOptions, final Long capacityBytes, final Boolean crossZoneInstanceCreation) { this(); this.zoneId = zoneId; this.provider = provider; @@ -88,6 +91,7 @@ public class BackupRepositoryVO implements BackupRepository { this.address = address; this.mountOptions = mountOptions; this.capacityBytes = capacityBytes; + this.crossZoneInstanceCreation = crossZoneInstanceCreation; this.created = new Date(); } @@ -139,6 +143,11 @@ public class BackupRepositoryVO implements BackupRepository { return mountOptions; } + @Override + public void setMountOptions(String mountOptions) { + this.mountOptions = mountOptions; + } + @Override public Long getUsedBytes() { return usedBytes; @@ -154,6 +163,16 @@ public class BackupRepositoryVO implements BackupRepository { return capacityBytes; } + @Override + public Boolean crossZoneInstanceCreationEnabled() { + return crossZoneInstanceCreation; + } + + @Override + public void setCrossZoneInstanceCreation(Boolean crossZoneInstanceCreation) { + this.crossZoneInstanceCreation = crossZoneInstanceCreation; + } + @Override public void setCapacityBytes(Long capacityBytes) { this.capacityBytes = capacityBytes; diff --git a/engine/schema/src/main/java/org/apache/cloudstack/backup/BackupScheduleVO.java b/engine/schema/src/main/java/org/apache/cloudstack/backup/BackupScheduleVO.java index 37e8105e3d5..1ee2cff78b6 100644 --- a/engine/schema/src/main/java/org/apache/cloudstack/backup/BackupScheduleVO.java +++ b/engine/schema/src/main/java/org/apache/cloudstack/backup/BackupScheduleVO.java @@ -68,10 +68,16 @@ public class BackupScheduleVO implements BackupSchedule { @Column(name = "quiescevm") Boolean quiesceVM = false; + @Column(name = "account_id") + Long accountId; + + @Column(name = "domain_id") + Long domainId; + public BackupScheduleVO() { } - public BackupScheduleVO(Long vmId, DateUtil.IntervalType scheduleType, String schedule, String timezone, Date scheduledTimestamp, int maxBackups, Boolean quiesceVM) { + public BackupScheduleVO(Long vmId, DateUtil.IntervalType scheduleType, String schedule, String timezone, Date scheduledTimestamp, int maxBackups, Boolean quiesceVM, Long accountId, Long domainId) { this.vmId = vmId; this.scheduleType = (short) scheduleType.ordinal(); this.schedule = schedule; @@ -79,6 +85,8 @@ public class BackupScheduleVO implements BackupSchedule { this.scheduledTimestamp = scheduledTimestamp; this.maxBackups = maxBackups; this.quiesceVM = quiesceVM; + this.accountId = accountId; + this.domainId = domainId; } @Override @@ -161,4 +169,32 @@ public class BackupScheduleVO implements BackupSchedule { public Boolean getQuiesceVM() { return quiesceVM; } + + @Override + public Class getEntityType() { + return BackupSchedule.class; + } + + @Override + public String getName() { + return null; + } + + @Override + public long getDomainId() { + return domainId; + } + + @Override + public long getAccountId() { + return accountId; + } + + public void setAccountId(Long accountId) { + this.accountId = accountId; + } + + public void setDomainId(Long domainId) { + this.domainId = domainId; + } } diff --git a/engine/schema/src/main/java/org/apache/cloudstack/backup/dao/BackupOfferingDao.java b/engine/schema/src/main/java/org/apache/cloudstack/backup/dao/BackupOfferingDao.java index d001de8b6c6..d40e828121e 100644 --- a/engine/schema/src/main/java/org/apache/cloudstack/backup/dao/BackupOfferingDao.java +++ b/engine/schema/src/main/java/org/apache/cloudstack/backup/dao/BackupOfferingDao.java @@ -24,7 +24,7 @@ import org.apache.cloudstack.backup.BackupOfferingVO; import com.cloud.utils.db.GenericDao; public interface BackupOfferingDao extends GenericDao { - BackupOfferingResponse newBackupOfferingResponse(BackupOffering policy); + BackupOfferingResponse newBackupOfferingResponse(BackupOffering policy, Boolean crossZoneInstanceCreation); BackupOffering findByExternalId(String externalId, Long zoneId); BackupOffering findByName(String name, Long zoneId); } diff --git a/engine/schema/src/main/java/org/apache/cloudstack/backup/dao/BackupOfferingDaoImpl.java b/engine/schema/src/main/java/org/apache/cloudstack/backup/dao/BackupOfferingDaoImpl.java index 9d67d07fe5e..a41e4e70d33 100644 --- a/engine/schema/src/main/java/org/apache/cloudstack/backup/dao/BackupOfferingDaoImpl.java +++ b/engine/schema/src/main/java/org/apache/cloudstack/backup/dao/BackupOfferingDaoImpl.java @@ -50,7 +50,7 @@ public class BackupOfferingDaoImpl extends GenericDaoBase { List findPoolsByStorageTypeAndZone(Storage.StoragePoolType storageType, Long zoneId); + List listByDataCenterIds(List dataCenterIds); } diff --git a/engine/schema/src/main/java/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreDaoImpl.java b/engine/schema/src/main/java/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreDaoImpl.java index 8b230d03154..b5d6415e3a1 100644 --- a/engine/schema/src/main/java/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreDaoImpl.java +++ b/engine/schema/src/main/java/org/apache/cloudstack/storage/datastore/db/PrimaryDataStoreDaoImpl.java @@ -65,6 +65,7 @@ public class PrimaryDataStoreDaoImpl extends GenericDaoBase private final GenericSearchBuilder StatusCountSearch; private final SearchBuilder ClustersSearch; private final SearchBuilder IdsSearch; + private final SearchBuilder DcsSearch; @Inject private StoragePoolDetailsDao _detailsDao; @@ -167,6 +168,9 @@ public class PrimaryDataStoreDaoImpl extends GenericDaoBase IdsSearch.and("ids", IdsSearch.entity().getId(), SearchCriteria.Op.IN); IdsSearch.done(); + DcsSearch = createSearchBuilder(); + DcsSearch.and("dataCenterId", DcsSearch.entity().getDataCenterId(), SearchCriteria.Op.IN); + DcsSearch.done(); } @Override @@ -320,6 +324,9 @@ public class PrimaryDataStoreDaoImpl extends GenericDaoBase pool = super.persist(pool); if (details != null) { for (Map.Entry detail : details.entrySet()) { + if (detail.getKey().toLowerCase().contains("password") || detail.getKey().toLowerCase().contains("token")) { + displayDetails = false; + } StoragePoolDetailVO vo = new StoragePoolDetailVO(pool.getId(), detail.getKey(), detail.getValue(), displayDetails); _detailsDao.persist(vo); } @@ -924,6 +931,16 @@ public class PrimaryDataStoreDaoImpl extends GenericDaoBase return listBy(sc); } + @Override + public List listByDataCenterIds(List dataCenterIds) { + if (CollectionUtils.isEmpty(dataCenterIds)) { + return Collections.emptyList(); + } + SearchCriteria sc = DcsSearch.create(); + sc.setParameters("dataCenterId", dataCenterIds.toArray()); + return listBy(sc); + } + private SearchCriteria createStoragePoolSearchCriteria(Long storagePoolId, String storagePoolName, Long zoneId, String path, Long podId, Long clusterId, Long hostId, String address, ScopeType scopeType, StoragePoolStatus status, String keyword, String storageAccessGroup) { diff --git a/engine/schema/src/main/resources/META-INF/cloudstack/core/spring-engine-schema-core-daos-context.xml b/engine/schema/src/main/resources/META-INF/cloudstack/core/spring-engine-schema-core-daos-context.xml index 7e9d6c3b54f..0656d5e3c44 100644 --- a/engine/schema/src/main/resources/META-INF/cloudstack/core/spring-engine-schema-core-daos-context.xml +++ b/engine/schema/src/main/resources/META-INF/cloudstack/core/spring-engine-schema-core-daos-context.xml @@ -309,4 +309,5 @@ + diff --git a/engine/schema/src/main/resources/META-INF/db/procedures/cloud.idempotent_drop_unique_key.sql b/engine/schema/src/main/resources/META-INF/db/procedures/cloud.idempotent_drop_unique_key.sql new file mode 100644 index 00000000000..fdcca6fb408 --- /dev/null +++ b/engine/schema/src/main/resources/META-INF/db/procedures/cloud.idempotent_drop_unique_key.sql @@ -0,0 +1,26 @@ +-- Licensed to the Apache Software Foundation (ASF) under one +-- or more contributor license agreements. See the NOTICE file +-- distributed with this work for additional information +-- regarding copyright ownership. The ASF licenses this file +-- to you under the Apache License, Version 2.0 (the +-- "License"); you may not use this file except in compliance +-- with the License. You may obtain a copy of the License at +-- +-- http://www.apache.org/licenses/LICENSE-2.0 +-- +-- Unless required by applicable law or agreed to in writing, +-- software distributed under the License is distributed on an +-- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +-- KIND, either express or implied. See the License for the +-- specific language governing permissions and limitations +-- under the License. + +-- in cloud +DROP PROCEDURE IF EXISTS `cloud`.`IDEMPOTENT_DROP_UNIQUE_KEY`; + +CREATE PROCEDURE `cloud`.`IDEMPOTENT_DROP_UNIQUE_KEY` ( + IN in_table_name VARCHAR(200), + IN in_index_name VARCHAR(200) +) +BEGIN + DECLARE CONTINUE HANDLER FOR 1091, 1025 BEGIN END; SET @ddl = CONCAT('ALTER TABLE ', in_table_name, ' DROP KEY ', in_index_name); PREPARE stmt FROM @ddl; EXECUTE stmt; DEALLOCATE PREPARE stmt; END; diff --git a/engine/schema/src/main/resources/META-INF/db/schema-307to410.sql b/engine/schema/src/main/resources/META-INF/db/schema-307to410.sql index 55d78b59437..3b0cfa8e6ce 100644 --- a/engine/schema/src/main/resources/META-INF/db/schema-307to410.sql +++ b/engine/schema/src/main/resources/META-INF/db/schema-307to410.sql @@ -3,7 +3,7 @@ -- distributed with this work for additional information -- regarding copyright ownership. The ASF licenses this file -- to you under the Apache License, Version 2.0 (the --- "License"); you may not use this file except in compliances +-- "License"); you may not use this file except in compliance -- with the License. You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 diff --git a/engine/schema/src/main/resources/META-INF/db/schema-410to420.sql b/engine/schema/src/main/resources/META-INF/db/schema-410to420.sql index 35f73b35d3c..d62a9bb9303 100644 --- a/engine/schema/src/main/resources/META-INF/db/schema-410to420.sql +++ b/engine/schema/src/main/resources/META-INF/db/schema-410to420.sql @@ -2305,7 +2305,7 @@ CREATE TABLE `cloud_usage`.`usage_vmsnapshot` ( ) ENGINE=InnoDB CHARSET=utf8; INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Advanced', 'DEFAULT', 'management-server', 'healthcheck.update.interval', '600', 'Time Interval to fetch the LB health check states (in sec)'); -INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Snapshots', 'DEFAULT', 'SnapshotManager', 'kvm.snapshot.enabled', 'false', 'whether snapshot is enabled for KVM hosts'); +INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Snapshots', 'DEFAULT', 'SnapshotManager', 'kvm.snapshot.enabled', 'true', 'whether snapshot is enabled for KVM hosts'); INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Advanced', 'DEFAULT', 'management-server', 'eip.use.multiple.netscalers', 'false', 'Should be set to true, if there will be multiple NetScaler devices providing EIP service in a zone'); INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Snapshots', 'DEFAULT', 'SnapshotManager', 'snapshot.backup.rightafter', 'true', 'backup snapshot right after snapshot is taken'); diff --git a/engine/schema/src/main/resources/META-INF/db/schema-42100to42200.sql b/engine/schema/src/main/resources/META-INF/db/schema-42100to42200.sql index cf3fe2ed772..b523016aa3d 100644 --- a/engine/schema/src/main/resources/META-INF/db/schema-42100to42200.sql +++ b/engine/schema/src/main/resources/META-INF/db/schema-42100to42200.sql @@ -19,5 +19,71 @@ -- Schema upgrade from 4.21.0.0 to 4.22.0.0 --; + +-- health check status as enum +CALL `cloud`.`IDEMPOTENT_CHANGE_COLUMN`('router_health_check', 'check_result', 'check_result', 'varchar(16) NOT NULL COMMENT "check executions result: SUCCESS, FAILURE, WARNING, UNKNOWN"'); + -- Increase length of scripts_version column to 128 due to md5sum to sha512sum change CALL `cloud`.`IDEMPOTENT_CHANGE_COLUMN`('cloud.domain_router', 'scripts_version', 'scripts_version', 'VARCHAR(128)'); + +CALL `cloud`.`IDEMPOTENT_ADD_COLUMN`('cloud.snapshot_policy','domain_id', 'BIGINT(20) DEFAULT NULL'); +CALL `cloud`.`IDEMPOTENT_ADD_COLUMN`('cloud.snapshot_policy','account_id', 'BIGINT(20) DEFAULT NULL'); + +CALL `cloud`.`IDEMPOTENT_ADD_COLUMN`('cloud.backup_schedule','domain_id', 'BIGINT(20) DEFAULT NULL'); +CALL `cloud`.`IDEMPOTENT_ADD_COLUMN`('cloud.backup_schedule','account_id', 'BIGINT(20) DEFAULT NULL'); + +-- Increase the cache_mode column size from cloud.disk_offering table +CALL `cloud`.`IDEMPOTENT_CHANGE_COLUMN`('cloud.disk_offering', 'cache_mode', 'cache_mode', 'varchar(18) DEFAULT "none" COMMENT "The disk cache mode to use for disks created with this offering"'); + +-- Add uuid column to ldap_configuration table +CALL `cloud`.`IDEMPOTENT_ADD_COLUMN`('cloud.ldap_configuration', 'uuid', 'VARCHAR(40) NOT NULL'); + +-- Populate uuid for existing rows where uuid is NULL or empty +UPDATE `cloud`.`ldap_configuration` SET uuid = UUID() WHERE uuid IS NULL OR uuid = ''; + +-- Add the column cross_zone_instance_creation to cloud.backup_repository. if enabled it means that new Instance can be created on all Zones from Backups on this Repository. +CALL `cloud`.`IDEMPOTENT_ADD_COLUMN`('cloud.backup_repository', 'cross_zone_instance_creation', 'TINYINT(1) DEFAULT NULL COMMENT ''Backup Repository can be used for disaster recovery on another zone'''); + +-- Updated display to false for password/token detail of the storage pool details +UPDATE `cloud`.`storage_pool_details` SET display = 0 WHERE name LIKE '%password%'; +UPDATE `cloud`.`storage_pool_details` SET display = 0 WHERE name LIKE '%token%'; + +-- Add csi_enabled column to kubernetes_cluster table to indicate if the cluster is using csi or not +CALL `cloud`.`IDEMPOTENT_ADD_COLUMN`('cloud.kubernetes_cluster', 'csi_enabled', 'TINYINT(1) unsigned NOT NULL DEFAULT 0 COMMENT "true if kubernetes cluster is using csi, false otherwise" '); + +-- VMware to KVM migration improvements +CREATE TABLE IF NOT EXISTS `cloud`.`import_vm_task`( + `id` bigint unsigned NOT NULL auto_increment COMMENT 'id', + `uuid` varchar(40), + `zone_id` bigint unsigned NOT NULL COMMENT 'Zone ID', + `account_id` bigint unsigned NOT NULL COMMENT 'Account ID', + `user_id` bigint unsigned NOT NULL COMMENT 'User ID', + `vm_id` bigint unsigned COMMENT 'VM ID', + `display_name` varchar(255) COMMENT 'Display VM Name', + `vcenter` varchar(255) COMMENT 'VCenter', + `datacenter` varchar(255) COMMENT 'VCenter Datacenter name', + `source_vm_name` varchar(255) COMMENT 'Source VM name on vCenter', + `convert_host_id` bigint unsigned COMMENT 'Convert Host ID', + `import_host_id` bigint unsigned COMMENT 'Import Host ID', + `step` varchar(20) COMMENT 'Importing VM Task Step', + `state` varchar(20) COMMENT 'Importing VM Task State', + `description` varchar(255) COMMENT 'Importing VM Task Description', + `duration` bigint unsigned COMMENT 'Duration in milliseconds for the completed tasks', + `created` datetime NOT NULL COMMENT 'date created', + `updated` datetime COMMENT 'date updated if not null', + `removed` datetime COMMENT 'date removed if not null', + PRIMARY KEY (`id`), + CONSTRAINT `fk_import_vm_task__zone_id` FOREIGN KEY `fk_import_vm_task__zone_id` (`zone_id`) REFERENCES `data_center`(`id`) ON DELETE CASCADE, + CONSTRAINT `fk_import_vm_task__account_id` FOREIGN KEY `fk_import_vm_task__account_id` (`account_id`) REFERENCES `account`(`id`) ON DELETE CASCADE, + CONSTRAINT `fk_import_vm_task__user_id` FOREIGN KEY `fk_import_vm_task__user_id` (`user_id`) REFERENCES `user`(`id`) ON DELETE CASCADE, + CONSTRAINT `fk_import_vm_task__vm_id` FOREIGN KEY `fk_import_vm_task__vm_id` (`vm_id`) REFERENCES `vm_instance`(`id`) ON DELETE CASCADE, + CONSTRAINT `fk_import_vm_task__convert_host_id` FOREIGN KEY `fk_import_vm_task__convert_host_id` (`convert_host_id`) REFERENCES `host`(`id`) ON DELETE CASCADE, + CONSTRAINT `fk_import_vm_task__import_host_id` FOREIGN KEY `fk_import_vm_task__import_host_id` (`import_host_id`) REFERENCES `host`(`id`) ON DELETE CASCADE, + INDEX `i_import_vm_task__zone_id`(`zone_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +CALL `cloud`.`INSERT_EXTENSION_IF_NOT_EXISTS`('MaaS', 'Baremetal Extension for Canonical MaaS written in Python', 'MaaS/maas.py'); +CALL `cloud`.`INSERT_EXTENSION_DETAIL_IF_NOT_EXISTS`('MaaS', 'orchestratorrequirespreparevm', 'true', 0); + +CALL `cloud`.`IDEMPOTENT_DROP_UNIQUE_KEY`('counter', 'uc_counter__provider__source__value'); +CALL `cloud`.`IDEMPOTENT_ADD_UNIQUE_KEY`('cloud.counter', 'uc_counter__provider__source__value__removed', '(provider, source, value, removed)'); diff --git a/engine/schema/src/main/resources/META-INF/db/schema-42200to42300-cleanup.sql b/engine/schema/src/main/resources/META-INF/db/schema-42200to42300-cleanup.sql new file mode 100644 index 00000000000..f2f5dec5003 --- /dev/null +++ b/engine/schema/src/main/resources/META-INF/db/schema-42200to42300-cleanup.sql @@ -0,0 +1,20 @@ +-- Licensed to the Apache Software Foundation (ASF) under one +-- or more contributor license agreements. See the NOTICE file +-- distributed with this work for additional information +-- regarding copyright ownership. The ASF licenses this file +-- to you under the Apache License, Version 2.0 (the +-- "License"); you may not use this file except in compliance +-- with the License. You may obtain a copy of the License at +-- +-- http://www.apache.org/licenses/LICENSE-2.0 +-- +-- Unless required by applicable law or agreed to in writing, +-- software distributed under the License is distributed on an +-- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +-- KIND, either express or implied. See the License for the +-- specific language governing permissions and limitations +-- under the License. + +--; +-- Schema upgrade cleanup from 4.22.0.0 to 4.23.0.0 +--; diff --git a/engine/schema/src/main/resources/META-INF/db/schema-42010to42100cleanup.sql b/engine/schema/src/main/resources/META-INF/db/schema-42200to42300.sql similarity index 94% rename from engine/schema/src/main/resources/META-INF/db/schema-42010to42100cleanup.sql rename to engine/schema/src/main/resources/META-INF/db/schema-42200to42300.sql index 9165565f544..c1f1bb2c094 100644 --- a/engine/schema/src/main/resources/META-INF/db/schema-42010to42100cleanup.sql +++ b/engine/schema/src/main/resources/META-INF/db/schema-42200to42300.sql @@ -16,5 +16,5 @@ -- under the License. --; --- Schema upgrade from 4.20.1.0 to 4.21.0.0 +-- Schema upgrade from 4.22.0.0 to 4.23.0.0 --; diff --git a/engine/schema/src/test/java/com/cloud/upgrade/dao/Upgrade42100to42200Test.java b/engine/schema/src/test/java/com/cloud/upgrade/dao/Upgrade42100to42200Test.java new file mode 100644 index 00000000000..cff34fb4e20 --- /dev/null +++ b/engine/schema/src/test/java/com/cloud/upgrade/dao/Upgrade42100to42200Test.java @@ -0,0 +1,242 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.upgrade.dao; + +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.inOrder; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InOrder; +import org.mockito.Mock; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; + +@RunWith(MockitoJUnitRunner.class) +public class Upgrade42100to42200Test { + + @Spy + Upgrade42100to42200 upgrade; + + @Mock + private Connection conn; + + @Mock + private PreparedStatement selectStmt; + + @Mock + private PreparedStatement updateStmt; + + @Mock + private ResultSet resultSet; + + @Test + public void testUpdateSnapshotPolicyOwnership() throws SQLException { + // Setup mock data for snapshot policies without ownership + when(conn.prepareStatement("SELECT sp.id, v.account_id, v.domain_id FROM snapshot_policy sp, volumes v WHERE sp.volume_id = v.id AND (sp.account_id IS NULL AND sp.domain_id IS NULL)")) + .thenReturn(selectStmt); + when(conn.prepareStatement("UPDATE snapshot_policy SET account_id = ?, domain_id = ? WHERE id = ?")) + .thenReturn(updateStmt); + when(selectStmt.executeQuery()).thenReturn(resultSet); + + when(resultSet.next()) + .thenReturn(true) + .thenReturn(true) + .thenReturn(false); + + when(resultSet.getLong(1)) + .thenReturn(1L) + .thenReturn(2L); + when(resultSet.getLong(2)) + .thenReturn(100L) + .thenReturn(200L); + when(resultSet.getLong(3)) + .thenReturn(1L) + .thenReturn(2L); + + upgrade.updateSnapshotPolicyOwnership(conn); + + verify(conn).prepareStatement("SELECT sp.id, v.account_id, v.domain_id FROM snapshot_policy sp, volumes v WHERE sp.volume_id = v.id AND (sp.account_id IS NULL AND sp.domain_id IS NULL)"); + verify(conn).prepareStatement("UPDATE snapshot_policy SET account_id = ?, domain_id = ? WHERE id = ?"); + + InOrder inOrder = inOrder(updateStmt); + + inOrder.verify(updateStmt).setLong(1, 100L); // account_id + inOrder.verify(updateStmt).setLong(2, 1L); // domain_id + inOrder.verify(updateStmt).setLong(3, 1L); // policy_id + inOrder.verify(updateStmt).executeUpdate(); + + inOrder.verify(updateStmt).setLong(1, 200L); // account_id + inOrder.verify(updateStmt).setLong(2, 2L); // domain_id + inOrder.verify(updateStmt).setLong(3, 2L); // policy_id + inOrder.verify(updateStmt).executeUpdate(); + + verify(updateStmt, times(2)).executeUpdate(); + } + + @Test + public void testUpdateBackupScheduleOwnership() throws SQLException { + when(conn.prepareStatement("SELECT bs.id, vm.account_id, vm.domain_id FROM backup_schedule bs, vm_instance vm WHERE bs.vm_id = vm.id AND (bs.account_id IS NULL AND bs.domain_id IS NULL)")) + .thenReturn(selectStmt); + when(conn.prepareStatement("UPDATE backup_schedule SET account_id = ?, domain_id = ? WHERE id = ?")) + .thenReturn(updateStmt); + when(selectStmt.executeQuery()).thenReturn(resultSet); + + when(resultSet.next()) + .thenReturn(true) + .thenReturn(true) + .thenReturn(true) + .thenReturn(false); + + when(resultSet.getLong(1)) + .thenReturn(10L) + .thenReturn(20L) + .thenReturn(30L); + when(resultSet.getLong(2)) + .thenReturn(500L) + .thenReturn(600L) + .thenReturn(700L); + when(resultSet.getLong(3)) + .thenReturn(5L) + .thenReturn(6L) + .thenReturn(7L); + + upgrade.updateBackupScheduleOwnership(conn); + + verify(conn).prepareStatement("SELECT bs.id, vm.account_id, vm.domain_id FROM backup_schedule bs, vm_instance vm WHERE bs.vm_id = vm.id AND (bs.account_id IS NULL AND bs.domain_id IS NULL)"); + verify(conn).prepareStatement("UPDATE backup_schedule SET account_id = ?, domain_id = ? WHERE id = ?"); + + InOrder inOrder = inOrder(updateStmt); + + inOrder.verify(updateStmt).setLong(1, 500L); + inOrder.verify(updateStmt).setLong(2, 5L); + inOrder.verify(updateStmt).setLong(3, 10L); + inOrder.verify(updateStmt).executeUpdate(); + + inOrder.verify(updateStmt).setLong(1, 600L); + inOrder.verify(updateStmt).setLong(2, 6L); + inOrder.verify(updateStmt).setLong(3, 20L); + inOrder.verify(updateStmt).executeUpdate(); + + inOrder.verify(updateStmt).setLong(1, 700L); + inOrder.verify(updateStmt).setLong(2, 7L); + inOrder.verify(updateStmt).setLong(3, 30L); + inOrder.verify(updateStmt).executeUpdate(); + + verify(updateStmt, times(3)).executeUpdate(); + } + + @Test + public void testUpdateSnapshotPolicyOwnershipNoResults() throws SQLException { + when(conn.prepareStatement("SELECT sp.id, v.account_id, v.domain_id FROM snapshot_policy sp, volumes v WHERE sp.volume_id = v.id AND (sp.account_id IS NULL AND sp.domain_id IS NULL)")) + .thenReturn(selectStmt); + when(conn.prepareStatement("UPDATE snapshot_policy SET account_id = ?, domain_id = ? WHERE id = ?")) + .thenReturn(updateStmt); + when(selectStmt.executeQuery()).thenReturn(resultSet); + + when(resultSet.next()).thenReturn(false); + + upgrade.updateSnapshotPolicyOwnership(conn); + + verify(selectStmt).executeQuery(); + verify(updateStmt, times(0)).executeUpdate(); + } + + @Test + public void testUpdateBackupScheduleOwnershipNoResults() throws SQLException { + when(conn.prepareStatement("SELECT bs.id, vm.account_id, vm.domain_id FROM backup_schedule bs, vm_instance vm WHERE bs.vm_id = vm.id AND (bs.account_id IS NULL AND bs.domain_id IS NULL)")) + .thenReturn(selectStmt); + when(conn.prepareStatement("UPDATE backup_schedule SET account_id = ?, domain_id = ? WHERE id = ?")) + .thenReturn(updateStmt); + when(selectStmt.executeQuery()).thenReturn(resultSet); + + when(resultSet.next()).thenReturn(false); + + upgrade.updateBackupScheduleOwnership(conn); + + verify(selectStmt).executeQuery(); + verify(updateStmt, times(0)).executeUpdate(); + } + + @Test + public void testPerformDataMigration() throws SQLException { + when(conn.prepareStatement(anyString())).thenReturn(selectStmt); + when(selectStmt.executeQuery()).thenReturn(resultSet); + when(resultSet.next()).thenReturn(false); + + upgrade.performDataMigration(conn); + + verify(conn).prepareStatement("SELECT sp.id, v.account_id, v.domain_id FROM snapshot_policy sp, volumes v WHERE sp.volume_id = v.id AND (sp.account_id IS NULL AND sp.domain_id IS NULL)"); + verify(conn).prepareStatement("SELECT bs.id, vm.account_id, vm.domain_id FROM backup_schedule bs, vm_instance vm WHERE bs.vm_id = vm.id AND (bs.account_id IS NULL AND bs.domain_id IS NULL)"); + } + + @Test + public void testUpdateSnapshotPolicyOwnershipSingleRecord() throws SQLException { + when(conn.prepareStatement("SELECT sp.id, v.account_id, v.domain_id FROM snapshot_policy sp, volumes v WHERE sp.volume_id = v.id AND (sp.account_id IS NULL AND sp.domain_id IS NULL)")) + .thenReturn(selectStmt); + when(conn.prepareStatement("UPDATE snapshot_policy SET account_id = ?, domain_id = ? WHERE id = ?")) + .thenReturn(updateStmt); + when(selectStmt.executeQuery()).thenReturn(resultSet); + + when(resultSet.next()) + .thenReturn(true) + .thenReturn(false); + + when(resultSet.getLong(1)).thenReturn(42L); + when(resultSet.getLong(2)).thenReturn(999L); + when(resultSet.getLong(3)).thenReturn(10L); + + upgrade.updateSnapshotPolicyOwnership(conn); + + verify(updateStmt).setLong(1, 999L); + verify(updateStmt).setLong(2, 10L); + verify(updateStmt).setLong(3, 42L); + verify(updateStmt, times(1)).executeUpdate(); + } + + @Test + public void testUpdateBackupScheduleOwnershipSingleRecord() throws SQLException { + when(conn.prepareStatement("SELECT bs.id, vm.account_id, vm.domain_id FROM backup_schedule bs, vm_instance vm WHERE bs.vm_id = vm.id AND (bs.account_id IS NULL AND bs.domain_id IS NULL)")) + .thenReturn(selectStmt); + when(conn.prepareStatement("UPDATE backup_schedule SET account_id = ?, domain_id = ? WHERE id = ?")) + .thenReturn(updateStmt); + when(selectStmt.executeQuery()).thenReturn(resultSet); + + when(resultSet.next()) + .thenReturn(true) + .thenReturn(false); + + when(resultSet.getLong(1)).thenReturn(55L); + when(resultSet.getLong(2)).thenReturn(888L); + when(resultSet.getLong(3)).thenReturn(15L); + + upgrade.updateBackupScheduleOwnership(conn); + + verify(updateStmt).setLong(1, 888L); + verify(updateStmt).setLong(2, 15L); + verify(updateStmt).setLong(3, 55L); + verify(updateStmt, times(1)).executeUpdate(); + } +} diff --git a/engine/service/pom.xml b/engine/service/pom.xml index 3ea24cfd4af..9b833804064 100644 --- a/engine/service/pom.xml +++ b/engine/service/pom.xml @@ -22,7 +22,7 @@ org.apache.cloudstack cloud-engine - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT cloud-engine-service war diff --git a/engine/storage/cache/pom.xml b/engine/storage/cache/pom.xml index fbdb7d2c548..ac330ca6997 100644 --- a/engine/storage/cache/pom.xml +++ b/engine/storage/cache/pom.xml @@ -24,7 +24,7 @@ org.apache.cloudstack cloud-engine - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT ../../pom.xml diff --git a/engine/storage/configdrive/pom.xml b/engine/storage/configdrive/pom.xml index 3ba607a6ad9..43eb249b538 100644 --- a/engine/storage/configdrive/pom.xml +++ b/engine/storage/configdrive/pom.xml @@ -24,7 +24,7 @@ org.apache.cloudstack cloud-engine - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT ../../pom.xml diff --git a/engine/storage/datamotion/pom.xml b/engine/storage/datamotion/pom.xml index 9652f804f1d..d3b6bb54352 100644 --- a/engine/storage/datamotion/pom.xml +++ b/engine/storage/datamotion/pom.xml @@ -24,7 +24,7 @@ org.apache.cloudstack cloud-engine - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT ../../pom.xml diff --git a/engine/storage/datamotion/src/main/java/org/apache/cloudstack/storage/motion/AncientDataMotionStrategy.java b/engine/storage/datamotion/src/main/java/org/apache/cloudstack/storage/motion/AncientDataMotionStrategy.java index 0b0065361d0..c494ca31594 100644 --- a/engine/storage/datamotion/src/main/java/org/apache/cloudstack/storage/motion/AncientDataMotionStrategy.java +++ b/engine/storage/datamotion/src/main/java/org/apache/cloudstack/storage/motion/AncientDataMotionStrategy.java @@ -18,9 +18,11 @@ */ package org.apache.cloudstack.storage.motion; +import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Objects; import javax.inject.Inject; @@ -67,6 +69,7 @@ import com.cloud.configuration.Config; import com.cloud.host.Host; import com.cloud.hypervisor.Hypervisor; import com.cloud.storage.DataStoreRole; +import com.cloud.storage.ScopeType; import com.cloud.storage.Snapshot.Type; import com.cloud.storage.SnapshotVO; import com.cloud.storage.StorageManager; @@ -85,6 +88,11 @@ public class AncientDataMotionStrategy implements DataMotionStrategy { protected Logger logger = LogManager.getLogger(getClass()); private static final String NO_REMOTE_ENDPOINT_SSVM = "No remote endpoint to send command, check if host or ssvm is down?"; private static final String NO_REMOTE_ENDPOINT_WITH_ENCRYPTION = "No remote endpoint to send command, unable to find a valid endpoint. Requires encryption support: %s"; + private static final List SUPPORTED_POOL_TYPES_TO_BYPASS_SECONDARY_STORE = Arrays.asList( + StoragePoolType.NetworkFilesystem, + StoragePoolType.Filesystem, + StoragePoolType.RBD + ); @Inject EndPointSelector selector; @@ -240,7 +248,6 @@ public class AncientDataMotionStrategy implements DataMotionStrategy { return dataTO; } - protected Answer copyObject(DataObject srcData, DataObject destData) { return copyObject(srcData, destData, null); } @@ -352,14 +359,12 @@ public class AncientDataMotionStrategy implements DataMotionStrategy { Scope destScope = getZoneScope(destData.getDataStore().getScope()); DataStore cacheStore = cacheMgr.getCacheStorage(destScope); - boolean bypassSecondaryStorage = false; - if (srcData instanceof VolumeInfo && ((VolumeInfo)srcData).isDirectDownload()) { - bypassSecondaryStorage = true; - } + boolean bypassSecondaryStorage = canBypassSecondaryStorage(srcData, destData); boolean encryptionRequired = anyVolumeRequiresEncryption(srcData, destData); if (cacheStore == null) { if (bypassSecondaryStorage) { + logger.debug("Secondary storage is bypassed, copy volume between pools directly"); CopyCommand cmd = new CopyCommand(srcData.getTO(), destData.getTO(), _copyvolumewait, VirtualMachineManager.ExecuteInSequence.value()); EndPoint ep = selector.select(srcData, destData, encryptionRequired); Answer answer = null; @@ -388,8 +393,8 @@ public class AncientDataMotionStrategy implements DataMotionStrategy { answer = copyObject(srcData, objOnImageStore); if (answer == null || !answer.getResult()) { - if (answer != null) { - if (logger.isDebugEnabled()) logger.debug("copy to image store failed: " + answer.getDetails()); + if (answer != null && logger.isDebugEnabled()) { + logger.debug("copy to image store failed: {}", answer.getDetails()); } objOnImageStore.processEvent(Event.OperationFailed); imageStore.delete(objOnImageStore); @@ -411,8 +416,8 @@ public class AncientDataMotionStrategy implements DataMotionStrategy { } if (answer == null || !answer.getResult()) { - if (answer != null) { - if (logger.isDebugEnabled()) logger.debug("copy to primary store failed: " + answer.getDetails()); + if (answer != null && logger.isDebugEnabled()) { + logger.debug("copy to primary store failed: {}", answer.getDetails()); } objOnImageStore.processEvent(Event.OperationFailed); imageStore.delete(objOnImageStore); @@ -423,7 +428,7 @@ public class AncientDataMotionStrategy implements DataMotionStrategy { objOnImageStore.processEvent(Event.OperationFailed); imageStore.delete(objOnImageStore); } - logger.error("Failed to perform operation: "+ e.getLocalizedMessage()); + logger.error("Failed to perform operation: {}", e.getLocalizedMessage()); throw e; } @@ -448,7 +453,78 @@ public class AncientDataMotionStrategy implements DataMotionStrategy { } return answer; } + } + private boolean canBypassSecondaryStorage(DataObject srcData, DataObject destData) { + if (srcData instanceof VolumeInfo) { + if (((VolumeInfo)srcData).isDirectDownload()) { + return true; + } + + if (destData instanceof VolumeInfo) { + Scope srcDataStoreScope = srcData.getDataStore().getScope(); + Scope destDataStoreScope = destData.getDataStore().getScope(); + logger.info("srcDataStoreScope: {}, srcData pool type: {}; destDataStoreScope: {}, destData pool type: {}", + srcDataStoreScope, ((VolumeInfo)srcData).getStoragePoolType(), destDataStoreScope, ((VolumeInfo)destData).getStoragePoolType()); + + if (srcDataStoreScope != null && destDataStoreScope != null && + SUPPORTED_POOL_TYPES_TO_BYPASS_SECONDARY_STORE.contains(((VolumeInfo)srcData).getStoragePoolType()) && + SUPPORTED_POOL_TYPES_TO_BYPASS_SECONDARY_STORE.contains(((VolumeInfo)destData).getStoragePoolType())) { + + return canDirectlyCopyBetweenDataStoreScopes(srcDataStoreScope, destDataStoreScope); + } + } + } + + return false; + } + + private boolean canDirectlyCopyBetweenDataStoreScopes(Scope srcDataStoreScope, Scope destDataStoreScope) { + if (srcDataStoreScope == null || destDataStoreScope == null) { + return false; + } + + if (srcDataStoreScope.isSameScope(destDataStoreScope)) { + return true; + } + + if (srcDataStoreScope.getScopeType() == ScopeType.HOST) { + if (destDataStoreScope.getScopeType() == ScopeType.CLUSTER && + (Objects.equals(((HostScope) srcDataStoreScope).getClusterId(), ((ClusterScope) destDataStoreScope).getScopeId()))) { + return true; + } + if (destDataStoreScope.getScopeType() == ScopeType.ZONE && + (Objects.equals(((HostScope) srcDataStoreScope).getZoneId(), ((ZoneScope) destDataStoreScope).getScopeId()))) { + return true; + } + } + + if (destDataStoreScope.getScopeType() == ScopeType.HOST) { + if (srcDataStoreScope.getScopeType() == ScopeType.CLUSTER && + (Objects.equals(((ClusterScope) srcDataStoreScope).getScopeId(), ((HostScope) destDataStoreScope).getClusterId()))) { + return true; + } + if (srcDataStoreScope.getScopeType() == ScopeType.ZONE && + (Objects.equals(((ZoneScope) srcDataStoreScope).getScopeId(), ((HostScope) destDataStoreScope).getZoneId()))) { + return true; + } + } + + if (srcDataStoreScope.getScopeType() == ScopeType.CLUSTER) { + if (destDataStoreScope.getScopeType() == ScopeType.ZONE && + (Objects.equals(((ClusterScope) srcDataStoreScope).getZoneId(), ((ZoneScope) destDataStoreScope).getScopeId()))) { + return true; + } + } + + if (destDataStoreScope.getScopeType() == ScopeType.CLUSTER) { + if (srcDataStoreScope.getScopeType() == ScopeType.ZONE && + (Objects.equals(((ZoneScope) srcDataStoreScope).getScopeId(), ((ClusterScope) destDataStoreScope).getZoneId()))) { + return true; + } + } + + return false; } protected Answer migrateVolumeToPool(DataObject srcData, DataObject destData) { @@ -492,6 +568,7 @@ public class AncientDataMotionStrategy implements DataMotionStrategy { } volumeVo.setPodId(destPool.getPodId()); volumeVo.setPoolId(destPool.getId()); + volumeVo.setPoolType(destPool.getPoolType()); volumeVo.setLastPoolId(oldPoolId); // For SMB, pool credentials are also stored in the uri query string. We trim the query string // part here to make sure the credentials do not get stored in the db unencrypted. diff --git a/engine/storage/datamotion/src/main/java/org/apache/cloudstack/storage/motion/StorageSystemDataMotionStrategy.java b/engine/storage/datamotion/src/main/java/org/apache/cloudstack/storage/motion/StorageSystemDataMotionStrategy.java index 0a211ab1934..fa8a7a79aa3 100644 --- a/engine/storage/datamotion/src/main/java/org/apache/cloudstack/storage/motion/StorageSystemDataMotionStrategy.java +++ b/engine/storage/datamotion/src/main/java/org/apache/cloudstack/storage/motion/StorageSystemDataMotionStrategy.java @@ -122,6 +122,7 @@ import com.cloud.storage.VMTemplateStoragePoolVO; import com.cloud.storage.VMTemplateStorageResourceAssoc; import com.cloud.storage.VMTemplateVO; import com.cloud.storage.Volume; +import com.cloud.storage.VolumeApiService; import com.cloud.storage.VolumeDetailVO; import com.cloud.storage.VolumeVO; import com.cloud.storage.dao.DiskOfferingDao; @@ -194,6 +195,8 @@ public class StorageSystemDataMotionStrategy implements DataMotionStrategy { @Inject private VolumeService _volumeService; @Inject + public VolumeApiService _volumeApiService; + @Inject private StorageCacheManager cacheMgr; @Inject private EndPointSelector selector; @@ -796,6 +799,7 @@ public class StorageSystemDataMotionStrategy implements DataMotionStrategy { volumeVO.setPodId(destPool.getPodId()); volumeVO.setPoolId(destPool.getId()); + volumeVO.setPoolType(destPool.getPoolType()); volumeVO.setLastPoolId(srcVolumeInfo.getPoolId()); _volumeDao.update(srcVolumeInfo.getId(), volumeVO); @@ -2348,11 +2352,22 @@ public class StorageSystemDataMotionStrategy implements DataMotionStrategy { volumeVO.setFormat(ImageFormat.QCOW2); volumeVO.setLastId(srcVolumeInfo.getId()); + if (Objects.equals(srcVolumeInfo.getDiskOfferingId(), destVolumeInfo.getDiskOfferingId())) { + StoragePoolVO srcPoolVO = _storagePoolDao.findById(srcVolumeInfo.getPoolId()); + StoragePoolVO destPoolVO = _storagePoolDao.findById(destVolumeInfo.getPoolId()); + if (srcPoolVO != null && destPoolVO != null && + ((srcPoolVO.isShared() && destPoolVO.isLocal()) || (srcPoolVO.isLocal() && destPoolVO.isShared()))) { + Long offeringId = getSuitableDiskOfferingForVolumeOnPool(volumeVO, destPoolVO); + if (offeringId != null) { + volumeVO.setDiskOfferingId(offeringId); + } + } + } + _volumeDao.update(volumeVO.getId(), volumeVO); _volumeService.copyPoliciesBetweenVolumesAndDestroySourceVolumeAfterMigration(Event.OperationSuccessed, null, srcVolumeInfo, destVolumeInfo, false); - // Update the volume ID for snapshots on secondary storage if (!_snapshotDao.listByVolumeId(srcVolumeInfo.getId()).isEmpty()) { _snapshotDao.updateVolumeIds(srcVolumeInfo.getId(), destVolumeInfo.getId()); @@ -2394,17 +2409,32 @@ public class StorageSystemDataMotionStrategy implements DataMotionStrategy { } } + private Long getSuitableDiskOfferingForVolumeOnPool(VolumeVO volume, StoragePoolVO pool) { + List diskOfferings = _diskOfferingDao.listAllActiveAndNonComputeDiskOfferings(); + for (DiskOfferingVO diskOffering : diskOfferings) { + try { + if (_volumeApiService.validateConditionsToReplaceDiskOfferingOfVolume(volume, diskOffering, pool)) { + logger.debug("Found suitable disk offering {} for the volume {}", diskOffering, volume); + return diskOffering.getId(); + } + } catch (Exception ignore) { + } + } + logger.warn("Unable to find suitable disk offering for the volume {}", volume); + return null; + } + private VolumeVO duplicateVolumeOnAnotherStorage(Volume volume, StoragePoolVO storagePoolVO) { Long lastPoolId = volume.getPoolId(); VolumeVO newVol = new VolumeVO(volume); - newVol.setInstanceId(null); newVol.setChainInfo(null); newVol.setPath(null); newVol.setFolder(null); newVol.setPodId(storagePoolVO.getPodId()); newVol.setPoolId(storagePoolVO.getId()); + newVol.setPoolType(storagePoolVO.getPoolType()); newVol.setLastPoolId(lastPoolId); newVol.setLastId(volume.getId()); diff --git a/engine/storage/datamotion/src/test/java/org/apache/cloudstack/storage/motion/AncientDataMotionStrategyTest.java b/engine/storage/datamotion/src/test/java/org/apache/cloudstack/storage/motion/AncientDataMotionStrategyTest.java index 67e3ea844d5..e167cc0a965 100755 --- a/engine/storage/datamotion/src/test/java/org/apache/cloudstack/storage/motion/AncientDataMotionStrategyTest.java +++ b/engine/storage/datamotion/src/test/java/org/apache/cloudstack/storage/motion/AncientDataMotionStrategyTest.java @@ -21,20 +21,34 @@ package org.apache.cloudstack.storage.motion; import static org.mockito.Mockito.when; import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.never; import static org.mockito.Mockito.any; +import com.cloud.storage.Storage; import com.cloud.storage.StorageManager; import com.cloud.storage.StoragePool; +import org.apache.cloudstack.engine.subsystem.api.storage.DataObject; +import org.apache.cloudstack.engine.subsystem.api.storage.DataStore; +import org.apache.cloudstack.engine.subsystem.api.storage.ClusterScope; +import org.apache.cloudstack.engine.subsystem.api.storage.HostScope; +import org.apache.cloudstack.engine.subsystem.api.storage.StorageCacheManager; +import org.apache.cloudstack.engine.subsystem.api.storage.ZoneScope; import org.apache.cloudstack.framework.config.ConfigKey; +import org.apache.cloudstack.framework.config.dao.ConfigurationDao; +import org.apache.cloudstack.storage.image.store.TemplateObject; import org.apache.cloudstack.storage.to.PrimaryDataStoreTO; +import org.apache.cloudstack.storage.volume.VolumeObject; +import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.Mockito; import org.mockito.Spy; import org.mockito.junit.MockitoJUnitRunner; @@ -57,6 +71,10 @@ public class AncientDataMotionStrategyTest { StorageManager storageManager; @Mock StoragePool storagePool; + @Mock + StorageCacheManager cacheMgr; + @Mock + ConfigurationDao configDao; private static final long POOL_ID = 1l; private static final Boolean FULL_CLONE_FLAG = true; @@ -88,4 +106,186 @@ public class AncientDataMotionStrategyTest { verify(dataStoreTO, never()).setFullCloneFlag(any(Boolean.class)); } + @Test + public void testCanBypassSecondaryStorageForDirectDownload() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { + VolumeObject srcVolumeInfo = Mockito.spy(new VolumeObject()); + Mockito.doReturn(true).when(srcVolumeInfo).isDirectDownload(); + + VolumeObject destVolumeInfo = Mockito.spy(new VolumeObject()); + + Method method; + method = AncientDataMotionStrategy.class.getDeclaredMethod("canBypassSecondaryStorage", DataObject.class, DataObject.class); + method.setAccessible(true); + boolean canBypassSecondaryStorage = (boolean) method.invoke(strategy, srcVolumeInfo, destVolumeInfo); + Assert.assertTrue(canBypassSecondaryStorage); + } + + @Test + public void testCanBypassSecondaryStorageForUnsupportedDataObject() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { + VolumeObject srcVolumeInfo = Mockito.spy(new VolumeObject()); + + TemplateObject destTemplateInfo = Mockito.spy(new TemplateObject()); + + Method method; + method = AncientDataMotionStrategy.class.getDeclaredMethod("canBypassSecondaryStorage", DataObject.class, DataObject.class); + method.setAccessible(true); + boolean canBypassSecondaryStorage = (boolean) method.invoke(strategy, srcVolumeInfo, destTemplateInfo); + Assert.assertFalse(canBypassSecondaryStorage); + } + + @Test + public void testCanBypassSecondaryStorageForUnsupportedSrcPoolType() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { + VolumeObject srcVolumeInfo = Mockito.spy(new VolumeObject()); + DataStore srcDataStore = Mockito.mock(DataStore.class); + Mockito.doReturn(new ZoneScope(1L)).when(srcDataStore).getScope(); + Mockito.doReturn(srcDataStore).when(srcVolumeInfo).getDataStore(); + Mockito.doReturn(Storage.StoragePoolType.PowerFlex).when(srcVolumeInfo).getStoragePoolType(); + + VolumeObject destVolumeInfo = Mockito.spy(new VolumeObject()); + DataStore destDataStore = Mockito.mock(DataStore.class); + Mockito.doReturn(new ZoneScope(1L)).when(destDataStore).getScope(); + Mockito.doReturn(destDataStore).when(destVolumeInfo).getDataStore(); + Mockito.doReturn(Storage.StoragePoolType.NetworkFilesystem).when(destVolumeInfo).getStoragePoolType(); + + Method method; + method = AncientDataMotionStrategy.class.getDeclaredMethod("canBypassSecondaryStorage", DataObject.class, DataObject.class); + method.setAccessible(true); + boolean canBypassSecondaryStorage = (boolean) method.invoke(strategy, srcVolumeInfo, destVolumeInfo); + Assert.assertFalse(canBypassSecondaryStorage); + } + + @Test + public void testCanBypassSecondaryStorageForUnsupportedDestPoolType() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { + VolumeObject srcVolumeInfo = Mockito.spy(new VolumeObject()); + DataStore srcDataStore = Mockito.mock(DataStore.class); + Mockito.doReturn(new ZoneScope(1L)).when(srcDataStore).getScope(); + Mockito.doReturn(srcDataStore).when(srcVolumeInfo).getDataStore(); + Mockito.doReturn(Storage.StoragePoolType.NetworkFilesystem).when(srcVolumeInfo).getStoragePoolType(); + + VolumeObject destVolumeInfo = Mockito.spy(new VolumeObject()); + DataStore destDataStore = Mockito.mock(DataStore.class); + Mockito.doReturn(new ZoneScope(1L)).when(destDataStore).getScope(); + Mockito.doReturn(destDataStore).when(destVolumeInfo).getDataStore(); + Mockito.doReturn(Storage.StoragePoolType.Iscsi).when(destVolumeInfo).getStoragePoolType(); + + Method method; + method = AncientDataMotionStrategy.class.getDeclaredMethod("canBypassSecondaryStorage", DataObject.class, DataObject.class); + method.setAccessible(true); + boolean canBypassSecondaryStorage = (boolean) method.invoke(strategy, srcVolumeInfo, destVolumeInfo); + Assert.assertFalse(canBypassSecondaryStorage); + } + + @Test + public void testCanBypassSecondaryStorageWithZoneWideNFSPoolsInSameZone() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { + VolumeObject srcVolumeInfo = Mockito.spy(new VolumeObject()); + DataStore srcDataStore = Mockito.mock(DataStore.class); + Mockito.doReturn(new ZoneScope(1L)).when(srcDataStore).getScope(); + Mockito.doReturn(srcDataStore).when(srcVolumeInfo).getDataStore(); + Mockito.doReturn(Storage.StoragePoolType.NetworkFilesystem).when(srcVolumeInfo).getStoragePoolType(); + + VolumeObject destVolumeInfo = Mockito.spy(new VolumeObject()); + DataStore destDataStore = Mockito.mock(DataStore.class); + Mockito.doReturn(new ZoneScope(1L)).when(destDataStore).getScope(); + Mockito.doReturn(destDataStore).when(destVolumeInfo).getDataStore(); + Mockito.doReturn(Storage.StoragePoolType.NetworkFilesystem).when(destVolumeInfo).getStoragePoolType(); + + Method method; + method = AncientDataMotionStrategy.class.getDeclaredMethod("canBypassSecondaryStorage", DataObject.class, DataObject.class); + method.setAccessible(true); + boolean canBypassSecondaryStorage = (boolean) method.invoke(strategy, srcVolumeInfo, destVolumeInfo); + Assert.assertTrue(canBypassSecondaryStorage); + } + + @Test + public void testCanBypassSecondaryStorageWithClusterWideNFSPoolsInSameCluster() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { + VolumeObject srcVolumeInfo = Mockito.spy(new VolumeObject()); + DataStore srcDataStore = Mockito.mock(DataStore.class); + Mockito.doReturn(new ClusterScope(5L, 2L, 1L)).when(srcDataStore).getScope(); + Mockito.doReturn(srcDataStore).when(srcVolumeInfo).getDataStore(); + Mockito.doReturn(Storage.StoragePoolType.NetworkFilesystem).when(srcVolumeInfo).getStoragePoolType(); + + VolumeObject destVolumeInfo = Mockito.spy(new VolumeObject()); + DataStore destDataStore = Mockito.mock(DataStore.class); + Mockito.doReturn(new ClusterScope(5L, 2L, 1L)).when(destDataStore).getScope(); + Mockito.doReturn(destDataStore).when(destVolumeInfo).getDataStore(); + Mockito.doReturn(Storage.StoragePoolType.NetworkFilesystem).when(destVolumeInfo).getStoragePoolType(); + + Method method; + method = AncientDataMotionStrategy.class.getDeclaredMethod("canBypassSecondaryStorage", DataObject.class, DataObject.class); + method.setAccessible(true); + boolean canBypassSecondaryStorage = (boolean) method.invoke(strategy, srcVolumeInfo, destVolumeInfo); + Assert.assertTrue(canBypassSecondaryStorage); + } + + @Test + public void testCanBypassSecondaryStorageWithLocalAndClusterWideNFSPoolsInSameCluster() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { + VolumeObject srcVolumeInfo = Mockito.spy(new VolumeObject()); + DataStore srcDataStore = Mockito.mock(DataStore.class); + Mockito.doReturn(new HostScope(1L, 1L, 1L)).when(srcDataStore).getScope(); + Mockito.doReturn(srcDataStore).when(srcVolumeInfo).getDataStore(); + Mockito.doReturn(Storage.StoragePoolType.Filesystem).when(srcVolumeInfo).getStoragePoolType(); + + VolumeObject destVolumeInfo = Mockito.spy(new VolumeObject()); + DataStore destDataStore = Mockito.mock(DataStore.class); + Mockito.doReturn(new ClusterScope(1L, 1L, 1L)).when(destDataStore).getScope(); + Mockito.doReturn(destDataStore).when(destVolumeInfo).getDataStore(); + Mockito.doReturn(Storage.StoragePoolType.NetworkFilesystem).when(destVolumeInfo).getStoragePoolType(); + + Method method; + method = AncientDataMotionStrategy.class.getDeclaredMethod("canBypassSecondaryStorage", DataObject.class, DataObject.class); + method.setAccessible(true); + boolean canBypassSecondaryStorage = (boolean) method.invoke(strategy, srcVolumeInfo, destVolumeInfo); + Assert.assertTrue(canBypassSecondaryStorage); + + canBypassSecondaryStorage = (boolean) method.invoke(strategy, destVolumeInfo, srcVolumeInfo); + Assert.assertTrue(canBypassSecondaryStorage); + } + + @Test + public void testCanBypassSecondaryStorageWithLocalAndZoneWideNFSPoolsInSameZone() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { + VolumeObject srcVolumeInfo = Mockito.spy(new VolumeObject()); + DataStore srcDataStore = Mockito.mock(DataStore.class); + Mockito.doReturn(new HostScope(1L, 1L, 1L)).when(srcDataStore).getScope(); + Mockito.doReturn(srcDataStore).when(srcVolumeInfo).getDataStore(); + Mockito.doReturn(Storage.StoragePoolType.Filesystem).when(srcVolumeInfo).getStoragePoolType(); + + VolumeObject destVolumeInfo = Mockito.spy(new VolumeObject()); + DataStore destDataStore = Mockito.mock(DataStore.class); + Mockito.doReturn(new ZoneScope(1L)).when(destDataStore).getScope(); + Mockito.doReturn(destDataStore).when(destVolumeInfo).getDataStore(); + Mockito.doReturn(Storage.StoragePoolType.NetworkFilesystem).when(destVolumeInfo).getStoragePoolType(); + + Method method; + method = AncientDataMotionStrategy.class.getDeclaredMethod("canBypassSecondaryStorage", DataObject.class, DataObject.class); + method.setAccessible(true); + boolean canBypassSecondaryStorage = (boolean) method.invoke(strategy, srcVolumeInfo, destVolumeInfo); + Assert.assertTrue(canBypassSecondaryStorage); + + canBypassSecondaryStorage = (boolean) method.invoke(strategy, destVolumeInfo, srcVolumeInfo); + Assert.assertTrue(canBypassSecondaryStorage); + } + + @Test + public void testCanBypassSecondaryStorageWithClusterWideNFSAndZoneWideNFSPoolsInSameZone() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { + VolumeObject srcVolumeInfo = Mockito.spy(new VolumeObject()); + DataStore srcDataStore = Mockito.mock(DataStore.class); + Mockito.doReturn(new ClusterScope(5L, 2L, 1L)).when(srcDataStore).getScope(); + Mockito.doReturn(srcDataStore).when(srcVolumeInfo).getDataStore(); + Mockito.doReturn(Storage.StoragePoolType.NetworkFilesystem).when(srcVolumeInfo).getStoragePoolType(); + + VolumeObject destVolumeInfo = Mockito.spy(new VolumeObject()); + DataStore destDataStore = Mockito.mock(DataStore.class); + Mockito.doReturn(new ZoneScope(1L)).when(destDataStore).getScope(); + Mockito.doReturn(destDataStore).when(destVolumeInfo).getDataStore(); + Mockito.doReturn(Storage.StoragePoolType.NetworkFilesystem).when(destVolumeInfo).getStoragePoolType(); + + Method method; + method = AncientDataMotionStrategy.class.getDeclaredMethod("canBypassSecondaryStorage", DataObject.class, DataObject.class); + method.setAccessible(true); + boolean canBypassSecondaryStorage = (boolean) method.invoke(strategy, srcVolumeInfo, destVolumeInfo); + Assert.assertTrue(canBypassSecondaryStorage); + + canBypassSecondaryStorage = (boolean) method.invoke(strategy, destVolumeInfo, srcVolumeInfo); + Assert.assertTrue(canBypassSecondaryStorage); + } } diff --git a/engine/storage/image/pom.xml b/engine/storage/image/pom.xml index d286a0ec920..2cdef352e7b 100644 --- a/engine/storage/image/pom.xml +++ b/engine/storage/image/pom.xml @@ -24,7 +24,7 @@ org.apache.cloudstack cloud-engine - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT ../../pom.xml diff --git a/engine/storage/integration-test/pom.xml b/engine/storage/integration-test/pom.xml index 3ecd86f4f5d..13f0b45dd21 100644 --- a/engine/storage/integration-test/pom.xml +++ b/engine/storage/integration-test/pom.xml @@ -24,7 +24,7 @@ org.apache.cloudstack cloud-engine - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT ../../pom.xml diff --git a/engine/storage/integration-test/src/test/java/org/apache/cloudstack/storage/test/SnapshotTestWithFakeData.java b/engine/storage/integration-test/src/test/java/org/apache/cloudstack/storage/test/SnapshotTestWithFakeData.java index 152c279547c..9868ccdf29a 100644 --- a/engine/storage/integration-test/src/test/java/org/apache/cloudstack/storage/test/SnapshotTestWithFakeData.java +++ b/engine/storage/integration-test/src/test/java/org/apache/cloudstack/storage/test/SnapshotTestWithFakeData.java @@ -305,7 +305,7 @@ public class SnapshotTestWithFakeData { } protected SnapshotPolicyVO createSnapshotPolicy(Long volId) { - SnapshotPolicyVO policyVO = new SnapshotPolicyVO(volId, "jfkd", "fdfd", DateUtil.IntervalType.DAILY, 8, true); + SnapshotPolicyVO policyVO = new SnapshotPolicyVO(volId, "jfkd", "fdfd", DateUtil.IntervalType.DAILY, 8, 1, 1, true); policyVO = snapshotPolicyDao.persist(policyVO); return policyVO; } diff --git a/engine/storage/object/pom.xml b/engine/storage/object/pom.xml index 334383070f1..d5f2a793948 100644 --- a/engine/storage/object/pom.xml +++ b/engine/storage/object/pom.xml @@ -24,7 +24,7 @@ org.apache.cloudstack cloud-engine - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT ../../pom.xml diff --git a/engine/storage/pom.xml b/engine/storage/pom.xml index d8415d0842b..a2044c6f4f8 100644 --- a/engine/storage/pom.xml +++ b/engine/storage/pom.xml @@ -24,7 +24,7 @@ org.apache.cloudstack cloud-engine - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT ../pom.xml diff --git a/engine/storage/snapshot/pom.xml b/engine/storage/snapshot/pom.xml index 368b1d3c3a6..177ab1069d9 100644 --- a/engine/storage/snapshot/pom.xml +++ b/engine/storage/snapshot/pom.xml @@ -24,7 +24,7 @@ org.apache.cloudstack cloud-engine - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT ../../pom.xml diff --git a/engine/storage/snapshot/src/main/java/org/apache/cloudstack/storage/snapshot/SnapshotDataFactoryImpl.java b/engine/storage/snapshot/src/main/java/org/apache/cloudstack/storage/snapshot/SnapshotDataFactoryImpl.java index 4d8919ccc48..cd314b0be63 100644 --- a/engine/storage/snapshot/src/main/java/org/apache/cloudstack/storage/snapshot/SnapshotDataFactoryImpl.java +++ b/engine/storage/snapshot/src/main/java/org/apache/cloudstack/storage/snapshot/SnapshotDataFactoryImpl.java @@ -23,11 +23,16 @@ import java.util.List; import javax.inject.Inject; +import com.cloud.storage.Snapshot; +import com.cloud.storage.Volume; +import com.cloud.utils.fsm.NoTransitionException; import org.apache.cloudstack.engine.subsystem.api.storage.DataObject; import org.apache.cloudstack.engine.subsystem.api.storage.DataStore; import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager; +import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine; import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotDataFactory; import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotInfo; +import org.apache.cloudstack.engine.subsystem.api.storage.VolumeInfo; import org.apache.cloudstack.storage.datastore.db.SnapshotDataStoreDao; import org.apache.cloudstack.storage.datastore.db.SnapshotDataStoreVO; import org.apache.commons.collections.CollectionUtils; @@ -73,7 +78,7 @@ public class SnapshotDataFactoryImpl implements SnapshotDataFactory { for (SnapshotDataStoreVO snapshotDataStoreVO : allSnapshotsFromVolumeAndDataStore) { DataStore store = storeMgr.getDataStore(snapshotDataStoreVO.getDataStoreId(), role); SnapshotVO snapshot = snapshotDao.findById(snapshotDataStoreVO.getSnapshotId()); - if (snapshot == null){ //snapshot may have been removed; + if (snapshot == null) { //snapshot may have been removed; continue; } SnapshotObject info = SnapshotObject.getSnapshotObject(snapshot, store); @@ -107,8 +112,6 @@ public class SnapshotDataFactoryImpl implements SnapshotDataFactory { return infos; } - - @Override public SnapshotInfo getSnapshot(long snapshotId, long storeId, DataStoreRole role) { SnapshotVO snapshot = snapshotDao.findById(snapshotId); @@ -202,4 +205,17 @@ public class SnapshotDataFactoryImpl implements SnapshotDataFactory { return snapObjs; } + @Override + public void updateOperationFailed(long snapshotId) throws NoTransitionException { + List snapshotStoreRefs = snapshotStoreDao.findBySnapshotId(snapshotId); + for (SnapshotDataStoreVO snapshotStoreRef : snapshotStoreRefs) { + SnapshotInfo snapshotInfo = getSnapshot(snapshotStoreRef.getSnapshotId(), snapshotStoreRef.getDataStoreId(), snapshotStoreRef.getRole()); + if (snapshotInfo != null) { + VolumeInfo volumeInfo = snapshotInfo.getBaseVolume(); + volumeInfo.stateTransit(Volume.Event.OperationFailed); + ((SnapshotObject)snapshotInfo).processEvent(Snapshot.Event.OperationFailed); + snapshotInfo.processEvent(ObjectInDataStoreStateMachine.Event.OperationFailed); + } + } + } } diff --git a/engine/storage/snapshot/src/main/java/org/apache/cloudstack/storage/vmsnapshot/DefaultVMSnapshotStrategy.java b/engine/storage/snapshot/src/main/java/org/apache/cloudstack/storage/vmsnapshot/DefaultVMSnapshotStrategy.java index 2d9b1e67e09..6e933396871 100644 --- a/engine/storage/snapshot/src/main/java/org/apache/cloudstack/storage/vmsnapshot/DefaultVMSnapshotStrategy.java +++ b/engine/storage/snapshot/src/main/java/org/apache/cloudstack/storage/vmsnapshot/DefaultVMSnapshotStrategy.java @@ -345,6 +345,7 @@ public class DefaultVMSnapshotStrategy extends ManagerBase implements VMSnapshot StoragePool pool = primaryDataStoreDao.findPoolByUUID(volume.getDataStoreUuid()); if (pool != null && pool.getId() != volumeVO.getPoolId()) { volumeVO.setPoolId(pool.getId()); + volumeVO.setPoolType(pool.getPoolType()); } } if (StringUtils.isNotEmpty(volume.getPath())) { @@ -514,4 +515,14 @@ public class DefaultVMSnapshotStrategy extends ManagerBase implements VMSnapshot return false; } + + @Override + public void updateOperationFailed(VMSnapshot vmSnapshot) throws NoTransitionException { + try { + vmSnapshotHelper.vmSnapshotStateTransitTo(vmSnapshot, VMSnapshot.Event.OperationFailed); + } catch (NoTransitionException e) { + logger.debug("Failed to change vm snapshot state with event OperationFailed"); + throw e; + } + } } diff --git a/engine/storage/snapshot/src/main/java/org/apache/cloudstack/storage/vmsnapshot/ScaleIOVMSnapshotStrategy.java b/engine/storage/snapshot/src/main/java/org/apache/cloudstack/storage/vmsnapshot/ScaleIOVMSnapshotStrategy.java index 09280921039..c7c855dfbc0 100644 --- a/engine/storage/snapshot/src/main/java/org/apache/cloudstack/storage/vmsnapshot/ScaleIOVMSnapshotStrategy.java +++ b/engine/storage/snapshot/src/main/java/org/apache/cloudstack/storage/vmsnapshot/ScaleIOVMSnapshotStrategy.java @@ -488,6 +488,16 @@ public class ScaleIOVMSnapshotStrategy extends ManagerBase implements VMSnapshot return vmSnapshotDao.remove(vmSnapshot.getId()); } + @Override + public void updateOperationFailed(VMSnapshot vmSnapshot) throws NoTransitionException { + try { + vmSnapshotHelper.vmSnapshotStateTransitTo(vmSnapshot, VMSnapshot.Event.OperationFailed); + } catch (NoTransitionException e) { + logger.debug("Failed to change vm snapshot state with event OperationFailed"); + throw e; + } + } + private void publishUsageEvent(String type, VMSnapshot vmSnapshot, UserVm userVm, VolumeObjectTO volumeTo) { VolumeVO volume = volumeDao.findById(volumeTo.getId()); Long diskOfferingId = volume.getDiskOfferingId(); diff --git a/engine/storage/src/main/java/org/apache/cloudstack/storage/allocator/AbstractStoragePoolAllocator.java b/engine/storage/src/main/java/org/apache/cloudstack/storage/allocator/AbstractStoragePoolAllocator.java index 4b259760915..e0e244d53d3 100644 --- a/engine/storage/src/main/java/org/apache/cloudstack/storage/allocator/AbstractStoragePoolAllocator.java +++ b/engine/storage/src/main/java/org/apache/cloudstack/storage/allocator/AbstractStoragePoolAllocator.java @@ -378,7 +378,7 @@ public abstract class AbstractStoragePoolAllocator extends AdapterBase implement return false; } } catch (StorageUnavailableException e) { - logger.warn(String.format("Could not verify storage policy complaince against storage pool %s due to exception %s", pool.getUuid(), e.getMessage())); + logger.warn(String.format("Could not verify storage policy compliance against storage pool %s due to exception %s", pool.getUuid(), e.getMessage())); return false; } } diff --git a/engine/storage/src/main/java/org/apache/cloudstack/storage/endpoint/DefaultEndPointSelector.java b/engine/storage/src/main/java/org/apache/cloudstack/storage/endpoint/DefaultEndPointSelector.java index da6b1cfede3..061d18dc376 100644 --- a/engine/storage/src/main/java/org/apache/cloudstack/storage/endpoint/DefaultEndPointSelector.java +++ b/engine/storage/src/main/java/org/apache/cloudstack/storage/endpoint/DefaultEndPointSelector.java @@ -232,7 +232,13 @@ public class DefaultEndPointSelector implements EndPointSelector { // assumption, at least one of scope should be zone, find the least // scope - if (srcScope.getScopeType() != ScopeType.ZONE) { + if (srcScope.getScopeType() == ScopeType.HOST) { + selectedScope = srcScope; + poolId = srcStore.getId(); + } else if (destScope.getScopeType() == ScopeType.HOST) { + selectedScope = destScope; + poolId = destStore.getId(); + } else if (srcScope.getScopeType() != ScopeType.ZONE) { selectedScope = srcScope; poolId = srcStore.getId(); } else if (destScope.getScopeType() != ScopeType.ZONE) { diff --git a/engine/storage/src/main/java/org/apache/cloudstack/storage/volume/datastore/PrimaryDataStoreHelper.java b/engine/storage/src/main/java/org/apache/cloudstack/storage/volume/datastore/PrimaryDataStoreHelper.java index 5e9891ef989..d17dae132a0 100644 --- a/engine/storage/src/main/java/org/apache/cloudstack/storage/volume/datastore/PrimaryDataStoreHelper.java +++ b/engine/storage/src/main/java/org/apache/cloudstack/storage/volume/datastore/PrimaryDataStoreHelper.java @@ -85,8 +85,7 @@ public class PrimaryDataStoreHelper { DataStoreProviderManager dataStoreProviderMgr; public DataStore createPrimaryDataStore(PrimaryDataStoreParameters params) { - if(params == null) - { + if (params == null) { throw new InvalidParameterValueException("createPrimaryDataStore: Input params is null, please check"); } StoragePoolVO dataStoreVO = dataStoreDao.findPoolByUUID(params.getUuid()); @@ -190,7 +189,9 @@ public class PrimaryDataStoreHelper { pool.setScope(scope.getScopeType()); pool.setUsedBytes(existingInfo.getCapacityBytes() - existingInfo.getAvailableBytes()); pool.setCapacityBytes(existingInfo.getCapacityBytes()); - pool.setStatus(StoragePoolStatus.Up); + if (pool.getStatus() != StoragePoolStatus.Disabled) { + pool.setStatus(StoragePoolStatus.Up); + } this.dataStoreDao.update(pool.getId(), pool); this.storageMgr.createCapacityEntry(pool, Capacity.CAPACITY_TYPE_LOCAL_STORAGE, pool.getUsedBytes()); return dataStoreMgr.getDataStore(pool.getId(), DataStoreRole.Primary); diff --git a/engine/storage/volume/pom.xml b/engine/storage/volume/pom.xml index 3c9d3c246f2..5422218ef02 100644 --- a/engine/storage/volume/pom.xml +++ b/engine/storage/volume/pom.xml @@ -24,7 +24,7 @@ org.apache.cloudstack cloud-engine - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT ../../pom.xml diff --git a/engine/storage/volume/src/main/java/org/apache/cloudstack/storage/datastore/PrimaryDataStoreImpl.java b/engine/storage/volume/src/main/java/org/apache/cloudstack/storage/datastore/PrimaryDataStoreImpl.java index 6a10c26cc0b..d0184359c8b 100644 --- a/engine/storage/volume/src/main/java/org/apache/cloudstack/storage/datastore/PrimaryDataStoreImpl.java +++ b/engine/storage/volume/src/main/java/org/apache/cloudstack/storage/datastore/PrimaryDataStoreImpl.java @@ -334,6 +334,7 @@ public class PrimaryDataStoreImpl implements PrimaryDataStore { VolumeVO vol = volumeDao.findById(obj.getId()); if (vol != null) { vol.setPoolId(getId()); + vol.setPoolType(getPoolType()); volumeDao.update(vol.getId(), vol); } } diff --git a/engine/storage/volume/src/main/java/org/apache/cloudstack/storage/volume/VolumeDataFactoryImpl.java b/engine/storage/volume/src/main/java/org/apache/cloudstack/storage/volume/VolumeDataFactoryImpl.java index 53fa21f3a79..5c2a774f8a2 100644 --- a/engine/storage/volume/src/main/java/org/apache/cloudstack/storage/volume/VolumeDataFactoryImpl.java +++ b/engine/storage/volume/src/main/java/org/apache/cloudstack/storage/volume/VolumeDataFactoryImpl.java @@ -30,6 +30,8 @@ import org.apache.cloudstack.engine.subsystem.api.storage.DataStore; import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager; import org.apache.cloudstack.engine.subsystem.api.storage.VolumeDataFactory; import org.apache.cloudstack.engine.subsystem.api.storage.VolumeInfo; +import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao; +import org.apache.cloudstack.storage.datastore.db.StoragePoolVO; import org.apache.cloudstack.storage.datastore.db.VolumeDataStoreDao; import org.apache.cloudstack.storage.datastore.db.VolumeDataStoreVO; @@ -46,6 +48,8 @@ public class VolumeDataFactoryImpl implements VolumeDataFactory { DataStoreManager storeMgr; @Inject VMTemplateDao templateDao; + @Inject + PrimaryDataStoreDao storagePoolDao; @Override public VolumeInfo getVolume(long volumeId, DataStore store) { @@ -92,6 +96,10 @@ public class VolumeDataFactoryImpl implements VolumeDataFactory { vol = VolumeObject.getVolumeObject(store, volumeVO); } else { DataStore store = storeMgr.getDataStore(volumeVO.getPoolId(), DataStoreRole.Primary); + StoragePoolVO pool = storagePoolDao.findById(volumeVO.getPoolId()); + if (pool != null) { + volumeVO.setPoolType(pool.getPoolType()); + } vol = VolumeObject.getVolumeObject(store, volumeVO); } if (vol.getTemplateId() != null) { diff --git a/engine/userdata/cloud-init/pom.xml b/engine/userdata/cloud-init/pom.xml index 2a6b61e40c1..a49a8ece0ce 100644 --- a/engine/userdata/cloud-init/pom.xml +++ b/engine/userdata/cloud-init/pom.xml @@ -23,7 +23,7 @@ cloud-engine org.apache.cloudstack - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT ../../pom.xml diff --git a/engine/userdata/pom.xml b/engine/userdata/pom.xml index 48788ddf8a7..56c181ae060 100644 --- a/engine/userdata/pom.xml +++ b/engine/userdata/pom.xml @@ -24,7 +24,7 @@ org.apache.cloudstack cloud-engine - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT ../pom.xml diff --git a/engine/userdata/src/main/java/org/apache/cloudstack/userdata/UserDataManagerImpl.java b/engine/userdata/src/main/java/org/apache/cloudstack/userdata/UserDataManagerImpl.java index 664d308e28d..7c5692564c9 100644 --- a/engine/userdata/src/main/java/org/apache/cloudstack/userdata/UserDataManagerImpl.java +++ b/engine/userdata/src/main/java/org/apache/cloudstack/userdata/UserDataManagerImpl.java @@ -16,12 +16,18 @@ // under the License. package org.apache.cloudstack.userdata; +import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.HashMap; import java.util.List; import java.util.Map; +import com.cloud.domain.Domain; +import com.cloud.user.User; +import com.cloud.user.UserDataVO; +import com.cloud.user.dao.UserDataDao; +import com.cloud.utils.compression.CompressionUtil; import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.framework.config.ConfigKey; import org.apache.commons.codec.binary.Base64; @@ -31,7 +37,12 @@ import com.cloud.exception.InvalidParameterValueException; import com.cloud.utils.component.ManagerBase; import com.cloud.utils.exception.CloudRuntimeException; +import javax.inject.Inject; + public class UserDataManagerImpl extends ManagerBase implements UserDataManager { + @Inject + UserDataDao userDataDao; + private static final int MAX_USER_DATA_LENGTH_BYTES = 2048; private static final int MAX_HTTP_GET_LENGTH = 2 * MAX_USER_DATA_LENGTH_BYTES; // 4KB private static final int NUM_OF_2K_BLOCKS = 512; @@ -118,6 +129,25 @@ public class UserDataManagerImpl extends ManagerBase implements UserDataManager return Base64.encodeBase64String(decodedUserData); } + @Override + public String validateAndGetUserDataForSystemVM(String userDataUuid) throws IOException { + if (StringUtils.isBlank(userDataUuid)) { + return null; + } + UserDataVO userDataVo = userDataDao.findByUuid(userDataUuid); + if (userDataVo == null) { + return null; + } + if (userDataVo.getDomainId() == Domain.ROOT_DOMAIN && userDataVo.getAccountId() == User.UID_ADMIN) { + // Decode base64 user data, compress it, then re-encode to reduce command line length + String plainTextUserData = new String(java.util.Base64.getDecoder().decode(userDataVo.getUserData())); + CompressionUtil compressionUtil = new CompressionUtil(); + byte[] compressedUserData = compressionUtil.compressString(plainTextUserData); + return java.util.Base64.getEncoder().encodeToString(compressedUserData); + } + throw new CloudRuntimeException("User data can only be used by system VMs if it belongs to the ROOT domain and ADMIN account."); + } + private byte[] validateAndDecodeByHTTPMethod(String userData, int maxHTTPLength, BaseCmd.HTTPMethod httpMethod) { byte[] decodedUserData = Base64.decodeBase64(userData.getBytes()); if (decodedUserData == null || decodedUserData.length < 1) { diff --git a/engine/userdata/src/test/java/org/apache/cloudstack/userdata/UserDataManagerImplTest.java b/engine/userdata/src/test/java/org/apache/cloudstack/userdata/UserDataManagerImplTest.java index 67e7b38e37d..70a56bc0c61 100644 --- a/engine/userdata/src/test/java/org/apache/cloudstack/userdata/UserDataManagerImplTest.java +++ b/engine/userdata/src/test/java/org/apache/cloudstack/userdata/UserDataManagerImplTest.java @@ -17,19 +17,37 @@ package org.apache.cloudstack.userdata; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.mockito.Mockito.when; +import java.io.IOException; import java.nio.charset.StandardCharsets; +import java.util.Base64; import org.apache.cloudstack.api.BaseCmd; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; import org.mockito.Spy; import org.mockito.junit.MockitoJUnitRunner; +import com.cloud.domain.Domain; +import com.cloud.user.User; +import com.cloud.user.UserDataVO; +import com.cloud.user.dao.UserDataDao; +import com.cloud.utils.exception.CloudRuntimeException; + @RunWith(MockitoJUnitRunner.class) public class UserDataManagerImplTest { + @Mock + private UserDataDao userDataDao; + @Spy @InjectMocks private UserDataManagerImpl userDataManager; @@ -56,4 +74,76 @@ public class UserDataManagerImplTest { assertEquals("validate return the value with padding", encodedUserdata, userDataManager.validateUserData(urlEncodedUserdata, BaseCmd.HTTPMethod.GET)); } + @Test + public void testValidateAndGetUserDataForSystemVMWithBlankUuid() throws IOException { + // Test with blank UUID should return null + assertNull("null UUID should return null", userDataManager.validateAndGetUserDataForSystemVM(null)); + assertNull("blank UUID should return null", userDataManager.validateAndGetUserDataForSystemVM("")); + assertNull("blank UUID should return null", userDataManager.validateAndGetUserDataForSystemVM(" ")); + } + + @Test + public void testValidateAndGetUserDataForSystemVMNotFound() throws IOException { + // Test when userDataVo is not found + String testUuid = "test-uuid-123"; + when(userDataDao.findByUuid(testUuid)).thenReturn(null); + + assertNull("userdata not found should return null", userDataManager.validateAndGetUserDataForSystemVM(testUuid)); + } + + @Test(expected = CloudRuntimeException.class) + public void testValidateAndGetUserDataForSystemVMInvalidDomain() throws IOException { + // Test with userDataVo that doesn't belong to ROOT domain + String testUuid = "test-uuid-123"; + UserDataVO userDataVo = Mockito.mock(UserDataVO.class); + when(userDataVo.getDomainId()).thenReturn(2L); // Not ROOT domain + + when(userDataDao.findByUuid(testUuid)).thenReturn(userDataVo); + userDataManager.validateAndGetUserDataForSystemVM(testUuid); + } + + @Test(expected = CloudRuntimeException.class) + public void testValidateAndGetUserDataForSystemVMInvalidAccount() throws IOException { + // Test with userDataVo that doesn't belong to ADMIN account + String testUuid = "test-uuid-123"; + UserDataVO userDataVo = Mockito.mock(UserDataVO.class); + when(userDataVo.getDomainId()).thenReturn(Domain.ROOT_DOMAIN); + when(userDataVo.getAccountId()).thenReturn(3L); + userDataVo.setUserData("dGVzdCBkYXRh"); // "test data" in base64 + + when(userDataDao.findByUuid(testUuid)).thenReturn(userDataVo); + userDataManager.validateAndGetUserDataForSystemVM(testUuid); + } + + @Test + public void testValidateAndGetUserDataForSystemVMValidSystemVMUserData() throws IOException { + // Test with valid system VM userdata (ROOT domain + ADMIN account) + String testUuid = "test-uuid-123"; + String originalText = "#!/bin/bash\necho 'Hello World'"; + String base64EncodedUserData = Base64.getEncoder().encodeToString(originalText.getBytes()); + + UserDataVO userDataVo = Mockito.mock(UserDataVO.class); + when(userDataVo.getDomainId()).thenReturn(Domain.ROOT_DOMAIN); + when(userDataVo.getAccountId()).thenReturn(User.UID_ADMIN); + when(userDataVo.getUserData()).thenReturn(base64EncodedUserData); + + when(userDataDao.findByUuid(testUuid)).thenReturn(userDataVo); + + String result = userDataManager.validateAndGetUserDataForSystemVM(testUuid); + + // Verify result is not null and is base64 encoded + assertNotNull("result should not be null", result); + assertFalse("result should be base64 encoded", result.isEmpty()); + + // Verify the result is valid base64 + try { + Base64.getDecoder().decode(result); + } catch (IllegalArgumentException e) { + throw new AssertionError("Result should be valid base64", e); + } + + // The result should be different from input since it's compressed + assertNotEquals("compressed result should be different from original", result, base64EncodedUserData); + } + } diff --git a/extensions/HyperV/hyperv.py b/extensions/HyperV/hyperv.py index 8ae2c7ff797..c9b1d4da77e 100755 --- a/extensions/HyperV/hyperv.py +++ b/extensions/HyperV/hyperv.py @@ -25,7 +25,7 @@ import winrm def fail(message): - print(json.dumps({"error": message})) + print(json.dumps({"status": "error", "error": message})) sys.exit(1) @@ -220,6 +220,9 @@ class HyperVManager: fail(str(e)) succeed({"status": "success", "message": "Instance deleted"}) + def get_console(self): + fail("Operation not supported") + def suspend(self): self.run_ps(f'Suspend-VM -Name "{self.data["vmname"]}"') succeed({"status": "success", "message": "Instance suspended"}) @@ -283,6 +286,7 @@ def main(): "reboot": manager.reboot, "delete": manager.delete, "status": manager.status, + "getconsole": manager.get_console, "suspend": manager.suspend, "resume": manager.resume, "listsnapshots": manager.list_snapshots, diff --git a/extensions/MaaS/maas.py b/extensions/MaaS/maas.py new file mode 100755 index 00000000000..3d97cedb02f --- /dev/null +++ b/extensions/MaaS/maas.py @@ -0,0 +1,263 @@ +#!/usr/bin/env python3 +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +import sys +import json +import time +from requests_oauthlib import OAuth1Session + + +def fail(message): + print(json.dumps({"error": message})) + sys.exit(1) + + +def succeed(data): + print(json.dumps(data)) + sys.exit(0) + + +class MaasManager: + def __init__(self, config_path): + self.config_path = config_path + self.data = self.parse_json() + self.session = self.init_session() + + def parse_json(self): + try: + with open(self.config_path, "r") as f: + json_data = json.load(f) + + extension = json_data.get("externaldetails", {}).get("extension", {}) + host = json_data.get("externaldetails", {}).get("host", {}) + vm = json_data.get("externaldetails", {}).get("virtualmachine", {}) + + endpoint = host.get("endpoint") or extension.get("endpoint") + apikey = host.get("apikey") or extension.get("apikey") + + details = json_data.get("cloudstack.vm.details", {}).get("details", {}) + + os_name = details.get("os") or vm.get("os") + architecture = details.get("architecture") or vm.get("architecture") + distro_series = details.get("distro_series") or vm.get("distro_series") + + if not endpoint or not apikey: + fail("Missing MAAS endpoint or apikey") + + if not endpoint.startswith("http://") and not endpoint.startswith("https://"): + endpoint = "http://" + endpoint + endpoint = endpoint.rstrip("/") + + parts = apikey.split(":") + if len(parts) != 3: + fail("Invalid apikey format. Expected consumer:token:secret") + + consumer, token, secret = parts + + system_id = details.get("maas_system_id") or vm.get("maas_system_id", "") + + vm_name = vm.get("vm_name") or json_data.get("cloudstack.vm.details", {}).get("name") + if not vm_name: + vm_name = f"cs-{system_id}" if system_id else "cs-unknown" + + return { + "endpoint": endpoint, + "consumer": consumer, + "token": token, + "secret": secret, + "distro_series": distro_series or "ubuntu/focal", + "os": os_name, + "architecture": architecture, + "system_id": system_id, + "vm_name": vm_name, + } + except Exception as e: + fail(f"Error parsing JSON: {str(e)}") + + def init_session(self): + return OAuth1Session( + self.data["consumer"], + resource_owner_key=self.data["token"], + resource_owner_secret=self.data["secret"], + ) + + def call_maas(self, method, path, data=None, ignore_404=False): + if not path.startswith("/"): + path = "/" + path + url = f"{self.data['endpoint']}:5240/MAAS/api/2.0{path}" + resp = self.session.request(method, url, data=data) + + if resp.status_code == 404 and ignore_404: + return None + + if not resp.ok: + fail(f"MAAS API error: {resp.status_code} {resp.text}") + + try: + return resp.json() if resp.text else {} + except ValueError: + return {} + + def prepare(self): + machines = self.call_maas("GET", "/machines/") + ready = [m for m in machines if m.get("status_name") == "Ready"] + if not ready: + fail("No Ready machines available") + + sysid = self.data.get("system_id") + + if sysid: + match = next((m for m in ready if m["system_id"] == sysid), None) + if not match: + fail(f"Provided system_id '{sysid}' not found among Ready machines") + system = match + else: + system = ready[0] + + system_id = system["system_id"] + mac = system.get("interface_set", [{}])[0].get("mac_address") + hostname = system.get("hostname", "") + + if not mac: + fail("No MAC address found") + + # Load original JSON so we can update nics + with open(self.config_path, "r") as f: + json_data = json.load(f) + + if json_data.get("cloudstack.vm.details", {}).get("nics"): + json_data["cloudstack.vm.details"]["nics"][0]["mac"] = mac + + console_url = f"http://{self.data['endpoint'].replace('http://','').replace('https://','')}:5240/MAAS/r/machine/{system_id}/summary" + + result = { + "nics": json_data["cloudstack.vm.details"]["nics"], + "details": { + "External:mac_address": mac, + "External:maas_system_id": system_id, + "External:hostname": hostname, + "External:console_url": console_url, + }, + } + succeed(result) + + def create(self): + sysid = self.data.get("system_id") + if not sysid: + fail("system_id missing for create") + + ds = self.data.get("distro_series", None) + os_name = self.data.get("os") + arch = self.data.get("architecture") + + deploy_payload = {"op": "deploy"} + + if os_name or arch: + if os_name: + deploy_payload["os"] = os_name + if arch: + deploy_payload["architecture"] = arch + if ds: + deploy_payload["distro_series"] = ds + else: + deploy_payload["distro_series"] = ds or "ubuntu/focal" + + deploy_payload["net-setup-method"] = "curtin" + + self.call_maas("POST", f"/machines/{sysid}/", deploy_payload) + + succeed({"status": "success", "message": "Instance created", "requested": deploy_payload}) + + def delete(self): + sysid = self.data.get("system_id") + if not sysid: + fail("system_id missing for delete") + + self.call_maas("POST", f"/machines/{sysid}/", {"op": "release"}, ignore_404=True) + succeed({"status": "success", "message": f"Instance deleted or not found ({sysid})"}) + + def start(self): + sysid = self.data.get("system_id") + if not sysid: + fail("system_id missing for start") + self.call_maas("POST", f"/machines/{sysid}/", {"op": "power_on"}) + succeed({"status": "success", "power_state": "PowerOn"}) + + def stop(self): + sysid = self.data.get("system_id") + if not sysid: + fail("system_id missing for stop") + self.call_maas("POST", f"/machines/{sysid}/", {"op": "power_off"}) + succeed({"status": "success", "power_state": "PowerOff"}) + + def reboot(self): + sysid = self.data.get("system_id") + if not sysid: + fail("system_id missing for reboot") + + self.call_maas("POST", f"/machines/{sysid}/", {"op": "power_off"}) + time.sleep(5) + self.call_maas("POST", f"/machines/{sysid}/", {"op": "power_on"}) + + succeed({"status": "success", "power_state": "PowerOn", "message": "Reboot completed"}) + + def status(self): + sysid = self.data.get("system_id") + if not sysid: + fail("system_id missing for status") + resp = self.call_maas("GET", f"/machines/{sysid}/") + state = resp.get("power_state", "") + if state == "on": + mapped = "PowerOn" + elif state == "off": + mapped = "PowerOff" + else: + mapped = "PowerUnknown" + succeed({"status": "success", "power_state": mapped}) + + +def main(): + if len(sys.argv) < 3: + fail("Usage: maas.py ") + + action = sys.argv[1].lower() + json_file = sys.argv[2] + + try: + manager = MaasManager(json_file) + except FileNotFoundError: + fail(f"JSON file not found: {json_file}") + + actions = { + "prepare": manager.prepare, + "create": manager.create, + "delete": manager.delete, + "start": manager.start, + "stop": manager.stop, + "reboot": manager.reboot, + "status": manager.status, + } + + if action not in actions: + fail("Invalid action") + + actions[action]() + + +if __name__ == "__main__": + main() diff --git a/extensions/Proxmox/proxmox.sh b/extensions/Proxmox/proxmox.sh index 7f363a6b9a0..23f30311e2b 100755 --- a/extensions/Proxmox/proxmox.sh +++ b/extensions/Proxmox/proxmox.sh @@ -18,7 +18,7 @@ parse_json() { local json_string="$1" - echo "$json_string" | jq '.' > /dev/null || { echo '{"error":"Invalid JSON input"}'; exit 1; } + echo "$json_string" | jq '.' > /dev/null || { echo '{"status": "error", "error": "Invalid JSON input"}'; exit 1; } local -A details while IFS="=" read -r key value; do @@ -112,9 +112,14 @@ call_proxmox_api() { curl_opts+=(-d "$data") fi - #echo curl "${curl_opts[@]}" "https://${url}:8006/api2/json${path}" >&2 response=$(curl "${curl_opts[@]}" "https://${url}:8006/api2/json${path}") + local status=$? + if [[ $status -ne 0 ]]; then + echo "{\"errors\":{\"curl\":\"API call failed with status $status: $(echo "$response" | jq -Rsa . | jq -r .)\"}}" + return $status + fi echo "$response" + return 0 } wait_for_proxmox_task() { @@ -129,7 +134,7 @@ wait_for_proxmox_task() { local now now=$(date +%s) if (( now - start_time > timeout )); then - echo '{"error":"Timeout while waiting for async task"}' + echo '{"status": "error", "error":"Timeout while waiting for async task"}' exit 1 fi @@ -139,7 +144,7 @@ wait_for_proxmox_task() { if [[ -z "$status_response" || "$status_response" == *'"errors":'* ]]; then local msg msg=$(echo "$status_response" | jq -r '.message // "Unknown error"') - echo "{\"error\":\"$msg\"}" + echo "{\"status\": \"error\", \"error\": \"$msg\"}" exit 1 fi @@ -285,6 +290,86 @@ status() { echo "{\"status\": \"success\", \"power_state\": \"$powerstate\"}" } +get_node_host() { + check_required_fields node + local net_json host + + if ! net_json="$(call_proxmox_api GET "/nodes/${node}/network")"; then + echo "" + return 1 + fi + + # Prefer a static non-bridge IP + host="$(echo "$net_json" | jq -r ' + .data + | map(select( + (.type // "") != "bridge" and + (.type // "") != "bond" and + (.method // "") == "static" and + ((.address // .cidr // "") != "") + )) + | map(.address // (.cidr | split("/")[0])) + | .[0] // empty + ' 2>/dev/null)" + + # Fallback: first interface with a CIDR + if [[ -z "$host" ]]; then + host="$(echo "$net_json" | jq -r ' + .data + | map(select((.cidr // "") != "")) + | map(.cidr | split("/")[0]) + | .[0] // empty + ' 2>/dev/null)" + fi + + echo "$host" +} + + get_console() { + check_required_fields node vmid + + local api_resp port ticket + if ! api_resp="$(call_proxmox_api POST "/nodes/${node}/qemu/${vmid}/vncproxy")"; then + echo "$api_resp" | jq -c '{status:"error", error:(.errors.curl // (.errors|tostring))}' + exit 1 + fi + + port="$(echo "$api_resp" | jq -re '.data.port // empty' 2>/dev/null || true)" + ticket="$(echo "$api_resp" | jq -re '.data.ticket // empty' 2>/dev/null || true)" + + if [[ -z "$port" || -z "$ticket" ]]; then + jq -n --arg raw "$api_resp" \ + '{status:"error", error:"Proxmox response missing port/ticket", upstream:$raw}' + exit 1 + fi + + # Derive host from node’s network info + local host + host="$(get_node_host)" + if [[ -z "$host" ]]; then + jq -n --arg msg "Could not determine host IP for node $node" \ + '{status:"error", error:$msg}' + exit 1 + fi + + jq -n \ + --arg host "$host" \ + --arg port "$port" \ + --arg password "$ticket" \ + --argjson passwordonetimeuseonly true \ + '{ + status: "success", + message: "Console retrieved", + console: { + host: $host, + port: $port, + password: $password, + passwordonetimeuseonly: $passwordonetimeuseonly, + protocol: "vnc" + } + }' + } + list_snapshots() { snapshot_response=$(call_proxmox_api GET "/nodes/${node}/qemu/${vmid}/snapshot") echo "$snapshot_response" | jq ' @@ -356,7 +441,12 @@ parameters_file="$2" wait_time=$3 if [[ -z "$action" || -z "$parameters_file" ]]; then - echo '{"error":"Missing required arguments"}' + echo '{"status": "error", "error": "Missing required arguments"}' + exit 1 +fi + +if [[ ! -r "$parameters_file" ]]; then + echo '{"status": "error", "error": "File not found or unreadable"}' exit 1 fi @@ -396,6 +486,9 @@ case $action in status) status ;; + getconsole) + get_console + ;; ListSnapshots) list_snapshots ;; @@ -409,7 +502,7 @@ case $action in delete_snapshot ;; *) - echo '{"error":"Invalid action"}' + echo '{"status": "error", "error": "Invalid action"}' exit 1 ;; esac diff --git a/framework/agent-lb/pom.xml b/framework/agent-lb/pom.xml index fb57d0b8135..b9d728f9bdc 100644 --- a/framework/agent-lb/pom.xml +++ b/framework/agent-lb/pom.xml @@ -24,7 +24,7 @@ cloudstack-framework org.apache.cloudstack - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT ../pom.xml diff --git a/framework/ca/pom.xml b/framework/ca/pom.xml index 118abcfda12..b090dbe40df 100644 --- a/framework/ca/pom.xml +++ b/framework/ca/pom.xml @@ -24,7 +24,7 @@ org.apache.cloudstack cloudstack-framework - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT ../pom.xml diff --git a/framework/cluster/pom.xml b/framework/cluster/pom.xml index 806236c5a4e..2dd28e8e628 100644 --- a/framework/cluster/pom.xml +++ b/framework/cluster/pom.xml @@ -24,7 +24,7 @@ org.apache.cloudstack cloudstack-framework - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT ../pom.xml diff --git a/framework/config/pom.xml b/framework/config/pom.xml index a289095431b..dea2f14420e 100644 --- a/framework/config/pom.xml +++ b/framework/config/pom.xml @@ -24,7 +24,7 @@ org.apache.cloudstack cloudstack-framework - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT ../pom.xml diff --git a/framework/config/src/main/java/org/apache/cloudstack/framework/config/ConfigKey.java b/framework/config/src/main/java/org/apache/cloudstack/framework/config/ConfigKey.java index 26151ab5b58..0ea910fcb6d 100644 --- a/framework/config/src/main/java/org/apache/cloudstack/framework/config/ConfigKey.java +++ b/framework/config/src/main/java/org/apache/cloudstack/framework/config/ConfigKey.java @@ -43,6 +43,64 @@ public class ConfigKey { public static final String CATEGORY_NETWORK = "Network"; public static final String CATEGORY_SYSTEM = "System"; + // Configuration Groups to be used to define group for a config key + // Group name, description, precedence + public static final Ternary GROUP_MISCELLANEOUS = new Ternary<>("Miscellaneous", "Miscellaneous configuration", 999L); + public static final Ternary GROUP_ACCESS = new Ternary<>("Access", "Identity and Access management configuration", 1L); + public static final Ternary GROUP_COMPUTE = new Ternary<>("Compute", "Compute configuration", 2L); + public static final Ternary GROUP_STORAGE = new Ternary<>("Storage", "Storage configuration", 3L); + public static final Ternary GROUP_NETWORK = new Ternary<>("Network", "Network configuration", 4L); + public static final Ternary GROUP_HYPERVISOR = new Ternary<>("Hypervisor", "Hypervisor specific configuration", 5L); + public static final Ternary GROUP_MANAGEMENT_SERVER = new Ternary<>("Management Server", "Management Server configuration", 6L); + public static final Ternary GROUP_SYSTEM_VMS = new Ternary<>("System VMs", "System VMs related configuration", 7L); + public static final Ternary GROUP_INFRASTRUCTURE = new Ternary<>("Infrastructure", "Infrastructure configuration", 8L); + public static final Ternary GROUP_USAGE_SERVER = new Ternary<>("Usage Server", "Usage Server related configuration", 9L); + + // Configuration Subgroups to be used to define subgroup for a config key + // Subgroup name, description, precedence + public static final Pair SUBGROUP_OTHERS = new Pair<>("Others", 999L); + public static final Pair SUBGROUP_ACCOUNT = new Pair<>("Account", 1L); + public static final Pair SUBGROUP_DOMAIN = new Pair<>("Domain", 2L); + public static final Pair SUBGROUP_PROJECT = new Pair<>("Project", 3L); + public static final Pair SUBGROUP_LDAP = new Pair<>("LDAP", 4L); + public static final Pair SUBGROUP_SAML = new Pair<>("SAML", 5L); + public static final Pair SUBGROUP_VIRTUAL_MACHINE = new Pair<>("Virtual Machine", 1L); + public static final Pair SUBGROUP_KUBERNETES = new Pair<>("Kubernetes", 2L); + public static final Pair SUBGROUP_HIGH_AVAILABILITY = new Pair<>("High Availability", 3L); + public static final Pair SUBGROUP_IMAGES = new Pair<>("Images", 1L); + public static final Pair SUBGROUP_VOLUME = new Pair<>("Volume", 2L); + public static final Pair SUBGROUP_SNAPSHOT = new Pair<>("Snapshot", 3L); + public static final Pair SUBGROUP_VM_SNAPSHOT = new Pair<>("VM Snapshot", 4L); + public static final Pair SUBGROUP_NETWORK = new Pair<>("Network", 1L); + public static final Pair SUBGROUP_DHCP = new Pair<>("DHCP", 2L); + public static final Pair SUBGROUP_VPC = new Pair<>("VPC", 3L); + public static final Pair SUBGROUP_LOADBALANCER = new Pair<>("LoadBalancer", 4L); + public static final Pair SUBGROUP_API = new Pair<>("API", 1L); + public static final Pair SUBGROUP_ALERTS = new Pair<>("Alerts", 2L); + public static final Pair SUBGROUP_EVENTS = new Pair<>("Events", 3L); + public static final Pair SUBGROUP_SECURITY = new Pair<>("Security", 4L); + public static final Pair SUBGROUP_USAGE = new Pair<>("Usage", 1L); + public static final Pair SUBGROUP_LIMITS = new Pair<>("Limits", 6L); + public static final Pair SUBGROUP_JOBS = new Pair<>("Jobs", 7L); + public static final Pair SUBGROUP_AGENT = new Pair<>("Agent", 8L); + public static final Pair SUBGROUP_HYPERVISOR = new Pair<>("Hypervisor", 1L); + public static final Pair SUBGROUP_KVM = new Pair<>("KVM", 2L); + public static final Pair SUBGROUP_VMWARE = new Pair<>("VMware", 3L); + public static final Pair SUBGROUP_XENSERVER = new Pair<>("XenServer", 4L); + public static final Pair SUBGROUP_OVM = new Pair<>("OVM", 5L); + public static final Pair SUBGROUP_BAREMETAL = new Pair<>("Baremetal", 6L); + public static final Pair SUBGROUP_CONSOLE_PROXY_VM = new Pair<>("ConsoleProxyVM", 1L); + public static final Pair SUBGROUP_SEC_STORAGE_VM = new Pair<>("SecStorageVM", 2L); + public static final Pair SUBGROUP_VIRTUAL_ROUTER = new Pair<>("VirtualRouter", 3L); + public static final Pair SUBGROUP_DIAGNOSTICS = new Pair<>("Diagnostics", 4L); + public static final Pair SUBGROUP_PRIMARY_STORAGE = new Pair<>("Primary Storage", 1L); + public static final Pair SUBGROUP_SECONDARY_STORAGE = new Pair<>("Secondary Storage", 2L); + public static final Pair SUBGROUP_BACKUP_AND_RECOVERY = new Pair<>("Backup & Recovery", 1L); + public static final Pair SUBGROUP_CERTIFICATE_AUTHORITY = new Pair<>("Certificate Authority", 2L); + public static final Pair SUBGROUP_QUOTA = new Pair<>("Quota", 3L); + public static final Pair SUBGROUP_CLOUDIAN = new Pair<>("Cloudian", 4L); + public static final Pair SUBGROUP_DRS = new Pair<>("DRS", 4L); + public enum Scope { Global(null, 1), Zone(Global, 1 << 1), @@ -378,23 +436,21 @@ public class ConfigKey { if (type.isAssignableFrom(Boolean.class)) { return (T)Boolean.valueOf(value); } else if (type.isAssignableFrom(Integer.class)) { - return (T)new Integer(Integer.parseInt(value) * multiplier.intValue()); + return (T)Integer.valueOf(Integer.parseInt(value) * multiplier.intValue()); } else if (type.isAssignableFrom(Long.class)) { - return (T)new Long(Long.parseLong(value) * multiplier.longValue()); + return (T)Long.valueOf(Long.parseLong(value) * multiplier.longValue()); } else if (type.isAssignableFrom(Short.class)) { - return (T)new Short(Short.parseShort(value)); + return (T)Short.valueOf(Short.parseShort(value)); } else if (type.isAssignableFrom(String.class)) { return (T)value; } else if (type.isAssignableFrom(Float.class)) { - return (T)new Float(Float.parseFloat(value) * multiplier.floatValue()); + return (T)Float.valueOf(Float.parseFloat(value) * multiplier.floatValue()); } else if (type.isAssignableFrom(Double.class)) { - return (T)new Double(Double.parseDouble(value) * multiplier.doubleValue()); - } else if (type.isAssignableFrom(String.class)) { - return (T)value; + return (T)Double.valueOf(Double.parseDouble(value) * multiplier.doubleValue()); } else if (type.isAssignableFrom(Date.class)) { return (T)Date.valueOf(value); } else if (type.isAssignableFrom(Character.class)) { - return (T)new Character(value.charAt(0)); + return (T)Character.valueOf(value.charAt(0)); } else { throw new CloudRuntimeException("Unsupported data type for config values: " + type); } diff --git a/framework/db/pom.xml b/framework/db/pom.xml index dbc22be18ee..04d0fcc7e89 100644 --- a/framework/db/pom.xml +++ b/framework/db/pom.xml @@ -24,7 +24,7 @@ org.apache.cloudstack cloudstack-framework - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT ../pom.xml diff --git a/framework/direct-download/pom.xml b/framework/direct-download/pom.xml index 42e4caa9e06..22e878178ae 100644 --- a/framework/direct-download/pom.xml +++ b/framework/direct-download/pom.xml @@ -32,7 +32,7 @@ cloudstack-framework org.apache.cloudstack - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT ../pom.xml diff --git a/framework/events/pom.xml b/framework/events/pom.xml index a63af7087c6..3a0d3746868 100644 --- a/framework/events/pom.xml +++ b/framework/events/pom.xml @@ -24,7 +24,7 @@ org.apache.cloudstack cloudstack-framework - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT ../pom.xml diff --git a/framework/extensions/pom.xml b/framework/extensions/pom.xml index 66a6b5edac9..4d42d6840dd 100644 --- a/framework/extensions/pom.xml +++ b/framework/extensions/pom.xml @@ -24,7 +24,7 @@ org.apache.cloudstack cloudstack-framework - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT ../pom.xml @@ -41,13 +41,13 @@ org.apache.cloudstack cloud-engine-schema - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT compile org.apache.cloudstack cloud-engine-components-api - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT compile diff --git a/framework/extensions/src/main/java/org/apache/cloudstack/framework/extensions/api/DeleteExtensionCmd.java b/framework/extensions/src/main/java/org/apache/cloudstack/framework/extensions/api/DeleteExtensionCmd.java index cdae48fdb3a..bef68c2d277 100644 --- a/framework/extensions/src/main/java/org/apache/cloudstack/framework/extensions/api/DeleteExtensionCmd.java +++ b/framework/extensions/src/main/java/org/apache/cloudstack/framework/extensions/api/DeleteExtensionCmd.java @@ -56,7 +56,8 @@ public class DeleteExtensionCmd extends BaseCmd { private Long id; @Parameter(name = ApiConstants.CLEANUP, type = CommandType.BOOLEAN, - entityType = ExtensionResponse.class, description = "Whether cleanup entry-point files for the extension") + entityType = ExtensionResponse.class, + description = "Whether to cleanup files for the extension. If true, the extension files will be deleted from all the management servers.") private Boolean cleanup; ///////////////////////////////////////////////////// diff --git a/framework/extensions/src/main/java/org/apache/cloudstack/framework/extensions/api/UpdateExtensionCmd.java b/framework/extensions/src/main/java/org/apache/cloudstack/framework/extensions/api/UpdateExtensionCmd.java index 713e7550a1e..ded07d2dd32 100644 --- a/framework/extensions/src/main/java/org/apache/cloudstack/framework/extensions/api/UpdateExtensionCmd.java +++ b/framework/extensions/src/main/java/org/apache/cloudstack/framework/extensions/api/UpdateExtensionCmd.java @@ -74,7 +74,7 @@ public class UpdateExtensionCmd extends BaseCmd { @Parameter(name = ApiConstants.CLEAN_UP_DETAILS, type = CommandType.BOOLEAN, description = "Optional boolean field, which indicates if details should be cleaned up or not " + - "(If set to true, details removed for this action, details field ignored; " + + "(If set to true, details removed for this extension, details field ignored; " + "if false or not set, no action)") private Boolean cleanupDetails; diff --git a/framework/extensions/src/main/java/org/apache/cloudstack/framework/extensions/manager/ExtensionsManager.java b/framework/extensions/src/main/java/org/apache/cloudstack/framework/extensions/manager/ExtensionsManager.java index 82174872e87..1b1a175c597 100644 --- a/framework/extensions/src/main/java/org/apache/cloudstack/framework/extensions/manager/ExtensionsManager.java +++ b/framework/extensions/src/main/java/org/apache/cloudstack/framework/extensions/manager/ExtensionsManager.java @@ -44,10 +44,12 @@ import org.apache.cloudstack.framework.extensions.api.UpdateCustomActionCmd; import org.apache.cloudstack.framework.extensions.api.UpdateExtensionCmd; import org.apache.cloudstack.framework.extensions.command.ExtensionServerActionBaseCommand; +import com.cloud.agent.api.Answer; import com.cloud.host.Host; import com.cloud.org.Cluster; import com.cloud.utils.Pair; import com.cloud.utils.component.Manager; +import com.cloud.vm.VirtualMachine; public interface ExtensionsManager extends Manager { @@ -93,4 +95,6 @@ public interface ExtensionsManager extends Manager { final ExtensionResourceMap.ResourceType resourceType, final Map details); void updateExtensionResourceMapDetails(final long extensionResourceMapId, final Map details); + + Answer getInstanceConsole(VirtualMachine vm, Host host); } diff --git a/framework/extensions/src/main/java/org/apache/cloudstack/framework/extensions/manager/ExtensionsManagerImpl.java b/framework/extensions/src/main/java/org/apache/cloudstack/framework/extensions/manager/ExtensionsManagerImpl.java index 5abf0f424a7..4171b9615fe 100644 --- a/framework/extensions/src/main/java/org/apache/cloudstack/framework/extensions/manager/ExtensionsManagerImpl.java +++ b/framework/extensions/src/main/java/org/apache/cloudstack/framework/extensions/manager/ExtensionsManagerImpl.java @@ -104,8 +104,10 @@ import org.apache.commons.lang3.StringUtils; import com.cloud.agent.AgentManager; import com.cloud.agent.api.Answer; import com.cloud.agent.api.Command; +import com.cloud.agent.api.GetExternalConsoleCommand; import com.cloud.agent.api.RunCustomActionAnswer; import com.cloud.agent.api.RunCustomActionCommand; +import com.cloud.agent.api.to.VirtualMachineTO; import com.cloud.alert.AlertManager; import com.cloud.cluster.ClusterManager; import com.cloud.cluster.ManagementServerHostVO; @@ -127,6 +129,7 @@ import com.cloud.org.Cluster; import com.cloud.serializer.GsonHelper; import com.cloud.storage.dao.VMTemplateDao; import com.cloud.user.Account; +import com.cloud.user.AccountService; import com.cloud.utils.Pair; import com.cloud.utils.component.ManagerBase; import com.cloud.utils.component.PluggableService; @@ -141,6 +144,8 @@ import com.cloud.utils.db.TransactionCallbackWithException; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.vm.VirtualMachine; import com.cloud.vm.VirtualMachineManager; +import com.cloud.vm.VirtualMachineProfile; +import com.cloud.vm.VirtualMachineProfileImpl; import com.cloud.vm.VmDetailConstants; import com.cloud.vm.dao.VMInstanceDao; @@ -148,7 +153,7 @@ public class ExtensionsManagerImpl extends ManagerBase implements ExtensionsMana ConfigKey PathStateCheckInterval = new ConfigKey<>("Advanced", Integer.class, "extension.path.state.check.interval", "300", - "Interval (in seconds) for checking entry-point state of extensions", + "Interval (in seconds) for checking state of extensions path", false, ConfigKey.Scope.Global); @Inject @@ -208,6 +213,9 @@ public class ExtensionsManagerImpl extends ManagerBase implements ExtensionsMana @Inject RoleService roleService; + @Inject + AccountService accountService; + private ScheduledExecutorService extensionPathStateCheckExecutor; protected String getDefaultExtensionRelativePath(String name) { @@ -260,11 +268,11 @@ public class ExtensionsManagerImpl extends ManagerBase implements ExtensionsMana protected boolean prepareExtensionPathOnMSPeer(Extension extension, ManagementServerHostVO msHost) { final String msPeer = Long.toString(msHost.getMsid()); - logger.debug("Sending prepare extension entry-point for {} command to MS: {}", extension, msPeer); + logger.debug("Sending prepare extension path for {} command to MS: {}", extension, msPeer); final Command[] commands = new Command[1]; commands[0] = new PrepareExtensionPathCommand(ManagementServerNode.getManagementServerId(), extension); String answersStr = clusterManager.execute(msPeer, 0L, GsonHelper.getGson().toJson(commands), true); - return getResultFromAnswersString(answersStr, extension, msHost, "prepare entry-point").first(); + return getResultFromAnswersString(answersStr, extension, msHost, "prepare path").first(); } protected Pair prepareExtensionPathOnCurrentServer(String name, boolean userDefined, @@ -272,7 +280,7 @@ public class ExtensionsManagerImpl extends ManagerBase implements ExtensionsMana try { externalProvisioner.prepareExtensionPath(name, userDefined, relativePath); } catch (CloudRuntimeException e) { - logger.error("Failed to prepare entry-point for Extension [name: {}, userDefined: {}, relativePath: {}] on this server", + logger.error("Failed to prepare path for Extension [name: {}, userDefined: {}, relativePath: {}] on this server", name, userDefined, relativePath, e); return new Pair<>(false, e.getMessage()); } @@ -281,11 +289,11 @@ public class ExtensionsManagerImpl extends ManagerBase implements ExtensionsMana protected boolean cleanupExtensionFilesOnMSPeer(Extension extension, ManagementServerHostVO msHost) { final String msPeer = Long.toString(msHost.getMsid()); - logger.debug("Sending cleanup extension entry-point for {} command to MS: {}", extension, msPeer); + logger.debug("Sending cleanup extension files for {} command to MS: {}", extension, msPeer); final Command[] commands = new Command[1]; commands[0] = new CleanupExtensionFilesCommand(ManagementServerNode.getManagementServerId(), extension); String answersStr = clusterManager.execute(msPeer, 0L, GsonHelper.getGson().toJson(commands), true); - return getResultFromAnswersString(answersStr, extension, msHost, "cleanup entry-point").first(); + return getResultFromAnswersString(answersStr, extension, msHost, "cleanup files").first(); } protected Pair cleanupExtensionFilesOnCurrentServer(String name, String relativePath) { @@ -293,7 +301,7 @@ public class ExtensionsManagerImpl extends ManagerBase implements ExtensionsMana externalProvisioner.cleanupExtensionPath(name, relativePath); externalProvisioner.cleanupExtensionData(name, 0, true); } catch (CloudRuntimeException e) { - logger.error("Failed to cleanup entry-point files for Extension [name: {}, relativePath: {}] on this server", + logger.error("Failed to cleanup files for Extension [name: {}, relativePath: {}] on this server", name, relativePath, e); return new Pair<>(false, e.getMessage()); } @@ -301,18 +309,18 @@ public class ExtensionsManagerImpl extends ManagerBase implements ExtensionsMana } protected void cleanupExtensionFilesAcrossServers(Extension extension) { - boolean cleanup = true; + boolean cleanedUp = true; List msHosts = managementServerHostDao.listBy(ManagementServerHost.State.Up); for (ManagementServerHostVO msHost : msHosts) { if (msHost.getMsid() == ManagementServerNode.getManagementServerId()) { - cleanup = cleanup && cleanupExtensionFilesOnCurrentServer(extension.getName(), + cleanedUp = cleanedUp && cleanupExtensionFilesOnCurrentServer(extension.getName(), extension.getRelativePath()).first(); continue; } - cleanup = cleanup && cleanupExtensionFilesOnMSPeer(extension, msHost); + cleanedUp = cleanedUp && cleanupExtensionFilesOnMSPeer(extension, msHost); } - if (!cleanup) { - throw new CloudRuntimeException("Extension is deleted but its entry-point files are not cleaned up across servers"); + if (!cleanedUp) { + throw new CloudRuntimeException("Extension is deleted but its files are not cleaned up across servers"); } } @@ -323,7 +331,7 @@ public class ExtensionsManagerImpl extends ManagerBase implements ExtensionsMana cmds[0] = new GetExtensionPathChecksumCommand(ManagementServerNode.getManagementServerId(), extension); String answersStr = clusterManager.execute(msPeer, 0L, GsonHelper.getGson().toJson(cmds), true); - return getResultFromAnswersString(answersStr, extension, msHost, "prepare entry-point"); + return getResultFromAnswersString(answersStr, extension, msHost, "get path checksum"); } protected List getParametersListFromMap(String actionName, Map parametersMap) { @@ -472,6 +480,29 @@ public class ExtensionsManagerImpl extends ManagerBase implements ExtensionsMana executorService.shutdown(); } + protected Map getCallerDetails() { + Account caller = CallContext.current().getCallingAccount(); + if (caller == null) { + return null; + } + Map callerDetails = new HashMap<>(); + callerDetails.put(ApiConstants.ID, caller.getUuid()); + callerDetails.put(ApiConstants.NAME, caller.getAccountName()); + if (caller.getType() != null) { + callerDetails.put(ApiConstants.TYPE, caller.getType().name()); + } + Role role = roleService.findRole(caller.getRoleId()); + if (role == null) { + return callerDetails; + } + callerDetails.put(ApiConstants.ROLE_ID, role.getUuid()); + callerDetails.put(ApiConstants.ROLE_NAME, role.getName()); + if (role.getRoleType() != null) { + callerDetails.put(ApiConstants.ROLE_TYPE, role.getRoleType().name()); + } + return callerDetails; + } + protected Map> getExternalAccessDetails(Map actionDetails, long hostId, ExtensionResourceMap resourceMap) { Map> externalDetails = new HashMap<>(); @@ -493,6 +524,10 @@ public class ExtensionsManagerImpl extends ManagerBase implements ExtensionsMana if (MapUtils.isNotEmpty(extensionDetails)) { externalDetails.put(ApiConstants.EXTENSION, extensionDetails); } + Map callerDetails = getCallerDetails(); + if (MapUtils.isNotEmpty(callerDetails)) { + externalDetails.put(ApiConstants.CALLER, callerDetails); + } return externalDetails; } @@ -518,7 +553,7 @@ public class ExtensionsManagerImpl extends ManagerBase implements ExtensionsMana final Pair msPeerChecksumResult = getChecksumForExtensionPathOnMSPeer(extension, msHost); if (!msPeerChecksumResult.first() || !checksum.equals(msPeerChecksumResult.second())) { - logger.error("Entry-point checksum for {} is different [msid: {}, checksum: {}] and [msid: {}, checksum: {}]", + logger.error("Path checksum for {} is different [msid: {}, checksum: {}] and [msid: {}, checksum: {}]", extension, ManagementServerNode.getManagementServerId(), checksum, msHost.getMsid(), (msPeerChecksumResult.first() ? msPeerChecksumResult.second() : "unknown")); updateExtensionPathReady(extension, false); @@ -599,7 +634,7 @@ public class ExtensionsManagerImpl extends ManagerBase implements ExtensionsMana !prepareExtensionPathAcrossServers(extensionVO)) { disableExtension(extensionVO.getId()); throw new CloudRuntimeException(String.format( - "Failed to enable extension: %s as it entry-point is not ready", + "Failed to enable extension: %s as its path is not ready", extensionVO.getName())); } return extensionVO; @@ -705,7 +740,7 @@ public class ExtensionsManagerImpl extends ManagerBase implements ExtensionsMana !prepareExtensionPathAcrossServers(result)) { disableExtension(result.getId()); throw new CloudRuntimeException(String.format( - "Failed to enable extension: %s as it entry-point is not ready", + "Failed to enable extension: %s as it path is not ready", extensionVO.getName())); } updateAllExtensionHosts(extensionVO, null, false); @@ -1323,11 +1358,14 @@ public class ExtensionsManagerImpl extends ManagerBase implements ExtensionsMana clusterId = host.getClusterId(); } else if (entity instanceof VirtualMachine) { VirtualMachine virtualMachine = (VirtualMachine)entity; - runCustomActionCommand.setVmId(virtualMachine.getId()); + accountService.checkAccess(caller, null, true, virtualMachine); if (!Hypervisor.HypervisorType.External.equals(virtualMachine.getHypervisorType())) { logger.error("Invalid {} specified as VM resource for running {}", entity, customActionVO); throw new InvalidParameterValueException(error); } + VirtualMachineProfile vmProfile = new VirtualMachineProfileImpl(virtualMachine); + VirtualMachineTO virtualMachineTO = virtualMachineManager.toVmTO(vmProfile); + runCustomActionCommand.setVmTO(virtualMachineTO); Pair clusterAndHostId = virtualMachineManager.findClusterAndHostIdForVm(virtualMachine, false); clusterId = clusterAndHostId.first(); hostId = clusterAndHostId.second(); @@ -1369,6 +1407,13 @@ public class ExtensionsManagerImpl extends ManagerBase implements ExtensionsMana actionResourceType, entity)); Map> externalDetails = getExternalAccessDetails(allDetails.first(), hostId, extensionResource); + Map vmExternalDetails = null; + if (runCustomActionCommand.getVmTO() != null) { + vmExternalDetails = runCustomActionCommand.getVmTO().getExternalDetails(); + } + if (MapUtils.isNotEmpty(vmExternalDetails)) { + externalDetails.put(ApiConstants.VIRTUAL_MACHINE, vmExternalDetails); + } runCustomActionCommand.setParameters(parameters); runCustomActionCommand.setExternalDetails(externalDetails); runCustomActionCommand.setWait(customActionVO.getTimeout()); @@ -1517,6 +1562,25 @@ public class ExtensionsManagerImpl extends ManagerBase implements ExtensionsMana extensionResourceMapDetailsDao.saveDetails(detailsList); } + @Override + public Answer getInstanceConsole(VirtualMachine vm, Host host) { + Extension extension = getExtensionForCluster(host.getClusterId()); + if (extension == null || !Extension.Type.Orchestrator.equals(extension.getType()) || + !Extension.State.Enabled.equals(extension.getState())) { + logger.error("No enabled orchestrator {} found for the {} while trying to get console for {}", + extension == null ? "extension" : extension, host, vm); + return new Answer(null, false, + String.format("No enabled orchestrator extension found for the host: %s", host.getName())); + } + VirtualMachineProfile vmProfile = new VirtualMachineProfileImpl(vm); + VirtualMachineTO virtualMachineTO = virtualMachineManager.toVmTO(vmProfile); + GetExternalConsoleCommand cmd = new GetExternalConsoleCommand(vm.getInstanceName(), virtualMachineTO); + Map> externalAccessDetails = + getExternalAccessDetails(host, virtualMachineTO.getExternalDetails()); + cmd.setExternalDetails(externalAccessDetails); + return agentMgr.easySend(host.getId(), cmd); + } + @Override public Long getExtensionIdForCluster(long clusterId) { ExtensionResourceMapVO map = extensionResourceMapDao.findByResourceIdAndType(clusterId, diff --git a/framework/extensions/src/test/java/org/apache/cloudstack/framework/extensions/manager/ExtensionsManagerImplTest.java b/framework/extensions/src/test/java/org/apache/cloudstack/framework/extensions/manager/ExtensionsManagerImplTest.java index fcceb16523e..085ae212b28 100644 --- a/framework/extensions/src/test/java/org/apache/cloudstack/framework/extensions/manager/ExtensionsManagerImplTest.java +++ b/framework/extensions/src/test/java/org/apache/cloudstack/framework/extensions/manager/ExtensionsManagerImplTest.java @@ -49,6 +49,8 @@ import java.util.List; import java.util.Map; import java.util.UUID; +import com.cloud.exception.PermissionDeniedException; +import com.cloud.user.AccountService; import org.apache.cloudstack.acl.Role; import org.apache.cloudstack.acl.RoleService; import org.apache.cloudstack.acl.RoleType; @@ -92,7 +94,6 @@ import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockedStatic; -import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.mockito.Spy; import org.mockito.junit.MockitoJUnitRunner; @@ -102,6 +103,7 @@ import com.cloud.agent.AgentManager; import com.cloud.agent.api.Answer; import com.cloud.agent.api.Command; import com.cloud.agent.api.RunCustomActionAnswer; +import com.cloud.agent.api.to.VirtualMachineTO; import com.cloud.alert.AlertManager; import com.cloud.cluster.ClusterManager; import com.cloud.cluster.ManagementServerHostVO; @@ -111,6 +113,7 @@ import com.cloud.dc.dao.ClusterDao; import com.cloud.exception.AgentUnavailableException; import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.OperationTimedoutException; +import com.cloud.host.Host; import com.cloud.host.dao.HostDao; import com.cloud.host.dao.HostDetailsDao; import com.cloud.hypervisor.ExternalProvisioner; @@ -120,6 +123,7 @@ import com.cloud.serializer.GsonHelper; import com.cloud.storage.dao.VMTemplateDao; import com.cloud.user.Account; import com.cloud.utils.Pair; +import com.cloud.utils.UuidUtils; import com.cloud.utils.db.EntityManager; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; @@ -174,6 +178,8 @@ public class ExtensionsManagerImplTest { private VMTemplateDao templateDao; @Mock private RoleService roleService; + @Mock + private AccountService accountService; @Before public void setUp() { @@ -524,11 +530,15 @@ public class ExtensionsManagerImplTest { when(hostDetailsDao.findDetails(hostId)).thenReturn(null); when(extensionResourceMapDetailsDao.listDetailsKeyPairs(2L, true)).thenReturn(Collections.emptyMap()); when(extensionDetailsDao.listDetailsKeyPairs(3L, true)).thenReturn(map); - Map> result = extensionsManager.getExternalAccessDetails(map, hostId, resourceMap); - assertTrue(result.containsKey(ApiConstants.ACTION)); - assertFalse(result.containsKey(ApiConstants.HOST)); - assertFalse(result.containsKey(ApiConstants.RESOURCE_MAP)); - assertTrue(result.containsKey(ApiConstants.EXTENSION)); + try (MockedStatic ignored = mockStatic(CallContext.class)) { + mockCallerRole(RoleType.Admin); + Map> result = extensionsManager.getExternalAccessDetails(map, hostId, resourceMap); + assertTrue(result.containsKey(ApiConstants.ACTION)); + assertFalse(result.containsKey(ApiConstants.HOST)); + assertFalse(result.containsKey(ApiConstants.RESOURCE_MAP)); + assertTrue(result.containsKey(ApiConstants.EXTENSION)); + assertTrue(result.containsKey(ApiConstants.CALLER)); + } } @Test(expected = CloudRuntimeException.class) @@ -1281,12 +1291,17 @@ public class ExtensionsManagerImplTest { } private void mockCallerRole(RoleType roleType) { - CallContext callContextMock = Mockito.mock(CallContext.class); + CallContext callContextMock = mock(CallContext.class); when(CallContext.current()).thenReturn(callContextMock); Account accountMock = mock(Account.class); + when(accountMock.getAccountName()).thenReturn("testAccount"); + when(accountMock.getUuid()).thenReturn(UUID.randomUUID().toString()); + when(accountMock.getType()).thenReturn(RoleType.Admin.equals(roleType) ? Account.Type.ADMIN : Account.Type.NORMAL); when(accountMock.getRoleId()).thenReturn(1L); Role role = mock(Role.class); when(role.getRoleType()).thenReturn(roleType); + when(role.getUuid()).thenReturn("role-uuid-1"); + when(role.getName()).thenReturn(roleType.name() + "Role"); when(roleService.findRole(1L)).thenReturn(role); when(callContextMock.getCallingAccount()).thenReturn(accountMock); } @@ -1629,6 +1644,35 @@ public class ExtensionsManagerImplTest { } } + @Test(expected = PermissionDeniedException.class) + public void runCustomAction_CheckAccessThrowsException() throws Exception { + RunCustomActionCmd cmd = mock(RunCustomActionCmd.class); + when(cmd.getCustomActionId()).thenReturn(1L); + when(cmd.getResourceId()).thenReturn("vm-123"); + when(cmd.getParameters()).thenReturn(Map.of("param1", "value1")); + + ExtensionCustomActionVO actionVO = mock(ExtensionCustomActionVO.class); + when(extensionCustomActionDao.findById(1L)).thenReturn(actionVO); + when(actionVO.isEnabled()).thenReturn(true); + when(actionVO.getResourceType()).thenReturn(ExtensionCustomAction.ResourceType.VirtualMachine); + when(actionVO.getAllowedRoleTypes()).thenReturn(RoleType.toCombinedMask(List.of(RoleType.Admin, RoleType.DomainAdmin, RoleType.User))); + + ExtensionVO extensionVO = mock(ExtensionVO.class); + when(extensionDao.findById(anyLong())).thenReturn(extensionVO); + when(extensionVO.getState()).thenReturn(Extension.State.Enabled); + + VirtualMachine vm = mock(VirtualMachine.class); + when(entityManager.findByUuid(eq(VirtualMachine.class), anyString())).thenReturn(vm); + doThrow(PermissionDeniedException.class).when(accountService).checkAccess(any(Account.class), eq(null), eq(true), eq(vm)); + + try (MockedStatic ignored = mockStatic(CallContext.class)) { + mockCallerRole(RoleType.User); + CustomActionResultResponse result = extensionsManager.runCustomAction(cmd); + + assertFalse(result.getSuccess()); + } + } + @Test public void createCustomActionResponse_SetsBasicFields() { ExtensionCustomAction action = mock(ExtensionCustomAction.class); @@ -1882,4 +1926,147 @@ public class ExtensionsManagerImplTest { Extension result = extensionsManager.getExtensionForCluster(clusterId); assertNull(result); } + + @Test + public void getInstanceConsole_whenValid() { + Extension extension = mock(Extension.class); + when(extension.getType()).thenReturn(Extension.Type.Orchestrator); + when(extension.getState()).thenReturn(Extension.State.Enabled); + when(extensionsManager.getExtensionForCluster(anyLong())).thenReturn(extension); + VirtualMachine vm = mock(VirtualMachine.class); + Host host = mock(Host.class); + when(host.getClusterId()).thenReturn(1L); + Answer expectedAnswer = mock(Answer.class); + when(virtualMachineManager.toVmTO(any())).thenReturn(mock(VirtualMachineTO.class)); + when(agentMgr.easySend(anyLong(), any())).thenReturn(expectedAnswer); + Answer result = extensionsManager.getInstanceConsole(vm, host); + assertNotNull(result); + assertEquals(expectedAnswer, result); + } + + @Test + public void getInstanceConsole_whenNullExtension() { + when(extensionsManager.getExtensionForCluster(anyLong())).thenReturn(null); + VirtualMachine vm = mock(VirtualMachine.class); + Host host = mock(Host.class); + when(host.getClusterId()).thenReturn(1L); + Answer result = extensionsManager.getInstanceConsole(vm, host); + assertNotNull(result); + assertFalse(result.getResult()); + } + + @Test + public void getInstanceConsole_whenNullExtensionNotOrchestrator() { + Extension extension = mock(Extension.class); + when(extensionsManager.getExtensionForCluster(anyLong())).thenReturn(extension); + VirtualMachine vm = mock(VirtualMachine.class); + Host host = mock(Host.class); + when(host.getClusterId()).thenReturn(1L); + Answer result = extensionsManager.getInstanceConsole(vm, host); + assertNotNull(result); + assertFalse(result.getResult()); + } + + @Test + public void getInstanceConsole_whenNullExtensionNotEnabled() { + Extension extension = mock(Extension.class); + when(extension.getType()).thenReturn(Extension.Type.Orchestrator); + when(extension.getState()).thenReturn(Extension.State.Disabled); + when(extensionsManager.getExtensionForCluster(anyLong())).thenReturn(extension); + VirtualMachine vm = mock(VirtualMachine.class); + Host host = mock(Host.class); + when(host.getClusterId()).thenReturn(1L); + Answer result = extensionsManager.getInstanceConsole(vm, host); + assertNotNull(result); + assertFalse(result.getResult()); + } + + @Test + public void getInstanceConsole_whenAgentManagerFails() { + Extension extension = mock(Extension.class); + when(extension.getType()).thenReturn(Extension.Type.Orchestrator); + when(extension.getState()).thenReturn(Extension.State.Enabled); + when(extensionsManager.getExtensionForCluster(anyLong())).thenReturn(extension); + VirtualMachine vm = mock(VirtualMachine.class); + Host host = mock(Host.class); + when(host.getClusterId()).thenReturn(1L); + when(virtualMachineManager.toVmTO(any())).thenReturn(mock(VirtualMachineTO.class)); + when(agentMgr.easySend(anyLong(), any())).thenReturn(null); + Answer result = extensionsManager.getInstanceConsole(vm, host); + assertNull(result); + } + + @Test + public void getExternalAccessDetailsReturnsExpectedDetails() { + Host host = mock(Host.class); + when(host.getId()).thenReturn(100L); + when(host.getClusterId()).thenReturn(1L); + Map vmDetails = Map.of("key1", "value1", "key2", "value2"); + ExtensionResourceMapVO resourceMapVO = mock(ExtensionResourceMapVO.class); + when(extensionResourceMapDao.findByResourceIdAndType(1L, ExtensionResourceMap.ResourceType.Cluster)) + .thenReturn(resourceMapVO); + doReturn(new HashMap<>()).when(extensionsManager).getExternalAccessDetails(null, 100L, resourceMapVO); + Map> result = extensionsManager.getExternalAccessDetails(host, vmDetails); + assertNotNull(result); + assertNotNull(result.get(ApiConstants.VIRTUAL_MACHINE)); + assertEquals(vmDetails, result.get(ApiConstants.VIRTUAL_MACHINE)); + } + + @Test + public void getExternalAccessDetailsReturnsExpectedNullDetails() { + Host host = mock(Host.class); + when(host.getId()).thenReturn(101L); + when(host.getClusterId()).thenReturn(1L); + Map vmDetails = null; + ExtensionResourceMapVO resourceMapVO = mock(ExtensionResourceMapVO.class); + when(extensionResourceMapDao.findByResourceIdAndType(1L, ExtensionResourceMap.ResourceType.Cluster)) + .thenReturn(resourceMapVO); + doReturn(new HashMap<>()).when(extensionsManager).getExternalAccessDetails(null, 101L, resourceMapVO); + Map> result = extensionsManager.getExternalAccessDetails(host, vmDetails); + assertNotNull(result); + assertNull(result.get(ApiConstants.VIRTUAL_MACHINE)); + } + + @Test + public void getCallerDetailsReturnsExpectedDetailsForValidCaller() { + try (MockedStatic ignored = mockStatic(CallContext.class)) { + mockCallerRole(RoleType.Admin); + Map result = extensionsManager.getCallerDetails(); + assertNotNull(result); + assertTrue(UuidUtils.isUuid(result.get(ApiConstants.ID))); + assertEquals("testAccount", result.get(ApiConstants.NAME)); + assertEquals("ADMIN", result.get(ApiConstants.TYPE)); + assertEquals("role-uuid-1", result.get(ApiConstants.ROLE_ID)); + assertEquals("AdminRole", result.get(ApiConstants.ROLE_NAME)); + assertEquals("Admin", result.get(ApiConstants.ROLE_TYPE)); + } + } + + @Test + public void getCallerDetailsReturnsNullWhenCallerIsNull() { + CallContext callContext = mock(CallContext.class); + when(callContext.getCallingAccount()).thenReturn(null); + try (MockedStatic mockedCallContext = mockStatic(CallContext.class)) { + mockedCallContext.when(CallContext::current).thenReturn(callContext); + Map result = extensionsManager.getCallerDetails(); + assertNull(result); + } + } + + @Test + public void getCallerDetailsReturnsDetailsWithoutRoleWhenRoleIsNull() { + try (MockedStatic ignored = mockStatic(CallContext.class)) { + mockCallerRole(RoleType.User); + when(roleService.findRole(1L)).thenReturn(null); + Map result = extensionsManager.getCallerDetails(); + assertNotNull(result); + assertTrue(UuidUtils.isUuid(result.get(ApiConstants.ID))); + assertEquals("testAccount", result.get(ApiConstants.NAME)); + assertEquals("NORMAL", result.get(ApiConstants.TYPE)); + assertNull(result.get(ApiConstants.ROLE_ID)); + assertNull(result.get(ApiConstants.ROLE_NAME)); + assertNull(result.get(ApiConstants.ROLE_TYPE)); + } + } + } diff --git a/framework/ipc/pom.xml b/framework/ipc/pom.xml index 14ef793cd34..d9fa9d85271 100644 --- a/framework/ipc/pom.xml +++ b/framework/ipc/pom.xml @@ -24,7 +24,7 @@ org.apache.cloudstack cloudstack-framework - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT ../pom.xml diff --git a/framework/jobs/pom.xml b/framework/jobs/pom.xml index c6e3926ed4d..ad342acf8d8 100644 --- a/framework/jobs/pom.xml +++ b/framework/jobs/pom.xml @@ -24,7 +24,7 @@ org.apache.cloudstack cloudstack-framework - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT ../pom.xml diff --git a/framework/jobs/src/main/java/org/apache/cloudstack/framework/jobs/impl/AsyncJobManagerImpl.java b/framework/jobs/src/main/java/org/apache/cloudstack/framework/jobs/impl/AsyncJobManagerImpl.java index ea7de4f79c6..7672b9dc6f9 100644 --- a/framework/jobs/src/main/java/org/apache/cloudstack/framework/jobs/impl/AsyncJobManagerImpl.java +++ b/framework/jobs/src/main/java/org/apache/cloudstack/framework/jobs/impl/AsyncJobManagerImpl.java @@ -35,6 +35,11 @@ import java.util.concurrent.TimeUnit; import javax.inject.Inject; import javax.naming.ConfigurationException; +import com.cloud.storage.SnapshotVO; +import com.cloud.vm.snapshot.VMSnapshot; +import com.cloud.vm.snapshot.VMSnapshotService; +import com.cloud.vm.snapshot.VMSnapshotVO; +import com.cloud.vm.snapshot.dao.VMSnapshotDao; import org.apache.cloudstack.api.ApiCommandResourceType; import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.command.ReconcileCommandService; @@ -155,11 +160,15 @@ public class AsyncJobManagerImpl extends ManagerBase implements AsyncJobManager, @Inject private SnapshotDao _snapshotDao; @Inject + private VMSnapshotDao _vmSnapshotDao; + @Inject private SnapshotService snapshotSrv; @Inject private SnapshotDataFactory snapshotFactory; @Inject private SnapshotDetailsDao _snapshotDetailsDao; + @Inject + private VMSnapshotService _vmSnapshotService; @Inject private VolumeDataFactory volFactory; @@ -1186,6 +1195,10 @@ public class AsyncJobManagerImpl extends ManagerBase implements AsyncJobManager, return cleanupVirtualMachine(job.getInstanceId()); case Network: return cleanupNetwork(job.getInstanceId()); + case Snapshot: + return cleanupSnapshot(job.getInstanceId()); + case VmSnapshot: + return cleanupVmSnapshot(job.getInstanceId()); } } catch (Exception e) { logger.warn("Error while cleaning up resource: [" + job.getInstanceType().toString() + "] with Id: " + job.getInstanceId(), e); @@ -1253,7 +1266,7 @@ public class AsyncJobManagerImpl extends ManagerBase implements AsyncJobManager, return true; } - private boolean cleanupNetwork(final long networkId) throws Exception { + private boolean cleanupNetwork(final long networkId) { NetworkVO networkVO = networkDao.findById(networkId); if (networkVO == null) { logger.warn("Network not found. Skip Cleanup. NetworkId: " + networkId); @@ -1272,6 +1285,46 @@ public class AsyncJobManagerImpl extends ManagerBase implements AsyncJobManager, return true; } + private boolean cleanupSnapshot(final long snapshotId) { + SnapshotVO snapshotVO = _snapshotDao.findById(snapshotId); + if (snapshotVO == null) { + logger.warn("Snapshot not found. Skip Cleanup. SnapshotId: " + snapshotId); + return true; + } + if (Snapshot.State.Allocated.equals(snapshotVO.getState())) { + _snapshotDao.remove(snapshotId); + } + if (Snapshot.State.Creating.equals(snapshotVO.getState())) { + try { + snapshotFactory.updateOperationFailed(snapshotId); + } catch (NoTransitionException e) { + snapshotVO.setState(Snapshot.State.Error); + _snapshotDao.update(snapshotVO.getId(), snapshotVO); + } + } + return true; + } + + private boolean cleanupVmSnapshot(final long vmSnapshotId) { + VMSnapshotVO vmSnapshotVO = _vmSnapshotDao.findById(vmSnapshotId); + if (vmSnapshotVO == null) { + logger.warn("VM Snapshot not found. Skip Cleanup. VMSnapshotId: " + vmSnapshotId); + return true; + } + if (VMSnapshot.State.Allocated.equals(vmSnapshotVO.getState())) { + _vmSnapshotDao.remove(vmSnapshotId); + } + if (VMSnapshot.State.Creating.equals(vmSnapshotVO.getState())) { + try { + _vmSnapshotService.updateOperationFailed(vmSnapshotVO); + } catch (NoTransitionException e) { + vmSnapshotVO.setState(VMSnapshot.State.Error); + _vmSnapshotDao.update(vmSnapshotVO.getId(), vmSnapshotVO); + } + } + return true; + } + private void cleanupFailedVolumesCreatedFromSnapshots(final long volumeId) { try { VolumeDetailVO volumeDetail = _volumeDetailsDao.findDetail(volumeId, VolumeService.SNAPSHOT_ID); diff --git a/framework/managed-context/pom.xml b/framework/managed-context/pom.xml index c74b12d6657..70f20ecb04e 100644 --- a/framework/managed-context/pom.xml +++ b/framework/managed-context/pom.xml @@ -24,7 +24,7 @@ org.apache.cloudstack cloudstack - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT ../../pom.xml diff --git a/framework/pom.xml b/framework/pom.xml index 38fa6857456..337e5b0268b 100644 --- a/framework/pom.xml +++ b/framework/pom.xml @@ -25,7 +25,7 @@ org.apache.cloudstack cloudstack - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT diff --git a/framework/quota/pom.xml b/framework/quota/pom.xml index bbf08ad37dd..70cb3ac8cd5 100644 --- a/framework/quota/pom.xml +++ b/framework/quota/pom.xml @@ -24,7 +24,7 @@ org.apache.cloudstack cloudstack-framework - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT ../pom.xml diff --git a/framework/quota/src/main/java/org/apache/cloudstack/quota/QuotaManagerImpl.java b/framework/quota/src/main/java/org/apache/cloudstack/quota/QuotaManagerImpl.java index a03f82a4358..7949259bc82 100644 --- a/framework/quota/src/main/java/org/apache/cloudstack/quota/QuotaManagerImpl.java +++ b/framework/quota/src/main/java/org/apache/cloudstack/quota/QuotaManagerImpl.java @@ -32,7 +32,6 @@ import java.util.stream.Collectors; import javax.inject.Inject; import javax.naming.ConfigurationException; -import com.cloud.user.Account; import org.apache.cloudstack.framework.config.dao.ConfigurationDao; import org.apache.cloudstack.quota.activationrule.presetvariables.Configuration; import org.apache.cloudstack.quota.activationrule.presetvariables.GenericPresetVariable; @@ -63,6 +62,7 @@ import org.springframework.stereotype.Component; import com.cloud.usage.UsageVO; import com.cloud.usage.dao.UsageDao; +import com.cloud.user.Account; import com.cloud.user.AccountVO; import com.cloud.user.dao.AccountDao; import com.cloud.utils.DateUtil; @@ -473,7 +473,7 @@ public class QuotaManagerImpl extends ManagerBase implements QuotaManager { jsInterpreter.injectVariable("configuration", configuration.toString()); } - jsInterpreter.injectStringVariable("resourceType", presetVariables.getResourceType()); + jsInterpreter.injectVariable("resourceType", presetVariables.getResourceType()); jsInterpreter.injectVariable("value", presetVariables.getValue().toString()); jsInterpreter.injectVariable("zone", presetVariables.getZone().toString()); } diff --git a/framework/quota/src/test/java/org/apache/cloudstack/quota/QuotaManagerImplTest.java b/framework/quota/src/test/java/org/apache/cloudstack/quota/QuotaManagerImplTest.java index c62f80d4a44..3b2ea54e86d 100644 --- a/framework/quota/src/test/java/org/apache/cloudstack/quota/QuotaManagerImplTest.java +++ b/framework/quota/src/test/java/org/apache/cloudstack/quota/QuotaManagerImplTest.java @@ -270,8 +270,7 @@ public class QuotaManagerImplTest { Mockito.verify(jsInterpreterMock).injectVariable(Mockito.eq("account"), Mockito.anyString()); Mockito.verify(jsInterpreterMock).injectVariable(Mockito.eq("domain"), Mockito.anyString()); Mockito.verify(jsInterpreterMock, Mockito.never()).injectVariable(Mockito.eq("project"), Mockito.anyString()); - Mockito.verify(jsInterpreterMock, Mockito.never()).injectVariable(Mockito.eq("configuration"), Mockito.anyString()); - Mockito.verify(jsInterpreterMock).injectStringVariable(Mockito.eq("resourceType"), Mockito.anyString()); + Mockito.verify(jsInterpreterMock).injectVariable(Mockito.eq("resourceType"), Mockito.anyString()); Mockito.verify(jsInterpreterMock).injectVariable(Mockito.eq("value"), Mockito.anyString()); Mockito.verify(jsInterpreterMock).injectVariable(Mockito.eq("zone"), Mockito.anyString()); } @@ -292,7 +291,7 @@ public class QuotaManagerImplTest { Mockito.verify(jsInterpreterMock).injectVariable(Mockito.eq("account"), Mockito.anyString()); Mockito.verify(jsInterpreterMock).injectVariable(Mockito.eq("domain"), Mockito.anyString()); Mockito.verify(jsInterpreterMock).injectVariable(Mockito.eq("project"), Mockito.anyString()); - Mockito.verify(jsInterpreterMock).injectStringVariable(Mockito.eq("resourceType"), Mockito.anyString()); + Mockito.verify(jsInterpreterMock).injectVariable(Mockito.eq("resourceType"), Mockito.anyString()); Mockito.verify(jsInterpreterMock).injectVariable(Mockito.eq("value"), Mockito.anyString()); Mockito.verify(jsInterpreterMock).injectVariable(Mockito.eq("zone"), Mockito.anyString()); } diff --git a/framework/rest/pom.xml b/framework/rest/pom.xml index 05b96731008..e2e787aec46 100644 --- a/framework/rest/pom.xml +++ b/framework/rest/pom.xml @@ -22,7 +22,7 @@ org.apache.cloudstack cloudstack-framework - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT ../pom.xml cloud-framework-rest diff --git a/framework/security/pom.xml b/framework/security/pom.xml index e2a06c5d5af..30940b68f1a 100644 --- a/framework/security/pom.xml +++ b/framework/security/pom.xml @@ -24,7 +24,7 @@ org.apache.cloudstack cloudstack-framework - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT ../pom.xml diff --git a/framework/spring/lifecycle/pom.xml b/framework/spring/lifecycle/pom.xml index acc3ee3395c..90a26a7be23 100644 --- a/framework/spring/lifecycle/pom.xml +++ b/framework/spring/lifecycle/pom.xml @@ -24,7 +24,7 @@ org.apache.cloudstack cloudstack - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT ../../../pom.xml diff --git a/framework/spring/module/pom.xml b/framework/spring/module/pom.xml index 5485e6d6e7f..f44cffa30b1 100644 --- a/framework/spring/module/pom.xml +++ b/framework/spring/module/pom.xml @@ -24,7 +24,7 @@ org.apache.cloudstack cloudstack - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT ../../../pom.xml diff --git a/packaging/README.md b/packaging/README.md index 78057b828b2..0c01ce5497c 100644 --- a/packaging/README.md +++ b/packaging/README.md @@ -1,3 +1,22 @@ + + # CloudStack RPM and DEB packaging This directory contains all the required scripts and tools needed to build RPM and DEB packages for Apache CloudStack. diff --git a/packaging/el10 b/packaging/el10 new file mode 120000 index 00000000000..4dad90d45e0 --- /dev/null +++ b/packaging/el10 @@ -0,0 +1 @@ +el8 \ No newline at end of file diff --git a/packaging/el8/cloud.spec b/packaging/el8/cloud.spec index 9c2f8d29bed..7e97957473c 100644 --- a/packaging/el8/cloud.spec +++ b/packaging/el8/cloud.spec @@ -17,7 +17,7 @@ %define __os_install_post %{nil} %global debug_package %{nil} -%global __requires_exclude libc\\.so\\..* +%global __requires_exclude libc\\.so\\..*|libc\\.so\\.6\\(GLIBC_.*\\) %define _binaries_in_noarch_packages_terminate_build 0 # DISABLE the post-percentinstall java repacking and line number stripping @@ -39,7 +39,7 @@ Source0: %{name}-%{_maventag}.tgz BuildRoot: %{_tmppath}/%{name}-%{_maventag}-%{release}-build BuildArch: noarch -BuildRequires: (java-11-openjdk-devel or java-17-openjdk-devel) +BuildRequires: (java-11-openjdk-devel or java-17-openjdk-devel or java-21-openjdk-devel) #BuildRequires: ws-commons-util BuildRequires: jpackage-utils BuildRequires: gcc @@ -55,7 +55,7 @@ intelligent IaaS cloud implementation. %package management Summary: CloudStack management server UI -Requires: java-17-openjdk +Requires: (java-17-openjdk or java-21-openjdk) Requires: (tzdata-java or timezone-java) Requires: python3 Requires: bash @@ -66,12 +66,12 @@ Requires: tar Requires: bzip2 Requires: gzip Requires: unzip -Requires: /sbin/mount.nfs +Requires: (/sbin/mount.nfs or /usr/sbin/mount.nfs) Requires: (openssh-clients or openssh) Requires: (nfs-utils or nfs-client) Requires: iproute Requires: wget -Requires: (mysql or mariadb) +Requires: (mysql or mariadb or mysql8.4) Requires: sudo Requires: /sbin/service Requires: /sbin/chkconfig @@ -96,12 +96,12 @@ Requires: python3 Group: System Environment/Libraries %description common The Apache CloudStack files shared between agent and management server -%global __requires_exclude ^(libuuid\\.so\\.1|/usr/bin/python)$ +%global __requires_exclude libc\\.so\\..*|libc\\.so\\.6\\(GLIBC_.*\\)|^(libuuid\\.so\\.1|/usr/bin/python)$ %package agent Summary: CloudStack Agent for KVM hypervisors Requires: (openssh-clients or openssh) -Requires: java-17-openjdk +Requires: (java-17-openjdk or java-21-openjdk) Requires: (tzdata-java or timezone-java) Requires: %{name}-common = %{_ver} Requires: libvirt @@ -142,7 +142,7 @@ The CloudStack baremetal agent %package usage Summary: CloudStack Usage calculation server -Requires: java-17-openjdk +Requires: (java-17-openjdk or java-21-openjdk) Requires: (tzdata-java or timezone-java) Group: System Environment/Libraries %description usage diff --git a/plugins/acl/dynamic-role-based/pom.xml b/plugins/acl/dynamic-role-based/pom.xml index 2c7e099f9b5..0b0b2300e77 100644 --- a/plugins/acl/dynamic-role-based/pom.xml +++ b/plugins/acl/dynamic-role-based/pom.xml @@ -24,7 +24,7 @@ org.apache.cloudstack cloudstack-plugins - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT ../../pom.xml diff --git a/plugins/acl/project-role-based/pom.xml b/plugins/acl/project-role-based/pom.xml index 6327ffe400d..2c351bdbc8c 100644 --- a/plugins/acl/project-role-based/pom.xml +++ b/plugins/acl/project-role-based/pom.xml @@ -24,7 +24,7 @@ org.apache.cloudstack cloudstack-plugins - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT ../../pom.xml diff --git a/plugins/acl/static-role-based/pom.xml b/plugins/acl/static-role-based/pom.xml index cdd58bb113a..c6e790b485e 100644 --- a/plugins/acl/static-role-based/pom.xml +++ b/plugins/acl/static-role-based/pom.xml @@ -24,7 +24,7 @@ org.apache.cloudstack cloudstack-plugins - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT ../../pom.xml diff --git a/plugins/affinity-group-processors/explicit-dedication/pom.xml b/plugins/affinity-group-processors/explicit-dedication/pom.xml index 97afc9ca375..769773e9dca 100644 --- a/plugins/affinity-group-processors/explicit-dedication/pom.xml +++ b/plugins/affinity-group-processors/explicit-dedication/pom.xml @@ -24,7 +24,7 @@ org.apache.cloudstack cloudstack-plugins - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT ../../pom.xml diff --git a/plugins/affinity-group-processors/host-affinity/pom.xml b/plugins/affinity-group-processors/host-affinity/pom.xml index e0e1f967ef3..925da93b29c 100644 --- a/plugins/affinity-group-processors/host-affinity/pom.xml +++ b/plugins/affinity-group-processors/host-affinity/pom.xml @@ -24,7 +24,7 @@ org.apache.cloudstack cloudstack-plugins - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT ../../pom.xml diff --git a/plugins/affinity-group-processors/host-anti-affinity/pom.xml b/plugins/affinity-group-processors/host-anti-affinity/pom.xml index c2534fae2d0..9b83518d779 100644 --- a/plugins/affinity-group-processors/host-anti-affinity/pom.xml +++ b/plugins/affinity-group-processors/host-anti-affinity/pom.xml @@ -24,7 +24,7 @@ org.apache.cloudstack cloudstack-plugins - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT ../../pom.xml diff --git a/plugins/affinity-group-processors/non-strict-host-affinity/pom.xml b/plugins/affinity-group-processors/non-strict-host-affinity/pom.xml index 887abf726ee..f0bc9e0d7e9 100644 --- a/plugins/affinity-group-processors/non-strict-host-affinity/pom.xml +++ b/plugins/affinity-group-processors/non-strict-host-affinity/pom.xml @@ -24,7 +24,7 @@ org.apache.cloudstack cloudstack-plugins - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT ../../pom.xml diff --git a/plugins/affinity-group-processors/non-strict-host-anti-affinity/pom.xml b/plugins/affinity-group-processors/non-strict-host-anti-affinity/pom.xml index cccd00547da..b12e49f62dd 100644 --- a/plugins/affinity-group-processors/non-strict-host-anti-affinity/pom.xml +++ b/plugins/affinity-group-processors/non-strict-host-anti-affinity/pom.xml @@ -32,7 +32,7 @@ org.apache.cloudstack cloudstack-plugins - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT ../../pom.xml diff --git a/plugins/alert-handlers/snmp-alerts/pom.xml b/plugins/alert-handlers/snmp-alerts/pom.xml index 797471e60fa..ea89037aa2b 100644 --- a/plugins/alert-handlers/snmp-alerts/pom.xml +++ b/plugins/alert-handlers/snmp-alerts/pom.xml @@ -24,7 +24,7 @@ cloudstack-plugins org.apache.cloudstack - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT ../../pom.xml diff --git a/plugins/alert-handlers/syslog-alerts/pom.xml b/plugins/alert-handlers/syslog-alerts/pom.xml index 98ee0f99a5a..a4ae4f08953 100644 --- a/plugins/alert-handlers/syslog-alerts/pom.xml +++ b/plugins/alert-handlers/syslog-alerts/pom.xml @@ -24,7 +24,7 @@ cloudstack-plugins org.apache.cloudstack - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT ../../pom.xml diff --git a/plugins/api/discovery/pom.xml b/plugins/api/discovery/pom.xml index 83ea736267d..b0f29612911 100644 --- a/plugins/api/discovery/pom.xml +++ b/plugins/api/discovery/pom.xml @@ -25,7 +25,7 @@ org.apache.cloudstack cloudstack-plugins - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT ../../pom.xml diff --git a/plugins/api/rate-limit/pom.xml b/plugins/api/rate-limit/pom.xml index 7c93459dc33..294ff18bcc9 100644 --- a/plugins/api/rate-limit/pom.xml +++ b/plugins/api/rate-limit/pom.xml @@ -24,7 +24,7 @@ org.apache.cloudstack cloudstack-plugins - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT ../../pom.xml diff --git a/plugins/api/solidfire-intg-test/pom.xml b/plugins/api/solidfire-intg-test/pom.xml index 04f42ad4b37..0cc9d1aba5a 100644 --- a/plugins/api/solidfire-intg-test/pom.xml +++ b/plugins/api/solidfire-intg-test/pom.xml @@ -24,7 +24,7 @@ org.apache.cloudstack cloudstack-plugins - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT ../../pom.xml diff --git a/plugins/api/vmware-sioc/pom.xml b/plugins/api/vmware-sioc/pom.xml index cb5c6f78ce3..e523568dc50 100644 --- a/plugins/api/vmware-sioc/pom.xml +++ b/plugins/api/vmware-sioc/pom.xml @@ -24,7 +24,7 @@ org.apache.cloudstack cloudstack-plugins - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT ../../pom.xml diff --git a/plugins/backup/dummy/pom.xml b/plugins/backup/dummy/pom.xml index 2446e43a512..63c89cdb3e0 100644 --- a/plugins/backup/dummy/pom.xml +++ b/plugins/backup/dummy/pom.xml @@ -23,7 +23,7 @@ cloudstack-plugins org.apache.cloudstack - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT ../../pom.xml diff --git a/plugins/backup/dummy/src/main/java/org/apache/cloudstack/backup/DummyBackupProvider.java b/plugins/backup/dummy/src/main/java/org/apache/cloudstack/backup/DummyBackupProvider.java index 48082c1c8a4..b228a9f8ce0 100644 --- a/plugins/backup/dummy/src/main/java/org/apache/cloudstack/backup/DummyBackupProvider.java +++ b/plugins/backup/dummy/src/main/java/org/apache/cloudstack/backup/DummyBackupProvider.java @@ -53,6 +53,11 @@ public class DummyBackupProvider extends AdapterBase implements BackupProvider { @Inject private DiskOfferingDao diskOfferingDao; + @Override + public Boolean crossZoneInstanceCreationEnabled(BackupOffering backupOffering) { + return true; + } + @Override public String getName() { return "dummy"; @@ -199,7 +204,7 @@ public class DummyBackupProvider extends AdapterBase implements BackupProvider { } @Override - public boolean restoreBackupToVM(VirtualMachine vm, Backup backup, String hostIp, String dataStoreUuid) { - return true; + public Pair restoreBackupToVM(VirtualMachine vm, Backup backup, String hostIp, String dataStoreUuid) { + return new Pair<>(true, null); } } diff --git a/plugins/backup/nas/pom.xml b/plugins/backup/nas/pom.xml index 5b86d01df0c..3c7cd8ab681 100644 --- a/plugins/backup/nas/pom.xml +++ b/plugins/backup/nas/pom.xml @@ -25,7 +25,7 @@ cloudstack-plugins org.apache.cloudstack - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT ../../pom.xml diff --git a/plugins/backup/nas/src/main/java/org/apache/cloudstack/backup/NASBackupProvider.java b/plugins/backup/nas/src/main/java/org/apache/cloudstack/backup/NASBackupProvider.java index e5f98ad291b..3b2c2692b0d 100644 --- a/plugins/backup/nas/src/main/java/org/apache/cloudstack/backup/NASBackupProvider.java +++ b/plugins/backup/nas/src/main/java/org/apache/cloudstack/backup/NASBackupProvider.java @@ -26,9 +26,9 @@ import com.cloud.host.dao.HostDao; import com.cloud.hypervisor.Hypervisor; import com.cloud.offering.DiskOffering; import com.cloud.resource.ResourceManager; +import com.cloud.storage.DataStoreRole; import com.cloud.storage.ScopeType; import com.cloud.storage.Storage; -import com.cloud.storage.StoragePoolHostVO; import com.cloud.storage.Volume; import com.cloud.storage.VolumeApiServiceImpl; import com.cloud.storage.VolumeVO; @@ -49,10 +49,13 @@ import com.cloud.vm.snapshot.dao.VMSnapshotDetailsDao; import org.apache.cloudstack.backup.dao.BackupDao; import org.apache.cloudstack.backup.dao.BackupRepositoryDao; +import org.apache.cloudstack.engine.subsystem.api.storage.DataStore; +import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager; import org.apache.cloudstack.framework.config.ConfigKey; import org.apache.cloudstack.framework.config.Configurable; import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao; import org.apache.cloudstack.storage.datastore.db.StoragePoolVO; +import org.apache.cloudstack.storage.to.PrimaryDataStoreTO; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; @@ -70,9 +73,18 @@ import java.util.Optional; import java.util.UUID; import java.util.stream.Collectors; +import static org.apache.cloudstack.backup.BackupManager.BackupFrameworkEnabled; + public class NASBackupProvider extends AdapterBase implements BackupProvider, Configurable { private static final Logger LOG = LogManager.getLogger(NASBackupProvider.class); + ConfigKey NASBackupRestoreMountTimeout = new ConfigKey<>("Advanced", Integer.class, + "nas.backup.restore.mount.timeout", + "30", + "Timeout in seconds after which backup repository mount for restore fails.", + true, + BackupFrameworkEnabled.key()); + @Inject private BackupDao backupDao; @@ -97,6 +109,9 @@ public class NASBackupProvider extends AdapterBase implements BackupProvider, Co @Inject private PrimaryDataStoreDao primaryDataStoreDao; + @Inject + DataStoreManager dataStoreMgr; + @Inject private AgentManager agentManager; @@ -115,30 +130,45 @@ public class NASBackupProvider extends AdapterBase implements BackupProvider, Co @Inject private DiskOfferingDao diskOfferingDao; - protected Host getLastVMHypervisorHost(VirtualMachine vm) { - Long hostId = vm.getLastHostId(); - if (hostId == null) { - LOG.debug("Cannot find last host for vm. This should never happen, please check your database."); + private Long getClusterIdFromRootVolume(VirtualMachine vm) { + VolumeVO rootVolume = volumeDao.getInstanceRootVolume(vm.getId()); + StoragePoolVO rootDiskPool = primaryDataStoreDao.findById(rootVolume.getPoolId()); + if (rootDiskPool == null) { return null; } - Host host = hostDao.findById(hostId); + return rootDiskPool.getClusterId(); + } - if (host.getStatus() == Status.Up) { - return host; - } else { + protected Host getVMHypervisorHost(VirtualMachine vm) { + Long hostId = vm.getLastHostId(); + Long clusterId = null; + + if (hostId != null) { + Host host = hostDao.findById(hostId); + if (host.getStatus() == Status.Up) { + return host; + } // Try to find any Up host in the same cluster - for (final Host hostInCluster : hostDao.findHypervisorHostInCluster(host.getClusterId())) { + clusterId = host.getClusterId(); + } else { + // Try to find any Up host in the same cluster as the root volume + clusterId = getClusterIdFromRootVolume(vm); + } + + if (clusterId != null) { + for (final Host hostInCluster : hostDao.findHypervisorHostInCluster(clusterId)) { if (hostInCluster.getStatus() == Status.Up) { - LOG.debug("Found Host {} in cluster {}", hostInCluster, host.getClusterId()); + LOG.debug("Found Host {} in cluster {}", hostInCluster, clusterId); return hostInCluster; } } } + // Try to find any Host in the zone - return resourceManager.findOneRandomRunningHostByHypervisor(Hypervisor.HypervisorType.KVM, host.getDataCenterId()); + return resourceManager.findOneRandomRunningHostByHypervisor(Hypervisor.HypervisorType.KVM, vm.getDataCenterId()); } - protected Host getVMHypervisorHost(VirtualMachine vm) { + protected Host getVMHypervisorHostForBackup(VirtualMachine vm) { Long hostId = vm.getHostId(); if (hostId == null && VirtualMachine.State.Running.equals(vm.getState())) { throw new CloudRuntimeException(String.format("Unable to find the hypervisor host for %s. Make sure the virtual machine is running", vm.getName())); @@ -158,7 +188,7 @@ public class NASBackupProvider extends AdapterBase implements BackupProvider, Co @Override public Pair takeBackup(final VirtualMachine vm, Boolean quiesceVM) { - final Host host = getVMHypervisorHost(vm); + final Host host = getVMHypervisorHostForBackup(vm); final BackupRepository backupRepository = backupRepositoryDao.findByBackupOfferingId(vm.getBackupOfferingId()); if (backupRepository == null) { @@ -179,8 +209,9 @@ public class NASBackupProvider extends AdapterBase implements BackupProvider, Co if (VirtualMachine.State.Stopped.equals(vm.getState())) { List vmVolumes = volumeDao.findByInstance(vm.getId()); vmVolumes.sort(Comparator.comparing(Volume::getDeviceId)); - List volumePaths = getVolumePaths(vmVolumes); - command.setVolumePaths(volumePaths); + Pair, List> volumePoolsAndPaths = getVolumePoolsAndPaths(vmVolumes); + command.setVolumePools(volumePoolsAndPaths.first()); + command.setVolumePaths(volumePoolsAndPaths.second()); } BackupAnswer answer; @@ -249,16 +280,16 @@ public class NASBackupProvider extends AdapterBase implements BackupProvider, Co } @Override - public boolean restoreBackupToVM(VirtualMachine vm, Backup backup, String hostIp, String dataStoreUuid) { + public Pair restoreBackupToVM(VirtualMachine vm, Backup backup, String hostIp, String dataStoreUuid) { return restoreVMBackup(vm, backup); } @Override public boolean restoreVMFromBackup(VirtualMachine vm, Backup backup) { - return restoreVMBackup(vm, backup); + return restoreVMBackup(vm, backup).first(); } - private boolean restoreVMBackup(VirtualMachine vm, Backup backup) { + private Pair restoreVMBackup(VirtualMachine vm, Backup backup) { List backedVolumesUUIDs = backup.getBackedUpVolumes().stream() .sorted(Comparator.comparingLong(Backup.VolumeInfo::getDeviceId)) .map(Backup.VolumeInfo::getUuid) @@ -271,7 +302,7 @@ public class NASBackupProvider extends AdapterBase implements BackupProvider, Co LOG.debug("Restoring vm {} from backup {} on the NAS Backup Provider", vm, backup); BackupRepository backupRepository = getBackupRepository(backup); - final Host host = getLastVMHypervisorHost(vm); + final Host host = getVMHypervisorHost(vm); RestoreBackupCommand restoreCommand = new RestoreBackupCommand(); restoreCommand.setBackupPath(backup.getExternalId()); restoreCommand.setBackupRepoType(backupRepository.getType()); @@ -279,9 +310,12 @@ public class NASBackupProvider extends AdapterBase implements BackupProvider, Co restoreCommand.setMountOptions(backupRepository.getMountOptions()); restoreCommand.setVmName(vm.getName()); restoreCommand.setBackupVolumesUUIDs(backedVolumesUUIDs); - restoreCommand.setRestoreVolumePaths(getVolumePaths(restoreVolumes)); + Pair, List> volumePoolsAndPaths = getVolumePoolsAndPaths(restoreVolumes); + restoreCommand.setRestoreVolumePools(volumePoolsAndPaths.first()); + restoreCommand.setRestoreVolumePaths(volumePoolsAndPaths.second()); restoreCommand.setVmExists(vm.getRemoved() == null); restoreCommand.setVmState(vm.getState()); + restoreCommand.setMountTimeout(NASBackupRestoreMountTimeout.value()); BackupAnswer answer; try { @@ -291,34 +325,45 @@ public class NASBackupProvider extends AdapterBase implements BackupProvider, Co } catch (OperationTimedoutException e) { throw new CloudRuntimeException("Operation to restore backup timed out, please try again"); } - return answer.getResult(); + return new Pair<>(answer.getResult(), answer.getDetails()); } - private List getVolumePaths(List volumes) { + private Pair, List> getVolumePoolsAndPaths(List volumes) { + List volumePools = new ArrayList<>(); List volumePaths = new ArrayList<>(); for (VolumeVO volume : volumes) { StoragePoolVO storagePool = primaryDataStoreDao.findById(volume.getPoolId()); if (Objects.isNull(storagePool)) { throw new CloudRuntimeException("Unable to find storage pool associated to the volume"); } - String volumePathPrefix; - if (ScopeType.HOST.equals(storagePool.getScope())) { - volumePathPrefix = storagePool.getPath(); - } else if (Storage.StoragePoolType.SharedMountPoint.equals(storagePool.getPoolType())) { - volumePathPrefix = storagePool.getPath(); - } else { - volumePathPrefix = String.format("/mnt/%s", storagePool.getUuid()); - } + + DataStore dataStore = dataStoreMgr.getDataStore(storagePool.getId(), DataStoreRole.Primary); + volumePools.add(dataStore != null ? (PrimaryDataStoreTO)dataStore.getTO() : null); + + String volumePathPrefix = getVolumePathPrefix(storagePool); volumePaths.add(String.format("%s/%s", volumePathPrefix, volume.getPath())); } - return volumePaths; + return new Pair<>(volumePools, volumePaths); + } + + private String getVolumePathPrefix(StoragePoolVO storagePool) { + String volumePathPrefix; + if (ScopeType.HOST.equals(storagePool.getScope()) || + Storage.StoragePoolType.SharedMountPoint.equals(storagePool.getPoolType()) || + Storage.StoragePoolType.RBD.equals(storagePool.getPoolType())) { + volumePathPrefix = storagePool.getPath(); + } else { + // Should be Storage.StoragePoolType.NetworkFilesystem + volumePathPrefix = String.format("/mnt/%s", storagePool.getUuid()); + } + return volumePathPrefix; } @Override public Pair restoreBackedUpVolume(Backup backup, Backup.VolumeInfo backupVolumeInfo, String hostIp, String dataStoreUuid, Pair vmNameAndState) { final VolumeVO volume = volumeDao.findByUuid(backupVolumeInfo.getUuid()); final DiskOffering diskOffering = diskOfferingDao.findByUuid(backupVolumeInfo.getDiskOfferingId()); - final StoragePoolHostVO dataStore = storagePoolHostDao.findByUuid(dataStoreUuid); + final StoragePoolVO pool = primaryDataStoreDao.findByUuid(dataStoreUuid); final HostVO hostVO = hostDao.findByIp(hostIp); LOG.debug("Restoring vm volume {} from backup {} on the NAS Backup Provider", backupVolumeInfo, backup); @@ -335,24 +380,32 @@ public class NASBackupProvider extends AdapterBase implements BackupProvider, Co restoredVolume.setUuid(volumeUUID); restoredVolume.setRemoved(null); restoredVolume.setDisplayVolume(true); - restoredVolume.setPoolId(dataStore.getPoolId()); + restoredVolume.setPoolId(pool.getId()); + restoredVolume.setPoolType(pool.getPoolType()); restoredVolume.setPath(restoredVolume.getUuid()); restoredVolume.setState(Volume.State.Copying); - restoredVolume.setFormat(Storage.ImageFormat.QCOW2); restoredVolume.setSize(backupVolumeInfo.getSize()); restoredVolume.setDiskOfferingId(diskOffering.getId()); + if (pool.getPoolType() != Storage.StoragePoolType.RBD) { + restoredVolume.setFormat(Storage.ImageFormat.QCOW2); + } else { + restoredVolume.setFormat(Storage.ImageFormat.RAW); + } RestoreBackupCommand restoreCommand = new RestoreBackupCommand(); restoreCommand.setBackupPath(backup.getExternalId()); restoreCommand.setBackupRepoType(backupRepository.getType()); restoreCommand.setBackupRepoAddress(backupRepository.getAddress()); restoreCommand.setVmName(vmNameAndState.first()); - restoreCommand.setRestoreVolumePaths(Collections.singletonList(String.format("%s/%s", dataStore.getLocalPath(), volumeUUID))); + restoreCommand.setRestoreVolumePaths(Collections.singletonList(String.format("%s/%s", getVolumePathPrefix(pool), volumeUUID))); + DataStore dataStore = dataStoreMgr.getDataStore(pool.getId(), DataStoreRole.Primary); + restoreCommand.setRestoreVolumePools(Collections.singletonList(dataStore != null ? (PrimaryDataStoreTO)dataStore.getTO() : null)); restoreCommand.setDiskType(backupVolumeInfo.getType().name().toLowerCase(Locale.ROOT)); restoreCommand.setMountOptions(backupRepository.getMountOptions()); restoreCommand.setVmExists(null); restoreCommand.setVmState(vmNameAndState.second()); restoreCommand.setRestoreVolumeUUID(backupVolumeInfo.getUuid()); + restoreCommand.setMountTimeout(NASBackupRestoreMountTimeout.value()); BackupAnswer answer; try { @@ -398,7 +451,7 @@ public class NASBackupProvider extends AdapterBase implements BackupProvider, Co final Host host; final VirtualMachine vm = vmInstanceDao.findByIdIncludingRemoved(backup.getVmId()); if (vm != null) { - host = getLastVMHypervisorHost(vm); + host = getVMHypervisorHost(vm); } else { host = resourceManager.findOneRandomRunningHostByHypervisor(Hypervisor.HypervisorType.KVM, backup.getZoneId()); } @@ -513,9 +566,19 @@ public class NASBackupProvider extends AdapterBase implements BackupProvider, Co return true; } + @Override + public Boolean crossZoneInstanceCreationEnabled(BackupOffering backupOffering) { + final BackupRepository backupRepository = backupRepositoryDao.findByBackupOfferingId(backupOffering.getId()); + if (backupRepository == null) { + throw new CloudRuntimeException("Backup repository not found for the backup offering" + backupOffering.getName()); + } + return Boolean.TRUE.equals(backupRepository.crossZoneInstanceCreationEnabled()); + } + @Override public ConfigKey[] getConfigKeys() { return new ConfigKey[]{ + NASBackupRestoreMountTimeout }; } diff --git a/plugins/backup/nas/src/test/java/org/apache/cloudstack/backup/NASBackupProviderTest.java b/plugins/backup/nas/src/test/java/org/apache/cloudstack/backup/NASBackupProviderTest.java index d6f29dc1aac..7540cabbbf5 100644 --- a/plugins/backup/nas/src/test/java/org/apache/cloudstack/backup/NASBackupProviderTest.java +++ b/plugins/backup/nas/src/test/java/org/apache/cloudstack/backup/NASBackupProviderTest.java @@ -21,11 +21,9 @@ import static org.mockito.Mockito.mock; import java.util.Collections; import java.util.List; +import java.util.Objects; import java.util.Optional; -import org.apache.cloudstack.backup.dao.BackupDao; -import org.apache.cloudstack.backup.dao.BackupRepositoryDao; -import org.apache.cloudstack.backup.dao.BackupOfferingDao; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; @@ -39,6 +37,7 @@ import org.springframework.test.util.ReflectionTestUtils; import com.cloud.agent.AgentManager; import com.cloud.exception.AgentUnavailableException; import com.cloud.exception.OperationTimedoutException; +import com.cloud.host.Host; import com.cloud.host.HostVO; import com.cloud.host.Status; import com.cloud.host.dao.HostDao; @@ -51,6 +50,12 @@ import com.cloud.utils.Pair; import com.cloud.vm.VMInstanceVO; import com.cloud.vm.dao.VMInstanceDao; +import org.apache.cloudstack.backup.dao.BackupDao; +import org.apache.cloudstack.backup.dao.BackupRepositoryDao; +import org.apache.cloudstack.backup.dao.BackupOfferingDao; +import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao; +import org.apache.cloudstack.storage.datastore.db.StoragePoolVO; + @RunWith(MockitoJUnitRunner.class) public class NASBackupProviderTest { @Spy @@ -84,6 +89,9 @@ public class NASBackupProviderTest { @Mock private ResourceManager resourceManager; + @Mock + private PrimaryDataStoreDao storagePoolDao; + @Test public void testDeleteBackup() throws OperationTimedoutException, AgentUnavailableException { Long hostId = 1L; @@ -94,7 +102,7 @@ public class NASBackupProviderTest { ReflectionTestUtils.setField(backup, "id", 1L); BackupRepositoryVO backupRepository = new BackupRepositoryVO(1L, "nas", "test-repo", - "nfs", "address", "sync", 1024L); + "nfs", "address", "sync", 1024L, null); VMInstanceVO vm = mock(VMInstanceVO.class); Mockito.when(vm.getLastHostId()).thenReturn(hostId); @@ -113,7 +121,7 @@ public class NASBackupProviderTest { @Test public void testSyncBackupStorageStats() throws AgentUnavailableException, OperationTimedoutException { BackupRepositoryVO backupRepository = new BackupRepositoryVO(1L, "nas", "test-repo", - "nfs", "address", "sync", 1024L); + "nfs", "address", "sync", 1024L, null); HostVO host = mock(HostVO.class); Mockito.when(resourceManager.findOneRandomRunningHostByHypervisor(Hypervisor.HypervisorType.KVM, 1L)).thenReturn(host); @@ -132,7 +140,7 @@ public class NASBackupProviderTest { @Test public void testListBackupOfferings() { BackupRepositoryVO backupRepository = new BackupRepositoryVO(1L, "nas", "test-repo", - "nfs", "address", "sync", 1024L); + "nfs", "address", "sync", 1024L, null); ReflectionTestUtils.setField(backupRepository, "uuid", "uuid"); Mockito.when(backupRepositoryDao.listByZoneAndProvider(1L, "nas")).thenReturn(Collections.singletonList(backupRepository)); @@ -146,11 +154,11 @@ public class NASBackupProviderTest { @Test public void testGetBackupStorageStats() { BackupRepositoryVO backupRepository1 = new BackupRepositoryVO(1L, "nas", "test-repo", - "nfs", "address", "sync", 1000L); + "nfs", "address", "sync", 1000L, null); backupRepository1.setUsedBytes(500L); BackupRepositoryVO backupRepository2 = new BackupRepositoryVO(1L, "nas", "test-repo", - "nfs", "address", "sync", 2000L); + "nfs", "address", "sync", 2000L, null); backupRepository2.setUsedBytes(600L); Mockito.when(backupRepositoryDao.listByZoneAndProvider(1L, "nas")) @@ -227,4 +235,118 @@ public class NASBackupProviderTest { Mockito.verify(backupDao).update(Mockito.anyLong(), Mockito.any(BackupVO.class)); Mockito.verify(agentManager).send(anyLong(), Mockito.any(TakeBackupCommand.class)); } + + @Test + public void testGetVMHypervisorHost() { + Long hostId = 1L; + Long vmId = 1L; + Long zoneId = 1L; + + VMInstanceVO vm = mock(VMInstanceVO.class); + Mockito.when(vm.getLastHostId()).thenReturn(hostId); + + HostVO host = mock(HostVO.class); + Mockito.when(host.getId()).thenReturn(hostId); + Mockito.when(host.getStatus()).thenReturn(Status.Up); + Mockito.when(hostDao.findById(hostId)).thenReturn(host); + + Host result = nasBackupProvider.getVMHypervisorHost(vm); + + Assert.assertNotNull(result); + Assert.assertTrue(Objects.equals(hostId, result.getId())); + Mockito.verify(hostDao).findById(hostId); + } + + @Test + public void testGetVMHypervisorHostWithHostDown() { + Long hostId = 1L; + Long clusterId = 2L; + Long vmId = 1L; + Long zoneId = 1L; + + VMInstanceVO vm = mock(VMInstanceVO.class); + Mockito.when(vm.getLastHostId()).thenReturn(hostId); + + HostVO downHost = mock(HostVO.class); + Mockito.when(downHost.getStatus()).thenReturn(Status.Down); + Mockito.when(downHost.getClusterId()).thenReturn(clusterId); + Mockito.when(hostDao.findById(hostId)).thenReturn(downHost); + + HostVO upHostInCluster = mock(HostVO.class); + Mockito.when(upHostInCluster.getId()).thenReturn(3L); + Mockito.when(upHostInCluster.getStatus()).thenReturn(Status.Up); + Mockito.when(hostDao.findHypervisorHostInCluster(clusterId)).thenReturn(List.of(upHostInCluster)); + + Host result = nasBackupProvider.getVMHypervisorHost(vm); + + Assert.assertNotNull(result); + Assert.assertTrue(Objects.equals(Long.valueOf(3L), result.getId())); + Mockito.verify(hostDao).findById(hostId); + Mockito.verify(hostDao).findHypervisorHostInCluster(clusterId); + } + + @Test + public void testGetVMHypervisorHostWithUpHostViaRootVolumeCluster() { + Long vmId = 1L; + Long zoneId = 1L; + Long clusterId = 2L; + Long poolId = 3L; + + VMInstanceVO vm = mock(VMInstanceVO.class); + Mockito.when(vm.getLastHostId()).thenReturn(null); + Mockito.when(vm.getId()).thenReturn(vmId); + + VolumeVO rootVolume = mock(VolumeVO.class); + Mockito.when(rootVolume.getPoolId()).thenReturn(poolId); + Mockito.when(volumeDao.getInstanceRootVolume(vmId)).thenReturn(rootVolume); + + StoragePoolVO storagePool = mock(StoragePoolVO.class); + Mockito.when(storagePool.getClusterId()).thenReturn(clusterId); + Mockito.when(storagePoolDao.findById(poolId)).thenReturn(storagePool); + + HostVO upHostInCluster = mock(HostVO.class); + Mockito.when(upHostInCluster.getId()).thenReturn(4L); + Mockito.when(upHostInCluster.getStatus()).thenReturn(Status.Up); + Mockito.when(hostDao.findHypervisorHostInCluster(clusterId)).thenReturn(List.of(upHostInCluster)); + + Host result = nasBackupProvider.getVMHypervisorHost(vm); + + Assert.assertNotNull(result); + Assert.assertTrue(Objects.equals(Long.valueOf(4L), result.getId())); + Mockito.verify(volumeDao).getInstanceRootVolume(vmId); + Mockito.verify(storagePoolDao).findById(poolId); + Mockito.verify(hostDao).findHypervisorHostInCluster(clusterId); + } + + @Test + public void testGetVMHypervisorHostFallbackToZoneWideKVMHost() { + Long hostId = 1L; + Long clusterId = 2L; + Long vmId = 1L; + Long zoneId = 1L; + + VMInstanceVO vm = mock(VMInstanceVO.class); + Mockito.when(vm.getLastHostId()).thenReturn(hostId); + Mockito.when(vm.getDataCenterId()).thenReturn(zoneId); + + HostVO downHost = mock(HostVO.class); + Mockito.when(downHost.getStatus()).thenReturn(Status.Down); + Mockito.when(downHost.getClusterId()).thenReturn(clusterId); + Mockito.when(hostDao.findById(hostId)).thenReturn(downHost); + + Mockito.when(hostDao.findHypervisorHostInCluster(clusterId)).thenReturn(Collections.emptyList()); + + HostVO fallbackHost = mock(HostVO.class); + Mockito.when(fallbackHost.getId()).thenReturn(5L); + Mockito.when(resourceManager.findOneRandomRunningHostByHypervisor(Hypervisor.HypervisorType.KVM, zoneId)) + .thenReturn(fallbackHost); + + Host result = nasBackupProvider.getVMHypervisorHost(vm); + + Assert.assertNotNull(result); + Assert.assertTrue(Objects.equals(Long.valueOf(5L), result.getId())); + Mockito.verify(hostDao).findById(hostId); + Mockito.verify(hostDao).findHypervisorHostInCluster(clusterId); + Mockito.verify(resourceManager).findOneRandomRunningHostByHypervisor(Hypervisor.HypervisorType.KVM, zoneId); + } } diff --git a/plugins/backup/networker/pom.xml b/plugins/backup/networker/pom.xml index a8a2b090a11..cad2b345435 100644 --- a/plugins/backup/networker/pom.xml +++ b/plugins/backup/networker/pom.xml @@ -25,7 +25,7 @@ cloudstack-plugins org.apache.cloudstack - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT ../../pom.xml diff --git a/plugins/backup/networker/src/main/java/org/apache/cloudstack/backup/NetworkerBackupProvider.java b/plugins/backup/networker/src/main/java/org/apache/cloudstack/backup/NetworkerBackupProvider.java index f39aedb55f2..66b633e11a9 100644 --- a/plugins/backup/networker/src/main/java/org/apache/cloudstack/backup/NetworkerBackupProvider.java +++ b/plugins/backup/networker/src/main/java/org/apache/cloudstack/backup/NetworkerBackupProvider.java @@ -158,6 +158,11 @@ public class NetworkerBackupProvider extends AdapterBase implements BackupProvid }; } + @Override + public Boolean crossZoneInstanceCreationEnabled(BackupOffering backupOffering) { + return false; + } + @Override public String getName() { return "networker"; @@ -630,7 +635,7 @@ public class NetworkerBackupProvider extends AdapterBase implements BackupProvid public boolean willDeleteBackupsOnOfferingRemoval() { return false; } @Override - public boolean restoreBackupToVM(VirtualMachine vm, Backup backup, String hostIp, String dataStoreUuid) { - return true; + public Pair restoreBackupToVM(VirtualMachine vm, Backup backup, String hostIp, String dataStoreUuid) { + return new Pair<>(true, null); } } diff --git a/plugins/backup/veeam/pom.xml b/plugins/backup/veeam/pom.xml index 0626c5f8e84..a2dcbd1d348 100644 --- a/plugins/backup/veeam/pom.xml +++ b/plugins/backup/veeam/pom.xml @@ -23,7 +23,7 @@ cloudstack-plugins org.apache.cloudstack - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT ../../pom.xml diff --git a/plugins/backup/veeam/src/main/java/org/apache/cloudstack/backup/VeeamBackupProvider.java b/plugins/backup/veeam/src/main/java/org/apache/cloudstack/backup/VeeamBackupProvider.java index c81c5d34ea2..39970dab342 100644 --- a/plugins/backup/veeam/src/main/java/org/apache/cloudstack/backup/VeeamBackupProvider.java +++ b/plugins/backup/veeam/src/main/java/org/apache/cloudstack/backup/VeeamBackupProvider.java @@ -337,11 +337,11 @@ public class VeeamBackupProvider extends AdapterBase implements BackupProvider, } @Override - public boolean restoreBackupToVM(VirtualMachine vm, Backup backup, String hostIp, String dataStoreUuid) { + public Pair restoreBackupToVM(VirtualMachine vm, Backup backup, String hostIp, String dataStoreUuid) { final Long zoneId = backup.getZoneId(); final String restorePointId = backup.getExternalId(); final String restoreLocation = vm.getInstanceName(); - return getClient(zoneId).restoreVMToDifferentLocation(restorePointId, restoreLocation, hostIp, dataStoreUuid).first(); + return getClient(zoneId).restoreVMToDifferentLocation(restorePointId, restoreLocation, hostIp, dataStoreUuid); } @Override @@ -358,6 +358,11 @@ public class VeeamBackupProvider extends AdapterBase implements BackupProvider, public void syncBackupStorageStats(Long zoneId) { } + @Override + public Boolean crossZoneInstanceCreationEnabled(BackupOffering backupOffering) { + return false; + } + @Override public String getConfigComponentName() { return BackupService.class.getSimpleName(); diff --git a/plugins/ca/root-ca/pom.xml b/plugins/ca/root-ca/pom.xml index 1cc97f88e13..2224ae06c85 100644 --- a/plugins/ca/root-ca/pom.xml +++ b/plugins/ca/root-ca/pom.xml @@ -24,7 +24,7 @@ org.apache.cloudstack cloudstack-plugins - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT ../../pom.xml diff --git a/plugins/database/mysql-ha/pom.xml b/plugins/database/mysql-ha/pom.xml index c2ac585dce2..eb1b1d571f1 100644 --- a/plugins/database/mysql-ha/pom.xml +++ b/plugins/database/mysql-ha/pom.xml @@ -24,7 +24,7 @@ org.apache.cloudstack cloudstack-plugins - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT ../../pom.xml diff --git a/plugins/database/quota/pom.xml b/plugins/database/quota/pom.xml index b6910079f95..52645385aab 100644 --- a/plugins/database/quota/pom.xml +++ b/plugins/database/quota/pom.xml @@ -24,7 +24,7 @@ org.apache.cloudstack cloudstack-plugins - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT ../../pom.xml diff --git a/plugins/database/quota/src/main/java/org/apache/cloudstack/api/response/QuotaResponseBuilderImpl.java b/plugins/database/quota/src/main/java/org/apache/cloudstack/api/response/QuotaResponseBuilderImpl.java index 7a987df0a35..42e94c1c017 100644 --- a/plugins/database/quota/src/main/java/org/apache/cloudstack/api/response/QuotaResponseBuilderImpl.java +++ b/plugins/database/quota/src/main/java/org/apache/cloudstack/api/response/QuotaResponseBuilderImpl.java @@ -80,8 +80,8 @@ import org.apache.cloudstack.quota.dao.QuotaCreditsDao; import org.apache.cloudstack.quota.dao.QuotaEmailConfigurationDao; import org.apache.cloudstack.quota.dao.QuotaEmailTemplatesDao; import org.apache.cloudstack.quota.dao.QuotaTariffDao; -import org.apache.cloudstack.quota.vo.QuotaAccountVO; import org.apache.cloudstack.quota.dao.QuotaUsageDao; +import org.apache.cloudstack.quota.vo.QuotaAccountVO; import org.apache.cloudstack.quota.vo.QuotaBalanceVO; import org.apache.cloudstack.quota.vo.QuotaCreditsVO; import org.apache.cloudstack.quota.vo.QuotaEmailConfigurationVO; @@ -90,15 +90,17 @@ import org.apache.cloudstack.quota.vo.QuotaTariffVO; import org.apache.cloudstack.quota.vo.QuotaUsageVO; import org.apache.cloudstack.utils.jsinterpreter.JsInterpreter; import org.apache.cloudstack.utils.reflectiontostringbuilderutils.ReflectionToStringBuilderUtils; +import org.apache.commons.lang3.ObjectUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.reflect.FieldUtils; -import org.apache.commons.lang3.ObjectUtils; -import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.springframework.stereotype.Component; import com.cloud.domain.DomainVO; import com.cloud.domain.dao.DomainDao; +import com.cloud.event.ActionEvent; +import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; import com.cloud.user.Account; import com.cloud.user.AccountManager; @@ -107,8 +109,6 @@ import com.cloud.user.dao.AccountDao; import com.cloud.user.dao.UserDao; import com.cloud.utils.Pair; import com.cloud.utils.db.Filter; -import com.cloud.event.ActionEvent; -import com.cloud.event.EventTypes; @Component public class QuotaResponseBuilderImpl implements QuotaResponseBuilder { @@ -150,6 +150,11 @@ public class QuotaResponseBuilderImpl implements QuotaResponseBuilder { private final Class[] assignableClasses = {GenericPresetVariable.class, ComputingResources.class}; + protected void checkActivationRulesAllowed(String activationRule) { + if (!_quotaService.isJsInterpretationEnabled() && StringUtils.isNotEmpty(activationRule)) { + throw new PermissionDeniedException("Quota Tariff Activation Rule cannot be set, as Javascript interpretation is disabled in the configuration."); + } + } @Override public QuotaTariffResponse createQuotaTariffResponse(QuotaTariffVO tariff, boolean returnActivationRule) { @@ -452,6 +457,8 @@ public class QuotaResponseBuilderImpl implements QuotaResponseBuilder { throw new InvalidParameterValueException(String.format("There is no quota tariffs with name [%s].", name)); } + checkActivationRulesAllowed(activationRule); + Date currentQuotaTariffStartDate = currentQuotaTariff.getEffectiveOn(); currentQuotaTariff.setRemoved(now); @@ -706,6 +713,8 @@ public class QuotaResponseBuilderImpl implements QuotaResponseBuilder { throw new InvalidParameterValueException(String.format("A quota tariff with name [%s] already exist.", name)); } + checkActivationRulesAllowed(activationRule); + if (startDate.compareTo(now) < 0) { throw new InvalidParameterValueException(String.format("The value passed as Quota tariff's start date is in the past: [%s]. " + "Please, inform a date in the future or do not pass the parameter to use the current date and time.", startDate)); diff --git a/plugins/database/quota/src/main/java/org/apache/cloudstack/quota/QuotaService.java b/plugins/database/quota/src/main/java/org/apache/cloudstack/quota/QuotaService.java index 8f3c34982c0..f6a34e01be8 100644 --- a/plugins/database/quota/src/main/java/org/apache/cloudstack/quota/QuotaService.java +++ b/plugins/database/quota/src/main/java/org/apache/cloudstack/quota/QuotaService.java @@ -16,15 +16,15 @@ //under the License. package org.apache.cloudstack.quota; -import com.cloud.user.AccountVO; -import com.cloud.utils.component.PluggableService; +import java.math.BigDecimal; +import java.util.Date; +import java.util.List; import org.apache.cloudstack.quota.vo.QuotaBalanceVO; import org.apache.cloudstack.quota.vo.QuotaUsageVO; -import java.math.BigDecimal; -import java.util.Date; -import java.util.List; +import com.cloud.user.AccountVO; +import com.cloud.utils.component.PluggableService; public interface QuotaService extends PluggableService { @@ -40,4 +40,6 @@ public interface QuotaService extends PluggableService { boolean saveQuotaAccount(AccountVO account, BigDecimal aggrUsage, Date endDate); + boolean isJsInterpretationEnabled(); + } diff --git a/plugins/database/quota/src/main/java/org/apache/cloudstack/quota/QuotaServiceImpl.java b/plugins/database/quota/src/main/java/org/apache/cloudstack/quota/QuotaServiceImpl.java index e02f260c142..f455c3cba14 100644 --- a/plugins/database/quota/src/main/java/org/apache/cloudstack/quota/QuotaServiceImpl.java +++ b/plugins/database/quota/src/main/java/org/apache/cloudstack/quota/QuotaServiceImpl.java @@ -62,6 +62,7 @@ import com.cloud.configuration.Config; import com.cloud.domain.dao.DomainDao; import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.PermissionDeniedException; +import com.cloud.server.ManagementService; import com.cloud.user.Account; import com.cloud.user.AccountVO; import com.cloud.user.dao.AccountDao; @@ -88,6 +89,8 @@ public class QuotaServiceImpl extends ManagerBase implements QuotaService, Confi private TimeZone _usageTimezone; + private boolean jsInterpretationEnabled = false; + public QuotaServiceImpl() { super(); } @@ -99,6 +102,8 @@ public class QuotaServiceImpl extends ManagerBase implements QuotaService, Confi String timeZoneStr = ObjectUtils.defaultIfNull(_configDao.getValue(Config.UsageAggregationTimezone.toString()), "GMT"); _usageTimezone = TimeZone.getTimeZone(timeZoneStr); + jsInterpretationEnabled = ManagementService.JsInterpretationEnabled.value(); + return true; } @@ -288,4 +293,8 @@ public class QuotaServiceImpl extends ManagerBase implements QuotaService, Confi } } + @Override + public boolean isJsInterpretationEnabled() { + return jsInterpretationEnabled; + } } diff --git a/plugins/dedicated-resources/pom.xml b/plugins/dedicated-resources/pom.xml index 31ce6da7e46..557668661f3 100644 --- a/plugins/dedicated-resources/pom.xml +++ b/plugins/dedicated-resources/pom.xml @@ -24,7 +24,7 @@ org.apache.cloudstack cloudstack-plugins - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT ../pom.xml diff --git a/plugins/deployment-planners/implicit-dedication/pom.xml b/plugins/deployment-planners/implicit-dedication/pom.xml index 322d4a7aa75..c33d6d07293 100644 --- a/plugins/deployment-planners/implicit-dedication/pom.xml +++ b/plugins/deployment-planners/implicit-dedication/pom.xml @@ -24,7 +24,7 @@ org.apache.cloudstack cloudstack-plugins - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT ../../pom.xml diff --git a/plugins/deployment-planners/user-concentrated-pod/pom.xml b/plugins/deployment-planners/user-concentrated-pod/pom.xml index 258d11e0c35..20420fbb080 100644 --- a/plugins/deployment-planners/user-concentrated-pod/pom.xml +++ b/plugins/deployment-planners/user-concentrated-pod/pom.xml @@ -24,7 +24,7 @@ org.apache.cloudstack cloudstack-plugins - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT ../../pom.xml diff --git a/plugins/deployment-planners/user-dispersing/pom.xml b/plugins/deployment-planners/user-dispersing/pom.xml index b18281a1cd4..85c839ceaca 100644 --- a/plugins/deployment-planners/user-dispersing/pom.xml +++ b/plugins/deployment-planners/user-dispersing/pom.xml @@ -24,7 +24,7 @@ org.apache.cloudstack cloudstack-plugins - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT ../../pom.xml diff --git a/plugins/drs/cluster/balanced/pom.xml b/plugins/drs/cluster/balanced/pom.xml index 51cbfc632b1..497dfcbede1 100644 --- a/plugins/drs/cluster/balanced/pom.xml +++ b/plugins/drs/cluster/balanced/pom.xml @@ -27,7 +27,7 @@ org.apache.cloudstack cloudstack-plugins - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT ../../../pom.xml diff --git a/plugins/drs/cluster/condensed/pom.xml b/plugins/drs/cluster/condensed/pom.xml index 38a9cd48eab..6e7c33ef55d 100644 --- a/plugins/drs/cluster/condensed/pom.xml +++ b/plugins/drs/cluster/condensed/pom.xml @@ -27,7 +27,7 @@ org.apache.cloudstack cloudstack-plugins - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT ../../../pom.xml diff --git a/plugins/event-bus/inmemory/pom.xml b/plugins/event-bus/inmemory/pom.xml index d6a3a02ec2c..5eadc3673f3 100644 --- a/plugins/event-bus/inmemory/pom.xml +++ b/plugins/event-bus/inmemory/pom.xml @@ -24,7 +24,7 @@ org.apache.cloudstack cloudstack-plugins - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT ../../pom.xml diff --git a/plugins/event-bus/kafka/pom.xml b/plugins/event-bus/kafka/pom.xml index 5784434735f..c57572533ad 100644 --- a/plugins/event-bus/kafka/pom.xml +++ b/plugins/event-bus/kafka/pom.xml @@ -24,7 +24,7 @@ org.apache.cloudstack cloudstack-plugins - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT ../../pom.xml diff --git a/plugins/event-bus/rabbitmq/pom.xml b/plugins/event-bus/rabbitmq/pom.xml index d5037b13408..3012ac1057a 100644 --- a/plugins/event-bus/rabbitmq/pom.xml +++ b/plugins/event-bus/rabbitmq/pom.xml @@ -24,7 +24,7 @@ org.apache.cloudstack cloudstack-plugins - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT ../../pom.xml diff --git a/plugins/event-bus/webhook/pom.xml b/plugins/event-bus/webhook/pom.xml index a2f915c9e5f..cb19b224ce8 100644 --- a/plugins/event-bus/webhook/pom.xml +++ b/plugins/event-bus/webhook/pom.xml @@ -24,7 +24,7 @@ org.apache.cloudstack cloudstack-plugins - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT ../../pom.xml diff --git a/plugins/ha-planners/skip-heurestics/pom.xml b/plugins/ha-planners/skip-heurestics/pom.xml index d40f3fac648..43f3abf9cb1 100644 --- a/plugins/ha-planners/skip-heurestics/pom.xml +++ b/plugins/ha-planners/skip-heurestics/pom.xml @@ -24,7 +24,7 @@ org.apache.cloudstack cloudstack-plugins - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT ../../pom.xml diff --git a/plugins/host-allocators/random/pom.xml b/plugins/host-allocators/random/pom.xml index 28b4df56ec2..061caf1573f 100644 --- a/plugins/host-allocators/random/pom.xml +++ b/plugins/host-allocators/random/pom.xml @@ -24,7 +24,7 @@ org.apache.cloudstack cloudstack-plugins - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT ../../pom.xml diff --git a/plugins/hypervisors/baremetal/pom.xml b/plugins/hypervisors/baremetal/pom.xml index cefb0cb1d11..fc4803b7902 100755 --- a/plugins/hypervisors/baremetal/pom.xml +++ b/plugins/hypervisors/baremetal/pom.xml @@ -22,7 +22,7 @@ org.apache.cloudstack cloudstack-plugins - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT ../../pom.xml cloud-plugin-hypervisor-baremetal diff --git a/plugins/hypervisors/external/pom.xml b/plugins/hypervisors/external/pom.xml index ca5ca7b9b82..1c581f3c0e5 100644 --- a/plugins/hypervisors/external/pom.xml +++ b/plugins/hypervisors/external/pom.xml @@ -22,7 +22,7 @@ org.apache.cloudstack cloudstack-plugins - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT ../../pom.xml cloud-plugin-hypervisor-external diff --git a/plugins/hypervisors/external/src/main/java/org/apache/cloudstack/hypervisor/external/provisioner/ExternalPathPayloadProvisioner.java b/plugins/hypervisors/external/src/main/java/org/apache/cloudstack/hypervisor/external/provisioner/ExternalPathPayloadProvisioner.java index 5a1632ce977..92205b13c6f 100644 --- a/plugins/hypervisors/external/src/main/java/org/apache/cloudstack/hypervisor/external/provisioner/ExternalPathPayloadProvisioner.java +++ b/plugins/hypervisors/external/src/main/java/org/apache/cloudstack/hypervisor/external/provisioner/ExternalPathPayloadProvisioner.java @@ -54,8 +54,11 @@ import org.apache.cloudstack.framework.extensions.manager.ExtensionsManager; import org.apache.cloudstack.utils.security.DigestHelper; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; +import org.apache.commons.lang3.ObjectUtils; import com.cloud.agent.AgentManager; +import com.cloud.agent.api.GetExternalConsoleAnswer; +import com.cloud.agent.api.GetExternalConsoleCommand; import com.cloud.agent.api.HostVmStateReportEntry; import com.cloud.agent.api.PrepareExternalProvisioningAnswer; import com.cloud.agent.api.PrepareExternalProvisioningCommand; @@ -85,13 +88,11 @@ import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.json.JsonMergeUtil; import com.cloud.utils.script.Script; import com.cloud.vm.UserVmVO; -import com.cloud.vm.VMInstanceVO; import com.cloud.vm.VirtualMachine; import com.cloud.vm.VirtualMachineProfile; import com.cloud.vm.VirtualMachineProfileImpl; import com.cloud.vm.VmDetailConstants; import com.cloud.vm.dao.UserVmDao; -import com.cloud.vm.dao.VMInstanceDao; import com.google.gson.JsonObject; import com.google.gson.JsonParser; @@ -102,10 +103,11 @@ public class ExternalPathPayloadProvisioner extends ManagerBase implements Exter BASE_EXTERNAL_PROVISIONER_SCRIPTS_DIR + "/provisioner.sh"; private static final String PROPERTIES_FILE = "server.properties"; + private static final String EXTENSIONS = "extensions"; private static final String EXTENSIONS_DEPLOYMENT_MODE_NAME = "extensions.deployment.mode"; private static final String EXTENSIONS_DIRECTORY_PROD = "/usr/share/cloudstack-management/extensions"; - private static final String EXTENSIONS_DATA_DIRECTORY_PROD = "/var/lib/cloudstack/management/extensions"; - private static final String EXTENSIONS_DIRECTORY_DEV = "extensions"; + private static final String EXTENSIONS_DATA_DIRECTORY_PROD = System.getProperty("user.home") + File.separator + EXTENSIONS; + private static final String EXTENSIONS_DIRECTORY_DEV = EXTENSIONS; private static final String EXTENSIONS_DATA_DIRECTORY_DEV = "client/target/extensions-data"; @Inject @@ -114,9 +116,6 @@ public class ExternalPathPayloadProvisioner extends ManagerBase implements Exter @Inject HostDao hostDao; - @Inject - VMInstanceDao vmInstanceDao; - @Inject HypervisorGuruManager hypervisorGuruManager; @@ -140,6 +139,10 @@ public class ExternalPathPayloadProvisioner extends ManagerBase implements Exter protected Map loadAccessDetails(Map> externalDetails, VirtualMachineTO virtualMachineTO) { Map modifiedDetails = new HashMap<>(); + if (MapUtils.isNotEmpty(externalDetails) && externalDetails.containsKey(ApiConstants.CALLER)) { + modifiedDetails.put(ApiConstants.CALLER, externalDetails.get(ApiConstants.CALLER)); + externalDetails.remove(ApiConstants.CALLER); + } if (MapUtils.isNotEmpty(externalDetails)) { modifiedDetails.put(ApiConstants.EXTERNAL_DETAILS, externalDetails); } @@ -208,6 +211,22 @@ public class ExternalPathPayloadProvisioner extends ManagerBase implements Exter logger.info("Extensions data directory path: {}", extensionsDataDirectory); } + protected VirtualMachineTO getVirtualMachineTO(VirtualMachine vm) { + if (vm == null) { + return null; + } + final HypervisorGuru hvGuru = hypervisorGuruManager.getGuru(Hypervisor.HypervisorType.External); + VirtualMachineProfile profile = new VirtualMachineProfileImpl(vm); + return hvGuru.implement(profile); + } + + protected String getSanitizedJsonStringForLog(String json) { + if (StringUtils.isBlank(json)) { + return json; + } + return json.replaceAll("(\"password\"\\s*:\\s*\")([^\"]*)(\")", "$1****$3"); + } + private String getServerProperty(String name) { Properties props = propertiesRef.get(); if (props == null) { @@ -289,12 +308,20 @@ public class ExternalPathPayloadProvisioner extends ManagerBase implements Exter } } + protected String getExtensionConfigureError(String extensionName, String hostName) { + StringBuilder sb = new StringBuilder("Extension: ").append(extensionName).append(" not configured"); + if (StringUtils.isNotBlank(hostName)) { + sb.append(" for host: ").append(hostName); + } + return sb.toString(); + } + @Override - public PrepareExternalProvisioningAnswer prepareExternalProvisioning(String hostGuid, + public PrepareExternalProvisioningAnswer prepareExternalProvisioning(String hostName, String extensionName, String extensionRelativePath, PrepareExternalProvisioningCommand cmd) { String extensionPath = getExtensionCheckedPath(extensionName, extensionRelativePath); if (StringUtils.isEmpty(extensionPath)) { - return new PrepareExternalProvisioningAnswer(cmd, false, "Extension not configured"); + return new PrepareExternalProvisioningAnswer(cmd, false, getExtensionConfigureError(extensionName, hostName)); } VirtualMachineTO vmTO = cmd.getVirtualMachineTO(); String vmUUID = vmTO.getUuid(); @@ -322,11 +349,11 @@ public class ExternalPathPayloadProvisioner extends ManagerBase implements Exter } @Override - public StartAnswer startInstance(String hostGuid, String extensionName, String extensionRelativePath, + public StartAnswer startInstance(String hostName, String extensionName, String extensionRelativePath, StartCommand cmd) { String extensionPath = getExtensionCheckedPath(extensionName, extensionRelativePath); if (StringUtils.isEmpty(extensionPath)) { - return new StartAnswer(cmd, "Extension not configured"); + return new StartAnswer(cmd, getExtensionConfigureError(extensionName, hostName)); } VirtualMachineTO virtualMachineTO = cmd.getVirtualMachine(); Map accessDetails = loadAccessDetails(cmd.getExternalDetails(), virtualMachineTO); @@ -366,11 +393,11 @@ public class ExternalPathPayloadProvisioner extends ManagerBase implements Exter } @Override - public StopAnswer stopInstance(String hostGuid, String extensionName, String extensionRelativePath, + public StopAnswer stopInstance(String hostName, String extensionName, String extensionRelativePath, StopCommand cmd) { String extensionPath = getExtensionCheckedPath(extensionName, extensionRelativePath); if (StringUtils.isEmpty(extensionPath)) { - return new StopAnswer(cmd, "Extension not configured", false); + return new StopAnswer(cmd, getExtensionConfigureError(extensionName, hostName), false); } logger.debug("Executing stop command on the external provisioner"); VirtualMachineTO virtualMachineTO = cmd.getVirtualMachine(); @@ -387,13 +414,12 @@ public class ExternalPathPayloadProvisioner extends ManagerBase implements Exter } @Override - public RebootAnswer rebootInstance(String hostGuid, String extensionName, String extensionRelativePath, + public RebootAnswer rebootInstance(String hostName, String extensionName, String extensionRelativePath, RebootCommand cmd) { String extensionPath = getExtensionCheckedPath(extensionName, extensionRelativePath); if (StringUtils.isEmpty(extensionPath)) { - return new RebootAnswer(cmd, "Extension not configured", false); + return new RebootAnswer(cmd, getExtensionConfigureError(extensionName, hostName), false); } - logger.debug("Executing reboot command using IPMI in the external provisioner"); VirtualMachineTO virtualMachineTO = cmd.getVirtualMachine(); String vmUUID = virtualMachineTO.getUuid(); logger.debug("Executing reboot command in the external system for the VM {}", vmUUID); @@ -408,11 +434,11 @@ public class ExternalPathPayloadProvisioner extends ManagerBase implements Exter } @Override - public StopAnswer expungeInstance(String hostGuid, String extensionName, String extensionRelativePath, + public StopAnswer expungeInstance(String hostName, String extensionName, String extensionRelativePath, StopCommand cmd) { String extensionPath = getExtensionCheckedPath(extensionName, extensionRelativePath); if (StringUtils.isEmpty(extensionPath)) { - return new StopAnswer(cmd, "Extension not configured", false); + return new StopAnswer(cmd, getExtensionConfigureError(extensionName, hostName), false); } VirtualMachineTO virtualMachineTO = cmd.getVirtualMachine(); String vmUUID = virtualMachineTO.getUuid(); @@ -456,24 +482,65 @@ public class ExternalPathPayloadProvisioner extends ManagerBase implements Exter } @Override - public RunCustomActionAnswer runCustomAction(String hostGuid, String extensionName, + public GetExternalConsoleAnswer getInstanceConsole(String hostName, String extensionName, + String extensionRelativePath, GetExternalConsoleCommand cmd) { + String extensionPath = getExtensionCheckedPath(extensionName, extensionRelativePath); + if (StringUtils.isEmpty(extensionPath)) { + return new GetExternalConsoleAnswer(cmd, getExtensionConfigureError(extensionName, hostName)); + } + VirtualMachineTO virtualMachineTO = cmd.getVirtualMachine(); + String vmUUID = virtualMachineTO.getUuid(); + logger.debug("Executing getconsole command in the external system for the VM {}", vmUUID); + Map accessDetails = loadAccessDetails(cmd.getExternalDetails(), virtualMachineTO); + Pair result = getInstanceConsoleOnExternalSystem(extensionName, extensionPath, vmUUID, + accessDetails, cmd.getWait()); + if (result == null) { + return new GetExternalConsoleAnswer(cmd, "No response from external system"); + } + String output = result.second(); + if (!result.first()) { + return new GetExternalConsoleAnswer(cmd, output); + } + logger.debug("Received console details from the external system: {}", + getSanitizedJsonStringForLog(output)); + try { + JsonObject jsonObj = JsonParser.parseString(output).getAsJsonObject(); + JsonObject consoleObj = jsonObj.has("console") ? jsonObj.getAsJsonObject("console") : null; + if (consoleObj == null) { + logger.error("Missing console object in external console output: {}", + getSanitizedJsonStringForLog(output)); + return new GetExternalConsoleAnswer(cmd, "Missing console object in output"); + } + String url = consoleObj.has("url") ? consoleObj.get("url").getAsString() : null; + String host = consoleObj.has("host") ? consoleObj.get("host").getAsString() : null; + Integer port = consoleObj.has("port") ? Integer.valueOf(consoleObj.get("port").getAsString()) : null; + String password = consoleObj.has("password") ? consoleObj.get("password").getAsString() : null; + boolean passwordOneTimeUseOnly = consoleObj.has("passwordonetimeuseonly") && + consoleObj.get("passwordonetimeuseonly").getAsBoolean(); + String protocol = consoleObj.has("protocol") ? consoleObj.get("protocol").getAsString() : null; + if (url == null && ObjectUtils.anyNull(host, port)) { + logger.error("Missing required fields in external console output: {}", + getSanitizedJsonStringForLog(output)); + return new GetExternalConsoleAnswer(cmd, "Missing required fields in output"); + } + return new GetExternalConsoleAnswer(cmd, url, host, port, password, passwordOneTimeUseOnly, protocol); + } catch (RuntimeException e) { + logger.error("Failed to parse output for getInstanceConsole: {}", e.getMessage(), e); + return new GetExternalConsoleAnswer(cmd, "Failed to parse output"); + } + } + + @Override + public RunCustomActionAnswer runCustomAction(String hostName, String extensionName, String extensionRelativePath, RunCustomActionCommand cmd) { String extensionPath = getExtensionCheckedPath(extensionName, extensionRelativePath); if (StringUtils.isEmpty(extensionPath)) { - return new RunCustomActionAnswer(cmd, false, "Extension not configured"); + return new RunCustomActionAnswer(cmd, false, getExtensionConfigureError(extensionName, hostName)); } final String actionName = cmd.getActionName(); final Map parameters = cmd.getParameters(); - logger.debug("Executing custom action '{}' in the external provisioner", actionName); - VirtualMachineTO virtualMachineTO = null; - if (cmd.getVmId() != null) { - VMInstanceVO vm = vmInstanceDao.findById(cmd.getVmId()); - final HypervisorGuru hvGuru = hypervisorGuruManager.getGuru(Hypervisor.HypervisorType.External); - VirtualMachineProfile profile = new VirtualMachineProfileImpl(vm); - virtualMachineTO = hvGuru.implement(profile); - } logger.debug("Executing custom action '{}' in the external system", actionName); - Map accessDetails = loadAccessDetails(cmd.getExternalDetails(), virtualMachineTO); + Map accessDetails = loadAccessDetails(cmd.getExternalDetails(), cmd.getVmTO()); accessDetails.put(ApiConstants.ACTION, actionName); if (MapUtils.isNotEmpty(parameters)) { accessDetails.put(ApiConstants.PARAMETERS, parameters); @@ -564,18 +631,18 @@ public class ExternalPathPayloadProvisioner extends ManagerBase implements Exter } if (!Files.isDirectory(filePath) && !Files.isRegularFile(filePath)) { throw new CloudRuntimeException( - String.format("Failed to cleanup extension entry-point: %s for extension: %s as it either " + + String.format("Failed to cleanup path: %s for extension: %s as it either " + "does not exist or is not a regular file/directory", extensionName, extensionRelativePath)); } if (!FileUtil.deleteRecursively(filePath)) { throw new CloudRuntimeException( - String.format("Failed to delete extension entry-point: %s for extension: %s", + String.format("Failed to delete path: %s for extension: %s", extensionName, filePath)); } } catch (IOException e) { throw new CloudRuntimeException( - String.format("Failed to cleanup extension entry-point: %s for extension: %s due to: %s", + String.format("Failed to cleanup path: %s for extension: %s due to: %s", extensionName, normalizedPath, e.getMessage()), e); } } @@ -659,9 +726,7 @@ public class ExternalPathPayloadProvisioner extends ManagerBase implements Exter private VirtualMachine.PowerState getVmPowerState(UserVmVO userVmVO, Map> accessDetails, String extensionName, String extensionPath) { - final HypervisorGuru hvGuru = hypervisorGuruManager.getGuru(Hypervisor.HypervisorType.External); - VirtualMachineProfile profile = new VirtualMachineProfileImpl(userVmVO); - VirtualMachineTO virtualMachineTO = hvGuru.implement(profile); + VirtualMachineTO virtualMachineTO = getVirtualMachineTO(userVmVO); accessDetails.put(ApiConstants.VIRTUAL_MACHINE, virtualMachineTO.getExternalDetails()); Map modifiedDetails = loadAccessDetails(accessDetails, virtualMachineTO); String vmUUID = userVmVO.getUuid(); @@ -718,6 +783,12 @@ public class ExternalPathPayloadProvisioner extends ManagerBase implements Exter String.format("Failed to get the instance power status %s on external system", vmUUID), filename); } + public Pair getInstanceConsoleOnExternalSystem(String extensionName, String filename, + String vmUUID, Map accessDetails, int wait) { + return executeExternalCommand(extensionName, "getconsole", accessDetails, wait, + String.format("Failed to get the instance console %s on external system", vmUUID), filename); + } + public Pair executeExternalCommand(String extensionName, String action, Map accessDetails, int wait, String errorLogPrefix, String file) { try { diff --git a/plugins/hypervisors/external/src/main/java/org/apache/cloudstack/hypervisor/external/resource/ExternalResource.java b/plugins/hypervisors/external/src/main/java/org/apache/cloudstack/hypervisor/external/resource/ExternalResource.java index ab70c880a81..02747350dd6 100644 --- a/plugins/hypervisors/external/src/main/java/org/apache/cloudstack/hypervisor/external/resource/ExternalResource.java +++ b/plugins/hypervisors/external/src/main/java/org/apache/cloudstack/hypervisor/external/resource/ExternalResource.java @@ -35,6 +35,8 @@ import com.cloud.agent.api.CheckNetworkAnswer; import com.cloud.agent.api.CheckNetworkCommand; import com.cloud.agent.api.CleanupNetworkRulesCmd; import com.cloud.agent.api.Command; +import com.cloud.agent.api.GetExternalConsoleAnswer; +import com.cloud.agent.api.GetExternalConsoleCommand; import com.cloud.agent.api.GetHostStatsAnswer; import com.cloud.agent.api.GetHostStatsCommand; import com.cloud.agent.api.GetVmStatsCommand; @@ -162,6 +164,8 @@ public class ExternalResource implements ServerResource { return execute((StopCommand) cmd); } else if (cmd instanceof RebootCommand) { return execute((RebootCommand) cmd); + } else if (cmd instanceof GetExternalConsoleCommand) { + return execute((GetExternalConsoleCommand) cmd); } else if (cmd instanceof PrepareExternalProvisioningCommand) { return execute((PrepareExternalProvisioningCommand) cmd); } else if (cmd instanceof GetHostStatsCommand) { @@ -273,6 +277,13 @@ public class ExternalResource implements ServerResource { return externalProvisioner.rebootInstance(guid, extensionName, extensionRelativePath, cmd); } + public GetExternalConsoleAnswer execute(GetExternalConsoleCommand cmd) { + if (isExtensionDisconnected() || isExtensionNotEnabled() || isExtensionPathNotReady()) { + return new GetExternalConsoleAnswer(cmd, logAndGetExtensionNotConnectedOrDisabledError()); + } + return externalProvisioner.getInstanceConsole(guid, extensionName, extensionRelativePath, cmd); + } + public PrepareExternalProvisioningAnswer execute(PrepareExternalProvisioningCommand cmd) { if (isExtensionDisconnected() || isExtensionNotEnabled() || isExtensionPathNotReady()) { return new PrepareExternalProvisioningAnswer(cmd, false, logAndGetExtensionNotConnectedOrDisabledError()); diff --git a/plugins/hypervisors/external/src/test/java/org/apache/cloudstack/hypervisor/external/provisioner/ExternalPathPayloadProvisionerTest.java b/plugins/hypervisors/external/src/test/java/org/apache/cloudstack/hypervisor/external/provisioner/ExternalPathPayloadProvisionerTest.java index 8c63a20fa31..d0a396f7a94 100644 --- a/plugins/hypervisors/external/src/test/java/org/apache/cloudstack/hypervisor/external/provisioner/ExternalPathPayloadProvisionerTest.java +++ b/plugins/hypervisors/external/src/test/java/org/apache/cloudstack/hypervisor/external/provisioner/ExternalPathPayloadProvisionerTest.java @@ -65,6 +65,8 @@ import org.mockito.Spy; import org.mockito.junit.MockitoJUnitRunner; import org.springframework.test.util.ReflectionTestUtils; +import com.cloud.agent.api.GetExternalConsoleAnswer; +import com.cloud.agent.api.GetExternalConsoleCommand; import com.cloud.agent.api.HostVmStateReportEntry; import com.cloud.agent.api.PrepareExternalProvisioningAnswer; import com.cloud.agent.api.PrepareExternalProvisioningCommand; @@ -88,11 +90,10 @@ import com.cloud.utils.Pair; import com.cloud.utils.PropertiesUtil; import com.cloud.utils.script.Script; import com.cloud.vm.UserVmVO; -import com.cloud.vm.VMInstanceVO; import com.cloud.vm.VirtualMachine; import com.cloud.vm.VirtualMachineProfile; +import com.cloud.vm.VmDetailConstants; import com.cloud.vm.dao.UserVmDao; -import com.cloud.vm.dao.VMInstanceDao; @RunWith(MockitoJUnitRunner.class) public class ExternalPathPayloadProvisionerTest { @@ -107,9 +108,6 @@ public class ExternalPathPayloadProvisionerTest { @Mock private HostDao hostDao; - @Mock - private VMInstanceDao vmInstanceDao; - @Mock private HypervisorGuruManager hypervisorGuruManager; @@ -208,6 +206,20 @@ public class ExternalPathPayloadProvisionerTest { assertEquals("test-vm", result.get(ApiConstants.VIRTUAL_MACHINE_NAME)); } + @Test + public void testLoadAccessDetails_WithCaller() { + Map> externalDetails = new HashMap<>(); + externalDetails.put(ApiConstants.EXTENSION, Map.of("key1", "value1")); + externalDetails.put(ApiConstants.CALLER, Map.of("key2", "value2")); + Map result = provisioner.loadAccessDetails(externalDetails, null); + + assertNotNull(result); + assertNotNull(result.get(ApiConstants.EXTERNAL_DETAILS)); + assertNotNull(((Map) result.get(ApiConstants.EXTERNAL_DETAILS)).get(ApiConstants.EXTENSION)); + assertNotNull(result.get(ApiConstants.CALLER)); + assertNull(result.get(VmDetailConstants.CLOUDSTACK_VM_DETAILS)); + } + @Test public void testGetExtensionCheckedPathValidFile() { String result = provisioner.getExtensionCheckedPath("test-extension", "test-extension.sh"); @@ -317,7 +329,7 @@ public class ExternalPathPayloadProvisionerTest { .executeExternalCommand(anyString(), anyString(), anyMap(), anyInt(), anyString(), anyString()); PrepareExternalProvisioningAnswer answer = provisioner.prepareExternalProvisioning( - "host-guid", "test-extension", "test-extension.sh", cmd); + "host-name", "test-extension", "test-extension.sh", cmd); assertTrue(answer.getResult()); assertEquals("test-net-uuid", answer.getVirtualMachineTO().getNics()[0].getNetworkUuid()); @@ -329,11 +341,14 @@ public class ExternalPathPayloadProvisionerTest { public void testPrepareExternalProvisioning_ExtensionNotConfigured() { PrepareExternalProvisioningCommand cmd = mock(PrepareExternalProvisioningCommand.class); + String extensionName = "test-extension"; + String hostName = "host-name"; PrepareExternalProvisioningAnswer answer = provisioner.prepareExternalProvisioning( - "host-guid", "test-extension", "nonexistent.sh", cmd); + hostName, extensionName, "nonexistent.sh", cmd); assertFalse(answer.getResult()); - assertEquals("Extension not configured", answer.getDetails()); + assertNotNull(answer); + assertEquals(String.format("Extension: %s not configured for host: %s", extensionName, hostName), answer.getDetails()); } @Test @@ -348,7 +363,7 @@ public class ExternalPathPayloadProvisionerTest { doReturn(new Pair<>(true, "{\"status\": \"success\", \"message\": \"Instance started\"}")).when(provisioner) .executeExternalCommand(anyString(), anyString(), anyMap(), anyInt(), anyString(), anyString()); - StartAnswer answer = provisioner.startInstance("host-guid", "test-extension", "test-extension.sh", cmd); + StartAnswer answer = provisioner.startInstance("host-name", "test-extension", "test-extension.sh", cmd); assertTrue(answer.getResult()); Mockito.verify(logger).debug("Starting VM test-uuid on the external system"); @@ -369,7 +384,7 @@ public class ExternalPathPayloadProvisionerTest { doReturn(new Pair<>(true, "{\"status\": \"success\", \"message\": \"Instance started\"}")).when(provisioner) .executeExternalCommand(anyString(), anyString(), anyMap(), anyInt(), anyString(), anyString()); - StartAnswer answer = provisioner.startInstance("host-guid", "test-extension", "test-extension.sh", cmd); + StartAnswer answer = provisioner.startInstance("host-name", "test-extension", "test-extension.sh", cmd); assertTrue(answer.getResult()); Mockito.verify(logger).debug("Deploying VM test-uuid on the external system"); @@ -387,7 +402,7 @@ public class ExternalPathPayloadProvisionerTest { doReturn(new Pair<>(false, "{\"error\": \"Instance failed to start\"}")).when(provisioner) .executeExternalCommand(anyString(), anyString(), anyMap(), anyInt(), anyString(), anyString()); - StartAnswer answer = provisioner.startInstance("host-guid", "test-extension", "test-extension.sh", cmd); + StartAnswer answer = provisioner.startInstance("host-name", "test-extension", "test-extension.sh", cmd); assertFalse(answer.getResult()); assertEquals("{\"error\": \"Instance failed to start\"}", answer.getDetails()); @@ -406,7 +421,7 @@ public class ExternalPathPayloadProvisionerTest { doReturn(new Pair<>(true, "success")).when(provisioner) .executeExternalCommand(anyString(), anyString(), anyMap(), anyInt(), anyString(), anyString()); - StopAnswer answer = provisioner.stopInstance("host-guid", "test-extension", "test-extension.sh", cmd); + StopAnswer answer = provisioner.stopInstance("host-name", "test-extension", "test-extension.sh", cmd); assertTrue(answer.getResult()); } @@ -423,7 +438,7 @@ public class ExternalPathPayloadProvisionerTest { doReturn(new Pair<>(true, "success")).when(provisioner) .executeExternalCommand(anyString(), anyString(), anyMap(), anyInt(), anyString(), anyString()); - RebootAnswer answer = provisioner.rebootInstance("host-guid", "test-extension", "test-extension.sh", cmd); + RebootAnswer answer = provisioner.rebootInstance("host-name", "test-extension", "test-extension.sh", cmd); assertTrue(answer.getResult()); } @@ -440,7 +455,7 @@ public class ExternalPathPayloadProvisionerTest { doReturn(new Pair<>(true, "success")).when(provisioner) .executeExternalCommand(anyString(), anyString(), anyMap(), anyInt(), anyString(), anyString()); - StopAnswer answer = provisioner.expungeInstance("host-guid", "test-extension", "test-extension.sh", cmd); + StopAnswer answer = provisioner.expungeInstance("host-name", "test-extension", "test-extension.sh", cmd); assertTrue(answer.getResult()); } @@ -489,19 +504,11 @@ public class ExternalPathPayloadProvisionerTest { when(cmd.getParameters()).thenReturn(new HashMap<>()); when(cmd.getExternalDetails()).thenReturn(new HashMap<>()); when(cmd.getWait()).thenReturn(30); - when(cmd.getVmId()).thenReturn(1L); - - VMInstanceVO vm = mock(VMInstanceVO.class); - when(vmInstanceDao.findById(anyLong())).thenReturn(vm); - - when(hypervisorGuruManager.getGuru(Hypervisor.HypervisorType.External)).thenReturn(hypervisorGuru); - VirtualMachineTO vmTO = mock(VirtualMachineTO.class); - when(hypervisorGuru.implement(any(VirtualMachineProfile.class))).thenReturn(vmTO); doReturn(new Pair<>(true, "success")).when(provisioner) .executeExternalCommand(anyString(), anyString(), anyMap(), anyInt(), anyString(), anyString()); - RunCustomActionAnswer answer = provisioner.runCustomAction("host-guid", "test-extension", "test-extension.sh", cmd); + RunCustomActionAnswer answer = provisioner.runCustomAction("host-name", "test-extension", "test-extension.sh", cmd); assertTrue(answer.getResult()); Mockito.verify(logger).debug("Executing custom action '{}' in the external system", "test-action"); @@ -747,4 +754,236 @@ public class ExternalPathPayloadProvisionerTest { VirtualMachine.PowerState result = provisioner.parsePowerStateFromResponse(vm, response); assertEquals(VirtualMachine.PowerState.PowerOn, result); } + + @Test + public void getVirtualMachineTOReturnsNullWhenVmIsNull() { + VirtualMachineTO result = provisioner.getVirtualMachineTO(null); + assertNull(result); + } + + @Test + public void getVirtualMachineTOReturnsValidTOWhenVmIsNotNull() { + VirtualMachine vm = mock(VirtualMachine.class); + VirtualMachineTO vmTO = mock(VirtualMachineTO.class); + when(hypervisorGuruManager.getGuru(Hypervisor.HypervisorType.External)).thenReturn(hypervisorGuru); + when(hypervisorGuru.implement(any(VirtualMachineProfile.class))).thenReturn(vmTO); + VirtualMachineTO result = provisioner.getVirtualMachineTO(vm); + assertNotNull(result); + assertEquals(vmTO, result); + Mockito.verify(hypervisorGuruManager).getGuru(Hypervisor.HypervisorType.External); + Mockito.verify(hypervisorGuru).implement(any(VirtualMachineProfile.class)); + } + + @Test + public void getInstanceConsoleReturnsAnswerWhenConsoleDetailsAreValid() { + GetExternalConsoleCommand cmd = mock(GetExternalConsoleCommand.class); + VirtualMachineTO vmTO = mock(VirtualMachineTO.class); + when(cmd.getVirtualMachine()).thenReturn(vmTO); + when(vmTO.getUuid()).thenReturn("test-uuid"); + + Map accessDetails = new HashMap<>(); + when(provisioner.loadAccessDetails(any(), eq(vmTO))).thenReturn(accessDetails); + + String validOutput = "{\"console\":{\"host\":\"127.0.0.1\",\"port\":5900,\"password\":\"pass\",\"protocol\":\"vnc\"}}"; + doReturn(new Pair<>(true, validOutput)).when(provisioner) + .getInstanceConsoleOnExternalSystem(anyString(), anyString(), anyString(), anyMap(), anyInt()); + + GetExternalConsoleAnswer result = provisioner.getInstanceConsole("host-name", "test-extension", "test-extension.sh", cmd); + + assertNotNull(result); + assertEquals("127.0.0.1", result.getHost()); + Integer port = 5900; + assertEquals(port, result.getPort()); + assertEquals("pass", result.getPassword()); + assertEquals("vnc", result.getProtocol()); + } + + @Test + public void getInstanceConsoleReturnsErrorWhenExtensionNotConfigured() { + GetExternalConsoleCommand cmd = mock(GetExternalConsoleCommand.class); + when(provisioner.getExtensionCheckedPath(anyString(), anyString())).thenReturn(null); + + String extensionName = "test-extension"; + String hostName = "host-name"; + GetExternalConsoleAnswer result = provisioner.getInstanceConsole(hostName, + extensionName, "test-extension.sh", cmd); + + assertNotNull(result); + assertEquals(String.format("Extension: %s not configured for host: %s", extensionName, hostName), result.getDetails()); + } + + @Test + public void getInstanceConsoleReturnsErrorWhenExternalSystemFails() { + GetExternalConsoleCommand cmd = mock(GetExternalConsoleCommand.class); + VirtualMachineTO vmTO = mock(VirtualMachineTO.class); + when(cmd.getVirtualMachine()).thenReturn(vmTO); + when(vmTO.getUuid()).thenReturn("test-uuid"); + + doReturn(new Pair<>(false, "External system error")).when(provisioner) + .getInstanceConsoleOnExternalSystem(anyString(), anyString(), anyString(), anyMap(), anyInt()); + + GetExternalConsoleAnswer result = provisioner.getInstanceConsole("host-name", "test-extension", "test-extension.sh", cmd); + + assertNotNull(result); + assertEquals("External system error", result.getDetails()); + } + + @Test + public void getInstanceConsoleReturnsErrorWhenConsoleObjectIsMissing() { + GetExternalConsoleCommand cmd = mock(GetExternalConsoleCommand.class); + VirtualMachineTO vmTO = mock(VirtualMachineTO.class); + when(cmd.getVirtualMachine()).thenReturn(vmTO); + when(vmTO.getUuid()).thenReturn("test-uuid"); + + String invalidOutput = "{\"invalid_key\":\"value\"}"; + doReturn(new Pair<>(true, invalidOutput)).when(provisioner) + .getInstanceConsoleOnExternalSystem(anyString(), anyString(), anyString(), anyMap(), anyInt()); + + GetExternalConsoleAnswer result = provisioner.getInstanceConsole("host-name", "test-extension", "test-extension.sh", cmd); + + assertNotNull(result); + assertEquals("Missing console object in output", result.getDetails()); + } + + @Test + public void getInstanceConsoleReturnsErrorWhenRequiredFieldsAreMissing() { + GetExternalConsoleCommand cmd = mock(GetExternalConsoleCommand.class); + VirtualMachineTO vmTO = mock(VirtualMachineTO.class); + when(cmd.getVirtualMachine()).thenReturn(vmTO); + when(vmTO.getUuid()).thenReturn("test-uuid"); + + String incompleteOutput = "{\"console\":{\"host\":\"127.0.0.1\"}}"; + doReturn(new Pair<>(true, incompleteOutput)).when(provisioner) + .getInstanceConsoleOnExternalSystem(anyString(), anyString(), anyString(), anyMap(), anyInt()); + + GetExternalConsoleAnswer result = provisioner.getInstanceConsole("host-name", "test-extension", "test-extension.sh", cmd); + + assertNotNull(result); + assertEquals("Missing required fields in output", result.getDetails()); + } + + @Test + public void getInstanceConsoleReturnsErrorWhenOutputParsingFails() { + GetExternalConsoleCommand cmd = mock(GetExternalConsoleCommand.class); + VirtualMachineTO vmTO = mock(VirtualMachineTO.class); + when(cmd.getVirtualMachine()).thenReturn(vmTO); + when(vmTO.getUuid()).thenReturn("test-uuid"); + + String malformedOutput = "{console:invalid}"; + doReturn(new Pair<>(true, malformedOutput)).when(provisioner) + .getInstanceConsoleOnExternalSystem(anyString(), anyString(), anyString(), anyMap(), anyInt()); + + GetExternalConsoleAnswer result = provisioner.getInstanceConsole("host-name", "test-extension", "test-extension.sh", cmd); + + assertNotNull(result); + assertEquals("Failed to parse output", result.getDetails()); + } + + @Test + public void getInstanceConsoleOnExternalSystemReturnsSuccessWhenCommandExecutesSuccessfully() { + String extensionName = "test-extension"; + String filename = "test-script.sh"; + String vmUUID = "test-vm-uuid"; + Map accessDetails = new HashMap<>(); + int wait = 30; + + doReturn(new Pair<>(true, "Console details")).when(provisioner) + .executeExternalCommand(eq(extensionName), eq("getconsole"), eq(accessDetails), eq(wait), anyString(), eq(filename)); + + Pair result = provisioner.getInstanceConsoleOnExternalSystem(extensionName, filename, vmUUID, accessDetails, wait); + + assertTrue(result.first()); + assertEquals("Console details", result.second()); + } + + @Test + public void getInstanceConsoleOnExternalSystemReturnsFailureWhenCommandFails() { + String extensionName = "test-extension"; + String filename = "test-script.sh"; + String vmUUID = "test-vm-uuid"; + Map accessDetails = new HashMap<>(); + int wait = 30; + + doReturn(new Pair<>(false, "Failed to get console")).when(provisioner) + .executeExternalCommand(eq(extensionName), eq("getconsole"), eq(accessDetails), eq(wait), anyString(), eq(filename)); + + Pair result = provisioner.getInstanceConsoleOnExternalSystem(extensionName, filename, vmUUID, accessDetails, wait); + + assertFalse(result.first()); + assertEquals("Failed to get console", result.second()); + } + + @Test + public void getInstanceConsoleOnExternalSystemHandlesNullResponseGracefully() { + String extensionName = "test-extension"; + String filename = "test-script.sh"; + String vmUUID = "test-vm-uuid"; + Map accessDetails = new HashMap<>(); + int wait = 30; + + doReturn(null).when(provisioner) + .executeExternalCommand(eq(extensionName), eq("getconsole"), eq(accessDetails), eq(wait), anyString(), eq(filename)); + + Pair result = provisioner.getInstanceConsoleOnExternalSystem(extensionName, filename, vmUUID, accessDetails, wait); + + assertNull(result); + } + + @Test + public void getSanitizedJsonStringForLogReturnsNullWhenInputIsNull() { + String result = provisioner.getSanitizedJsonStringForLog(null); + assertNull(result); + } + + @Test + public void getSanitizedJsonStringForLogReturnsEmptyWhenInputIsEmpty() { + String result = provisioner.getSanitizedJsonStringForLog(""); + assertEquals("", result); + } + + @Test + public void getSanitizedJsonStringForLogReturnsSameStringWhenNoPasswordField() { + String json = "{\"key\":\"value\"}"; + String result = provisioner.getSanitizedJsonStringForLog(json); + assertEquals(json, result); + } + + @Test + public void getSanitizedJsonStringForLogMasksPasswordField() { + String json = "{\"password\":\"secret\"}"; + String result = provisioner.getSanitizedJsonStringForLog(json); + assertEquals("{\"password\":\"****\"}", result); + } + + @Test + public void getSanitizedJsonStringForLogHandlesMultiplePasswordFields() { + String json = "{\"password\":\"secret\",\"nested\":{\"password\":\"anotherSecret\"}}"; + String result = provisioner.getSanitizedJsonStringForLog(json); + assertEquals("{\"password\":\"****\",\"nested\":{\"password\":\"****\"}}", result); + } + + @Test + public void getSanitizedJsonStringForLogHandlesMalformedJsonGracefully() { + String json = "{password:\"secret\""; + String result = provisioner.getSanitizedJsonStringForLog(json); + assertEquals("{password:\"secret\"", result); + } + + @Test + public void getExtensionConfigureErrorReturnsMessageWhenHostNameIsNotBlank() { + String result = provisioner.getExtensionConfigureError("test-extension", "test-host"); + assertEquals("Extension: test-extension not configured for host: test-host", result); + } + + @Test + public void getExtensionConfigureErrorReturnsMessageWhenHostNameIsBlank() { + String result = provisioner.getExtensionConfigureError("test-extension", ""); + assertEquals("Extension: test-extension not configured", result); + } + + @Test + public void getExtensionConfigureErrorReturnsMessageWhenHostNameIsNull() { + String result = provisioner.getExtensionConfigureError("test-extension", null); + assertEquals("Extension: test-extension not configured", result); + } } diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/ServerResource.Tests/HypervResourceController1Test.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/ServerResource.Tests/HypervResourceController1Test.cs index 6d8e2b2e15a..6f9e68302f8 100644 --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/ServerResource.Tests/HypervResourceController1Test.cs +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/ServerResource.Tests/HypervResourceController1Test.cs @@ -1,350 +1,350 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -using System; -using CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2; -using System.Management; -using Newtonsoft.Json.Linq; -using Newtonsoft.Json; -using System.IO; -using log4net; -using HypervResource; -using CloudStack.Plugin.AgentShell; -using System.Collections.Generic; -using NSubstitute; -using System.Web.Http; -using Xunit; - -namespace ServerResource.Tests -{ - public class HypervResourceController1Test - { - protected static string testCifsUrl = AgentSettings.Default.testCifsUrl; - protected static string testCifsPath = AgentSettings.Default.testCifsPath; - protected static String testPrimaryDataStoreHost = HypervResourceController.config.StorageIpAddress; - protected static String testS3TemplateName = AgentSettings.Default.testS3TemplateName; - protected static String testCifsTemplateName = AgentSettings.Default.testS3TemplateName; - protected static String testSystemVMTemplateName = AgentSettings.Default.testSystemVMTemplateName; - protected static String testSystemVMTemplateNameNoExt = AgentSettings.Default.testSystemVMTemplateNameNoExt; - protected static String testLocalStoreUUID = "5fe2bad3-d785-394e-9949-89786b8a63d2"; - protected static String testLocalStorePath = Path.Combine(AgentSettings.Default.hyperv_plugin_root, "var", "test", "storagepool"); - protected static String testSecondaryStoreLocalPath = Path.Combine(AgentSettings.Default.hyperv_plugin_root, "var", "test", "secondary"); - - // TODO: differentiate between NFS and HTTP template URLs. - protected static String testSampleTemplateUUID = "TestCopiedLocalTemplate.vhdx"; - protected static String testSampleTemplateURL = testSampleTemplateUUID; - - // test volumes are both a minimal size vhdx. Changing the extension to .vhd makes on corrupt. - protected static String testSampleVolumeWorkingUUID = "TestVolumeLegit.vhdx"; - protected static String testSampleVolumeCorruptUUID = "TestVolumeCorrupt.vhd"; - protected static String testSampleVolumeTempUUID = "TestVolumeTemp.vhdx"; - protected static String testSampleVolumeTempUUIDNoExt = "TestVolumeTemp"; - protected static String testSampleVolumeWorkingURIJSON; - protected static String testSampleVolumeCorruptURIJSON; - protected static String testSampleVolumeTempURIJSON; - - protected static String testSampleTemplateURLJSON; - protected static String testLocalStorePathJSON; - - protected static IWmiCallsV2 wmiCallsV2; - - - private static ILog s_logger = LogManager.GetLogger(typeof(HypervResourceController1Test)); - - /// - /// Test WmiCalls to which incoming HTTP POST requests are dispatched. - /// - /// TODO: revise beyond first approximation - /// First approximation is a quick port of the existing Java tests for Hyper-V server resource. - /// A second approximation would use the AgentShell settings files directly. - /// A third approximation would look to invoke ServerResource methods via an HTTP request - /// - - public HypervResourceController1Test() - { - wmiCallsV2 = Substitute.For(); - //AgentService.ConfigServerResource(); - HypervResourceController.config.PrivateMacAddress = AgentSettings.Default.private_mac_address; - HypervResourceController.config.PrivateNetmask = AgentSettings.Default.private_ip_netmask; - HypervResourceController.config.StorageIpAddress = HypervResourceController.config.PrivateIpAddress; - HypervResourceController.config.StorageMacAddress = HypervResourceController.config.PrivateMacAddress; - HypervResourceController.config.StorageNetmask = HypervResourceController.config.PrivateNetmask; - - - // Used to create existing StoragePool in preparation for the ModifyStoragePool - testLocalStoreUUID = AgentSettings.Default.local_storage_uuid.ToString(); - - // Make sure secondary store is available. - string fullPath = Path.GetFullPath(testSecondaryStoreLocalPath); - s_logger.Info("Test secondary storage in " + fullPath); - DirectoryInfo testSecondarStoreDir = new DirectoryInfo(fullPath); - if (!testSecondarStoreDir.Exists) - { - try - { - testSecondarStoreDir.Create(); - } - catch (System.IO.IOException ex) - { - throw new NotImplementedException("Need to be able to create the folder " + testSecondarStoreDir.FullName + " failed due to " + ex.Message); - } - } - - // Convert to secondary storage string to canonical path - testSecondaryStoreLocalPath = testSecondarStoreDir.FullName; - AgentSettings.Default.local_secondary_storage_path = testSecondaryStoreLocalPath; - - // Make sure local primary storage is available - DirectoryInfo testPoolDir = new DirectoryInfo(testLocalStorePath); - //Assert.True(testPoolDir.Exists, "To simulate local file system Storage Pool, you need folder at " + testPoolDir.FullName); - - // Convert to local primary storage string to canonical path - testLocalStorePath = testPoolDir.FullName; - AgentSettings.Default.local_storage_path = testLocalStorePath; - - // Clean up old test files in local storage folder - FileInfo testVolWorks = new FileInfo(Path.Combine(testLocalStorePath, testSampleVolumeWorkingUUID)); - // Assert.True(testVolWorks.Exists, "Create a working virtual disk at " + testVolWorks.FullName); - - testSampleTemplateURLJSON = JsonConvert.SerializeObject(testSampleTemplateUUID); - s_logger.Info("Created " + testSampleTemplateURLJSON + " in local storage."); - - - // Capture other JSON encoded paths - testSampleVolumeWorkingURIJSON = Newtonsoft.Json.JsonConvert.SerializeObject(testVolWorks.FullName); - testLocalStorePathJSON = JsonConvert.SerializeObject(testLocalStorePath); - - // TODO: may need to initialise the server resource in future. - // s_hypervresource.initialize(); - - // Verify sample template is in place storage pool - s_logger.Info("setUp complete, sample StoragePool at " + testLocalStorePathJSON - + " sample template at " + testSampleTemplateURLJSON); - } - - private String CreateTestDiskImageFromExistingImage(FileInfo srcFile, - String dstPath, - String dstFileName) - { - var newFullname = Path.Combine(dstPath, dstFileName); - var newFileInfo = new FileInfo(newFullname); - if (!newFileInfo.Exists) - { - newFileInfo = srcFile.CopyTo(newFullname); - } - newFileInfo.Refresh(); - Assert.True(newFileInfo.Exists, "Attempted to create " + newFullname + " from " + newFileInfo.FullName); - - return JsonConvert.SerializeObject(newFileInfo.FullName); - } - - [Fact] - public void TestCreateCommand() - { - DirectoryInfo localStorePath = new DirectoryInfo(testLocalStorePath); - if (!localStorePath.Exists) - { - try - { - localStorePath.Create(); - } - catch (System.IO.IOException ex) - { - throw new NotImplementedException("Need to be able to create the folder " + localStorePath.FullName + " failed due to " + ex.Message); - } - } - - FileInfo sampleTemplateFile = new FileInfo(Path.Combine(testLocalStorePath, testSampleTemplateUUID)); - if (!sampleTemplateFile.Exists) - { - //Create a file to write to. - using (StreamWriter sw = sampleTemplateFile.CreateText()) - { - sw.WriteLine("This is fake template file for test"); - } - } - var counter = 0; - wmiCallsV2.When(x => x.CreateDynamicVirtualHardDisk(Arg.Any(), Arg.Any())).Do(x => counter++); - // TODO: Need sample to update the test. - // Arrange - String createCmd = "{\"volId\":10,\"pool\":{\"id\":201,\"uuid\":\"" + testLocalStoreUUID + "\",\"host\":\"" + HypervResourceController.config.StorageIpAddress + "\"" + - ",\"path\":" + testLocalStorePathJSON + ",\"port\":0,\"type\":\"Filesystem\"},\"diskCharacteristics\":{\"size\":0," + - "\"tags\":[],\"type\":\"ROOT\",\"name\":\"ROOT-9\",\"useLocalStorage\":true,\"recreatable\":true,\"diskOfferingId\":11," + - "\"volumeId\":10,\"hyperType\":\"Hyperv\"},\"templateUrl\":" + testSampleTemplateURLJSON + ",\"contextMap\":{},\"wait\":0}"; - dynamic jsonCreateCmd = JsonConvert.DeserializeObject(createCmd); - HypervResourceController rsrcServer = new HypervResourceController(); - HypervResourceController.wmiCallsV2 = wmiCallsV2; - - Assert.True(Directory.Exists(testLocalStorePath), testLocalStorePath + " does not exist "); - string filePath = Path.Combine(testLocalStorePath, (string)JsonConvert.DeserializeObject(testSampleTemplateURLJSON)); - Assert.True(File.Exists(filePath), "The template we make volumes from is missing from path " + filePath); - int fileCount = Directory.GetFiles(testLocalStorePath).Length; - s_logger.Debug(" test local store has " + fileCount + "files"); - - // Act - // Test requires there to be a template at the tempalteUrl, which is its location in the local file system. - dynamic jsonResult = rsrcServer.CreateCommand(jsonCreateCmd); - s_logger.Debug("CreateDynamicVirtualHardDisk method is called " + counter + " times"); - - //Assert.Equal(counter, 1); - - JObject ansAsProperty2 = jsonResult[0]; - dynamic ans = ansAsProperty2.GetValue(CloudStackTypes.CreateAnswer); - Assert.NotNull(ans); - Assert.True((bool)ans.result, "Failed to CreateCommand due to " + (string)ans.result); - Assert.Equal(Directory.GetFiles(testLocalStorePath).Length, fileCount + 1); - FileInfo newFile = new FileInfo((string)ans.volume.path); - Assert.True(newFile.Length > 0, "The new file should have a size greater than zero"); - newFile.Delete(); - sampleTemplateFile.Delete(); - } - - [Fact] - public void TestDestroyCommand() - { - testSampleVolumeTempURIJSON = "\"storagepool\""; - // Arrange - String destroyCmd = //"{\"volume\":" + getSampleVolumeObjectTO() + "}"; - "{\"volume\":{\"name\":\"" + testSampleVolumeTempUUIDNoExt - + "\",\"storagePoolType\":\"Filesystem\"," - + "\"mountPoint\":" - + testLocalStorePathJSON - + ",\"path\":" + testSampleVolumeTempURIJSON - + ",\"storagePoolUuid\":\"" + testLocalStoreUUID - + "\"," - + "\"type\":\"ROOT\",\"id\":9,\"size\":0}}"; - - ImageManagementService imgmgr = new ImageManagementService(); - wmiCallsV2.GetImageManagementService().Returns(imgmgr); - - HypervResourceController rsrcServer = new HypervResourceController(); - HypervResourceController.wmiCallsV2 = wmiCallsV2; - - dynamic jsonDestroyCmd = JsonConvert.DeserializeObject(destroyCmd); - - // Act - dynamic destroyAns = rsrcServer.DestroyCommand(jsonDestroyCmd); - - // Assert - JObject ansAsProperty2 = destroyAns[0]; - dynamic ans = ansAsProperty2.GetValue(CloudStackTypes.Answer); - String path = jsonDestroyCmd.volume.path; - Assert.True((bool)ans.result, "DestroyCommand did not succeed " + ans.details); - Assert.True(!File.Exists(path), "Failed to delete file " + path); - } - - [Fact] - public void TestStartCommand() - { - ComputerSystem system = new ComputerSystem(); - wmiCallsV2.DeployVirtualMachine(Arg.Any(), Arg.Any()).Returns(system); - - // Arrange - HypervResourceController rsrcServer = new HypervResourceController(); - HypervResourceController.wmiCallsV2 = wmiCallsV2; - String sample = getSampleStartCommand(); - - - dynamic jsonStartCmd = JsonConvert.DeserializeObject(sample); - - // Act - dynamic startAns = rsrcServer.StartCommand(jsonStartCmd); - - // Assert - Assert.NotNull(startAns[0][CloudStackTypes.StartAnswer]); - Assert.True((bool)startAns[0][CloudStackTypes.StartAnswer].result, "StartCommand did not succeed " + startAns[0][CloudStackTypes.StartAnswer].details); - - Assert.Null((string)startAns[0][CloudStackTypes.StartAnswer].details); - } - - [Fact] - public void TestStopCommand() - { - //string vmName = "Test VM"; - var counter = 0; - wmiCallsV2.When(x => x.DestroyVm(Arg.Any())).Do(x => counter++); - - // Arrange - HypervResourceController rsrcServer = new HypervResourceController(); - HypervResourceController.wmiCallsV2 = wmiCallsV2; - - String sampleStop = "{\"isProxy\":false,\"vmName\":\"i-2-17-VM\",\"contextMap\":{},\"checkBeforeCleanup\":false,\"wait\":0}"; - dynamic jsonStopCmd = JsonConvert.DeserializeObject(sampleStop); - - // Act - dynamic stopAns = rsrcServer.StopCommand(jsonStopCmd); - - // Assert VM is gone! - Assert.NotNull(stopAns[0][CloudStackTypes.StopAnswer]); - Assert.True((bool)stopAns[0][CloudStackTypes.StopAnswer].result, "StopCommand did not succeed " + stopAns[0][CloudStackTypes.StopAnswer].details); - - Assert.Null((string)stopAns[0][CloudStackTypes.StopAnswer].details); - Assert.Equal(counter, 1); - } - - public static String getSamplePrimaryDataStoreInfo() - { - String samplePrimaryDataStoreInfo = - "{\"org.apache.cloudstack.storage.to.PrimaryDataStoreTO\":" + - "{\"uuid\":\"" + testLocalStoreUUID + "\"," + - "\"id\":201," + - "\"host\":\"" + testPrimaryDataStoreHost + "\"," + - "\"type\":\"Filesystem\"," + // Not used in PrimaryDataStoreTO - "\"poolType\":\"Filesystem\"," + // Not used in PrimaryDataStoreTO - "\"path\":" + testLocalStorePathJSON + "," + - "\"port\":0}" + - "}"; - return samplePrimaryDataStoreInfo; - } - - public static String getSampleVolumeObjectTO() - { - String sampleVolumeObjectTO = - "{\"org.apache.cloudstack.storage.to.VolumeObjectTO\":" + - "{\"uuid\":\"19ae8e67-cb2c-4ab4-901e-e0b864272b59\"," + - "\"volumeType\":\"ROOT\"," + - "\"format\":\"VHDX\"," + - "\"dataStore\":" + getSamplePrimaryDataStoreInfo() + "," + - "\"name\":\"" + testSampleVolumeTempUUIDNoExt + "\"," + - "\"size\":52428800," + - "\"volumeId\":10," + - // "\"vmName\":\"i-3-5-VM\"," + // TODO: do we have to fill in the vmName? - "\"accountId\":3,\"id\":10}" + - "}"; // end of destTO - return sampleVolumeObjectTO; - } - - public static String getSampleStartCommand() - { - String sample = "{\"vm\":{\"id\":17,\"name\":\"i-2-17-VM\",\"type\":\"User\",\"cpus\":1,\"speed\":500," + - "\"minRam\":536870912,\"maxRam\":536870912,\"arch\":\"x86_64\"," + - "\"os\":\"CentOS 6.0 (64-bit)\",\"bootArgs\":\"\",\"rebootOnCrash\":false," + - "\"enableHA\":false,\"limitCpuUse\":false,\"vncPassword\":\"31f82f29aff646eb\"," + - "\"params\":{},\"uuid\":\"8b030b6a-0243-440a-8cc5-45d08815ca11\"" + - ",\"disks\":[" + - "{\"data\":" + getSampleVolumeObjectTO() + ",\"diskSeq\":0,\"type\":\"ROOT\"}," + - "{\"diskSeq\":1,\"type\":\"ISO\"}" + - "]," + - "\"nics\":[" + - "{\"deviceId\":0,\"networkRateMbps\":100,\"defaultNic\":true,\"uuid\":\"99cb4813-23af-428c-a87a-2d1899be4f4b\"," + - "\"ip\":\"10.1.1.67\",\"netmask\":\"255.255.255.0\",\"gateway\":\"10.1.1.1\"," + - "\"mac\":\"02:00:51:2c:00:0e\",\"dns1\":\"4.4.4.4\",\"broadcastType\":\"Vlan\",\"type\":\"Guest\"," + - "\"broadcastUri\":\"vlan://261\",\"isolationUri\":\"vlan://261\",\"isSecurityGroupEnabled\":false}" + - "]},\"contextMap\":{},\"wait\":0}"; - return sample; - } - } -} +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +using System; +using CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2; +using System.Management; +using Newtonsoft.Json.Linq; +using Newtonsoft.Json; +using System.IO; +using log4net; +using HypervResource; +using CloudStack.Plugin.AgentShell; +using System.Collections.Generic; +using NSubstitute; +using System.Web.Http; +using Xunit; + +namespace ServerResource.Tests +{ + public class HypervResourceController1Test + { + protected static string testCifsUrl = AgentSettings.Default.testCifsUrl; + protected static string testCifsPath = AgentSettings.Default.testCifsPath; + protected static String testPrimaryDataStoreHost = HypervResourceController.config.StorageIpAddress; + protected static String testS3TemplateName = AgentSettings.Default.testS3TemplateName; + protected static String testCifsTemplateName = AgentSettings.Default.testS3TemplateName; + protected static String testSystemVMTemplateName = AgentSettings.Default.testSystemVMTemplateName; + protected static String testSystemVMTemplateNameNoExt = AgentSettings.Default.testSystemVMTemplateNameNoExt; + protected static String testLocalStoreUUID = "5fe2bad3-d785-394e-9949-89786b8a63d2"; + protected static String testLocalStorePath = Path.Combine(AgentSettings.Default.hyperv_plugin_root, "var", "test", "storagepool"); + protected static String testSecondaryStoreLocalPath = Path.Combine(AgentSettings.Default.hyperv_plugin_root, "var", "test", "secondary"); + + // TODO: differentiate between NFS and HTTP template URLs. + protected static String testSampleTemplateUUID = "TestCopiedLocalTemplate.vhdx"; + protected static String testSampleTemplateURL = testSampleTemplateUUID; + + // test volumes are both a minimal size vhdx. Changing the extension to .vhd makes on corrupt. + protected static String testSampleVolumeWorkingUUID = "TestVolumeLegit.vhdx"; + protected static String testSampleVolumeCorruptUUID = "TestVolumeCorrupt.vhd"; + protected static String testSampleVolumeTempUUID = "TestVolumeTemp.vhdx"; + protected static String testSampleVolumeTempUUIDNoExt = "TestVolumeTemp"; + protected static String testSampleVolumeWorkingURIJSON; + protected static String testSampleVolumeCorruptURIJSON; + protected static String testSampleVolumeTempURIJSON; + + protected static String testSampleTemplateURLJSON; + protected static String testLocalStorePathJSON; + + protected static IWmiCallsV2 wmiCallsV2; + + + private static ILog s_logger = LogManager.GetLogger(typeof(HypervResourceController1Test)); + + /// + /// Test WmiCalls to which incoming HTTP POST requests are dispatched. + /// + /// TODO: revise beyond first approximation + /// First approximation is a quick port of the existing Java tests for Hyper-V server resource. + /// A second approximation would use the AgentShell settings files directly. + /// A third approximation would look to invoke ServerResource methods via an HTTP request + /// + + public HypervResourceController1Test() + { + wmiCallsV2 = Substitute.For(); + //AgentService.ConfigServerResource(); + HypervResourceController.config.PrivateMacAddress = AgentSettings.Default.private_mac_address; + HypervResourceController.config.PrivateNetmask = AgentSettings.Default.private_ip_netmask; + HypervResourceController.config.StorageIpAddress = HypervResourceController.config.PrivateIpAddress; + HypervResourceController.config.StorageMacAddress = HypervResourceController.config.PrivateMacAddress; + HypervResourceController.config.StorageNetmask = HypervResourceController.config.PrivateNetmask; + + + // Used to create existing StoragePool in preparation for the ModifyStoragePool + testLocalStoreUUID = AgentSettings.Default.local_storage_uuid.ToString(); + + // Make sure secondary store is available. + string fullPath = Path.GetFullPath(testSecondaryStoreLocalPath); + s_logger.Info("Test secondary storage in " + fullPath); + DirectoryInfo testSecondarStoreDir = new DirectoryInfo(fullPath); + if (!testSecondarStoreDir.Exists) + { + try + { + testSecondarStoreDir.Create(); + } + catch (System.IO.IOException ex) + { + throw new NotImplementedException("Need to be able to create the folder " + testSecondarStoreDir.FullName + " failed due to " + ex.Message); + } + } + + // Convert to secondary storage string to canonical path + testSecondaryStoreLocalPath = testSecondarStoreDir.FullName; + AgentSettings.Default.local_secondary_storage_path = testSecondaryStoreLocalPath; + + // Make sure local primary storage is available + DirectoryInfo testPoolDir = new DirectoryInfo(testLocalStorePath); + //Assert.True(testPoolDir.Exists, "To simulate local file system Storage Pool, you need folder at " + testPoolDir.FullName); + + // Convert to local primary storage string to canonical path + testLocalStorePath = testPoolDir.FullName; + AgentSettings.Default.local_storage_path = testLocalStorePath; + + // Clean up old test files in local storage folder + FileInfo testVolWorks = new FileInfo(Path.Combine(testLocalStorePath, testSampleVolumeWorkingUUID)); + // Assert.True(testVolWorks.Exists, "Create a working virtual disk at " + testVolWorks.FullName); + + testSampleTemplateURLJSON = JsonConvert.SerializeObject(testSampleTemplateUUID); + s_logger.Info("Created " + testSampleTemplateURLJSON + " in local storage."); + + + // Capture other JSON encoded paths + testSampleVolumeWorkingURIJSON = Newtonsoft.Json.JsonConvert.SerializeObject(testVolWorks.FullName); + testLocalStorePathJSON = JsonConvert.SerializeObject(testLocalStorePath); + + // TODO: may need to initialise the server resource in future. + // s_hypervresource.initialize(); + + // Verify sample template is in place storage pool + s_logger.Info("setUp complete, sample StoragePool at " + testLocalStorePathJSON + + " sample template at " + testSampleTemplateURLJSON); + } + + private String CreateTestDiskImageFromExistingImage(FileInfo srcFile, + String dstPath, + String dstFileName) + { + var newFullname = Path.Combine(dstPath, dstFileName); + var newFileInfo = new FileInfo(newFullname); + if (!newFileInfo.Exists) + { + newFileInfo = srcFile.CopyTo(newFullname); + } + newFileInfo.Refresh(); + Assert.True(newFileInfo.Exists, "Attempted to create " + newFullname + " from " + newFileInfo.FullName); + + return JsonConvert.SerializeObject(newFileInfo.FullName); + } + + [Fact] + public void TestCreateCommand() + { + DirectoryInfo localStorePath = new DirectoryInfo(testLocalStorePath); + if (!localStorePath.Exists) + { + try + { + localStorePath.Create(); + } + catch (System.IO.IOException ex) + { + throw new NotImplementedException("Need to be able to create the folder " + localStorePath.FullName + " failed due to " + ex.Message); + } + } + + FileInfo sampleTemplateFile = new FileInfo(Path.Combine(testLocalStorePath, testSampleTemplateUUID)); + if (!sampleTemplateFile.Exists) + { + //Create a file to write to. + using (StreamWriter sw = sampleTemplateFile.CreateText()) + { + sw.WriteLine("This is fake template file for test"); + } + } + var counter = 0; + wmiCallsV2.When(x => x.CreateDynamicVirtualHardDisk(Arg.Any(), Arg.Any())).Do(x => counter++); + // TODO: Need sample to update the test. + // Arrange + String createCmd = "{\"volId\":10,\"pool\":{\"id\":201,\"uuid\":\"" + testLocalStoreUUID + "\",\"host\":\"" + HypervResourceController.config.StorageIpAddress + "\"" + + ",\"path\":" + testLocalStorePathJSON + ",\"port\":0,\"type\":\"Filesystem\"},\"diskCharacteristics\":{\"size\":0," + + "\"tags\":[],\"type\":\"ROOT\",\"name\":\"ROOT-9\",\"useLocalStorage\":true,\"recreatable\":true,\"diskOfferingId\":11," + + "\"volumeId\":10,\"hyperType\":\"Hyperv\"},\"templateUrl\":" + testSampleTemplateURLJSON + ",\"contextMap\":{},\"wait\":0}"; + dynamic jsonCreateCmd = JsonConvert.DeserializeObject(createCmd); + HypervResourceController rsrcServer = new HypervResourceController(); + HypervResourceController.wmiCallsV2 = wmiCallsV2; + + Assert.True(Directory.Exists(testLocalStorePath), testLocalStorePath + " does not exist "); + string filePath = Path.Combine(testLocalStorePath, (string)JsonConvert.DeserializeObject(testSampleTemplateURLJSON)); + Assert.True(File.Exists(filePath), "The template we make volumes from is missing from path " + filePath); + int fileCount = Directory.GetFiles(testLocalStorePath).Length; + s_logger.Debug(" test local store has " + fileCount + "files"); + + // Act + // Test requires there to be a template at the tempalteUrl, which is its location in the local file system. + dynamic jsonResult = rsrcServer.CreateCommand(jsonCreateCmd); + s_logger.Debug("CreateDynamicVirtualHardDisk method is called " + counter + " times"); + + //Assert.Equal(counter, 1); + + JObject ansAsProperty2 = jsonResult[0]; + dynamic ans = ansAsProperty2.GetValue(CloudStackTypes.CreateAnswer); + Assert.NotNull(ans); + Assert.True((bool)ans.result, "Failed to CreateCommand due to " + (string)ans.result); + Assert.Equal(Directory.GetFiles(testLocalStorePath).Length, fileCount + 1); + FileInfo newFile = new FileInfo((string)ans.volume.path); + Assert.True(newFile.Length > 0, "The new file should have a size greater than zero"); + newFile.Delete(); + sampleTemplateFile.Delete(); + } + + [Fact] + public void TestDestroyCommand() + { + testSampleVolumeTempURIJSON = "\"storagepool\""; + // Arrange + String destroyCmd = //"{\"volume\":" + getSampleVolumeObjectTO() + "}"; + "{\"volume\":{\"name\":\"" + testSampleVolumeTempUUIDNoExt + + "\",\"storagePoolType\":\"Filesystem\"," + + "\"mountPoint\":" + + testLocalStorePathJSON + + ",\"path\":" + testSampleVolumeTempURIJSON + + ",\"storagePoolUuid\":\"" + testLocalStoreUUID + + "\"," + + "\"type\":\"ROOT\",\"id\":9,\"size\":0}}"; + + ImageManagementService imgmgr = new ImageManagementService(); + wmiCallsV2.GetImageManagementService().Returns(imgmgr); + + HypervResourceController rsrcServer = new HypervResourceController(); + HypervResourceController.wmiCallsV2 = wmiCallsV2; + + dynamic jsonDestroyCmd = JsonConvert.DeserializeObject(destroyCmd); + + // Act + dynamic destroyAns = rsrcServer.DestroyCommand(jsonDestroyCmd); + + // Assert + JObject ansAsProperty2 = destroyAns[0]; + dynamic ans = ansAsProperty2.GetValue(CloudStackTypes.Answer); + String path = jsonDestroyCmd.volume.path; + Assert.True((bool)ans.result, "DestroyCommand did not succeed " + ans.details); + Assert.True(!File.Exists(path), "Failed to delete file " + path); + } + + [Fact] + public void TestStartCommand() + { + ComputerSystem system = new ComputerSystem(); + wmiCallsV2.DeployVirtualMachine(Arg.Any(), Arg.Any()).Returns(system); + + // Arrange + HypervResourceController rsrcServer = new HypervResourceController(); + HypervResourceController.wmiCallsV2 = wmiCallsV2; + String sample = getSampleStartCommand(); + + + dynamic jsonStartCmd = JsonConvert.DeserializeObject(sample); + + // Act + dynamic startAns = rsrcServer.StartCommand(jsonStartCmd); + + // Assert + Assert.NotNull(startAns[0][CloudStackTypes.StartAnswer]); + Assert.True((bool)startAns[0][CloudStackTypes.StartAnswer].result, "StartCommand did not succeed " + startAns[0][CloudStackTypes.StartAnswer].details); + + Assert.Null((string)startAns[0][CloudStackTypes.StartAnswer].details); + } + + [Fact] + public void TestStopCommand() + { + //string vmName = "Test VM"; + var counter = 0; + wmiCallsV2.When(x => x.DestroyVm(Arg.Any())).Do(x => counter++); + + // Arrange + HypervResourceController rsrcServer = new HypervResourceController(); + HypervResourceController.wmiCallsV2 = wmiCallsV2; + + String sampleStop = "{\"isProxy\":false,\"vmName\":\"i-2-17-VM\",\"contextMap\":{},\"checkBeforeCleanup\":false,\"wait\":0}"; + dynamic jsonStopCmd = JsonConvert.DeserializeObject(sampleStop); + + // Act + dynamic stopAns = rsrcServer.StopCommand(jsonStopCmd); + + // Assert VM is gone! + Assert.NotNull(stopAns[0][CloudStackTypes.StopAnswer]); + Assert.True((bool)stopAns[0][CloudStackTypes.StopAnswer].result, "StopCommand did not succeed " + stopAns[0][CloudStackTypes.StopAnswer].details); + + Assert.Null((string)stopAns[0][CloudStackTypes.StopAnswer].details); + Assert.Equal(counter, 1); + } + + public static String getSamplePrimaryDataStoreInfo() + { + String samplePrimaryDataStoreInfo = + "{\"org.apache.cloudstack.storage.to.PrimaryDataStoreTO\":" + + "{\"uuid\":\"" + testLocalStoreUUID + "\"," + + "\"id\":201," + + "\"host\":\"" + testPrimaryDataStoreHost + "\"," + + "\"type\":\"Filesystem\"," + // Not used in PrimaryDataStoreTO + "\"poolType\":\"Filesystem\"," + // Not used in PrimaryDataStoreTO + "\"path\":" + testLocalStorePathJSON + "," + + "\"port\":0}" + + "}"; + return samplePrimaryDataStoreInfo; + } + + public static String getSampleVolumeObjectTO() + { + String sampleVolumeObjectTO = + "{\"org.apache.cloudstack.storage.to.VolumeObjectTO\":" + + "{\"uuid\":\"19ae8e67-cb2c-4ab4-901e-e0b864272b59\"," + + "\"volumeType\":\"ROOT\"," + + "\"format\":\"VHDX\"," + + "\"dataStore\":" + getSamplePrimaryDataStoreInfo() + "," + + "\"name\":\"" + testSampleVolumeTempUUIDNoExt + "\"," + + "\"size\":52428800," + + "\"volumeId\":10," + + // "\"vmName\":\"i-3-5-VM\"," + // TODO: do we have to fill in the vmName? + "\"accountId\":3,\"id\":10}" + + "}"; // end of destTO + return sampleVolumeObjectTO; + } + + public static String getSampleStartCommand() + { + String sample = "{\"vm\":{\"id\":17,\"name\":\"i-2-17-VM\",\"type\":\"User\",\"cpus\":1,\"speed\":500," + + "\"minRam\":536870912,\"maxRam\":536870912,\"arch\":\"x86_64\"," + + "\"os\":\"CentOS 6.0 (64-bit)\",\"bootArgs\":\"\",\"rebootOnCrash\":false," + + "\"enableHA\":false,\"limitCpuUse\":false,\"vncPassword\":\"31f82f29aff646eb\"," + + "\"params\":{},\"uuid\":\"8b030b6a-0243-440a-8cc5-45d08815ca11\"" + + ",\"disks\":[" + + "{\"data\":" + getSampleVolumeObjectTO() + ",\"diskSeq\":0,\"type\":\"ROOT\"}," + + "{\"diskSeq\":1,\"type\":\"ISO\"}" + + "]," + + "\"nics\":[" + + "{\"deviceId\":0,\"networkRateMbps\":100,\"defaultNic\":true,\"uuid\":\"99cb4813-23af-428c-a87a-2d1899be4f4b\"," + + "\"ip\":\"10.1.1.67\",\"netmask\":\"255.255.255.0\",\"gateway\":\"10.1.1.1\"," + + "\"mac\":\"02:00:51:2c:00:0e\",\"dns1\":\"4.4.4.4\",\"broadcastType\":\"Vlan\",\"type\":\"Guest\"," + + "\"broadcastUri\":\"vlan://261\",\"isolationUri\":\"vlan://261\",\"isSecurityGroupEnabled\":false}" + + "]},\"contextMap\":{},\"wait\":0}"; + return sample; + } + } +} diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/ServerResource.Tests/HypervResourceControllerTest.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/ServerResource.Tests/HypervResourceControllerTest.cs index f816309c820..288d1a1c406 100644 --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/ServerResource.Tests/HypervResourceControllerTest.cs +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/ServerResource.Tests/HypervResourceControllerTest.cs @@ -1,1147 +1,1147 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. -using System; -using CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION; -using System.Management; -using Newtonsoft.Json.Linq; -using Newtonsoft.Json; -using System.IO; -using log4net; -using HypervResource; -using CloudStack.Plugin.AgentShell; -using System.Collections.Generic; -using System.Xml; -using Xunit; - -namespace ServerResource.Tests -{ - public class HypervResourceControllerTest - { - protected static string testCifsUrl = AgentSettings.Default.testCifsUrl; - protected static string testCifsPath = AgentSettings.Default.testCifsPath; - protected static String testPrimaryDataStoreHost = HypervResourceController.config.StorageIpAddress; - protected static String testS3TemplateName = AgentSettings.Default.testS3TemplateName; - protected static String testCifsTemplateName = AgentSettings.Default.testS3TemplateName; - protected static String testSystemVMTemplateName = AgentSettings.Default.testSystemVMTemplateName; - protected static String testSystemVMTemplateNameNoExt = AgentSettings.Default.testSystemVMTemplateNameNoExt; - protected static String testLocalStoreUUID = "5fe2bad3-d785-394e-9949-89786b8a63d2"; - protected static String testLocalStorePath = Path.Combine(AgentSettings.Default.hyperv_plugin_root, "var", "test", "storagepool"); - protected static String testSecondaryStoreLocalPath = Path.Combine(AgentSettings.Default.hyperv_plugin_root, "var", "test", "secondary"); - - // TODO: differentiate between NFS and HTTP template URLs. - protected static String testSampleTemplateUUID = "TestCopiedLocalTemplate.vhdx"; - protected static String testSampleTemplateURL = testSampleTemplateUUID; - - // test volumes are both a minimal size vhdx. Changing the extension to .vhd makes on corrupt. - protected static String testSampleVolumeWorkingUUID = "TestVolumeLegit.vhdx"; - protected static String testSampleVolumeCorruptUUID = "TestVolumeCorrupt.vhd"; - protected static String testSampleVolumeTempUUID = "TestVolumeTemp.vhdx"; - protected static String testSampleVolumeTempUUIDNoExt = "TestVolumeTemp"; - protected static String testSampleVolumeWorkingURIJSON; - protected static String testSampleVolumeCorruptURIJSON; - protected static String testSampleVolumeTempURIJSON; - - protected static String testSampleTemplateURLJSON; - protected static String testLocalStorePathJSON; - - protected static WmiCallsV2 wmiCallsV2 = new WmiCallsV2(); - - private static ILog s_logger = LogManager.GetLogger(typeof(HypervResourceControllerTest)); - - /// - /// Test WmiCalls to which incoming HTTP POST requests are dispatched. - /// - /// TODO: revise beyond first approximation - /// First approximation is a quick port of the existing Java tests for Hyper-V server resource. - /// A second approximation would use the AgentShell settings files directly. - /// A third approximation would look to invoke ServerResource methods via an HTTP request - /// - public HypervResourceControllerTest() - { - AgentService.ConfigServerResource(); - HypervResourceController.config.PrivateMacAddress = AgentSettings.Default.private_mac_address; - HypervResourceController.config.PrivateNetmask = AgentSettings.Default.private_ip_netmask; - HypervResourceController.config.StorageIpAddress = HypervResourceController.config.PrivateIpAddress; - HypervResourceController.config.StorageMacAddress = HypervResourceController.config.PrivateMacAddress; - HypervResourceController.config.StorageNetmask = HypervResourceController.config.PrivateNetmask; - - - // Used to create existing StoragePool in preparation for the ModifyStoragePool - testLocalStoreUUID = AgentSettings.Default.local_storage_uuid.ToString(); - - // Make sure secondary store is available. - string fullPath = Path.GetFullPath(testSecondaryStoreLocalPath); - s_logger.Info("Test secondary storage in " + fullPath); - DirectoryInfo testSecondarStoreDir = new DirectoryInfo(fullPath); - if (!testSecondarStoreDir.Exists) - { - try - { - testSecondarStoreDir.Create(); - } - catch (System.IO.IOException ex) - { - throw new NotImplementedException("Need to be able to create the folder " + testSecondarStoreDir.FullName + " failed due to " + ex.Message); - } - } - - // Convert to secondary storage string to canonical path - testSecondaryStoreLocalPath = testSecondarStoreDir.FullName; - AgentSettings.Default.local_secondary_storage_path = testSecondaryStoreLocalPath; - - // Make sure local primary storage is available - DirectoryInfo testPoolDir = new DirectoryInfo(testLocalStorePath); - Assert.True(testPoolDir.Exists, "To simulate local file system Storage Pool, you need folder at " + testPoolDir.FullName); - - // Convert to local primary storage string to canonical path - testLocalStorePath = testPoolDir.FullName; - AgentSettings.Default.local_storage_path = testLocalStorePath; - - // Clean up old test files in local storage folder - FileInfo testVolWorks = new FileInfo(Path.Combine(testLocalStorePath, testSampleVolumeWorkingUUID)); - Assert.True(testVolWorks.Exists, "Create a working virtual disk at " + testVolWorks.FullName); - - - // Delete all temporary files in local folder save the testVolWorks - foreach (var file in testPoolDir.GetFiles()) - { - if (file.FullName == testVolWorks.FullName) - { - continue; - } - file.Delete(); - file.Refresh(); - Assert.False(file.Exists, "removed file from previous test called " + file.FullName); - } - - // Recreate starting point files for test, and record JSON encoded paths for each ... - testSampleVolumeTempURIJSON = CreateTestDiskImageFromExistingImage(testVolWorks, testLocalStorePath, testSampleVolumeTempUUID); - s_logger.Info("Created " + testSampleVolumeTempURIJSON); - testSampleVolumeCorruptURIJSON = CreateTestDiskImageFromExistingImage(testVolWorks, testLocalStorePath, testSampleVolumeCorruptUUID); - s_logger.Info("Created " + testSampleVolumeCorruptURIJSON); - CreateTestDiskImageFromExistingImage(testVolWorks, testLocalStorePath, testSampleTemplateUUID); - testSampleTemplateURLJSON = JsonConvert.SerializeObject(testSampleTemplateUUID); - s_logger.Info("Created " + testSampleTemplateURLJSON + " in local storage."); - - // ... including a secondary storage template: - CreateTestDiskImageFromExistingImage(testVolWorks, testSecondarStoreDir.FullName, "af39aa7f-2b12-37e1-86d3-e23f2f005101.vhdx"); - s_logger.Info("Created " + "af39aa7f-2b12-37e1-86d3-e23f2f005101.vhdx" + " in secondary (NFS) storage."); - - - // Capture other JSON encoded paths - testSampleVolumeWorkingURIJSON = Newtonsoft.Json.JsonConvert.SerializeObject(testVolWorks.FullName); - testLocalStorePathJSON = JsonConvert.SerializeObject(testLocalStorePath); - - // TODO: may need to initialise the server resource in future. - // s_hypervresource.initialize(); - - // Verify sample template is in place storage pool - s_logger.Info("setUp complete, sample StoragePool at " + testLocalStorePathJSON - + " sample template at " + testSampleTemplateURLJSON); - } - - private String CreateTestDiskImageFromExistingImage(FileInfo srcFile, - String dstPath, - String dstFileName) - { - var newFullname = Path.Combine(dstPath, dstFileName); - var newFileInfo = new FileInfo(newFullname); - if (!newFileInfo.Exists) - { - newFileInfo = srcFile.CopyTo(newFullname); - } - newFileInfo.Refresh(); - Assert.True(newFileInfo.Exists, "Attempted to create " + newFullname + " from " + newFileInfo.FullName); - - return JsonConvert.SerializeObject(newFileInfo.FullName); - } - - [Fact(Skip="these are functional tests")] - public void TestPrimaryStorageDownloadCommandHTTP() - { - string downloadURI = "https://s3-eu-west-1.amazonaws.com/cshv3eu/SmallDisk.vhdx"; - corePrimaryStorageDownloadCommandTestCycle(downloadURI); - } - - private void corePrimaryStorageDownloadCommandTestCycle(string downloadURI) - { - // Arrange - HypervResourceController rsrcServer = new HypervResourceController(); - dynamic jsonPSDCmd = JsonConvert.DeserializeObject(samplePrimaryDownloadCommand()); - jsonPSDCmd.url = downloadURI; - - // Act - dynamic jsonResult = rsrcServer.PrimaryStorageDownloadCommand(jsonPSDCmd); - - // Assert - JObject ansAsProperty = jsonResult[0]; - dynamic ans = ansAsProperty.GetValue(CloudStackTypes.PrimaryStorageDownloadAnswer); - Assert.True((bool)ans.result, "PrimaryStorageDownloadCommand did not succeed " + ans.details); - - // Test that URL of downloaded template works for file creation. - dynamic jsonCreateCmd = JsonConvert.DeserializeObject(CreateCommandSample()); - jsonCreateCmd.templateUrl = ans.installPath; - dynamic jsonAns2 = rsrcServer.CreateCommand(jsonCreateCmd); - JObject ansAsProperty2 = jsonAns2[0]; - dynamic ans2 = ansAsProperty2.GetValue(CloudStackTypes.CreateAnswer); - - Assert.True((bool)ans2.result, (string)ans2.details); - - FileInfo newFile = new FileInfo((string)ans2.volume.path); - Assert.True(newFile.Length > 0, "The new file should have a size greater than zero"); - newFile.Delete(); - } - - private string samplePrimaryDownloadCommand() - { - String cmdJson = "{\"localPath\":" + testLocalStorePathJSON + - ",\"poolUuid\":\"" + testLocalStoreUUID + "\",\"poolId\":201," + - "\"secondaryStorageUrl\":\"nfs://10.70.176.36/mnt/cshv3/secondarystorage\"," + - "\"primaryStorageUrl\":\"nfs://" + HypervResourceController.config.StorageIpAddress + "E:\\\\Disks\\\\Disks\"," + - "\"url\":\"nfs://10.70.176.36/mnt/cshv3/secondarystorage/template/tmpl//2/204//af39aa7f-2b12-37e1-86d3-e23f2f005101.vhdx\"," + - "\"format\":\"VHDX\",\"accountId\":2,\"name\":\"204-2-5a1db1ac-932b-3e7e-a0e8-5684c72cb862\"" + - ",\"contextMap\":{},\"wait\":10800}"; - return cmdJson; - } - - public string CreateCommandSample() - { - String sample = "{\"volId\":17,\"pool\":{\"id\":201,\"uuid\":\"" + testLocalStoreUUID + "\",\"host\":\"" + HypervResourceController.config.StorageIpAddress + "\"" + - ",\"path\":" + testLocalStorePathJSON + ",\"port\":0,\"type\":\"Filesystem\"},\"diskCharacteristics\":{\"size\":0," + - "\"tags\":[],\"type\":\"ROOT\",\"name\":\"ROOT-15\",\"useLocalStorage\":true,\"recreatable\":true,\"diskOfferingId\":11," + - "\"volumeId\":17,\"hyperType\":\"Hyperv\"},\"templateUrl\":" + testSampleTemplateURLJSON + ",\"wait\":0}"; - return sample; - } - - [Fact(Skip="these are functional tests")] - public void TestDestroyCommand() - { - // Arrange - String sampleVolume = getSampleVolumeObjectTO(); - String destroyCmd = //"{\"volume\":" + getSampleVolumeObjectTO() + "}"; - "{\"volume\":{\"name\":\"" + testSampleVolumeTempUUIDNoExt - + "\",\"storagePoolType\":\"Filesystem\"," - + "\"mountPoint\":" - + testLocalStorePathJSON - + ",\"path\":" + testSampleVolumeTempURIJSON - + ",\"storagePoolUuid\":\"" + testLocalStoreUUID - + "\"," - + "\"type\":\"ROOT\",\"id\":9,\"size\":0}}"; - - HypervResourceController rsrcServer = new HypervResourceController(); - dynamic jsonDestroyCmd = JsonConvert.DeserializeObject(destroyCmd); - - // Act - dynamic destroyAns = rsrcServer.DestroyCommand(jsonDestroyCmd); - - // Assert - JObject ansAsProperty2 = destroyAns[0]; - dynamic ans = ansAsProperty2.GetValue(CloudStackTypes.Answer); - String path = jsonDestroyCmd.volume.path; - Assert.True((bool)ans.result, "DestroyCommand did not succeed " + ans.details); - Assert.True(!File.Exists(path), "Failed to delete file " + path); - } - - [Fact(Skip="these are functional tests")] - public void TestCreateCommand() - { - // TODO: Need sample to update the test. - // Arrange - String createCmd = "{\"volId\":10,\"pool\":{\"id\":201,\"uuid\":\"" + testLocalStoreUUID + "\",\"host\":\"" + HypervResourceController.config.StorageIpAddress + "\"" + - ",\"path\":" + testLocalStorePathJSON + ",\"port\":0,\"type\":\"Filesystem\"},\"diskCharacteristics\":{\"size\":0," + - "\"tags\":[],\"type\":\"ROOT\",\"name\":\"ROOT-9\",\"useLocalStorage\":true,\"recreatable\":true,\"diskOfferingId\":11," + - "\"volumeId\":10,\"hyperType\":\"Hyperv\"},\"templateUrl\":" + testSampleTemplateURLJSON + ",\"contextMap\":{},\"wait\":0}"; - dynamic jsonCreateCmd = JsonConvert.DeserializeObject(createCmd); - HypervResourceController rsrcServer = new HypervResourceController(); - - Assert.True(Directory.Exists(testLocalStorePath)); - string filePath = Path.Combine(testLocalStorePath, (string)JsonConvert.DeserializeObject(testSampleTemplateURLJSON)); - Assert.True(File.Exists(filePath), "The template we make volumes from is missing from path " + filePath); - int fileCount = Directory.GetFiles(testLocalStorePath).Length; - s_logger.Debug(" test local store has " + fileCount + "files"); - - // Act - // Test requires there to be a template at the tempalteUrl, which is its location in the local file system. - dynamic jsonResult = rsrcServer.CreateCommand(jsonCreateCmd); - - JObject ansAsProperty2 = jsonResult[0]; - dynamic ans = ansAsProperty2.GetValue(CloudStackTypes.CreateAnswer); - Assert.NotNull(ans); - Assert.True((bool)ans.result, "Failed to CreateCommand due to " + (string)ans.result); - Assert.Equal(Directory.GetFiles(testLocalStorePath).Length, fileCount + 1); - FileInfo newFile = new FileInfo((string)ans.volume.path); - Assert.True(newFile.Length > 0, "The new file should have a size greater than zero"); - newFile.Delete(); - } - - /// - /// Possible additional tests: place an ISO in the drive - /// - [Fact(Skip="these are functional tests")] - public void TestStartStopCommand() - { - string vmName = TestStartCommand(); - TestStopCommand(vmName); - } - - public static String getSamplePrimaryDataStoreInfo() - { - String samplePrimaryDataStoreInfo = - "{\"org.apache.cloudstack.storage.to.PrimaryDataStoreTO\":" + - "{\"uuid\":\"" + testLocalStoreUUID + "\"," + - "\"id\":201," + - "\"host\":\"" + testPrimaryDataStoreHost + "\"," + - "\"type\":\"Filesystem\"," + // Not used in PrimaryDataStoreTO - "\"poolType\":\"Filesystem\"," + // Not used in PrimaryDataStoreTO - "\"path\":" + testLocalStorePathJSON + "," + - "\"port\":0}" + - "}"; - return samplePrimaryDataStoreInfo; - } - - public static String getSampleVolumeObjectTO() - { - String sampleVolumeObjectTO = - "{\"org.apache.cloudstack.storage.to.VolumeObjectTO\":" + - "{\"uuid\":\"19ae8e67-cb2c-4ab4-901e-e0b864272b59\"," + - "\"volumeType\":\"ROOT\"," + - "\"format\":\"VHDX\"," + - "\"dataStore\":" + getSamplePrimaryDataStoreInfo() + "," + - "\"name\":\"" + testSampleVolumeTempUUIDNoExt + "\"," + - "\"size\":52428800," + - "\"volumeId\":10," + - // "\"vmName\":\"i-3-5-VM\"," + // TODO: do we have to fill in the vmName? - "\"accountId\":3,\"id\":10}" + - "}"; // end of destTO - return sampleVolumeObjectTO; - } - - public static String getSampleStartCommand() - { - String sample = "{\"vm\":{\"id\":17,\"name\":\"i-2-17-VM\",\"type\":\"User\",\"cpus\":1,\"speed\":500," + - "\"minRam\":536870912,\"maxRam\":536870912,\"arch\":\"x86_64\"," + - "\"os\":\"CentOS 6.0 (64-bit)\",\"bootArgs\":\"\",\"rebootOnCrash\":false," + - "\"enableHA\":false,\"limitCpuUse\":false,\"vncPassword\":\"31f82f29aff646eb\"," + - "\"params\":{},\"uuid\":\"8b030b6a-0243-440a-8cc5-45d08815ca11\"" + - ",\"disks\":[" + - "{\"data\":" + getSampleVolumeObjectTO() + ",\"diskSeq\":0,\"type\":\"ROOT\"}," + - "{\"diskSeq\":1,\"type\":\"ISO\"}" + - "]," + - "\"nics\":[" + - "{\"deviceId\":0,\"networkRateMbps\":100,\"defaultNic\":true,\"uuid\":\"99cb4813-23af-428c-a87a-2d1899be4f4b\"," + - "\"ip\":\"10.1.1.67\",\"netmask\":\"255.255.255.0\",\"gateway\":\"10.1.1.1\"," + - "\"mac\":\"02:00:51:2c:00:0e\",\"dns1\":\"4.4.4.4\",\"broadcastType\":\"Vlan\",\"type\":\"Guest\"," + - "\"broadcastUri\":\"vlan://261\",\"isolationUri\":\"vlan://261\",\"isSecurityGroupEnabled\":false}" + - "]},\"contextMap\":{},\"wait\":0}"; - return sample; - } - - - [Fact(Skip="these are functional tests")] - public void TestCopyCommandFromCifs() - { - // Arrange - string sampleCopyCommandForTemplateDownload = - #region string_literal - // org.apache.cloudstack.storage.command.CopyCommand - "{\"srcTO\":" + - "{\"org.apache.cloudstack.storage.to.TemplateObjectTO\":" + - "{\"path\":\"" + testCifsPath + "\"," + - "\"origUrl\":\"http://10.147.28.7/templates/5d67394c-4efd-4b62-966b-51aa53b35277.vhd.bz2\"," + - "\"uuid\":\"7e4ca941-cb1b-4113-ab9e-043960d0fb10\"," + - "\"id\":206," + - "\"format\":\"VHDX\"," + - "\"accountId\":2," + - "\"checksum\":\"4b31e2846cc67fc10ea7281986519a54\"," + - "\"hvm\":true," + - "\"displayText\":\"OS031\"," + - "\"imageDataStore\":" + - "{\"com.cloud.agent.api.to.NfsTO\":" + - "{\"_url\":\"" + testCifsUrl + "\"," + // Unique item here - "\"_role\":\"Image\"}" + - "}," + // end of imageDataStore - "\"hypervisorType\":\"Hyperv\"," + - "\"name\":\"" + testS3TemplateName + "\"}" + - "}," + // end of srcTO - "\"destTO\":" + - "{\"org.apache.cloudstack.storage.to.TemplateObjectTO\":" + - "{" + - "\"origUrl\":\"http://10.147.28.7/templates/5d67394c-4efd-4b62-966b-51aa53b35277.vhd.bz2\"," + - "\"uuid\":\"7e4ca941-cb1b-4113-ab9e-043960d0fb10\"," + - "\"id\":206," + - "\"format\":\"VHDX\"," + - "\"accountId\":2," + - "\"checksum\":\"4b31e2846cc67fc10ea7281986519a54\"," + - "\"hvm\":true," + - "\"displayText\":\"Test of CIFS Download\"," + - "\"imageDataStore\":" + getSamplePrimaryDataStoreInfo() + "," + // end of imageDataStore - "\"name\":\"" + testS3TemplateName + "\"," + - "\"hypervisorType\":\"Hyperv\"}" + - "}," +// end of destTO - "\"wait\":10800}"; // end of CopyCommand - #endregion - - HypervResourceController rsrcServer; - dynamic jsonDownloadCopyCmd; - string dwnldDest; - dynamic jsonCloneCopyCmd; - string newVolName; - CopyCommandTestSetupCifs(null, sampleCopyCommandForTemplateDownload, out rsrcServer, out jsonDownloadCopyCmd, out dwnldDest, out jsonCloneCopyCmd, out newVolName); - - // Act & Assert - DownloadTemplateToPrimaryStorage(rsrcServer, jsonDownloadCopyCmd, dwnldDest); - - // Repeat to verify ability to detect existing file. - DownloadTemplateToPrimaryStorage(rsrcServer, jsonDownloadCopyCmd, dwnldDest); - - File.Delete(dwnldDest); - } - - [Fact(Skip="these are functional tests")] - public void TestCopyCommand() - { - // Arrange - string sampleCopyCommandToCreateVolumeFromTemplate = - #region string_literal - // org.apache.cloudstack.storage.command.CopyCommand - "{\"srcTO\":" + - "{\"org.apache.cloudstack.storage.to.TemplateObjectTO\":" + - "{" + - "\"origUrl\":\"http://people.apache.org/~bhaisaab/vms/ttylinux_pv.vhd\"," + - "\"uuid\":\"9873f1c0-bdcc-11e2-8baa-ea85dab5fcd0\"," + - "\"id\":5," + - "\"format\":\"VHDX\"," + - "\"accountId\":1," + - "\"checksum\":\"4b31e2846cc67fc10ea7281986519a54\"," + - "\"hvm\":false," + - "\"displayText\":\"tiny Linux\"," + - "\"imageDataStore\":" + getSamplePrimaryDataStoreInfo() + "," + - "\"name\":\"" + testS3TemplateName + "\"}" + - "}," + // end of srcTO - "\"destTO\":" + - "{\"org.apache.cloudstack.storage.to.VolumeObjectTO\":" + - "{\"uuid\":\"19ae8e67-cb2c-4ab4-901e-e0b864272b59\"," + - "\"volumeType\":\"ROOT\"," + - "\"dataStore\":" + getSamplePrimaryDataStoreInfo() + "," + - "\"name\":\"ROOT-5\"," + - "\"size\":52428800," + - "\"volumeId\":10," + - "\"vmName\":\"i-3-5-VM\"," + - "\"accountId\":3," + - "\"id\":10 }" + - "}," + // end of destTO - "\"wait\":0}"; // end of Copy Command - #endregion - //"name":"ROOT-8","size":140616708,"volumeId":8,"vmName":"s-8-VM","accountId":1,"id":8}},"contextMap":{},"wait":0} - - string sampleCopyCommandForTemplateDownload = - #region string_literal - // org.apache.cloudstack.storage.command.CopyCommand - "{\"srcTO\":" + - "{\"org.apache.cloudstack.storage.to.TemplateObjectTO\":" + - "{\"path\":\"" + testS3TemplateName + ".vhdx" + "\"," + - "\"origUrl\":\"http://10.147.28.7/templates/5d67394c-4efd-4b62-966b-51aa53b35277.vhd.bz2\"," + - "\"uuid\":\"7e4ca941-cb1b-4113-ab9e-043960d0fb10\"," + - "\"id\":206," + - "\"format\":\"VHDX\"," + - "\"accountId\":2," + - "\"checksum\":\"4b31e2846cc67fc10ea7281986519a54\"," + - "\"hvm\":true," + - "\"displayText\":\"OS031\"," + - "\"imageDataStore\":" + - "{\"com.cloud.agent.api.to.S3TO\":" + - "{\"id\":1," + - "\"uuid\":\"95a64c8f-2128-4502-b5b4-0d7aa77406d2\"," + - "\"accessKey\":\"" + AgentSettings.Default.testS3AccessKey + "\"," + - "\"secretKey\":\"" + AgentSettings.Default.testS3SecretKey + "\"," + - "\"endPoint\":\"" + AgentSettings.Default.testS3Endpoint + "\"," + - "\"bucketName\":\"" + AgentSettings.Default.testS3Bucket + "\"," + - "\"httpsFlag\":false," + - "\"created\":\"May 19, 2013 4:17:25 PM\"}" + - "}," + // end of imageDataStore - "\"name\":\"" + testS3TemplateName + "\"}" + - "}," + // end of srcTO - "\"destTO\":" + - "{\"org.apache.cloudstack.storage.to.TemplateObjectTO\":" + - "{" + - "\"origUrl\":\"http://10.147.28.7/templates/5d67394c-4efd-4b62-966b-51aa53b35277.vhd.bz2\"," + - "\"uuid\":\"7e4ca941-cb1b-4113-ab9e-043960d0fb10\"," + - "\"id\":206," + - "\"format\":\"VHDX\"," + - "\"accountId\":2," + - "\"checksum\":\"4b31e2846cc67fc10ea7281986519a54\"," + - "\"hvm\":true," + - "\"displayText\":\"OS031\"," + - "\"imageDataStore\":" + getSamplePrimaryDataStoreInfo() + "," + // end of imageDataStore - "\"name\":\"" + testS3TemplateName + "\"}" + - "}," +// end of destTO - "\"wait\":10800}"; // end of CopyCommand - #endregion - - HypervResourceController rsrcServer; - dynamic jsonDownloadCopyCmd; - string dwnldDest; - dynamic jsonCloneCopyCmd; - string newVolName; - CopyCommandTestSetup(sampleCopyCommandToCreateVolumeFromTemplate, sampleCopyCommandForTemplateDownload, out rsrcServer, out jsonDownloadCopyCmd, out dwnldDest, out jsonCloneCopyCmd, out newVolName); - - // Act & Assert - DownloadTemplateToPrimaryStorage(rsrcServer, jsonDownloadCopyCmd, dwnldDest); - CreateVolumeFromTemplate(rsrcServer, jsonCloneCopyCmd, newVolName); - - // Repeat to verify ability to detect existing file. - DownloadTemplateToPrimaryStorage(rsrcServer, jsonDownloadCopyCmd, dwnldDest); - - File.Delete(dwnldDest); - File.Delete(newVolName); - } - - private static void CreateVolumeFromTemplate(HypervResourceController rsrcServer, dynamic jsonCloneCopyCmd, string newVolName) - { - dynamic copyResult = rsrcServer.CopyCommand(jsonCloneCopyCmd); - - // Assert - Assert.NotNull(copyResult[0][CloudStackTypes.CopyCmdAnswer]); - Assert.True((bool)copyResult[0][CloudStackTypes.CopyCmdAnswer].result, "CopyCommand did not succeed " + copyResult[0][CloudStackTypes.CopyCmdAnswer].details); - Assert.True(File.Exists(newVolName), "CopyCommand failed to generate " + newVolName); - } - - private static void DownloadTemplateToPrimaryStorage(HypervResourceController rsrcServer, dynamic jsonDownloadCopyCmd, string dwnldDest) - { - dynamic dwnldResult = rsrcServer.CopyCommand(jsonDownloadCopyCmd); - - // Assert - Assert.NotNull(dwnldResult[0][CloudStackTypes.CopyCmdAnswer]); - Assert.True((bool)dwnldResult[0][CloudStackTypes.CopyCmdAnswer].result, "CopyCommand did not succeed " + dwnldResult[0][CloudStackTypes.CopyCmdAnswer].details); - Assert.True(File.Exists(dwnldDest), "CopyCommand failed to generate " + dwnldDest); - } - - [Fact(Skip="these are functional tests")] - public void TestCopyCommandBz2Img() - { - // Arrange - string sampleCopyCommandToCreateVolumeFromTemplate = - #region string_literal - // org.apache.cloudstack.storage.command.CopyCommand - "{\"srcTO\":" + - "{\"org.apache.cloudstack.storage.to.TemplateObjectTO\":" + - "{" + - "\"origUrl\":\"http://people.apache.org/~bhaisaab/vms/ttylinux_pv.vhd\"," + - "\"uuid\":\"9873f1c0-bdcc-11e2-8baa-ea85dab5fcd0\"," + - "\"id\":5," + - "\"format\":\"VHD\"," + - "\"accountId\":1," + - "\"checksum\":\"f613f38c96bf039f2e5cbf92fa8ad4f8\"," + - "\"hvm\":false," + - "\"displayText\":\"tiny Linux\"," + - "\"imageDataStore\":" + getSamplePrimaryDataStoreInfo() + "," + - "\"name\":\"" + testSystemVMTemplateNameNoExt + "\"}" + - "}," + // end of srcTO - "\"destTO\":" + - "{\"org.apache.cloudstack.storage.to.VolumeObjectTO\":" + - "{\"uuid\":\"19ae8e67-cb2c-4ab4-901e-e0b864272b59\"," + - "\"volumeType\":\"ROOT\"," + - "\"dataStore\":" + getSamplePrimaryDataStoreInfo() + "," + - "\"name\":\"ROOT-5\"," + - "\"size\":52428800," + - "\"volumeId\":10," + - "\"vmName\":\"i-3-5-VM\"," + - "\"accountId\":1," + - "\"id\":10}" + - "}," + // end of destTO - "\"wait\":0}"; // end of Copy Command - #endregion - - string sampleCopyCommandForTemplateDownload = - #region string_literal - // org.apache.cloudstack.storage.command.CopyCommand - "{\"srcTO\":" + - "{\"org.apache.cloudstack.storage.to.TemplateObjectTO\":" + - "{\"path\":\"" + testSystemVMTemplateName + "\"," + - "\"origUrl\":\"http://10.147.28.7/templates/5d67394c-4efd-4b62-966b-51aa53b35277.vhd.bz2\"," + - "\"uuid\":\"7e4ca941-cb1b-4113-ab9e-043960d0fb10\"," + - "\"id\":206," + - "\"format\":\"VHD\"," + - "\"accountId\":1," + - "\"checksum\": \"f613f38c96bf039f2e5cbf92fa8ad4f8\"," + - "\"hvm\":true," + - "\"displayText\":\"OS031\"," + - "\"imageDataStore\":" + - "{\"com.cloud.agent.api.to.S3TO\":" + - "{\"id\":1," + - "\"uuid\":\"95a64c8f-2128-4502-b5b4-0d7aa77406d2\"," + - "\"accessKey\":\"" + AgentSettings.Default.testS3AccessKey + "\"," + - "\"secretKey\":\"" + AgentSettings.Default.testS3SecretKey + "\"," + - "\"endPoint\":\"" + AgentSettings.Default.testS3Endpoint + "\"," + - "\"bucketName\":\"" + AgentSettings.Default.testS3Bucket + "\"," + - "\"httpsFlag\":false," + - "\"created\":\"May 19, 2013 4:17:25 PM\"}" + - "}," + // end of imageDataStore - "\"name\":\"" + testSystemVMTemplateNameNoExt + "\"}" + - "}," + // end of srcTO - "\"destTO\":" + - "{\"org.apache.cloudstack.storage.to.TemplateObjectTO\":" + - "{" + - "\"origUrl\":\"http://10.147.28.7/templates/5d67394c-4efd-4b62-966b-51aa53b35277.vhd.bz2\"," + - "\"uuid\":\"7e4ca941-cb1b-4113-ab9e-043960d0fb10\"," + - "\"id\":206," + - "\"format\":\"VHD\"," + - "\"accountId\":1," + - "\"checksum\": \"f613f38c96bf039f2e5cbf92fa8ad4f8\"," + - "\"hvm\":true," + - "\"displayText\":\"OS031\"," + - "\"imageDataStore\":" + getSamplePrimaryDataStoreInfo() + "," + // end of imageDataStore - "\"name\":\"" + testSystemVMTemplateNameNoExt + "\"}" + - "}," +// end of destTO - "\"wait\":10800}"; // end of CopyCommand - #endregion - - HypervResourceController rsrcServer; - dynamic jsonDownloadCopyCmd; - string dwnldDest; - dynamic jsonCloneCopyCmd; - string newVolName; - CopyCommandTestSetup(sampleCopyCommandToCreateVolumeFromTemplate, sampleCopyCommandForTemplateDownload, out rsrcServer, out jsonDownloadCopyCmd, out dwnldDest, out jsonCloneCopyCmd, out newVolName); - - // Act & Assert - DownloadTemplateToPrimaryStorage(rsrcServer, jsonDownloadCopyCmd, dwnldDest); - CreateVolumeFromTemplate(rsrcServer, jsonCloneCopyCmd, newVolName); - - File.Delete(dwnldDest); - File.Delete(newVolName); - } - - private static void CopyCommandTestSetup(string sampleCopyCommandToCreateVolumeFromTemplate, string sampleCopyCommandForTemplateDownload, out HypervResourceController rsrcServer, out dynamic jsonDownloadCopyCmd, out string dwnldDest, out dynamic jsonCloneCopyCmd, out string newVolName) - { - rsrcServer = new HypervResourceController(); - jsonDownloadCopyCmd = JsonConvert.DeserializeObject(sampleCopyCommandForTemplateDownload); - TemplateObjectTO dwnldTemplate = TemplateObjectTO.ParseJson(jsonDownloadCopyCmd.destTO); - dwnldDest = dwnldTemplate.FullFileName; - - jsonCloneCopyCmd = JsonConvert.DeserializeObject(sampleCopyCommandToCreateVolumeFromTemplate); - VolumeObjectTO newVol = VolumeObjectTO.ParseJson(jsonCloneCopyCmd.destTO); - newVol.format = dwnldTemplate.format; - newVolName = dwnldTemplate.FullFileName; - - if (File.Exists(dwnldDest)) - { - File.Delete(dwnldDest); - } - if (File.Exists(newVolName)) - { - File.Delete(newVolName); - } - } - - private static void CopyCommandTestSetupCifs(string sampleCopyCommandToCreateVolumeFromTemplate, string sampleCopyCommandForTemplateDownload, out HypervResourceController rsrcServer, out dynamic jsonDownloadCopyCmd, out string dwnldDest, out dynamic jsonCloneCopyCmd, out string newVolName) - { - rsrcServer = new HypervResourceController(); - jsonDownloadCopyCmd = JsonConvert.DeserializeObject(sampleCopyCommandForTemplateDownload); - TemplateObjectTO dwnldTemplate = TemplateObjectTO.ParseJson(jsonDownloadCopyCmd.destTO); - dwnldDest = dwnldTemplate.FullFileName; - - if (File.Exists(dwnldDest)) - { - File.Delete(dwnldDest); - } - newVolName = null; - jsonCloneCopyCmd = null; - } - - [Fact(Skip="these are functional tests")] - public void TestModifyStoragePoolCommand() - { - // Create dummy folder - String folderName = Path.Combine(".", "Dummy"); - if (!Directory.Exists(folderName)) - { - Directory.CreateDirectory(folderName); - } - - var pool = new - { // From java class StorageFilerTO - type = Enum.GetName(typeof(StoragePoolType), StoragePoolType.Filesystem), - host = "127.0.0.1", - port = -1, - path = folderName, - uuid = Guid.NewGuid().ToString(), - userInfo = string.Empty // Used in future to hold credential - }; - - var cmd = new - { - add = true, - pool = pool, - localPath = folderName - }; - JToken tok = JToken.FromObject(cmd); - HypervResourceController controller = new HypervResourceController(); - - // Act - dynamic jsonResult = controller.ModifyStoragePoolCommand(tok); - - // Assert - dynamic ans = jsonResult[0][CloudStackTypes.ModifyStoragePoolAnswer]; - Assert.True((bool)ans.result, (string)ans.details); // always succeeds - - // Clean up - var cmd2 = new - { - pool = pool, - localPath = folderName - }; - JToken tok2 = JToken.FromObject(cmd); - - // Act - dynamic jsonResult2 = controller.DeleteStoragePoolCommand(tok2); - - // Assert - dynamic ans2 = jsonResult2[0][CloudStackTypes.Answer]; - Assert.True((bool)ans2.result, (string)ans2.details); // always succeeds - } - - [Fact(Skip="these are functional tests")] - public void CreateStoragePoolCommand() - { - var cmd = new { localPath = "NULL" }; - JToken tok = JToken.FromObject(cmd); - HypervResourceController controller = new HypervResourceController(); - - // Act - dynamic jsonResult = controller.CreateStoragePoolCommand(tok); - - // Assert - dynamic ans = jsonResult[0][CloudStackTypes.Answer]; - Assert.True((bool)ans.result, (string)ans.details); // always succeeds - } - - [Fact(Skip="these are functional tests")] - public void MaintainCommand() - { - // Omit HostEnvironment object, as this is a series of settings currently not used. - var cmd = new { }; - JToken tok = JToken.FromObject(cmd); - HypervResourceController controller = new HypervResourceController(); - - // Act - dynamic jsonResult = controller.MaintainCommand(tok); - - // Assert - dynamic ans = jsonResult[0][CloudStackTypes.MaintainAnswer]; - Assert.True((bool)ans.result, (string)ans.details); // always succeeds - } - - [Fact(Skip="these are functional tests")] - public void SetupCommand() - { - // Omit HostEnvironment object, as this is a series of settings currently not used. - var cmd = new { multipath = false, needSetup = true }; - JToken tok = JToken.FromObject(cmd); - HypervResourceController controller = new HypervResourceController(); - - // Act - dynamic jsonResult = controller.SetupCommand(tok); - - // Assert - dynamic ans = jsonResult[0][CloudStackTypes.SetupAnswer]; - Assert.True((bool)ans.result, (string)ans.details); // always succeeds - } - - [Fact(Skip="these are functional tests")] - public void TestPassingUserdataToVm() - { - // Sample data - String key = "cloudstack-vm-userdata"; - String value = "username=root;password=1pass@word1"; - - // Find the VM - List vmNames = wmiCallsV2.GetVmElementNames(); - - // Get associated WMI object - var vm = wmiCallsV2.GetComputerSystem(AgentSettings.Default.testKvpVmName); - - // Get existing KVP - var vmSettings = wmiCallsV2.GetVmSettings(vm); - var kvpInfo = wmiCallsV2.GetKvpSettings(vmSettings); - - // HostExchangesItems are embedded objects in the sense that the object value is stored and not a reference to the object. - string[] kvpProps = kvpInfo.HostExchangeItems; - - // If the value already exists, delete it - foreach (var item in kvpProps) - { - String wmiObjectXml = item; - String existingKey; - String existingValue; - ParseKVP(wmiObjectXml, out existingKey, out existingValue); - - if (existingKey == key) - { - wmiCallsV2.DeleteHostKvpItem(vm, existingKey); - break; - } - } - - // Add new user data - wmiCallsV2.AddUserData(vm, value); - - // Verify key added to subsystem - kvpInfo = wmiCallsV2.GetKvpSettings(vmSettings); - - // HostExchangesItems are embedded objects in the sense that the object value is stored and not a reference to the object. - kvpProps = kvpInfo.HostExchangeItems; - - // If the value already exists, delete it - bool userDataInPlace = false; - foreach (var item in kvpProps) - { - String wmiObjectXml = item; - String existingKey; - String existingValue; - ParseKVP(wmiObjectXml, out existingKey, out existingValue); - - if (existingKey == key && existingValue == value) - { -// wmiCallsV2.DeleteHostKvpItem(vm, existingKey); - userDataInPlace = true; - break; - } - } - - Assert.True(userDataInPlace, "User data key / value did no save properly"); - } - - private static void ParseKVP(String wmiObjectXml, out String existingKey, out String existingValue) - { - // Reference: http://blogs.msdn.com/b/virtual_pc_guy/archive/2008/12/05/enumerating-parent-kvp-data.aspx - - // Create XML parser - var xmlDoc = new XmlDocument(); - - // Load WMI object - xmlDoc.LoadXml(wmiObjectXml); - - // Use xpath to get name and value - var namePropXpath = "/INSTANCE/PROPERTY[@NAME='Name']/VALUE"; - var nameNode = xmlDoc.SelectSingleNode(namePropXpath); - existingKey = nameNode.InnerText; - var dataPropXpath = "/INSTANCE/PROPERTY[@NAME='Data']/VALUE"; - var dataNode = xmlDoc.SelectSingleNode(dataPropXpath); - existingValue = dataNode.InnerText; - } - - [Fact(Skip="these are functional tests")] - public void GetVmStatsCommandFail() - { - // Use WMI to find existing VMs - List vmNames = new List(); - vmNames.Add("FakeVM"); - - var cmd = new - { - hostGuid = "FAKEguid", - hostName = AgentSettings.Default.host, - vmNames = vmNames - }; - JToken tok = JToken.FromObject(cmd); - HypervResourceController controller = new HypervResourceController(); - - // Act - dynamic jsonResult = controller.GetVmStatsCommand(tok); - - // Assert - dynamic ans = jsonResult[0][CloudStackTypes.GetVmStatsAnswer]; - Assert.True((bool)ans.result, (string)ans.details); // always succeeds, fake VM means no answer for the named VM - } - - [Fact(Skip="these are functional tests")] - public void GetVmStatsCommand() - { - // Use WMI to find existing VMs - List vmNames = wmiCallsV2.GetVmElementNames(); - - var cmd = new - { - hostGuid = "FAKEguid", - hostName = AgentSettings.Default.host, - vmNames = vmNames - }; - JToken tok = JToken.FromObject(cmd); - HypervResourceController controller = new HypervResourceController(); - - // Act - dynamic jsonResult = controller.GetVmStatsCommand(tok); - - // Assert - dynamic ans = jsonResult[0][CloudStackTypes.GetVmStatsAnswer]; - Assert.True((bool)ans.result, (string)ans.details); - } - - [Fact(Skip="these are functional tests")] - public void GetStorageStatsCommand() - { - // TODO: Update sample data to unsure it is using correct info. - String sample = String.Format( - #region string_literal -"{{\"" + - "id\":{0}," + - "\"localPath\":{1}," + - "\"pooltype\":\"Filesystem\"," + - "\"contextMap\":{{}}," + - "\"wait\":0}}", - JsonConvert.SerializeObject(AgentSettings.Default.testLocalStoreUUID), - JsonConvert.SerializeObject(AgentSettings.Default.testLocalStorePath) - ); - #endregion - var cmd = JsonConvert.DeserializeObject(sample); - JToken tok = JToken.FromObject(cmd); - HypervResourceController controller = new HypervResourceController(); - - // Act - dynamic jsonResult = controller.GetStorageStatsCommand(tok); - - // Assert - dynamic ans = jsonResult[0][CloudStackTypes.GetStorageStatsAnswer]; - Assert.True((bool)ans.result, (string)ans.details); - Assert.True((long)ans.used <= (long)ans.capacity); // TODO: verify that capacity is indeed capacity and not used. - } - - // TODO: can we speed up this command? The logic takes over a second. - [Fact(Skip="these are functional tests")] - public void GetHostStatsCommand() - { - // Arrange - long hostIdVal = 5; - HypervResourceController controller = new HypervResourceController(); - string sample = string.Format( - #region string_literal -"{{" + - "\"hostGuid\":\"B4AE5970-FCBF-4780-9F8A-2D2E04FECC34-HypervResource\"," + - "\"hostName\":\"CC-SVR11\"," + - "\"hostId\":{0}," + - "\"contextMap\":{{}}," + - "\"wait\":0}}", - JsonConvert.SerializeObject(hostIdVal)); - #endregion - var cmd = JsonConvert.DeserializeObject(sample); - JToken tok = JToken.FromObject(cmd); - - // Act - dynamic jsonResult = controller.GetHostStatsCommand(tok); - - // Assert - dynamic ans = jsonResult[0][CloudStackTypes.GetHostStatsAnswer]; - Assert.True((bool)ans.result); - Assert.True(hostIdVal == (long)ans.hostStats.hostId); - Assert.True(0.0 < (double)ans.hostStats.totalMemoryKBs); - Assert.True(0.0 < (double)ans.hostStats.freeMemoryKBs); - Assert.True(0.0 <= (double)ans.hostStats.networkReadKBs); - Assert.True(0.0 <= (double)ans.hostStats.networkWriteKBs); - Assert.True(0.0 <= (double)ans.hostStats.cpuUtilization); - Assert.True(100.0 >= (double)ans.hostStats.cpuUtilization); - Assert.True("host".Equals((string)ans.hostStats.entityType)); - Assert.True(String.IsNullOrEmpty((string)ans.details)); - } - - [Fact(Skip="these are functional tests")] - public void GetHostStatsCommandFail() - { - // Arrange - HypervResourceController controller = new HypervResourceController(); - var cmd = new { GetHostStatsCommand = new { hostId = "badvalueType" } }; - JToken tokFail = JToken.FromObject(cmd); - - // Act - dynamic jsonResult = controller.GetHostStatsCommand(tokFail); - - // Assert - dynamic ans = jsonResult[0][CloudStackTypes.GetHostStatsAnswer]; - Assert.False((bool)ans.result); - Assert.Null((string)ans.hostStats); - Assert.NotNull(ans.details); - } - - [Fact(Skip="these are functional tests")] - public void TestStartupCommand() - { - // Arrange - HypervResourceController controller = new HypervResourceController(); - String sampleStartupRoutingCommand = - #region string_literal - "[{\"" + CloudStackTypes.StartupRoutingCommand + "\":{" + - "\"cpus\":0," + - "\"speed\":0," + - "\"memory\":0," + - "\"dom0MinMemory\":0," + - "\"poolSync\":false," + - "\"vms\":{}," + - "\"hypervisorType\":\"Hyperv\"," + - "\"hostDetails\":{" + - "\"com.cloud.network.Networks.RouterPrivateIpStrategy\":\"HostLocal\"" + - "}," + - "\"type\":\"Routing\"," + - "\"dataCenter\":\"1\"," + - "\"pod\":\"1\"," + - "\"cluster\":\"1\"," + - "\"guid\":\"16f85622-4508-415e-b13a-49a39bb14e4d\"," + - "\"name\":\"localhost\"," + - "\"version\":\"4.2.0\"," + - "\"privateIpAddress\":\"1\"," + - "\"storageIpAddress\":\"1\"," + - "\"contextMap\":{}," + - "\"wait\":0}}]"; - #endregion - - uint cores; - uint mhz; - wmiCallsV2.GetProcessorResources(out cores, out mhz); - ulong memory_mb; - ulong freememory; - wmiCallsV2.GetMemoryResources(out memory_mb, out freememory); - memory_mb *= 1024; - long capacityBytes; - long availableBytes; - HypervResourceController.GetCapacityForLocalPath(wmiCallsV2.GetDefaultVirtualDiskFolder(), - out capacityBytes, out availableBytes); - var DefaultVirtualDiskFolder = JsonConvert.SerializeObject(wmiCallsV2.GetDefaultVirtualDiskFolder()); - string expected = - #region string_literal - "[{\"" + CloudStackTypes.StartupRoutingCommand + "\":{" + - "\"cpus\":" + cores + "," + - "\"speed\":" + mhz + "," + - "\"memory\":" + memory_mb + "," + - "\"dom0MinMemory\":" + (AgentSettings.Default.dom0MinMemory * 1024 * 1024) + "," + - "\"poolSync\":false," + - "\"vms\":{}," + - "\"hypervisorType\":\"Hyperv\"," + - "\"hostDetails\":{" + - "\"com.cloud.network.Networks.RouterPrivateIpStrategy\":\"HostLocal\"" + - "}," + - "\"type\":\"Routing\"," + - "\"dataCenter\":\"1\"," + - "\"pod\":\"1\"," + - "\"cluster\":\"1\"," + - "\"guid\":\"16f85622-4508-415e-b13a-49a39bb14e4d\"," + - "\"name\":\"localhost\"," + - "\"version\":\"4.2.0\"," + - "\"privateIpAddress\":\"" + AgentSettings.Default.private_ip_address + "\"," + - "\"storageIpAddress\":\"" + AgentSettings.Default.private_ip_address + "\"," + - "\"contextMap\":{}," + - "\"wait\":0," + - "\"privateNetmask\":\"" + AgentSettings.Default.private_ip_netmask + "\"," + - "\"privateMacAddress\":\"" + AgentSettings.Default.private_mac_address + "\"," + - "\"storageNetmask\":\"" + AgentSettings.Default.private_ip_netmask + "\"," + - "\"storageMacAddress\":\"" + AgentSettings.Default.private_mac_address + "\"," + - "\"gatewayIpAddress\":\"" + AgentSettings.Default.gateway_ip_address + "\"" + - ",\"caps\":\"hvm\"" + - "}}," + - "{\"com.cloud.agent.api.StartupStorageCommand\":{" + - "\"poolInfo\":{" + - "\"uuid\":\"16f85622-4508-415e-b13a-49a39bb14e4d\"," + - "\"host\":\"" + AgentSettings.Default.private_ip_address + "\"," + - "\"localPath\":" + DefaultVirtualDiskFolder + "," + - "\"hostPath\":" + DefaultVirtualDiskFolder + "," + - "\"poolType\":\"Filesystem\"," + - "\"capacityBytes\":" + capacityBytes + "," + - "\"availableBytes\":" + availableBytes + "," + - "\"details\":null" + - "}," + - "\"guid\":\"16f85622-4508-415e-b13a-49a39bb14e4d\"," + - "\"dataCenter\":\"1\"," + - "\"resourceType\":\"STORAGE_POOL\"" + - "}}]"; - #endregion - - dynamic jsonArray = JsonConvert.DeserializeObject(sampleStartupRoutingCommand); - - // Act - dynamic jsonResult = controller.StartupCommand(jsonArray); - - // Assert - string actual = JsonConvert.SerializeObject(jsonResult); - Assert.Equal(expected, actual); - } - - - private static string TestStartCommand() - { - // Arrange - HypervResourceController rsrcServer = new HypervResourceController(); - String sample = getSampleStartCommand(); - - - dynamic jsonStartCmd = JsonConvert.DeserializeObject(sample); - - // Act - dynamic startAns = rsrcServer.StartCommand(jsonStartCmd); - - // Assert - Assert.NotNull(startAns[0][CloudStackTypes.StartAnswer]); - Assert.True((bool)startAns[0][CloudStackTypes.StartAnswer].result, "StartCommand did not succeed " + startAns[0][CloudStackTypes.StartAnswer].details); - string vmCmdName = jsonStartCmd.vm.name.Value; - var vm = wmiCallsV2.GetComputerSystem(vmCmdName); - var vmSettings = wmiCallsV2.GetVmSettings(vm); - var memSettings = wmiCallsV2.GetMemSettings(vmSettings); - var procSettings = wmiCallsV2.GetProcSettings(vmSettings); - dynamic jsonObj = JsonConvert.DeserializeObject(sample); - var vmInfo = jsonObj.vm; - string vmName = vmInfo.name; - var nicInfo = vmInfo.nics; - int vcpus = vmInfo.cpus; - int memSize = vmInfo.maxRam / 1048576; - Assert.True((long)memSettings.VirtualQuantity == memSize); - Assert.True((long)memSettings.Reservation == memSize); - Assert.True((long)memSettings.Limit == memSize); - Assert.True((int)procSettings.VirtualQuantity == vcpus); - Assert.True((int)procSettings.Reservation == vcpus); - Assert.True((int)procSettings.Limit == 100000); - - // examine NIC for correctness - var nicSettingsViaVm = wmiCallsV2.GetEthernetPortSettings(vm); - Assert.True(nicSettingsViaVm.Length > 0, "Should be at least one ethernet port on VM"); - string expectedMac = (string)jsonStartCmd.vm.nics[0].mac; - string strippedExpectedMac = expectedMac.Replace(":", string.Empty); - Assert.Equal(nicSettingsViaVm[0].Address.ToLower(), strippedExpectedMac.ToLower()); - - // Assert switchport has correct VLAN - var ethernetConnections = wmiCallsV2.GetEthernetConnections(vm); - var vlanSettings = wmiCallsV2.GetVlanSettings(ethernetConnections[0]); - string isolationUri = (string)jsonStartCmd.vm.nics[0].isolationUri; - string vlan = isolationUri.Replace("vlan://", string.Empty); - Assert.Equal(vlanSettings.AccessVlanId.ToString(), vlan); - - return vmName; - } - - private static void TestStopCommand(string vmName) - { - // Arrange - HypervResourceController rsrcServer = new HypervResourceController(); - String sampleStop = "{\"isProxy\":false,\"vmName\":\"i-2-17-VM\",\"contextMap\":{},\"wait\":0}"; - dynamic jsonStopCmd = JsonConvert.DeserializeObject(sampleStop); - - // Act - dynamic stopAns = rsrcServer.StopCommand(jsonStopCmd); - - // Assert VM is gone! - Assert.NotNull(stopAns[0][CloudStackTypes.StopAnswer]); - Assert.True((bool)stopAns[0][CloudStackTypes.StopAnswer].result, "StopCommand did not succeed " + stopAns[0][CloudStackTypes.StopAnswer].details); - var finalVm = wmiCallsV2.GetComputerSystem(vmName); - Assert.True(wmiCallsV2.GetComputerSystem(vmName) == null); - } - } -} +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +using System; +using CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION; +using System.Management; +using Newtonsoft.Json.Linq; +using Newtonsoft.Json; +using System.IO; +using log4net; +using HypervResource; +using CloudStack.Plugin.AgentShell; +using System.Collections.Generic; +using System.Xml; +using Xunit; + +namespace ServerResource.Tests +{ + public class HypervResourceControllerTest + { + protected static string testCifsUrl = AgentSettings.Default.testCifsUrl; + protected static string testCifsPath = AgentSettings.Default.testCifsPath; + protected static String testPrimaryDataStoreHost = HypervResourceController.config.StorageIpAddress; + protected static String testS3TemplateName = AgentSettings.Default.testS3TemplateName; + protected static String testCifsTemplateName = AgentSettings.Default.testS3TemplateName; + protected static String testSystemVMTemplateName = AgentSettings.Default.testSystemVMTemplateName; + protected static String testSystemVMTemplateNameNoExt = AgentSettings.Default.testSystemVMTemplateNameNoExt; + protected static String testLocalStoreUUID = "5fe2bad3-d785-394e-9949-89786b8a63d2"; + protected static String testLocalStorePath = Path.Combine(AgentSettings.Default.hyperv_plugin_root, "var", "test", "storagepool"); + protected static String testSecondaryStoreLocalPath = Path.Combine(AgentSettings.Default.hyperv_plugin_root, "var", "test", "secondary"); + + // TODO: differentiate between NFS and HTTP template URLs. + protected static String testSampleTemplateUUID = "TestCopiedLocalTemplate.vhdx"; + protected static String testSampleTemplateURL = testSampleTemplateUUID; + + // test volumes are both a minimal size vhdx. Changing the extension to .vhd makes on corrupt. + protected static String testSampleVolumeWorkingUUID = "TestVolumeLegit.vhdx"; + protected static String testSampleVolumeCorruptUUID = "TestVolumeCorrupt.vhd"; + protected static String testSampleVolumeTempUUID = "TestVolumeTemp.vhdx"; + protected static String testSampleVolumeTempUUIDNoExt = "TestVolumeTemp"; + protected static String testSampleVolumeWorkingURIJSON; + protected static String testSampleVolumeCorruptURIJSON; + protected static String testSampleVolumeTempURIJSON; + + protected static String testSampleTemplateURLJSON; + protected static String testLocalStorePathJSON; + + protected static WmiCallsV2 wmiCallsV2 = new WmiCallsV2(); + + private static ILog s_logger = LogManager.GetLogger(typeof(HypervResourceControllerTest)); + + /// + /// Test WmiCalls to which incoming HTTP POST requests are dispatched. + /// + /// TODO: revise beyond first approximation + /// First approximation is a quick port of the existing Java tests for Hyper-V server resource. + /// A second approximation would use the AgentShell settings files directly. + /// A third approximation would look to invoke ServerResource methods via an HTTP request + /// + public HypervResourceControllerTest() + { + AgentService.ConfigServerResource(); + HypervResourceController.config.PrivateMacAddress = AgentSettings.Default.private_mac_address; + HypervResourceController.config.PrivateNetmask = AgentSettings.Default.private_ip_netmask; + HypervResourceController.config.StorageIpAddress = HypervResourceController.config.PrivateIpAddress; + HypervResourceController.config.StorageMacAddress = HypervResourceController.config.PrivateMacAddress; + HypervResourceController.config.StorageNetmask = HypervResourceController.config.PrivateNetmask; + + + // Used to create existing StoragePool in preparation for the ModifyStoragePool + testLocalStoreUUID = AgentSettings.Default.local_storage_uuid.ToString(); + + // Make sure secondary store is available. + string fullPath = Path.GetFullPath(testSecondaryStoreLocalPath); + s_logger.Info("Test secondary storage in " + fullPath); + DirectoryInfo testSecondarStoreDir = new DirectoryInfo(fullPath); + if (!testSecondarStoreDir.Exists) + { + try + { + testSecondarStoreDir.Create(); + } + catch (System.IO.IOException ex) + { + throw new NotImplementedException("Need to be able to create the folder " + testSecondarStoreDir.FullName + " failed due to " + ex.Message); + } + } + + // Convert to secondary storage string to canonical path + testSecondaryStoreLocalPath = testSecondarStoreDir.FullName; + AgentSettings.Default.local_secondary_storage_path = testSecondaryStoreLocalPath; + + // Make sure local primary storage is available + DirectoryInfo testPoolDir = new DirectoryInfo(testLocalStorePath); + Assert.True(testPoolDir.Exists, "To simulate local file system Storage Pool, you need folder at " + testPoolDir.FullName); + + // Convert to local primary storage string to canonical path + testLocalStorePath = testPoolDir.FullName; + AgentSettings.Default.local_storage_path = testLocalStorePath; + + // Clean up old test files in local storage folder + FileInfo testVolWorks = new FileInfo(Path.Combine(testLocalStorePath, testSampleVolumeWorkingUUID)); + Assert.True(testVolWorks.Exists, "Create a working virtual disk at " + testVolWorks.FullName); + + + // Delete all temporary files in local folder save the testVolWorks + foreach (var file in testPoolDir.GetFiles()) + { + if (file.FullName == testVolWorks.FullName) + { + continue; + } + file.Delete(); + file.Refresh(); + Assert.False(file.Exists, "removed file from previous test called " + file.FullName); + } + + // Recreate starting point files for test, and record JSON encoded paths for each ... + testSampleVolumeTempURIJSON = CreateTestDiskImageFromExistingImage(testVolWorks, testLocalStorePath, testSampleVolumeTempUUID); + s_logger.Info("Created " + testSampleVolumeTempURIJSON); + testSampleVolumeCorruptURIJSON = CreateTestDiskImageFromExistingImage(testVolWorks, testLocalStorePath, testSampleVolumeCorruptUUID); + s_logger.Info("Created " + testSampleVolumeCorruptURIJSON); + CreateTestDiskImageFromExistingImage(testVolWorks, testLocalStorePath, testSampleTemplateUUID); + testSampleTemplateURLJSON = JsonConvert.SerializeObject(testSampleTemplateUUID); + s_logger.Info("Created " + testSampleTemplateURLJSON + " in local storage."); + + // ... including a secondary storage template: + CreateTestDiskImageFromExistingImage(testVolWorks, testSecondarStoreDir.FullName, "af39aa7f-2b12-37e1-86d3-e23f2f005101.vhdx"); + s_logger.Info("Created " + "af39aa7f-2b12-37e1-86d3-e23f2f005101.vhdx" + " in secondary (NFS) storage."); + + + // Capture other JSON encoded paths + testSampleVolumeWorkingURIJSON = Newtonsoft.Json.JsonConvert.SerializeObject(testVolWorks.FullName); + testLocalStorePathJSON = JsonConvert.SerializeObject(testLocalStorePath); + + // TODO: may need to initialise the server resource in future. + // s_hypervresource.initialize(); + + // Verify sample template is in place storage pool + s_logger.Info("setUp complete, sample StoragePool at " + testLocalStorePathJSON + + " sample template at " + testSampleTemplateURLJSON); + } + + private String CreateTestDiskImageFromExistingImage(FileInfo srcFile, + String dstPath, + String dstFileName) + { + var newFullname = Path.Combine(dstPath, dstFileName); + var newFileInfo = new FileInfo(newFullname); + if (!newFileInfo.Exists) + { + newFileInfo = srcFile.CopyTo(newFullname); + } + newFileInfo.Refresh(); + Assert.True(newFileInfo.Exists, "Attempted to create " + newFullname + " from " + newFileInfo.FullName); + + return JsonConvert.SerializeObject(newFileInfo.FullName); + } + + [Fact(Skip="these are functional tests")] + public void TestPrimaryStorageDownloadCommandHTTP() + { + string downloadURI = "https://s3-eu-west-1.amazonaws.com/cshv3eu/SmallDisk.vhdx"; + corePrimaryStorageDownloadCommandTestCycle(downloadURI); + } + + private void corePrimaryStorageDownloadCommandTestCycle(string downloadURI) + { + // Arrange + HypervResourceController rsrcServer = new HypervResourceController(); + dynamic jsonPSDCmd = JsonConvert.DeserializeObject(samplePrimaryDownloadCommand()); + jsonPSDCmd.url = downloadURI; + + // Act + dynamic jsonResult = rsrcServer.PrimaryStorageDownloadCommand(jsonPSDCmd); + + // Assert + JObject ansAsProperty = jsonResult[0]; + dynamic ans = ansAsProperty.GetValue(CloudStackTypes.PrimaryStorageDownloadAnswer); + Assert.True((bool)ans.result, "PrimaryStorageDownloadCommand did not succeed " + ans.details); + + // Test that URL of downloaded template works for file creation. + dynamic jsonCreateCmd = JsonConvert.DeserializeObject(CreateCommandSample()); + jsonCreateCmd.templateUrl = ans.installPath; + dynamic jsonAns2 = rsrcServer.CreateCommand(jsonCreateCmd); + JObject ansAsProperty2 = jsonAns2[0]; + dynamic ans2 = ansAsProperty2.GetValue(CloudStackTypes.CreateAnswer); + + Assert.True((bool)ans2.result, (string)ans2.details); + + FileInfo newFile = new FileInfo((string)ans2.volume.path); + Assert.True(newFile.Length > 0, "The new file should have a size greater than zero"); + newFile.Delete(); + } + + private string samplePrimaryDownloadCommand() + { + String cmdJson = "{\"localPath\":" + testLocalStorePathJSON + + ",\"poolUuid\":\"" + testLocalStoreUUID + "\",\"poolId\":201," + + "\"secondaryStorageUrl\":\"nfs://10.70.176.36/mnt/cshv3/secondarystorage\"," + + "\"primaryStorageUrl\":\"nfs://" + HypervResourceController.config.StorageIpAddress + "E:\\\\Disks\\\\Disks\"," + + "\"url\":\"nfs://10.70.176.36/mnt/cshv3/secondarystorage/template/tmpl//2/204//af39aa7f-2b12-37e1-86d3-e23f2f005101.vhdx\"," + + "\"format\":\"VHDX\",\"accountId\":2,\"name\":\"204-2-5a1db1ac-932b-3e7e-a0e8-5684c72cb862\"" + + ",\"contextMap\":{},\"wait\":10800}"; + return cmdJson; + } + + public string CreateCommandSample() + { + String sample = "{\"volId\":17,\"pool\":{\"id\":201,\"uuid\":\"" + testLocalStoreUUID + "\",\"host\":\"" + HypervResourceController.config.StorageIpAddress + "\"" + + ",\"path\":" + testLocalStorePathJSON + ",\"port\":0,\"type\":\"Filesystem\"},\"diskCharacteristics\":{\"size\":0," + + "\"tags\":[],\"type\":\"ROOT\",\"name\":\"ROOT-15\",\"useLocalStorage\":true,\"recreatable\":true,\"diskOfferingId\":11," + + "\"volumeId\":17,\"hyperType\":\"Hyperv\"},\"templateUrl\":" + testSampleTemplateURLJSON + ",\"wait\":0}"; + return sample; + } + + [Fact(Skip="these are functional tests")] + public void TestDestroyCommand() + { + // Arrange + String sampleVolume = getSampleVolumeObjectTO(); + String destroyCmd = //"{\"volume\":" + getSampleVolumeObjectTO() + "}"; + "{\"volume\":{\"name\":\"" + testSampleVolumeTempUUIDNoExt + + "\",\"storagePoolType\":\"Filesystem\"," + + "\"mountPoint\":" + + testLocalStorePathJSON + + ",\"path\":" + testSampleVolumeTempURIJSON + + ",\"storagePoolUuid\":\"" + testLocalStoreUUID + + "\"," + + "\"type\":\"ROOT\",\"id\":9,\"size\":0}}"; + + HypervResourceController rsrcServer = new HypervResourceController(); + dynamic jsonDestroyCmd = JsonConvert.DeserializeObject(destroyCmd); + + // Act + dynamic destroyAns = rsrcServer.DestroyCommand(jsonDestroyCmd); + + // Assert + JObject ansAsProperty2 = destroyAns[0]; + dynamic ans = ansAsProperty2.GetValue(CloudStackTypes.Answer); + String path = jsonDestroyCmd.volume.path; + Assert.True((bool)ans.result, "DestroyCommand did not succeed " + ans.details); + Assert.True(!File.Exists(path), "Failed to delete file " + path); + } + + [Fact(Skip="these are functional tests")] + public void TestCreateCommand() + { + // TODO: Need sample to update the test. + // Arrange + String createCmd = "{\"volId\":10,\"pool\":{\"id\":201,\"uuid\":\"" + testLocalStoreUUID + "\",\"host\":\"" + HypervResourceController.config.StorageIpAddress + "\"" + + ",\"path\":" + testLocalStorePathJSON + ",\"port\":0,\"type\":\"Filesystem\"},\"diskCharacteristics\":{\"size\":0," + + "\"tags\":[],\"type\":\"ROOT\",\"name\":\"ROOT-9\",\"useLocalStorage\":true,\"recreatable\":true,\"diskOfferingId\":11," + + "\"volumeId\":10,\"hyperType\":\"Hyperv\"},\"templateUrl\":" + testSampleTemplateURLJSON + ",\"contextMap\":{},\"wait\":0}"; + dynamic jsonCreateCmd = JsonConvert.DeserializeObject(createCmd); + HypervResourceController rsrcServer = new HypervResourceController(); + + Assert.True(Directory.Exists(testLocalStorePath)); + string filePath = Path.Combine(testLocalStorePath, (string)JsonConvert.DeserializeObject(testSampleTemplateURLJSON)); + Assert.True(File.Exists(filePath), "The template we make volumes from is missing from path " + filePath); + int fileCount = Directory.GetFiles(testLocalStorePath).Length; + s_logger.Debug(" test local store has " + fileCount + "files"); + + // Act + // Test requires there to be a template at the tempalteUrl, which is its location in the local file system. + dynamic jsonResult = rsrcServer.CreateCommand(jsonCreateCmd); + + JObject ansAsProperty2 = jsonResult[0]; + dynamic ans = ansAsProperty2.GetValue(CloudStackTypes.CreateAnswer); + Assert.NotNull(ans); + Assert.True((bool)ans.result, "Failed to CreateCommand due to " + (string)ans.result); + Assert.Equal(Directory.GetFiles(testLocalStorePath).Length, fileCount + 1); + FileInfo newFile = new FileInfo((string)ans.volume.path); + Assert.True(newFile.Length > 0, "The new file should have a size greater than zero"); + newFile.Delete(); + } + + /// + /// Possible additional tests: place an ISO in the drive + /// + [Fact(Skip="these are functional tests")] + public void TestStartStopCommand() + { + string vmName = TestStartCommand(); + TestStopCommand(vmName); + } + + public static String getSamplePrimaryDataStoreInfo() + { + String samplePrimaryDataStoreInfo = + "{\"org.apache.cloudstack.storage.to.PrimaryDataStoreTO\":" + + "{\"uuid\":\"" + testLocalStoreUUID + "\"," + + "\"id\":201," + + "\"host\":\"" + testPrimaryDataStoreHost + "\"," + + "\"type\":\"Filesystem\"," + // Not used in PrimaryDataStoreTO + "\"poolType\":\"Filesystem\"," + // Not used in PrimaryDataStoreTO + "\"path\":" + testLocalStorePathJSON + "," + + "\"port\":0}" + + "}"; + return samplePrimaryDataStoreInfo; + } + + public static String getSampleVolumeObjectTO() + { + String sampleVolumeObjectTO = + "{\"org.apache.cloudstack.storage.to.VolumeObjectTO\":" + + "{\"uuid\":\"19ae8e67-cb2c-4ab4-901e-e0b864272b59\"," + + "\"volumeType\":\"ROOT\"," + + "\"format\":\"VHDX\"," + + "\"dataStore\":" + getSamplePrimaryDataStoreInfo() + "," + + "\"name\":\"" + testSampleVolumeTempUUIDNoExt + "\"," + + "\"size\":52428800," + + "\"volumeId\":10," + + // "\"vmName\":\"i-3-5-VM\"," + // TODO: do we have to fill in the vmName? + "\"accountId\":3,\"id\":10}" + + "}"; // end of destTO + return sampleVolumeObjectTO; + } + + public static String getSampleStartCommand() + { + String sample = "{\"vm\":{\"id\":17,\"name\":\"i-2-17-VM\",\"type\":\"User\",\"cpus\":1,\"speed\":500," + + "\"minRam\":536870912,\"maxRam\":536870912,\"arch\":\"x86_64\"," + + "\"os\":\"CentOS 6.0 (64-bit)\",\"bootArgs\":\"\",\"rebootOnCrash\":false," + + "\"enableHA\":false,\"limitCpuUse\":false,\"vncPassword\":\"31f82f29aff646eb\"," + + "\"params\":{},\"uuid\":\"8b030b6a-0243-440a-8cc5-45d08815ca11\"" + + ",\"disks\":[" + + "{\"data\":" + getSampleVolumeObjectTO() + ",\"diskSeq\":0,\"type\":\"ROOT\"}," + + "{\"diskSeq\":1,\"type\":\"ISO\"}" + + "]," + + "\"nics\":[" + + "{\"deviceId\":0,\"networkRateMbps\":100,\"defaultNic\":true,\"uuid\":\"99cb4813-23af-428c-a87a-2d1899be4f4b\"," + + "\"ip\":\"10.1.1.67\",\"netmask\":\"255.255.255.0\",\"gateway\":\"10.1.1.1\"," + + "\"mac\":\"02:00:51:2c:00:0e\",\"dns1\":\"4.4.4.4\",\"broadcastType\":\"Vlan\",\"type\":\"Guest\"," + + "\"broadcastUri\":\"vlan://261\",\"isolationUri\":\"vlan://261\",\"isSecurityGroupEnabled\":false}" + + "]},\"contextMap\":{},\"wait\":0}"; + return sample; + } + + + [Fact(Skip="these are functional tests")] + public void TestCopyCommandFromCifs() + { + // Arrange + string sampleCopyCommandForTemplateDownload = + #region string_literal + // org.apache.cloudstack.storage.command.CopyCommand + "{\"srcTO\":" + + "{\"org.apache.cloudstack.storage.to.TemplateObjectTO\":" + + "{\"path\":\"" + testCifsPath + "\"," + + "\"origUrl\":\"http://10.147.28.7/templates/5d67394c-4efd-4b62-966b-51aa53b35277.vhd.bz2\"," + + "\"uuid\":\"7e4ca941-cb1b-4113-ab9e-043960d0fb10\"," + + "\"id\":206," + + "\"format\":\"VHDX\"," + + "\"accountId\":2," + + "\"checksum\":\"4b31e2846cc67fc10ea7281986519a54\"," + + "\"hvm\":true," + + "\"displayText\":\"OS031\"," + + "\"imageDataStore\":" + + "{\"com.cloud.agent.api.to.NfsTO\":" + + "{\"_url\":\"" + testCifsUrl + "\"," + // Unique item here + "\"_role\":\"Image\"}" + + "}," + // end of imageDataStore + "\"hypervisorType\":\"Hyperv\"," + + "\"name\":\"" + testS3TemplateName + "\"}" + + "}," + // end of srcTO + "\"destTO\":" + + "{\"org.apache.cloudstack.storage.to.TemplateObjectTO\":" + + "{" + + "\"origUrl\":\"http://10.147.28.7/templates/5d67394c-4efd-4b62-966b-51aa53b35277.vhd.bz2\"," + + "\"uuid\":\"7e4ca941-cb1b-4113-ab9e-043960d0fb10\"," + + "\"id\":206," + + "\"format\":\"VHDX\"," + + "\"accountId\":2," + + "\"checksum\":\"4b31e2846cc67fc10ea7281986519a54\"," + + "\"hvm\":true," + + "\"displayText\":\"Test of CIFS Download\"," + + "\"imageDataStore\":" + getSamplePrimaryDataStoreInfo() + "," + // end of imageDataStore + "\"name\":\"" + testS3TemplateName + "\"," + + "\"hypervisorType\":\"Hyperv\"}" + + "}," +// end of destTO + "\"wait\":10800}"; // end of CopyCommand + #endregion + + HypervResourceController rsrcServer; + dynamic jsonDownloadCopyCmd; + string dwnldDest; + dynamic jsonCloneCopyCmd; + string newVolName; + CopyCommandTestSetupCifs(null, sampleCopyCommandForTemplateDownload, out rsrcServer, out jsonDownloadCopyCmd, out dwnldDest, out jsonCloneCopyCmd, out newVolName); + + // Act & Assert + DownloadTemplateToPrimaryStorage(rsrcServer, jsonDownloadCopyCmd, dwnldDest); + + // Repeat to verify ability to detect existing file. + DownloadTemplateToPrimaryStorage(rsrcServer, jsonDownloadCopyCmd, dwnldDest); + + File.Delete(dwnldDest); + } + + [Fact(Skip="these are functional tests")] + public void TestCopyCommand() + { + // Arrange + string sampleCopyCommandToCreateVolumeFromTemplate = + #region string_literal + // org.apache.cloudstack.storage.command.CopyCommand + "{\"srcTO\":" + + "{\"org.apache.cloudstack.storage.to.TemplateObjectTO\":" + + "{" + + "\"origUrl\":\"http://people.apache.org/~bhaisaab/vms/ttylinux_pv.vhd\"," + + "\"uuid\":\"9873f1c0-bdcc-11e2-8baa-ea85dab5fcd0\"," + + "\"id\":5," + + "\"format\":\"VHDX\"," + + "\"accountId\":1," + + "\"checksum\":\"4b31e2846cc67fc10ea7281986519a54\"," + + "\"hvm\":false," + + "\"displayText\":\"tiny Linux\"," + + "\"imageDataStore\":" + getSamplePrimaryDataStoreInfo() + "," + + "\"name\":\"" + testS3TemplateName + "\"}" + + "}," + // end of srcTO + "\"destTO\":" + + "{\"org.apache.cloudstack.storage.to.VolumeObjectTO\":" + + "{\"uuid\":\"19ae8e67-cb2c-4ab4-901e-e0b864272b59\"," + + "\"volumeType\":\"ROOT\"," + + "\"dataStore\":" + getSamplePrimaryDataStoreInfo() + "," + + "\"name\":\"ROOT-5\"," + + "\"size\":52428800," + + "\"volumeId\":10," + + "\"vmName\":\"i-3-5-VM\"," + + "\"accountId\":3," + + "\"id\":10 }" + + "}," + // end of destTO + "\"wait\":0}"; // end of Copy Command + #endregion + //"name":"ROOT-8","size":140616708,"volumeId":8,"vmName":"s-8-VM","accountId":1,"id":8}},"contextMap":{},"wait":0} + + string sampleCopyCommandForTemplateDownload = + #region string_literal + // org.apache.cloudstack.storage.command.CopyCommand + "{\"srcTO\":" + + "{\"org.apache.cloudstack.storage.to.TemplateObjectTO\":" + + "{\"path\":\"" + testS3TemplateName + ".vhdx" + "\"," + + "\"origUrl\":\"http://10.147.28.7/templates/5d67394c-4efd-4b62-966b-51aa53b35277.vhd.bz2\"," + + "\"uuid\":\"7e4ca941-cb1b-4113-ab9e-043960d0fb10\"," + + "\"id\":206," + + "\"format\":\"VHDX\"," + + "\"accountId\":2," + + "\"checksum\":\"4b31e2846cc67fc10ea7281986519a54\"," + + "\"hvm\":true," + + "\"displayText\":\"OS031\"," + + "\"imageDataStore\":" + + "{\"com.cloud.agent.api.to.S3TO\":" + + "{\"id\":1," + + "\"uuid\":\"95a64c8f-2128-4502-b5b4-0d7aa77406d2\"," + + "\"accessKey\":\"" + AgentSettings.Default.testS3AccessKey + "\"," + + "\"secretKey\":\"" + AgentSettings.Default.testS3SecretKey + "\"," + + "\"endPoint\":\"" + AgentSettings.Default.testS3Endpoint + "\"," + + "\"bucketName\":\"" + AgentSettings.Default.testS3Bucket + "\"," + + "\"httpsFlag\":false," + + "\"created\":\"May 19, 2013 4:17:25 PM\"}" + + "}," + // end of imageDataStore + "\"name\":\"" + testS3TemplateName + "\"}" + + "}," + // end of srcTO + "\"destTO\":" + + "{\"org.apache.cloudstack.storage.to.TemplateObjectTO\":" + + "{" + + "\"origUrl\":\"http://10.147.28.7/templates/5d67394c-4efd-4b62-966b-51aa53b35277.vhd.bz2\"," + + "\"uuid\":\"7e4ca941-cb1b-4113-ab9e-043960d0fb10\"," + + "\"id\":206," + + "\"format\":\"VHDX\"," + + "\"accountId\":2," + + "\"checksum\":\"4b31e2846cc67fc10ea7281986519a54\"," + + "\"hvm\":true," + + "\"displayText\":\"OS031\"," + + "\"imageDataStore\":" + getSamplePrimaryDataStoreInfo() + "," + // end of imageDataStore + "\"name\":\"" + testS3TemplateName + "\"}" + + "}," +// end of destTO + "\"wait\":10800}"; // end of CopyCommand + #endregion + + HypervResourceController rsrcServer; + dynamic jsonDownloadCopyCmd; + string dwnldDest; + dynamic jsonCloneCopyCmd; + string newVolName; + CopyCommandTestSetup(sampleCopyCommandToCreateVolumeFromTemplate, sampleCopyCommandForTemplateDownload, out rsrcServer, out jsonDownloadCopyCmd, out dwnldDest, out jsonCloneCopyCmd, out newVolName); + + // Act & Assert + DownloadTemplateToPrimaryStorage(rsrcServer, jsonDownloadCopyCmd, dwnldDest); + CreateVolumeFromTemplate(rsrcServer, jsonCloneCopyCmd, newVolName); + + // Repeat to verify ability to detect existing file. + DownloadTemplateToPrimaryStorage(rsrcServer, jsonDownloadCopyCmd, dwnldDest); + + File.Delete(dwnldDest); + File.Delete(newVolName); + } + + private static void CreateVolumeFromTemplate(HypervResourceController rsrcServer, dynamic jsonCloneCopyCmd, string newVolName) + { + dynamic copyResult = rsrcServer.CopyCommand(jsonCloneCopyCmd); + + // Assert + Assert.NotNull(copyResult[0][CloudStackTypes.CopyCmdAnswer]); + Assert.True((bool)copyResult[0][CloudStackTypes.CopyCmdAnswer].result, "CopyCommand did not succeed " + copyResult[0][CloudStackTypes.CopyCmdAnswer].details); + Assert.True(File.Exists(newVolName), "CopyCommand failed to generate " + newVolName); + } + + private static void DownloadTemplateToPrimaryStorage(HypervResourceController rsrcServer, dynamic jsonDownloadCopyCmd, string dwnldDest) + { + dynamic dwnldResult = rsrcServer.CopyCommand(jsonDownloadCopyCmd); + + // Assert + Assert.NotNull(dwnldResult[0][CloudStackTypes.CopyCmdAnswer]); + Assert.True((bool)dwnldResult[0][CloudStackTypes.CopyCmdAnswer].result, "CopyCommand did not succeed " + dwnldResult[0][CloudStackTypes.CopyCmdAnswer].details); + Assert.True(File.Exists(dwnldDest), "CopyCommand failed to generate " + dwnldDest); + } + + [Fact(Skip="these are functional tests")] + public void TestCopyCommandBz2Img() + { + // Arrange + string sampleCopyCommandToCreateVolumeFromTemplate = + #region string_literal + // org.apache.cloudstack.storage.command.CopyCommand + "{\"srcTO\":" + + "{\"org.apache.cloudstack.storage.to.TemplateObjectTO\":" + + "{" + + "\"origUrl\":\"http://people.apache.org/~bhaisaab/vms/ttylinux_pv.vhd\"," + + "\"uuid\":\"9873f1c0-bdcc-11e2-8baa-ea85dab5fcd0\"," + + "\"id\":5," + + "\"format\":\"VHD\"," + + "\"accountId\":1," + + "\"checksum\":\"f613f38c96bf039f2e5cbf92fa8ad4f8\"," + + "\"hvm\":false," + + "\"displayText\":\"tiny Linux\"," + + "\"imageDataStore\":" + getSamplePrimaryDataStoreInfo() + "," + + "\"name\":\"" + testSystemVMTemplateNameNoExt + "\"}" + + "}," + // end of srcTO + "\"destTO\":" + + "{\"org.apache.cloudstack.storage.to.VolumeObjectTO\":" + + "{\"uuid\":\"19ae8e67-cb2c-4ab4-901e-e0b864272b59\"," + + "\"volumeType\":\"ROOT\"," + + "\"dataStore\":" + getSamplePrimaryDataStoreInfo() + "," + + "\"name\":\"ROOT-5\"," + + "\"size\":52428800," + + "\"volumeId\":10," + + "\"vmName\":\"i-3-5-VM\"," + + "\"accountId\":1," + + "\"id\":10}" + + "}," + // end of destTO + "\"wait\":0}"; // end of Copy Command + #endregion + + string sampleCopyCommandForTemplateDownload = + #region string_literal + // org.apache.cloudstack.storage.command.CopyCommand + "{\"srcTO\":" + + "{\"org.apache.cloudstack.storage.to.TemplateObjectTO\":" + + "{\"path\":\"" + testSystemVMTemplateName + "\"," + + "\"origUrl\":\"http://10.147.28.7/templates/5d67394c-4efd-4b62-966b-51aa53b35277.vhd.bz2\"," + + "\"uuid\":\"7e4ca941-cb1b-4113-ab9e-043960d0fb10\"," + + "\"id\":206," + + "\"format\":\"VHD\"," + + "\"accountId\":1," + + "\"checksum\": \"f613f38c96bf039f2e5cbf92fa8ad4f8\"," + + "\"hvm\":true," + + "\"displayText\":\"OS031\"," + + "\"imageDataStore\":" + + "{\"com.cloud.agent.api.to.S3TO\":" + + "{\"id\":1," + + "\"uuid\":\"95a64c8f-2128-4502-b5b4-0d7aa77406d2\"," + + "\"accessKey\":\"" + AgentSettings.Default.testS3AccessKey + "\"," + + "\"secretKey\":\"" + AgentSettings.Default.testS3SecretKey + "\"," + + "\"endPoint\":\"" + AgentSettings.Default.testS3Endpoint + "\"," + + "\"bucketName\":\"" + AgentSettings.Default.testS3Bucket + "\"," + + "\"httpsFlag\":false," + + "\"created\":\"May 19, 2013 4:17:25 PM\"}" + + "}," + // end of imageDataStore + "\"name\":\"" + testSystemVMTemplateNameNoExt + "\"}" + + "}," + // end of srcTO + "\"destTO\":" + + "{\"org.apache.cloudstack.storage.to.TemplateObjectTO\":" + + "{" + + "\"origUrl\":\"http://10.147.28.7/templates/5d67394c-4efd-4b62-966b-51aa53b35277.vhd.bz2\"," + + "\"uuid\":\"7e4ca941-cb1b-4113-ab9e-043960d0fb10\"," + + "\"id\":206," + + "\"format\":\"VHD\"," + + "\"accountId\":1," + + "\"checksum\": \"f613f38c96bf039f2e5cbf92fa8ad4f8\"," + + "\"hvm\":true," + + "\"displayText\":\"OS031\"," + + "\"imageDataStore\":" + getSamplePrimaryDataStoreInfo() + "," + // end of imageDataStore + "\"name\":\"" + testSystemVMTemplateNameNoExt + "\"}" + + "}," +// end of destTO + "\"wait\":10800}"; // end of CopyCommand + #endregion + + HypervResourceController rsrcServer; + dynamic jsonDownloadCopyCmd; + string dwnldDest; + dynamic jsonCloneCopyCmd; + string newVolName; + CopyCommandTestSetup(sampleCopyCommandToCreateVolumeFromTemplate, sampleCopyCommandForTemplateDownload, out rsrcServer, out jsonDownloadCopyCmd, out dwnldDest, out jsonCloneCopyCmd, out newVolName); + + // Act & Assert + DownloadTemplateToPrimaryStorage(rsrcServer, jsonDownloadCopyCmd, dwnldDest); + CreateVolumeFromTemplate(rsrcServer, jsonCloneCopyCmd, newVolName); + + File.Delete(dwnldDest); + File.Delete(newVolName); + } + + private static void CopyCommandTestSetup(string sampleCopyCommandToCreateVolumeFromTemplate, string sampleCopyCommandForTemplateDownload, out HypervResourceController rsrcServer, out dynamic jsonDownloadCopyCmd, out string dwnldDest, out dynamic jsonCloneCopyCmd, out string newVolName) + { + rsrcServer = new HypervResourceController(); + jsonDownloadCopyCmd = JsonConvert.DeserializeObject(sampleCopyCommandForTemplateDownload); + TemplateObjectTO dwnldTemplate = TemplateObjectTO.ParseJson(jsonDownloadCopyCmd.destTO); + dwnldDest = dwnldTemplate.FullFileName; + + jsonCloneCopyCmd = JsonConvert.DeserializeObject(sampleCopyCommandToCreateVolumeFromTemplate); + VolumeObjectTO newVol = VolumeObjectTO.ParseJson(jsonCloneCopyCmd.destTO); + newVol.format = dwnldTemplate.format; + newVolName = dwnldTemplate.FullFileName; + + if (File.Exists(dwnldDest)) + { + File.Delete(dwnldDest); + } + if (File.Exists(newVolName)) + { + File.Delete(newVolName); + } + } + + private static void CopyCommandTestSetupCifs(string sampleCopyCommandToCreateVolumeFromTemplate, string sampleCopyCommandForTemplateDownload, out HypervResourceController rsrcServer, out dynamic jsonDownloadCopyCmd, out string dwnldDest, out dynamic jsonCloneCopyCmd, out string newVolName) + { + rsrcServer = new HypervResourceController(); + jsonDownloadCopyCmd = JsonConvert.DeserializeObject(sampleCopyCommandForTemplateDownload); + TemplateObjectTO dwnldTemplate = TemplateObjectTO.ParseJson(jsonDownloadCopyCmd.destTO); + dwnldDest = dwnldTemplate.FullFileName; + + if (File.Exists(dwnldDest)) + { + File.Delete(dwnldDest); + } + newVolName = null; + jsonCloneCopyCmd = null; + } + + [Fact(Skip="these are functional tests")] + public void TestModifyStoragePoolCommand() + { + // Create dummy folder + String folderName = Path.Combine(".", "Dummy"); + if (!Directory.Exists(folderName)) + { + Directory.CreateDirectory(folderName); + } + + var pool = new + { // From java class StorageFilerTO + type = Enum.GetName(typeof(StoragePoolType), StoragePoolType.Filesystem), + host = "127.0.0.1", + port = -1, + path = folderName, + uuid = Guid.NewGuid().ToString(), + userInfo = string.Empty // Used in future to hold credential + }; + + var cmd = new + { + add = true, + pool = pool, + localPath = folderName + }; + JToken tok = JToken.FromObject(cmd); + HypervResourceController controller = new HypervResourceController(); + + // Act + dynamic jsonResult = controller.ModifyStoragePoolCommand(tok); + + // Assert + dynamic ans = jsonResult[0][CloudStackTypes.ModifyStoragePoolAnswer]; + Assert.True((bool)ans.result, (string)ans.details); // always succeeds + + // Clean up + var cmd2 = new + { + pool = pool, + localPath = folderName + }; + JToken tok2 = JToken.FromObject(cmd); + + // Act + dynamic jsonResult2 = controller.DeleteStoragePoolCommand(tok2); + + // Assert + dynamic ans2 = jsonResult2[0][CloudStackTypes.Answer]; + Assert.True((bool)ans2.result, (string)ans2.details); // always succeeds + } + + [Fact(Skip="these are functional tests")] + public void CreateStoragePoolCommand() + { + var cmd = new { localPath = "NULL" }; + JToken tok = JToken.FromObject(cmd); + HypervResourceController controller = new HypervResourceController(); + + // Act + dynamic jsonResult = controller.CreateStoragePoolCommand(tok); + + // Assert + dynamic ans = jsonResult[0][CloudStackTypes.Answer]; + Assert.True((bool)ans.result, (string)ans.details); // always succeeds + } + + [Fact(Skip="these are functional tests")] + public void MaintainCommand() + { + // Omit HostEnvironment object, as this is a series of settings currently not used. + var cmd = new { }; + JToken tok = JToken.FromObject(cmd); + HypervResourceController controller = new HypervResourceController(); + + // Act + dynamic jsonResult = controller.MaintainCommand(tok); + + // Assert + dynamic ans = jsonResult[0][CloudStackTypes.MaintainAnswer]; + Assert.True((bool)ans.result, (string)ans.details); // always succeeds + } + + [Fact(Skip="these are functional tests")] + public void SetupCommand() + { + // Omit HostEnvironment object, as this is a series of settings currently not used. + var cmd = new { multipath = false, needSetup = true }; + JToken tok = JToken.FromObject(cmd); + HypervResourceController controller = new HypervResourceController(); + + // Act + dynamic jsonResult = controller.SetupCommand(tok); + + // Assert + dynamic ans = jsonResult[0][CloudStackTypes.SetupAnswer]; + Assert.True((bool)ans.result, (string)ans.details); // always succeeds + } + + [Fact(Skip="these are functional tests")] + public void TestPassingUserdataToVm() + { + // Sample data + String key = "cloudstack-vm-userdata"; + String value = "username=root;password=1pass@word1"; + + // Find the VM + List vmNames = wmiCallsV2.GetVmElementNames(); + + // Get associated WMI object + var vm = wmiCallsV2.GetComputerSystem(AgentSettings.Default.testKvpVmName); + + // Get existing KVP + var vmSettings = wmiCallsV2.GetVmSettings(vm); + var kvpInfo = wmiCallsV2.GetKvpSettings(vmSettings); + + // HostExchangesItems are embedded objects in the sense that the object value is stored and not a reference to the object. + string[] kvpProps = kvpInfo.HostExchangeItems; + + // If the value already exists, delete it + foreach (var item in kvpProps) + { + String wmiObjectXml = item; + String existingKey; + String existingValue; + ParseKVP(wmiObjectXml, out existingKey, out existingValue); + + if (existingKey == key) + { + wmiCallsV2.DeleteHostKvpItem(vm, existingKey); + break; + } + } + + // Add new user data + wmiCallsV2.AddUserData(vm, value); + + // Verify key added to subsystem + kvpInfo = wmiCallsV2.GetKvpSettings(vmSettings); + + // HostExchangesItems are embedded objects in the sense that the object value is stored and not a reference to the object. + kvpProps = kvpInfo.HostExchangeItems; + + // If the value already exists, delete it + bool userDataInPlace = false; + foreach (var item in kvpProps) + { + String wmiObjectXml = item; + String existingKey; + String existingValue; + ParseKVP(wmiObjectXml, out existingKey, out existingValue); + + if (existingKey == key && existingValue == value) + { +// wmiCallsV2.DeleteHostKvpItem(vm, existingKey); + userDataInPlace = true; + break; + } + } + + Assert.True(userDataInPlace, "User data key / value did no save properly"); + } + + private static void ParseKVP(String wmiObjectXml, out String existingKey, out String existingValue) + { + // Reference: http://blogs.msdn.com/b/virtual_pc_guy/archive/2008/12/05/enumerating-parent-kvp-data.aspx + + // Create XML parser + var xmlDoc = new XmlDocument(); + + // Load WMI object + xmlDoc.LoadXml(wmiObjectXml); + + // Use xpath to get name and value + var namePropXpath = "/INSTANCE/PROPERTY[@NAME='Name']/VALUE"; + var nameNode = xmlDoc.SelectSingleNode(namePropXpath); + existingKey = nameNode.InnerText; + var dataPropXpath = "/INSTANCE/PROPERTY[@NAME='Data']/VALUE"; + var dataNode = xmlDoc.SelectSingleNode(dataPropXpath); + existingValue = dataNode.InnerText; + } + + [Fact(Skip="these are functional tests")] + public void GetVmStatsCommandFail() + { + // Use WMI to find existing VMs + List vmNames = new List(); + vmNames.Add("FakeVM"); + + var cmd = new + { + hostGuid = "FAKEguid", + hostName = AgentSettings.Default.host, + vmNames = vmNames + }; + JToken tok = JToken.FromObject(cmd); + HypervResourceController controller = new HypervResourceController(); + + // Act + dynamic jsonResult = controller.GetVmStatsCommand(tok); + + // Assert + dynamic ans = jsonResult[0][CloudStackTypes.GetVmStatsAnswer]; + Assert.True((bool)ans.result, (string)ans.details); // always succeeds, fake VM means no answer for the named VM + } + + [Fact(Skip="these are functional tests")] + public void GetVmStatsCommand() + { + // Use WMI to find existing VMs + List vmNames = wmiCallsV2.GetVmElementNames(); + + var cmd = new + { + hostGuid = "FAKEguid", + hostName = AgentSettings.Default.host, + vmNames = vmNames + }; + JToken tok = JToken.FromObject(cmd); + HypervResourceController controller = new HypervResourceController(); + + // Act + dynamic jsonResult = controller.GetVmStatsCommand(tok); + + // Assert + dynamic ans = jsonResult[0][CloudStackTypes.GetVmStatsAnswer]; + Assert.True((bool)ans.result, (string)ans.details); + } + + [Fact(Skip="these are functional tests")] + public void GetStorageStatsCommand() + { + // TODO: Update sample data to unsure it is using correct info. + String sample = String.Format( + #region string_literal +"{{\"" + + "id\":{0}," + + "\"localPath\":{1}," + + "\"pooltype\":\"Filesystem\"," + + "\"contextMap\":{{}}," + + "\"wait\":0}}", + JsonConvert.SerializeObject(AgentSettings.Default.testLocalStoreUUID), + JsonConvert.SerializeObject(AgentSettings.Default.testLocalStorePath) + ); + #endregion + var cmd = JsonConvert.DeserializeObject(sample); + JToken tok = JToken.FromObject(cmd); + HypervResourceController controller = new HypervResourceController(); + + // Act + dynamic jsonResult = controller.GetStorageStatsCommand(tok); + + // Assert + dynamic ans = jsonResult[0][CloudStackTypes.GetStorageStatsAnswer]; + Assert.True((bool)ans.result, (string)ans.details); + Assert.True((long)ans.used <= (long)ans.capacity); // TODO: verify that capacity is indeed capacity and not used. + } + + // TODO: can we speed up this command? The logic takes over a second. + [Fact(Skip="these are functional tests")] + public void GetHostStatsCommand() + { + // Arrange + long hostIdVal = 5; + HypervResourceController controller = new HypervResourceController(); + string sample = string.Format( + #region string_literal +"{{" + + "\"hostGuid\":\"B4AE5970-FCBF-4780-9F8A-2D2E04FECC34-HypervResource\"," + + "\"hostName\":\"CC-SVR11\"," + + "\"hostId\":{0}," + + "\"contextMap\":{{}}," + + "\"wait\":0}}", + JsonConvert.SerializeObject(hostIdVal)); + #endregion + var cmd = JsonConvert.DeserializeObject(sample); + JToken tok = JToken.FromObject(cmd); + + // Act + dynamic jsonResult = controller.GetHostStatsCommand(tok); + + // Assert + dynamic ans = jsonResult[0][CloudStackTypes.GetHostStatsAnswer]; + Assert.True((bool)ans.result); + Assert.True(hostIdVal == (long)ans.hostStats.hostId); + Assert.True(0.0 < (double)ans.hostStats.totalMemoryKBs); + Assert.True(0.0 < (double)ans.hostStats.freeMemoryKBs); + Assert.True(0.0 <= (double)ans.hostStats.networkReadKBs); + Assert.True(0.0 <= (double)ans.hostStats.networkWriteKBs); + Assert.True(0.0 <= (double)ans.hostStats.cpuUtilization); + Assert.True(100.0 >= (double)ans.hostStats.cpuUtilization); + Assert.True("host".Equals((string)ans.hostStats.entityType)); + Assert.True(String.IsNullOrEmpty((string)ans.details)); + } + + [Fact(Skip="these are functional tests")] + public void GetHostStatsCommandFail() + { + // Arrange + HypervResourceController controller = new HypervResourceController(); + var cmd = new { GetHostStatsCommand = new { hostId = "badvalueType" } }; + JToken tokFail = JToken.FromObject(cmd); + + // Act + dynamic jsonResult = controller.GetHostStatsCommand(tokFail); + + // Assert + dynamic ans = jsonResult[0][CloudStackTypes.GetHostStatsAnswer]; + Assert.False((bool)ans.result); + Assert.Null((string)ans.hostStats); + Assert.NotNull(ans.details); + } + + [Fact(Skip="these are functional tests")] + public void TestStartupCommand() + { + // Arrange + HypervResourceController controller = new HypervResourceController(); + String sampleStartupRoutingCommand = + #region string_literal + "[{\"" + CloudStackTypes.StartupRoutingCommand + "\":{" + + "\"cpus\":0," + + "\"speed\":0," + + "\"memory\":0," + + "\"dom0MinMemory\":0," + + "\"poolSync\":false," + + "\"vms\":{}," + + "\"hypervisorType\":\"Hyperv\"," + + "\"hostDetails\":{" + + "\"com.cloud.network.Networks.RouterPrivateIpStrategy\":\"HostLocal\"" + + "}," + + "\"type\":\"Routing\"," + + "\"dataCenter\":\"1\"," + + "\"pod\":\"1\"," + + "\"cluster\":\"1\"," + + "\"guid\":\"16f85622-4508-415e-b13a-49a39bb14e4d\"," + + "\"name\":\"localhost\"," + + "\"version\":\"4.2.0\"," + + "\"privateIpAddress\":\"1\"," + + "\"storageIpAddress\":\"1\"," + + "\"contextMap\":{}," + + "\"wait\":0}}]"; + #endregion + + uint cores; + uint mhz; + wmiCallsV2.GetProcessorResources(out cores, out mhz); + ulong memory_mb; + ulong freememory; + wmiCallsV2.GetMemoryResources(out memory_mb, out freememory); + memory_mb *= 1024; + long capacityBytes; + long availableBytes; + HypervResourceController.GetCapacityForLocalPath(wmiCallsV2.GetDefaultVirtualDiskFolder(), + out capacityBytes, out availableBytes); + var DefaultVirtualDiskFolder = JsonConvert.SerializeObject(wmiCallsV2.GetDefaultVirtualDiskFolder()); + string expected = + #region string_literal + "[{\"" + CloudStackTypes.StartupRoutingCommand + "\":{" + + "\"cpus\":" + cores + "," + + "\"speed\":" + mhz + "," + + "\"memory\":" + memory_mb + "," + + "\"dom0MinMemory\":" + (AgentSettings.Default.dom0MinMemory * 1024 * 1024) + "," + + "\"poolSync\":false," + + "\"vms\":{}," + + "\"hypervisorType\":\"Hyperv\"," + + "\"hostDetails\":{" + + "\"com.cloud.network.Networks.RouterPrivateIpStrategy\":\"HostLocal\"" + + "}," + + "\"type\":\"Routing\"," + + "\"dataCenter\":\"1\"," + + "\"pod\":\"1\"," + + "\"cluster\":\"1\"," + + "\"guid\":\"16f85622-4508-415e-b13a-49a39bb14e4d\"," + + "\"name\":\"localhost\"," + + "\"version\":\"4.2.0\"," + + "\"privateIpAddress\":\"" + AgentSettings.Default.private_ip_address + "\"," + + "\"storageIpAddress\":\"" + AgentSettings.Default.private_ip_address + "\"," + + "\"contextMap\":{}," + + "\"wait\":0," + + "\"privateNetmask\":\"" + AgentSettings.Default.private_ip_netmask + "\"," + + "\"privateMacAddress\":\"" + AgentSettings.Default.private_mac_address + "\"," + + "\"storageNetmask\":\"" + AgentSettings.Default.private_ip_netmask + "\"," + + "\"storageMacAddress\":\"" + AgentSettings.Default.private_mac_address + "\"," + + "\"gatewayIpAddress\":\"" + AgentSettings.Default.gateway_ip_address + "\"" + + ",\"caps\":\"hvm\"" + + "}}," + + "{\"com.cloud.agent.api.StartupStorageCommand\":{" + + "\"poolInfo\":{" + + "\"uuid\":\"16f85622-4508-415e-b13a-49a39bb14e4d\"," + + "\"host\":\"" + AgentSettings.Default.private_ip_address + "\"," + + "\"localPath\":" + DefaultVirtualDiskFolder + "," + + "\"hostPath\":" + DefaultVirtualDiskFolder + "," + + "\"poolType\":\"Filesystem\"," + + "\"capacityBytes\":" + capacityBytes + "," + + "\"availableBytes\":" + availableBytes + "," + + "\"details\":null" + + "}," + + "\"guid\":\"16f85622-4508-415e-b13a-49a39bb14e4d\"," + + "\"dataCenter\":\"1\"," + + "\"resourceType\":\"STORAGE_POOL\"" + + "}}]"; + #endregion + + dynamic jsonArray = JsonConvert.DeserializeObject(sampleStartupRoutingCommand); + + // Act + dynamic jsonResult = controller.StartupCommand(jsonArray); + + // Assert + string actual = JsonConvert.SerializeObject(jsonResult); + Assert.Equal(expected, actual); + } + + + private static string TestStartCommand() + { + // Arrange + HypervResourceController rsrcServer = new HypervResourceController(); + String sample = getSampleStartCommand(); + + + dynamic jsonStartCmd = JsonConvert.DeserializeObject(sample); + + // Act + dynamic startAns = rsrcServer.StartCommand(jsonStartCmd); + + // Assert + Assert.NotNull(startAns[0][CloudStackTypes.StartAnswer]); + Assert.True((bool)startAns[0][CloudStackTypes.StartAnswer].result, "StartCommand did not succeed " + startAns[0][CloudStackTypes.StartAnswer].details); + string vmCmdName = jsonStartCmd.vm.name.Value; + var vm = wmiCallsV2.GetComputerSystem(vmCmdName); + var vmSettings = wmiCallsV2.GetVmSettings(vm); + var memSettings = wmiCallsV2.GetMemSettings(vmSettings); + var procSettings = wmiCallsV2.GetProcSettings(vmSettings); + dynamic jsonObj = JsonConvert.DeserializeObject(sample); + var vmInfo = jsonObj.vm; + string vmName = vmInfo.name; + var nicInfo = vmInfo.nics; + int vcpus = vmInfo.cpus; + int memSize = vmInfo.maxRam / 1048576; + Assert.True((long)memSettings.VirtualQuantity == memSize); + Assert.True((long)memSettings.Reservation == memSize); + Assert.True((long)memSettings.Limit == memSize); + Assert.True((int)procSettings.VirtualQuantity == vcpus); + Assert.True((int)procSettings.Reservation == vcpus); + Assert.True((int)procSettings.Limit == 100000); + + // examine NIC for correctness + var nicSettingsViaVm = wmiCallsV2.GetEthernetPortSettings(vm); + Assert.True(nicSettingsViaVm.Length > 0, "Should be at least one ethernet port on VM"); + string expectedMac = (string)jsonStartCmd.vm.nics[0].mac; + string strippedExpectedMac = expectedMac.Replace(":", string.Empty); + Assert.Equal(nicSettingsViaVm[0].Address.ToLower(), strippedExpectedMac.ToLower()); + + // Assert switchport has correct VLAN + var ethernetConnections = wmiCallsV2.GetEthernetConnections(vm); + var vlanSettings = wmiCallsV2.GetVlanSettings(ethernetConnections[0]); + string isolationUri = (string)jsonStartCmd.vm.nics[0].isolationUri; + string vlan = isolationUri.Replace("vlan://", string.Empty); + Assert.Equal(vlanSettings.AccessVlanId.ToString(), vlan); + + return vmName; + } + + private static void TestStopCommand(string vmName) + { + // Arrange + HypervResourceController rsrcServer = new HypervResourceController(); + String sampleStop = "{\"isProxy\":false,\"vmName\":\"i-2-17-VM\",\"contextMap\":{},\"wait\":0}"; + dynamic jsonStopCmd = JsonConvert.DeserializeObject(sampleStop); + + // Act + dynamic stopAns = rsrcServer.StopCommand(jsonStopCmd); + + // Assert VM is gone! + Assert.NotNull(stopAns[0][CloudStackTypes.StopAnswer]); + Assert.True((bool)stopAns[0][CloudStackTypes.StopAnswer].result, "StopCommand did not succeed " + stopAns[0][CloudStackTypes.StopAnswer].details); + var finalVm = wmiCallsV2.GetComputerSystem(vmName); + Assert.True(wmiCallsV2.GetComputerSystem(vmName) == null); + } + } +} diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_ComputerSystem.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_ComputerSystem.cs index 530275e3358..f3f1abbcc28 100644 --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_ComputerSystem.cs +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_ComputerSystem.cs @@ -1,1818 +1,1818 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2 { - using System; - using System.ComponentModel; - using System.Management; - using System.Collections; - using System.Globalization; - using System.ComponentModel.Design.Serialization; - using System.Reflection; - - - // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. - // Functions IsNull() are used to check if a property is NULL. - // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. - // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. - // Datetime conversion functions ToDateTime and ToDmtfDateTime are added to the class to convert DMTF datetime to System.DateTime and vice-versa. - // An Early Bound class generated for the WMI class.Msvm_ComputerSystem - public class ComputerSystem : System.ComponentModel.Component { - - // Private property to hold the WMI namespace in which the class resides. - private static string CreatedWmiNamespace = "ROOT\\virtualization\\v2"; - - // Private property to hold the name of WMI class which created this class. - private static string CreatedClassName = "Msvm_ComputerSystem"; - - // Private member variable to hold the ManagementScope which is used by the various methods. - private static System.Management.ManagementScope statMgmtScope = null; - - private ManagementSystemProperties PrivateSystemProperties; - - // Underlying lateBound WMI object. - private System.Management.ManagementObject PrivateLateBoundObject; - - // Member variable to store the 'automatic commit' behavior for the class. - private bool AutoCommitProp; - - // Private variable to hold the embedded property representing the instance. - private System.Management.ManagementBaseObject embeddedObj; - - // The current WMI object used - private System.Management.ManagementBaseObject curObj; - - // Flag to indicate if the instance is an embedded object. - private bool isEmbedded; - - // Below are different overloads of constructors to initialize an instance of the class with a WMI object. - public ComputerSystem() { - this.InitializeObject(null, null, null); - } - - public ComputerSystem(string keyCreationClassName, string keyName) { - this.InitializeObject(null, new System.Management.ManagementPath(ComputerSystem.ConstructPath(keyCreationClassName, keyName)), null); - } - - public ComputerSystem(System.Management.ManagementScope mgmtScope, string keyCreationClassName, string keyName) { - this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(ComputerSystem.ConstructPath(keyCreationClassName, keyName)), null); - } - - public ComputerSystem(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(null, path, getOptions); - } - - public ComputerSystem(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { - this.InitializeObject(mgmtScope, path, null); - } - - public ComputerSystem(System.Management.ManagementPath path) { - this.InitializeObject(null, path, null); - } - - public ComputerSystem(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(mgmtScope, path, getOptions); - } - - public ComputerSystem(System.Management.ManagementObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - PrivateLateBoundObject = theObject; - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - public ComputerSystem(System.Management.ManagementBaseObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - embeddedObj = theObject; - PrivateSystemProperties = new ManagementSystemProperties(theObject); - curObj = embeddedObj; - isEmbedded = true; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - // Property returns the namespace of the WMI class. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OriginatingNamespace { - get { - return "ROOT\\virtualization\\v2"; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ManagementClassName { - get { - string strRet = CreatedClassName; - if ((curObj != null)) { - if ((curObj.ClassPath != null)) { - strRet = ((string)(curObj["__CLASS"])); - if (((strRet == null) - || (strRet == string.Empty))) { - strRet = CreatedClassName; - } - } - } - return strRet; - } - } - - // Property pointing to an embedded object to get System properties of the WMI object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ManagementSystemProperties SystemProperties { - get { - return PrivateSystemProperties; - } - } - - // Property returning the underlying lateBound object. - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementBaseObject LateBoundObject { - get { - return curObj; - } - } - - // ManagementScope of the object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementScope Scope { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Scope; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Scope = value; - } - } - } - - // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool AutoCommit { - get { - return AutoCommitProp; - } - set { - AutoCommitProp = value; - } - } - - // The ManagementPath of the underlying WMI object. - [Browsable(true)] - public System.Management.ManagementPath Path { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Path; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - if ((CheckIfProperClass(null, value, null) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - PrivateLateBoundObject.Path = value; - } - } - } - - // Public static scope property which is used by the various methods. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public static System.Management.ManagementScope StaticScope { - get { - return statMgmtScope; - } - set { - statMgmtScope = value; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ushort[] AvailableRequestedStates { - get { - return ((ushort[])(curObj["AvailableRequestedStates"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Caption { - get { - return ((string)(curObj["Caption"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsCommunicationStatusNull { - get { - if ((curObj["CommunicationStatus"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort CommunicationStatus { - get { - if ((curObj["CommunicationStatus"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["CommunicationStatus"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string CreationClassName { - get { - return ((string)(curObj["CreationClassName"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ushort[] Dedicated { - get { - return ((ushort[])(curObj["Dedicated"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Description { - get { - return ((string)(curObj["Description"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsDetailedStatusNull { - get { - if ((curObj["DetailedStatus"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort DetailedStatus { - get { - if ((curObj["DetailedStatus"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["DetailedStatus"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ElementName { - get { - return ((string)(curObj["ElementName"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsEnabledDefaultNull { - get { - if ((curObj["EnabledDefault"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort EnabledDefault { - get { - if ((curObj["EnabledDefault"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["EnabledDefault"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsEnabledStateNull { - get { - if ((curObj["EnabledState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort EnabledState { - get { - if ((curObj["EnabledState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["EnabledState"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsFailedOverReplicationTypeNull { - get { - if ((curObj["FailedOverReplicationType"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("Type of failover that was performed for the virtual machine.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public FailedOverReplicationTypeValues FailedOverReplicationType { - get { - if ((curObj["FailedOverReplicationType"] == null)) { - return ((FailedOverReplicationTypeValues)(System.Convert.ToInt32(4))); - } - return ((FailedOverReplicationTypeValues)(System.Convert.ToInt32(curObj["FailedOverReplicationType"]))); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsHealthStateNull { - get { - if ((curObj["HealthState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort HealthState { - get { - if ((curObj["HealthState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["HealthState"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] IdentifyingDescriptions { - get { - return ((string[])(curObj["IdentifyingDescriptions"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsInstallDateNull { - get { - if ((curObj["InstallDate"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public System.DateTime InstallDate { - get { - if ((curObj["InstallDate"] != null)) { - return ToDateTime(((string)(curObj["InstallDate"]))); - } - else { - return System.DateTime.MinValue; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string InstanceID { - get { - return ((string)(curObj["InstanceID"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsLastApplicationConsistentReplicationTimeNull { - get { - if ((curObj["LastApplicationConsistentReplicationTime"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The time at which the last application consistent replication is received on reco" + - "very for the virtual machine.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public System.DateTime LastApplicationConsistentReplicationTime { - get { - if ((curObj["LastApplicationConsistentReplicationTime"] != null)) { - return ToDateTime(((string)(curObj["LastApplicationConsistentReplicationTime"]))); - } - else { - return System.DateTime.MinValue; - } - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsLastReplicationTimeNull { - get { - if ((curObj["LastReplicationTime"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The time at which the last replication is received on recovery for the virtual ma" + - "chine.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public System.DateTime LastReplicationTime { - get { - if ((curObj["LastReplicationTime"] != null)) { - return ToDateTime(((string)(curObj["LastReplicationTime"]))); - } - else { - return System.DateTime.MinValue; - } - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsLastReplicationTypeNull { - get { - if ((curObj["LastReplicationType"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("Type of the last replication that was received for the virtual machine.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public LastReplicationTypeValues LastReplicationType { - get { - if ((curObj["LastReplicationType"] == null)) { - return ((LastReplicationTypeValues)(System.Convert.ToInt32(4))); - } - return ((LastReplicationTypeValues)(System.Convert.ToInt32(curObj["LastReplicationType"]))); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsLastSuccessfulBackupTimeNull { - get { - if ((curObj["LastSuccessfulBackupTime"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The time at which the last successful backup has completed for the virtual machin" + - "e.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public System.DateTime LastSuccessfulBackupTime { - get { - if ((curObj["LastSuccessfulBackupTime"] != null)) { - return ToDateTime(((string)(curObj["LastSuccessfulBackupTime"]))); - } - else { - return System.DateTime.MinValue; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Name { - get { - return ((string)(curObj["Name"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string NameFormat { - get { - return ((string)(curObj["NameFormat"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsNumberOfNumaNodesNull { - get { - if ((curObj["NumberOfNumaNodes"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description(@"The number of non-uniform memory access (NUMA) nodes of the computer system. When Msvm_ComputerSystem represents the hosting computer system, this property contains the count of physical NUMA nodes. When Msvm_ComputerSystem represents a virtual computer system, this property contains the number of virtual NUMA nodes that are presented to the guest OS through the ACPI System Resource Affinity Table (SRAT).")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort NumberOfNumaNodes { - get { - if ((curObj["NumberOfNumaNodes"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["NumberOfNumaNodes"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsOnTimeInMillisecondsNull { - get { - if ((curObj["OnTimeInMilliseconds"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description(@"For the virtual system, this property describes the total up time, in milliseconds, since the machine was last turned on, reset, or restored. This time excludes the time the virtual system was in the paused state. For the host system, this property is set to NULL.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong OnTimeInMilliseconds { - get { - if ((curObj["OnTimeInMilliseconds"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["OnTimeInMilliseconds"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsOperatingStatusNull { - get { - if ((curObj["OperatingStatus"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort OperatingStatus { - get { - if ((curObj["OperatingStatus"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["OperatingStatus"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ushort[] OperationalStatus { - get { - return ((ushort[])(curObj["OperationalStatus"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] OtherDedicatedDescriptions { - get { - return ((string[])(curObj["OtherDedicatedDescriptions"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OtherEnabledState { - get { - return ((string)(curObj["OtherEnabledState"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] OtherIdentifyingInfo { - get { - return ((string[])(curObj["OtherIdentifyingInfo"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ushort[] PowerManagementCapabilities { - get { - return ((ushort[])(curObj["PowerManagementCapabilities"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string PrimaryOwnerContact { - get { - return ((string)(curObj["PrimaryOwnerContact"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string PrimaryOwnerName { - get { - return ((string)(curObj["PrimaryOwnerName"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsPrimaryStatusNull { - get { - if ((curObj["PrimaryStatus"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort PrimaryStatus { - get { - if ((curObj["PrimaryStatus"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["PrimaryStatus"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsProcessIDNull { - get { - if ((curObj["ProcessID"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The identifier of the process under which this virtual machine is running. This v" + - "alue can be used to uniquely identify the instance of Vmwp.exe on the system tha" + - "t is running the virtual machine.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public uint ProcessID { - get { - if ((curObj["ProcessID"] == null)) { - return System.Convert.ToUInt32(0); - } - return ((uint)(curObj["ProcessID"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsReplicationHealthNull { - get { - if ((curObj["ReplicationHealth"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("Replication health for the virtual machine.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ReplicationHealthValues ReplicationHealth { - get { - if ((curObj["ReplicationHealth"] == null)) { - return ((ReplicationHealthValues)(System.Convert.ToInt32(4))); - } - return ((ReplicationHealthValues)(System.Convert.ToInt32(curObj["ReplicationHealth"]))); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsReplicationModeNull { - get { - if ((curObj["ReplicationMode"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("Identifies replication type for the virtual machine.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ReplicationModeValues ReplicationMode { - get { - if ((curObj["ReplicationMode"] == null)) { - return ((ReplicationModeValues)(System.Convert.ToInt32(4))); - } - return ((ReplicationModeValues)(System.Convert.ToInt32(curObj["ReplicationMode"]))); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsReplicationStateNull { - get { - if ((curObj["ReplicationState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("Replication state for the virtual machine.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ReplicationStateValues ReplicationState { - get { - if ((curObj["ReplicationState"] == null)) { - return ((ReplicationStateValues)(System.Convert.ToInt32(12))); - } - return ((ReplicationStateValues)(System.Convert.ToInt32(curObj["ReplicationState"]))); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsRequestedStateNull { - get { - if ((curObj["RequestedState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort RequestedState { - get { - if ((curObj["RequestedState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["RequestedState"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsResetCapabilityNull { - get { - if ((curObj["ResetCapability"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort ResetCapability { - get { - if ((curObj["ResetCapability"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["ResetCapability"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] Roles { - get { - return ((string[])(curObj["Roles"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Status { - get { - return ((string)(curObj["Status"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] StatusDescriptions { - get { - return ((string[])(curObj["StatusDescriptions"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsTimeOfLastConfigurationChangeNull { - get { - if ((curObj["TimeOfLastConfigurationChange"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The date and time when the virtual machine configuration file was last modified. " + - "The configuration file is modified during certain virtual machine operations, as" + - " well as when any of the virtual machine or device settings are added, modified," + - " or removed.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public System.DateTime TimeOfLastConfigurationChange { - get { - if ((curObj["TimeOfLastConfigurationChange"] != null)) { - return ToDateTime(((string)(curObj["TimeOfLastConfigurationChange"]))); - } - else { - return System.DateTime.MinValue; - } - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsTimeOfLastStateChangeNull { - get { - if ((curObj["TimeOfLastStateChange"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public System.DateTime TimeOfLastStateChange { - get { - if ((curObj["TimeOfLastStateChange"] != null)) { - return ToDateTime(((string)(curObj["TimeOfLastStateChange"]))); - } - else { - return System.DateTime.MinValue; - } - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsTransitioningToStateNull { - get { - if ((curObj["TransitioningToState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort TransitioningToState { - get { - if ((curObj["TransitioningToState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["TransitioningToState"])); - } - } - - private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { - if (((path != null) - && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); - } - } - - private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { - if (((theObj != null) - && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); - if ((parentClasses != null)) { - int count = 0; - for (count = 0; (count < parentClasses.Length); count = (count + 1)) { - if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { - return true; - } - } - } - } - return false; - } - - private bool ShouldSerializeCommunicationStatus() { - if ((this.IsCommunicationStatusNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeDetailedStatus() { - if ((this.IsDetailedStatusNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeEnabledDefault() { - if ((this.IsEnabledDefaultNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeEnabledState() { - if ((this.IsEnabledStateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeFailedOverReplicationType() { - if ((this.IsFailedOverReplicationTypeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeHealthState() { - if ((this.IsHealthStateNull == false)) { - return true; - } - return false; - } - - // Converts a given datetime in DMTF format to System.DateTime object. - static System.DateTime ToDateTime(string dmtfDate) { - System.DateTime initializer = System.DateTime.MinValue; - int year = initializer.Year; - int month = initializer.Month; - int day = initializer.Day; - int hour = initializer.Hour; - int minute = initializer.Minute; - int second = initializer.Second; - long ticks = 0; - string dmtf = dmtfDate; - System.DateTime datetime = System.DateTime.MinValue; - string tempString = string.Empty; - if ((dmtf == null)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtf.Length == 0)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtf.Length != 25)) { - throw new System.ArgumentOutOfRangeException(); - } - try { - tempString = dmtf.Substring(0, 4); - if (("****" != tempString)) { - year = int.Parse(tempString); - } - tempString = dmtf.Substring(4, 2); - if (("**" != tempString)) { - month = int.Parse(tempString); - } - tempString = dmtf.Substring(6, 2); - if (("**" != tempString)) { - day = int.Parse(tempString); - } - tempString = dmtf.Substring(8, 2); - if (("**" != tempString)) { - hour = int.Parse(tempString); - } - tempString = dmtf.Substring(10, 2); - if (("**" != tempString)) { - minute = int.Parse(tempString); - } - tempString = dmtf.Substring(12, 2); - if (("**" != tempString)) { - second = int.Parse(tempString); - } - tempString = dmtf.Substring(15, 6); - if (("******" != tempString)) { - ticks = (long.Parse(tempString) * ((long)((System.TimeSpan.TicksPerMillisecond / 1000)))); - } - if (((((((((year < 0) - || (month < 0)) - || (day < 0)) - || (hour < 0)) - || (minute < 0)) - || (minute < 0)) - || (second < 0)) - || (ticks < 0))) { - throw new System.ArgumentOutOfRangeException(); - } - } - catch (System.Exception e) { - throw new System.ArgumentOutOfRangeException(null, e.Message); - } - datetime = new System.DateTime(year, month, day, hour, minute, second, 0); - datetime = datetime.AddTicks(ticks); - System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(datetime); - int UTCOffset = 0; - int OffsetToBeAdjusted = 0; - long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); - tempString = dmtf.Substring(22, 3); - if ((tempString != "******")) { - tempString = dmtf.Substring(21, 4); - try { - UTCOffset = int.Parse(tempString); - } - catch (System.Exception e) { - throw new System.ArgumentOutOfRangeException(null, e.Message); - } - OffsetToBeAdjusted = ((int)((OffsetMins - UTCOffset))); - datetime = datetime.AddMinutes(((double)(OffsetToBeAdjusted))); - } - return datetime; - } - - // Converts a given System.DateTime object to DMTF datetime format. - static string ToDmtfDateTime(System.DateTime date) { - string utcString = string.Empty; - System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(date); - long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); - if ((System.Math.Abs(OffsetMins) > 999)) { - date = date.ToUniversalTime(); - utcString = "+000"; - } - else { - if ((tickOffset.Ticks >= 0)) { - utcString = string.Concat("+", ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))).ToString().PadLeft(3, '0')); - } - else { - string strTemp = ((long)(OffsetMins)).ToString(); - utcString = string.Concat("-", strTemp.Substring(1, (strTemp.Length - 1)).PadLeft(3, '0')); - } - } - string dmtfDateTime = ((int)(date.Year)).ToString().PadLeft(4, '0'); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Month)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Day)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Hour)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Minute)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Second)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, "."); - System.DateTime dtTemp = new System.DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, 0); - long microsec = ((long)((((date.Ticks - dtTemp.Ticks) - * 1000) - / System.TimeSpan.TicksPerMillisecond))); - string strMicrosec = ((long)(microsec)).ToString(); - if ((strMicrosec.Length > 6)) { - strMicrosec = strMicrosec.Substring(0, 6); - } - dmtfDateTime = string.Concat(dmtfDateTime, strMicrosec.PadLeft(6, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, utcString); - return dmtfDateTime; - } - - private bool ShouldSerializeInstallDate() { - if ((this.IsInstallDateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeLastApplicationConsistentReplicationTime() { - if ((this.IsLastApplicationConsistentReplicationTimeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeLastReplicationTime() { - if ((this.IsLastReplicationTimeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeLastReplicationType() { - if ((this.IsLastReplicationTypeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeLastSuccessfulBackupTime() { - if ((this.IsLastSuccessfulBackupTimeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeNumberOfNumaNodes() { - if ((this.IsNumberOfNumaNodesNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeOnTimeInMilliseconds() { - if ((this.IsOnTimeInMillisecondsNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeOperatingStatus() { - if ((this.IsOperatingStatusNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializePrimaryStatus() { - if ((this.IsPrimaryStatusNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeProcessID() { - if ((this.IsProcessIDNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeReplicationHealth() { - if ((this.IsReplicationHealthNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeReplicationMode() { - if ((this.IsReplicationModeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeReplicationState() { - if ((this.IsReplicationStateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeRequestedState() { - if ((this.IsRequestedStateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeResetCapability() { - if ((this.IsResetCapabilityNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeTimeOfLastConfigurationChange() { - if ((this.IsTimeOfLastConfigurationChangeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeTimeOfLastStateChange() { - if ((this.IsTimeOfLastStateChangeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeTransitioningToState() { - if ((this.IsTransitioningToStateNull == false)) { - return true; - } - return false; - } - - [Browsable(true)] - public void CommitObject() { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(); - } - } - - [Browsable(true)] - public void CommitObject(System.Management.PutOptions putOptions) { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(putOptions); - } - } - - private void Initialize() { - AutoCommitProp = true; - isEmbedded = false; - } - - private static string ConstructPath(string keyCreationClassName, string keyName) { - string strPath = "ROOT\\virtualization\\v2:Msvm_ComputerSystem"; - strPath = string.Concat(strPath, string.Concat(".CreationClassName=", string.Concat("\"", string.Concat(keyCreationClassName, "\"")))); - strPath = string.Concat(strPath, string.Concat(",Name=", string.Concat("\"", string.Concat(keyName, "\"")))); - return strPath; - } - - private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - Initialize(); - if ((path != null)) { - if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - } - PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - - // Different overloads of GetInstances() help in enumerating instances of the WMI class. - public static ComputerSystemCollection GetInstances() { - return GetInstances(null, null, null); - } - - public static ComputerSystemCollection GetInstances(string condition) { - return GetInstances(null, condition, null); - } - - public static ComputerSystemCollection GetInstances(string[] selectedProperties) { - return GetInstances(null, null, selectedProperties); - } - - public static ComputerSystemCollection GetInstances(string condition, string[] selectedProperties) { - return GetInstances(null, condition, selectedProperties); - } - - public static ComputerSystemCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); - pathObj.ClassName = "Msvm_ComputerSystem"; - pathObj.NamespacePath = "root\\virtualization\\v2"; - System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); - if ((enumOptions == null)) { - enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - } - return new ComputerSystemCollection(clsObject.GetInstances(enumOptions)); - } - - public static ComputerSystemCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { - return GetInstances(mgmtScope, condition, null); - } - - public static ComputerSystemCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { - return GetInstances(mgmtScope, null, selectedProperties); - } - - public static ComputerSystemCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_ComputerSystem", condition, selectedProperties)); - System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - ObjectSearcher.Options = enumOptions; - return new ComputerSystemCollection(ObjectSearcher.Get()); - } - - [Browsable(true)] - public static ComputerSystem CreateInstance() { - System.Management.ManagementScope mgmtScope = null; - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = CreatedWmiNamespace; - } - else { - mgmtScope = statMgmtScope; - } - System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); - System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); - return new ComputerSystem(tmpMgmtClass.CreateInstance()); - } - - [Browsable(true)] - public void Delete() { - PrivateLateBoundObject.Delete(); - } - - public uint RequestReplicationStateChange(ushort RequestedState, System.DateTime TimeoutPeriod, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("RequestReplicationStateChange"); - inParams["RequestedState"] = ((ushort)(RequestedState)); - inParams["TimeoutPeriod"] = ToDmtfDateTime(((System.DateTime)(TimeoutPeriod))); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RequestReplicationStateChange", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null) && outParams.Properties["Job"].Value != null) { - Job = new System.Management.ManagementPath(outParams.Properties["Job"].Value.ToString()); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - return System.Convert.ToUInt32(0); - } - } - - public uint RequestStateChange(ushort RequestedState, System.DateTime TimeoutPeriod, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("RequestStateChange"); - inParams["RequestedState"] = RequestedState; - inParams["TimeoutPeriod"] = null; // ToDmtfDateTime(((System.DateTime)(TimeoutPeriod))); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RequestStateChange", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null) && outParams.Properties["Job"].Value != null) - { - Job = new System.Management.ManagementPath(outParams.Properties["Job"].Value.ToString()); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - return System.Convert.ToUInt32(0); - } - } - - public uint SetPowerState(uint PowerState, System.DateTime Time) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("SetPowerState"); - inParams["PowerState"] = ((uint)(PowerState)); - inParams["Time"] = ToDmtfDateTime(((System.DateTime)(Time))); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("SetPowerState", inParams, null); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - return System.Convert.ToUInt32(0); - } - } - - public enum FailedOverReplicationTypeValues { - - None = 0, - - Regular = 1, - - Application_consistent = 2, - - Planned = 3, - - NULL_ENUM_VALUE = 4, - } - - public enum LastReplicationTypeValues { - - None = 0, - - Regular = 1, - - Application_consistent = 2, - - Planned = 3, - - NULL_ENUM_VALUE = 4, - } - - public enum ReplicationHealthValues { - - Not_applicable = 0, - - Ok = 1, - - Warning = 2, - - Critical = 3, - - NULL_ENUM_VALUE = 4, - } - - public enum ReplicationModeValues { - - None = 0, - - Primary = 1, - - Recovery = 2, - - Test_Replica = 3, - - NULL_ENUM_VALUE = 4, - } - - public enum ReplicationStateValues { - - Disabled = 0, - - Ready_for_replication = 1, - - Waiting_to_complete_initial_replication = 2, - - Replicating = 3, - - Synced_replication_complete = 4, - - Recovered = 5, - - Committed = 6, - - Suspended = 7, - - Critical = 8, - - Waiting_to_start_resynchronization = 9, - - Resynchronizing = 10, - - Resynchronization_suspended = 11, - - NULL_ENUM_VALUE = 12, - } - - // Enumerator implementation for enumerating instances of the class. - public class ComputerSystemCollection : object, ICollection { - - private ManagementObjectCollection privColObj; - - public ComputerSystemCollection(ManagementObjectCollection objCollection) { - privColObj = objCollection; - } - - public virtual int Count { - get { - return privColObj.Count; - } - } - - public virtual bool IsSynchronized { - get { - return privColObj.IsSynchronized; - } - } - - public virtual object SyncRoot { - get { - return this; - } - } - - public virtual void CopyTo(System.Array array, int index) { - privColObj.CopyTo(array, index); - int nCtr; - for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { - array.SetValue(new ComputerSystem(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); - } - } - - public virtual System.Collections.IEnumerator GetEnumerator() { - return new ComputerSystemEnumerator(privColObj.GetEnumerator()); - } - - public class ComputerSystemEnumerator : object, System.Collections.IEnumerator { - - private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; - - public ComputerSystemEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { - privObjEnum = objEnum; - } - - public virtual object Current { - get { - return new ComputerSystem(((System.Management.ManagementObject)(privObjEnum.Current))); - } - } - - public virtual bool MoveNext() { - return privObjEnum.MoveNext(); - } - - public virtual void Reset() { - privObjEnum.Reset(); - } - } - } - - // TypeConverter to handle null values for ValueType properties - public class WMIValueTypeConverter : TypeConverter { - - private TypeConverter baseConverter; - - private System.Type baseType; - - public WMIValueTypeConverter(System.Type inBaseType) { - baseConverter = TypeDescriptor.GetConverter(inBaseType); - baseType = inBaseType; - } - - public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { - return baseConverter.CanConvertFrom(context, srcType); - } - - public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { - return baseConverter.CanConvertTo(context, destinationType); - } - - public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { - return baseConverter.ConvertFrom(context, culture, value); - } - - public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { - return baseConverter.CreateInstance(context, dictionary); - } - - public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetCreateInstanceSupported(context); - } - - public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { - return baseConverter.GetProperties(context, value, attributeVar); - } - - public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetPropertiesSupported(context); - } - - public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValues(context); - } - - public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesExclusive(context); - } - - public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesSupported(context); - } - - public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { - if ((baseType.BaseType == typeof(System.Enum))) { - if ((value.GetType() == destinationType)) { - return value; - } - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return "NULL_ENUM_VALUE" ; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((baseType == typeof(bool)) - && (baseType.BaseType == typeof(System.ValueType)))) { - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((context != null) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - } - - // Embedded class to represent WMI system Properties. - [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] - public class ManagementSystemProperties { - - private System.Management.ManagementBaseObject PrivateLateBoundObject; - - public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { - PrivateLateBoundObject = ManagedObject; - } - - [Browsable(true)] - public int GENUS { - get { - return ((int)(PrivateLateBoundObject["__GENUS"])); - } - } - - [Browsable(true)] - public string CLASS { - get { - return ((string)(PrivateLateBoundObject["__CLASS"])); - } - } - - [Browsable(true)] - public string SUPERCLASS { - get { - return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); - } - } - - [Browsable(true)] - public string DYNASTY { - get { - return ((string)(PrivateLateBoundObject["__DYNASTY"])); - } - } - - [Browsable(true)] - public string RELPATH { - get { - return ((string)(PrivateLateBoundObject["__RELPATH"])); - } - } - - [Browsable(true)] - public int PROPERTY_COUNT { - get { - return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); - } - } - - [Browsable(true)] - public string[] DERIVATION { - get { - return ((string[])(PrivateLateBoundObject["__DERIVATION"])); - } - } - - [Browsable(true)] - public string SERVER { - get { - return ((string)(PrivateLateBoundObject["__SERVER"])); - } - } - - [Browsable(true)] - public string NAMESPACE { - get { - return ((string)(PrivateLateBoundObject["__NAMESPACE"])); - } - } - - [Browsable(true)] - public string PATH { - get { - return ((string)(PrivateLateBoundObject["__PATH"])); - } - } - } - } -} +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2 { + using System; + using System.ComponentModel; + using System.Management; + using System.Collections; + using System.Globalization; + using System.ComponentModel.Design.Serialization; + using System.Reflection; + + + // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. + // Functions IsNull() are used to check if a property is NULL. + // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. + // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. + // Datetime conversion functions ToDateTime and ToDmtfDateTime are added to the class to convert DMTF datetime to System.DateTime and vice-versa. + // An Early Bound class generated for the WMI class.Msvm_ComputerSystem + public class ComputerSystem : System.ComponentModel.Component { + + // Private property to hold the WMI namespace in which the class resides. + private static string CreatedWmiNamespace = "ROOT\\virtualization\\v2"; + + // Private property to hold the name of WMI class which created this class. + private static string CreatedClassName = "Msvm_ComputerSystem"; + + // Private member variable to hold the ManagementScope which is used by the various methods. + private static System.Management.ManagementScope statMgmtScope = null; + + private ManagementSystemProperties PrivateSystemProperties; + + // Underlying lateBound WMI object. + private System.Management.ManagementObject PrivateLateBoundObject; + + // Member variable to store the 'automatic commit' behavior for the class. + private bool AutoCommitProp; + + // Private variable to hold the embedded property representing the instance. + private System.Management.ManagementBaseObject embeddedObj; + + // The current WMI object used + private System.Management.ManagementBaseObject curObj; + + // Flag to indicate if the instance is an embedded object. + private bool isEmbedded; + + // Below are different overloads of constructors to initialize an instance of the class with a WMI object. + public ComputerSystem() { + this.InitializeObject(null, null, null); + } + + public ComputerSystem(string keyCreationClassName, string keyName) { + this.InitializeObject(null, new System.Management.ManagementPath(ComputerSystem.ConstructPath(keyCreationClassName, keyName)), null); + } + + public ComputerSystem(System.Management.ManagementScope mgmtScope, string keyCreationClassName, string keyName) { + this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(ComputerSystem.ConstructPath(keyCreationClassName, keyName)), null); + } + + public ComputerSystem(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(null, path, getOptions); + } + + public ComputerSystem(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { + this.InitializeObject(mgmtScope, path, null); + } + + public ComputerSystem(System.Management.ManagementPath path) { + this.InitializeObject(null, path, null); + } + + public ComputerSystem(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(mgmtScope, path, getOptions); + } + + public ComputerSystem(System.Management.ManagementObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + PrivateLateBoundObject = theObject; + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + public ComputerSystem(System.Management.ManagementBaseObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + embeddedObj = theObject; + PrivateSystemProperties = new ManagementSystemProperties(theObject); + curObj = embeddedObj; + isEmbedded = true; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + // Property returns the namespace of the WMI class. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OriginatingNamespace { + get { + return "ROOT\\virtualization\\v2"; + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ManagementClassName { + get { + string strRet = CreatedClassName; + if ((curObj != null)) { + if ((curObj.ClassPath != null)) { + strRet = ((string)(curObj["__CLASS"])); + if (((strRet == null) + || (strRet == string.Empty))) { + strRet = CreatedClassName; + } + } + } + return strRet; + } + } + + // Property pointing to an embedded object to get System properties of the WMI object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ManagementSystemProperties SystemProperties { + get { + return PrivateSystemProperties; + } + } + + // Property returning the underlying lateBound object. + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementBaseObject LateBoundObject { + get { + return curObj; + } + } + + // ManagementScope of the object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementScope Scope { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Scope; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Scope = value; + } + } + } + + // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool AutoCommit { + get { + return AutoCommitProp; + } + set { + AutoCommitProp = value; + } + } + + // The ManagementPath of the underlying WMI object. + [Browsable(true)] + public System.Management.ManagementPath Path { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Path; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + if ((CheckIfProperClass(null, value, null) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + PrivateLateBoundObject.Path = value; + } + } + } + + // Public static scope property which is used by the various methods. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public static System.Management.ManagementScope StaticScope { + get { + return statMgmtScope; + } + set { + statMgmtScope = value; + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ushort[] AvailableRequestedStates { + get { + return ((ushort[])(curObj["AvailableRequestedStates"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Caption { + get { + return ((string)(curObj["Caption"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsCommunicationStatusNull { + get { + if ((curObj["CommunicationStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort CommunicationStatus { + get { + if ((curObj["CommunicationStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["CommunicationStatus"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string CreationClassName { + get { + return ((string)(curObj["CreationClassName"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ushort[] Dedicated { + get { + return ((ushort[])(curObj["Dedicated"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Description { + get { + return ((string)(curObj["Description"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsDetailedStatusNull { + get { + if ((curObj["DetailedStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort DetailedStatus { + get { + if ((curObj["DetailedStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["DetailedStatus"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ElementName { + get { + return ((string)(curObj["ElementName"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsEnabledDefaultNull { + get { + if ((curObj["EnabledDefault"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort EnabledDefault { + get { + if ((curObj["EnabledDefault"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["EnabledDefault"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsEnabledStateNull { + get { + if ((curObj["EnabledState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort EnabledState { + get { + if ((curObj["EnabledState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["EnabledState"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsFailedOverReplicationTypeNull { + get { + if ((curObj["FailedOverReplicationType"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Type of failover that was performed for the virtual machine.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public FailedOverReplicationTypeValues FailedOverReplicationType { + get { + if ((curObj["FailedOverReplicationType"] == null)) { + return ((FailedOverReplicationTypeValues)(System.Convert.ToInt32(4))); + } + return ((FailedOverReplicationTypeValues)(System.Convert.ToInt32(curObj["FailedOverReplicationType"]))); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsHealthStateNull { + get { + if ((curObj["HealthState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort HealthState { + get { + if ((curObj["HealthState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["HealthState"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] IdentifyingDescriptions { + get { + return ((string[])(curObj["IdentifyingDescriptions"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsInstallDateNull { + get { + if ((curObj["InstallDate"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime InstallDate { + get { + if ((curObj["InstallDate"] != null)) { + return ToDateTime(((string)(curObj["InstallDate"]))); + } + else { + return System.DateTime.MinValue; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string InstanceID { + get { + return ((string)(curObj["InstanceID"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsLastApplicationConsistentReplicationTimeNull { + get { + if ((curObj["LastApplicationConsistentReplicationTime"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The time at which the last application consistent replication is received on reco" + + "very for the virtual machine.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime LastApplicationConsistentReplicationTime { + get { + if ((curObj["LastApplicationConsistentReplicationTime"] != null)) { + return ToDateTime(((string)(curObj["LastApplicationConsistentReplicationTime"]))); + } + else { + return System.DateTime.MinValue; + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsLastReplicationTimeNull { + get { + if ((curObj["LastReplicationTime"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The time at which the last replication is received on recovery for the virtual ma" + + "chine.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime LastReplicationTime { + get { + if ((curObj["LastReplicationTime"] != null)) { + return ToDateTime(((string)(curObj["LastReplicationTime"]))); + } + else { + return System.DateTime.MinValue; + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsLastReplicationTypeNull { + get { + if ((curObj["LastReplicationType"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Type of the last replication that was received for the virtual machine.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public LastReplicationTypeValues LastReplicationType { + get { + if ((curObj["LastReplicationType"] == null)) { + return ((LastReplicationTypeValues)(System.Convert.ToInt32(4))); + } + return ((LastReplicationTypeValues)(System.Convert.ToInt32(curObj["LastReplicationType"]))); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsLastSuccessfulBackupTimeNull { + get { + if ((curObj["LastSuccessfulBackupTime"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The time at which the last successful backup has completed for the virtual machin" + + "e.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime LastSuccessfulBackupTime { + get { + if ((curObj["LastSuccessfulBackupTime"] != null)) { + return ToDateTime(((string)(curObj["LastSuccessfulBackupTime"]))); + } + else { + return System.DateTime.MinValue; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Name { + get { + return ((string)(curObj["Name"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string NameFormat { + get { + return ((string)(curObj["NameFormat"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsNumberOfNumaNodesNull { + get { + if ((curObj["NumberOfNumaNodes"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"The number of non-uniform memory access (NUMA) nodes of the computer system. When Msvm_ComputerSystem represents the hosting computer system, this property contains the count of physical NUMA nodes. When Msvm_ComputerSystem represents a virtual computer system, this property contains the number of virtual NUMA nodes that are presented to the guest OS through the ACPI System Resource Affinity Table (SRAT).")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort NumberOfNumaNodes { + get { + if ((curObj["NumberOfNumaNodes"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["NumberOfNumaNodes"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsOnTimeInMillisecondsNull { + get { + if ((curObj["OnTimeInMilliseconds"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"For the virtual system, this property describes the total up time, in milliseconds, since the machine was last turned on, reset, or restored. This time excludes the time the virtual system was in the paused state. For the host system, this property is set to NULL.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong OnTimeInMilliseconds { + get { + if ((curObj["OnTimeInMilliseconds"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["OnTimeInMilliseconds"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsOperatingStatusNull { + get { + if ((curObj["OperatingStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort OperatingStatus { + get { + if ((curObj["OperatingStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["OperatingStatus"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ushort[] OperationalStatus { + get { + return ((ushort[])(curObj["OperationalStatus"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] OtherDedicatedDescriptions { + get { + return ((string[])(curObj["OtherDedicatedDescriptions"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherEnabledState { + get { + return ((string)(curObj["OtherEnabledState"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] OtherIdentifyingInfo { + get { + return ((string[])(curObj["OtherIdentifyingInfo"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ushort[] PowerManagementCapabilities { + get { + return ((ushort[])(curObj["PowerManagementCapabilities"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string PrimaryOwnerContact { + get { + return ((string)(curObj["PrimaryOwnerContact"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string PrimaryOwnerName { + get { + return ((string)(curObj["PrimaryOwnerName"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPrimaryStatusNull { + get { + if ((curObj["PrimaryStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort PrimaryStatus { + get { + if ((curObj["PrimaryStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["PrimaryStatus"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsProcessIDNull { + get { + if ((curObj["ProcessID"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The identifier of the process under which this virtual machine is running. This v" + + "alue can be used to uniquely identify the instance of Vmwp.exe on the system tha" + + "t is running the virtual machine.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint ProcessID { + get { + if ((curObj["ProcessID"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["ProcessID"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsReplicationHealthNull { + get { + if ((curObj["ReplicationHealth"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Replication health for the virtual machine.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ReplicationHealthValues ReplicationHealth { + get { + if ((curObj["ReplicationHealth"] == null)) { + return ((ReplicationHealthValues)(System.Convert.ToInt32(4))); + } + return ((ReplicationHealthValues)(System.Convert.ToInt32(curObj["ReplicationHealth"]))); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsReplicationModeNull { + get { + if ((curObj["ReplicationMode"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Identifies replication type for the virtual machine.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ReplicationModeValues ReplicationMode { + get { + if ((curObj["ReplicationMode"] == null)) { + return ((ReplicationModeValues)(System.Convert.ToInt32(4))); + } + return ((ReplicationModeValues)(System.Convert.ToInt32(curObj["ReplicationMode"]))); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsReplicationStateNull { + get { + if ((curObj["ReplicationState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Replication state for the virtual machine.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ReplicationStateValues ReplicationState { + get { + if ((curObj["ReplicationState"] == null)) { + return ((ReplicationStateValues)(System.Convert.ToInt32(12))); + } + return ((ReplicationStateValues)(System.Convert.ToInt32(curObj["ReplicationState"]))); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsRequestedStateNull { + get { + if ((curObj["RequestedState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort RequestedState { + get { + if ((curObj["RequestedState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["RequestedState"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsResetCapabilityNull { + get { + if ((curObj["ResetCapability"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort ResetCapability { + get { + if ((curObj["ResetCapability"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["ResetCapability"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] Roles { + get { + return ((string[])(curObj["Roles"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Status { + get { + return ((string)(curObj["Status"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] StatusDescriptions { + get { + return ((string[])(curObj["StatusDescriptions"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsTimeOfLastConfigurationChangeNull { + get { + if ((curObj["TimeOfLastConfigurationChange"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The date and time when the virtual machine configuration file was last modified. " + + "The configuration file is modified during certain virtual machine operations, as" + + " well as when any of the virtual machine or device settings are added, modified," + + " or removed.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime TimeOfLastConfigurationChange { + get { + if ((curObj["TimeOfLastConfigurationChange"] != null)) { + return ToDateTime(((string)(curObj["TimeOfLastConfigurationChange"]))); + } + else { + return System.DateTime.MinValue; + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsTimeOfLastStateChangeNull { + get { + if ((curObj["TimeOfLastStateChange"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime TimeOfLastStateChange { + get { + if ((curObj["TimeOfLastStateChange"] != null)) { + return ToDateTime(((string)(curObj["TimeOfLastStateChange"]))); + } + else { + return System.DateTime.MinValue; + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsTransitioningToStateNull { + get { + if ((curObj["TransitioningToState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort TransitioningToState { + get { + if ((curObj["TransitioningToState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["TransitioningToState"])); + } + } + + private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { + if (((path != null) + && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); + } + } + + private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { + if (((theObj != null) + && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); + if ((parentClasses != null)) { + int count = 0; + for (count = 0; (count < parentClasses.Length); count = (count + 1)) { + if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { + return true; + } + } + } + } + return false; + } + + private bool ShouldSerializeCommunicationStatus() { + if ((this.IsCommunicationStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeDetailedStatus() { + if ((this.IsDetailedStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeEnabledDefault() { + if ((this.IsEnabledDefaultNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeEnabledState() { + if ((this.IsEnabledStateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeFailedOverReplicationType() { + if ((this.IsFailedOverReplicationTypeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeHealthState() { + if ((this.IsHealthStateNull == false)) { + return true; + } + return false; + } + + // Converts a given datetime in DMTF format to System.DateTime object. + static System.DateTime ToDateTime(string dmtfDate) { + System.DateTime initializer = System.DateTime.MinValue; + int year = initializer.Year; + int month = initializer.Month; + int day = initializer.Day; + int hour = initializer.Hour; + int minute = initializer.Minute; + int second = initializer.Second; + long ticks = 0; + string dmtf = dmtfDate; + System.DateTime datetime = System.DateTime.MinValue; + string tempString = string.Empty; + if ((dmtf == null)) { + throw new System.ArgumentOutOfRangeException(); + } + if ((dmtf.Length == 0)) { + throw new System.ArgumentOutOfRangeException(); + } + if ((dmtf.Length != 25)) { + throw new System.ArgumentOutOfRangeException(); + } + try { + tempString = dmtf.Substring(0, 4); + if (("****" != tempString)) { + year = int.Parse(tempString); + } + tempString = dmtf.Substring(4, 2); + if (("**" != tempString)) { + month = int.Parse(tempString); + } + tempString = dmtf.Substring(6, 2); + if (("**" != tempString)) { + day = int.Parse(tempString); + } + tempString = dmtf.Substring(8, 2); + if (("**" != tempString)) { + hour = int.Parse(tempString); + } + tempString = dmtf.Substring(10, 2); + if (("**" != tempString)) { + minute = int.Parse(tempString); + } + tempString = dmtf.Substring(12, 2); + if (("**" != tempString)) { + second = int.Parse(tempString); + } + tempString = dmtf.Substring(15, 6); + if (("******" != tempString)) { + ticks = (long.Parse(tempString) * ((long)((System.TimeSpan.TicksPerMillisecond / 1000)))); + } + if (((((((((year < 0) + || (month < 0)) + || (day < 0)) + || (hour < 0)) + || (minute < 0)) + || (minute < 0)) + || (second < 0)) + || (ticks < 0))) { + throw new System.ArgumentOutOfRangeException(); + } + } + catch (System.Exception e) { + throw new System.ArgumentOutOfRangeException(null, e.Message); + } + datetime = new System.DateTime(year, month, day, hour, minute, second, 0); + datetime = datetime.AddTicks(ticks); + System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(datetime); + int UTCOffset = 0; + int OffsetToBeAdjusted = 0; + long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); + tempString = dmtf.Substring(22, 3); + if ((tempString != "******")) { + tempString = dmtf.Substring(21, 4); + try { + UTCOffset = int.Parse(tempString); + } + catch (System.Exception e) { + throw new System.ArgumentOutOfRangeException(null, e.Message); + } + OffsetToBeAdjusted = ((int)((OffsetMins - UTCOffset))); + datetime = datetime.AddMinutes(((double)(OffsetToBeAdjusted))); + } + return datetime; + } + + // Converts a given System.DateTime object to DMTF datetime format. + static string ToDmtfDateTime(System.DateTime date) { + string utcString = string.Empty; + System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(date); + long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); + if ((System.Math.Abs(OffsetMins) > 999)) { + date = date.ToUniversalTime(); + utcString = "+000"; + } + else { + if ((tickOffset.Ticks >= 0)) { + utcString = string.Concat("+", ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))).ToString().PadLeft(3, '0')); + } + else { + string strTemp = ((long)(OffsetMins)).ToString(); + utcString = string.Concat("-", strTemp.Substring(1, (strTemp.Length - 1)).PadLeft(3, '0')); + } + } + string dmtfDateTime = ((int)(date.Year)).ToString().PadLeft(4, '0'); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Month)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Day)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Hour)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Minute)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Second)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, "."); + System.DateTime dtTemp = new System.DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, 0); + long microsec = ((long)((((date.Ticks - dtTemp.Ticks) + * 1000) + / System.TimeSpan.TicksPerMillisecond))); + string strMicrosec = ((long)(microsec)).ToString(); + if ((strMicrosec.Length > 6)) { + strMicrosec = strMicrosec.Substring(0, 6); + } + dmtfDateTime = string.Concat(dmtfDateTime, strMicrosec.PadLeft(6, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, utcString); + return dmtfDateTime; + } + + private bool ShouldSerializeInstallDate() { + if ((this.IsInstallDateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeLastApplicationConsistentReplicationTime() { + if ((this.IsLastApplicationConsistentReplicationTimeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeLastReplicationTime() { + if ((this.IsLastReplicationTimeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeLastReplicationType() { + if ((this.IsLastReplicationTypeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeLastSuccessfulBackupTime() { + if ((this.IsLastSuccessfulBackupTimeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeNumberOfNumaNodes() { + if ((this.IsNumberOfNumaNodesNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeOnTimeInMilliseconds() { + if ((this.IsOnTimeInMillisecondsNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeOperatingStatus() { + if ((this.IsOperatingStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePrimaryStatus() { + if ((this.IsPrimaryStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeProcessID() { + if ((this.IsProcessIDNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeReplicationHealth() { + if ((this.IsReplicationHealthNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeReplicationMode() { + if ((this.IsReplicationModeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeReplicationState() { + if ((this.IsReplicationStateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeRequestedState() { + if ((this.IsRequestedStateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeResetCapability() { + if ((this.IsResetCapabilityNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeTimeOfLastConfigurationChange() { + if ((this.IsTimeOfLastConfigurationChangeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeTimeOfLastStateChange() { + if ((this.IsTimeOfLastStateChangeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeTransitioningToState() { + if ((this.IsTransitioningToStateNull == false)) { + return true; + } + return false; + } + + [Browsable(true)] + public void CommitObject() { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(); + } + } + + [Browsable(true)] + public void CommitObject(System.Management.PutOptions putOptions) { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(putOptions); + } + } + + private void Initialize() { + AutoCommitProp = true; + isEmbedded = false; + } + + private static string ConstructPath(string keyCreationClassName, string keyName) { + string strPath = "ROOT\\virtualization\\v2:Msvm_ComputerSystem"; + strPath = string.Concat(strPath, string.Concat(".CreationClassName=", string.Concat("\"", string.Concat(keyCreationClassName, "\"")))); + strPath = string.Concat(strPath, string.Concat(",Name=", string.Concat("\"", string.Concat(keyName, "\"")))); + return strPath; + } + + private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + Initialize(); + if ((path != null)) { + if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + } + PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + + // Different overloads of GetInstances() help in enumerating instances of the WMI class. + public static ComputerSystemCollection GetInstances() { + return GetInstances(null, null, null); + } + + public static ComputerSystemCollection GetInstances(string condition) { + return GetInstances(null, condition, null); + } + + public static ComputerSystemCollection GetInstances(string[] selectedProperties) { + return GetInstances(null, null, selectedProperties); + } + + public static ComputerSystemCollection GetInstances(string condition, string[] selectedProperties) { + return GetInstances(null, condition, selectedProperties); + } + + public static ComputerSystemCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); + pathObj.ClassName = "Msvm_ComputerSystem"; + pathObj.NamespacePath = "root\\virtualization\\v2"; + System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); + if ((enumOptions == null)) { + enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + } + return new ComputerSystemCollection(clsObject.GetInstances(enumOptions)); + } + + public static ComputerSystemCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { + return GetInstances(mgmtScope, condition, null); + } + + public static ComputerSystemCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { + return GetInstances(mgmtScope, null, selectedProperties); + } + + public static ComputerSystemCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_ComputerSystem", condition, selectedProperties)); + System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + ObjectSearcher.Options = enumOptions; + return new ComputerSystemCollection(ObjectSearcher.Get()); + } + + [Browsable(true)] + public static ComputerSystem CreateInstance() { + System.Management.ManagementScope mgmtScope = null; + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = CreatedWmiNamespace; + } + else { + mgmtScope = statMgmtScope; + } + System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); + System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); + return new ComputerSystem(tmpMgmtClass.CreateInstance()); + } + + [Browsable(true)] + public void Delete() { + PrivateLateBoundObject.Delete(); + } + + public uint RequestReplicationStateChange(ushort RequestedState, System.DateTime TimeoutPeriod, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("RequestReplicationStateChange"); + inParams["RequestedState"] = ((ushort)(RequestedState)); + inParams["TimeoutPeriod"] = ToDmtfDateTime(((System.DateTime)(TimeoutPeriod))); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RequestReplicationStateChange", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null) && outParams.Properties["Job"].Value != null) { + Job = new System.Management.ManagementPath(outParams.Properties["Job"].Value.ToString()); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + return System.Convert.ToUInt32(0); + } + } + + public uint RequestStateChange(ushort RequestedState, System.DateTime TimeoutPeriod, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("RequestStateChange"); + inParams["RequestedState"] = RequestedState; + inParams["TimeoutPeriod"] = null; // ToDmtfDateTime(((System.DateTime)(TimeoutPeriod))); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RequestStateChange", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null) && outParams.Properties["Job"].Value != null) + { + Job = new System.Management.ManagementPath(outParams.Properties["Job"].Value.ToString()); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + return System.Convert.ToUInt32(0); + } + } + + public uint SetPowerState(uint PowerState, System.DateTime Time) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("SetPowerState"); + inParams["PowerState"] = ((uint)(PowerState)); + inParams["Time"] = ToDmtfDateTime(((System.DateTime)(Time))); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("SetPowerState", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + public enum FailedOverReplicationTypeValues { + + None = 0, + + Regular = 1, + + Application_consistent = 2, + + Planned = 3, + + NULL_ENUM_VALUE = 4, + } + + public enum LastReplicationTypeValues { + + None = 0, + + Regular = 1, + + Application_consistent = 2, + + Planned = 3, + + NULL_ENUM_VALUE = 4, + } + + public enum ReplicationHealthValues { + + Not_applicable = 0, + + Ok = 1, + + Warning = 2, + + Critical = 3, + + NULL_ENUM_VALUE = 4, + } + + public enum ReplicationModeValues { + + None = 0, + + Primary = 1, + + Recovery = 2, + + Test_Replica = 3, + + NULL_ENUM_VALUE = 4, + } + + public enum ReplicationStateValues { + + Disabled = 0, + + Ready_for_replication = 1, + + Waiting_to_complete_initial_replication = 2, + + Replicating = 3, + + Synced_replication_complete = 4, + + Recovered = 5, + + Committed = 6, + + Suspended = 7, + + Critical = 8, + + Waiting_to_start_resynchronization = 9, + + Resynchronizing = 10, + + Resynchronization_suspended = 11, + + NULL_ENUM_VALUE = 12, + } + + // Enumerator implementation for enumerating instances of the class. + public class ComputerSystemCollection : object, ICollection { + + private ManagementObjectCollection privColObj; + + public ComputerSystemCollection(ManagementObjectCollection objCollection) { + privColObj = objCollection; + } + + public virtual int Count { + get { + return privColObj.Count; + } + } + + public virtual bool IsSynchronized { + get { + return privColObj.IsSynchronized; + } + } + + public virtual object SyncRoot { + get { + return this; + } + } + + public virtual void CopyTo(System.Array array, int index) { + privColObj.CopyTo(array, index); + int nCtr; + for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { + array.SetValue(new ComputerSystem(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); + } + } + + public virtual System.Collections.IEnumerator GetEnumerator() { + return new ComputerSystemEnumerator(privColObj.GetEnumerator()); + } + + public class ComputerSystemEnumerator : object, System.Collections.IEnumerator { + + private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; + + public ComputerSystemEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { + privObjEnum = objEnum; + } + + public virtual object Current { + get { + return new ComputerSystem(((System.Management.ManagementObject)(privObjEnum.Current))); + } + } + + public virtual bool MoveNext() { + return privObjEnum.MoveNext(); + } + + public virtual void Reset() { + privObjEnum.Reset(); + } + } + } + + // TypeConverter to handle null values for ValueType properties + public class WMIValueTypeConverter : TypeConverter { + + private TypeConverter baseConverter; + + private System.Type baseType; + + public WMIValueTypeConverter(System.Type inBaseType) { + baseConverter = TypeDescriptor.GetConverter(inBaseType); + baseType = inBaseType; + } + + public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { + return baseConverter.CanConvertFrom(context, srcType); + } + + public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { + return baseConverter.CanConvertTo(context, destinationType); + } + + public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { + return baseConverter.ConvertFrom(context, culture, value); + } + + public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { + return baseConverter.CreateInstance(context, dictionary); + } + + public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetCreateInstanceSupported(context); + } + + public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { + return baseConverter.GetProperties(context, value, attributeVar); + } + + public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetPropertiesSupported(context); + } + + public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValues(context); + } + + public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesExclusive(context); + } + + public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesSupported(context); + } + + public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { + if ((baseType.BaseType == typeof(System.Enum))) { + if ((value.GetType() == destinationType)) { + return value; + } + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return "NULL_ENUM_VALUE" ; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((baseType == typeof(bool)) + && (baseType.BaseType == typeof(System.ValueType)))) { + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((context != null) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + } + + // Embedded class to represent WMI system Properties. + [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] + public class ManagementSystemProperties { + + private System.Management.ManagementBaseObject PrivateLateBoundObject; + + public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { + PrivateLateBoundObject = ManagedObject; + } + + [Browsable(true)] + public int GENUS { + get { + return ((int)(PrivateLateBoundObject["__GENUS"])); + } + } + + [Browsable(true)] + public string CLASS { + get { + return ((string)(PrivateLateBoundObject["__CLASS"])); + } + } + + [Browsable(true)] + public string SUPERCLASS { + get { + return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); + } + } + + [Browsable(true)] + public string DYNASTY { + get { + return ((string)(PrivateLateBoundObject["__DYNASTY"])); + } + } + + [Browsable(true)] + public string RELPATH { + get { + return ((string)(PrivateLateBoundObject["__RELPATH"])); + } + } + + [Browsable(true)] + public int PROPERTY_COUNT { + get { + return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); + } + } + + [Browsable(true)] + public string[] DERIVATION { + get { + return ((string[])(PrivateLateBoundObject["__DERIVATION"])); + } + } + + [Browsable(true)] + public string SERVER { + get { + return ((string)(PrivateLateBoundObject["__SERVER"])); + } + } + + [Browsable(true)] + public string NAMESPACE { + get { + return ((string)(PrivateLateBoundObject["__NAMESPACE"])); + } + } + + [Browsable(true)] + public string PATH { + get { + return ((string)(PrivateLateBoundObject["__PATH"])); + } + } + } + } +} diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_ConcreteJob.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_ConcreteJob.cs index 256029d96a7..73b3599a8ce 100644 --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_ConcreteJob.cs +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_ConcreteJob.cs @@ -1,1843 +1,1843 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2 { - using System; - using System.ComponentModel; - using System.Management; - using System.Collections; - using System.Globalization; - using System.ComponentModel.Design.Serialization; - using System.Reflection; - - - // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. - // Functions IsNull() are used to check if a property is NULL. - // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. - // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. - // Time interval functions ToTimeSpan and ToDmtfTimeInterval are added to the class to convert DMTF Time Interval to System.TimeSpan and vice-versa. - // Datetime conversion functions ToDateTime and ToDmtfDateTime are added to the class to convert DMTF datetime to System.DateTime and vice-versa. - // An Early Bound class generated for the WMI class.Msvm_ConcreteJob - public class ConcreteJob : System.ComponentModel.Component { - - // Private property to hold the WMI namespace in which the class resides. - private static string CreatedWmiNamespace = "ROOT\\virtualization\\v2"; - - // Private property to hold the name of WMI class which created this class. - private static string CreatedClassName = "Msvm_ConcreteJob"; - - // Private member variable to hold the ManagementScope which is used by the various methods. - private static System.Management.ManagementScope statMgmtScope = null; - - private ManagementSystemProperties PrivateSystemProperties; - - // Underlying lateBound WMI object. - private System.Management.ManagementObject PrivateLateBoundObject; - - // Member variable to store the 'automatic commit' behavior for the class. - private bool AutoCommitProp; - - // Private variable to hold the embedded property representing the instance. - private System.Management.ManagementBaseObject embeddedObj; - - // The current WMI object used - private System.Management.ManagementBaseObject curObj; - - // Flag to indicate if the instance is an embedded object. - private bool isEmbedded; - - // Below are different overloads of constructors to initialize an instance of the class with a WMI object. - public ConcreteJob() { - this.InitializeObject(null, null, null); - } - - public ConcreteJob(string keyInstanceID) { - this.InitializeObject(null, new System.Management.ManagementPath(ConcreteJob.ConstructPath(keyInstanceID)), null); - } - - public ConcreteJob(System.Management.ManagementScope mgmtScope, string keyInstanceID) { - this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(ConcreteJob.ConstructPath(keyInstanceID)), null); - } - - public ConcreteJob(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(null, path, getOptions); - } - - public ConcreteJob(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { - this.InitializeObject(mgmtScope, path, null); - } - - public ConcreteJob(System.Management.ManagementPath path) { - this.InitializeObject(null, path, null); - } - - public ConcreteJob(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(mgmtScope, path, getOptions); - } - - public ConcreteJob(System.Management.ManagementObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - PrivateLateBoundObject = theObject; - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - public ConcreteJob(System.Management.ManagementBaseObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - embeddedObj = theObject; - PrivateSystemProperties = new ManagementSystemProperties(theObject); - curObj = embeddedObj; - isEmbedded = true; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - // Property returns the namespace of the WMI class. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OriginatingNamespace { - get { - return "ROOT\\virtualization\\v2"; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ManagementClassName { - get { - string strRet = CreatedClassName; - if ((curObj != null)) { - if ((curObj.ClassPath != null)) { - strRet = ((string)(curObj["__CLASS"])); - if (((strRet == null) - || (strRet == string.Empty))) { - strRet = CreatedClassName; - } - } - } - return strRet; - } - } - - // Property pointing to an embedded object to get System properties of the WMI object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ManagementSystemProperties SystemProperties { - get { - return PrivateSystemProperties; - } - } - - // Property returning the underlying lateBound object. - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementBaseObject LateBoundObject { - get { - return curObj; - } - } - - // ManagementScope of the object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementScope Scope { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Scope; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Scope = value; - } - } - } - - // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool AutoCommit { - get { - return AutoCommitProp; - } - set { - AutoCommitProp = value; - } - } - - // The ManagementPath of the underlying WMI object. - [Browsable(true)] - public System.Management.ManagementPath Path { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Path; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - if ((CheckIfProperClass(null, value, null) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - PrivateLateBoundObject.Path = value; - } - } - } - - // Public static scope property which is used by the various methods. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public static System.Management.ManagementScope StaticScope { - get { - return statMgmtScope; - } - set { - statMgmtScope = value; - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsCancellableNull { - get { - if ((curObj["Cancellable"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("Indicates whether the job can be cancelled. The value of this property does not g" + - "uarantee that a request to cancel the job will succeed.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool Cancellable { - get { - if ((curObj["Cancellable"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["Cancellable"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Caption { - get { - return ((string)(curObj["Caption"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsCommunicationStatusNull { - get { - if ((curObj["CommunicationStatus"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort CommunicationStatus { - get { - if ((curObj["CommunicationStatus"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["CommunicationStatus"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsDeleteOnCompletionNull { - get { - if ((curObj["DeleteOnCompletion"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool DeleteOnCompletion { - get { - if ((curObj["DeleteOnCompletion"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["DeleteOnCompletion"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Description { - get { - return ((string)(curObj["Description"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsDetailedStatusNull { - get { - if ((curObj["DetailedStatus"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort DetailedStatus { - get { - if ((curObj["DetailedStatus"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["DetailedStatus"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsElapsedTimeNull { - get { - if ((curObj["ElapsedTime"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public System.TimeSpan ElapsedTime { - get { - if ((curObj["ElapsedTime"] != null)) { - return ToTimeSpan(((string)(curObj["ElapsedTime"]))); - } - else { - return new System.TimeSpan(0, 0, 0, 0, 0); - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ElementName { - get { - return ((string)(curObj["ElementName"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsErrorCodeNull { - get { - if ((curObj["ErrorCode"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort ErrorCode { - get { - if ((curObj["ErrorCode"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["ErrorCode"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ErrorDescription { - get { - return ((string)(curObj["ErrorDescription"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ErrorSummaryDescription { - get { - return ((string)(curObj["ErrorSummaryDescription"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsHealthStateNull { - get { - if ((curObj["HealthState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort HealthState { - get { - if ((curObj["HealthState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["HealthState"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsInstallDateNull { - get { - if ((curObj["InstallDate"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public System.DateTime InstallDate { - get { - if ((curObj["InstallDate"] != null)) { - return ToDateTime(((string)(curObj["InstallDate"]))); - } - else { - return System.DateTime.MinValue; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string InstanceID { - get { - return ((string)(curObj["InstanceID"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsJobRunTimesNull { - get { - if ((curObj["JobRunTimes"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public uint JobRunTimes { - get { - if ((curObj["JobRunTimes"] == null)) { - return System.Convert.ToUInt32(0); - } - return ((uint)(curObj["JobRunTimes"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsJobStateNull { - get { - if ((curObj["JobState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort JobState { - get { - if ((curObj["JobState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["JobState"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string JobStatus { - get { - return ((string)(curObj["JobStatus"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsJobTypeNull { - get { - if ((curObj["JobType"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("Indicates the type of Job being tracked by this object.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort JobType { - get { - if ((curObj["JobType"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["JobType"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsLocalOrUtcTimeNull { - get { - if ((curObj["LocalOrUtcTime"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort LocalOrUtcTime { - get { - if ((curObj["LocalOrUtcTime"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["LocalOrUtcTime"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Name { - get { - return ((string)(curObj["Name"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Notify { - get { - return ((string)(curObj["Notify"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsOperatingStatusNull { - get { - if ((curObj["OperatingStatus"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort OperatingStatus { - get { - if ((curObj["OperatingStatus"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["OperatingStatus"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ushort[] OperationalStatus { - get { - return ((ushort[])(curObj["OperationalStatus"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OtherRecoveryAction { - get { - return ((string)(curObj["OtherRecoveryAction"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Owner { - get { - return ((string)(curObj["Owner"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsPercentCompleteNull { - get { - if ((curObj["PercentComplete"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort PercentComplete { - get { - if ((curObj["PercentComplete"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["PercentComplete"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsPrimaryStatusNull { - get { - if ((curObj["PrimaryStatus"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort PrimaryStatus { - get { - if ((curObj["PrimaryStatus"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["PrimaryStatus"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsPriorityNull { - get { - if ((curObj["Priority"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public uint Priority { - get { - if ((curObj["Priority"] == null)) { - return System.Convert.ToUInt32(0); - } - return ((uint)(curObj["Priority"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsRecoveryActionNull { - get { - if ((curObj["RecoveryAction"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort RecoveryAction { - get { - if ((curObj["RecoveryAction"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["RecoveryAction"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsRunDayNull { - get { - if ((curObj["RunDay"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public sbyte RunDay { - get { - if ((curObj["RunDay"] == null)) { - return System.Convert.ToSByte(0); - } - return ((sbyte)(curObj["RunDay"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsRunDayOfWeekNull { - get { - if ((curObj["RunDayOfWeek"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public sbyte RunDayOfWeek { - get { - if ((curObj["RunDayOfWeek"] == null)) { - return System.Convert.ToSByte(0); - } - return ((sbyte)(curObj["RunDayOfWeek"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsRunMonthNull { - get { - if ((curObj["RunMonth"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public byte RunMonth { - get { - if ((curObj["RunMonth"] == null)) { - return System.Convert.ToByte(0); - } - return ((byte)(curObj["RunMonth"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsRunStartIntervalNull { - get { - if ((curObj["RunStartInterval"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public System.TimeSpan RunStartInterval { - get { - if ((curObj["RunStartInterval"] != null)) { - return ToTimeSpan(((string)(curObj["RunStartInterval"]))); - } - else { - return new System.TimeSpan(0, 0, 0, 0, 0); - } - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsScheduledStartTimeNull { - get { - if ((curObj["ScheduledStartTime"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public System.DateTime ScheduledStartTime { - get { - if ((curObj["ScheduledStartTime"] != null)) { - return ToDateTime(((string)(curObj["ScheduledStartTime"]))); - } - else { - return System.DateTime.MinValue; - } - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsStartTimeNull { - get { - if ((curObj["StartTime"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public System.DateTime StartTime { - get { - if ((curObj["StartTime"] != null)) { - return ToDateTime(((string)(curObj["StartTime"]))); - } - else { - return System.DateTime.MinValue; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Status { - get { - return ((string)(curObj["Status"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] StatusDescriptions { - get { - return ((string[])(curObj["StatusDescriptions"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsTimeBeforeRemovalNull { - get { - if ((curObj["TimeBeforeRemoval"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public System.TimeSpan TimeBeforeRemoval { - get { - if ((curObj["TimeBeforeRemoval"] != null)) { - return ToTimeSpan(((string)(curObj["TimeBeforeRemoval"]))); - } - else { - return new System.TimeSpan(0, 0, 0, 0, 0); - } - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsTimeOfLastStateChangeNull { - get { - if ((curObj["TimeOfLastStateChange"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public System.DateTime TimeOfLastStateChange { - get { - if ((curObj["TimeOfLastStateChange"] != null)) { - return ToDateTime(((string)(curObj["TimeOfLastStateChange"]))); - } - else { - return System.DateTime.MinValue; - } - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsTimeSubmittedNull { - get { - if ((curObj["TimeSubmitted"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public System.DateTime TimeSubmitted { - get { - if ((curObj["TimeSubmitted"] != null)) { - return ToDateTime(((string)(curObj["TimeSubmitted"]))); - } - else { - return System.DateTime.MinValue; - } - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsUntilTimeNull { - get { - if ((curObj["UntilTime"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public System.DateTime UntilTime { - get { - if ((curObj["UntilTime"] != null)) { - return ToDateTime(((string)(curObj["UntilTime"]))); - } - else { - return System.DateTime.MinValue; - } - } - } - - private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { - if (((path != null) - && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); - } - } - - private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { - if (((theObj != null) - && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); - if ((parentClasses != null)) { - int count = 0; - for (count = 0; (count < parentClasses.Length); count = (count + 1)) { - if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { - return true; - } - } - } - } - return false; - } - - private bool ShouldSerializeCancellable() { - if ((this.IsCancellableNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeCommunicationStatus() { - if ((this.IsCommunicationStatusNull == false)) { - return true; - } - return false; - } - - // Converts a given time interval in DMTF format to System.TimeSpan object. - static System.TimeSpan ToTimeSpan(string dmtfTimespan) { - int days = 0; - int hours = 0; - int minutes = 0; - int seconds = 0; - long ticks = 0; - if ((dmtfTimespan == null)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtfTimespan.Length == 0)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtfTimespan.Length != 25)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtfTimespan.Substring(21, 4) != ":000")) { - throw new System.ArgumentOutOfRangeException(); - } - try { - string tempString = string.Empty; - tempString = dmtfTimespan.Substring(0, 8); - days = int.Parse(tempString); - tempString = dmtfTimespan.Substring(8, 2); - hours = int.Parse(tempString); - tempString = dmtfTimespan.Substring(10, 2); - minutes = int.Parse(tempString); - tempString = dmtfTimespan.Substring(12, 2); - seconds = int.Parse(tempString); - tempString = dmtfTimespan.Substring(15, 6); - ticks = (long.Parse(tempString) * ((long)((System.TimeSpan.TicksPerMillisecond / 1000)))); - } - catch (System.Exception e) { - throw new System.ArgumentOutOfRangeException(null, e.Message); - } - System.TimeSpan timespan = new System.TimeSpan(days, hours, minutes, seconds, 0); - System.TimeSpan tsTemp = System.TimeSpan.FromTicks(ticks); - timespan = timespan.Add(tsTemp); - return timespan; - } - - // Converts a given System.TimeSpan object to DMTF Time interval format. - static string ToDmtfTimeInterval(System.TimeSpan timespan) { - string dmtftimespan = ((int)(timespan.Days)).ToString().PadLeft(8, '0'); - System.TimeSpan maxTimeSpan = System.TimeSpan.MaxValue; - if ((timespan.Days > maxTimeSpan.Days)) { - throw new System.ArgumentOutOfRangeException(); - } - System.TimeSpan minTimeSpan = System.TimeSpan.MinValue; - if ((timespan.Days < minTimeSpan.Days)) { - throw new System.ArgumentOutOfRangeException(); - } - dmtftimespan = string.Concat(dmtftimespan, ((int)(timespan.Hours)).ToString().PadLeft(2, '0')); - dmtftimespan = string.Concat(dmtftimespan, ((int)(timespan.Minutes)).ToString().PadLeft(2, '0')); - dmtftimespan = string.Concat(dmtftimespan, ((int)(timespan.Seconds)).ToString().PadLeft(2, '0')); - dmtftimespan = string.Concat(dmtftimespan, "."); - System.TimeSpan tsTemp = new System.TimeSpan(timespan.Days, timespan.Hours, timespan.Minutes, timespan.Seconds, 0); - long microsec = ((long)((((timespan.Ticks - tsTemp.Ticks) - * 1000) - / System.TimeSpan.TicksPerMillisecond))); - string strMicroSec = ((long)(microsec)).ToString(); - if ((strMicroSec.Length > 6)) { - strMicroSec = strMicroSec.Substring(0, 6); - } - dmtftimespan = string.Concat(dmtftimespan, strMicroSec.PadLeft(6, '0')); - dmtftimespan = string.Concat(dmtftimespan, ":000"); - return dmtftimespan; - } - - private bool ShouldSerializeDeleteOnCompletion() { - if ((this.IsDeleteOnCompletionNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeDetailedStatus() { - if ((this.IsDetailedStatusNull == false)) { - return true; - } - return false; - } - - // Converts a given datetime in DMTF format to System.DateTime object. - static System.DateTime ToDateTime(string dmtfDate) { - System.DateTime initializer = System.DateTime.MinValue; - int year = initializer.Year; - int month = initializer.Month; - int day = initializer.Day; - int hour = initializer.Hour; - int minute = initializer.Minute; - int second = initializer.Second; - long ticks = 0; - string dmtf = dmtfDate; - System.DateTime datetime = System.DateTime.MinValue; - string tempString = string.Empty; - if ((dmtf == null)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtf.Length == 0)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtf.Length != 25)) { - throw new System.ArgumentOutOfRangeException(); - } - try { - tempString = dmtf.Substring(0, 4); - if (("****" != tempString)) { - year = int.Parse(tempString); - } - tempString = dmtf.Substring(4, 2); - if (("**" != tempString)) { - month = int.Parse(tempString); - } - tempString = dmtf.Substring(6, 2); - if (("**" != tempString)) { - day = int.Parse(tempString); - } - tempString = dmtf.Substring(8, 2); - if (("**" != tempString)) { - hour = int.Parse(tempString); - } - tempString = dmtf.Substring(10, 2); - if (("**" != tempString)) { - minute = int.Parse(tempString); - } - tempString = dmtf.Substring(12, 2); - if (("**" != tempString)) { - second = int.Parse(tempString); - } - tempString = dmtf.Substring(15, 6); - if (("******" != tempString)) { - ticks = (long.Parse(tempString) * ((long)((System.TimeSpan.TicksPerMillisecond / 1000)))); - } - if (((((((((year < 0) - || (month < 0)) - || (day < 0)) - || (hour < 0)) - || (minute < 0)) - || (minute < 0)) - || (second < 0)) - || (ticks < 0))) { - throw new System.ArgumentOutOfRangeException(); - } - } - catch (System.Exception e) { - throw new System.ArgumentOutOfRangeException(null, e.Message); - } - datetime = new System.DateTime(year, month, day, hour, minute, second, 0); - datetime = datetime.AddTicks(ticks); - System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(datetime); - int UTCOffset = 0; - int OffsetToBeAdjusted = 0; - long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); - tempString = dmtf.Substring(22, 3); - if ((tempString != "******")) { - tempString = dmtf.Substring(21, 4); - try { - UTCOffset = int.Parse(tempString); - } - catch (System.Exception e) { - throw new System.ArgumentOutOfRangeException(null, e.Message); - } - OffsetToBeAdjusted = ((int)((OffsetMins - UTCOffset))); - datetime = datetime.AddMinutes(((double)(OffsetToBeAdjusted))); - } - return datetime; - } - - // Converts a given System.DateTime object to DMTF datetime format. - static string ToDmtfDateTime(System.DateTime date) { - string utcString = string.Empty; - System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(date); - long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); - if ((System.Math.Abs(OffsetMins) > 999)) { - date = date.ToUniversalTime(); - utcString = "+000"; - } - else { - if ((tickOffset.Ticks >= 0)) { - utcString = string.Concat("+", ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))).ToString().PadLeft(3, '0')); - } - else { - string strTemp = ((long)(OffsetMins)).ToString(); - utcString = string.Concat("-", strTemp.Substring(1, (strTemp.Length - 1)).PadLeft(3, '0')); - } - } - string dmtfDateTime = ((int)(date.Year)).ToString().PadLeft(4, '0'); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Month)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Day)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Hour)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Minute)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Second)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, "."); - System.DateTime dtTemp = new System.DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, 0); - long microsec = ((long)((((date.Ticks - dtTemp.Ticks) - * 1000) - / System.TimeSpan.TicksPerMillisecond))); - string strMicrosec = ((long)(microsec)).ToString(); - if ((strMicrosec.Length > 6)) { - strMicrosec = strMicrosec.Substring(0, 6); - } - dmtfDateTime = string.Concat(dmtfDateTime, strMicrosec.PadLeft(6, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, utcString); - return dmtfDateTime; - } - - private bool ShouldSerializeElapsedTime() { - if ((this.IsElapsedTimeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeErrorCode() { - if ((this.IsErrorCodeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeHealthState() { - if ((this.IsHealthStateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeInstallDate() { - if ((this.IsInstallDateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeJobRunTimes() { - if ((this.IsJobRunTimesNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeJobState() { - if ((this.IsJobStateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeJobType() { - if ((this.IsJobTypeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeLocalOrUtcTime() { - if ((this.IsLocalOrUtcTimeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeOperatingStatus() { - if ((this.IsOperatingStatusNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializePercentComplete() { - if ((this.IsPercentCompleteNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializePrimaryStatus() { - if ((this.IsPrimaryStatusNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializePriority() { - if ((this.IsPriorityNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeRecoveryAction() { - if ((this.IsRecoveryActionNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeRunDay() { - if ((this.IsRunDayNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeRunDayOfWeek() { - if ((this.IsRunDayOfWeekNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeRunMonth() { - if ((this.IsRunMonthNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeRunStartInterval() { - if ((this.IsRunStartIntervalNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeScheduledStartTime() { - if ((this.IsScheduledStartTimeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeStartTime() { - if ((this.IsStartTimeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeTimeBeforeRemoval() { - if ((this.IsTimeBeforeRemovalNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeTimeOfLastStateChange() { - if ((this.IsTimeOfLastStateChangeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeTimeSubmitted() { - if ((this.IsTimeSubmittedNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeUntilTime() { - if ((this.IsUntilTimeNull == false)) { - return true; - } - return false; - } - - [Browsable(true)] - public void CommitObject() { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(); - } - } - - [Browsable(true)] - public void CommitObject(System.Management.PutOptions putOptions) { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(putOptions); - } - } - - private void Initialize() { - AutoCommitProp = true; - isEmbedded = false; - } - - private static string ConstructPath(string keyInstanceID) { - string strPath = "ROOT\\virtualization\\v2:Msvm_ConcreteJob"; - strPath = string.Concat(strPath, string.Concat(".InstanceID=", string.Concat("\"", string.Concat(keyInstanceID, "\"")))); - return strPath; - } - - private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - Initialize(); - if ((path != null)) { - if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - } - PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - - // Different overloads of GetInstances() help in enumerating instances of the WMI class. - public static ConcreteJobCollection GetInstances() { - return GetInstances(null, null, null); - } - - public static ConcreteJobCollection GetInstances(string condition) { - return GetInstances(null, condition, null); - } - - public static ConcreteJobCollection GetInstances(string[] selectedProperties) { - return GetInstances(null, null, selectedProperties); - } - - public static ConcreteJobCollection GetInstances(string condition, string[] selectedProperties) { - return GetInstances(null, condition, selectedProperties); - } - - public static ConcreteJobCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); - pathObj.ClassName = "Msvm_ConcreteJob"; - pathObj.NamespacePath = "root\\virtualization\\v2"; - System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); - if ((enumOptions == null)) { - enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - } - return new ConcreteJobCollection(clsObject.GetInstances(enumOptions)); - } - - public static ConcreteJobCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { - return GetInstances(mgmtScope, condition, null); - } - - public static ConcreteJobCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { - return GetInstances(mgmtScope, null, selectedProperties); - } - - public static ConcreteJobCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_ConcreteJob", condition, selectedProperties)); - System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - ObjectSearcher.Options = enumOptions; - return new ConcreteJobCollection(ObjectSearcher.Get()); - } - - [Browsable(true)] - public static ConcreteJob CreateInstance() { - System.Management.ManagementScope mgmtScope = null; - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = CreatedWmiNamespace; - } - else { - mgmtScope = statMgmtScope; - } - System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); - System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); - return new ConcreteJob(tmpMgmtClass.CreateInstance()); - } - - [Browsable(true)] - public void Delete() { - PrivateLateBoundObject.Delete(); - } - - public uint GetError(out string Error) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("GetError", inParams, null); - Error = System.Convert.ToString(outParams.Properties["Error"].Value); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Error = null; - return System.Convert.ToUInt32(0); - } - } - - public uint GetErrorEx(out string[] Errors) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("GetErrorEx", inParams, null); - Errors = ((string[])(outParams.Properties["Errors"].Value)); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Errors = null; - return System.Convert.ToUInt32(0); - } - } - - public uint KillJob(bool DeleteOnKill) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("KillJob"); - inParams["DeleteOnKill"] = ((bool)(DeleteOnKill)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("KillJob", inParams, null); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - return System.Convert.ToUInt32(0); - } - } - - public uint RequestStateChange(ushort RequestedState, System.TimeSpan TimeoutPeriod) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("RequestStateChange"); - inParams["RequestedState"] = ((ushort)(RequestedState)); - inParams["TimeoutPeriod"] = ToDmtfTimeInterval(((System.TimeSpan)(TimeoutPeriod))); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RequestStateChange", inParams, null); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - return System.Convert.ToUInt32(0); - } - } - - // Enumerator implementation for enumerating instances of the class. - public class ConcreteJobCollection : object, ICollection { - - private ManagementObjectCollection privColObj; - - public ConcreteJobCollection(ManagementObjectCollection objCollection) { - privColObj = objCollection; - } - - public virtual int Count { - get { - return privColObj.Count; - } - } - - public virtual bool IsSynchronized { - get { - return privColObj.IsSynchronized; - } - } - - public virtual object SyncRoot { - get { - return this; - } - } - - public virtual void CopyTo(System.Array array, int index) { - privColObj.CopyTo(array, index); - int nCtr; - for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { - array.SetValue(new ConcreteJob(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); - } - } - - public virtual System.Collections.IEnumerator GetEnumerator() { - return new ConcreteJobEnumerator(privColObj.GetEnumerator()); - } - - public class ConcreteJobEnumerator : object, System.Collections.IEnumerator { - - private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; - - public ConcreteJobEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { - privObjEnum = objEnum; - } - - public virtual object Current { - get { - return new ConcreteJob(((System.Management.ManagementObject)(privObjEnum.Current))); - } - } - - public virtual bool MoveNext() { - return privObjEnum.MoveNext(); - } - - public virtual void Reset() { - privObjEnum.Reset(); - } - } - } - - // TypeConverter to handle null values for ValueType properties - public class WMIValueTypeConverter : TypeConverter { - - private TypeConverter baseConverter; - - private System.Type baseType; - - public WMIValueTypeConverter(System.Type inBaseType) { - baseConverter = TypeDescriptor.GetConverter(inBaseType); - baseType = inBaseType; - } - - public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { - return baseConverter.CanConvertFrom(context, srcType); - } - - public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { - return baseConverter.CanConvertTo(context, destinationType); - } - - public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { - return baseConverter.ConvertFrom(context, culture, value); - } - - public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { - return baseConverter.CreateInstance(context, dictionary); - } - - public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetCreateInstanceSupported(context); - } - - public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { - return baseConverter.GetProperties(context, value, attributeVar); - } - - public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetPropertiesSupported(context); - } - - public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValues(context); - } - - public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesExclusive(context); - } - - public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesSupported(context); - } - - public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { - if ((baseType.BaseType == typeof(System.Enum))) { - if ((value.GetType() == destinationType)) { - return value; - } - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return "NULL_ENUM_VALUE" ; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((baseType == typeof(bool)) - && (baseType.BaseType == typeof(System.ValueType)))) { - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((context != null) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - } - - // Embedded class to represent WMI system Properties. - [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] - public class ManagementSystemProperties { - - private System.Management.ManagementBaseObject PrivateLateBoundObject; - - public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { - PrivateLateBoundObject = ManagedObject; - } - - [Browsable(true)] - public int GENUS { - get { - return ((int)(PrivateLateBoundObject["__GENUS"])); - } - } - - [Browsable(true)] - public string CLASS { - get { - return ((string)(PrivateLateBoundObject["__CLASS"])); - } - } - - [Browsable(true)] - public string SUPERCLASS { - get { - return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); - } - } - - [Browsable(true)] - public string DYNASTY { - get { - return ((string)(PrivateLateBoundObject["__DYNASTY"])); - } - } - - [Browsable(true)] - public string RELPATH { - get { - return ((string)(PrivateLateBoundObject["__RELPATH"])); - } - } - - [Browsable(true)] - public int PROPERTY_COUNT { - get { - return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); - } - } - - [Browsable(true)] - public string[] DERIVATION { - get { - return ((string[])(PrivateLateBoundObject["__DERIVATION"])); - } - } - - [Browsable(true)] - public string SERVER { - get { - return ((string)(PrivateLateBoundObject["__SERVER"])); - } - } - - [Browsable(true)] - public string NAMESPACE { - get { - return ((string)(PrivateLateBoundObject["__NAMESPACE"])); - } - } - - [Browsable(true)] - public string PATH { - get { - return ((string)(PrivateLateBoundObject["__PATH"])); - } - } - } - } -} +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2 { + using System; + using System.ComponentModel; + using System.Management; + using System.Collections; + using System.Globalization; + using System.ComponentModel.Design.Serialization; + using System.Reflection; + + + // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. + // Functions IsNull() are used to check if a property is NULL. + // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. + // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. + // Time interval functions ToTimeSpan and ToDmtfTimeInterval are added to the class to convert DMTF Time Interval to System.TimeSpan and vice-versa. + // Datetime conversion functions ToDateTime and ToDmtfDateTime are added to the class to convert DMTF datetime to System.DateTime and vice-versa. + // An Early Bound class generated for the WMI class.Msvm_ConcreteJob + public class ConcreteJob : System.ComponentModel.Component { + + // Private property to hold the WMI namespace in which the class resides. + private static string CreatedWmiNamespace = "ROOT\\virtualization\\v2"; + + // Private property to hold the name of WMI class which created this class. + private static string CreatedClassName = "Msvm_ConcreteJob"; + + // Private member variable to hold the ManagementScope which is used by the various methods. + private static System.Management.ManagementScope statMgmtScope = null; + + private ManagementSystemProperties PrivateSystemProperties; + + // Underlying lateBound WMI object. + private System.Management.ManagementObject PrivateLateBoundObject; + + // Member variable to store the 'automatic commit' behavior for the class. + private bool AutoCommitProp; + + // Private variable to hold the embedded property representing the instance. + private System.Management.ManagementBaseObject embeddedObj; + + // The current WMI object used + private System.Management.ManagementBaseObject curObj; + + // Flag to indicate if the instance is an embedded object. + private bool isEmbedded; + + // Below are different overloads of constructors to initialize an instance of the class with a WMI object. + public ConcreteJob() { + this.InitializeObject(null, null, null); + } + + public ConcreteJob(string keyInstanceID) { + this.InitializeObject(null, new System.Management.ManagementPath(ConcreteJob.ConstructPath(keyInstanceID)), null); + } + + public ConcreteJob(System.Management.ManagementScope mgmtScope, string keyInstanceID) { + this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(ConcreteJob.ConstructPath(keyInstanceID)), null); + } + + public ConcreteJob(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(null, path, getOptions); + } + + public ConcreteJob(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { + this.InitializeObject(mgmtScope, path, null); + } + + public ConcreteJob(System.Management.ManagementPath path) { + this.InitializeObject(null, path, null); + } + + public ConcreteJob(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(mgmtScope, path, getOptions); + } + + public ConcreteJob(System.Management.ManagementObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + PrivateLateBoundObject = theObject; + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + public ConcreteJob(System.Management.ManagementBaseObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + embeddedObj = theObject; + PrivateSystemProperties = new ManagementSystemProperties(theObject); + curObj = embeddedObj; + isEmbedded = true; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + // Property returns the namespace of the WMI class. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OriginatingNamespace { + get { + return "ROOT\\virtualization\\v2"; + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ManagementClassName { + get { + string strRet = CreatedClassName; + if ((curObj != null)) { + if ((curObj.ClassPath != null)) { + strRet = ((string)(curObj["__CLASS"])); + if (((strRet == null) + || (strRet == string.Empty))) { + strRet = CreatedClassName; + } + } + } + return strRet; + } + } + + // Property pointing to an embedded object to get System properties of the WMI object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ManagementSystemProperties SystemProperties { + get { + return PrivateSystemProperties; + } + } + + // Property returning the underlying lateBound object. + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementBaseObject LateBoundObject { + get { + return curObj; + } + } + + // ManagementScope of the object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementScope Scope { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Scope; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Scope = value; + } + } + } + + // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool AutoCommit { + get { + return AutoCommitProp; + } + set { + AutoCommitProp = value; + } + } + + // The ManagementPath of the underlying WMI object. + [Browsable(true)] + public System.Management.ManagementPath Path { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Path; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + if ((CheckIfProperClass(null, value, null) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + PrivateLateBoundObject.Path = value; + } + } + } + + // Public static scope property which is used by the various methods. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public static System.Management.ManagementScope StaticScope { + get { + return statMgmtScope; + } + set { + statMgmtScope = value; + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsCancellableNull { + get { + if ((curObj["Cancellable"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Indicates whether the job can be cancelled. The value of this property does not g" + + "uarantee that a request to cancel the job will succeed.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool Cancellable { + get { + if ((curObj["Cancellable"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["Cancellable"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Caption { + get { + return ((string)(curObj["Caption"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsCommunicationStatusNull { + get { + if ((curObj["CommunicationStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort CommunicationStatus { + get { + if ((curObj["CommunicationStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["CommunicationStatus"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsDeleteOnCompletionNull { + get { + if ((curObj["DeleteOnCompletion"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool DeleteOnCompletion { + get { + if ((curObj["DeleteOnCompletion"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["DeleteOnCompletion"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Description { + get { + return ((string)(curObj["Description"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsDetailedStatusNull { + get { + if ((curObj["DetailedStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort DetailedStatus { + get { + if ((curObj["DetailedStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["DetailedStatus"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsElapsedTimeNull { + get { + if ((curObj["ElapsedTime"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.TimeSpan ElapsedTime { + get { + if ((curObj["ElapsedTime"] != null)) { + return ToTimeSpan(((string)(curObj["ElapsedTime"]))); + } + else { + return new System.TimeSpan(0, 0, 0, 0, 0); + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ElementName { + get { + return ((string)(curObj["ElementName"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsErrorCodeNull { + get { + if ((curObj["ErrorCode"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort ErrorCode { + get { + if ((curObj["ErrorCode"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["ErrorCode"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ErrorDescription { + get { + return ((string)(curObj["ErrorDescription"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ErrorSummaryDescription { + get { + return ((string)(curObj["ErrorSummaryDescription"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsHealthStateNull { + get { + if ((curObj["HealthState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort HealthState { + get { + if ((curObj["HealthState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["HealthState"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsInstallDateNull { + get { + if ((curObj["InstallDate"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime InstallDate { + get { + if ((curObj["InstallDate"] != null)) { + return ToDateTime(((string)(curObj["InstallDate"]))); + } + else { + return System.DateTime.MinValue; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string InstanceID { + get { + return ((string)(curObj["InstanceID"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsJobRunTimesNull { + get { + if ((curObj["JobRunTimes"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint JobRunTimes { + get { + if ((curObj["JobRunTimes"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["JobRunTimes"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsJobStateNull { + get { + if ((curObj["JobState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort JobState { + get { + if ((curObj["JobState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["JobState"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string JobStatus { + get { + return ((string)(curObj["JobStatus"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsJobTypeNull { + get { + if ((curObj["JobType"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Indicates the type of Job being tracked by this object.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort JobType { + get { + if ((curObj["JobType"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["JobType"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsLocalOrUtcTimeNull { + get { + if ((curObj["LocalOrUtcTime"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort LocalOrUtcTime { + get { + if ((curObj["LocalOrUtcTime"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["LocalOrUtcTime"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Name { + get { + return ((string)(curObj["Name"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Notify { + get { + return ((string)(curObj["Notify"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsOperatingStatusNull { + get { + if ((curObj["OperatingStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort OperatingStatus { + get { + if ((curObj["OperatingStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["OperatingStatus"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ushort[] OperationalStatus { + get { + return ((ushort[])(curObj["OperationalStatus"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherRecoveryAction { + get { + return ((string)(curObj["OtherRecoveryAction"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Owner { + get { + return ((string)(curObj["Owner"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPercentCompleteNull { + get { + if ((curObj["PercentComplete"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort PercentComplete { + get { + if ((curObj["PercentComplete"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["PercentComplete"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPrimaryStatusNull { + get { + if ((curObj["PrimaryStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort PrimaryStatus { + get { + if ((curObj["PrimaryStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["PrimaryStatus"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPriorityNull { + get { + if ((curObj["Priority"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint Priority { + get { + if ((curObj["Priority"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["Priority"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsRecoveryActionNull { + get { + if ((curObj["RecoveryAction"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort RecoveryAction { + get { + if ((curObj["RecoveryAction"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["RecoveryAction"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsRunDayNull { + get { + if ((curObj["RunDay"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public sbyte RunDay { + get { + if ((curObj["RunDay"] == null)) { + return System.Convert.ToSByte(0); + } + return ((sbyte)(curObj["RunDay"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsRunDayOfWeekNull { + get { + if ((curObj["RunDayOfWeek"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public sbyte RunDayOfWeek { + get { + if ((curObj["RunDayOfWeek"] == null)) { + return System.Convert.ToSByte(0); + } + return ((sbyte)(curObj["RunDayOfWeek"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsRunMonthNull { + get { + if ((curObj["RunMonth"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public byte RunMonth { + get { + if ((curObj["RunMonth"] == null)) { + return System.Convert.ToByte(0); + } + return ((byte)(curObj["RunMonth"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsRunStartIntervalNull { + get { + if ((curObj["RunStartInterval"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.TimeSpan RunStartInterval { + get { + if ((curObj["RunStartInterval"] != null)) { + return ToTimeSpan(((string)(curObj["RunStartInterval"]))); + } + else { + return new System.TimeSpan(0, 0, 0, 0, 0); + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsScheduledStartTimeNull { + get { + if ((curObj["ScheduledStartTime"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime ScheduledStartTime { + get { + if ((curObj["ScheduledStartTime"] != null)) { + return ToDateTime(((string)(curObj["ScheduledStartTime"]))); + } + else { + return System.DateTime.MinValue; + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsStartTimeNull { + get { + if ((curObj["StartTime"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime StartTime { + get { + if ((curObj["StartTime"] != null)) { + return ToDateTime(((string)(curObj["StartTime"]))); + } + else { + return System.DateTime.MinValue; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Status { + get { + return ((string)(curObj["Status"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] StatusDescriptions { + get { + return ((string[])(curObj["StatusDescriptions"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsTimeBeforeRemovalNull { + get { + if ((curObj["TimeBeforeRemoval"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.TimeSpan TimeBeforeRemoval { + get { + if ((curObj["TimeBeforeRemoval"] != null)) { + return ToTimeSpan(((string)(curObj["TimeBeforeRemoval"]))); + } + else { + return new System.TimeSpan(0, 0, 0, 0, 0); + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsTimeOfLastStateChangeNull { + get { + if ((curObj["TimeOfLastStateChange"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime TimeOfLastStateChange { + get { + if ((curObj["TimeOfLastStateChange"] != null)) { + return ToDateTime(((string)(curObj["TimeOfLastStateChange"]))); + } + else { + return System.DateTime.MinValue; + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsTimeSubmittedNull { + get { + if ((curObj["TimeSubmitted"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime TimeSubmitted { + get { + if ((curObj["TimeSubmitted"] != null)) { + return ToDateTime(((string)(curObj["TimeSubmitted"]))); + } + else { + return System.DateTime.MinValue; + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsUntilTimeNull { + get { + if ((curObj["UntilTime"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime UntilTime { + get { + if ((curObj["UntilTime"] != null)) { + return ToDateTime(((string)(curObj["UntilTime"]))); + } + else { + return System.DateTime.MinValue; + } + } + } + + private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { + if (((path != null) + && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); + } + } + + private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { + if (((theObj != null) + && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); + if ((parentClasses != null)) { + int count = 0; + for (count = 0; (count < parentClasses.Length); count = (count + 1)) { + if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { + return true; + } + } + } + } + return false; + } + + private bool ShouldSerializeCancellable() { + if ((this.IsCancellableNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeCommunicationStatus() { + if ((this.IsCommunicationStatusNull == false)) { + return true; + } + return false; + } + + // Converts a given time interval in DMTF format to System.TimeSpan object. + static System.TimeSpan ToTimeSpan(string dmtfTimespan) { + int days = 0; + int hours = 0; + int minutes = 0; + int seconds = 0; + long ticks = 0; + if ((dmtfTimespan == null)) { + throw new System.ArgumentOutOfRangeException(); + } + if ((dmtfTimespan.Length == 0)) { + throw new System.ArgumentOutOfRangeException(); + } + if ((dmtfTimespan.Length != 25)) { + throw new System.ArgumentOutOfRangeException(); + } + if ((dmtfTimespan.Substring(21, 4) != ":000")) { + throw new System.ArgumentOutOfRangeException(); + } + try { + string tempString = string.Empty; + tempString = dmtfTimespan.Substring(0, 8); + days = int.Parse(tempString); + tempString = dmtfTimespan.Substring(8, 2); + hours = int.Parse(tempString); + tempString = dmtfTimespan.Substring(10, 2); + minutes = int.Parse(tempString); + tempString = dmtfTimespan.Substring(12, 2); + seconds = int.Parse(tempString); + tempString = dmtfTimespan.Substring(15, 6); + ticks = (long.Parse(tempString) * ((long)((System.TimeSpan.TicksPerMillisecond / 1000)))); + } + catch (System.Exception e) { + throw new System.ArgumentOutOfRangeException(null, e.Message); + } + System.TimeSpan timespan = new System.TimeSpan(days, hours, minutes, seconds, 0); + System.TimeSpan tsTemp = System.TimeSpan.FromTicks(ticks); + timespan = timespan.Add(tsTemp); + return timespan; + } + + // Converts a given System.TimeSpan object to DMTF Time interval format. + static string ToDmtfTimeInterval(System.TimeSpan timespan) { + string dmtftimespan = ((int)(timespan.Days)).ToString().PadLeft(8, '0'); + System.TimeSpan maxTimeSpan = System.TimeSpan.MaxValue; + if ((timespan.Days > maxTimeSpan.Days)) { + throw new System.ArgumentOutOfRangeException(); + } + System.TimeSpan minTimeSpan = System.TimeSpan.MinValue; + if ((timespan.Days < minTimeSpan.Days)) { + throw new System.ArgumentOutOfRangeException(); + } + dmtftimespan = string.Concat(dmtftimespan, ((int)(timespan.Hours)).ToString().PadLeft(2, '0')); + dmtftimespan = string.Concat(dmtftimespan, ((int)(timespan.Minutes)).ToString().PadLeft(2, '0')); + dmtftimespan = string.Concat(dmtftimespan, ((int)(timespan.Seconds)).ToString().PadLeft(2, '0')); + dmtftimespan = string.Concat(dmtftimespan, "."); + System.TimeSpan tsTemp = new System.TimeSpan(timespan.Days, timespan.Hours, timespan.Minutes, timespan.Seconds, 0); + long microsec = ((long)((((timespan.Ticks - tsTemp.Ticks) + * 1000) + / System.TimeSpan.TicksPerMillisecond))); + string strMicroSec = ((long)(microsec)).ToString(); + if ((strMicroSec.Length > 6)) { + strMicroSec = strMicroSec.Substring(0, 6); + } + dmtftimespan = string.Concat(dmtftimespan, strMicroSec.PadLeft(6, '0')); + dmtftimespan = string.Concat(dmtftimespan, ":000"); + return dmtftimespan; + } + + private bool ShouldSerializeDeleteOnCompletion() { + if ((this.IsDeleteOnCompletionNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeDetailedStatus() { + if ((this.IsDetailedStatusNull == false)) { + return true; + } + return false; + } + + // Converts a given datetime in DMTF format to System.DateTime object. + static System.DateTime ToDateTime(string dmtfDate) { + System.DateTime initializer = System.DateTime.MinValue; + int year = initializer.Year; + int month = initializer.Month; + int day = initializer.Day; + int hour = initializer.Hour; + int minute = initializer.Minute; + int second = initializer.Second; + long ticks = 0; + string dmtf = dmtfDate; + System.DateTime datetime = System.DateTime.MinValue; + string tempString = string.Empty; + if ((dmtf == null)) { + throw new System.ArgumentOutOfRangeException(); + } + if ((dmtf.Length == 0)) { + throw new System.ArgumentOutOfRangeException(); + } + if ((dmtf.Length != 25)) { + throw new System.ArgumentOutOfRangeException(); + } + try { + tempString = dmtf.Substring(0, 4); + if (("****" != tempString)) { + year = int.Parse(tempString); + } + tempString = dmtf.Substring(4, 2); + if (("**" != tempString)) { + month = int.Parse(tempString); + } + tempString = dmtf.Substring(6, 2); + if (("**" != tempString)) { + day = int.Parse(tempString); + } + tempString = dmtf.Substring(8, 2); + if (("**" != tempString)) { + hour = int.Parse(tempString); + } + tempString = dmtf.Substring(10, 2); + if (("**" != tempString)) { + minute = int.Parse(tempString); + } + tempString = dmtf.Substring(12, 2); + if (("**" != tempString)) { + second = int.Parse(tempString); + } + tempString = dmtf.Substring(15, 6); + if (("******" != tempString)) { + ticks = (long.Parse(tempString) * ((long)((System.TimeSpan.TicksPerMillisecond / 1000)))); + } + if (((((((((year < 0) + || (month < 0)) + || (day < 0)) + || (hour < 0)) + || (minute < 0)) + || (minute < 0)) + || (second < 0)) + || (ticks < 0))) { + throw new System.ArgumentOutOfRangeException(); + } + } + catch (System.Exception e) { + throw new System.ArgumentOutOfRangeException(null, e.Message); + } + datetime = new System.DateTime(year, month, day, hour, minute, second, 0); + datetime = datetime.AddTicks(ticks); + System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(datetime); + int UTCOffset = 0; + int OffsetToBeAdjusted = 0; + long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); + tempString = dmtf.Substring(22, 3); + if ((tempString != "******")) { + tempString = dmtf.Substring(21, 4); + try { + UTCOffset = int.Parse(tempString); + } + catch (System.Exception e) { + throw new System.ArgumentOutOfRangeException(null, e.Message); + } + OffsetToBeAdjusted = ((int)((OffsetMins - UTCOffset))); + datetime = datetime.AddMinutes(((double)(OffsetToBeAdjusted))); + } + return datetime; + } + + // Converts a given System.DateTime object to DMTF datetime format. + static string ToDmtfDateTime(System.DateTime date) { + string utcString = string.Empty; + System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(date); + long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); + if ((System.Math.Abs(OffsetMins) > 999)) { + date = date.ToUniversalTime(); + utcString = "+000"; + } + else { + if ((tickOffset.Ticks >= 0)) { + utcString = string.Concat("+", ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))).ToString().PadLeft(3, '0')); + } + else { + string strTemp = ((long)(OffsetMins)).ToString(); + utcString = string.Concat("-", strTemp.Substring(1, (strTemp.Length - 1)).PadLeft(3, '0')); + } + } + string dmtfDateTime = ((int)(date.Year)).ToString().PadLeft(4, '0'); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Month)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Day)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Hour)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Minute)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Second)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, "."); + System.DateTime dtTemp = new System.DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, 0); + long microsec = ((long)((((date.Ticks - dtTemp.Ticks) + * 1000) + / System.TimeSpan.TicksPerMillisecond))); + string strMicrosec = ((long)(microsec)).ToString(); + if ((strMicrosec.Length > 6)) { + strMicrosec = strMicrosec.Substring(0, 6); + } + dmtfDateTime = string.Concat(dmtfDateTime, strMicrosec.PadLeft(6, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, utcString); + return dmtfDateTime; + } + + private bool ShouldSerializeElapsedTime() { + if ((this.IsElapsedTimeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeErrorCode() { + if ((this.IsErrorCodeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeHealthState() { + if ((this.IsHealthStateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeInstallDate() { + if ((this.IsInstallDateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeJobRunTimes() { + if ((this.IsJobRunTimesNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeJobState() { + if ((this.IsJobStateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeJobType() { + if ((this.IsJobTypeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeLocalOrUtcTime() { + if ((this.IsLocalOrUtcTimeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeOperatingStatus() { + if ((this.IsOperatingStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePercentComplete() { + if ((this.IsPercentCompleteNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePrimaryStatus() { + if ((this.IsPrimaryStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePriority() { + if ((this.IsPriorityNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeRecoveryAction() { + if ((this.IsRecoveryActionNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeRunDay() { + if ((this.IsRunDayNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeRunDayOfWeek() { + if ((this.IsRunDayOfWeekNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeRunMonth() { + if ((this.IsRunMonthNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeRunStartInterval() { + if ((this.IsRunStartIntervalNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeScheduledStartTime() { + if ((this.IsScheduledStartTimeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeStartTime() { + if ((this.IsStartTimeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeTimeBeforeRemoval() { + if ((this.IsTimeBeforeRemovalNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeTimeOfLastStateChange() { + if ((this.IsTimeOfLastStateChangeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeTimeSubmitted() { + if ((this.IsTimeSubmittedNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeUntilTime() { + if ((this.IsUntilTimeNull == false)) { + return true; + } + return false; + } + + [Browsable(true)] + public void CommitObject() { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(); + } + } + + [Browsable(true)] + public void CommitObject(System.Management.PutOptions putOptions) { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(putOptions); + } + } + + private void Initialize() { + AutoCommitProp = true; + isEmbedded = false; + } + + private static string ConstructPath(string keyInstanceID) { + string strPath = "ROOT\\virtualization\\v2:Msvm_ConcreteJob"; + strPath = string.Concat(strPath, string.Concat(".InstanceID=", string.Concat("\"", string.Concat(keyInstanceID, "\"")))); + return strPath; + } + + private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + Initialize(); + if ((path != null)) { + if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + } + PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + + // Different overloads of GetInstances() help in enumerating instances of the WMI class. + public static ConcreteJobCollection GetInstances() { + return GetInstances(null, null, null); + } + + public static ConcreteJobCollection GetInstances(string condition) { + return GetInstances(null, condition, null); + } + + public static ConcreteJobCollection GetInstances(string[] selectedProperties) { + return GetInstances(null, null, selectedProperties); + } + + public static ConcreteJobCollection GetInstances(string condition, string[] selectedProperties) { + return GetInstances(null, condition, selectedProperties); + } + + public static ConcreteJobCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); + pathObj.ClassName = "Msvm_ConcreteJob"; + pathObj.NamespacePath = "root\\virtualization\\v2"; + System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); + if ((enumOptions == null)) { + enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + } + return new ConcreteJobCollection(clsObject.GetInstances(enumOptions)); + } + + public static ConcreteJobCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { + return GetInstances(mgmtScope, condition, null); + } + + public static ConcreteJobCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { + return GetInstances(mgmtScope, null, selectedProperties); + } + + public static ConcreteJobCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_ConcreteJob", condition, selectedProperties)); + System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + ObjectSearcher.Options = enumOptions; + return new ConcreteJobCollection(ObjectSearcher.Get()); + } + + [Browsable(true)] + public static ConcreteJob CreateInstance() { + System.Management.ManagementScope mgmtScope = null; + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = CreatedWmiNamespace; + } + else { + mgmtScope = statMgmtScope; + } + System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); + System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); + return new ConcreteJob(tmpMgmtClass.CreateInstance()); + } + + [Browsable(true)] + public void Delete() { + PrivateLateBoundObject.Delete(); + } + + public uint GetError(out string Error) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("GetError", inParams, null); + Error = System.Convert.ToString(outParams.Properties["Error"].Value); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Error = null; + return System.Convert.ToUInt32(0); + } + } + + public uint GetErrorEx(out string[] Errors) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("GetErrorEx", inParams, null); + Errors = ((string[])(outParams.Properties["Errors"].Value)); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Errors = null; + return System.Convert.ToUInt32(0); + } + } + + public uint KillJob(bool DeleteOnKill) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("KillJob"); + inParams["DeleteOnKill"] = ((bool)(DeleteOnKill)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("KillJob", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + public uint RequestStateChange(ushort RequestedState, System.TimeSpan TimeoutPeriod) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("RequestStateChange"); + inParams["RequestedState"] = ((ushort)(RequestedState)); + inParams["TimeoutPeriod"] = ToDmtfTimeInterval(((System.TimeSpan)(TimeoutPeriod))); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RequestStateChange", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + // Enumerator implementation for enumerating instances of the class. + public class ConcreteJobCollection : object, ICollection { + + private ManagementObjectCollection privColObj; + + public ConcreteJobCollection(ManagementObjectCollection objCollection) { + privColObj = objCollection; + } + + public virtual int Count { + get { + return privColObj.Count; + } + } + + public virtual bool IsSynchronized { + get { + return privColObj.IsSynchronized; + } + } + + public virtual object SyncRoot { + get { + return this; + } + } + + public virtual void CopyTo(System.Array array, int index) { + privColObj.CopyTo(array, index); + int nCtr; + for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { + array.SetValue(new ConcreteJob(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); + } + } + + public virtual System.Collections.IEnumerator GetEnumerator() { + return new ConcreteJobEnumerator(privColObj.GetEnumerator()); + } + + public class ConcreteJobEnumerator : object, System.Collections.IEnumerator { + + private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; + + public ConcreteJobEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { + privObjEnum = objEnum; + } + + public virtual object Current { + get { + return new ConcreteJob(((System.Management.ManagementObject)(privObjEnum.Current))); + } + } + + public virtual bool MoveNext() { + return privObjEnum.MoveNext(); + } + + public virtual void Reset() { + privObjEnum.Reset(); + } + } + } + + // TypeConverter to handle null values for ValueType properties + public class WMIValueTypeConverter : TypeConverter { + + private TypeConverter baseConverter; + + private System.Type baseType; + + public WMIValueTypeConverter(System.Type inBaseType) { + baseConverter = TypeDescriptor.GetConverter(inBaseType); + baseType = inBaseType; + } + + public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { + return baseConverter.CanConvertFrom(context, srcType); + } + + public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { + return baseConverter.CanConvertTo(context, destinationType); + } + + public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { + return baseConverter.ConvertFrom(context, culture, value); + } + + public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { + return baseConverter.CreateInstance(context, dictionary); + } + + public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetCreateInstanceSupported(context); + } + + public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { + return baseConverter.GetProperties(context, value, attributeVar); + } + + public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetPropertiesSupported(context); + } + + public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValues(context); + } + + public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesExclusive(context); + } + + public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesSupported(context); + } + + public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { + if ((baseType.BaseType == typeof(System.Enum))) { + if ((value.GetType() == destinationType)) { + return value; + } + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return "NULL_ENUM_VALUE" ; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((baseType == typeof(bool)) + && (baseType.BaseType == typeof(System.ValueType)))) { + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((context != null) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + } + + // Embedded class to represent WMI system Properties. + [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] + public class ManagementSystemProperties { + + private System.Management.ManagementBaseObject PrivateLateBoundObject; + + public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { + PrivateLateBoundObject = ManagedObject; + } + + [Browsable(true)] + public int GENUS { + get { + return ((int)(PrivateLateBoundObject["__GENUS"])); + } + } + + [Browsable(true)] + public string CLASS { + get { + return ((string)(PrivateLateBoundObject["__CLASS"])); + } + } + + [Browsable(true)] + public string SUPERCLASS { + get { + return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); + } + } + + [Browsable(true)] + public string DYNASTY { + get { + return ((string)(PrivateLateBoundObject["__DYNASTY"])); + } + } + + [Browsable(true)] + public string RELPATH { + get { + return ((string)(PrivateLateBoundObject["__RELPATH"])); + } + } + + [Browsable(true)] + public int PROPERTY_COUNT { + get { + return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); + } + } + + [Browsable(true)] + public string[] DERIVATION { + get { + return ((string[])(PrivateLateBoundObject["__DERIVATION"])); + } + } + + [Browsable(true)] + public string SERVER { + get { + return ((string)(PrivateLateBoundObject["__SERVER"])); + } + } + + [Browsable(true)] + public string NAMESPACE { + get { + return ((string)(PrivateLateBoundObject["__NAMESPACE"])); + } + } + + [Browsable(true)] + public string PATH { + get { + return ((string)(PrivateLateBoundObject["__PATH"])); + } + } + } + } +} diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_EthernetPortAllocationSettingData.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_EthernetPortAllocationSettingData.cs index 6400ec64516..3f28309e23c 100644 --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_EthernetPortAllocationSettingData.cs +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_EthernetPortAllocationSettingData.cs @@ -1,1164 +1,1164 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2 { - using System; - using System.ComponentModel; - using System.Management; - using System.Collections; - using System.Globalization; - using System.ComponentModel.Design.Serialization; - using System.Reflection; - - - // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. - // Functions IsNull() are used to check if a property is NULL. - // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. - // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. - // An Early Bound class generated for the WMI class.Msvm_EthernetPortAllocationSettingData - public class EthernetPortAllocationSettingData : System.ComponentModel.Component { - - // Private property to hold the WMI namespace in which the class resides. - private static string CreatedWmiNamespace = "ROOT\\virtualization\\v2"; - - // Private property to hold the name of WMI class which created this class. - public static string CreatedClassName = "Msvm_EthernetPortAllocationSettingData"; - - // Private member variable to hold the ManagementScope which is used by the various methods. - private static System.Management.ManagementScope statMgmtScope = null; - - private ManagementSystemProperties PrivateSystemProperties; - - // Underlying lateBound WMI object. - private System.Management.ManagementObject PrivateLateBoundObject; - - // Member variable to store the 'automatic commit' behavior for the class. - private bool AutoCommitProp; - - // Private variable to hold the embedded property representing the instance. - private System.Management.ManagementBaseObject embeddedObj; - - // The current WMI object used - private System.Management.ManagementBaseObject curObj; - - // Flag to indicate if the instance is an embedded object. - private bool isEmbedded; - - // Below are different overloads of constructors to initialize an instance of the class with a WMI object. - public EthernetPortAllocationSettingData() { - this.InitializeObject(null, null, null); - } - - public EthernetPortAllocationSettingData(string keyInstanceID) { - this.InitializeObject(null, new System.Management.ManagementPath(EthernetPortAllocationSettingData.ConstructPath(keyInstanceID)), null); - } - - public EthernetPortAllocationSettingData(System.Management.ManagementScope mgmtScope, string keyInstanceID) { - this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(EthernetPortAllocationSettingData.ConstructPath(keyInstanceID)), null); - } - - public EthernetPortAllocationSettingData(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(null, path, getOptions); - } - - public EthernetPortAllocationSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { - this.InitializeObject(mgmtScope, path, null); - } - - public EthernetPortAllocationSettingData(System.Management.ManagementPath path) { - this.InitializeObject(null, path, null); - } - - public EthernetPortAllocationSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(mgmtScope, path, getOptions); - } - - public EthernetPortAllocationSettingData(System.Management.ManagementObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - PrivateLateBoundObject = theObject; - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - public EthernetPortAllocationSettingData(System.Management.ManagementBaseObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - embeddedObj = theObject; - PrivateSystemProperties = new ManagementSystemProperties(theObject); - curObj = embeddedObj; - isEmbedded = true; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - // Property returns the namespace of the WMI class. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OriginatingNamespace { - get { - return "ROOT\\virtualization\\v2"; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ManagementClassName { - get { - string strRet = CreatedClassName; - if ((curObj != null)) { - if ((curObj.ClassPath != null)) { - strRet = ((string)(curObj["__CLASS"])); - if (((strRet == null) - || (strRet == string.Empty))) { - strRet = CreatedClassName; - } - } - } - return strRet; - } - } - - // Property pointing to an embedded object to get System properties of the WMI object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ManagementSystemProperties SystemProperties { - get { - return PrivateSystemProperties; - } - } - - // Property returning the underlying lateBound object. - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementBaseObject LateBoundObject { - get { - return curObj; - } - } - - // ManagementScope of the object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementScope Scope { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Scope; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Scope = value; - } - } - } - - // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool AutoCommit { - get { - return AutoCommitProp; - } - set { - AutoCommitProp = value; - } - } - - // The ManagementPath of the underlying WMI object. - [Browsable(true)] - public System.Management.ManagementPath Path { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Path; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - if ((CheckIfProperClass(null, value, null) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - PrivateLateBoundObject.Path = value; - } - } - } - - // Public static scope property which is used by the various methods. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public static System.Management.ManagementScope StaticScope { - get { - return statMgmtScope; - } - set { - statMgmtScope = value; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Address { - get { - return ((string)(curObj["Address"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string AddressOnParent { - get { - return ((string)(curObj["AddressOnParent"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string AllocationUnits { - get { - return ((string)(curObj["AllocationUnits"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsAutomaticAllocationNull { - get { - if ((curObj["AutomaticAllocation"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool AutomaticAllocation { - get { - if ((curObj["AutomaticAllocation"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["AutomaticAllocation"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsAutomaticDeallocationNull { - get { - if ((curObj["AutomaticDeallocation"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool AutomaticDeallocation { - get { - if ((curObj["AutomaticDeallocation"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["AutomaticDeallocation"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Caption { - get { - return ((string)(curObj["Caption"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] Connection { - get { - return ((string[])(curObj["Connection"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsConsumerVisibilityNull { - get { - if ((curObj["ConsumerVisibility"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort ConsumerVisibility { - get { - if ((curObj["ConsumerVisibility"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["ConsumerVisibility"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Description { - get { - return ((string)(curObj["Description"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsDesiredVLANEndpointModeNull { - get { - if ((curObj["DesiredVLANEndpointMode"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort DesiredVLANEndpointMode { - get { - if ((curObj["DesiredVLANEndpointMode"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["DesiredVLANEndpointMode"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ElementName { - get { - return ((string)(curObj["ElementName"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsEnabledStateNull { - get { - if ((curObj["EnabledState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description(@"EnabledState is an integer enumeration that indicates whether the allocation request is enabled or disabled. When an allocation request is marked as Disabled (3), then the allocation is not processed. The EnabledState for an active configuration is always marked as Enabled (2).")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public EnabledStateValues EnabledState { - get { - if ((curObj["EnabledState"] == null)) { - return ((EnabledStateValues)(System.Convert.ToInt32(0))); - } - return ((EnabledStateValues)(System.Convert.ToInt32(curObj["EnabledState"]))); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] HostResource { - get { - return ((string[])(curObj["HostResource"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string InstanceID { - get { - return ((string)(curObj["InstanceID"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsLimitNull { - get { - if ((curObj["Limit"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong Limit { - get { - if ((curObj["Limit"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["Limit"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsMappingBehaviorNull { - get { - if ((curObj["MappingBehavior"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort MappingBehavior { - get { - if ((curObj["MappingBehavior"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["MappingBehavior"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OtherEndpointMode { - get { - return ((string)(curObj["OtherEndpointMode"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OtherResourceType { - get { - return ((string)(curObj["OtherResourceType"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Parent { - get { - return ((string)(curObj["Parent"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string PoolID { - get { - return ((string)(curObj["PoolID"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The list of friendly names corresponding to each entry in the RequiredFeatures.")] - public string[] RequiredFeatureHints { - get { - return ((string[])(curObj["RequiredFeatureHints"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The list of feature identifers representing all the features that are required fo" + - "r a port.")] - public string[] RequiredFeatures { - get { - return ((string[])(curObj["RequiredFeatures"])); - } - set { - curObj["RequiredFeatures"] = value; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsReservationNull { - get { - if ((curObj["Reservation"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong Reservation { - get { - if ((curObj["Reservation"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["Reservation"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ResourceSubType { - get { - return ((string)(curObj["ResourceSubType"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsResourceTypeNull { - get { - if ((curObj["ResourceType"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort ResourceType { - get { - if ((curObj["ResourceType"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["ResourceType"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("This property specifies the network resource pool from which a connection will be" + - " allocated to test replica system when it is created.")] - public string TestReplicaPoolID { - get { - return ((string)(curObj["TestReplicaPoolID"])); - } - set { - curObj["TestReplicaPoolID"] = value; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("This property specifies the friendly name of the virtual network switch to which " + - "a connection will be allocated for the test replica system when it is created.")] - public string TestReplicaSwitchName { - get { - return ((string)(curObj["TestReplicaSwitchName"])); - } - set { - curObj["TestReplicaSwitchName"] = value; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsVirtualQuantityNull { - get { - if ((curObj["VirtualQuantity"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong VirtualQuantity { - get { - if ((curObj["VirtualQuantity"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["VirtualQuantity"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string VirtualQuantityUnits { - get { - return ((string)(curObj["VirtualQuantityUnits"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsWeightNull { - get { - if ((curObj["Weight"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public uint Weight { - get { - if ((curObj["Weight"] == null)) { - return System.Convert.ToUInt32(0); - } - return ((uint)(curObj["Weight"])); - } - } - - private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { - if (((path != null) - && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); - } - } - - private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { - if (((theObj != null) - && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); - if ((parentClasses != null)) { - int count = 0; - for (count = 0; (count < parentClasses.Length); count = (count + 1)) { - if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { - return true; - } - } - } - } - return false; - } - - private bool ShouldSerializeAutomaticAllocation() { - if ((this.IsAutomaticAllocationNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeAutomaticDeallocation() { - if ((this.IsAutomaticDeallocationNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeConsumerVisibility() { - if ((this.IsConsumerVisibilityNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeDesiredVLANEndpointMode() { - if ((this.IsDesiredVLANEndpointModeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeEnabledState() { - if ((this.IsEnabledStateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeLimit() { - if ((this.IsLimitNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeMappingBehavior() { - if ((this.IsMappingBehaviorNull == false)) { - return true; - } - return false; - } - - private void ResetRequiredFeatures() { - curObj["RequiredFeatures"] = null; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - - private bool ShouldSerializeReservation() { - if ((this.IsReservationNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeResourceType() { - if ((this.IsResourceTypeNull == false)) { - return true; - } - return false; - } - - private void ResetTestReplicaPoolID() { - curObj["TestReplicaPoolID"] = null; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - - private void ResetTestReplicaSwitchName() { - curObj["TestReplicaSwitchName"] = null; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - - private bool ShouldSerializeVirtualQuantity() { - if ((this.IsVirtualQuantityNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeWeight() { - if ((this.IsWeightNull == false)) { - return true; - } - return false; - } - - [Browsable(true)] - public void CommitObject() { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(); - } - } - - [Browsable(true)] - public void CommitObject(System.Management.PutOptions putOptions) { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(putOptions); - } - } - - private void Initialize() { - AutoCommitProp = true; - isEmbedded = false; - } - - private static string ConstructPath(string keyInstanceID) { - string strPath = "ROOT\\virtualization\\v2:Msvm_EthernetPortAllocationSettingData"; - strPath = string.Concat(strPath, string.Concat(".InstanceID=", string.Concat("\"", string.Concat(keyInstanceID, "\"")))); - return strPath; - } - - private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - Initialize(); - if ((path != null)) { - if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - } - PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - - // Different overloads of GetInstances() help in enumerating instances of the WMI class. - public static EthernetPortAllocationSettingDataCollection GetInstances() { - return GetInstances(null, null, null); - } - - public static EthernetPortAllocationSettingDataCollection GetInstances(string condition) { - return GetInstances(null, condition, null); - } - - public static EthernetPortAllocationSettingDataCollection GetInstances(string[] selectedProperties) { - return GetInstances(null, null, selectedProperties); - } - - public static EthernetPortAllocationSettingDataCollection GetInstances(string condition, string[] selectedProperties) { - return GetInstances(null, condition, selectedProperties); - } - - public static EthernetPortAllocationSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); - pathObj.ClassName = "Msvm_EthernetPortAllocationSettingData"; - pathObj.NamespacePath = "root\\virtualization\\v2"; - System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); - if ((enumOptions == null)) { - enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - } - return new EthernetPortAllocationSettingDataCollection(clsObject.GetInstances(enumOptions)); - } - - public static EthernetPortAllocationSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { - return GetInstances(mgmtScope, condition, null); - } - - public static EthernetPortAllocationSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { - return GetInstances(mgmtScope, null, selectedProperties); - } - - public static EthernetPortAllocationSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_EthernetPortAllocationSettingData", condition, selectedProperties)); - System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - ObjectSearcher.Options = enumOptions; - return new EthernetPortAllocationSettingDataCollection(ObjectSearcher.Get()); - } - - [Browsable(true)] - public static EthernetPortAllocationSettingData CreateInstance() { - System.Management.ManagementScope mgmtScope = null; - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = CreatedWmiNamespace; - } - else { - mgmtScope = statMgmtScope; - } - System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); - System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); - return new EthernetPortAllocationSettingData(tmpMgmtClass.CreateInstance()); - } - - [Browsable(true)] - public void Delete() { - PrivateLateBoundObject.Delete(); - } - - public enum EnabledStateValues { - - Enabled = 2, - - Disabled = 3, - - NULL_ENUM_VALUE = 0, - } - - // Enumerator implementation for enumerating instances of the class. - public class EthernetPortAllocationSettingDataCollection : object, ICollection { - - private ManagementObjectCollection privColObj; - - public EthernetPortAllocationSettingDataCollection(ManagementObjectCollection objCollection) { - privColObj = objCollection; - } - - public virtual int Count { - get { - return privColObj.Count; - } - } - - public virtual bool IsSynchronized { - get { - return privColObj.IsSynchronized; - } - } - - public virtual object SyncRoot { - get { - return this; - } - } - - public virtual void CopyTo(System.Array array, int index) { - privColObj.CopyTo(array, index); - int nCtr; - for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { - array.SetValue(new EthernetPortAllocationSettingData(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); - } - } - - public virtual System.Collections.IEnumerator GetEnumerator() { - return new EthernetPortAllocationSettingDataEnumerator(privColObj.GetEnumerator()); - } - - public class EthernetPortAllocationSettingDataEnumerator : object, System.Collections.IEnumerator { - - private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; - - public EthernetPortAllocationSettingDataEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { - privObjEnum = objEnum; - } - - public virtual object Current { - get { - return new EthernetPortAllocationSettingData(((System.Management.ManagementObject)(privObjEnum.Current))); - } - } - - public virtual bool MoveNext() { - return privObjEnum.MoveNext(); - } - - public virtual void Reset() { - privObjEnum.Reset(); - } - } - } - - // TypeConverter to handle null values for ValueType properties - public class WMIValueTypeConverter : TypeConverter { - - private TypeConverter baseConverter; - - private System.Type baseType; - - public WMIValueTypeConverter(System.Type inBaseType) { - baseConverter = TypeDescriptor.GetConverter(inBaseType); - baseType = inBaseType; - } - - public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { - return baseConverter.CanConvertFrom(context, srcType); - } - - public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { - return baseConverter.CanConvertTo(context, destinationType); - } - - public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { - return baseConverter.ConvertFrom(context, culture, value); - } - - public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { - return baseConverter.CreateInstance(context, dictionary); - } - - public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetCreateInstanceSupported(context); - } - - public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { - return baseConverter.GetProperties(context, value, attributeVar); - } - - public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetPropertiesSupported(context); - } - - public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValues(context); - } - - public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesExclusive(context); - } - - public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesSupported(context); - } - - public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { - if ((baseType.BaseType == typeof(System.Enum))) { - if ((value.GetType() == destinationType)) { - return value; - } - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return "NULL_ENUM_VALUE" ; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((baseType == typeof(bool)) - && (baseType.BaseType == typeof(System.ValueType)))) { - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((context != null) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - } - - // Embedded class to represent WMI system Properties. - [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] - public class ManagementSystemProperties { - - private System.Management.ManagementBaseObject PrivateLateBoundObject; - - public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { - PrivateLateBoundObject = ManagedObject; - } - - [Browsable(true)] - public int GENUS { - get { - return ((int)(PrivateLateBoundObject["__GENUS"])); - } - } - - [Browsable(true)] - public string CLASS { - get { - return ((string)(PrivateLateBoundObject["__CLASS"])); - } - } - - [Browsable(true)] - public string SUPERCLASS { - get { - return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); - } - } - - [Browsable(true)] - public string DYNASTY { - get { - return ((string)(PrivateLateBoundObject["__DYNASTY"])); - } - } - - [Browsable(true)] - public string RELPATH { - get { - return ((string)(PrivateLateBoundObject["__RELPATH"])); - } - } - - [Browsable(true)] - public int PROPERTY_COUNT { - get { - return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); - } - } - - [Browsable(true)] - public string[] DERIVATION { - get { - return ((string[])(PrivateLateBoundObject["__DERIVATION"])); - } - } - - [Browsable(true)] - public string SERVER { - get { - return ((string)(PrivateLateBoundObject["__SERVER"])); - } - } - - [Browsable(true)] - public string NAMESPACE { - get { - return ((string)(PrivateLateBoundObject["__NAMESPACE"])); - } - } - - [Browsable(true)] - public string PATH { - get { - return ((string)(PrivateLateBoundObject["__PATH"])); - } - } - } - } -} +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2 { + using System; + using System.ComponentModel; + using System.Management; + using System.Collections; + using System.Globalization; + using System.ComponentModel.Design.Serialization; + using System.Reflection; + + + // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. + // Functions IsNull() are used to check if a property is NULL. + // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. + // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. + // An Early Bound class generated for the WMI class.Msvm_EthernetPortAllocationSettingData + public class EthernetPortAllocationSettingData : System.ComponentModel.Component { + + // Private property to hold the WMI namespace in which the class resides. + private static string CreatedWmiNamespace = "ROOT\\virtualization\\v2"; + + // Private property to hold the name of WMI class which created this class. + public static string CreatedClassName = "Msvm_EthernetPortAllocationSettingData"; + + // Private member variable to hold the ManagementScope which is used by the various methods. + private static System.Management.ManagementScope statMgmtScope = null; + + private ManagementSystemProperties PrivateSystemProperties; + + // Underlying lateBound WMI object. + private System.Management.ManagementObject PrivateLateBoundObject; + + // Member variable to store the 'automatic commit' behavior for the class. + private bool AutoCommitProp; + + // Private variable to hold the embedded property representing the instance. + private System.Management.ManagementBaseObject embeddedObj; + + // The current WMI object used + private System.Management.ManagementBaseObject curObj; + + // Flag to indicate if the instance is an embedded object. + private bool isEmbedded; + + // Below are different overloads of constructors to initialize an instance of the class with a WMI object. + public EthernetPortAllocationSettingData() { + this.InitializeObject(null, null, null); + } + + public EthernetPortAllocationSettingData(string keyInstanceID) { + this.InitializeObject(null, new System.Management.ManagementPath(EthernetPortAllocationSettingData.ConstructPath(keyInstanceID)), null); + } + + public EthernetPortAllocationSettingData(System.Management.ManagementScope mgmtScope, string keyInstanceID) { + this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(EthernetPortAllocationSettingData.ConstructPath(keyInstanceID)), null); + } + + public EthernetPortAllocationSettingData(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(null, path, getOptions); + } + + public EthernetPortAllocationSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { + this.InitializeObject(mgmtScope, path, null); + } + + public EthernetPortAllocationSettingData(System.Management.ManagementPath path) { + this.InitializeObject(null, path, null); + } + + public EthernetPortAllocationSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(mgmtScope, path, getOptions); + } + + public EthernetPortAllocationSettingData(System.Management.ManagementObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + PrivateLateBoundObject = theObject; + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + public EthernetPortAllocationSettingData(System.Management.ManagementBaseObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + embeddedObj = theObject; + PrivateSystemProperties = new ManagementSystemProperties(theObject); + curObj = embeddedObj; + isEmbedded = true; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + // Property returns the namespace of the WMI class. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OriginatingNamespace { + get { + return "ROOT\\virtualization\\v2"; + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ManagementClassName { + get { + string strRet = CreatedClassName; + if ((curObj != null)) { + if ((curObj.ClassPath != null)) { + strRet = ((string)(curObj["__CLASS"])); + if (((strRet == null) + || (strRet == string.Empty))) { + strRet = CreatedClassName; + } + } + } + return strRet; + } + } + + // Property pointing to an embedded object to get System properties of the WMI object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ManagementSystemProperties SystemProperties { + get { + return PrivateSystemProperties; + } + } + + // Property returning the underlying lateBound object. + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementBaseObject LateBoundObject { + get { + return curObj; + } + } + + // ManagementScope of the object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementScope Scope { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Scope; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Scope = value; + } + } + } + + // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool AutoCommit { + get { + return AutoCommitProp; + } + set { + AutoCommitProp = value; + } + } + + // The ManagementPath of the underlying WMI object. + [Browsable(true)] + public System.Management.ManagementPath Path { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Path; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + if ((CheckIfProperClass(null, value, null) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + PrivateLateBoundObject.Path = value; + } + } + } + + // Public static scope property which is used by the various methods. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public static System.Management.ManagementScope StaticScope { + get { + return statMgmtScope; + } + set { + statMgmtScope = value; + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Address { + get { + return ((string)(curObj["Address"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string AddressOnParent { + get { + return ((string)(curObj["AddressOnParent"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string AllocationUnits { + get { + return ((string)(curObj["AllocationUnits"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAutomaticAllocationNull { + get { + if ((curObj["AutomaticAllocation"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool AutomaticAllocation { + get { + if ((curObj["AutomaticAllocation"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["AutomaticAllocation"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAutomaticDeallocationNull { + get { + if ((curObj["AutomaticDeallocation"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool AutomaticDeallocation { + get { + if ((curObj["AutomaticDeallocation"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["AutomaticDeallocation"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Caption { + get { + return ((string)(curObj["Caption"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] Connection { + get { + return ((string[])(curObj["Connection"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsConsumerVisibilityNull { + get { + if ((curObj["ConsumerVisibility"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort ConsumerVisibility { + get { + if ((curObj["ConsumerVisibility"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["ConsumerVisibility"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Description { + get { + return ((string)(curObj["Description"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsDesiredVLANEndpointModeNull { + get { + if ((curObj["DesiredVLANEndpointMode"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort DesiredVLANEndpointMode { + get { + if ((curObj["DesiredVLANEndpointMode"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["DesiredVLANEndpointMode"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ElementName { + get { + return ((string)(curObj["ElementName"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsEnabledStateNull { + get { + if ((curObj["EnabledState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"EnabledState is an integer enumeration that indicates whether the allocation request is enabled or disabled. When an allocation request is marked as Disabled (3), then the allocation is not processed. The EnabledState for an active configuration is always marked as Enabled (2).")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public EnabledStateValues EnabledState { + get { + if ((curObj["EnabledState"] == null)) { + return ((EnabledStateValues)(System.Convert.ToInt32(0))); + } + return ((EnabledStateValues)(System.Convert.ToInt32(curObj["EnabledState"]))); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] HostResource { + get { + return ((string[])(curObj["HostResource"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string InstanceID { + get { + return ((string)(curObj["InstanceID"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsLimitNull { + get { + if ((curObj["Limit"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong Limit { + get { + if ((curObj["Limit"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["Limit"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsMappingBehaviorNull { + get { + if ((curObj["MappingBehavior"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort MappingBehavior { + get { + if ((curObj["MappingBehavior"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["MappingBehavior"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherEndpointMode { + get { + return ((string)(curObj["OtherEndpointMode"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherResourceType { + get { + return ((string)(curObj["OtherResourceType"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Parent { + get { + return ((string)(curObj["Parent"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string PoolID { + get { + return ((string)(curObj["PoolID"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The list of friendly names corresponding to each entry in the RequiredFeatures.")] + public string[] RequiredFeatureHints { + get { + return ((string[])(curObj["RequiredFeatureHints"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The list of feature identifers representing all the features that are required fo" + + "r a port.")] + public string[] RequiredFeatures { + get { + return ((string[])(curObj["RequiredFeatures"])); + } + set { + curObj["RequiredFeatures"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsReservationNull { + get { + if ((curObj["Reservation"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong Reservation { + get { + if ((curObj["Reservation"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["Reservation"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ResourceSubType { + get { + return ((string)(curObj["ResourceSubType"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsResourceTypeNull { + get { + if ((curObj["ResourceType"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort ResourceType { + get { + if ((curObj["ResourceType"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["ResourceType"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("This property specifies the network resource pool from which a connection will be" + + " allocated to test replica system when it is created.")] + public string TestReplicaPoolID { + get { + return ((string)(curObj["TestReplicaPoolID"])); + } + set { + curObj["TestReplicaPoolID"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("This property specifies the friendly name of the virtual network switch to which " + + "a connection will be allocated for the test replica system when it is created.")] + public string TestReplicaSwitchName { + get { + return ((string)(curObj["TestReplicaSwitchName"])); + } + set { + curObj["TestReplicaSwitchName"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsVirtualQuantityNull { + get { + if ((curObj["VirtualQuantity"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong VirtualQuantity { + get { + if ((curObj["VirtualQuantity"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["VirtualQuantity"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string VirtualQuantityUnits { + get { + return ((string)(curObj["VirtualQuantityUnits"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsWeightNull { + get { + if ((curObj["Weight"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint Weight { + get { + if ((curObj["Weight"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["Weight"])); + } + } + + private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { + if (((path != null) + && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); + } + } + + private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { + if (((theObj != null) + && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); + if ((parentClasses != null)) { + int count = 0; + for (count = 0; (count < parentClasses.Length); count = (count + 1)) { + if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { + return true; + } + } + } + } + return false; + } + + private bool ShouldSerializeAutomaticAllocation() { + if ((this.IsAutomaticAllocationNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeAutomaticDeallocation() { + if ((this.IsAutomaticDeallocationNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeConsumerVisibility() { + if ((this.IsConsumerVisibilityNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeDesiredVLANEndpointMode() { + if ((this.IsDesiredVLANEndpointModeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeEnabledState() { + if ((this.IsEnabledStateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeLimit() { + if ((this.IsLimitNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeMappingBehavior() { + if ((this.IsMappingBehaviorNull == false)) { + return true; + } + return false; + } + + private void ResetRequiredFeatures() { + curObj["RequiredFeatures"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private bool ShouldSerializeReservation() { + if ((this.IsReservationNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeResourceType() { + if ((this.IsResourceTypeNull == false)) { + return true; + } + return false; + } + + private void ResetTestReplicaPoolID() { + curObj["TestReplicaPoolID"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private void ResetTestReplicaSwitchName() { + curObj["TestReplicaSwitchName"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private bool ShouldSerializeVirtualQuantity() { + if ((this.IsVirtualQuantityNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeWeight() { + if ((this.IsWeightNull == false)) { + return true; + } + return false; + } + + [Browsable(true)] + public void CommitObject() { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(); + } + } + + [Browsable(true)] + public void CommitObject(System.Management.PutOptions putOptions) { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(putOptions); + } + } + + private void Initialize() { + AutoCommitProp = true; + isEmbedded = false; + } + + private static string ConstructPath(string keyInstanceID) { + string strPath = "ROOT\\virtualization\\v2:Msvm_EthernetPortAllocationSettingData"; + strPath = string.Concat(strPath, string.Concat(".InstanceID=", string.Concat("\"", string.Concat(keyInstanceID, "\"")))); + return strPath; + } + + private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + Initialize(); + if ((path != null)) { + if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + } + PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + + // Different overloads of GetInstances() help in enumerating instances of the WMI class. + public static EthernetPortAllocationSettingDataCollection GetInstances() { + return GetInstances(null, null, null); + } + + public static EthernetPortAllocationSettingDataCollection GetInstances(string condition) { + return GetInstances(null, condition, null); + } + + public static EthernetPortAllocationSettingDataCollection GetInstances(string[] selectedProperties) { + return GetInstances(null, null, selectedProperties); + } + + public static EthernetPortAllocationSettingDataCollection GetInstances(string condition, string[] selectedProperties) { + return GetInstances(null, condition, selectedProperties); + } + + public static EthernetPortAllocationSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); + pathObj.ClassName = "Msvm_EthernetPortAllocationSettingData"; + pathObj.NamespacePath = "root\\virtualization\\v2"; + System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); + if ((enumOptions == null)) { + enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + } + return new EthernetPortAllocationSettingDataCollection(clsObject.GetInstances(enumOptions)); + } + + public static EthernetPortAllocationSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { + return GetInstances(mgmtScope, condition, null); + } + + public static EthernetPortAllocationSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { + return GetInstances(mgmtScope, null, selectedProperties); + } + + public static EthernetPortAllocationSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_EthernetPortAllocationSettingData", condition, selectedProperties)); + System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + ObjectSearcher.Options = enumOptions; + return new EthernetPortAllocationSettingDataCollection(ObjectSearcher.Get()); + } + + [Browsable(true)] + public static EthernetPortAllocationSettingData CreateInstance() { + System.Management.ManagementScope mgmtScope = null; + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = CreatedWmiNamespace; + } + else { + mgmtScope = statMgmtScope; + } + System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); + System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); + return new EthernetPortAllocationSettingData(tmpMgmtClass.CreateInstance()); + } + + [Browsable(true)] + public void Delete() { + PrivateLateBoundObject.Delete(); + } + + public enum EnabledStateValues { + + Enabled = 2, + + Disabled = 3, + + NULL_ENUM_VALUE = 0, + } + + // Enumerator implementation for enumerating instances of the class. + public class EthernetPortAllocationSettingDataCollection : object, ICollection { + + private ManagementObjectCollection privColObj; + + public EthernetPortAllocationSettingDataCollection(ManagementObjectCollection objCollection) { + privColObj = objCollection; + } + + public virtual int Count { + get { + return privColObj.Count; + } + } + + public virtual bool IsSynchronized { + get { + return privColObj.IsSynchronized; + } + } + + public virtual object SyncRoot { + get { + return this; + } + } + + public virtual void CopyTo(System.Array array, int index) { + privColObj.CopyTo(array, index); + int nCtr; + for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { + array.SetValue(new EthernetPortAllocationSettingData(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); + } + } + + public virtual System.Collections.IEnumerator GetEnumerator() { + return new EthernetPortAllocationSettingDataEnumerator(privColObj.GetEnumerator()); + } + + public class EthernetPortAllocationSettingDataEnumerator : object, System.Collections.IEnumerator { + + private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; + + public EthernetPortAllocationSettingDataEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { + privObjEnum = objEnum; + } + + public virtual object Current { + get { + return new EthernetPortAllocationSettingData(((System.Management.ManagementObject)(privObjEnum.Current))); + } + } + + public virtual bool MoveNext() { + return privObjEnum.MoveNext(); + } + + public virtual void Reset() { + privObjEnum.Reset(); + } + } + } + + // TypeConverter to handle null values for ValueType properties + public class WMIValueTypeConverter : TypeConverter { + + private TypeConverter baseConverter; + + private System.Type baseType; + + public WMIValueTypeConverter(System.Type inBaseType) { + baseConverter = TypeDescriptor.GetConverter(inBaseType); + baseType = inBaseType; + } + + public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { + return baseConverter.CanConvertFrom(context, srcType); + } + + public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { + return baseConverter.CanConvertTo(context, destinationType); + } + + public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { + return baseConverter.ConvertFrom(context, culture, value); + } + + public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { + return baseConverter.CreateInstance(context, dictionary); + } + + public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetCreateInstanceSupported(context); + } + + public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { + return baseConverter.GetProperties(context, value, attributeVar); + } + + public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetPropertiesSupported(context); + } + + public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValues(context); + } + + public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesExclusive(context); + } + + public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesSupported(context); + } + + public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { + if ((baseType.BaseType == typeof(System.Enum))) { + if ((value.GetType() == destinationType)) { + return value; + } + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return "NULL_ENUM_VALUE" ; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((baseType == typeof(bool)) + && (baseType.BaseType == typeof(System.ValueType)))) { + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((context != null) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + } + + // Embedded class to represent WMI system Properties. + [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] + public class ManagementSystemProperties { + + private System.Management.ManagementBaseObject PrivateLateBoundObject; + + public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { + PrivateLateBoundObject = ManagedObject; + } + + [Browsable(true)] + public int GENUS { + get { + return ((int)(PrivateLateBoundObject["__GENUS"])); + } + } + + [Browsable(true)] + public string CLASS { + get { + return ((string)(PrivateLateBoundObject["__CLASS"])); + } + } + + [Browsable(true)] + public string SUPERCLASS { + get { + return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); + } + } + + [Browsable(true)] + public string DYNASTY { + get { + return ((string)(PrivateLateBoundObject["__DYNASTY"])); + } + } + + [Browsable(true)] + public string RELPATH { + get { + return ((string)(PrivateLateBoundObject["__RELPATH"])); + } + } + + [Browsable(true)] + public int PROPERTY_COUNT { + get { + return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); + } + } + + [Browsable(true)] + public string[] DERIVATION { + get { + return ((string[])(PrivateLateBoundObject["__DERIVATION"])); + } + } + + [Browsable(true)] + public string SERVER { + get { + return ((string)(PrivateLateBoundObject["__SERVER"])); + } + } + + [Browsable(true)] + public string NAMESPACE { + get { + return ((string)(PrivateLateBoundObject["__NAMESPACE"])); + } + } + + [Browsable(true)] + public string PATH { + get { + return ((string)(PrivateLateBoundObject["__PATH"])); + } + } + } + } +} diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_EthernetSwitchPort.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_EthernetSwitchPort.cs index 018e3f5021e..9626fa61916 100644 --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_EthernetSwitchPort.cs +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_EthernetSwitchPort.cs @@ -1,2119 +1,2119 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2 { - using System; - using System.ComponentModel; - using System.Management; - using System.Collections; - using System.Globalization; - using System.ComponentModel.Design.Serialization; - using System.Reflection; - - - // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. - // Functions IsNull() are used to check if a property is NULL. - // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. - // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. - // Datetime conversion functions ToDateTime and ToDmtfDateTime are added to the class to convert DMTF datetime to System.DateTime and vice-versa. - // An Early Bound class generated for the WMI class.Msvm_EthernetSwitchPort - public class EthernetSwitchPort : System.ComponentModel.Component { - - // Private property to hold the WMI namespace in which the class resides. - private static string CreatedWmiNamespace = "ROOT\\virtualization\\v2"; - - // Private property to hold the name of WMI class which created this class. - public static string CreatedClassName = "Msvm_EthernetSwitchPort"; - - // Private member variable to hold the ManagementScope which is used by the various methods. - private static System.Management.ManagementScope statMgmtScope = null; - - private ManagementSystemProperties PrivateSystemProperties; - - // Underlying lateBound WMI object. - private System.Management.ManagementObject PrivateLateBoundObject; - - // Member variable to store the 'automatic commit' behavior for the class. - private bool AutoCommitProp; - - // Private variable to hold the embedded property representing the instance. - private System.Management.ManagementBaseObject embeddedObj; - - // The current WMI object used - private System.Management.ManagementBaseObject curObj; - - // Flag to indicate if the instance is an embedded object. - private bool isEmbedded; - - // Below are different overloads of constructors to initialize an instance of the class with a WMI object. - public EthernetSwitchPort() { - this.InitializeObject(null, null, null); - } - - public EthernetSwitchPort(string keyCreationClassName, string keyDeviceID, string keySystemCreationClassName, string keySystemName) { - this.InitializeObject(null, new System.Management.ManagementPath(EthernetSwitchPort.ConstructPath(keyCreationClassName, keyDeviceID, keySystemCreationClassName, keySystemName)), null); - } - - public EthernetSwitchPort(System.Management.ManagementScope mgmtScope, string keyCreationClassName, string keyDeviceID, string keySystemCreationClassName, string keySystemName) { - this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(EthernetSwitchPort.ConstructPath(keyCreationClassName, keyDeviceID, keySystemCreationClassName, keySystemName)), null); - } - - public EthernetSwitchPort(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(null, path, getOptions); - } - - public EthernetSwitchPort(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { - this.InitializeObject(mgmtScope, path, null); - } - - public EthernetSwitchPort(System.Management.ManagementPath path) { - this.InitializeObject(null, path, null); - } - - public EthernetSwitchPort(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(mgmtScope, path, getOptions); - } - - public EthernetSwitchPort(System.Management.ManagementObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - PrivateLateBoundObject = theObject; - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - public EthernetSwitchPort(System.Management.ManagementBaseObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - embeddedObj = theObject; - PrivateSystemProperties = new ManagementSystemProperties(theObject); - curObj = embeddedObj; - isEmbedded = true; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - // Property returns the namespace of the WMI class. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OriginatingNamespace { - get { - return "ROOT\\virtualization\\v2"; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ManagementClassName { - get { - string strRet = CreatedClassName; - if ((curObj != null)) { - if ((curObj.ClassPath != null)) { - strRet = ((string)(curObj["__CLASS"])); - if (((strRet == null) - || (strRet == string.Empty))) { - strRet = CreatedClassName; - } - } - } - return strRet; - } - } - - // Property pointing to an embedded object to get System properties of the WMI object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ManagementSystemProperties SystemProperties { - get { - return PrivateSystemProperties; - } - } - - // Property returning the underlying lateBound object. - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementBaseObject LateBoundObject { - get { - return curObj; - } - } - - // ManagementScope of the object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementScope Scope { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Scope; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Scope = value; - } - } - } - - // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool AutoCommit { - get { - return AutoCommitProp; - } - set { - AutoCommitProp = value; - } - } - - // The ManagementPath of the underlying WMI object. - [Browsable(true)] - public System.Management.ManagementPath Path { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Path; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - if ((CheckIfProperClass(null, value, null) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - PrivateLateBoundObject.Path = value; - } - } - } - - // Public static scope property which is used by the various methods. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public static System.Management.ManagementScope StaticScope { - get { - return statMgmtScope; - } - set { - statMgmtScope = value; - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsActiveMaximumTransmissionUnitNull { - get { - if ((curObj["ActiveMaximumTransmissionUnit"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong ActiveMaximumTransmissionUnit { - get { - if ((curObj["ActiveMaximumTransmissionUnit"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["ActiveMaximumTransmissionUnit"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ushort[] AdditionalAvailability { - get { - return ((ushort[])(curObj["AdditionalAvailability"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsAutoSenseNull { - get { - if ((curObj["AutoSense"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool AutoSense { - get { - if ((curObj["AutoSense"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["AutoSense"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsAvailabilityNull { - get { - if ((curObj["Availability"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort Availability { - get { - if ((curObj["Availability"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["Availability"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ushort[] AvailableRequestedStates { - get { - return ((ushort[])(curObj["AvailableRequestedStates"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ushort[] Capabilities { - get { - return ((ushort[])(curObj["Capabilities"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] CapabilityDescriptions { - get { - return ((string[])(curObj["CapabilityDescriptions"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Caption { - get { - return ((string)(curObj["Caption"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsCommunicationStatusNull { - get { - if ((curObj["CommunicationStatus"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort CommunicationStatus { - get { - if ((curObj["CommunicationStatus"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["CommunicationStatus"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string CreationClassName { - get { - return ((string)(curObj["CreationClassName"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Description { - get { - return ((string)(curObj["Description"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsDetailedStatusNull { - get { - if ((curObj["DetailedStatus"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort DetailedStatus { - get { - if ((curObj["DetailedStatus"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["DetailedStatus"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string DeviceID { - get { - return ((string)(curObj["DeviceID"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ElementName { - get { - return ((string)(curObj["ElementName"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ushort[] EnabledCapabilities { - get { - return ((ushort[])(curObj["EnabledCapabilities"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsEnabledDefaultNull { - get { - if ((curObj["EnabledDefault"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort EnabledDefault { - get { - if ((curObj["EnabledDefault"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["EnabledDefault"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsEnabledStateNull { - get { - if ((curObj["EnabledState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort EnabledState { - get { - if ((curObj["EnabledState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["EnabledState"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsErrorClearedNull { - get { - if ((curObj["ErrorCleared"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool ErrorCleared { - get { - if ((curObj["ErrorCleared"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["ErrorCleared"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ErrorDescription { - get { - return ((string)(curObj["ErrorDescription"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsFullDuplexNull { - get { - if ((curObj["FullDuplex"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool FullDuplex { - get { - if ((curObj["FullDuplex"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["FullDuplex"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsHealthStateNull { - get { - if ((curObj["HealthState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort HealthState { - get { - if ((curObj["HealthState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["HealthState"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] IdentifyingDescriptions { - get { - return ((string[])(curObj["IdentifyingDescriptions"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsInstallDateNull { - get { - if ((curObj["InstallDate"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public System.DateTime InstallDate { - get { - if ((curObj["InstallDate"] != null)) { - return ToDateTime(((string)(curObj["InstallDate"]))); - } - else { - return System.DateTime.MinValue; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string InstanceID { - get { - return ((string)(curObj["InstanceID"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsIOVOffloadUsageNull { - get { - if ((curObj["IOVOffloadUsage"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The current I/O virtualization (IOV) offload usage on this port. The usage is the" + - "amount of IOV resources in use on the port.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public uint IOVOffloadUsage { - get { - if ((curObj["IOVOffloadUsage"] == null)) { - return System.Convert.ToUInt32(0); - } - return ((uint)(curObj["IOVOffloadUsage"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsLastErrorCodeNull { - get { - if ((curObj["LastErrorCode"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public uint LastErrorCode { - get { - if ((curObj["LastErrorCode"] == null)) { - return System.Convert.ToUInt32(0); - } - return ((uint)(curObj["LastErrorCode"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsLinkTechnologyNull { - get { - if ((curObj["LinkTechnology"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort LinkTechnology { - get { - if ((curObj["LinkTechnology"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["LinkTechnology"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsMaxDataSizeNull { - get { - if ((curObj["MaxDataSize"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public uint MaxDataSize { - get { - if ((curObj["MaxDataSize"] == null)) { - return System.Convert.ToUInt32(0); - } - return ((uint)(curObj["MaxDataSize"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsMaxQuiesceTimeNull { - get { - if ((curObj["MaxQuiesceTime"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong MaxQuiesceTime { - get { - if ((curObj["MaxQuiesceTime"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["MaxQuiesceTime"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsMaxSpeedNull { - get { - if ((curObj["MaxSpeed"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong MaxSpeed { - get { - if ((curObj["MaxSpeed"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["MaxSpeed"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Name { - get { - return ((string)(curObj["Name"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] NetworkAddresses { - get { - return ((string[])(curObj["NetworkAddresses"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsOperatingStatusNull { - get { - if ((curObj["OperatingStatus"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort OperatingStatus { - get { - if ((curObj["OperatingStatus"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["OperatingStatus"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ushort[] OperationalStatus { - get { - return ((ushort[])(curObj["OperationalStatus"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] OtherEnabledCapabilities { - get { - return ((string[])(curObj["OtherEnabledCapabilities"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OtherEnabledState { - get { - return ((string)(curObj["OtherEnabledState"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] OtherIdentifyingInfo { - get { - return ((string[])(curObj["OtherIdentifyingInfo"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OtherLinkTechnology { - get { - return ((string)(curObj["OtherLinkTechnology"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OtherNetworkPortType { - get { - return ((string)(curObj["OtherNetworkPortType"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OtherPortType { - get { - return ((string)(curObj["OtherPortType"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string PermanentAddress { - get { - return ((string)(curObj["PermanentAddress"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsPortNumberNull { - get { - if ((curObj["PortNumber"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort PortNumber { - get { - if ((curObj["PortNumber"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["PortNumber"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsPortTypeNull { - get { - if ((curObj["PortType"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort PortType { - get { - if ((curObj["PortType"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["PortType"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ushort[] PowerManagementCapabilities { - get { - return ((ushort[])(curObj["PowerManagementCapabilities"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsPowerManagementSupportedNull { - get { - if ((curObj["PowerManagementSupported"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool PowerManagementSupported { - get { - if ((curObj["PowerManagementSupported"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["PowerManagementSupported"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsPowerOnHoursNull { - get { - if ((curObj["PowerOnHours"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong PowerOnHours { - get { - if ((curObj["PowerOnHours"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["PowerOnHours"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsPrimaryStatusNull { - get { - if ((curObj["PrimaryStatus"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort PrimaryStatus { - get { - if ((curObj["PrimaryStatus"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["PrimaryStatus"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsRequestedSpeedNull { - get { - if ((curObj["RequestedSpeed"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong RequestedSpeed { - get { - if ((curObj["RequestedSpeed"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["RequestedSpeed"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsRequestedStateNull { - get { - if ((curObj["RequestedState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort RequestedState { - get { - if ((curObj["RequestedState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["RequestedState"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsSpeedNull { - get { - if ((curObj["Speed"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong Speed { - get { - if ((curObj["Speed"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["Speed"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Status { - get { - return ((string)(curObj["Status"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] StatusDescriptions { - get { - return ((string[])(curObj["StatusDescriptions"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsStatusInfoNull { - get { - if ((curObj["StatusInfo"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort StatusInfo { - get { - if ((curObj["StatusInfo"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["StatusInfo"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsSupportedMaximumTransmissionUnitNull { - get { - if ((curObj["SupportedMaximumTransmissionUnit"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong SupportedMaximumTransmissionUnit { - get { - if ((curObj["SupportedMaximumTransmissionUnit"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["SupportedMaximumTransmissionUnit"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string SystemCreationClassName { - get { - return ((string)(curObj["SystemCreationClassName"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string SystemName { - get { - return ((string)(curObj["SystemName"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsTimeOfLastStateChangeNull { - get { - if ((curObj["TimeOfLastStateChange"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public System.DateTime TimeOfLastStateChange { - get { - if ((curObj["TimeOfLastStateChange"] != null)) { - return ToDateTime(((string)(curObj["TimeOfLastStateChange"]))); - } - else { - return System.DateTime.MinValue; - } - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsTotalPowerOnHoursNull { - get { - if ((curObj["TotalPowerOnHours"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong TotalPowerOnHours { - get { - if ((curObj["TotalPowerOnHours"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["TotalPowerOnHours"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsTransitioningToStateNull { - get { - if ((curObj["TransitioningToState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort TransitioningToState { - get { - if ((curObj["TransitioningToState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["TransitioningToState"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsUsageRestrictionNull { - get { - if ((curObj["UsageRestriction"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort UsageRestriction { - get { - if ((curObj["UsageRestriction"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["UsageRestriction"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsVMQOffloadUsageNull { - get { - if ((curObj["VMQOffloadUsage"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The current VMQ offloading usage on this port. The usage is the amount of VMQ res" + - "ources in use on the port.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public uint VMQOffloadUsage { - get { - if ((curObj["VMQOffloadUsage"] == null)) { - return System.Convert.ToUInt32(0); - } - return ((uint)(curObj["VMQOffloadUsage"])); - } - } - - private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { - if (((path != null) - && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); - } - } - - private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { - if (((theObj != null) - && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); - if ((parentClasses != null)) { - int count = 0; - for (count = 0; (count < parentClasses.Length); count = (count + 1)) { - if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { - return true; - } - } - } - } - return false; - } - - private bool ShouldSerializeActiveMaximumTransmissionUnit() { - if ((this.IsActiveMaximumTransmissionUnitNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeAutoSense() { - if ((this.IsAutoSenseNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeAvailability() { - if ((this.IsAvailabilityNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeCommunicationStatus() { - if ((this.IsCommunicationStatusNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeDetailedStatus() { - if ((this.IsDetailedStatusNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeEnabledDefault() { - if ((this.IsEnabledDefaultNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeEnabledState() { - if ((this.IsEnabledStateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeErrorCleared() { - if ((this.IsErrorClearedNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeFullDuplex() { - if ((this.IsFullDuplexNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeHealthState() { - if ((this.IsHealthStateNull == false)) { - return true; - } - return false; - } - - // Converts a given datetime in DMTF format to System.DateTime object. - static System.DateTime ToDateTime(string dmtfDate) { - System.DateTime initializer = System.DateTime.MinValue; - int year = initializer.Year; - int month = initializer.Month; - int day = initializer.Day; - int hour = initializer.Hour; - int minute = initializer.Minute; - int second = initializer.Second; - long ticks = 0; - string dmtf = dmtfDate; - System.DateTime datetime = System.DateTime.MinValue; - string tempString = string.Empty; - if ((dmtf == null)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtf.Length == 0)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtf.Length != 25)) { - throw new System.ArgumentOutOfRangeException(); - } - try { - tempString = dmtf.Substring(0, 4); - if (("****" != tempString)) { - year = int.Parse(tempString); - } - tempString = dmtf.Substring(4, 2); - if (("**" != tempString)) { - month = int.Parse(tempString); - } - tempString = dmtf.Substring(6, 2); - if (("**" != tempString)) { - day = int.Parse(tempString); - } - tempString = dmtf.Substring(8, 2); - if (("**" != tempString)) { - hour = int.Parse(tempString); - } - tempString = dmtf.Substring(10, 2); - if (("**" != tempString)) { - minute = int.Parse(tempString); - } - tempString = dmtf.Substring(12, 2); - if (("**" != tempString)) { - second = int.Parse(tempString); - } - tempString = dmtf.Substring(15, 6); - if (("******" != tempString)) { - ticks = (long.Parse(tempString) * ((long)((System.TimeSpan.TicksPerMillisecond / 1000)))); - } - if (((((((((year < 0) - || (month < 0)) - || (day < 0)) - || (hour < 0)) - || (minute < 0)) - || (minute < 0)) - || (second < 0)) - || (ticks < 0))) { - throw new System.ArgumentOutOfRangeException(); - } - } - catch (System.Exception e) { - throw new System.ArgumentOutOfRangeException(null, e.Message); - } - datetime = new System.DateTime(year, month, day, hour, minute, second, 0); - datetime = datetime.AddTicks(ticks); - System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(datetime); - int UTCOffset = 0; - int OffsetToBeAdjusted = 0; - long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); - tempString = dmtf.Substring(22, 3); - if ((tempString != "******")) { - tempString = dmtf.Substring(21, 4); - try { - UTCOffset = int.Parse(tempString); - } - catch (System.Exception e) { - throw new System.ArgumentOutOfRangeException(null, e.Message); - } - OffsetToBeAdjusted = ((int)((OffsetMins - UTCOffset))); - datetime = datetime.AddMinutes(((double)(OffsetToBeAdjusted))); - } - return datetime; - } - - // Converts a given System.DateTime object to DMTF datetime format. - static string ToDmtfDateTime(System.DateTime date) { - string utcString = string.Empty; - System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(date); - long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); - if ((System.Math.Abs(OffsetMins) > 999)) { - date = date.ToUniversalTime(); - utcString = "+000"; - } - else { - if ((tickOffset.Ticks >= 0)) { - utcString = string.Concat("+", ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))).ToString().PadLeft(3, '0')); - } - else { - string strTemp = ((long)(OffsetMins)).ToString(); - utcString = string.Concat("-", strTemp.Substring(1, (strTemp.Length - 1)).PadLeft(3, '0')); - } - } - string dmtfDateTime = ((int)(date.Year)).ToString().PadLeft(4, '0'); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Month)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Day)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Hour)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Minute)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Second)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, "."); - System.DateTime dtTemp = new System.DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, 0); - long microsec = ((long)((((date.Ticks - dtTemp.Ticks) - * 1000) - / System.TimeSpan.TicksPerMillisecond))); - string strMicrosec = ((long)(microsec)).ToString(); - if ((strMicrosec.Length > 6)) { - strMicrosec = strMicrosec.Substring(0, 6); - } - dmtfDateTime = string.Concat(dmtfDateTime, strMicrosec.PadLeft(6, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, utcString); - return dmtfDateTime; - } - - private bool ShouldSerializeInstallDate() { - if ((this.IsInstallDateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeIOVOffloadUsage() { - if ((this.IsIOVOffloadUsageNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeLastErrorCode() { - if ((this.IsLastErrorCodeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeLinkTechnology() { - if ((this.IsLinkTechnologyNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeMaxDataSize() { - if ((this.IsMaxDataSizeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeMaxQuiesceTime() { - if ((this.IsMaxQuiesceTimeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeMaxSpeed() { - if ((this.IsMaxSpeedNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeOperatingStatus() { - if ((this.IsOperatingStatusNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializePortNumber() { - if ((this.IsPortNumberNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializePortType() { - if ((this.IsPortTypeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializePowerManagementSupported() { - if ((this.IsPowerManagementSupportedNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializePowerOnHours() { - if ((this.IsPowerOnHoursNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializePrimaryStatus() { - if ((this.IsPrimaryStatusNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeRequestedSpeed() { - if ((this.IsRequestedSpeedNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeRequestedState() { - if ((this.IsRequestedStateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeSpeed() { - if ((this.IsSpeedNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeStatusInfo() { - if ((this.IsStatusInfoNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeSupportedMaximumTransmissionUnit() { - if ((this.IsSupportedMaximumTransmissionUnitNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeTimeOfLastStateChange() { - if ((this.IsTimeOfLastStateChangeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeTotalPowerOnHours() { - if ((this.IsTotalPowerOnHoursNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeTransitioningToState() { - if ((this.IsTransitioningToStateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeUsageRestriction() { - if ((this.IsUsageRestrictionNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeVMQOffloadUsage() { - if ((this.IsVMQOffloadUsageNull == false)) { - return true; - } - return false; - } - - [Browsable(true)] - public void CommitObject() { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(); - } - } - - [Browsable(true)] - public void CommitObject(System.Management.PutOptions putOptions) { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(putOptions); - } - } - - private void Initialize() { - AutoCommitProp = true; - isEmbedded = false; - } - - private static string ConstructPath(string keyCreationClassName, string keyDeviceID, string keySystemCreationClassName, string keySystemName) { - string strPath = "ROOT\\virtualization\\v2:Msvm_EthernetSwitchPort"; - strPath = string.Concat(strPath, string.Concat(".CreationClassName=", string.Concat("\"", string.Concat(keyCreationClassName, "\"")))); - strPath = string.Concat(strPath, string.Concat(",DeviceID=", string.Concat("\"", string.Concat(keyDeviceID, "\"")))); - strPath = string.Concat(strPath, string.Concat(",SystemCreationClassName=", string.Concat("\"", string.Concat(keySystemCreationClassName, "\"")))); - strPath = string.Concat(strPath, string.Concat(",SystemName=", string.Concat("\"", string.Concat(keySystemName, "\"")))); - return strPath; - } - - private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - Initialize(); - if ((path != null)) { - if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - } - PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - - // Different overloads of GetInstances() help in enumerating instances of the WMI class. - public static EthernetSwitchPortCollection GetInstances() { - return GetInstances(null, null, null); - } - - public static EthernetSwitchPortCollection GetInstances(string condition) { - return GetInstances(null, condition, null); - } - - public static EthernetSwitchPortCollection GetInstances(string[] selectedProperties) { - return GetInstances(null, null, selectedProperties); - } - - public static EthernetSwitchPortCollection GetInstances(string condition, string[] selectedProperties) { - return GetInstances(null, condition, selectedProperties); - } - - public static EthernetSwitchPortCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); - pathObj.ClassName = "Msvm_EthernetSwitchPort"; - pathObj.NamespacePath = "root\\virtualization\\v2"; - System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); - if ((enumOptions == null)) { - enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - } - return new EthernetSwitchPortCollection(clsObject.GetInstances(enumOptions)); - } - - public static EthernetSwitchPortCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { - return GetInstances(mgmtScope, condition, null); - } - - public static EthernetSwitchPortCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { - return GetInstances(mgmtScope, null, selectedProperties); - } - - public static EthernetSwitchPortCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_EthernetSwitchPort", condition, selectedProperties)); - System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - ObjectSearcher.Options = enumOptions; - return new EthernetSwitchPortCollection(ObjectSearcher.Get()); - } - - [Browsable(true)] - public static EthernetSwitchPort CreateInstance() { - System.Management.ManagementScope mgmtScope = null; - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = CreatedWmiNamespace; - } - else { - mgmtScope = statMgmtScope; - } - System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); - System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); - return new EthernetSwitchPort(tmpMgmtClass.CreateInstance()); - } - - [Browsable(true)] - public void Delete() { - PrivateLateBoundObject.Delete(); - } - - public uint EnableDevice(bool Enabled) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("EnableDevice"); - inParams["Enabled"] = ((bool)(Enabled)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("EnableDevice", inParams, null); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - return System.Convert.ToUInt32(0); - } - } - - public uint OnlineDevice(bool Online) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("OnlineDevice"); - inParams["Online"] = ((bool)(Online)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("OnlineDevice", inParams, null); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - return System.Convert.ToUInt32(0); - } - } - - public uint QuiesceDevice(bool Quiesce) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("QuiesceDevice"); - inParams["Quiesce"] = ((bool)(Quiesce)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("QuiesceDevice", inParams, null); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - return System.Convert.ToUInt32(0); - } - } - - public uint RequestStateChange(ushort RequestedState, System.DateTime TimeoutPeriod, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("RequestStateChange"); - inParams["RequestedState"] = ((ushort)(RequestedState)); - inParams["TimeoutPeriod"] = ToDmtfDateTime(((System.DateTime)(TimeoutPeriod))); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RequestStateChange", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null) && outParams.Properties["Job"].Value != null) { - Job = new System.Management.ManagementPath(outParams.Properties["Job"].Value.ToString()); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - return System.Convert.ToUInt32(0); - } - } - - public uint Reset() { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("Reset", inParams, null); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - return System.Convert.ToUInt32(0); - } - } - - public uint RestoreProperties() { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RestoreProperties", inParams, null); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - return System.Convert.ToUInt32(0); - } - } - - public uint SaveProperties() { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("SaveProperties", inParams, null); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - return System.Convert.ToUInt32(0); - } - } - - public uint SetPowerState(ushort PowerState, System.DateTime Time) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("SetPowerState"); - inParams["PowerState"] = ((ushort)(PowerState)); - inParams["Time"] = ToDmtfDateTime(((System.DateTime)(Time))); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("SetPowerState", inParams, null); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - return System.Convert.ToUInt32(0); - } - } - - // Enumerator implementation for enumerating instances of the class. - public class EthernetSwitchPortCollection : object, ICollection { - - private ManagementObjectCollection privColObj; - - public EthernetSwitchPortCollection(ManagementObjectCollection objCollection) { - privColObj = objCollection; - } - - public virtual int Count { - get { - return privColObj.Count; - } - } - - public virtual bool IsSynchronized { - get { - return privColObj.IsSynchronized; - } - } - - public virtual object SyncRoot { - get { - return this; - } - } - - public virtual void CopyTo(System.Array array, int index) { - privColObj.CopyTo(array, index); - int nCtr; - for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { - array.SetValue(new EthernetSwitchPort(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); - } - } - - public virtual System.Collections.IEnumerator GetEnumerator() { - return new EthernetSwitchPortEnumerator(privColObj.GetEnumerator()); - } - - public class EthernetSwitchPortEnumerator : object, System.Collections.IEnumerator { - - private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; - - public EthernetSwitchPortEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { - privObjEnum = objEnum; - } - - public virtual object Current { - get { - return new EthernetSwitchPort(((System.Management.ManagementObject)(privObjEnum.Current))); - } - } - - public virtual bool MoveNext() { - return privObjEnum.MoveNext(); - } - - public virtual void Reset() { - privObjEnum.Reset(); - } - } - } - - // TypeConverter to handle null values for ValueType properties - public class WMIValueTypeConverter : TypeConverter { - - private TypeConverter baseConverter; - - private System.Type baseType; - - public WMIValueTypeConverter(System.Type inBaseType) { - baseConverter = TypeDescriptor.GetConverter(inBaseType); - baseType = inBaseType; - } - - public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { - return baseConverter.CanConvertFrom(context, srcType); - } - - public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { - return baseConverter.CanConvertTo(context, destinationType); - } - - public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { - return baseConverter.ConvertFrom(context, culture, value); - } - - public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { - return baseConverter.CreateInstance(context, dictionary); - } - - public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetCreateInstanceSupported(context); - } - - public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { - return baseConverter.GetProperties(context, value, attributeVar); - } - - public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetPropertiesSupported(context); - } - - public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValues(context); - } - - public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesExclusive(context); - } - - public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesSupported(context); - } - - public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { - if ((baseType.BaseType == typeof(System.Enum))) { - if ((value.GetType() == destinationType)) { - return value; - } - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return "NULL_ENUM_VALUE" ; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((baseType == typeof(bool)) - && (baseType.BaseType == typeof(System.ValueType)))) { - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((context != null) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - } - - // Embedded class to represent WMI system Properties. - [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] - public class ManagementSystemProperties { - - private System.Management.ManagementBaseObject PrivateLateBoundObject; - - public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { - PrivateLateBoundObject = ManagedObject; - } - - [Browsable(true)] - public int GENUS { - get { - return ((int)(PrivateLateBoundObject["__GENUS"])); - } - } - - [Browsable(true)] - public string CLASS { - get { - return ((string)(PrivateLateBoundObject["__CLASS"])); - } - } - - [Browsable(true)] - public string SUPERCLASS { - get { - return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); - } - } - - [Browsable(true)] - public string DYNASTY { - get { - return ((string)(PrivateLateBoundObject["__DYNASTY"])); - } - } - - [Browsable(true)] - public string RELPATH { - get { - return ((string)(PrivateLateBoundObject["__RELPATH"])); - } - } - - [Browsable(true)] - public int PROPERTY_COUNT { - get { - return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); - } - } - - [Browsable(true)] - public string[] DERIVATION { - get { - return ((string[])(PrivateLateBoundObject["__DERIVATION"])); - } - } - - [Browsable(true)] - public string SERVER { - get { - return ((string)(PrivateLateBoundObject["__SERVER"])); - } - } - - [Browsable(true)] - public string NAMESPACE { - get { - return ((string)(PrivateLateBoundObject["__NAMESPACE"])); - } - } - - [Browsable(true)] - public string PATH { - get { - return ((string)(PrivateLateBoundObject["__PATH"])); - } - } - } - } -} +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2 { + using System; + using System.ComponentModel; + using System.Management; + using System.Collections; + using System.Globalization; + using System.ComponentModel.Design.Serialization; + using System.Reflection; + + + // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. + // Functions IsNull() are used to check if a property is NULL. + // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. + // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. + // Datetime conversion functions ToDateTime and ToDmtfDateTime are added to the class to convert DMTF datetime to System.DateTime and vice-versa. + // An Early Bound class generated for the WMI class.Msvm_EthernetSwitchPort + public class EthernetSwitchPort : System.ComponentModel.Component { + + // Private property to hold the WMI namespace in which the class resides. + private static string CreatedWmiNamespace = "ROOT\\virtualization\\v2"; + + // Private property to hold the name of WMI class which created this class. + public static string CreatedClassName = "Msvm_EthernetSwitchPort"; + + // Private member variable to hold the ManagementScope which is used by the various methods. + private static System.Management.ManagementScope statMgmtScope = null; + + private ManagementSystemProperties PrivateSystemProperties; + + // Underlying lateBound WMI object. + private System.Management.ManagementObject PrivateLateBoundObject; + + // Member variable to store the 'automatic commit' behavior for the class. + private bool AutoCommitProp; + + // Private variable to hold the embedded property representing the instance. + private System.Management.ManagementBaseObject embeddedObj; + + // The current WMI object used + private System.Management.ManagementBaseObject curObj; + + // Flag to indicate if the instance is an embedded object. + private bool isEmbedded; + + // Below are different overloads of constructors to initialize an instance of the class with a WMI object. + public EthernetSwitchPort() { + this.InitializeObject(null, null, null); + } + + public EthernetSwitchPort(string keyCreationClassName, string keyDeviceID, string keySystemCreationClassName, string keySystemName) { + this.InitializeObject(null, new System.Management.ManagementPath(EthernetSwitchPort.ConstructPath(keyCreationClassName, keyDeviceID, keySystemCreationClassName, keySystemName)), null); + } + + public EthernetSwitchPort(System.Management.ManagementScope mgmtScope, string keyCreationClassName, string keyDeviceID, string keySystemCreationClassName, string keySystemName) { + this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(EthernetSwitchPort.ConstructPath(keyCreationClassName, keyDeviceID, keySystemCreationClassName, keySystemName)), null); + } + + public EthernetSwitchPort(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(null, path, getOptions); + } + + public EthernetSwitchPort(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { + this.InitializeObject(mgmtScope, path, null); + } + + public EthernetSwitchPort(System.Management.ManagementPath path) { + this.InitializeObject(null, path, null); + } + + public EthernetSwitchPort(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(mgmtScope, path, getOptions); + } + + public EthernetSwitchPort(System.Management.ManagementObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + PrivateLateBoundObject = theObject; + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + public EthernetSwitchPort(System.Management.ManagementBaseObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + embeddedObj = theObject; + PrivateSystemProperties = new ManagementSystemProperties(theObject); + curObj = embeddedObj; + isEmbedded = true; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + // Property returns the namespace of the WMI class. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OriginatingNamespace { + get { + return "ROOT\\virtualization\\v2"; + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ManagementClassName { + get { + string strRet = CreatedClassName; + if ((curObj != null)) { + if ((curObj.ClassPath != null)) { + strRet = ((string)(curObj["__CLASS"])); + if (((strRet == null) + || (strRet == string.Empty))) { + strRet = CreatedClassName; + } + } + } + return strRet; + } + } + + // Property pointing to an embedded object to get System properties of the WMI object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ManagementSystemProperties SystemProperties { + get { + return PrivateSystemProperties; + } + } + + // Property returning the underlying lateBound object. + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementBaseObject LateBoundObject { + get { + return curObj; + } + } + + // ManagementScope of the object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementScope Scope { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Scope; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Scope = value; + } + } + } + + // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool AutoCommit { + get { + return AutoCommitProp; + } + set { + AutoCommitProp = value; + } + } + + // The ManagementPath of the underlying WMI object. + [Browsable(true)] + public System.Management.ManagementPath Path { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Path; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + if ((CheckIfProperClass(null, value, null) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + PrivateLateBoundObject.Path = value; + } + } + } + + // Public static scope property which is used by the various methods. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public static System.Management.ManagementScope StaticScope { + get { + return statMgmtScope; + } + set { + statMgmtScope = value; + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsActiveMaximumTransmissionUnitNull { + get { + if ((curObj["ActiveMaximumTransmissionUnit"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong ActiveMaximumTransmissionUnit { + get { + if ((curObj["ActiveMaximumTransmissionUnit"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["ActiveMaximumTransmissionUnit"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ushort[] AdditionalAvailability { + get { + return ((ushort[])(curObj["AdditionalAvailability"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAutoSenseNull { + get { + if ((curObj["AutoSense"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool AutoSense { + get { + if ((curObj["AutoSense"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["AutoSense"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAvailabilityNull { + get { + if ((curObj["Availability"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort Availability { + get { + if ((curObj["Availability"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["Availability"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ushort[] AvailableRequestedStates { + get { + return ((ushort[])(curObj["AvailableRequestedStates"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ushort[] Capabilities { + get { + return ((ushort[])(curObj["Capabilities"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] CapabilityDescriptions { + get { + return ((string[])(curObj["CapabilityDescriptions"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Caption { + get { + return ((string)(curObj["Caption"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsCommunicationStatusNull { + get { + if ((curObj["CommunicationStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort CommunicationStatus { + get { + if ((curObj["CommunicationStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["CommunicationStatus"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string CreationClassName { + get { + return ((string)(curObj["CreationClassName"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Description { + get { + return ((string)(curObj["Description"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsDetailedStatusNull { + get { + if ((curObj["DetailedStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort DetailedStatus { + get { + if ((curObj["DetailedStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["DetailedStatus"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string DeviceID { + get { + return ((string)(curObj["DeviceID"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ElementName { + get { + return ((string)(curObj["ElementName"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ushort[] EnabledCapabilities { + get { + return ((ushort[])(curObj["EnabledCapabilities"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsEnabledDefaultNull { + get { + if ((curObj["EnabledDefault"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort EnabledDefault { + get { + if ((curObj["EnabledDefault"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["EnabledDefault"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsEnabledStateNull { + get { + if ((curObj["EnabledState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort EnabledState { + get { + if ((curObj["EnabledState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["EnabledState"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsErrorClearedNull { + get { + if ((curObj["ErrorCleared"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool ErrorCleared { + get { + if ((curObj["ErrorCleared"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["ErrorCleared"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ErrorDescription { + get { + return ((string)(curObj["ErrorDescription"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsFullDuplexNull { + get { + if ((curObj["FullDuplex"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool FullDuplex { + get { + if ((curObj["FullDuplex"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["FullDuplex"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsHealthStateNull { + get { + if ((curObj["HealthState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort HealthState { + get { + if ((curObj["HealthState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["HealthState"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] IdentifyingDescriptions { + get { + return ((string[])(curObj["IdentifyingDescriptions"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsInstallDateNull { + get { + if ((curObj["InstallDate"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime InstallDate { + get { + if ((curObj["InstallDate"] != null)) { + return ToDateTime(((string)(curObj["InstallDate"]))); + } + else { + return System.DateTime.MinValue; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string InstanceID { + get { + return ((string)(curObj["InstanceID"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsIOVOffloadUsageNull { + get { + if ((curObj["IOVOffloadUsage"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The current I/O virtualization (IOV) offload usage on this port. The usage is the" + + "amount of IOV resources in use on the port.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint IOVOffloadUsage { + get { + if ((curObj["IOVOffloadUsage"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["IOVOffloadUsage"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsLastErrorCodeNull { + get { + if ((curObj["LastErrorCode"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint LastErrorCode { + get { + if ((curObj["LastErrorCode"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["LastErrorCode"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsLinkTechnologyNull { + get { + if ((curObj["LinkTechnology"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort LinkTechnology { + get { + if ((curObj["LinkTechnology"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["LinkTechnology"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsMaxDataSizeNull { + get { + if ((curObj["MaxDataSize"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint MaxDataSize { + get { + if ((curObj["MaxDataSize"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["MaxDataSize"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsMaxQuiesceTimeNull { + get { + if ((curObj["MaxQuiesceTime"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong MaxQuiesceTime { + get { + if ((curObj["MaxQuiesceTime"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["MaxQuiesceTime"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsMaxSpeedNull { + get { + if ((curObj["MaxSpeed"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong MaxSpeed { + get { + if ((curObj["MaxSpeed"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["MaxSpeed"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Name { + get { + return ((string)(curObj["Name"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] NetworkAddresses { + get { + return ((string[])(curObj["NetworkAddresses"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsOperatingStatusNull { + get { + if ((curObj["OperatingStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort OperatingStatus { + get { + if ((curObj["OperatingStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["OperatingStatus"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ushort[] OperationalStatus { + get { + return ((ushort[])(curObj["OperationalStatus"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] OtherEnabledCapabilities { + get { + return ((string[])(curObj["OtherEnabledCapabilities"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherEnabledState { + get { + return ((string)(curObj["OtherEnabledState"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] OtherIdentifyingInfo { + get { + return ((string[])(curObj["OtherIdentifyingInfo"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherLinkTechnology { + get { + return ((string)(curObj["OtherLinkTechnology"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherNetworkPortType { + get { + return ((string)(curObj["OtherNetworkPortType"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherPortType { + get { + return ((string)(curObj["OtherPortType"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string PermanentAddress { + get { + return ((string)(curObj["PermanentAddress"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPortNumberNull { + get { + if ((curObj["PortNumber"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort PortNumber { + get { + if ((curObj["PortNumber"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["PortNumber"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPortTypeNull { + get { + if ((curObj["PortType"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort PortType { + get { + if ((curObj["PortType"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["PortType"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ushort[] PowerManagementCapabilities { + get { + return ((ushort[])(curObj["PowerManagementCapabilities"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPowerManagementSupportedNull { + get { + if ((curObj["PowerManagementSupported"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool PowerManagementSupported { + get { + if ((curObj["PowerManagementSupported"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["PowerManagementSupported"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPowerOnHoursNull { + get { + if ((curObj["PowerOnHours"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong PowerOnHours { + get { + if ((curObj["PowerOnHours"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["PowerOnHours"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPrimaryStatusNull { + get { + if ((curObj["PrimaryStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort PrimaryStatus { + get { + if ((curObj["PrimaryStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["PrimaryStatus"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsRequestedSpeedNull { + get { + if ((curObj["RequestedSpeed"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong RequestedSpeed { + get { + if ((curObj["RequestedSpeed"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["RequestedSpeed"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsRequestedStateNull { + get { + if ((curObj["RequestedState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort RequestedState { + get { + if ((curObj["RequestedState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["RequestedState"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsSpeedNull { + get { + if ((curObj["Speed"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong Speed { + get { + if ((curObj["Speed"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["Speed"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Status { + get { + return ((string)(curObj["Status"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] StatusDescriptions { + get { + return ((string[])(curObj["StatusDescriptions"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsStatusInfoNull { + get { + if ((curObj["StatusInfo"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort StatusInfo { + get { + if ((curObj["StatusInfo"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["StatusInfo"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsSupportedMaximumTransmissionUnitNull { + get { + if ((curObj["SupportedMaximumTransmissionUnit"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong SupportedMaximumTransmissionUnit { + get { + if ((curObj["SupportedMaximumTransmissionUnit"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["SupportedMaximumTransmissionUnit"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string SystemCreationClassName { + get { + return ((string)(curObj["SystemCreationClassName"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string SystemName { + get { + return ((string)(curObj["SystemName"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsTimeOfLastStateChangeNull { + get { + if ((curObj["TimeOfLastStateChange"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime TimeOfLastStateChange { + get { + if ((curObj["TimeOfLastStateChange"] != null)) { + return ToDateTime(((string)(curObj["TimeOfLastStateChange"]))); + } + else { + return System.DateTime.MinValue; + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsTotalPowerOnHoursNull { + get { + if ((curObj["TotalPowerOnHours"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong TotalPowerOnHours { + get { + if ((curObj["TotalPowerOnHours"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["TotalPowerOnHours"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsTransitioningToStateNull { + get { + if ((curObj["TransitioningToState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort TransitioningToState { + get { + if ((curObj["TransitioningToState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["TransitioningToState"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsUsageRestrictionNull { + get { + if ((curObj["UsageRestriction"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort UsageRestriction { + get { + if ((curObj["UsageRestriction"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["UsageRestriction"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsVMQOffloadUsageNull { + get { + if ((curObj["VMQOffloadUsage"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The current VMQ offloading usage on this port. The usage is the amount of VMQ " + + "resources in use on the port.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint VMQOffloadUsage { + get { + if ((curObj["VMQOffloadUsage"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["VMQOffloadUsage"])); + } + } + + private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { + if (((path != null) + && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); + } + } + + private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { + if (((theObj != null) + && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); + if ((parentClasses != null)) { + int count = 0; + for (count = 0; (count < parentClasses.Length); count = (count + 1)) { + if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { + return true; + } + } + } + } + return false; + } + + private bool ShouldSerializeActiveMaximumTransmissionUnit() { + if ((this.IsActiveMaximumTransmissionUnitNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeAutoSense() { + if ((this.IsAutoSenseNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeAvailability() { + if ((this.IsAvailabilityNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeCommunicationStatus() { + if ((this.IsCommunicationStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeDetailedStatus() { + if ((this.IsDetailedStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeEnabledDefault() { + if ((this.IsEnabledDefaultNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeEnabledState() { + if ((this.IsEnabledStateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeErrorCleared() { + if ((this.IsErrorClearedNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeFullDuplex() { + if ((this.IsFullDuplexNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeHealthState() { + if ((this.IsHealthStateNull == false)) { + return true; + } + return false; + } + + // Converts a given datetime in DMTF format to System.DateTime object. + static System.DateTime ToDateTime(string dmtfDate) { + System.DateTime initializer = System.DateTime.MinValue; + int year = initializer.Year; + int month = initializer.Month; + int day = initializer.Day; + int hour = initializer.Hour; + int minute = initializer.Minute; + int second = initializer.Second; + long ticks = 0; + string dmtf = dmtfDate; + System.DateTime datetime = System.DateTime.MinValue; + string tempString = string.Empty; + if ((dmtf == null)) { + throw new System.ArgumentOutOfRangeException(); + } + if ((dmtf.Length == 0)) { + throw new System.ArgumentOutOfRangeException(); + } + if ((dmtf.Length != 25)) { + throw new System.ArgumentOutOfRangeException(); + } + try { + tempString = dmtf.Substring(0, 4); + if (("****" != tempString)) { + year = int.Parse(tempString); + } + tempString = dmtf.Substring(4, 2); + if (("**" != tempString)) { + month = int.Parse(tempString); + } + tempString = dmtf.Substring(6, 2); + if (("**" != tempString)) { + day = int.Parse(tempString); + } + tempString = dmtf.Substring(8, 2); + if (("**" != tempString)) { + hour = int.Parse(tempString); + } + tempString = dmtf.Substring(10, 2); + if (("**" != tempString)) { + minute = int.Parse(tempString); + } + tempString = dmtf.Substring(12, 2); + if (("**" != tempString)) { + second = int.Parse(tempString); + } + tempString = dmtf.Substring(15, 6); + if (("******" != tempString)) { + ticks = (long.Parse(tempString) * ((long)((System.TimeSpan.TicksPerMillisecond / 1000)))); + } + if (((((((((year < 0) + || (month < 0)) + || (day < 0)) + || (hour < 0)) + || (minute < 0)) + || (minute < 0)) + || (second < 0)) + || (ticks < 0))) { + throw new System.ArgumentOutOfRangeException(); + } + } + catch (System.Exception e) { + throw new System.ArgumentOutOfRangeException(null, e.Message); + } + datetime = new System.DateTime(year, month, day, hour, minute, second, 0); + datetime = datetime.AddTicks(ticks); + System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(datetime); + int UTCOffset = 0; + int OffsetToBeAdjusted = 0; + long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); + tempString = dmtf.Substring(22, 3); + if ((tempString != "******")) { + tempString = dmtf.Substring(21, 4); + try { + UTCOffset = int.Parse(tempString); + } + catch (System.Exception e) { + throw new System.ArgumentOutOfRangeException(null, e.Message); + } + OffsetToBeAdjusted = ((int)((OffsetMins - UTCOffset))); + datetime = datetime.AddMinutes(((double)(OffsetToBeAdjusted))); + } + return datetime; + } + + // Converts a given System.DateTime object to DMTF datetime format. + static string ToDmtfDateTime(System.DateTime date) { + string utcString = string.Empty; + System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(date); + long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); + if ((System.Math.Abs(OffsetMins) > 999)) { + date = date.ToUniversalTime(); + utcString = "+000"; + } + else { + if ((tickOffset.Ticks >= 0)) { + utcString = string.Concat("+", ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))).ToString().PadLeft(3, '0')); + } + else { + string strTemp = ((long)(OffsetMins)).ToString(); + utcString = string.Concat("-", strTemp.Substring(1, (strTemp.Length - 1)).PadLeft(3, '0')); + } + } + string dmtfDateTime = ((int)(date.Year)).ToString().PadLeft(4, '0'); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Month)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Day)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Hour)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Minute)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Second)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, "."); + System.DateTime dtTemp = new System.DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, 0); + long microsec = ((long)((((date.Ticks - dtTemp.Ticks) + * 1000) + / System.TimeSpan.TicksPerMillisecond))); + string strMicrosec = ((long)(microsec)).ToString(); + if ((strMicrosec.Length > 6)) { + strMicrosec = strMicrosec.Substring(0, 6); + } + dmtfDateTime = string.Concat(dmtfDateTime, strMicrosec.PadLeft(6, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, utcString); + return dmtfDateTime; + } + + private bool ShouldSerializeInstallDate() { + if ((this.IsInstallDateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeIOVOffloadUsage() { + if ((this.IsIOVOffloadUsageNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeLastErrorCode() { + if ((this.IsLastErrorCodeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeLinkTechnology() { + if ((this.IsLinkTechnologyNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeMaxDataSize() { + if ((this.IsMaxDataSizeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeMaxQuiesceTime() { + if ((this.IsMaxQuiesceTimeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeMaxSpeed() { + if ((this.IsMaxSpeedNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeOperatingStatus() { + if ((this.IsOperatingStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePortNumber() { + if ((this.IsPortNumberNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePortType() { + if ((this.IsPortTypeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePowerManagementSupported() { + if ((this.IsPowerManagementSupportedNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePowerOnHours() { + if ((this.IsPowerOnHoursNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePrimaryStatus() { + if ((this.IsPrimaryStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeRequestedSpeed() { + if ((this.IsRequestedSpeedNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeRequestedState() { + if ((this.IsRequestedStateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeSpeed() { + if ((this.IsSpeedNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeStatusInfo() { + if ((this.IsStatusInfoNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeSupportedMaximumTransmissionUnit() { + if ((this.IsSupportedMaximumTransmissionUnitNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeTimeOfLastStateChange() { + if ((this.IsTimeOfLastStateChangeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeTotalPowerOnHours() { + if ((this.IsTotalPowerOnHoursNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeTransitioningToState() { + if ((this.IsTransitioningToStateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeUsageRestriction() { + if ((this.IsUsageRestrictionNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeVMQOffloadUsage() { + if ((this.IsVMQOffloadUsageNull == false)) { + return true; + } + return false; + } + + [Browsable(true)] + public void CommitObject() { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(); + } + } + + [Browsable(true)] + public void CommitObject(System.Management.PutOptions putOptions) { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(putOptions); + } + } + + private void Initialize() { + AutoCommitProp = true; + isEmbedded = false; + } + + private static string ConstructPath(string keyCreationClassName, string keyDeviceID, string keySystemCreationClassName, string keySystemName) { + string strPath = "ROOT\\virtualization\\v2:Msvm_EthernetSwitchPort"; + strPath = string.Concat(strPath, string.Concat(".CreationClassName=", string.Concat("\"", string.Concat(keyCreationClassName, "\"")))); + strPath = string.Concat(strPath, string.Concat(",DeviceID=", string.Concat("\"", string.Concat(keyDeviceID, "\"")))); + strPath = string.Concat(strPath, string.Concat(",SystemCreationClassName=", string.Concat("\"", string.Concat(keySystemCreationClassName, "\"")))); + strPath = string.Concat(strPath, string.Concat(",SystemName=", string.Concat("\"", string.Concat(keySystemName, "\"")))); + return strPath; + } + + private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + Initialize(); + if ((path != null)) { + if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + } + PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + + // Different overloads of GetInstances() help in enumerating instances of the WMI class. + public static EthernetSwitchPortCollection GetInstances() { + return GetInstances(null, null, null); + } + + public static EthernetSwitchPortCollection GetInstances(string condition) { + return GetInstances(null, condition, null); + } + + public static EthernetSwitchPortCollection GetInstances(string[] selectedProperties) { + return GetInstances(null, null, selectedProperties); + } + + public static EthernetSwitchPortCollection GetInstances(string condition, string[] selectedProperties) { + return GetInstances(null, condition, selectedProperties); + } + + public static EthernetSwitchPortCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); + pathObj.ClassName = "Msvm_EthernetSwitchPort"; + pathObj.NamespacePath = "root\\virtualization\\v2"; + System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); + if ((enumOptions == null)) { + enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + } + return new EthernetSwitchPortCollection(clsObject.GetInstances(enumOptions)); + } + + public static EthernetSwitchPortCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { + return GetInstances(mgmtScope, condition, null); + } + + public static EthernetSwitchPortCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { + return GetInstances(mgmtScope, null, selectedProperties); + } + + public static EthernetSwitchPortCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_EthernetSwitchPort", condition, selectedProperties)); + System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + ObjectSearcher.Options = enumOptions; + return new EthernetSwitchPortCollection(ObjectSearcher.Get()); + } + + [Browsable(true)] + public static EthernetSwitchPort CreateInstance() { + System.Management.ManagementScope mgmtScope = null; + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = CreatedWmiNamespace; + } + else { + mgmtScope = statMgmtScope; + } + System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); + System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); + return new EthernetSwitchPort(tmpMgmtClass.CreateInstance()); + } + + [Browsable(true)] + public void Delete() { + PrivateLateBoundObject.Delete(); + } + + public uint EnableDevice(bool Enabled) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("EnableDevice"); + inParams["Enabled"] = ((bool)(Enabled)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("EnableDevice", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + public uint OnlineDevice(bool Online) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("OnlineDevice"); + inParams["Online"] = ((bool)(Online)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("OnlineDevice", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + public uint QuiesceDevice(bool Quiesce) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("QuiesceDevice"); + inParams["Quiesce"] = ((bool)(Quiesce)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("QuiesceDevice", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + public uint RequestStateChange(ushort RequestedState, System.DateTime TimeoutPeriod, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("RequestStateChange"); + inParams["RequestedState"] = ((ushort)(RequestedState)); + inParams["TimeoutPeriod"] = ToDmtfDateTime(((System.DateTime)(TimeoutPeriod))); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RequestStateChange", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null) && outParams.Properties["Job"].Value != null) { + Job = new System.Management.ManagementPath(outParams.Properties["Job"].Value.ToString()); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + return System.Convert.ToUInt32(0); + } + } + + public uint Reset() { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("Reset", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + public uint RestoreProperties() { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RestoreProperties", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + public uint SaveProperties() { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("SaveProperties", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + public uint SetPowerState(ushort PowerState, System.DateTime Time) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("SetPowerState"); + inParams["PowerState"] = ((ushort)(PowerState)); + inParams["Time"] = ToDmtfDateTime(((System.DateTime)(Time))); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("SetPowerState", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + // Enumerator implementation for enumerating instances of the class. + public class EthernetSwitchPortCollection : object, ICollection { + + private ManagementObjectCollection privColObj; + + public EthernetSwitchPortCollection(ManagementObjectCollection objCollection) { + privColObj = objCollection; + } + + public virtual int Count { + get { + return privColObj.Count; + } + } + + public virtual bool IsSynchronized { + get { + return privColObj.IsSynchronized; + } + } + + public virtual object SyncRoot { + get { + return this; + } + } + + public virtual void CopyTo(System.Array array, int index) { + privColObj.CopyTo(array, index); + int nCtr; + for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { + array.SetValue(new EthernetSwitchPort(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); + } + } + + public virtual System.Collections.IEnumerator GetEnumerator() { + return new EthernetSwitchPortEnumerator(privColObj.GetEnumerator()); + } + + public class EthernetSwitchPortEnumerator : object, System.Collections.IEnumerator { + + private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; + + public EthernetSwitchPortEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { + privObjEnum = objEnum; + } + + public virtual object Current { + get { + return new EthernetSwitchPort(((System.Management.ManagementObject)(privObjEnum.Current))); + } + } + + public virtual bool MoveNext() { + return privObjEnum.MoveNext(); + } + + public virtual void Reset() { + privObjEnum.Reset(); + } + } + } + + // TypeConverter to handle null values for ValueType properties + public class WMIValueTypeConverter : TypeConverter { + + private TypeConverter baseConverter; + + private System.Type baseType; + + public WMIValueTypeConverter(System.Type inBaseType) { + baseConverter = TypeDescriptor.GetConverter(inBaseType); + baseType = inBaseType; + } + + public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { + return baseConverter.CanConvertFrom(context, srcType); + } + + public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { + return baseConverter.CanConvertTo(context, destinationType); + } + + public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { + return baseConverter.ConvertFrom(context, culture, value); + } + + public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { + return baseConverter.CreateInstance(context, dictionary); + } + + public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetCreateInstanceSupported(context); + } + + public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { + return baseConverter.GetProperties(context, value, attributeVar); + } + + public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetPropertiesSupported(context); + } + + public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValues(context); + } + + public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesExclusive(context); + } + + public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesSupported(context); + } + + public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { + if ((baseType.BaseType == typeof(System.Enum))) { + if ((value.GetType() == destinationType)) { + return value; + } + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return "NULL_ENUM_VALUE" ; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((baseType == typeof(bool)) + && (baseType.BaseType == typeof(System.ValueType)))) { + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((context != null) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + } + + // Embedded class to represent WMI system Properties. + [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] + public class ManagementSystemProperties { + + private System.Management.ManagementBaseObject PrivateLateBoundObject; + + public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { + PrivateLateBoundObject = ManagedObject; + } + + [Browsable(true)] + public int GENUS { + get { + return ((int)(PrivateLateBoundObject["__GENUS"])); + } + } + + [Browsable(true)] + public string CLASS { + get { + return ((string)(PrivateLateBoundObject["__CLASS"])); + } + } + + [Browsable(true)] + public string SUPERCLASS { + get { + return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); + } + } + + [Browsable(true)] + public string DYNASTY { + get { + return ((string)(PrivateLateBoundObject["__DYNASTY"])); + } + } + + [Browsable(true)] + public string RELPATH { + get { + return ((string)(PrivateLateBoundObject["__RELPATH"])); + } + } + + [Browsable(true)] + public int PROPERTY_COUNT { + get { + return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); + } + } + + [Browsable(true)] + public string[] DERIVATION { + get { + return ((string[])(PrivateLateBoundObject["__DERIVATION"])); + } + } + + [Browsable(true)] + public string SERVER { + get { + return ((string)(PrivateLateBoundObject["__SERVER"])); + } + } + + [Browsable(true)] + public string NAMESPACE { + get { + return ((string)(PrivateLateBoundObject["__NAMESPACE"])); + } + } + + [Browsable(true)] + public string PATH { + get { + return ((string)(PrivateLateBoundObject["__PATH"])); + } + } + } + } +} diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_EthernetSwitchPortVlanSettingData.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_EthernetSwitchPortVlanSettingData.cs index 5418bec7f98..24cc7dbf41e 100644 --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_EthernetSwitchPortVlanSettingData.cs +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_EthernetSwitchPortVlanSettingData.cs @@ -1,1022 +1,1022 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2 { - using System; - using System.ComponentModel; - using System.Management; - using System.Collections; - using System.Globalization; - using System.ComponentModel.Design.Serialization; - using System.Reflection; - - - // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. - // Functions IsNull() are used to check if a property is NULL. - // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. - // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. - // An Early Bound class generated for the WMI class.Msvm_EthernetSwitchPortVlanSettingData - public class EthernetSwitchPortVlanSettingData : System.ComponentModel.Component { - - // Private property to hold the WMI namespace in which the class resides. - private static string CreatedWmiNamespace = "ROOT\\virtualization\\v2"; - - // Private property to hold the name of WMI class which created this class. - public static string CreatedClassName = "Msvm_EthernetSwitchPortVlanSettingData"; - - // Private member variable to hold the ManagementScope which is used by the various methods. - private static System.Management.ManagementScope statMgmtScope = null; - - private ManagementSystemProperties PrivateSystemProperties; - - // Underlying lateBound WMI object. - private System.Management.ManagementObject PrivateLateBoundObject; - - // Member variable to store the 'automatic commit' behavior for the class. - private bool AutoCommitProp; - - // Private variable to hold the embedded property representing the instance. - private System.Management.ManagementBaseObject embeddedObj; - - // The current WMI object used - private System.Management.ManagementBaseObject curObj; - - // Flag to indicate if the instance is an embedded object. - private bool isEmbedded; - - // Below are different overloads of constructors to initialize an instance of the class with a WMI object. - public EthernetSwitchPortVlanSettingData() { - this.InitializeObject(null, null, null); - } - - public EthernetSwitchPortVlanSettingData(string keyInstanceID) { - this.InitializeObject(null, new System.Management.ManagementPath(EthernetSwitchPortVlanSettingData.ConstructPath(keyInstanceID)), null); - } - - public EthernetSwitchPortVlanSettingData(System.Management.ManagementScope mgmtScope, string keyInstanceID) { - this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(EthernetSwitchPortVlanSettingData.ConstructPath(keyInstanceID)), null); - } - - public EthernetSwitchPortVlanSettingData(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(null, path, getOptions); - } - - public EthernetSwitchPortVlanSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { - this.InitializeObject(mgmtScope, path, null); - } - - public EthernetSwitchPortVlanSettingData(System.Management.ManagementPath path) { - this.InitializeObject(null, path, null); - } - - public EthernetSwitchPortVlanSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(mgmtScope, path, getOptions); - } - - public EthernetSwitchPortVlanSettingData(System.Management.ManagementObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - PrivateLateBoundObject = theObject; - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - public EthernetSwitchPortVlanSettingData(System.Management.ManagementBaseObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - embeddedObj = theObject; - PrivateSystemProperties = new ManagementSystemProperties(theObject); - curObj = embeddedObj; - isEmbedded = true; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - // Property returns the namespace of the WMI class. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OriginatingNamespace { - get { - return "ROOT\\virtualization\\v2"; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ManagementClassName { - get { - string strRet = CreatedClassName; - if ((curObj != null)) { - if ((curObj.ClassPath != null)) { - strRet = ((string)(curObj["__CLASS"])); - if (((strRet == null) - || (strRet == string.Empty))) { - strRet = CreatedClassName; - } - } - } - return strRet; - } - } - - // Property pointing to an embedded object to get System properties of the WMI object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ManagementSystemProperties SystemProperties { - get { - return PrivateSystemProperties; - } - } - - // Property returning the underlying lateBound object. - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementBaseObject LateBoundObject { - get { - return curObj; - } - } - - // ManagementScope of the object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementScope Scope { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Scope; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Scope = value; - } - } - } - - // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool AutoCommit { - get { - return AutoCommitProp; - } - set { - AutoCommitProp = value; - } - } - - // The ManagementPath of the underlying WMI object. - [Browsable(true)] - public System.Management.ManagementPath Path { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Path; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - if ((CheckIfProperClass(null, value, null) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - PrivateLateBoundObject.Path = value; - } - } - } - - // Public static scope property which is used by the various methods. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public static System.Management.ManagementScope StaticScope { - get { - return statMgmtScope; - } - set { - statMgmtScope = value; - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsAccessVlanIdNull { - get { - if ((curObj["AccessVlanId"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The vlan ID in access mode.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort AccessVlanId { - get { - if ((curObj["AccessVlanId"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["AccessVlanId"])); - } - set { - curObj["AccessVlanId"] = value; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Caption { - get { - return ((string)(curObj["Caption"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Description { - get { - return ((string)(curObj["Description"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ElementName { - get { - return ((string)(curObj["ElementName"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string InstanceID { - get { - return ((string)(curObj["InstanceID"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsNativeVlanIdNull { - get { - if ((curObj["NativeVlanId"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The vlan ID in trunk mode.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort NativeVlanId { - get { - if ((curObj["NativeVlanId"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["NativeVlanId"])); - } - set { - curObj["NativeVlanId"] = value; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsOperationModeNull { - get { - if ((curObj["OperationMode"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The vlan operation modes.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public OperationModeValues OperationMode { - get { - if ((curObj["OperationMode"] == null)) { - return ((OperationModeValues)(System.Convert.ToInt32(0))); - } - return ((OperationModeValues)(System.Convert.ToInt32(curObj["OperationMode"]))); - } - set { - if ((OperationModeValues.NULL_ENUM_VALUE == value)) { - curObj["OperationMode"] = null; - } - else { - curObj["OperationMode"] = value; - } - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsPrimaryVlanIdNull { - get { - if ((curObj["PrimaryVlanId"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The primary vlan ID in private mode.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort PrimaryVlanId { - get { - if ((curObj["PrimaryVlanId"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["PrimaryVlanId"])); - } - set { - curObj["PrimaryVlanId"] = value; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The prune vlan ID bitmap in trunk mode.")] - public ushort[] PruneVlanIdArray { - get { - return ((ushort[])(curObj["PruneVlanIdArray"])); - } - set { - curObj["PruneVlanIdArray"] = value; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsPvlanModeNull { - get { - if ((curObj["PvlanMode"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The private vlan modes.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public PvlanModeValues PvlanMode { - get { - if ((curObj["PvlanMode"] == null)) { - return ((PvlanModeValues)(System.Convert.ToInt32(0))); - } - return ((PvlanModeValues)(System.Convert.ToInt32(curObj["PvlanMode"]))); - } - set { - if ((PvlanModeValues.NULL_ENUM_VALUE == value)) { - curObj["PvlanMode"] = null; - } - else { - curObj["PvlanMode"] = value; - } - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsSecondaryVlanIdNull { - get { - if ((curObj["SecondaryVlanId"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The secondary vlan ID in private mode.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort SecondaryVlanId { - get { - if ((curObj["SecondaryVlanId"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["SecondaryVlanId"])); - } - set { - curObj["SecondaryVlanId"] = value; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The secondary vlan ID bitmap in private mode.")] - public ushort[] SecondaryVlanIdArray { - get { - return ((ushort[])(curObj["SecondaryVlanIdArray"])); - } - set { - curObj["SecondaryVlanIdArray"] = value; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The trunk vlan ID bitmap in trunk mode.")] - public ushort[] TrunkVlanIdArray { - get { - return ((ushort[])(curObj["TrunkVlanIdArray"])); - } - set { - curObj["TrunkVlanIdArray"] = value; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - } - - private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { - if (((path != null) - && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); - } - } - - private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { - if (((theObj != null) - && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); - if ((parentClasses != null)) { - int count = 0; - for (count = 0; (count < parentClasses.Length); count = (count + 1)) { - if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { - return true; - } - } - } - } - return false; - } - - private bool ShouldSerializeAccessVlanId() { - if ((this.IsAccessVlanIdNull == false)) { - return true; - } - return false; - } - - private void ResetAccessVlanId() { - curObj["AccessVlanId"] = null; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - - private bool ShouldSerializeNativeVlanId() { - if ((this.IsNativeVlanIdNull == false)) { - return true; - } - return false; - } - - private void ResetNativeVlanId() { - curObj["NativeVlanId"] = null; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - - private bool ShouldSerializeOperationMode() { - if ((this.IsOperationModeNull == false)) { - return true; - } - return false; - } - - private void ResetOperationMode() { - curObj["OperationMode"] = null; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - - private bool ShouldSerializePrimaryVlanId() { - if ((this.IsPrimaryVlanIdNull == false)) { - return true; - } - return false; - } - - private void ResetPrimaryVlanId() { - curObj["PrimaryVlanId"] = null; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - - private void ResetPruneVlanIdArray() { - curObj["PruneVlanIdArray"] = null; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - - private bool ShouldSerializePvlanMode() { - if ((this.IsPvlanModeNull == false)) { - return true; - } - return false; - } - - private void ResetPvlanMode() { - curObj["PvlanMode"] = null; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - - private bool ShouldSerializeSecondaryVlanId() { - if ((this.IsSecondaryVlanIdNull == false)) { - return true; - } - return false; - } - - private void ResetSecondaryVlanId() { - curObj["SecondaryVlanId"] = null; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - - private void ResetSecondaryVlanIdArray() { - curObj["SecondaryVlanIdArray"] = null; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - - private void ResetTrunkVlanIdArray() { - curObj["TrunkVlanIdArray"] = null; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - - [Browsable(true)] - public void CommitObject() { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(); - } - } - - [Browsable(true)] - public void CommitObject(System.Management.PutOptions putOptions) { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(putOptions); - } - } - - private void Initialize() { - AutoCommitProp = true; - isEmbedded = false; - } - - private static string ConstructPath(string keyInstanceID) { - string strPath = "ROOT\\virtualization\\v2:Msvm_EthernetSwitchPortVlanSettingData"; - strPath = string.Concat(strPath, string.Concat(".InstanceID=", string.Concat("\"", string.Concat(keyInstanceID, "\"")))); - return strPath; - } - - private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - Initialize(); - if ((path != null)) { - if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - } - PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - - // Different overloads of GetInstances() help in enumerating instances of the WMI class. - public static EthernetSwitchPortVlanSettingDataCollection GetInstances() { - return GetInstances(null, null, null); - } - - public static EthernetSwitchPortVlanSettingDataCollection GetInstances(string condition) { - return GetInstances(null, condition, null); - } - - public static EthernetSwitchPortVlanSettingDataCollection GetInstances(string[] selectedProperties) { - return GetInstances(null, null, selectedProperties); - } - - public static EthernetSwitchPortVlanSettingDataCollection GetInstances(string condition, string[] selectedProperties) { - return GetInstances(null, condition, selectedProperties); - } - - public static EthernetSwitchPortVlanSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); - pathObj.ClassName = "Msvm_EthernetSwitchPortVlanSettingData"; - pathObj.NamespacePath = "root\\virtualization\\v2"; - System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); - if ((enumOptions == null)) { - enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - } - return new EthernetSwitchPortVlanSettingDataCollection(clsObject.GetInstances(enumOptions)); - } - - public static EthernetSwitchPortVlanSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { - return GetInstances(mgmtScope, condition, null); - } - - public static EthernetSwitchPortVlanSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { - return GetInstances(mgmtScope, null, selectedProperties); - } - - public static EthernetSwitchPortVlanSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_EthernetSwitchPortVlanSettingData", condition, selectedProperties)); - System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - ObjectSearcher.Options = enumOptions; - return new EthernetSwitchPortVlanSettingDataCollection(ObjectSearcher.Get()); - } - - [Browsable(true)] - public static EthernetSwitchPortVlanSettingData CreateInstance() { - System.Management.ManagementScope mgmtScope = null; - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = CreatedWmiNamespace; - } - else { - mgmtScope = statMgmtScope; - } - System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); - System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); - return new EthernetSwitchPortVlanSettingData(tmpMgmtClass.CreateInstance()); - } - - [Browsable(true)] - public void Delete() { - PrivateLateBoundObject.Delete(); - } - - public enum OperationModeValues { - - Access = 1, - - Trunk = 2, - - Private = 3, - - NULL_ENUM_VALUE = 0, - } - - public enum PvlanModeValues { - - Isolated = 1, - - Community = 2, - - Promiscuous = 3, - - NULL_ENUM_VALUE = 0, - } - - // Enumerator implementation for enumerating instances of the class. - public class EthernetSwitchPortVlanSettingDataCollection : object, ICollection { - - private ManagementObjectCollection privColObj; - - public EthernetSwitchPortVlanSettingDataCollection(ManagementObjectCollection objCollection) { - privColObj = objCollection; - } - - public virtual int Count { - get { - return privColObj.Count; - } - } - - public virtual bool IsSynchronized { - get { - return privColObj.IsSynchronized; - } - } - - public virtual object SyncRoot { - get { - return this; - } - } - - public virtual void CopyTo(System.Array array, int index) { - privColObj.CopyTo(array, index); - int nCtr; - for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { - array.SetValue(new EthernetSwitchPortVlanSettingData(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); - } - } - - public virtual System.Collections.IEnumerator GetEnumerator() { - return new EthernetSwitchPortVlanSettingDataEnumerator(privColObj.GetEnumerator()); - } - - public class EthernetSwitchPortVlanSettingDataEnumerator : object, System.Collections.IEnumerator { - - private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; - - public EthernetSwitchPortVlanSettingDataEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { - privObjEnum = objEnum; - } - - public virtual object Current { - get { - return new EthernetSwitchPortVlanSettingData(((System.Management.ManagementObject)(privObjEnum.Current))); - } - } - - public virtual bool MoveNext() { - return privObjEnum.MoveNext(); - } - - public virtual void Reset() { - privObjEnum.Reset(); - } - } - } - - // TypeConverter to handle null values for ValueType properties - public class WMIValueTypeConverter : TypeConverter { - - private TypeConverter baseConverter; - - private System.Type baseType; - - public WMIValueTypeConverter(System.Type inBaseType) { - baseConverter = TypeDescriptor.GetConverter(inBaseType); - baseType = inBaseType; - } - - public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { - return baseConverter.CanConvertFrom(context, srcType); - } - - public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { - return baseConverter.CanConvertTo(context, destinationType); - } - - public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { - return baseConverter.ConvertFrom(context, culture, value); - } - - public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { - return baseConverter.CreateInstance(context, dictionary); - } - - public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetCreateInstanceSupported(context); - } - - public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { - return baseConverter.GetProperties(context, value, attributeVar); - } - - public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetPropertiesSupported(context); - } - - public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValues(context); - } - - public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesExclusive(context); - } - - public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesSupported(context); - } - - public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { - if ((baseType.BaseType == typeof(System.Enum))) { - if ((value.GetType() == destinationType)) { - return value; - } - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return "NULL_ENUM_VALUE" ; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((baseType == typeof(bool)) - && (baseType.BaseType == typeof(System.ValueType)))) { - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((context != null) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - } - - // Embedded class to represent WMI system Properties. - [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] - public class ManagementSystemProperties { - - private System.Management.ManagementBaseObject PrivateLateBoundObject; - - public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { - PrivateLateBoundObject = ManagedObject; - } - - [Browsable(true)] - public int GENUS { - get { - return ((int)(PrivateLateBoundObject["__GENUS"])); - } - } - - [Browsable(true)] - public string CLASS { - get { - return ((string)(PrivateLateBoundObject["__CLASS"])); - } - } - - [Browsable(true)] - public string SUPERCLASS { - get { - return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); - } - } - - [Browsable(true)] - public string DYNASTY { - get { - return ((string)(PrivateLateBoundObject["__DYNASTY"])); - } - } - - [Browsable(true)] - public string RELPATH { - get { - return ((string)(PrivateLateBoundObject["__RELPATH"])); - } - } - - [Browsable(true)] - public int PROPERTY_COUNT { - get { - return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); - } - } - - [Browsable(true)] - public string[] DERIVATION { - get { - return ((string[])(PrivateLateBoundObject["__DERIVATION"])); - } - } - - [Browsable(true)] - public string SERVER { - get { - return ((string)(PrivateLateBoundObject["__SERVER"])); - } - } - - [Browsable(true)] - public string NAMESPACE { - get { - return ((string)(PrivateLateBoundObject["__NAMESPACE"])); - } - } - - [Browsable(true)] - public string PATH { - get { - return ((string)(PrivateLateBoundObject["__PATH"])); - } - } - } - } -} +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2 { + using System; + using System.ComponentModel; + using System.Management; + using System.Collections; + using System.Globalization; + using System.ComponentModel.Design.Serialization; + using System.Reflection; + + + // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. + // Functions IsNull() are used to check if a property is NULL. + // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. + // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. + // An Early Bound class generated for the WMI class.Msvm_EthernetSwitchPortVlanSettingData + public class EthernetSwitchPortVlanSettingData : System.ComponentModel.Component { + + // Private property to hold the WMI namespace in which the class resides. + private static string CreatedWmiNamespace = "ROOT\\virtualization\\v2"; + + // Private property to hold the name of WMI class which created this class. + public static string CreatedClassName = "Msvm_EthernetSwitchPortVlanSettingData"; + + // Private member variable to hold the ManagementScope which is used by the various methods. + private static System.Management.ManagementScope statMgmtScope = null; + + private ManagementSystemProperties PrivateSystemProperties; + + // Underlying lateBound WMI object. + private System.Management.ManagementObject PrivateLateBoundObject; + + // Member variable to store the 'automatic commit' behavior for the class. + private bool AutoCommitProp; + + // Private variable to hold the embedded property representing the instance. + private System.Management.ManagementBaseObject embeddedObj; + + // The current WMI object used + private System.Management.ManagementBaseObject curObj; + + // Flag to indicate if the instance is an embedded object. + private bool isEmbedded; + + // Below are different overloads of constructors to initialize an instance of the class with a WMI object. + public EthernetSwitchPortVlanSettingData() { + this.InitializeObject(null, null, null); + } + + public EthernetSwitchPortVlanSettingData(string keyInstanceID) { + this.InitializeObject(null, new System.Management.ManagementPath(EthernetSwitchPortVlanSettingData.ConstructPath(keyInstanceID)), null); + } + + public EthernetSwitchPortVlanSettingData(System.Management.ManagementScope mgmtScope, string keyInstanceID) { + this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(EthernetSwitchPortVlanSettingData.ConstructPath(keyInstanceID)), null); + } + + public EthernetSwitchPortVlanSettingData(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(null, path, getOptions); + } + + public EthernetSwitchPortVlanSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { + this.InitializeObject(mgmtScope, path, null); + } + + public EthernetSwitchPortVlanSettingData(System.Management.ManagementPath path) { + this.InitializeObject(null, path, null); + } + + public EthernetSwitchPortVlanSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(mgmtScope, path, getOptions); + } + + public EthernetSwitchPortVlanSettingData(System.Management.ManagementObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + PrivateLateBoundObject = theObject; + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + public EthernetSwitchPortVlanSettingData(System.Management.ManagementBaseObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + embeddedObj = theObject; + PrivateSystemProperties = new ManagementSystemProperties(theObject); + curObj = embeddedObj; + isEmbedded = true; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + // Property returns the namespace of the WMI class. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OriginatingNamespace { + get { + return "ROOT\\virtualization\\v2"; + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ManagementClassName { + get { + string strRet = CreatedClassName; + if ((curObj != null)) { + if ((curObj.ClassPath != null)) { + strRet = ((string)(curObj["__CLASS"])); + if (((strRet == null) + || (strRet == string.Empty))) { + strRet = CreatedClassName; + } + } + } + return strRet; + } + } + + // Property pointing to an embedded object to get System properties of the WMI object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ManagementSystemProperties SystemProperties { + get { + return PrivateSystemProperties; + } + } + + // Property returning the underlying lateBound object. + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementBaseObject LateBoundObject { + get { + return curObj; + } + } + + // ManagementScope of the object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementScope Scope { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Scope; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Scope = value; + } + } + } + + // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool AutoCommit { + get { + return AutoCommitProp; + } + set { + AutoCommitProp = value; + } + } + + // The ManagementPath of the underlying WMI object. + [Browsable(true)] + public System.Management.ManagementPath Path { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Path; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + if ((CheckIfProperClass(null, value, null) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + PrivateLateBoundObject.Path = value; + } + } + } + + // Public static scope property which is used by the various methods. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public static System.Management.ManagementScope StaticScope { + get { + return statMgmtScope; + } + set { + statMgmtScope = value; + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAccessVlanIdNull { + get { + if ((curObj["AccessVlanId"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The vlan ID in access mode.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort AccessVlanId { + get { + if ((curObj["AccessVlanId"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["AccessVlanId"])); + } + set { + curObj["AccessVlanId"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Caption { + get { + return ((string)(curObj["Caption"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Description { + get { + return ((string)(curObj["Description"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ElementName { + get { + return ((string)(curObj["ElementName"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string InstanceID { + get { + return ((string)(curObj["InstanceID"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsNativeVlanIdNull { + get { + if ((curObj["NativeVlanId"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The vlan ID in trunk mode.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort NativeVlanId { + get { + if ((curObj["NativeVlanId"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["NativeVlanId"])); + } + set { + curObj["NativeVlanId"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsOperationModeNull { + get { + if ((curObj["OperationMode"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The vlan operation modes.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public OperationModeValues OperationMode { + get { + if ((curObj["OperationMode"] == null)) { + return ((OperationModeValues)(System.Convert.ToInt32(0))); + } + return ((OperationModeValues)(System.Convert.ToInt32(curObj["OperationMode"]))); + } + set { + if ((OperationModeValues.NULL_ENUM_VALUE == value)) { + curObj["OperationMode"] = null; + } + else { + curObj["OperationMode"] = value; + } + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPrimaryVlanIdNull { + get { + if ((curObj["PrimaryVlanId"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The primary vlan ID in private mode.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort PrimaryVlanId { + get { + if ((curObj["PrimaryVlanId"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["PrimaryVlanId"])); + } + set { + curObj["PrimaryVlanId"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The prune vlan ID bitmap in trunk mode.")] + public ushort[] PruneVlanIdArray { + get { + return ((ushort[])(curObj["PruneVlanIdArray"])); + } + set { + curObj["PruneVlanIdArray"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPvlanModeNull { + get { + if ((curObj["PvlanMode"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The private vlan modes.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public PvlanModeValues PvlanMode { + get { + if ((curObj["PvlanMode"] == null)) { + return ((PvlanModeValues)(System.Convert.ToInt32(0))); + } + return ((PvlanModeValues)(System.Convert.ToInt32(curObj["PvlanMode"]))); + } + set { + if ((PvlanModeValues.NULL_ENUM_VALUE == value)) { + curObj["PvlanMode"] = null; + } + else { + curObj["PvlanMode"] = value; + } + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsSecondaryVlanIdNull { + get { + if ((curObj["SecondaryVlanId"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The secondary vlan ID in private mode.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort SecondaryVlanId { + get { + if ((curObj["SecondaryVlanId"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["SecondaryVlanId"])); + } + set { + curObj["SecondaryVlanId"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The secondary vlan ID bitmap in private mode.")] + public ushort[] SecondaryVlanIdArray { + get { + return ((ushort[])(curObj["SecondaryVlanIdArray"])); + } + set { + curObj["SecondaryVlanIdArray"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The trunk vlan ID bitmap in trunk mode.")] + public ushort[] TrunkVlanIdArray { + get { + return ((ushort[])(curObj["TrunkVlanIdArray"])); + } + set { + curObj["TrunkVlanIdArray"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { + if (((path != null) + && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); + } + } + + private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { + if (((theObj != null) + && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); + if ((parentClasses != null)) { + int count = 0; + for (count = 0; (count < parentClasses.Length); count = (count + 1)) { + if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { + return true; + } + } + } + } + return false; + } + + private bool ShouldSerializeAccessVlanId() { + if ((this.IsAccessVlanIdNull == false)) { + return true; + } + return false; + } + + private void ResetAccessVlanId() { + curObj["AccessVlanId"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private bool ShouldSerializeNativeVlanId() { + if ((this.IsNativeVlanIdNull == false)) { + return true; + } + return false; + } + + private void ResetNativeVlanId() { + curObj["NativeVlanId"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private bool ShouldSerializeOperationMode() { + if ((this.IsOperationModeNull == false)) { + return true; + } + return false; + } + + private void ResetOperationMode() { + curObj["OperationMode"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private bool ShouldSerializePrimaryVlanId() { + if ((this.IsPrimaryVlanIdNull == false)) { + return true; + } + return false; + } + + private void ResetPrimaryVlanId() { + curObj["PrimaryVlanId"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private void ResetPruneVlanIdArray() { + curObj["PruneVlanIdArray"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private bool ShouldSerializePvlanMode() { + if ((this.IsPvlanModeNull == false)) { + return true; + } + return false; + } + + private void ResetPvlanMode() { + curObj["PvlanMode"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private bool ShouldSerializeSecondaryVlanId() { + if ((this.IsSecondaryVlanIdNull == false)) { + return true; + } + return false; + } + + private void ResetSecondaryVlanId() { + curObj["SecondaryVlanId"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private void ResetSecondaryVlanIdArray() { + curObj["SecondaryVlanIdArray"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private void ResetTrunkVlanIdArray() { + curObj["TrunkVlanIdArray"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + [Browsable(true)] + public void CommitObject() { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(); + } + } + + [Browsable(true)] + public void CommitObject(System.Management.PutOptions putOptions) { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(putOptions); + } + } + + private void Initialize() { + AutoCommitProp = true; + isEmbedded = false; + } + + private static string ConstructPath(string keyInstanceID) { + string strPath = "ROOT\\virtualization\\v2:Msvm_EthernetSwitchPortVlanSettingData"; + strPath = string.Concat(strPath, string.Concat(".InstanceID=", string.Concat("\"", string.Concat(keyInstanceID, "\"")))); + return strPath; + } + + private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + Initialize(); + if ((path != null)) { + if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + } + PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + + // Different overloads of GetInstances() help in enumerating instances of the WMI class. + public static EthernetSwitchPortVlanSettingDataCollection GetInstances() { + return GetInstances(null, null, null); + } + + public static EthernetSwitchPortVlanSettingDataCollection GetInstances(string condition) { + return GetInstances(null, condition, null); + } + + public static EthernetSwitchPortVlanSettingDataCollection GetInstances(string[] selectedProperties) { + return GetInstances(null, null, selectedProperties); + } + + public static EthernetSwitchPortVlanSettingDataCollection GetInstances(string condition, string[] selectedProperties) { + return GetInstances(null, condition, selectedProperties); + } + + public static EthernetSwitchPortVlanSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); + pathObj.ClassName = "Msvm_EthernetSwitchPortVlanSettingData"; + pathObj.NamespacePath = "root\\virtualization\\v2"; + System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); + if ((enumOptions == null)) { + enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + } + return new EthernetSwitchPortVlanSettingDataCollection(clsObject.GetInstances(enumOptions)); + } + + public static EthernetSwitchPortVlanSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { + return GetInstances(mgmtScope, condition, null); + } + + public static EthernetSwitchPortVlanSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { + return GetInstances(mgmtScope, null, selectedProperties); + } + + public static EthernetSwitchPortVlanSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_EthernetSwitchPortVlanSettingData", condition, selectedProperties)); + System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + ObjectSearcher.Options = enumOptions; + return new EthernetSwitchPortVlanSettingDataCollection(ObjectSearcher.Get()); + } + + [Browsable(true)] + public static EthernetSwitchPortVlanSettingData CreateInstance() { + System.Management.ManagementScope mgmtScope = null; + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = CreatedWmiNamespace; + } + else { + mgmtScope = statMgmtScope; + } + System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); + System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); + return new EthernetSwitchPortVlanSettingData(tmpMgmtClass.CreateInstance()); + } + + [Browsable(true)] + public void Delete() { + PrivateLateBoundObject.Delete(); + } + + public enum OperationModeValues { + + Access = 1, + + Trunk = 2, + + Private = 3, + + NULL_ENUM_VALUE = 0, + } + + public enum PvlanModeValues { + + Isolated = 1, + + Community = 2, + + Promiscuous = 3, + + NULL_ENUM_VALUE = 0, + } + + // Enumerator implementation for enumerating instances of the class. + public class EthernetSwitchPortVlanSettingDataCollection : object, ICollection { + + private ManagementObjectCollection privColObj; + + public EthernetSwitchPortVlanSettingDataCollection(ManagementObjectCollection objCollection) { + privColObj = objCollection; + } + + public virtual int Count { + get { + return privColObj.Count; + } + } + + public virtual bool IsSynchronized { + get { + return privColObj.IsSynchronized; + } + } + + public virtual object SyncRoot { + get { + return this; + } + } + + public virtual void CopyTo(System.Array array, int index) { + privColObj.CopyTo(array, index); + int nCtr; + for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { + array.SetValue(new EthernetSwitchPortVlanSettingData(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); + } + } + + public virtual System.Collections.IEnumerator GetEnumerator() { + return new EthernetSwitchPortVlanSettingDataEnumerator(privColObj.GetEnumerator()); + } + + public class EthernetSwitchPortVlanSettingDataEnumerator : object, System.Collections.IEnumerator { + + private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; + + public EthernetSwitchPortVlanSettingDataEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { + privObjEnum = objEnum; + } + + public virtual object Current { + get { + return new EthernetSwitchPortVlanSettingData(((System.Management.ManagementObject)(privObjEnum.Current))); + } + } + + public virtual bool MoveNext() { + return privObjEnum.MoveNext(); + } + + public virtual void Reset() { + privObjEnum.Reset(); + } + } + } + + // TypeConverter to handle null values for ValueType properties + public class WMIValueTypeConverter : TypeConverter { + + private TypeConverter baseConverter; + + private System.Type baseType; + + public WMIValueTypeConverter(System.Type inBaseType) { + baseConverter = TypeDescriptor.GetConverter(inBaseType); + baseType = inBaseType; + } + + public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { + return baseConverter.CanConvertFrom(context, srcType); + } + + public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { + return baseConverter.CanConvertTo(context, destinationType); + } + + public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { + return baseConverter.ConvertFrom(context, culture, value); + } + + public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { + return baseConverter.CreateInstance(context, dictionary); + } + + public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetCreateInstanceSupported(context); + } + + public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { + return baseConverter.GetProperties(context, value, attributeVar); + } + + public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetPropertiesSupported(context); + } + + public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValues(context); + } + + public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesExclusive(context); + } + + public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesSupported(context); + } + + public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { + if ((baseType.BaseType == typeof(System.Enum))) { + if ((value.GetType() == destinationType)) { + return value; + } + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return "NULL_ENUM_VALUE" ; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((baseType == typeof(bool)) + && (baseType.BaseType == typeof(System.ValueType)))) { + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((context != null) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + } + + // Embedded class to represent WMI system Properties. + [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] + public class ManagementSystemProperties { + + private System.Management.ManagementBaseObject PrivateLateBoundObject; + + public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { + PrivateLateBoundObject = ManagedObject; + } + + [Browsable(true)] + public int GENUS { + get { + return ((int)(PrivateLateBoundObject["__GENUS"])); + } + } + + [Browsable(true)] + public string CLASS { + get { + return ((string)(PrivateLateBoundObject["__CLASS"])); + } + } + + [Browsable(true)] + public string SUPERCLASS { + get { + return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); + } + } + + [Browsable(true)] + public string DYNASTY { + get { + return ((string)(PrivateLateBoundObject["__DYNASTY"])); + } + } + + [Browsable(true)] + public string RELPATH { + get { + return ((string)(PrivateLateBoundObject["__RELPATH"])); + } + } + + [Browsable(true)] + public int PROPERTY_COUNT { + get { + return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); + } + } + + [Browsable(true)] + public string[] DERIVATION { + get { + return ((string[])(PrivateLateBoundObject["__DERIVATION"])); + } + } + + [Browsable(true)] + public string SERVER { + get { + return ((string)(PrivateLateBoundObject["__SERVER"])); + } + } + + [Browsable(true)] + public string NAMESPACE { + get { + return ((string)(PrivateLateBoundObject["__NAMESPACE"])); + } + } + + [Browsable(true)] + public string PATH { + get { + return ((string)(PrivateLateBoundObject["__PATH"])); + } + } + } + } +} diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_ExternalEthernetPort.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_ExternalEthernetPort.cs index c5138852547..801aa9e7dd7 100644 --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_ExternalEthernetPort.cs +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_ExternalEthernetPort.cs @@ -1,2087 +1,2086 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2 { - using System; - using System.ComponentModel; - using System.Management; - using System.Collections; - using System.Globalization; - using System.ComponentModel.Design.Serialization; - using System.Reflection; - - - // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. - // Functions IsNull() are used to check if a property is NULL. - // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. - // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. - // Datetime conversion functions ToDateTime and ToDmtfDateTime are added to the class to convert DMTF datetime to System.DateTime and vice-versa. - // An Early Bound class generated for the WMI class.Msvm_ExternalEthernetPort - public class ExternalEthernetPort : System.ComponentModel.Component { - - // Private property to hold the WMI namespace in which the class resides. - private static string CreatedWmiNamespace = "ROOT\\virtualization\\v2"; - - // Private property to hold the name of WMI class which created this class. - private static string CreatedClassName = "Msvm_ExternalEthernetPort"; - - // Private member variable to hold the ManagementScope which is used by the various methods. - private static System.Management.ManagementScope statMgmtScope = null; - - private ManagementSystemProperties PrivateSystemProperties; - - // Underlying lateBound WMI object. - private System.Management.ManagementObject PrivateLateBoundObject; - - // Member variable to store the 'automatic commit' behavior for the class. - private bool AutoCommitProp; - - // Private variable to hold the embedded property representing the instance. - private System.Management.ManagementBaseObject embeddedObj; - - // The current WMI object used - private System.Management.ManagementBaseObject curObj; - - // Flag to indicate if the instance is an embedded object. - private bool isEmbedded; - - // Below are different overloads of constructors to initialize an instance of the class with a WMI object. - public ExternalEthernetPort() { - this.InitializeObject(null, null, null); - } - - public ExternalEthernetPort(string keyCreationClassName, string keyDeviceID, string keySystemCreationClassName, string keySystemName) { - this.InitializeObject(null, new System.Management.ManagementPath(ExternalEthernetPort.ConstructPath(keyCreationClassName, keyDeviceID, keySystemCreationClassName, keySystemName)), null); - } - - public ExternalEthernetPort(System.Management.ManagementScope mgmtScope, string keyCreationClassName, string keyDeviceID, string keySystemCreationClassName, string keySystemName) { - this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(ExternalEthernetPort.ConstructPath(keyCreationClassName, keyDeviceID, keySystemCreationClassName, keySystemName)), null); - } - - public ExternalEthernetPort(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(null, path, getOptions); - } - - public ExternalEthernetPort(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { - this.InitializeObject(mgmtScope, path, null); - } - - public ExternalEthernetPort(System.Management.ManagementPath path) { - this.InitializeObject(null, path, null); - } - - public ExternalEthernetPort(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(mgmtScope, path, getOptions); - } - - public ExternalEthernetPort(System.Management.ManagementObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - PrivateLateBoundObject = theObject; - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - public ExternalEthernetPort(System.Management.ManagementBaseObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - embeddedObj = theObject; - PrivateSystemProperties = new ManagementSystemProperties(theObject); - curObj = embeddedObj; - isEmbedded = true; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - // Property returns the namespace of the WMI class. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OriginatingNamespace { - get { - return "ROOT\\virtualization\\v2"; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ManagementClassName { - get { - string strRet = CreatedClassName; - if ((curObj != null)) { - if ((curObj.ClassPath != null)) { - strRet = ((string)(curObj["__CLASS"])); - if (((strRet == null) - || (strRet == string.Empty))) { - strRet = CreatedClassName; - } - } - } - return strRet; - } - } - - // Property pointing to an embedded object to get System properties of the WMI object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ManagementSystemProperties SystemProperties { - get { - return PrivateSystemProperties; - } - } - - // Property returning the underlying lateBound object. - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementBaseObject LateBoundObject { - get { - return curObj; - } - } - - // ManagementScope of the object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementScope Scope { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Scope; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Scope = value; - } - } - } - - // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool AutoCommit { - get { - return AutoCommitProp; - } - set { - AutoCommitProp = value; - } - } - - // The ManagementPath of the underlying WMI object. - [Browsable(true)] - public System.Management.ManagementPath Path { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Path; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - if ((CheckIfProperClass(null, value, null) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - PrivateLateBoundObject.Path = value; - } - } - } - - // Public static scope property which is used by the various methods. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public static System.Management.ManagementScope StaticScope { - get { - return statMgmtScope; - } - set { - statMgmtScope = value; - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsActiveMaximumTransmissionUnitNull { - get { - if ((curObj["ActiveMaximumTransmissionUnit"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong ActiveMaximumTransmissionUnit { - get { - if ((curObj["ActiveMaximumTransmissionUnit"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["ActiveMaximumTransmissionUnit"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ushort[] AdditionalAvailability { - get { - return ((ushort[])(curObj["AdditionalAvailability"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsAutoSenseNull { - get { - if ((curObj["AutoSense"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool AutoSense { - get { - if ((curObj["AutoSense"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["AutoSense"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsAvailabilityNull { - get { - if ((curObj["Availability"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort Availability { - get { - if ((curObj["Availability"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["Availability"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ushort[] AvailableRequestedStates { - get { - return ((ushort[])(curObj["AvailableRequestedStates"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ushort[] Capabilities { - get { - return ((ushort[])(curObj["Capabilities"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] CapabilityDescriptions { - get { - return ((string[])(curObj["CapabilityDescriptions"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Caption { - get { - return ((string)(curObj["Caption"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsCommunicationStatusNull { - get { - if ((curObj["CommunicationStatus"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort CommunicationStatus { - get { - if ((curObj["CommunicationStatus"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["CommunicationStatus"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string CreationClassName { - get { - return ((string)(curObj["CreationClassName"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Description { - get { - return ((string)(curObj["Description"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsDetailedStatusNull { - get { - if ((curObj["DetailedStatus"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort DetailedStatus { - get { - if ((curObj["DetailedStatus"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["DetailedStatus"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string DeviceID { - get { - return ((string)(curObj["DeviceID"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ElementName { - get { - return ((string)(curObj["ElementName"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ushort[] EnabledCapabilities { - get { - return ((ushort[])(curObj["EnabledCapabilities"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsEnabledDefaultNull { - get { - if ((curObj["EnabledDefault"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort EnabledDefault { - get { - if ((curObj["EnabledDefault"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["EnabledDefault"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsEnabledStateNull { - get { - if ((curObj["EnabledState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort EnabledState { - get { - if ((curObj["EnabledState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["EnabledState"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsErrorClearedNull { - get { - if ((curObj["ErrorCleared"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool ErrorCleared { - get { - if ((curObj["ErrorCleared"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["ErrorCleared"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ErrorDescription { - get { - return ((string)(curObj["ErrorDescription"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsFullDuplexNull { - get { - if ((curObj["FullDuplex"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool FullDuplex { - get { - if ((curObj["FullDuplex"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["FullDuplex"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsHealthStateNull { - get { - if ((curObj["HealthState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort HealthState { - get { - if ((curObj["HealthState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["HealthState"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] IdentifyingDescriptions { - get { - return ((string[])(curObj["IdentifyingDescriptions"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsInstallDateNull { - get { - if ((curObj["InstallDate"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public System.DateTime InstallDate { - get { - if ((curObj["InstallDate"] != null)) { - return ToDateTime(((string)(curObj["InstallDate"]))); - } - else { - return System.DateTime.MinValue; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string InstanceID { - get { - return ((string)(curObj["InstanceID"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsIsBoundNull { - get { - if ((curObj["IsBound"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("If this property is true, then this Ethernet port can be connected to the switche" + - "s and thus can provide connectivity to virtual machine. If this property is fals" + - "e, then this Ethernet is not being used by the virtual machine networking archit" + - "ecture.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool IsBound { - get { - if ((curObj["IsBound"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["IsBound"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsLastErrorCodeNull { - get { - if ((curObj["LastErrorCode"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public uint LastErrorCode { - get { - if ((curObj["LastErrorCode"] == null)) { - return System.Convert.ToUInt32(0); - } - return ((uint)(curObj["LastErrorCode"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsLinkTechnologyNull { - get { - if ((curObj["LinkTechnology"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort LinkTechnology { - get { - if ((curObj["LinkTechnology"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["LinkTechnology"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsMaxDataSizeNull { - get { - if ((curObj["MaxDataSize"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public uint MaxDataSize { - get { - if ((curObj["MaxDataSize"] == null)) { - return System.Convert.ToUInt32(0); - } - return ((uint)(curObj["MaxDataSize"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsMaxQuiesceTimeNull { - get { - if ((curObj["MaxQuiesceTime"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong MaxQuiesceTime { - get { - if ((curObj["MaxQuiesceTime"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["MaxQuiesceTime"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsMaxSpeedNull { - get { - if ((curObj["MaxSpeed"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong MaxSpeed { - get { - if ((curObj["MaxSpeed"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["MaxSpeed"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Name { - get { - return ((string)(curObj["Name"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] NetworkAddresses { - get { - return ((string[])(curObj["NetworkAddresses"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsOperatingStatusNull { - get { - if ((curObj["OperatingStatus"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort OperatingStatus { - get { - if ((curObj["OperatingStatus"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["OperatingStatus"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ushort[] OperationalStatus { - get { - return ((ushort[])(curObj["OperationalStatus"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] OtherEnabledCapabilities { - get { - return ((string[])(curObj["OtherEnabledCapabilities"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OtherEnabledState { - get { - return ((string)(curObj["OtherEnabledState"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] OtherIdentifyingInfo { - get { - return ((string[])(curObj["OtherIdentifyingInfo"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OtherLinkTechnology { - get { - return ((string)(curObj["OtherLinkTechnology"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OtherNetworkPortType { - get { - return ((string)(curObj["OtherNetworkPortType"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OtherPortType { - get { - return ((string)(curObj["OtherPortType"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string PermanentAddress { - get { - return ((string)(curObj["PermanentAddress"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsPortNumberNull { - get { - if ((curObj["PortNumber"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort PortNumber { - get { - if ((curObj["PortNumber"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["PortNumber"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsPortTypeNull { - get { - if ((curObj["PortType"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort PortType { - get { - if ((curObj["PortType"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["PortType"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ushort[] PowerManagementCapabilities { - get { - return ((ushort[])(curObj["PowerManagementCapabilities"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsPowerManagementSupportedNull { - get { - if ((curObj["PowerManagementSupported"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool PowerManagementSupported { - get { - if ((curObj["PowerManagementSupported"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["PowerManagementSupported"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsPowerOnHoursNull { - get { - if ((curObj["PowerOnHours"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong PowerOnHours { - get { - if ((curObj["PowerOnHours"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["PowerOnHours"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsPrimaryStatusNull { - get { - if ((curObj["PrimaryStatus"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort PrimaryStatus { - get { - if ((curObj["PrimaryStatus"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["PrimaryStatus"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsRequestedSpeedNull { - get { - if ((curObj["RequestedSpeed"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong RequestedSpeed { - get { - if ((curObj["RequestedSpeed"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["RequestedSpeed"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsRequestedStateNull { - get { - if ((curObj["RequestedState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort RequestedState { - get { - if ((curObj["RequestedState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["RequestedState"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsSpeedNull { - get { - if ((curObj["Speed"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong Speed { - get { - if ((curObj["Speed"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["Speed"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Status { - get { - return ((string)(curObj["Status"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] StatusDescriptions { - get { - return ((string[])(curObj["StatusDescriptions"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsStatusInfoNull { - get { - if ((curObj["StatusInfo"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort StatusInfo { - get { - if ((curObj["StatusInfo"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["StatusInfo"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsSupportedMaximumTransmissionUnitNull { - get { - if ((curObj["SupportedMaximumTransmissionUnit"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong SupportedMaximumTransmissionUnit { - get { - if ((curObj["SupportedMaximumTransmissionUnit"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["SupportedMaximumTransmissionUnit"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string SystemCreationClassName { - get { - return ((string)(curObj["SystemCreationClassName"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string SystemName { - get { - return ((string)(curObj["SystemName"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsTimeOfLastStateChangeNull { - get { - if ((curObj["TimeOfLastStateChange"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public System.DateTime TimeOfLastStateChange { - get { - if ((curObj["TimeOfLastStateChange"] != null)) { - return ToDateTime(((string)(curObj["TimeOfLastStateChange"]))); - } - else { - return System.DateTime.MinValue; - } - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsTotalPowerOnHoursNull { - get { - if ((curObj["TotalPowerOnHours"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong TotalPowerOnHours { - get { - if ((curObj["TotalPowerOnHours"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["TotalPowerOnHours"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsTransitioningToStateNull { - get { - if ((curObj["TransitioningToState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort TransitioningToState { - get { - if ((curObj["TransitioningToState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["TransitioningToState"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsUsageRestrictionNull { - get { - if ((curObj["UsageRestriction"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort UsageRestriction { - get { - if ((curObj["UsageRestriction"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["UsageRestriction"])); - } - } - - private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { - if (((path != null) - && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); - } - } - - private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { - if (((theObj != null) - && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); - if ((parentClasses != null)) { - int count = 0; - for (count = 0; (count < parentClasses.Length); count = (count + 1)) { - if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { - return true; - } - } - } - } - return false; - } - - private bool ShouldSerializeActiveMaximumTransmissionUnit() { - if ((this.IsActiveMaximumTransmissionUnitNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeAutoSense() { - if ((this.IsAutoSenseNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeAvailability() { - if ((this.IsAvailabilityNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeCommunicationStatus() { - if ((this.IsCommunicationStatusNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeDetailedStatus() { - if ((this.IsDetailedStatusNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeEnabledDefault() { - if ((this.IsEnabledDefaultNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeEnabledState() { - if ((this.IsEnabledStateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeErrorCleared() { - if ((this.IsErrorClearedNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeFullDuplex() { - if ((this.IsFullDuplexNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeHealthState() { - if ((this.IsHealthStateNull == false)) { - return true; - } - return false; - } - - // Converts a given datetime in DMTF format to System.DateTime object. - static System.DateTime ToDateTime(string dmtfDate) { - System.DateTime initializer = System.DateTime.MinValue; - int year = initializer.Year; - int month = initializer.Month; - int day = initializer.Day; - int hour = initializer.Hour; - int minute = initializer.Minute; - int second = initializer.Second; - long ticks = 0; - string dmtf = dmtfDate; - System.DateTime datetime = System.DateTime.MinValue; - string tempString = string.Empty; - if ((dmtf == null)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtf.Length == 0)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtf.Length != 25)) { - throw new System.ArgumentOutOfRangeException(); - } - try { - tempString = dmtf.Substring(0, 4); - if (("****" != tempString)) { - year = int.Parse(tempString); - } - tempString = dmtf.Substring(4, 2); - if (("**" != tempString)) { - month = int.Parse(tempString); - } - tempString = dmtf.Substring(6, 2); - if (("**" != tempString)) { - day = int.Parse(tempString); - } - tempString = dmtf.Substring(8, 2); - if (("**" != tempString)) { - hour = int.Parse(tempString); - } - tempString = dmtf.Substring(10, 2); - if (("**" != tempString)) { - minute = int.Parse(tempString); - } - tempString = dmtf.Substring(12, 2); - if (("**" != tempString)) { - second = int.Parse(tempString); - } - tempString = dmtf.Substring(15, 6); - if (("******" != tempString)) { - ticks = (long.Parse(tempString) * ((long)((System.TimeSpan.TicksPerMillisecond / 1000)))); - } - if (((((((((year < 0) - || (month < 0)) - || (day < 0)) - || (hour < 0)) - || (minute < 0)) - || (minute < 0)) - || (second < 0)) - || (ticks < 0))) { - throw new System.ArgumentOutOfRangeException(); - } - } - catch (System.Exception e) { - throw new System.ArgumentOutOfRangeException(null, e.Message); - } - datetime = new System.DateTime(year, month, day, hour, minute, second, 0); - datetime = datetime.AddTicks(ticks); - System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(datetime); - int UTCOffset = 0; - int OffsetToBeAdjusted = 0; - long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); - tempString = dmtf.Substring(22, 3); - if ((tempString != "******")) { - tempString = dmtf.Substring(21, 4); - try { - UTCOffset = int.Parse(tempString); - } - catch (System.Exception e) { - throw new System.ArgumentOutOfRangeException(null, e.Message); - } - OffsetToBeAdjusted = ((int)((OffsetMins - UTCOffset))); - datetime = datetime.AddMinutes(((double)(OffsetToBeAdjusted))); - } - return datetime; - } - - // Converts a given System.DateTime object to DMTF datetime format. - static string ToDmtfDateTime(System.DateTime date) { - string utcString = string.Empty; - System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(date); - long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); - if ((System.Math.Abs(OffsetMins) > 999)) { - date = date.ToUniversalTime(); - utcString = "+000"; - } - else { - if ((tickOffset.Ticks >= 0)) { - utcString = string.Concat("+", ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))).ToString().PadLeft(3, '0')); - } - else { - string strTemp = ((long)(OffsetMins)).ToString(); - utcString = string.Concat("-", strTemp.Substring(1, (strTemp.Length - 1)).PadLeft(3, '0')); - } - } - string dmtfDateTime = ((int)(date.Year)).ToString().PadLeft(4, '0'); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Month)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Day)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Hour)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Minute)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Second)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, "."); - System.DateTime dtTemp = new System.DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, 0); - long microsec = ((long)((((date.Ticks - dtTemp.Ticks) - * 1000) - / System.TimeSpan.TicksPerMillisecond))); - string strMicrosec = ((long)(microsec)).ToString(); - if ((strMicrosec.Length > 6)) { - strMicrosec = strMicrosec.Substring(0, 6); - } - dmtfDateTime = string.Concat(dmtfDateTime, strMicrosec.PadLeft(6, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, utcString); - return dmtfDateTime; - } - - private bool ShouldSerializeInstallDate() { - if ((this.IsInstallDateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeIsBound() { - if ((this.IsIsBoundNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeLastErrorCode() { - if ((this.IsLastErrorCodeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeLinkTechnology() { - if ((this.IsLinkTechnologyNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeMaxDataSize() { - if ((this.IsMaxDataSizeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeMaxQuiesceTime() { - if ((this.IsMaxQuiesceTimeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeMaxSpeed() { - if ((this.IsMaxSpeedNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeOperatingStatus() { - if ((this.IsOperatingStatusNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializePortNumber() { - if ((this.IsPortNumberNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializePortType() { - if ((this.IsPortTypeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializePowerManagementSupported() { - if ((this.IsPowerManagementSupportedNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializePowerOnHours() { - if ((this.IsPowerOnHoursNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializePrimaryStatus() { - if ((this.IsPrimaryStatusNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeRequestedSpeed() { - if ((this.IsRequestedSpeedNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeRequestedState() { - if ((this.IsRequestedStateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeSpeed() { - if ((this.IsSpeedNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeStatusInfo() { - if ((this.IsStatusInfoNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeSupportedMaximumTransmissionUnit() { - if ((this.IsSupportedMaximumTransmissionUnitNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeTimeOfLastStateChange() { - if ((this.IsTimeOfLastStateChangeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeTotalPowerOnHours() { - if ((this.IsTotalPowerOnHoursNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeTransitioningToState() { - if ((this.IsTransitioningToStateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeUsageRestriction() { - if ((this.IsUsageRestrictionNull == false)) { - return true; - } - return false; - } - - [Browsable(true)] - public void CommitObject() { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(); - } - } - - [Browsable(true)] - public void CommitObject(System.Management.PutOptions putOptions) { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(putOptions); - } - } - - private void Initialize() { - AutoCommitProp = true; - isEmbedded = false; - } - - private static string ConstructPath(string keyCreationClassName, string keyDeviceID, string keySystemCreationClassName, string keySystemName) { - string strPath = "ROOT\\virtualization\\v2:Msvm_ExternalEthernetPort"; - strPath = string.Concat(strPath, string.Concat(".CreationClassName=", string.Concat("\"", string.Concat(keyCreationClassName, "\"")))); - strPath = string.Concat(strPath, string.Concat(",DeviceID=", string.Concat("\"", string.Concat(keyDeviceID, "\"")))); - strPath = string.Concat(strPath, string.Concat(",SystemCreationClassName=", string.Concat("\"", string.Concat(keySystemCreationClassName, "\"")))); - strPath = string.Concat(strPath, string.Concat(",SystemName=", string.Concat("\"", string.Concat(keySystemName, "\"")))); - return strPath; - } - - private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - Initialize(); - if ((path != null)) { - if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - } - PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - - // Different overloads of GetInstances() help in enumerating instances of the WMI class. - public static ExternalEthernetPortCollection GetInstances() { - return GetInstances(null, null, null); - } - - public static ExternalEthernetPortCollection GetInstances(string condition) { - return GetInstances(null, condition, null); - } - - public static ExternalEthernetPortCollection GetInstances(string[] selectedProperties) { - return GetInstances(null, null, selectedProperties); - } - - public static ExternalEthernetPortCollection GetInstances(string condition, string[] selectedProperties) { - return GetInstances(null, condition, selectedProperties); - } - - public static ExternalEthernetPortCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); - pathObj.ClassName = "Msvm_ExternalEthernetPort"; - pathObj.NamespacePath = "root\\virtualization\\v2"; - System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); - if ((enumOptions == null)) { - enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - } - return new ExternalEthernetPortCollection(clsObject.GetInstances(enumOptions)); - } - - public static ExternalEthernetPortCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { - return GetInstances(mgmtScope, condition, null); - } - - public static ExternalEthernetPortCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { - return GetInstances(mgmtScope, null, selectedProperties); - } - - public static ExternalEthernetPortCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_ExternalEthernetPort", condition, selectedProperties)); - System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - ObjectSearcher.Options = enumOptions; - return new ExternalEthernetPortCollection(ObjectSearcher.Get()); - } - - [Browsable(true)] - public static ExternalEthernetPort CreateInstance() { - System.Management.ManagementScope mgmtScope = null; - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = CreatedWmiNamespace; - } - else { - mgmtScope = statMgmtScope; - } - System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); - System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); - return new ExternalEthernetPort(tmpMgmtClass.CreateInstance()); - } - - [Browsable(true)] - public void Delete() { - PrivateLateBoundObject.Delete(); - } - - public uint EnableDevice(bool Enabled) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("EnableDevice"); - inParams["Enabled"] = ((bool)(Enabled)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("EnableDevice", inParams, null); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - return System.Convert.ToUInt32(0); - } - } - - public uint OnlineDevice(bool Online) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("OnlineDevice"); - inParams["Online"] = ((bool)(Online)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("OnlineDevice", inParams, null); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - return System.Convert.ToUInt32(0); - } - } - - public uint QuiesceDevice(bool Quiesce) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("QuiesceDevice"); - inParams["Quiesce"] = ((bool)(Quiesce)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("QuiesceDevice", inParams, null); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - return System.Convert.ToUInt32(0); - } - } - - public uint RequestStateChange(ushort RequestedState, System.DateTime TimeoutPeriod, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("RequestStateChange"); - inParams["RequestedState"] = ((ushort)(RequestedState)); - inParams["TimeoutPeriod"] = ToDmtfDateTime(((System.DateTime)(TimeoutPeriod))); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RequestStateChange", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null) && outParams.Properties["Job"].Value != null) { - Job = new System.Management.ManagementPath(outParams.Properties["Job"].Value.ToString()); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - return System.Convert.ToUInt32(0); - } - } - - public uint Reset() { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("Reset", inParams, null); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - return System.Convert.ToUInt32(0); - } - } - - public uint RestoreProperties() { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RestoreProperties", inParams, null); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - return System.Convert.ToUInt32(0); - } - } - - public uint SaveProperties() { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("SaveProperties", inParams, null); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - return System.Convert.ToUInt32(0); - } - } - - public uint SetPowerState(ushort PowerState, System.DateTime Time) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("SetPowerState"); - inParams["PowerState"] = ((ushort)(PowerState)); - inParams["Time"] = ToDmtfDateTime(((System.DateTime)(Time))); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("SetPowerState", inParams, null); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - return System.Convert.ToUInt32(0); - } - } - - // Enumerator implementation for enumerating instances of the class. - public class ExternalEthernetPortCollection : object, ICollection { - - private ManagementObjectCollection privColObj; - - public ExternalEthernetPortCollection(ManagementObjectCollection objCollection) { - privColObj = objCollection; - } - - public virtual int Count { - get { - return privColObj.Count; - } - } - - public virtual bool IsSynchronized { - get { - return privColObj.IsSynchronized; - } - } - - public virtual object SyncRoot { - get { - return this; - } - } - - public virtual void CopyTo(System.Array array, int index) { - privColObj.CopyTo(array, index); - int nCtr; - for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { - array.SetValue(new ExternalEthernetPort(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); - } - } - - public virtual System.Collections.IEnumerator GetEnumerator() { - return new ExternalEthernetPortEnumerator(privColObj.GetEnumerator()); - } - - public class ExternalEthernetPortEnumerator : object, System.Collections.IEnumerator { - - private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; - - public ExternalEthernetPortEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { - privObjEnum = objEnum; - } - - public virtual object Current { - get { - return new ExternalEthernetPort(((System.Management.ManagementObject)(privObjEnum.Current))); - } - } - - public virtual bool MoveNext() { - return privObjEnum.MoveNext(); - } - - public virtual void Reset() { - privObjEnum.Reset(); - } - } - } - - // TypeConverter to handle null values for ValueType properties - public class WMIValueTypeConverter : TypeConverter { - - private TypeConverter baseConverter; - - private System.Type baseType; - - public WMIValueTypeConverter(System.Type inBaseType) { - baseConverter = TypeDescriptor.GetConverter(inBaseType); - baseType = inBaseType; - } - - public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { - return baseConverter.CanConvertFrom(context, srcType); - } - - public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { - return baseConverter.CanConvertTo(context, destinationType); - } - - public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { - return baseConverter.ConvertFrom(context, culture, value); - } - - public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { - return baseConverter.CreateInstance(context, dictionary); - } - - public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetCreateInstanceSupported(context); - } - - public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { - return baseConverter.GetProperties(context, value, attributeVar); - } - - public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetPropertiesSupported(context); - } - - public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValues(context); - } - - public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesExclusive(context); - } - - public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesSupported(context); - } - - public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { - if ((baseType.BaseType == typeof(System.Enum))) { - if ((value.GetType() == destinationType)) { - return value; - } - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return "NULL_ENUM_VALUE" ; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((baseType == typeof(bool)) - && (baseType.BaseType == typeof(System.ValueType)))) { - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((context != null) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - } - - // Embedded class to represent WMI system Properties. - [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] - public class ManagementSystemProperties { - - private System.Management.ManagementBaseObject PrivateLateBoundObject; - - public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { - PrivateLateBoundObject = ManagedObject; - } - - [Browsable(true)] - public int GENUS { - get { - return ((int)(PrivateLateBoundObject["__GENUS"])); - } - } - - [Browsable(true)] - public string CLASS { - get { - return ((string)(PrivateLateBoundObject["__CLASS"])); - } - } - - [Browsable(true)] - public string SUPERCLASS { - get { - return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); - } - } - - [Browsable(true)] - public string DYNASTY { - get { - return ((string)(PrivateLateBoundObject["__DYNASTY"])); - } - } - - [Browsable(true)] - public string RELPATH { - get { - return ((string)(PrivateLateBoundObject["__RELPATH"])); - } - } - - [Browsable(true)] - public int PROPERTY_COUNT { - get { - return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); - } - } - - [Browsable(true)] - public string[] DERIVATION { - get { - return ((string[])(PrivateLateBoundObject["__DERIVATION"])); - } - } - - [Browsable(true)] - public string SERVER { - get { - return ((string)(PrivateLateBoundObject["__SERVER"])); - } - } - - [Browsable(true)] - public string NAMESPACE { - get { - return ((string)(PrivateLateBoundObject["__NAMESPACE"])); - } - } - - [Browsable(true)] - public string PATH { - get { - return ((string)(PrivateLateBoundObject["__PATH"])); - } - } - } - } -} +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2 { + using System; + using System.ComponentModel; + using System.Management; + using System.Collections; + using System.Globalization; + using System.ComponentModel.Design.Serialization; + using System.Reflection; + + + // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. + // Functions IsNull() are used to check if a property is NULL. + // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. + // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. + // Datetime conversion functions ToDateTime and ToDmtfDateTime are added to the class to convert DMTF datetime to System.DateTime and vice-versa. + // An Early Bound class generated for the WMI class.Msvm_ExternalEthernetPort + public class ExternalEthernetPort : System.ComponentModel.Component { + + // Private property to hold the WMI namespace in which the class resides. + private static string CreatedWmiNamespace = "ROOT\\virtualization\\v2"; + + // Private property to hold the name of WMI class which created this class. + private static string CreatedClassName = "Msvm_ExternalEthernetPort"; + + // Private member variable to hold the ManagementScope which is used by the various methods. + private static System.Management.ManagementScope statMgmtScope = null; + + private ManagementSystemProperties PrivateSystemProperties; + + // Underlying lateBound WMI object. + private System.Management.ManagementObject PrivateLateBoundObject; + + // Member variable to store the 'automatic commit' behavior for the class. + private bool AutoCommitProp; + + // Private variable to hold the embedded property representing the instance. + private System.Management.ManagementBaseObject embeddedObj; + + // The current WMI object used + private System.Management.ManagementBaseObject curObj; + + // Flag to indicate if the instance is an embedded object. + private bool isEmbedded; + + // Below are different overloads of constructors to initialize an instance of the class with a WMI object. + public ExternalEthernetPort() { + this.InitializeObject(null, null, null); + } + + public ExternalEthernetPort(string keyCreationClassName, string keyDeviceID, string keySystemCreationClassName, string keySystemName) { + this.InitializeObject(null, new System.Management.ManagementPath(ExternalEthernetPort.ConstructPath(keyCreationClassName, keyDeviceID, keySystemCreationClassName, keySystemName)), null); + } + + public ExternalEthernetPort(System.Management.ManagementScope mgmtScope, string keyCreationClassName, string keyDeviceID, string keySystemCreationClassName, string keySystemName) { + this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(ExternalEthernetPort.ConstructPath(keyCreationClassName, keyDeviceID, keySystemCreationClassName, keySystemName)), null); + } + + public ExternalEthernetPort(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(null, path, getOptions); + } + + public ExternalEthernetPort(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { + this.InitializeObject(mgmtScope, path, null); + } + + public ExternalEthernetPort(System.Management.ManagementPath path) { + this.InitializeObject(null, path, null); + } + + public ExternalEthernetPort(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(mgmtScope, path, getOptions); + } + + public ExternalEthernetPort(System.Management.ManagementObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + PrivateLateBoundObject = theObject; + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + public ExternalEthernetPort(System.Management.ManagementBaseObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + embeddedObj = theObject; + PrivateSystemProperties = new ManagementSystemProperties(theObject); + curObj = embeddedObj; + isEmbedded = true; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + // Property returns the namespace of the WMI class. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OriginatingNamespace { + get { + return "ROOT\\virtualization\\v2"; + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ManagementClassName { + get { + string strRet = CreatedClassName; + if ((curObj != null)) { + if ((curObj.ClassPath != null)) { + strRet = ((string)(curObj["__CLASS"])); + if (((strRet == null) + || (strRet == string.Empty))) { + strRet = CreatedClassName; + } + } + } + return strRet; + } + } + + // Property pointing to an embedded object to get System properties of the WMI object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ManagementSystemProperties SystemProperties { + get { + return PrivateSystemProperties; + } + } + + // Property returning the underlying lateBound object. + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementBaseObject LateBoundObject { + get { + return curObj; + } + } + + // ManagementScope of the object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementScope Scope { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Scope; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Scope = value; + } + } + } + + // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool AutoCommit { + get { + return AutoCommitProp; + } + set { + AutoCommitProp = value; + } + } + + // The ManagementPath of the underlying WMI object. + [Browsable(true)] + public System.Management.ManagementPath Path { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Path; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + if ((CheckIfProperClass(null, value, null) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + PrivateLateBoundObject.Path = value; + } + } + } + + // Public static scope property which is used by the various methods. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public static System.Management.ManagementScope StaticScope { + get { + return statMgmtScope; + } + set { + statMgmtScope = value; + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsActiveMaximumTransmissionUnitNull { + get { + if ((curObj["ActiveMaximumTransmissionUnit"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong ActiveMaximumTransmissionUnit { + get { + if ((curObj["ActiveMaximumTransmissionUnit"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["ActiveMaximumTransmissionUnit"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ushort[] AdditionalAvailability { + get { + return ((ushort[])(curObj["AdditionalAvailability"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAutoSenseNull { + get { + if ((curObj["AutoSense"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool AutoSense { + get { + if ((curObj["AutoSense"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["AutoSense"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAvailabilityNull { + get { + if ((curObj["Availability"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort Availability { + get { + if ((curObj["Availability"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["Availability"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ushort[] AvailableRequestedStates { + get { + return ((ushort[])(curObj["AvailableRequestedStates"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ushort[] Capabilities { + get { + return ((ushort[])(curObj["Capabilities"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] CapabilityDescriptions { + get { + return ((string[])(curObj["CapabilityDescriptions"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Caption { + get { + return ((string)(curObj["Caption"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsCommunicationStatusNull { + get { + if ((curObj["CommunicationStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort CommunicationStatus { + get { + if ((curObj["CommunicationStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["CommunicationStatus"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string CreationClassName { + get { + return ((string)(curObj["CreationClassName"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Description { + get { + return ((string)(curObj["Description"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsDetailedStatusNull { + get { + if ((curObj["DetailedStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort DetailedStatus { + get { + if ((curObj["DetailedStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["DetailedStatus"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string DeviceID { + get { + return ((string)(curObj["DeviceID"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ElementName { + get { + return ((string)(curObj["ElementName"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ushort[] EnabledCapabilities { + get { + return ((ushort[])(curObj["EnabledCapabilities"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsEnabledDefaultNull { + get { + if ((curObj["EnabledDefault"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort EnabledDefault { + get { + if ((curObj["EnabledDefault"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["EnabledDefault"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsEnabledStateNull { + get { + if ((curObj["EnabledState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort EnabledState { + get { + if ((curObj["EnabledState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["EnabledState"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsErrorClearedNull { + get { + if ((curObj["ErrorCleared"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool ErrorCleared { + get { + if ((curObj["ErrorCleared"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["ErrorCleared"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ErrorDescription { + get { + return ((string)(curObj["ErrorDescription"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsFullDuplexNull { + get { + if ((curObj["FullDuplex"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool FullDuplex { + get { + if ((curObj["FullDuplex"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["FullDuplex"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsHealthStateNull { + get { + if ((curObj["HealthState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort HealthState { + get { + if ((curObj["HealthState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["HealthState"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] IdentifyingDescriptions { + get { + return ((string[])(curObj["IdentifyingDescriptions"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsInstallDateNull { + get { + if ((curObj["InstallDate"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime InstallDate { + get { + if ((curObj["InstallDate"] != null)) { + return ToDateTime(((string)(curObj["InstallDate"]))); + } + else { + return System.DateTime.MinValue; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string InstanceID { + get { + return ((string)(curObj["InstanceID"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsIsBoundNull { + get { + if ((curObj["IsBound"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("If this property is true, then this Ethernet port can be connected to the switches" + + " and thus can provide connectivity to virtual machine. If this property is false" + + ", then this Ethernet is not being used by the virtual machine networking architecture.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool IsBound { + get { + if ((curObj["IsBound"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["IsBound"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsLastErrorCodeNull { + get { + if ((curObj["LastErrorCode"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint LastErrorCode { + get { + if ((curObj["LastErrorCode"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["LastErrorCode"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsLinkTechnologyNull { + get { + if ((curObj["LinkTechnology"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort LinkTechnology { + get { + if ((curObj["LinkTechnology"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["LinkTechnology"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsMaxDataSizeNull { + get { + if ((curObj["MaxDataSize"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint MaxDataSize { + get { + if ((curObj["MaxDataSize"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["MaxDataSize"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsMaxQuiesceTimeNull { + get { + if ((curObj["MaxQuiesceTime"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong MaxQuiesceTime { + get { + if ((curObj["MaxQuiesceTime"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["MaxQuiesceTime"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsMaxSpeedNull { + get { + if ((curObj["MaxSpeed"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong MaxSpeed { + get { + if ((curObj["MaxSpeed"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["MaxSpeed"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Name { + get { + return ((string)(curObj["Name"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] NetworkAddresses { + get { + return ((string[])(curObj["NetworkAddresses"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsOperatingStatusNull { + get { + if ((curObj["OperatingStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort OperatingStatus { + get { + if ((curObj["OperatingStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["OperatingStatus"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ushort[] OperationalStatus { + get { + return ((ushort[])(curObj["OperationalStatus"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] OtherEnabledCapabilities { + get { + return ((string[])(curObj["OtherEnabledCapabilities"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherEnabledState { + get { + return ((string)(curObj["OtherEnabledState"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] OtherIdentifyingInfo { + get { + return ((string[])(curObj["OtherIdentifyingInfo"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherLinkTechnology { + get { + return ((string)(curObj["OtherLinkTechnology"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherNetworkPortType { + get { + return ((string)(curObj["OtherNetworkPortType"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherPortType { + get { + return ((string)(curObj["OtherPortType"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string PermanentAddress { + get { + return ((string)(curObj["PermanentAddress"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPortNumberNull { + get { + if ((curObj["PortNumber"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort PortNumber { + get { + if ((curObj["PortNumber"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["PortNumber"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPortTypeNull { + get { + if ((curObj["PortType"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort PortType { + get { + if ((curObj["PortType"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["PortType"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ushort[] PowerManagementCapabilities { + get { + return ((ushort[])(curObj["PowerManagementCapabilities"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPowerManagementSupportedNull { + get { + if ((curObj["PowerManagementSupported"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool PowerManagementSupported { + get { + if ((curObj["PowerManagementSupported"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["PowerManagementSupported"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPowerOnHoursNull { + get { + if ((curObj["PowerOnHours"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong PowerOnHours { + get { + if ((curObj["PowerOnHours"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["PowerOnHours"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPrimaryStatusNull { + get { + if ((curObj["PrimaryStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort PrimaryStatus { + get { + if ((curObj["PrimaryStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["PrimaryStatus"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsRequestedSpeedNull { + get { + if ((curObj["RequestedSpeed"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong RequestedSpeed { + get { + if ((curObj["RequestedSpeed"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["RequestedSpeed"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsRequestedStateNull { + get { + if ((curObj["RequestedState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort RequestedState { + get { + if ((curObj["RequestedState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["RequestedState"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsSpeedNull { + get { + if ((curObj["Speed"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong Speed { + get { + if ((curObj["Speed"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["Speed"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Status { + get { + return ((string)(curObj["Status"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] StatusDescriptions { + get { + return ((string[])(curObj["StatusDescriptions"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsStatusInfoNull { + get { + if ((curObj["StatusInfo"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort StatusInfo { + get { + if ((curObj["StatusInfo"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["StatusInfo"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsSupportedMaximumTransmissionUnitNull { + get { + if ((curObj["SupportedMaximumTransmissionUnit"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong SupportedMaximumTransmissionUnit { + get { + if ((curObj["SupportedMaximumTransmissionUnit"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["SupportedMaximumTransmissionUnit"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string SystemCreationClassName { + get { + return ((string)(curObj["SystemCreationClassName"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string SystemName { + get { + return ((string)(curObj["SystemName"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsTimeOfLastStateChangeNull { + get { + if ((curObj["TimeOfLastStateChange"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime TimeOfLastStateChange { + get { + if ((curObj["TimeOfLastStateChange"] != null)) { + return ToDateTime(((string)(curObj["TimeOfLastStateChange"]))); + } + else { + return System.DateTime.MinValue; + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsTotalPowerOnHoursNull { + get { + if ((curObj["TotalPowerOnHours"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong TotalPowerOnHours { + get { + if ((curObj["TotalPowerOnHours"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["TotalPowerOnHours"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsTransitioningToStateNull { + get { + if ((curObj["TransitioningToState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort TransitioningToState { + get { + if ((curObj["TransitioningToState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["TransitioningToState"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsUsageRestrictionNull { + get { + if ((curObj["UsageRestriction"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort UsageRestriction { + get { + if ((curObj["UsageRestriction"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["UsageRestriction"])); + } + } + + private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { + if (((path != null) + && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); + } + } + + private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { + if (((theObj != null) + && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); + if ((parentClasses != null)) { + int count = 0; + for (count = 0; (count < parentClasses.Length); count = (count + 1)) { + if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { + return true; + } + } + } + } + return false; + } + + private bool ShouldSerializeActiveMaximumTransmissionUnit() { + if ((this.IsActiveMaximumTransmissionUnitNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeAutoSense() { + if ((this.IsAutoSenseNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeAvailability() { + if ((this.IsAvailabilityNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeCommunicationStatus() { + if ((this.IsCommunicationStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeDetailedStatus() { + if ((this.IsDetailedStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeEnabledDefault() { + if ((this.IsEnabledDefaultNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeEnabledState() { + if ((this.IsEnabledStateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeErrorCleared() { + if ((this.IsErrorClearedNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeFullDuplex() { + if ((this.IsFullDuplexNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeHealthState() { + if ((this.IsHealthStateNull == false)) { + return true; + } + return false; + } + + // Converts a given datetime in DMTF format to System.DateTime object. + static System.DateTime ToDateTime(string dmtfDate) { + System.DateTime initializer = System.DateTime.MinValue; + int year = initializer.Year; + int month = initializer.Month; + int day = initializer.Day; + int hour = initializer.Hour; + int minute = initializer.Minute; + int second = initializer.Second; + long ticks = 0; + string dmtf = dmtfDate; + System.DateTime datetime = System.DateTime.MinValue; + string tempString = string.Empty; + if ((dmtf == null)) { + throw new System.ArgumentOutOfRangeException(); + } + if ((dmtf.Length == 0)) { + throw new System.ArgumentOutOfRangeException(); + } + if ((dmtf.Length != 25)) { + throw new System.ArgumentOutOfRangeException(); + } + try { + tempString = dmtf.Substring(0, 4); + if (("****" != tempString)) { + year = int.Parse(tempString); + } + tempString = dmtf.Substring(4, 2); + if (("**" != tempString)) { + month = int.Parse(tempString); + } + tempString = dmtf.Substring(6, 2); + if (("**" != tempString)) { + day = int.Parse(tempString); + } + tempString = dmtf.Substring(8, 2); + if (("**" != tempString)) { + hour = int.Parse(tempString); + } + tempString = dmtf.Substring(10, 2); + if (("**" != tempString)) { + minute = int.Parse(tempString); + } + tempString = dmtf.Substring(12, 2); + if (("**" != tempString)) { + second = int.Parse(tempString); + } + tempString = dmtf.Substring(15, 6); + if (("******" != tempString)) { + ticks = (long.Parse(tempString) * ((long)((System.TimeSpan.TicksPerMillisecond / 1000)))); + } + if (((((((((year < 0) + || (month < 0)) + || (day < 0)) + || (hour < 0)) + || (minute < 0)) + || (minute < 0)) + || (second < 0)) + || (ticks < 0))) { + throw new System.ArgumentOutOfRangeException(); + } + } + catch (System.Exception e) { + throw new System.ArgumentOutOfRangeException(null, e.Message); + } + datetime = new System.DateTime(year, month, day, hour, minute, second, 0); + datetime = datetime.AddTicks(ticks); + System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(datetime); + int UTCOffset = 0; + int OffsetToBeAdjusted = 0; + long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); + tempString = dmtf.Substring(22, 3); + if ((tempString != "******")) { + tempString = dmtf.Substring(21, 4); + try { + UTCOffset = int.Parse(tempString); + } + catch (System.Exception e) { + throw new System.ArgumentOutOfRangeException(null, e.Message); + } + OffsetToBeAdjusted = ((int)((OffsetMins - UTCOffset))); + datetime = datetime.AddMinutes(((double)(OffsetToBeAdjusted))); + } + return datetime; + } + + // Converts a given System.DateTime object to DMTF datetime format. + static string ToDmtfDateTime(System.DateTime date) { + string utcString = string.Empty; + System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(date); + long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); + if ((System.Math.Abs(OffsetMins) > 999)) { + date = date.ToUniversalTime(); + utcString = "+000"; + } + else { + if ((tickOffset.Ticks >= 0)) { + utcString = string.Concat("+", ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))).ToString().PadLeft(3, '0')); + } + else { + string strTemp = ((long)(OffsetMins)).ToString(); + utcString = string.Concat("-", strTemp.Substring(1, (strTemp.Length - 1)).PadLeft(3, '0')); + } + } + string dmtfDateTime = ((int)(date.Year)).ToString().PadLeft(4, '0'); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Month)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Day)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Hour)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Minute)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Second)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, "."); + System.DateTime dtTemp = new System.DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, 0); + long microsec = ((long)((((date.Ticks - dtTemp.Ticks) + * 1000) + / System.TimeSpan.TicksPerMillisecond))); + string strMicrosec = ((long)(microsec)).ToString(); + if ((strMicrosec.Length > 6)) { + strMicrosec = strMicrosec.Substring(0, 6); + } + dmtfDateTime = string.Concat(dmtfDateTime, strMicrosec.PadLeft(6, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, utcString); + return dmtfDateTime; + } + + private bool ShouldSerializeInstallDate() { + if ((this.IsInstallDateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeIsBound() { + if ((this.IsIsBoundNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeLastErrorCode() { + if ((this.IsLastErrorCodeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeLinkTechnology() { + if ((this.IsLinkTechnologyNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeMaxDataSize() { + if ((this.IsMaxDataSizeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeMaxQuiesceTime() { + if ((this.IsMaxQuiesceTimeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeMaxSpeed() { + if ((this.IsMaxSpeedNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeOperatingStatus() { + if ((this.IsOperatingStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePortNumber() { + if ((this.IsPortNumberNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePortType() { + if ((this.IsPortTypeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePowerManagementSupported() { + if ((this.IsPowerManagementSupportedNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePowerOnHours() { + if ((this.IsPowerOnHoursNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePrimaryStatus() { + if ((this.IsPrimaryStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeRequestedSpeed() { + if ((this.IsRequestedSpeedNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeRequestedState() { + if ((this.IsRequestedStateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeSpeed() { + if ((this.IsSpeedNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeStatusInfo() { + if ((this.IsStatusInfoNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeSupportedMaximumTransmissionUnit() { + if ((this.IsSupportedMaximumTransmissionUnitNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeTimeOfLastStateChange() { + if ((this.IsTimeOfLastStateChangeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeTotalPowerOnHours() { + if ((this.IsTotalPowerOnHoursNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeTransitioningToState() { + if ((this.IsTransitioningToStateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeUsageRestriction() { + if ((this.IsUsageRestrictionNull == false)) { + return true; + } + return false; + } + + [Browsable(true)] + public void CommitObject() { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(); + } + } + + [Browsable(true)] + public void CommitObject(System.Management.PutOptions putOptions) { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(putOptions); + } + } + + private void Initialize() { + AutoCommitProp = true; + isEmbedded = false; + } + + private static string ConstructPath(string keyCreationClassName, string keyDeviceID, string keySystemCreationClassName, string keySystemName) { + string strPath = "ROOT\\virtualization\\v2:Msvm_ExternalEthernetPort"; + strPath = string.Concat(strPath, string.Concat(".CreationClassName=", string.Concat("\"", string.Concat(keyCreationClassName, "\"")))); + strPath = string.Concat(strPath, string.Concat(",DeviceID=", string.Concat("\"", string.Concat(keyDeviceID, "\"")))); + strPath = string.Concat(strPath, string.Concat(",SystemCreationClassName=", string.Concat("\"", string.Concat(keySystemCreationClassName, "\"")))); + strPath = string.Concat(strPath, string.Concat(",SystemName=", string.Concat("\"", string.Concat(keySystemName, "\"")))); + return strPath; + } + + private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + Initialize(); + if ((path != null)) { + if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + } + PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + + // Different overloads of GetInstances() help in enumerating instances of the WMI class. + public static ExternalEthernetPortCollection GetInstances() { + return GetInstances(null, null, null); + } + + public static ExternalEthernetPortCollection GetInstances(string condition) { + return GetInstances(null, condition, null); + } + + public static ExternalEthernetPortCollection GetInstances(string[] selectedProperties) { + return GetInstances(null, null, selectedProperties); + } + + public static ExternalEthernetPortCollection GetInstances(string condition, string[] selectedProperties) { + return GetInstances(null, condition, selectedProperties); + } + + public static ExternalEthernetPortCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); + pathObj.ClassName = "Msvm_ExternalEthernetPort"; + pathObj.NamespacePath = "root\\virtualization\\v2"; + System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); + if ((enumOptions == null)) { + enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + } + return new ExternalEthernetPortCollection(clsObject.GetInstances(enumOptions)); + } + + public static ExternalEthernetPortCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { + return GetInstances(mgmtScope, condition, null); + } + + public static ExternalEthernetPortCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { + return GetInstances(mgmtScope, null, selectedProperties); + } + + public static ExternalEthernetPortCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_ExternalEthernetPort", condition, selectedProperties)); + System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + ObjectSearcher.Options = enumOptions; + return new ExternalEthernetPortCollection(ObjectSearcher.Get()); + } + + [Browsable(true)] + public static ExternalEthernetPort CreateInstance() { + System.Management.ManagementScope mgmtScope = null; + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = CreatedWmiNamespace; + } + else { + mgmtScope = statMgmtScope; + } + System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); + System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); + return new ExternalEthernetPort(tmpMgmtClass.CreateInstance()); + } + + [Browsable(true)] + public void Delete() { + PrivateLateBoundObject.Delete(); + } + + public uint EnableDevice(bool Enabled) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("EnableDevice"); + inParams["Enabled"] = ((bool)(Enabled)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("EnableDevice", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + public uint OnlineDevice(bool Online) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("OnlineDevice"); + inParams["Online"] = ((bool)(Online)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("OnlineDevice", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + public uint QuiesceDevice(bool Quiesce) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("QuiesceDevice"); + inParams["Quiesce"] = ((bool)(Quiesce)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("QuiesceDevice", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + public uint RequestStateChange(ushort RequestedState, System.DateTime TimeoutPeriod, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("RequestStateChange"); + inParams["RequestedState"] = ((ushort)(RequestedState)); + inParams["TimeoutPeriod"] = ToDmtfDateTime(((System.DateTime)(TimeoutPeriod))); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RequestStateChange", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null) && outParams.Properties["Job"].Value != null) { + Job = new System.Management.ManagementPath(outParams.Properties["Job"].Value.ToString()); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + return System.Convert.ToUInt32(0); + } + } + + public uint Reset() { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("Reset", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + public uint RestoreProperties() { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RestoreProperties", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + public uint SaveProperties() { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("SaveProperties", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + public uint SetPowerState(ushort PowerState, System.DateTime Time) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("SetPowerState"); + inParams["PowerState"] = ((ushort)(PowerState)); + inParams["Time"] = ToDmtfDateTime(((System.DateTime)(Time))); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("SetPowerState", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + // Enumerator implementation for enumerating instances of the class. + public class ExternalEthernetPortCollection : object, ICollection { + + private ManagementObjectCollection privColObj; + + public ExternalEthernetPortCollection(ManagementObjectCollection objCollection) { + privColObj = objCollection; + } + + public virtual int Count { + get { + return privColObj.Count; + } + } + + public virtual bool IsSynchronized { + get { + return privColObj.IsSynchronized; + } + } + + public virtual object SyncRoot { + get { + return this; + } + } + + public virtual void CopyTo(System.Array array, int index) { + privColObj.CopyTo(array, index); + int nCtr; + for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { + array.SetValue(new ExternalEthernetPort(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); + } + } + + public virtual System.Collections.IEnumerator GetEnumerator() { + return new ExternalEthernetPortEnumerator(privColObj.GetEnumerator()); + } + + public class ExternalEthernetPortEnumerator : object, System.Collections.IEnumerator { + + private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; + + public ExternalEthernetPortEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { + privObjEnum = objEnum; + } + + public virtual object Current { + get { + return new ExternalEthernetPort(((System.Management.ManagementObject)(privObjEnum.Current))); + } + } + + public virtual bool MoveNext() { + return privObjEnum.MoveNext(); + } + + public virtual void Reset() { + privObjEnum.Reset(); + } + } + } + + // TypeConverter to handle null values for ValueType properties + public class WMIValueTypeConverter : TypeConverter { + + private TypeConverter baseConverter; + + private System.Type baseType; + + public WMIValueTypeConverter(System.Type inBaseType) { + baseConverter = TypeDescriptor.GetConverter(inBaseType); + baseType = inBaseType; + } + + public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { + return baseConverter.CanConvertFrom(context, srcType); + } + + public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { + return baseConverter.CanConvertTo(context, destinationType); + } + + public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { + return baseConverter.ConvertFrom(context, culture, value); + } + + public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { + return baseConverter.CreateInstance(context, dictionary); + } + + public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetCreateInstanceSupported(context); + } + + public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { + return baseConverter.GetProperties(context, value, attributeVar); + } + + public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetPropertiesSupported(context); + } + + public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValues(context); + } + + public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesExclusive(context); + } + + public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesSupported(context); + } + + public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { + if ((baseType.BaseType == typeof(System.Enum))) { + if ((value.GetType() == destinationType)) { + return value; + } + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return "NULL_ENUM_VALUE" ; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((baseType == typeof(bool)) + && (baseType.BaseType == typeof(System.ValueType)))) { + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((context != null) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + } + + // Embedded class to represent WMI system Properties. + [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] + public class ManagementSystemProperties { + + private System.Management.ManagementBaseObject PrivateLateBoundObject; + + public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { + PrivateLateBoundObject = ManagedObject; + } + + [Browsable(true)] + public int GENUS { + get { + return ((int)(PrivateLateBoundObject["__GENUS"])); + } + } + + [Browsable(true)] + public string CLASS { + get { + return ((string)(PrivateLateBoundObject["__CLASS"])); + } + } + + [Browsable(true)] + public string SUPERCLASS { + get { + return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); + } + } + + [Browsable(true)] + public string DYNASTY { + get { + return ((string)(PrivateLateBoundObject["__DYNASTY"])); + } + } + + [Browsable(true)] + public string RELPATH { + get { + return ((string)(PrivateLateBoundObject["__RELPATH"])); + } + } + + [Browsable(true)] + public int PROPERTY_COUNT { + get { + return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); + } + } + + [Browsable(true)] + public string[] DERIVATION { + get { + return ((string[])(PrivateLateBoundObject["__DERIVATION"])); + } + } + + [Browsable(true)] + public string SERVER { + get { + return ((string)(PrivateLateBoundObject["__SERVER"])); + } + } + + [Browsable(true)] + public string NAMESPACE { + get { + return ((string)(PrivateLateBoundObject["__NAMESPACE"])); + } + } + + [Browsable(true)] + public string PATH { + get { + return ((string)(PrivateLateBoundObject["__PATH"])); + } + } + } + } +} diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_ImageManagementService.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_ImageManagementService.cs index ff27854e8d5..ba96348416e 100644 --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_ImageManagementService.cs +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_ImageManagementService.cs @@ -1,1525 +1,1525 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2 { - using System; - using System.ComponentModel; - using System.Management; - using System.Collections; - using System.Globalization; - using System.ComponentModel.Design.Serialization; - using System.Reflection; - - - // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. - // Functions IsNull() are used to check if a property is NULL. - // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. - // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. - // Datetime conversion functions ToDateTime and ToDmtfDateTime are added to the class to convert DMTF datetime to System.DateTime and vice-versa. - // An Early Bound class generated for the WMI class.Msvm_ImageManagementService - public class ImageManagementService : System.ComponentModel.Component { - - // Private property to hold the WMI namespace in which the class resides. - private static string CreatedWmiNamespace = "ROOT\\virtualization\\v2"; - - // Private property to hold the name of WMI class which created this class. - private static string CreatedClassName = "Msvm_ImageManagementService"; - - // Private member variable to hold the ManagementScope which is used by the various methods. - private static System.Management.ManagementScope statMgmtScope = null; - - private ManagementSystemProperties PrivateSystemProperties; - - // Underlying lateBound WMI object. - private System.Management.ManagementObject PrivateLateBoundObject; - - // Member variable to store the 'automatic commit' behavior for the class. - private bool AutoCommitProp; - - // Private variable to hold the embedded property representing the instance. - private System.Management.ManagementBaseObject embeddedObj; - - // The current WMI object used - private System.Management.ManagementBaseObject curObj; - - // Flag to indicate if the instance is an embedded object. - private bool isEmbedded; - - // Below are different overloads of constructors to initialize an instance of the class with a WMI object. - public ImageManagementService() { - this.InitializeObject(null, null, null); - } - - public ImageManagementService(string keyCreationClassName, string keyName, string keySystemCreationClassName, string keySystemName) { - this.InitializeObject(null, new System.Management.ManagementPath(ImageManagementService.ConstructPath(keyCreationClassName, keyName, keySystemCreationClassName, keySystemName)), null); - } - - public ImageManagementService(System.Management.ManagementScope mgmtScope, string keyCreationClassName, string keyName, string keySystemCreationClassName, string keySystemName) { - this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(ImageManagementService.ConstructPath(keyCreationClassName, keyName, keySystemCreationClassName, keySystemName)), null); - } - - public ImageManagementService(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(null, path, getOptions); - } - - public ImageManagementService(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { - this.InitializeObject(mgmtScope, path, null); - } - - public ImageManagementService(System.Management.ManagementPath path) { - this.InitializeObject(null, path, null); - } - - public ImageManagementService(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(mgmtScope, path, getOptions); - } - - public ImageManagementService(System.Management.ManagementObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - PrivateLateBoundObject = theObject; - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - public ImageManagementService(System.Management.ManagementBaseObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - embeddedObj = theObject; - PrivateSystemProperties = new ManagementSystemProperties(theObject); - curObj = embeddedObj; - isEmbedded = true; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - // Property returns the namespace of the WMI class. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OriginatingNamespace { - get { - return "ROOT\\virtualization\\v2"; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ManagementClassName { - get { - string strRet = CreatedClassName; - if ((curObj != null)) { - if ((curObj.ClassPath != null)) { - strRet = ((string)(curObj["__CLASS"])); - if (((strRet == null) - || (strRet == string.Empty))) { - strRet = CreatedClassName; - } - } - } - return strRet; - } - } - - // Property pointing to an embedded object to get System properties of the WMI object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ManagementSystemProperties SystemProperties { - get { - return PrivateSystemProperties; - } - } - - // Property returning the underlying lateBound object. - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementBaseObject LateBoundObject { - get { - return curObj; - } - } - - // ManagementScope of the object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementScope Scope { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Scope; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Scope = value; - } - } - } - - // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool AutoCommit { - get { - return AutoCommitProp; - } - set { - AutoCommitProp = value; - } - } - - // The ManagementPath of the underlying WMI object. - [Browsable(true)] - public System.Management.ManagementPath Path { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Path; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - if ((CheckIfProperClass(null, value, null) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - PrivateLateBoundObject.Path = value; - } - } - } - - // Public static scope property which is used by the various methods. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public static System.Management.ManagementScope StaticScope { - get { - return statMgmtScope; - } - set { - statMgmtScope = value; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ushort[] AvailableRequestedStates { - get { - return ((ushort[])(curObj["AvailableRequestedStates"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Caption { - get { - return ((string)(curObj["Caption"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsCommunicationStatusNull { - get { - if ((curObj["CommunicationStatus"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort CommunicationStatus { - get { - if ((curObj["CommunicationStatus"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["CommunicationStatus"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string CreationClassName { - get { - return ((string)(curObj["CreationClassName"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Description { - get { - return ((string)(curObj["Description"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsDetailedStatusNull { - get { - if ((curObj["DetailedStatus"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort DetailedStatus { - get { - if ((curObj["DetailedStatus"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["DetailedStatus"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ElementName { - get { - return ((string)(curObj["ElementName"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsEnabledDefaultNull { - get { - if ((curObj["EnabledDefault"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort EnabledDefault { - get { - if ((curObj["EnabledDefault"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["EnabledDefault"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsEnabledStateNull { - get { - if ((curObj["EnabledState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort EnabledState { - get { - if ((curObj["EnabledState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["EnabledState"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsHealthStateNull { - get { - if ((curObj["HealthState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort HealthState { - get { - if ((curObj["HealthState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["HealthState"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsInstallDateNull { - get { - if ((curObj["InstallDate"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public System.DateTime InstallDate { - get { - if ((curObj["InstallDate"] != null)) { - return ToDateTime(((string)(curObj["InstallDate"]))); - } - else { - return System.DateTime.MinValue; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string InstanceID { - get { - return ((string)(curObj["InstanceID"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Name { - get { - return ((string)(curObj["Name"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsOperatingStatusNull { - get { - if ((curObj["OperatingStatus"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort OperatingStatus { - get { - if ((curObj["OperatingStatus"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["OperatingStatus"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ushort[] OperationalStatus { - get { - return ((ushort[])(curObj["OperationalStatus"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OtherEnabledState { - get { - return ((string)(curObj["OtherEnabledState"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string PrimaryOwnerContact { - get { - return ((string)(curObj["PrimaryOwnerContact"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string PrimaryOwnerName { - get { - return ((string)(curObj["PrimaryOwnerName"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsPrimaryStatusNull { - get { - if ((curObj["PrimaryStatus"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort PrimaryStatus { - get { - if ((curObj["PrimaryStatus"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["PrimaryStatus"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsRequestedStateNull { - get { - if ((curObj["RequestedState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort RequestedState { - get { - if ((curObj["RequestedState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["RequestedState"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsStartedNull { - get { - if ((curObj["Started"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool Started { - get { - if ((curObj["Started"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["Started"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string StartMode { - get { - return ((string)(curObj["StartMode"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Status { - get { - return ((string)(curObj["Status"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] StatusDescriptions { - get { - return ((string[])(curObj["StatusDescriptions"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string SystemCreationClassName { - get { - return ((string)(curObj["SystemCreationClassName"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string SystemName { - get { - return ((string)(curObj["SystemName"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsTimeOfLastStateChangeNull { - get { - if ((curObj["TimeOfLastStateChange"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public System.DateTime TimeOfLastStateChange { - get { - if ((curObj["TimeOfLastStateChange"] != null)) { - return ToDateTime(((string)(curObj["TimeOfLastStateChange"]))); - } - else { - return System.DateTime.MinValue; - } - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsTransitioningToStateNull { - get { - if ((curObj["TransitioningToState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort TransitioningToState { - get { - if ((curObj["TransitioningToState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["TransitioningToState"])); - } - } - - private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { - if (((path != null) - && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); - } - } - - private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { - if (((theObj != null) - && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); - if ((parentClasses != null)) { - int count = 0; - for (count = 0; (count < parentClasses.Length); count = (count + 1)) { - if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { - return true; - } - } - } - } - return false; - } - - private bool ShouldSerializeCommunicationStatus() { - if ((this.IsCommunicationStatusNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeDetailedStatus() { - if ((this.IsDetailedStatusNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeEnabledDefault() { - if ((this.IsEnabledDefaultNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeEnabledState() { - if ((this.IsEnabledStateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeHealthState() { - if ((this.IsHealthStateNull == false)) { - return true; - } - return false; - } - - // Converts a given datetime in DMTF format to System.DateTime object. - static System.DateTime ToDateTime(string dmtfDate) { - System.DateTime initializer = System.DateTime.MinValue; - int year = initializer.Year; - int month = initializer.Month; - int day = initializer.Day; - int hour = initializer.Hour; - int minute = initializer.Minute; - int second = initializer.Second; - long ticks = 0; - string dmtf = dmtfDate; - System.DateTime datetime = System.DateTime.MinValue; - string tempString = string.Empty; - if ((dmtf == null)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtf.Length == 0)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtf.Length != 25)) { - throw new System.ArgumentOutOfRangeException(); - } - try { - tempString = dmtf.Substring(0, 4); - if (("****" != tempString)) { - year = int.Parse(tempString); - } - tempString = dmtf.Substring(4, 2); - if (("**" != tempString)) { - month = int.Parse(tempString); - } - tempString = dmtf.Substring(6, 2); - if (("**" != tempString)) { - day = int.Parse(tempString); - } - tempString = dmtf.Substring(8, 2); - if (("**" != tempString)) { - hour = int.Parse(tempString); - } - tempString = dmtf.Substring(10, 2); - if (("**" != tempString)) { - minute = int.Parse(tempString); - } - tempString = dmtf.Substring(12, 2); - if (("**" != tempString)) { - second = int.Parse(tempString); - } - tempString = dmtf.Substring(15, 6); - if (("******" != tempString)) { - ticks = (long.Parse(tempString) * ((long)((System.TimeSpan.TicksPerMillisecond / 1000)))); - } - if (((((((((year < 0) - || (month < 0)) - || (day < 0)) - || (hour < 0)) - || (minute < 0)) - || (minute < 0)) - || (second < 0)) - || (ticks < 0))) { - throw new System.ArgumentOutOfRangeException(); - } - } - catch (System.Exception e) { - throw new System.ArgumentOutOfRangeException(null, e.Message); - } - datetime = new System.DateTime(year, month, day, hour, minute, second, 0); - datetime = datetime.AddTicks(ticks); - System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(datetime); - int UTCOffset = 0; - int OffsetToBeAdjusted = 0; - long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); - tempString = dmtf.Substring(22, 3); - if ((tempString != "******")) { - tempString = dmtf.Substring(21, 4); - try { - UTCOffset = int.Parse(tempString); - } - catch (System.Exception e) { - throw new System.ArgumentOutOfRangeException(null, e.Message); - } - OffsetToBeAdjusted = ((int)((OffsetMins - UTCOffset))); - datetime = datetime.AddMinutes(((double)(OffsetToBeAdjusted))); - } - return datetime; - } - - // Converts a given System.DateTime object to DMTF datetime format. - static string ToDmtfDateTime(System.DateTime date) { - string utcString = string.Empty; - System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(date); - long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); - if ((System.Math.Abs(OffsetMins) > 999)) { - date = date.ToUniversalTime(); - utcString = "+000"; - } - else { - if ((tickOffset.Ticks >= 0)) { - utcString = string.Concat("+", ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))).ToString().PadLeft(3, '0')); - } - else { - string strTemp = ((long)(OffsetMins)).ToString(); - utcString = string.Concat("-", strTemp.Substring(1, (strTemp.Length - 1)).PadLeft(3, '0')); - } - } - string dmtfDateTime = ((int)(date.Year)).ToString().PadLeft(4, '0'); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Month)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Day)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Hour)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Minute)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Second)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, "."); - System.DateTime dtTemp = new System.DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, 0); - long microsec = ((long)((((date.Ticks - dtTemp.Ticks) - * 1000) - / System.TimeSpan.TicksPerMillisecond))); - string strMicrosec = ((long)(microsec)).ToString(); - if ((strMicrosec.Length > 6)) { - strMicrosec = strMicrosec.Substring(0, 6); - } - dmtfDateTime = string.Concat(dmtfDateTime, strMicrosec.PadLeft(6, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, utcString); - return dmtfDateTime; - } - - private bool ShouldSerializeInstallDate() { - if ((this.IsInstallDateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeOperatingStatus() { - if ((this.IsOperatingStatusNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializePrimaryStatus() { - if ((this.IsPrimaryStatusNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeRequestedState() { - if ((this.IsRequestedStateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeStarted() { - if ((this.IsStartedNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeTimeOfLastStateChange() { - if ((this.IsTimeOfLastStateChangeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeTransitioningToState() { - if ((this.IsTransitioningToStateNull == false)) { - return true; - } - return false; - } - - [Browsable(true)] - public void CommitObject() { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(); - } - } - - [Browsable(true)] - public void CommitObject(System.Management.PutOptions putOptions) { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(putOptions); - } - } - - private void Initialize() { - AutoCommitProp = true; - isEmbedded = false; - } - - private static string ConstructPath(string keyCreationClassName, string keyName, string keySystemCreationClassName, string keySystemName) { - string strPath = "ROOT\\virtualization\\v2:Msvm_ImageManagementService"; - strPath = string.Concat(strPath, string.Concat(".CreationClassName=", string.Concat("\"", string.Concat(keyCreationClassName, "\"")))); - strPath = string.Concat(strPath, string.Concat(",Name=", string.Concat("\"", string.Concat(keyName, "\"")))); - strPath = string.Concat(strPath, string.Concat(",SystemCreationClassName=", string.Concat("\"", string.Concat(keySystemCreationClassName, "\"")))); - strPath = string.Concat(strPath, string.Concat(",SystemName=", string.Concat("\"", string.Concat(keySystemName, "\"")))); - return strPath; - } - - private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - Initialize(); - if ((path != null)) { - if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - } - PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - - // Different overloads of GetInstances() help in enumerating instances of the WMI class. - public static ImageManagementServiceCollection GetInstances() { - return GetInstances(null, null, null); - } - - public static ImageManagementServiceCollection GetInstances(string condition) { - return GetInstances(null, condition, null); - } - - public static ImageManagementServiceCollection GetInstances(string[] selectedProperties) { - return GetInstances(null, null, selectedProperties); - } - - public static ImageManagementServiceCollection GetInstances(string condition, string[] selectedProperties) { - return GetInstances(null, condition, selectedProperties); - } - - public static ImageManagementServiceCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); - pathObj.ClassName = "Msvm_ImageManagementService"; - pathObj.NamespacePath = "root\\virtualization\\v2"; - System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); - if ((enumOptions == null)) { - enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - } - return new ImageManagementServiceCollection(clsObject.GetInstances(enumOptions)); - } - - public static ImageManagementServiceCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { - return GetInstances(mgmtScope, condition, null); - } - - public static ImageManagementServiceCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { - return GetInstances(mgmtScope, null, selectedProperties); - } - - public static ImageManagementServiceCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_ImageManagementService", condition, selectedProperties)); - System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - ObjectSearcher.Options = enumOptions; - return new ImageManagementServiceCollection(ObjectSearcher.Get()); - } - - [Browsable(true)] - public static ImageManagementService CreateInstance() { - System.Management.ManagementScope mgmtScope = null; - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = CreatedWmiNamespace; - } - else { - mgmtScope = statMgmtScope; - } - System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); - System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); - return new ImageManagementService(tmpMgmtClass.CreateInstance()); - } - - [Browsable(true)] - public void Delete() { - PrivateLateBoundObject.Delete(); - } - - public uint AttachVirtualHardDisk(bool AssignDriveLetter, string Path, bool ReadOnly, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("AttachVirtualHardDisk"); - inParams["AssignDriveLetter"] = ((bool)(AssignDriveLetter)); - inParams["Path"] = ((string)(Path)); - inParams["ReadOnly"] = ((bool)(ReadOnly)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("AttachVirtualHardDisk", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null)) - { - Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - return System.Convert.ToUInt32(0); - } - } - - public uint CompactVirtualHardDisk(ushort Mode, string Path, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("CompactVirtualHardDisk"); - inParams["Mode"] = ((ushort)(Mode)); - inParams["Path"] = ((string)(Path)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("CompactVirtualHardDisk", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null)) - { - Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - return System.Convert.ToUInt32(0); - } - } - - public uint ConvertVirtualHardDisk(string SourcePath, string VirtualDiskSettingData, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("ConvertVirtualHardDisk"); - inParams["SourcePath"] = ((string)(SourcePath)); - inParams["VirtualDiskSettingData"] = ((string)(VirtualDiskSettingData)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ConvertVirtualHardDisk", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null)) - { - Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - return System.Convert.ToUInt32(0); - } - } - - public uint CreateVirtualFloppyDisk(string Path, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("CreateVirtualFloppyDisk"); - inParams["Path"] = ((string)(Path)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("CreateVirtualFloppyDisk", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null)) - { - Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - return System.Convert.ToUInt32(0); - } - } - - public uint CreateVirtualHardDisk(string VirtualDiskSettingData, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("CreateVirtualHardDisk"); - inParams["VirtualDiskSettingData"] = ((string)(VirtualDiskSettingData)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("CreateVirtualHardDisk", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null)) - { - Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - return System.Convert.ToUInt32(0); - } - } - - public uint GetVirtualHardDiskSettingData(string Path, out System.Management.ManagementPath Job, out string SettingData) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("GetVirtualHardDiskSettingData"); - inParams["Path"] = ((string)(Path)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("GetVirtualHardDiskSettingData", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null)) - { - Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); - } - SettingData = System.Convert.ToString(outParams.Properties["SettingData"].Value); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - SettingData = null; - return System.Convert.ToUInt32(0); - } - } - - public uint GetVirtualHardDiskState(string Path, out System.Management.ManagementPath Job, out string State) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("GetVirtualHardDiskState"); - inParams["Path"] = ((string)(Path)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("GetVirtualHardDiskState", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null)) - { - Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); - } - State = System.Convert.ToString(outParams.Properties["State"].Value); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - State = null; - return System.Convert.ToUInt32(0); - } - } - - public uint MergeVirtualHardDisk(string DestinationPath, string SourcePath, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("MergeVirtualHardDisk"); - inParams["DestinationPath"] = ((string)(DestinationPath)); - inParams["SourcePath"] = ((string)(SourcePath)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("MergeVirtualHardDisk", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null)) - { - Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - return System.Convert.ToUInt32(0); - } - } - - public uint RequestStateChange(ushort RequestedState, System.DateTime TimeoutPeriod, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("RequestStateChange"); - inParams["RequestedState"] = ((ushort)(RequestedState)); - inParams["TimeoutPeriod"] = ToDmtfDateTime(((System.DateTime)(TimeoutPeriod))); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RequestStateChange", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null)) - { - Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - return System.Convert.ToUInt32(0); - } - } - - public uint ResizeVirtualHardDisk(ulong MaxInternalSize, string Path, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("ResizeVirtualHardDisk"); - inParams["MaxInternalSize"] = ((ulong)(MaxInternalSize)); - inParams["Path"] = ((string)(Path)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ResizeVirtualHardDisk", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null)) - { - Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - return System.Convert.ToUInt32(0); - } - } - - public uint SetParentVirtualHardDisk(string ChildPath, bool IgnoreIDMismatch, string LeafPath, string ParentPath, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("SetParentVirtualHardDisk"); - inParams["ChildPath"] = ((string)(ChildPath)); - inParams["IgnoreIDMismatch"] = ((bool)(IgnoreIDMismatch)); - inParams["LeafPath"] = ((string)(LeafPath)); - inParams["ParentPath"] = ((string)(ParentPath)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("SetParentVirtualHardDisk", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null)) - { - Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - return System.Convert.ToUInt32(0); - } - } - - public uint SetVirtualHardDiskSettingData(string VirtualDiskSettingData, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("SetVirtualHardDiskSettingData"); - inParams["VirtualDiskSettingData"] = ((string)(VirtualDiskSettingData)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("SetVirtualHardDiskSettingData", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null)) - { - Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - return System.Convert.ToUInt32(0); - } - } - - public uint StartService() { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("StartService", inParams, null); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - return System.Convert.ToUInt32(0); - } - } - - public uint StopService() { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("StopService", inParams, null); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - return System.Convert.ToUInt32(0); - } - } - - public uint ValidateVirtualHardDisk(string Path, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("ValidateVirtualHardDisk"); - inParams["Path"] = ((string)(Path)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ValidateVirtualHardDisk", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null)) - { - Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - return System.Convert.ToUInt32(0); - } - } - - // Enumerator implementation for enumerating instances of the class. - public class ImageManagementServiceCollection : object, ICollection { - - private ManagementObjectCollection privColObj; - - public ImageManagementServiceCollection(ManagementObjectCollection objCollection) { - privColObj = objCollection; - } - - public virtual int Count { - get { - return privColObj.Count; - } - } - - public virtual bool IsSynchronized { - get { - return privColObj.IsSynchronized; - } - } - - public virtual object SyncRoot { - get { - return this; - } - } - - public virtual void CopyTo(System.Array array, int index) { - privColObj.CopyTo(array, index); - int nCtr; - for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { - array.SetValue(new ImageManagementService(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); - } - } - - public virtual System.Collections.IEnumerator GetEnumerator() { - return new ImageManagementServiceEnumerator(privColObj.GetEnumerator()); - } - - public class ImageManagementServiceEnumerator : object, System.Collections.IEnumerator { - - private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; - - public ImageManagementServiceEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { - privObjEnum = objEnum; - } - - public virtual object Current { - get { - return new ImageManagementService(((System.Management.ManagementObject)(privObjEnum.Current))); - } - } - - public virtual bool MoveNext() { - return privObjEnum.MoveNext(); - } - - public virtual void Reset() { - privObjEnum.Reset(); - } - } - } - - // TypeConverter to handle null values for ValueType properties - public class WMIValueTypeConverter : TypeConverter { - - private TypeConverter baseConverter; - - private System.Type baseType; - - public WMIValueTypeConverter(System.Type inBaseType) { - baseConverter = TypeDescriptor.GetConverter(inBaseType); - baseType = inBaseType; - } - - public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { - return baseConverter.CanConvertFrom(context, srcType); - } - - public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { - return baseConverter.CanConvertTo(context, destinationType); - } - - public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { - return baseConverter.ConvertFrom(context, culture, value); - } - - public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { - return baseConverter.CreateInstance(context, dictionary); - } - - public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetCreateInstanceSupported(context); - } - - public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { - return baseConverter.GetProperties(context, value, attributeVar); - } - - public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetPropertiesSupported(context); - } - - public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValues(context); - } - - public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesExclusive(context); - } - - public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesSupported(context); - } - - public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { - if ((baseType.BaseType == typeof(System.Enum))) { - if ((value.GetType() == destinationType)) { - return value; - } - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return "NULL_ENUM_VALUE" ; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((baseType == typeof(bool)) - && (baseType.BaseType == typeof(System.ValueType)))) { - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((context != null) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - } - - // Embedded class to represent WMI system Properties. - [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] - public class ManagementSystemProperties { - - private System.Management.ManagementBaseObject PrivateLateBoundObject; - - public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { - PrivateLateBoundObject = ManagedObject; - } - - [Browsable(true)] - public int GENUS { - get { - return ((int)(PrivateLateBoundObject["__GENUS"])); - } - } - - [Browsable(true)] - public string CLASS { - get { - return ((string)(PrivateLateBoundObject["__CLASS"])); - } - } - - [Browsable(true)] - public string SUPERCLASS { - get { - return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); - } - } - - [Browsable(true)] - public string DYNASTY { - get { - return ((string)(PrivateLateBoundObject["__DYNASTY"])); - } - } - - [Browsable(true)] - public string RELPATH { - get { - return ((string)(PrivateLateBoundObject["__RELPATH"])); - } - } - - [Browsable(true)] - public int PROPERTY_COUNT { - get { - return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); - } - } - - [Browsable(true)] - public string[] DERIVATION { - get { - return ((string[])(PrivateLateBoundObject["__DERIVATION"])); - } - } - - [Browsable(true)] - public string SERVER { - get { - return ((string)(PrivateLateBoundObject["__SERVER"])); - } - } - - [Browsable(true)] - public string NAMESPACE { - get { - return ((string)(PrivateLateBoundObject["__NAMESPACE"])); - } - } - - [Browsable(true)] - public string PATH { - get { - return ((string)(PrivateLateBoundObject["__PATH"])); - } - } - } - } -} +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2 { + using System; + using System.ComponentModel; + using System.Management; + using System.Collections; + using System.Globalization; + using System.ComponentModel.Design.Serialization; + using System.Reflection; + + + // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. + // Functions IsNull() are used to check if a property is NULL. + // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. + // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. + // Datetime conversion functions ToDateTime and ToDmtfDateTime are added to the class to convert DMTF datetime to System.DateTime and vice-versa. + // An Early Bound class generated for the WMI class.Msvm_ImageManagementService + public class ImageManagementService : System.ComponentModel.Component { + + // Private property to hold the WMI namespace in which the class resides. + private static string CreatedWmiNamespace = "ROOT\\virtualization\\v2"; + + // Private property to hold the name of WMI class which created this class. + private static string CreatedClassName = "Msvm_ImageManagementService"; + + // Private member variable to hold the ManagementScope which is used by the various methods. + private static System.Management.ManagementScope statMgmtScope = null; + + private ManagementSystemProperties PrivateSystemProperties; + + // Underlying lateBound WMI object. + private System.Management.ManagementObject PrivateLateBoundObject; + + // Member variable to store the 'automatic commit' behavior for the class. + private bool AutoCommitProp; + + // Private variable to hold the embedded property representing the instance. + private System.Management.ManagementBaseObject embeddedObj; + + // The current WMI object used + private System.Management.ManagementBaseObject curObj; + + // Flag to indicate if the instance is an embedded object. + private bool isEmbedded; + + // Below are different overloads of constructors to initialize an instance of the class with a WMI object. + public ImageManagementService() { + this.InitializeObject(null, null, null); + } + + public ImageManagementService(string keyCreationClassName, string keyName, string keySystemCreationClassName, string keySystemName) { + this.InitializeObject(null, new System.Management.ManagementPath(ImageManagementService.ConstructPath(keyCreationClassName, keyName, keySystemCreationClassName, keySystemName)), null); + } + + public ImageManagementService(System.Management.ManagementScope mgmtScope, string keyCreationClassName, string keyName, string keySystemCreationClassName, string keySystemName) { + this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(ImageManagementService.ConstructPath(keyCreationClassName, keyName, keySystemCreationClassName, keySystemName)), null); + } + + public ImageManagementService(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(null, path, getOptions); + } + + public ImageManagementService(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { + this.InitializeObject(mgmtScope, path, null); + } + + public ImageManagementService(System.Management.ManagementPath path) { + this.InitializeObject(null, path, null); + } + + public ImageManagementService(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(mgmtScope, path, getOptions); + } + + public ImageManagementService(System.Management.ManagementObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + PrivateLateBoundObject = theObject; + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + public ImageManagementService(System.Management.ManagementBaseObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + embeddedObj = theObject; + PrivateSystemProperties = new ManagementSystemProperties(theObject); + curObj = embeddedObj; + isEmbedded = true; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + // Property returns the namespace of the WMI class. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OriginatingNamespace { + get { + return "ROOT\\virtualization\\v2"; + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ManagementClassName { + get { + string strRet = CreatedClassName; + if ((curObj != null)) { + if ((curObj.ClassPath != null)) { + strRet = ((string)(curObj["__CLASS"])); + if (((strRet == null) + || (strRet == string.Empty))) { + strRet = CreatedClassName; + } + } + } + return strRet; + } + } + + // Property pointing to an embedded object to get System properties of the WMI object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ManagementSystemProperties SystemProperties { + get { + return PrivateSystemProperties; + } + } + + // Property returning the underlying lateBound object. + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementBaseObject LateBoundObject { + get { + return curObj; + } + } + + // ManagementScope of the object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementScope Scope { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Scope; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Scope = value; + } + } + } + + // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool AutoCommit { + get { + return AutoCommitProp; + } + set { + AutoCommitProp = value; + } + } + + // The ManagementPath of the underlying WMI object. + [Browsable(true)] + public System.Management.ManagementPath Path { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Path; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + if ((CheckIfProperClass(null, value, null) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + PrivateLateBoundObject.Path = value; + } + } + } + + // Public static scope property which is used by the various methods. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public static System.Management.ManagementScope StaticScope { + get { + return statMgmtScope; + } + set { + statMgmtScope = value; + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ushort[] AvailableRequestedStates { + get { + return ((ushort[])(curObj["AvailableRequestedStates"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Caption { + get { + return ((string)(curObj["Caption"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsCommunicationStatusNull { + get { + if ((curObj["CommunicationStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort CommunicationStatus { + get { + if ((curObj["CommunicationStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["CommunicationStatus"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string CreationClassName { + get { + return ((string)(curObj["CreationClassName"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Description { + get { + return ((string)(curObj["Description"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsDetailedStatusNull { + get { + if ((curObj["DetailedStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort DetailedStatus { + get { + if ((curObj["DetailedStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["DetailedStatus"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ElementName { + get { + return ((string)(curObj["ElementName"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsEnabledDefaultNull { + get { + if ((curObj["EnabledDefault"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort EnabledDefault { + get { + if ((curObj["EnabledDefault"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["EnabledDefault"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsEnabledStateNull { + get { + if ((curObj["EnabledState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort EnabledState { + get { + if ((curObj["EnabledState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["EnabledState"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsHealthStateNull { + get { + if ((curObj["HealthState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort HealthState { + get { + if ((curObj["HealthState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["HealthState"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsInstallDateNull { + get { + if ((curObj["InstallDate"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime InstallDate { + get { + if ((curObj["InstallDate"] != null)) { + return ToDateTime(((string)(curObj["InstallDate"]))); + } + else { + return System.DateTime.MinValue; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string InstanceID { + get { + return ((string)(curObj["InstanceID"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Name { + get { + return ((string)(curObj["Name"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsOperatingStatusNull { + get { + if ((curObj["OperatingStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort OperatingStatus { + get { + if ((curObj["OperatingStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["OperatingStatus"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ushort[] OperationalStatus { + get { + return ((ushort[])(curObj["OperationalStatus"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherEnabledState { + get { + return ((string)(curObj["OtherEnabledState"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string PrimaryOwnerContact { + get { + return ((string)(curObj["PrimaryOwnerContact"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string PrimaryOwnerName { + get { + return ((string)(curObj["PrimaryOwnerName"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPrimaryStatusNull { + get { + if ((curObj["PrimaryStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort PrimaryStatus { + get { + if ((curObj["PrimaryStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["PrimaryStatus"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsRequestedStateNull { + get { + if ((curObj["RequestedState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort RequestedState { + get { + if ((curObj["RequestedState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["RequestedState"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsStartedNull { + get { + if ((curObj["Started"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool Started { + get { + if ((curObj["Started"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["Started"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string StartMode { + get { + return ((string)(curObj["StartMode"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Status { + get { + return ((string)(curObj["Status"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] StatusDescriptions { + get { + return ((string[])(curObj["StatusDescriptions"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string SystemCreationClassName { + get { + return ((string)(curObj["SystemCreationClassName"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string SystemName { + get { + return ((string)(curObj["SystemName"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsTimeOfLastStateChangeNull { + get { + if ((curObj["TimeOfLastStateChange"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime TimeOfLastStateChange { + get { + if ((curObj["TimeOfLastStateChange"] != null)) { + return ToDateTime(((string)(curObj["TimeOfLastStateChange"]))); + } + else { + return System.DateTime.MinValue; + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsTransitioningToStateNull { + get { + if ((curObj["TransitioningToState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort TransitioningToState { + get { + if ((curObj["TransitioningToState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["TransitioningToState"])); + } + } + + private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { + if (((path != null) + && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); + } + } + + private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { + if (((theObj != null) + && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); + if ((parentClasses != null)) { + int count = 0; + for (count = 0; (count < parentClasses.Length); count = (count + 1)) { + if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { + return true; + } + } + } + } + return false; + } + + private bool ShouldSerializeCommunicationStatus() { + if ((this.IsCommunicationStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeDetailedStatus() { + if ((this.IsDetailedStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeEnabledDefault() { + if ((this.IsEnabledDefaultNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeEnabledState() { + if ((this.IsEnabledStateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeHealthState() { + if ((this.IsHealthStateNull == false)) { + return true; + } + return false; + } + + // Converts a given datetime in DMTF format to System.DateTime object. + static System.DateTime ToDateTime(string dmtfDate) { + System.DateTime initializer = System.DateTime.MinValue; + int year = initializer.Year; + int month = initializer.Month; + int day = initializer.Day; + int hour = initializer.Hour; + int minute = initializer.Minute; + int second = initializer.Second; + long ticks = 0; + string dmtf = dmtfDate; + System.DateTime datetime = System.DateTime.MinValue; + string tempString = string.Empty; + if ((dmtf == null)) { + throw new System.ArgumentOutOfRangeException(); + } + if ((dmtf.Length == 0)) { + throw new System.ArgumentOutOfRangeException(); + } + if ((dmtf.Length != 25)) { + throw new System.ArgumentOutOfRangeException(); + } + try { + tempString = dmtf.Substring(0, 4); + if (("****" != tempString)) { + year = int.Parse(tempString); + } + tempString = dmtf.Substring(4, 2); + if (("**" != tempString)) { + month = int.Parse(tempString); + } + tempString = dmtf.Substring(6, 2); + if (("**" != tempString)) { + day = int.Parse(tempString); + } + tempString = dmtf.Substring(8, 2); + if (("**" != tempString)) { + hour = int.Parse(tempString); + } + tempString = dmtf.Substring(10, 2); + if (("**" != tempString)) { + minute = int.Parse(tempString); + } + tempString = dmtf.Substring(12, 2); + if (("**" != tempString)) { + second = int.Parse(tempString); + } + tempString = dmtf.Substring(15, 6); + if (("******" != tempString)) { + ticks = (long.Parse(tempString) * ((long)((System.TimeSpan.TicksPerMillisecond / 1000)))); + } + if (((((((((year < 0) + || (month < 0)) + || (day < 0)) + || (hour < 0)) + || (minute < 0)) + || (minute < 0)) + || (second < 0)) + || (ticks < 0))) { + throw new System.ArgumentOutOfRangeException(); + } + } + catch (System.Exception e) { + throw new System.ArgumentOutOfRangeException(null, e.Message); + } + datetime = new System.DateTime(year, month, day, hour, minute, second, 0); + datetime = datetime.AddTicks(ticks); + System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(datetime); + int UTCOffset = 0; + int OffsetToBeAdjusted = 0; + long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); + tempString = dmtf.Substring(22, 3); + if ((tempString != "******")) { + tempString = dmtf.Substring(21, 4); + try { + UTCOffset = int.Parse(tempString); + } + catch (System.Exception e) { + throw new System.ArgumentOutOfRangeException(null, e.Message); + } + OffsetToBeAdjusted = ((int)((OffsetMins - UTCOffset))); + datetime = datetime.AddMinutes(((double)(OffsetToBeAdjusted))); + } + return datetime; + } + + // Converts a given System.DateTime object to DMTF datetime format. + static string ToDmtfDateTime(System.DateTime date) { + string utcString = string.Empty; + System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(date); + long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); + if ((System.Math.Abs(OffsetMins) > 999)) { + date = date.ToUniversalTime(); + utcString = "+000"; + } + else { + if ((tickOffset.Ticks >= 0)) { + utcString = string.Concat("+", ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))).ToString().PadLeft(3, '0')); + } + else { + string strTemp = ((long)(OffsetMins)).ToString(); + utcString = string.Concat("-", strTemp.Substring(1, (strTemp.Length - 1)).PadLeft(3, '0')); + } + } + string dmtfDateTime = ((int)(date.Year)).ToString().PadLeft(4, '0'); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Month)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Day)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Hour)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Minute)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Second)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, "."); + System.DateTime dtTemp = new System.DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, 0); + long microsec = ((long)((((date.Ticks - dtTemp.Ticks) + * 1000) + / System.TimeSpan.TicksPerMillisecond))); + string strMicrosec = ((long)(microsec)).ToString(); + if ((strMicrosec.Length > 6)) { + strMicrosec = strMicrosec.Substring(0, 6); + } + dmtfDateTime = string.Concat(dmtfDateTime, strMicrosec.PadLeft(6, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, utcString); + return dmtfDateTime; + } + + private bool ShouldSerializeInstallDate() { + if ((this.IsInstallDateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeOperatingStatus() { + if ((this.IsOperatingStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePrimaryStatus() { + if ((this.IsPrimaryStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeRequestedState() { + if ((this.IsRequestedStateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeStarted() { + if ((this.IsStartedNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeTimeOfLastStateChange() { + if ((this.IsTimeOfLastStateChangeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeTransitioningToState() { + if ((this.IsTransitioningToStateNull == false)) { + return true; + } + return false; + } + + [Browsable(true)] + public void CommitObject() { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(); + } + } + + [Browsable(true)] + public void CommitObject(System.Management.PutOptions putOptions) { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(putOptions); + } + } + + private void Initialize() { + AutoCommitProp = true; + isEmbedded = false; + } + + private static string ConstructPath(string keyCreationClassName, string keyName, string keySystemCreationClassName, string keySystemName) { + string strPath = "ROOT\\virtualization\\v2:Msvm_ImageManagementService"; + strPath = string.Concat(strPath, string.Concat(".CreationClassName=", string.Concat("\"", string.Concat(keyCreationClassName, "\"")))); + strPath = string.Concat(strPath, string.Concat(",Name=", string.Concat("\"", string.Concat(keyName, "\"")))); + strPath = string.Concat(strPath, string.Concat(",SystemCreationClassName=", string.Concat("\"", string.Concat(keySystemCreationClassName, "\"")))); + strPath = string.Concat(strPath, string.Concat(",SystemName=", string.Concat("\"", string.Concat(keySystemName, "\"")))); + return strPath; + } + + private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + Initialize(); + if ((path != null)) { + if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + } + PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + + // Different overloads of GetInstances() help in enumerating instances of the WMI class. + public static ImageManagementServiceCollection GetInstances() { + return GetInstances(null, null, null); + } + + public static ImageManagementServiceCollection GetInstances(string condition) { + return GetInstances(null, condition, null); + } + + public static ImageManagementServiceCollection GetInstances(string[] selectedProperties) { + return GetInstances(null, null, selectedProperties); + } + + public static ImageManagementServiceCollection GetInstances(string condition, string[] selectedProperties) { + return GetInstances(null, condition, selectedProperties); + } + + public static ImageManagementServiceCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); + pathObj.ClassName = "Msvm_ImageManagementService"; + pathObj.NamespacePath = "root\\virtualization\\v2"; + System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); + if ((enumOptions == null)) { + enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + } + return new ImageManagementServiceCollection(clsObject.GetInstances(enumOptions)); + } + + public static ImageManagementServiceCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { + return GetInstances(mgmtScope, condition, null); + } + + public static ImageManagementServiceCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { + return GetInstances(mgmtScope, null, selectedProperties); + } + + public static ImageManagementServiceCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_ImageManagementService", condition, selectedProperties)); + System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + ObjectSearcher.Options = enumOptions; + return new ImageManagementServiceCollection(ObjectSearcher.Get()); + } + + [Browsable(true)] + public static ImageManagementService CreateInstance() { + System.Management.ManagementScope mgmtScope = null; + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = CreatedWmiNamespace; + } + else { + mgmtScope = statMgmtScope; + } + System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); + System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); + return new ImageManagementService(tmpMgmtClass.CreateInstance()); + } + + [Browsable(true)] + public void Delete() { + PrivateLateBoundObject.Delete(); + } + + public uint AttachVirtualHardDisk(bool AssignDriveLetter, string Path, bool ReadOnly, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("AttachVirtualHardDisk"); + inParams["AssignDriveLetter"] = ((bool)(AssignDriveLetter)); + inParams["Path"] = ((string)(Path)); + inParams["ReadOnly"] = ((bool)(ReadOnly)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("AttachVirtualHardDisk", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null)) + { + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + return System.Convert.ToUInt32(0); + } + } + + public uint CompactVirtualHardDisk(ushort Mode, string Path, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("CompactVirtualHardDisk"); + inParams["Mode"] = ((ushort)(Mode)); + inParams["Path"] = ((string)(Path)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("CompactVirtualHardDisk", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null)) + { + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + return System.Convert.ToUInt32(0); + } + } + + public uint ConvertVirtualHardDisk(string SourcePath, string VirtualDiskSettingData, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("ConvertVirtualHardDisk"); + inParams["SourcePath"] = ((string)(SourcePath)); + inParams["VirtualDiskSettingData"] = ((string)(VirtualDiskSettingData)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ConvertVirtualHardDisk", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null)) + { + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + return System.Convert.ToUInt32(0); + } + } + + public uint CreateVirtualFloppyDisk(string Path, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("CreateVirtualFloppyDisk"); + inParams["Path"] = ((string)(Path)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("CreateVirtualFloppyDisk", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null)) + { + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + return System.Convert.ToUInt32(0); + } + } + + public uint CreateVirtualHardDisk(string VirtualDiskSettingData, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("CreateVirtualHardDisk"); + inParams["VirtualDiskSettingData"] = ((string)(VirtualDiskSettingData)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("CreateVirtualHardDisk", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null)) + { + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + return System.Convert.ToUInt32(0); + } + } + + public uint GetVirtualHardDiskSettingData(string Path, out System.Management.ManagementPath Job, out string SettingData) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("GetVirtualHardDiskSettingData"); + inParams["Path"] = ((string)(Path)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("GetVirtualHardDiskSettingData", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null)) + { + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); + } + SettingData = System.Convert.ToString(outParams.Properties["SettingData"].Value); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + SettingData = null; + return System.Convert.ToUInt32(0); + } + } + + public uint GetVirtualHardDiskState(string Path, out System.Management.ManagementPath Job, out string State) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("GetVirtualHardDiskState"); + inParams["Path"] = ((string)(Path)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("GetVirtualHardDiskState", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null)) + { + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); + } + State = System.Convert.ToString(outParams.Properties["State"].Value); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + State = null; + return System.Convert.ToUInt32(0); + } + } + + public uint MergeVirtualHardDisk(string DestinationPath, string SourcePath, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("MergeVirtualHardDisk"); + inParams["DestinationPath"] = ((string)(DestinationPath)); + inParams["SourcePath"] = ((string)(SourcePath)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("MergeVirtualHardDisk", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null)) + { + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + return System.Convert.ToUInt32(0); + } + } + + public uint RequestStateChange(ushort RequestedState, System.DateTime TimeoutPeriod, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("RequestStateChange"); + inParams["RequestedState"] = ((ushort)(RequestedState)); + inParams["TimeoutPeriod"] = ToDmtfDateTime(((System.DateTime)(TimeoutPeriod))); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RequestStateChange", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null)) + { + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + return System.Convert.ToUInt32(0); + } + } + + public uint ResizeVirtualHardDisk(ulong MaxInternalSize, string Path, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("ResizeVirtualHardDisk"); + inParams["MaxInternalSize"] = ((ulong)(MaxInternalSize)); + inParams["Path"] = ((string)(Path)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ResizeVirtualHardDisk", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null)) + { + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + return System.Convert.ToUInt32(0); + } + } + + public uint SetParentVirtualHardDisk(string ChildPath, bool IgnoreIDMismatch, string LeafPath, string ParentPath, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("SetParentVirtualHardDisk"); + inParams["ChildPath"] = ((string)(ChildPath)); + inParams["IgnoreIDMismatch"] = ((bool)(IgnoreIDMismatch)); + inParams["LeafPath"] = ((string)(LeafPath)); + inParams["ParentPath"] = ((string)(ParentPath)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("SetParentVirtualHardDisk", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null)) + { + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + return System.Convert.ToUInt32(0); + } + } + + public uint SetVirtualHardDiskSettingData(string VirtualDiskSettingData, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("SetVirtualHardDiskSettingData"); + inParams["VirtualDiskSettingData"] = ((string)(VirtualDiskSettingData)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("SetVirtualHardDiskSettingData", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null)) + { + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + return System.Convert.ToUInt32(0); + } + } + + public uint StartService() { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("StartService", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + public uint StopService() { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("StopService", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + public uint ValidateVirtualHardDisk(string Path, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("ValidateVirtualHardDisk"); + inParams["Path"] = ((string)(Path)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ValidateVirtualHardDisk", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null)) + { + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + return System.Convert.ToUInt32(0); + } + } + + // Enumerator implementation for enumerating instances of the class. + public class ImageManagementServiceCollection : object, ICollection { + + private ManagementObjectCollection privColObj; + + public ImageManagementServiceCollection(ManagementObjectCollection objCollection) { + privColObj = objCollection; + } + + public virtual int Count { + get { + return privColObj.Count; + } + } + + public virtual bool IsSynchronized { + get { + return privColObj.IsSynchronized; + } + } + + public virtual object SyncRoot { + get { + return this; + } + } + + public virtual void CopyTo(System.Array array, int index) { + privColObj.CopyTo(array, index); + int nCtr; + for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { + array.SetValue(new ImageManagementService(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); + } + } + + public virtual System.Collections.IEnumerator GetEnumerator() { + return new ImageManagementServiceEnumerator(privColObj.GetEnumerator()); + } + + public class ImageManagementServiceEnumerator : object, System.Collections.IEnumerator { + + private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; + + public ImageManagementServiceEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { + privObjEnum = objEnum; + } + + public virtual object Current { + get { + return new ImageManagementService(((System.Management.ManagementObject)(privObjEnum.Current))); + } + } + + public virtual bool MoveNext() { + return privObjEnum.MoveNext(); + } + + public virtual void Reset() { + privObjEnum.Reset(); + } + } + } + + // TypeConverter to handle null values for ValueType properties + public class WMIValueTypeConverter : TypeConverter { + + private TypeConverter baseConverter; + + private System.Type baseType; + + public WMIValueTypeConverter(System.Type inBaseType) { + baseConverter = TypeDescriptor.GetConverter(inBaseType); + baseType = inBaseType; + } + + public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { + return baseConverter.CanConvertFrom(context, srcType); + } + + public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { + return baseConverter.CanConvertTo(context, destinationType); + } + + public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { + return baseConverter.ConvertFrom(context, culture, value); + } + + public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { + return baseConverter.CreateInstance(context, dictionary); + } + + public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetCreateInstanceSupported(context); + } + + public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { + return baseConverter.GetProperties(context, value, attributeVar); + } + + public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetPropertiesSupported(context); + } + + public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValues(context); + } + + public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesExclusive(context); + } + + public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesSupported(context); + } + + public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { + if ((baseType.BaseType == typeof(System.Enum))) { + if ((value.GetType() == destinationType)) { + return value; + } + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return "NULL_ENUM_VALUE" ; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((baseType == typeof(bool)) + && (baseType.BaseType == typeof(System.ValueType)))) { + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((context != null) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + } + + // Embedded class to represent WMI system Properties. + [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] + public class ManagementSystemProperties { + + private System.Management.ManagementBaseObject PrivateLateBoundObject; + + public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { + PrivateLateBoundObject = ManagedObject; + } + + [Browsable(true)] + public int GENUS { + get { + return ((int)(PrivateLateBoundObject["__GENUS"])); + } + } + + [Browsable(true)] + public string CLASS { + get { + return ((string)(PrivateLateBoundObject["__CLASS"])); + } + } + + [Browsable(true)] + public string SUPERCLASS { + get { + return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); + } + } + + [Browsable(true)] + public string DYNASTY { + get { + return ((string)(PrivateLateBoundObject["__DYNASTY"])); + } + } + + [Browsable(true)] + public string RELPATH { + get { + return ((string)(PrivateLateBoundObject["__RELPATH"])); + } + } + + [Browsable(true)] + public int PROPERTY_COUNT { + get { + return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); + } + } + + [Browsable(true)] + public string[] DERIVATION { + get { + return ((string[])(PrivateLateBoundObject["__DERIVATION"])); + } + } + + [Browsable(true)] + public string SERVER { + get { + return ((string)(PrivateLateBoundObject["__SERVER"])); + } + } + + [Browsable(true)] + public string NAMESPACE { + get { + return ((string)(PrivateLateBoundObject["__NAMESPACE"])); + } + } + + [Browsable(true)] + public string PATH { + get { + return ((string)(PrivateLateBoundObject["__PATH"])); + } + } + } + } +} diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_KvpExchangeComponent.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_KvpExchangeComponent.cs index d9f6c5667a6..aaf02d6beaf 100644 --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_KvpExchangeComponent.cs +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_KvpExchangeComponent.cs @@ -1,1615 +1,1615 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2 -{ - using System; - using System.ComponentModel; - using System.Management; - using System.Collections; - using System.Globalization; - using System.ComponentModel.Design.Serialization; - using System.Reflection; - - - // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. - // Functions IsNull() are used to check if a property is NULL. - // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. - // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. - // Datetime conversion functions ToDateTime and ToDmtfDateTime are added to the class to convert DMTF datetime to System.DateTime and vice-versa. - // An Early Bound class generated for the WMI class.Msvm_KvpExchangeComponent - public class KvpExchangeComponent : System.ComponentModel.Component { - - // Private property to hold the WMI namespace in which the class resides. - private static string CreatedWmiNamespace = "ROOT\\virtualization\\v2"; - - // Private property to hold the name of WMI class which created this class. - private static string CreatedClassName = "Msvm_KvpExchangeComponent"; - - // Private member variable to hold the ManagementScope which is used by the various methods. - private static System.Management.ManagementScope statMgmtScope = null; - - private ManagementSystemProperties PrivateSystemProperties; - - // Underlying lateBound WMI object. - private System.Management.ManagementObject PrivateLateBoundObject; - - // Member variable to store the 'automatic commit' behavior for the class. - private bool AutoCommitProp; - - // Private variable to hold the embedded property representing the instance. - private System.Management.ManagementBaseObject embeddedObj; - - // The current WMI object used - private System.Management.ManagementBaseObject curObj; - - // Flag to indicate if the instance is an embedded object. - private bool isEmbedded; - - // Below are different overloads of constructors to initialize an instance of the class with a WMI object. - public KvpExchangeComponent() { - this.InitializeObject(null, null, null); - } - - public KvpExchangeComponent(string keyCreationClassName, string keyDeviceID, string keySystemCreationClassName, string keySystemName) { - this.InitializeObject(null, new System.Management.ManagementPath(KvpExchangeComponent.ConstructPath(keyCreationClassName, keyDeviceID, keySystemCreationClassName, keySystemName)), null); - } - - public KvpExchangeComponent(System.Management.ManagementScope mgmtScope, string keyCreationClassName, string keyDeviceID, string keySystemCreationClassName, string keySystemName) { - this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(KvpExchangeComponent.ConstructPath(keyCreationClassName, keyDeviceID, keySystemCreationClassName, keySystemName)), null); - } - - public KvpExchangeComponent(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(null, path, getOptions); - } - - public KvpExchangeComponent(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { - this.InitializeObject(mgmtScope, path, null); - } - - public KvpExchangeComponent(System.Management.ManagementPath path) { - this.InitializeObject(null, path, null); - } - - public KvpExchangeComponent(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(mgmtScope, path, getOptions); - } - - public KvpExchangeComponent(System.Management.ManagementObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - PrivateLateBoundObject = theObject; - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - public KvpExchangeComponent(System.Management.ManagementBaseObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - embeddedObj = theObject; - PrivateSystemProperties = new ManagementSystemProperties(theObject); - curObj = embeddedObj; - isEmbedded = true; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - // Property returns the namespace of the WMI class. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OriginatingNamespace { - get { - return "ROOT\\virtualization\\v2"; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ManagementClassName { - get { - string strRet = CreatedClassName; - if ((curObj != null)) { - if ((curObj.ClassPath != null)) { - strRet = ((string)(curObj["__CLASS"])); - if (((strRet == null) - || (strRet == string.Empty))) { - strRet = CreatedClassName; - } - } - } - return strRet; - } - } - - // Property pointing to an embedded object to get System properties of the WMI object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ManagementSystemProperties SystemProperties { - get { - return PrivateSystemProperties; - } - } - - // Property returning the underlying lateBound object. - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementBaseObject LateBoundObject { - get { - return curObj; - } - } - - // ManagementScope of the object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementScope Scope { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Scope; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Scope = value; - } - } - } - - // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool AutoCommit { - get { - return AutoCommitProp; - } - set { - AutoCommitProp = value; - } - } - - // The ManagementPath of the underlying WMI object. - [Browsable(true)] - public System.Management.ManagementPath Path { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Path; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - if ((CheckIfProperClass(null, value, null) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - PrivateLateBoundObject.Path = value; - } - } - } - - // Public static scope property which is used by the various methods. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public static System.Management.ManagementScope StaticScope { - get { - return statMgmtScope; - } - set { - statMgmtScope = value; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ushort[] AdditionalAvailability { - get { - return ((ushort[])(curObj["AdditionalAvailability"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsAvailabilityNull { - get { - if ((curObj["Availability"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort Availability { - get { - if ((curObj["Availability"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["Availability"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ushort[] AvailableRequestedStates { - get { - return ((ushort[])(curObj["AvailableRequestedStates"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Caption { - get { - return ((string)(curObj["Caption"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsCommunicationStatusNull { - get { - if ((curObj["CommunicationStatus"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort CommunicationStatus { - get { - if ((curObj["CommunicationStatus"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["CommunicationStatus"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string CreationClassName { - get { - return ((string)(curObj["CreationClassName"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Description { - get { - return ((string)(curObj["Description"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsDetailedStatusNull { - get { - if ((curObj["DetailedStatus"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort DetailedStatus { - get { - if ((curObj["DetailedStatus"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["DetailedStatus"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string DeviceID { - get { - return ((string)(curObj["DeviceID"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ElementName { - get { - return ((string)(curObj["ElementName"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsEnabledDefaultNull { - get { - if ((curObj["EnabledDefault"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort EnabledDefault { - get { - if ((curObj["EnabledDefault"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["EnabledDefault"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsEnabledStateNull { - get { - if ((curObj["EnabledState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort EnabledState { - get { - if ((curObj["EnabledState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["EnabledState"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsErrorClearedNull { - get { - if ((curObj["ErrorCleared"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool ErrorCleared { - get { - if ((curObj["ErrorCleared"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["ErrorCleared"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ErrorDescription { - get { - return ((string)(curObj["ErrorDescription"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description(@"An array of embedded Msvm_KvpExchangeDataItem instances which contain the set of key-value pairs that components running within the guest operating system have pushed up to be available for access by external clients. This array will not contain any intrinsic items that are pushed by the integration component directly.")] - public string[] GuestExchangeItems { - get { - return ((string[])(curObj["GuestExchangeItems"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description(@"An array of embedded Msvm_KvpExchangeDataItem instances which contain the set of key-value pairs that the guest operating system has pushed up to be available for access by external clients. This array will not contain any data items pushed by other components running within the guest operating system.")] - public string[] GuestIntrinsicExchangeItems { - get { - return ((string[])(curObj["GuestIntrinsicExchangeItems"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsHealthStateNull { - get { - if ((curObj["HealthState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort HealthState { - get { - if ((curObj["HealthState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["HealthState"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] IdentifyingDescriptions { - get { - return ((string[])(curObj["IdentifyingDescriptions"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsInstallDateNull { - get { - if ((curObj["InstallDate"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public System.DateTime InstallDate { - get { - if ((curObj["InstallDate"] != null)) { - return ToDateTime(((string)(curObj["InstallDate"]))); - } - else { - return System.DateTime.MinValue; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string InstanceID { - get { - return ((string)(curObj["InstanceID"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsLastErrorCodeNull { - get { - if ((curObj["LastErrorCode"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public uint LastErrorCode { - get { - if ((curObj["LastErrorCode"] == null)) { - return System.Convert.ToUInt32(0); - } - return ((uint)(curObj["LastErrorCode"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsMaxQuiesceTimeNull { - get { - if ((curObj["MaxQuiesceTime"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong MaxQuiesceTime { - get { - if ((curObj["MaxQuiesceTime"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["MaxQuiesceTime"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Name { - get { - return ((string)(curObj["Name"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsOperatingStatusNull { - get { - if ((curObj["OperatingStatus"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort OperatingStatus { - get { - if ((curObj["OperatingStatus"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["OperatingStatus"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ushort[] OperationalStatus { - get { - return ((ushort[])(curObj["OperationalStatus"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OtherEnabledState { - get { - return ((string)(curObj["OtherEnabledState"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] OtherIdentifyingInfo { - get { - return ((string[])(curObj["OtherIdentifyingInfo"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ushort[] PowerManagementCapabilities { - get { - return ((ushort[])(curObj["PowerManagementCapabilities"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsPowerManagementSupportedNull { - get { - if ((curObj["PowerManagementSupported"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool PowerManagementSupported { - get { - if ((curObj["PowerManagementSupported"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["PowerManagementSupported"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsPowerOnHoursNull { - get { - if ((curObj["PowerOnHours"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong PowerOnHours { - get { - if ((curObj["PowerOnHours"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["PowerOnHours"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsPrimaryStatusNull { - get { - if ((curObj["PrimaryStatus"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort PrimaryStatus { - get { - if ((curObj["PrimaryStatus"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["PrimaryStatus"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsRequestedStateNull { - get { - if ((curObj["RequestedState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort RequestedState { - get { - if ((curObj["RequestedState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["RequestedState"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Status { - get { - return ((string)(curObj["Status"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] StatusDescriptions { - get { - return ((string[])(curObj["StatusDescriptions"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsStatusInfoNull { - get { - if ((curObj["StatusInfo"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort StatusInfo { - get { - if ((curObj["StatusInfo"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["StatusInfo"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string SystemCreationClassName { - get { - return ((string)(curObj["SystemCreationClassName"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string SystemName { - get { - return ((string)(curObj["SystemName"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsTimeOfLastStateChangeNull { - get { - if ((curObj["TimeOfLastStateChange"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public System.DateTime TimeOfLastStateChange { - get { - if ((curObj["TimeOfLastStateChange"] != null)) { - return ToDateTime(((string)(curObj["TimeOfLastStateChange"]))); - } - else { - return System.DateTime.MinValue; - } - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsTotalPowerOnHoursNull { - get { - if ((curObj["TotalPowerOnHours"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong TotalPowerOnHours { - get { - if ((curObj["TotalPowerOnHours"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["TotalPowerOnHours"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsTransitioningToStateNull { - get { - if ((curObj["TransitioningToState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort TransitioningToState { - get { - if ((curObj["TransitioningToState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["TransitioningToState"])); - } - } - - private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { - if (((path != null) - && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); - } - } - - private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { - if (((theObj != null) - && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); - if ((parentClasses != null)) { - int count = 0; - for (count = 0; (count < parentClasses.Length); count = (count + 1)) { - if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { - return true; - } - } - } - } - return false; - } - - private bool ShouldSerializeAvailability() { - if ((this.IsAvailabilityNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeCommunicationStatus() { - if ((this.IsCommunicationStatusNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeDetailedStatus() { - if ((this.IsDetailedStatusNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeEnabledDefault() { - if ((this.IsEnabledDefaultNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeEnabledState() { - if ((this.IsEnabledStateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeErrorCleared() { - if ((this.IsErrorClearedNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeHealthState() { - if ((this.IsHealthStateNull == false)) { - return true; - } - return false; - } - - // Converts a given datetime in DMTF format to System.DateTime object. - static System.DateTime ToDateTime(string dmtfDate) { - System.DateTime initializer = System.DateTime.MinValue; - int year = initializer.Year; - int month = initializer.Month; - int day = initializer.Day; - int hour = initializer.Hour; - int minute = initializer.Minute; - int second = initializer.Second; - long ticks = 0; - string dmtf = dmtfDate; - System.DateTime datetime = System.DateTime.MinValue; - string tempString = string.Empty; - if ((dmtf == null)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtf.Length == 0)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtf.Length != 25)) { - throw new System.ArgumentOutOfRangeException(); - } - try { - tempString = dmtf.Substring(0, 4); - if (("****" != tempString)) { - year = int.Parse(tempString); - } - tempString = dmtf.Substring(4, 2); - if (("**" != tempString)) { - month = int.Parse(tempString); - } - tempString = dmtf.Substring(6, 2); - if (("**" != tempString)) { - day = int.Parse(tempString); - } - tempString = dmtf.Substring(8, 2); - if (("**" != tempString)) { - hour = int.Parse(tempString); - } - tempString = dmtf.Substring(10, 2); - if (("**" != tempString)) { - minute = int.Parse(tempString); - } - tempString = dmtf.Substring(12, 2); - if (("**" != tempString)) { - second = int.Parse(tempString); - } - tempString = dmtf.Substring(15, 6); - if (("******" != tempString)) { - ticks = (long.Parse(tempString) * ((long)((System.TimeSpan.TicksPerMillisecond / 1000)))); - } - if (((((((((year < 0) - || (month < 0)) - || (day < 0)) - || (hour < 0)) - || (minute < 0)) - || (minute < 0)) - || (second < 0)) - || (ticks < 0))) { - throw new System.ArgumentOutOfRangeException(); - } - } - catch (System.Exception e) { - throw new System.ArgumentOutOfRangeException(null, e.Message); - } - datetime = new System.DateTime(year, month, day, hour, minute, second, 0); - datetime = datetime.AddTicks(ticks); - System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(datetime); - int UTCOffset = 0; - int OffsetToBeAdjusted = 0; - long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); - tempString = dmtf.Substring(22, 3); - if ((tempString != "******")) { - tempString = dmtf.Substring(21, 4); - try { - UTCOffset = int.Parse(tempString); - } - catch (System.Exception e) { - throw new System.ArgumentOutOfRangeException(null, e.Message); - } - OffsetToBeAdjusted = ((int)((OffsetMins - UTCOffset))); - datetime = datetime.AddMinutes(((double)(OffsetToBeAdjusted))); - } - return datetime; - } - - // Converts a given System.DateTime object to DMTF datetime format. - static string ToDmtfDateTime(System.DateTime date) { - string utcString = string.Empty; - System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(date); - long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); - if ((System.Math.Abs(OffsetMins) > 999)) { - date = date.ToUniversalTime(); - utcString = "+000"; - } - else { - if ((tickOffset.Ticks >= 0)) { - utcString = string.Concat("+", ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))).ToString().PadLeft(3, '0')); - } - else { - string strTemp = ((long)(OffsetMins)).ToString(); - utcString = string.Concat("-", strTemp.Substring(1, (strTemp.Length - 1)).PadLeft(3, '0')); - } - } - string dmtfDateTime = ((int)(date.Year)).ToString().PadLeft(4, '0'); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Month)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Day)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Hour)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Minute)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Second)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, "."); - System.DateTime dtTemp = new System.DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, 0); - long microsec = ((long)((((date.Ticks - dtTemp.Ticks) - * 1000) - / System.TimeSpan.TicksPerMillisecond))); - string strMicrosec = ((long)(microsec)).ToString(); - if ((strMicrosec.Length > 6)) { - strMicrosec = strMicrosec.Substring(0, 6); - } - dmtfDateTime = string.Concat(dmtfDateTime, strMicrosec.PadLeft(6, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, utcString); - return dmtfDateTime; - } - - private bool ShouldSerializeInstallDate() { - if ((this.IsInstallDateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeLastErrorCode() { - if ((this.IsLastErrorCodeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeMaxQuiesceTime() { - if ((this.IsMaxQuiesceTimeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeOperatingStatus() { - if ((this.IsOperatingStatusNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializePowerManagementSupported() { - if ((this.IsPowerManagementSupportedNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializePowerOnHours() { - if ((this.IsPowerOnHoursNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializePrimaryStatus() { - if ((this.IsPrimaryStatusNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeRequestedState() { - if ((this.IsRequestedStateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeStatusInfo() { - if ((this.IsStatusInfoNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeTimeOfLastStateChange() { - if ((this.IsTimeOfLastStateChangeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeTotalPowerOnHours() { - if ((this.IsTotalPowerOnHoursNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeTransitioningToState() { - if ((this.IsTransitioningToStateNull == false)) { - return true; - } - return false; - } - - [Browsable(true)] - public void CommitObject() { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(); - } - } - - [Browsable(true)] - public void CommitObject(System.Management.PutOptions putOptions) { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(putOptions); - } - } - - private void Initialize() { - AutoCommitProp = true; - isEmbedded = false; - } - - private static string ConstructPath(string keyCreationClassName, string keyDeviceID, string keySystemCreationClassName, string keySystemName) { - string strPath = "ROOT\\virtualization\\v2:Msvm_KvpExchangeComponent"; - strPath = string.Concat(strPath, string.Concat(".CreationClassName=", string.Concat("\"", string.Concat(keyCreationClassName, "\"")))); - strPath = string.Concat(strPath, string.Concat(",DeviceID=", string.Concat("\"", string.Concat(keyDeviceID, "\"")))); - strPath = string.Concat(strPath, string.Concat(",SystemCreationClassName=", string.Concat("\"", string.Concat(keySystemCreationClassName, "\"")))); - strPath = string.Concat(strPath, string.Concat(",SystemName=", string.Concat("\"", string.Concat(keySystemName, "\"")))); - return strPath; - } - - private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - Initialize(); - if ((path != null)) { - if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - } - PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - - // Different overloads of GetInstances() help in enumerating instances of the WMI class. - public static KvpExchangeComponentCollection GetInstances() { - return GetInstances(null, null, null); - } - - public static KvpExchangeComponentCollection GetInstances(string condition) { - return GetInstances(null, condition, null); - } - - public static KvpExchangeComponentCollection GetInstances(string[] selectedProperties) { - return GetInstances(null, null, selectedProperties); - } - - public static KvpExchangeComponentCollection GetInstances(string condition, string[] selectedProperties) { - return GetInstances(null, condition, selectedProperties); - } - - public static KvpExchangeComponentCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); - pathObj.ClassName = "Msvm_KvpExchangeComponent"; - pathObj.NamespacePath = "root\\virtualization\\v2"; - System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); - if ((enumOptions == null)) { - enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - } - return new KvpExchangeComponentCollection(clsObject.GetInstances(enumOptions)); - } - - public static KvpExchangeComponentCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { - return GetInstances(mgmtScope, condition, null); - } - - public static KvpExchangeComponentCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { - return GetInstances(mgmtScope, null, selectedProperties); - } - - public static KvpExchangeComponentCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_KvpExchangeComponent", condition, selectedProperties)); - System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - ObjectSearcher.Options = enumOptions; - return new KvpExchangeComponentCollection(ObjectSearcher.Get()); - } - - [Browsable(true)] - public static KvpExchangeComponent CreateInstance() { - System.Management.ManagementScope mgmtScope = null; - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = CreatedWmiNamespace; - } - else { - mgmtScope = statMgmtScope; - } - System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); - System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); - return new KvpExchangeComponent(tmpMgmtClass.CreateInstance()); - } - - [Browsable(true)] - public void Delete() { - PrivateLateBoundObject.Delete(); - } - - public uint EnableDevice(bool Enabled) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("EnableDevice"); - inParams["Enabled"] = ((bool)(Enabled)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("EnableDevice", inParams, null); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - return System.Convert.ToUInt32(0); - } - } - - public uint OnlineDevice(bool Online) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("OnlineDevice"); - inParams["Online"] = ((bool)(Online)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("OnlineDevice", inParams, null); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - return System.Convert.ToUInt32(0); - } - } - - public uint QuiesceDevice(bool Quiesce) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("QuiesceDevice"); - inParams["Quiesce"] = ((bool)(Quiesce)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("QuiesceDevice", inParams, null); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - return System.Convert.ToUInt32(0); - } - } - - public uint RequestStateChange(ushort RequestedState, System.DateTime TimeoutPeriod, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("RequestStateChange"); - inParams["RequestedState"] = ((ushort)(RequestedState)); - inParams["TimeoutPeriod"] = ToDmtfDateTime(((System.DateTime)(TimeoutPeriod))); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RequestStateChange", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null)) - { - Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - return System.Convert.ToUInt32(0); - } - } - - public uint Reset() { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("Reset", inParams, null); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - return System.Convert.ToUInt32(0); - } - } - - public uint RestoreProperties() { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RestoreProperties", inParams, null); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - return System.Convert.ToUInt32(0); - } - } - - public uint SaveProperties() { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("SaveProperties", inParams, null); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - return System.Convert.ToUInt32(0); - } - } - - public uint SetPowerState(ushort PowerState, System.DateTime Time) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("SetPowerState"); - inParams["PowerState"] = ((ushort)(PowerState)); - inParams["Time"] = ToDmtfDateTime(((System.DateTime)(Time))); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("SetPowerState", inParams, null); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - return System.Convert.ToUInt32(0); - } - } - - // Enumerator implementation for enumerating instances of the class. - public class KvpExchangeComponentCollection : object, ICollection { - - private ManagementObjectCollection privColObj; - - public KvpExchangeComponentCollection(ManagementObjectCollection objCollection) { - privColObj = objCollection; - } - - public virtual int Count { - get { - return privColObj.Count; - } - } - - public virtual bool IsSynchronized { - get { - return privColObj.IsSynchronized; - } - } - - public virtual object SyncRoot { - get { - return this; - } - } - - public virtual void CopyTo(System.Array array, int index) { - privColObj.CopyTo(array, index); - int nCtr; - for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { - array.SetValue(new KvpExchangeComponent(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); - } - } - - public virtual System.Collections.IEnumerator GetEnumerator() { - return new KvpExchangeComponentEnumerator(privColObj.GetEnumerator()); - } - - public class KvpExchangeComponentEnumerator : object, System.Collections.IEnumerator { - - private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; - - public KvpExchangeComponentEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { - privObjEnum = objEnum; - } - - public virtual object Current { - get { - return new KvpExchangeComponent(((System.Management.ManagementObject)(privObjEnum.Current))); - } - } - - public virtual bool MoveNext() { - return privObjEnum.MoveNext(); - } - - public virtual void Reset() { - privObjEnum.Reset(); - } - } - } - - // TypeConverter to handle null values for ValueType properties - public class WMIValueTypeConverter : TypeConverter { - - private TypeConverter baseConverter; - - private System.Type baseType; - - public WMIValueTypeConverter(System.Type inBaseType) { - baseConverter = TypeDescriptor.GetConverter(inBaseType); - baseType = inBaseType; - } - - public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { - return baseConverter.CanConvertFrom(context, srcType); - } - - public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { - return baseConverter.CanConvertTo(context, destinationType); - } - - public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { - return baseConverter.ConvertFrom(context, culture, value); - } - - public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { - return baseConverter.CreateInstance(context, dictionary); - } - - public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetCreateInstanceSupported(context); - } - - public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { - return baseConverter.GetProperties(context, value, attributeVar); - } - - public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetPropertiesSupported(context); - } - - public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValues(context); - } - - public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesExclusive(context); - } - - public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesSupported(context); - } - - public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { - if ((baseType.BaseType == typeof(System.Enum))) { - if ((value.GetType() == destinationType)) { - return value; - } - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return "NULL_ENUM_VALUE" ; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((baseType == typeof(bool)) - && (baseType.BaseType == typeof(System.ValueType)))) { - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((context != null) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - } - - // Embedded class to represent WMI system Properties. - [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] - public class ManagementSystemProperties { - - private System.Management.ManagementBaseObject PrivateLateBoundObject; - - public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { - PrivateLateBoundObject = ManagedObject; - } - - [Browsable(true)] - public int GENUS { - get { - return ((int)(PrivateLateBoundObject["__GENUS"])); - } - } - - [Browsable(true)] - public string CLASS { - get { - return ((string)(PrivateLateBoundObject["__CLASS"])); - } - } - - [Browsable(true)] - public string SUPERCLASS { - get { - return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); - } - } - - [Browsable(true)] - public string DYNASTY { - get { - return ((string)(PrivateLateBoundObject["__DYNASTY"])); - } - } - - [Browsable(true)] - public string RELPATH { - get { - return ((string)(PrivateLateBoundObject["__RELPATH"])); - } - } - - [Browsable(true)] - public int PROPERTY_COUNT { - get { - return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); - } - } - - [Browsable(true)] - public string[] DERIVATION { - get { - return ((string[])(PrivateLateBoundObject["__DERIVATION"])); - } - } - - [Browsable(true)] - public string SERVER { - get { - return ((string)(PrivateLateBoundObject["__SERVER"])); - } - } - - [Browsable(true)] - public string NAMESPACE { - get { - return ((string)(PrivateLateBoundObject["__NAMESPACE"])); - } - } - - [Browsable(true)] - public string PATH { - get { - return ((string)(PrivateLateBoundObject["__PATH"])); - } - } - } - } -} +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2 +{ + using System; + using System.ComponentModel; + using System.Management; + using System.Collections; + using System.Globalization; + using System.ComponentModel.Design.Serialization; + using System.Reflection; + + + // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. + // Functions IsNull() are used to check if a property is NULL. + // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. + // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. + // Datetime conversion functions ToDateTime and ToDmtfDateTime are added to the class to convert DMTF datetime to System.DateTime and vice-versa. + // An Early Bound class generated for the WMI class.Msvm_KvpExchangeComponent + public class KvpExchangeComponent : System.ComponentModel.Component { + + // Private property to hold the WMI namespace in which the class resides. + private static string CreatedWmiNamespace = "ROOT\\virtualization\\v2"; + + // Private property to hold the name of WMI class which created this class. + private static string CreatedClassName = "Msvm_KvpExchangeComponent"; + + // Private member variable to hold the ManagementScope which is used by the various methods. + private static System.Management.ManagementScope statMgmtScope = null; + + private ManagementSystemProperties PrivateSystemProperties; + + // Underlying lateBound WMI object. + private System.Management.ManagementObject PrivateLateBoundObject; + + // Member variable to store the 'automatic commit' behavior for the class. + private bool AutoCommitProp; + + // Private variable to hold the embedded property representing the instance. + private System.Management.ManagementBaseObject embeddedObj; + + // The current WMI object used + private System.Management.ManagementBaseObject curObj; + + // Flag to indicate if the instance is an embedded object. + private bool isEmbedded; + + // Below are different overloads of constructors to initialize an instance of the class with a WMI object. + public KvpExchangeComponent() { + this.InitializeObject(null, null, null); + } + + public KvpExchangeComponent(string keyCreationClassName, string keyDeviceID, string keySystemCreationClassName, string keySystemName) { + this.InitializeObject(null, new System.Management.ManagementPath(KvpExchangeComponent.ConstructPath(keyCreationClassName, keyDeviceID, keySystemCreationClassName, keySystemName)), null); + } + + public KvpExchangeComponent(System.Management.ManagementScope mgmtScope, string keyCreationClassName, string keyDeviceID, string keySystemCreationClassName, string keySystemName) { + this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(KvpExchangeComponent.ConstructPath(keyCreationClassName, keyDeviceID, keySystemCreationClassName, keySystemName)), null); + } + + public KvpExchangeComponent(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(null, path, getOptions); + } + + public KvpExchangeComponent(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { + this.InitializeObject(mgmtScope, path, null); + } + + public KvpExchangeComponent(System.Management.ManagementPath path) { + this.InitializeObject(null, path, null); + } + + public KvpExchangeComponent(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(mgmtScope, path, getOptions); + } + + public KvpExchangeComponent(System.Management.ManagementObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + PrivateLateBoundObject = theObject; + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + public KvpExchangeComponent(System.Management.ManagementBaseObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + embeddedObj = theObject; + PrivateSystemProperties = new ManagementSystemProperties(theObject); + curObj = embeddedObj; + isEmbedded = true; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + // Property returns the namespace of the WMI class. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OriginatingNamespace { + get { + return "ROOT\\virtualization\\v2"; + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ManagementClassName { + get { + string strRet = CreatedClassName; + if ((curObj != null)) { + if ((curObj.ClassPath != null)) { + strRet = ((string)(curObj["__CLASS"])); + if (((strRet == null) + || (strRet == string.Empty))) { + strRet = CreatedClassName; + } + } + } + return strRet; + } + } + + // Property pointing to an embedded object to get System properties of the WMI object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ManagementSystemProperties SystemProperties { + get { + return PrivateSystemProperties; + } + } + + // Property returning the underlying lateBound object. + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementBaseObject LateBoundObject { + get { + return curObj; + } + } + + // ManagementScope of the object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementScope Scope { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Scope; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Scope = value; + } + } + } + + // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool AutoCommit { + get { + return AutoCommitProp; + } + set { + AutoCommitProp = value; + } + } + + // The ManagementPath of the underlying WMI object. + [Browsable(true)] + public System.Management.ManagementPath Path { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Path; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + if ((CheckIfProperClass(null, value, null) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + PrivateLateBoundObject.Path = value; + } + } + } + + // Public static scope property which is used by the various methods. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public static System.Management.ManagementScope StaticScope { + get { + return statMgmtScope; + } + set { + statMgmtScope = value; + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ushort[] AdditionalAvailability { + get { + return ((ushort[])(curObj["AdditionalAvailability"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAvailabilityNull { + get { + if ((curObj["Availability"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort Availability { + get { + if ((curObj["Availability"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["Availability"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ushort[] AvailableRequestedStates { + get { + return ((ushort[])(curObj["AvailableRequestedStates"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Caption { + get { + return ((string)(curObj["Caption"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsCommunicationStatusNull { + get { + if ((curObj["CommunicationStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort CommunicationStatus { + get { + if ((curObj["CommunicationStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["CommunicationStatus"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string CreationClassName { + get { + return ((string)(curObj["CreationClassName"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Description { + get { + return ((string)(curObj["Description"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsDetailedStatusNull { + get { + if ((curObj["DetailedStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort DetailedStatus { + get { + if ((curObj["DetailedStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["DetailedStatus"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string DeviceID { + get { + return ((string)(curObj["DeviceID"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ElementName { + get { + return ((string)(curObj["ElementName"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsEnabledDefaultNull { + get { + if ((curObj["EnabledDefault"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort EnabledDefault { + get { + if ((curObj["EnabledDefault"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["EnabledDefault"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsEnabledStateNull { + get { + if ((curObj["EnabledState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort EnabledState { + get { + if ((curObj["EnabledState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["EnabledState"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsErrorClearedNull { + get { + if ((curObj["ErrorCleared"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool ErrorCleared { + get { + if ((curObj["ErrorCleared"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["ErrorCleared"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ErrorDescription { + get { + return ((string)(curObj["ErrorDescription"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"An array of embedded Msvm_KvpExchangeDataItem instances which contain the set of key-value pairs that components running within the guest operating system have pushed up to be available for access by external clients. This array will not contain any intrinsic items that are pushed by the integration component directly.")] + public string[] GuestExchangeItems { + get { + return ((string[])(curObj["GuestExchangeItems"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"An array of embedded Msvm_KvpExchangeDataItem instances which contain the set of key-value pairs that the guest operating system has pushed up to be available for access by external clients. This array will not contain any data items pushed by other components running within the guest operating system.")] + public string[] GuestIntrinsicExchangeItems { + get { + return ((string[])(curObj["GuestIntrinsicExchangeItems"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsHealthStateNull { + get { + if ((curObj["HealthState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort HealthState { + get { + if ((curObj["HealthState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["HealthState"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] IdentifyingDescriptions { + get { + return ((string[])(curObj["IdentifyingDescriptions"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsInstallDateNull { + get { + if ((curObj["InstallDate"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime InstallDate { + get { + if ((curObj["InstallDate"] != null)) { + return ToDateTime(((string)(curObj["InstallDate"]))); + } + else { + return System.DateTime.MinValue; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string InstanceID { + get { + return ((string)(curObj["InstanceID"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsLastErrorCodeNull { + get { + if ((curObj["LastErrorCode"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint LastErrorCode { + get { + if ((curObj["LastErrorCode"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["LastErrorCode"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsMaxQuiesceTimeNull { + get { + if ((curObj["MaxQuiesceTime"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong MaxQuiesceTime { + get { + if ((curObj["MaxQuiesceTime"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["MaxQuiesceTime"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Name { + get { + return ((string)(curObj["Name"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsOperatingStatusNull { + get { + if ((curObj["OperatingStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort OperatingStatus { + get { + if ((curObj["OperatingStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["OperatingStatus"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ushort[] OperationalStatus { + get { + return ((ushort[])(curObj["OperationalStatus"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherEnabledState { + get { + return ((string)(curObj["OtherEnabledState"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] OtherIdentifyingInfo { + get { + return ((string[])(curObj["OtherIdentifyingInfo"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ushort[] PowerManagementCapabilities { + get { + return ((ushort[])(curObj["PowerManagementCapabilities"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPowerManagementSupportedNull { + get { + if ((curObj["PowerManagementSupported"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool PowerManagementSupported { + get { + if ((curObj["PowerManagementSupported"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["PowerManagementSupported"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPowerOnHoursNull { + get { + if ((curObj["PowerOnHours"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong PowerOnHours { + get { + if ((curObj["PowerOnHours"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["PowerOnHours"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPrimaryStatusNull { + get { + if ((curObj["PrimaryStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort PrimaryStatus { + get { + if ((curObj["PrimaryStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["PrimaryStatus"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsRequestedStateNull { + get { + if ((curObj["RequestedState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort RequestedState { + get { + if ((curObj["RequestedState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["RequestedState"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Status { + get { + return ((string)(curObj["Status"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] StatusDescriptions { + get { + return ((string[])(curObj["StatusDescriptions"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsStatusInfoNull { + get { + if ((curObj["StatusInfo"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort StatusInfo { + get { + if ((curObj["StatusInfo"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["StatusInfo"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string SystemCreationClassName { + get { + return ((string)(curObj["SystemCreationClassName"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string SystemName { + get { + return ((string)(curObj["SystemName"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsTimeOfLastStateChangeNull { + get { + if ((curObj["TimeOfLastStateChange"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime TimeOfLastStateChange { + get { + if ((curObj["TimeOfLastStateChange"] != null)) { + return ToDateTime(((string)(curObj["TimeOfLastStateChange"]))); + } + else { + return System.DateTime.MinValue; + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsTotalPowerOnHoursNull { + get { + if ((curObj["TotalPowerOnHours"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong TotalPowerOnHours { + get { + if ((curObj["TotalPowerOnHours"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["TotalPowerOnHours"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsTransitioningToStateNull { + get { + if ((curObj["TransitioningToState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort TransitioningToState { + get { + if ((curObj["TransitioningToState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["TransitioningToState"])); + } + } + + private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { + if (((path != null) + && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); + } + } + + private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { + if (((theObj != null) + && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); + if ((parentClasses != null)) { + int count = 0; + for (count = 0; (count < parentClasses.Length); count = (count + 1)) { + if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { + return true; + } + } + } + } + return false; + } + + private bool ShouldSerializeAvailability() { + if ((this.IsAvailabilityNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeCommunicationStatus() { + if ((this.IsCommunicationStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeDetailedStatus() { + if ((this.IsDetailedStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeEnabledDefault() { + if ((this.IsEnabledDefaultNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeEnabledState() { + if ((this.IsEnabledStateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeErrorCleared() { + if ((this.IsErrorClearedNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeHealthState() { + if ((this.IsHealthStateNull == false)) { + return true; + } + return false; + } + + // Converts a given datetime in DMTF format to System.DateTime object. + static System.DateTime ToDateTime(string dmtfDate) { + System.DateTime initializer = System.DateTime.MinValue; + int year = initializer.Year; + int month = initializer.Month; + int day = initializer.Day; + int hour = initializer.Hour; + int minute = initializer.Minute; + int second = initializer.Second; + long ticks = 0; + string dmtf = dmtfDate; + System.DateTime datetime = System.DateTime.MinValue; + string tempString = string.Empty; + if ((dmtf == null)) { + throw new System.ArgumentOutOfRangeException(); + } + if ((dmtf.Length == 0)) { + throw new System.ArgumentOutOfRangeException(); + } + if ((dmtf.Length != 25)) { + throw new System.ArgumentOutOfRangeException(); + } + try { + tempString = dmtf.Substring(0, 4); + if (("****" != tempString)) { + year = int.Parse(tempString); + } + tempString = dmtf.Substring(4, 2); + if (("**" != tempString)) { + month = int.Parse(tempString); + } + tempString = dmtf.Substring(6, 2); + if (("**" != tempString)) { + day = int.Parse(tempString); + } + tempString = dmtf.Substring(8, 2); + if (("**" != tempString)) { + hour = int.Parse(tempString); + } + tempString = dmtf.Substring(10, 2); + if (("**" != tempString)) { + minute = int.Parse(tempString); + } + tempString = dmtf.Substring(12, 2); + if (("**" != tempString)) { + second = int.Parse(tempString); + } + tempString = dmtf.Substring(15, 6); + if (("******" != tempString)) { + ticks = (long.Parse(tempString) * ((long)((System.TimeSpan.TicksPerMillisecond / 1000)))); + } + if (((((((((year < 0) + || (month < 0)) + || (day < 0)) + || (hour < 0)) + || (minute < 0)) + || (minute < 0)) + || (second < 0)) + || (ticks < 0))) { + throw new System.ArgumentOutOfRangeException(); + } + } + catch (System.Exception e) { + throw new System.ArgumentOutOfRangeException(null, e.Message); + } + datetime = new System.DateTime(year, month, day, hour, minute, second, 0); + datetime = datetime.AddTicks(ticks); + System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(datetime); + int UTCOffset = 0; + int OffsetToBeAdjusted = 0; + long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); + tempString = dmtf.Substring(22, 3); + if ((tempString != "******")) { + tempString = dmtf.Substring(21, 4); + try { + UTCOffset = int.Parse(tempString); + } + catch (System.Exception e) { + throw new System.ArgumentOutOfRangeException(null, e.Message); + } + OffsetToBeAdjusted = ((int)((OffsetMins - UTCOffset))); + datetime = datetime.AddMinutes(((double)(OffsetToBeAdjusted))); + } + return datetime; + } + + // Converts a given System.DateTime object to DMTF datetime format. + static string ToDmtfDateTime(System.DateTime date) { + string utcString = string.Empty; + System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(date); + long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); + if ((System.Math.Abs(OffsetMins) > 999)) { + date = date.ToUniversalTime(); + utcString = "+000"; + } + else { + if ((tickOffset.Ticks >= 0)) { + utcString = string.Concat("+", ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))).ToString().PadLeft(3, '0')); + } + else { + string strTemp = ((long)(OffsetMins)).ToString(); + utcString = string.Concat("-", strTemp.Substring(1, (strTemp.Length - 1)).PadLeft(3, '0')); + } + } + string dmtfDateTime = ((int)(date.Year)).ToString().PadLeft(4, '0'); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Month)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Day)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Hour)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Minute)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Second)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, "."); + System.DateTime dtTemp = new System.DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, 0); + long microsec = ((long)((((date.Ticks - dtTemp.Ticks) + * 1000) + / System.TimeSpan.TicksPerMillisecond))); + string strMicrosec = ((long)(microsec)).ToString(); + if ((strMicrosec.Length > 6)) { + strMicrosec = strMicrosec.Substring(0, 6); + } + dmtfDateTime = string.Concat(dmtfDateTime, strMicrosec.PadLeft(6, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, utcString); + return dmtfDateTime; + } + + private bool ShouldSerializeInstallDate() { + if ((this.IsInstallDateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeLastErrorCode() { + if ((this.IsLastErrorCodeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeMaxQuiesceTime() { + if ((this.IsMaxQuiesceTimeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeOperatingStatus() { + if ((this.IsOperatingStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePowerManagementSupported() { + if ((this.IsPowerManagementSupportedNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePowerOnHours() { + if ((this.IsPowerOnHoursNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePrimaryStatus() { + if ((this.IsPrimaryStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeRequestedState() { + if ((this.IsRequestedStateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeStatusInfo() { + if ((this.IsStatusInfoNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeTimeOfLastStateChange() { + if ((this.IsTimeOfLastStateChangeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeTotalPowerOnHours() { + if ((this.IsTotalPowerOnHoursNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeTransitioningToState() { + if ((this.IsTransitioningToStateNull == false)) { + return true; + } + return false; + } + + [Browsable(true)] + public void CommitObject() { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(); + } + } + + [Browsable(true)] + public void CommitObject(System.Management.PutOptions putOptions) { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(putOptions); + } + } + + private void Initialize() { + AutoCommitProp = true; + isEmbedded = false; + } + + private static string ConstructPath(string keyCreationClassName, string keyDeviceID, string keySystemCreationClassName, string keySystemName) { + string strPath = "ROOT\\virtualization\\v2:Msvm_KvpExchangeComponent"; + strPath = string.Concat(strPath, string.Concat(".CreationClassName=", string.Concat("\"", string.Concat(keyCreationClassName, "\"")))); + strPath = string.Concat(strPath, string.Concat(",DeviceID=", string.Concat("\"", string.Concat(keyDeviceID, "\"")))); + strPath = string.Concat(strPath, string.Concat(",SystemCreationClassName=", string.Concat("\"", string.Concat(keySystemCreationClassName, "\"")))); + strPath = string.Concat(strPath, string.Concat(",SystemName=", string.Concat("\"", string.Concat(keySystemName, "\"")))); + return strPath; + } + + private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + Initialize(); + if ((path != null)) { + if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + } + PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + + // Different overloads of GetInstances() help in enumerating instances of the WMI class. + public static KvpExchangeComponentCollection GetInstances() { + return GetInstances(null, null, null); + } + + public static KvpExchangeComponentCollection GetInstances(string condition) { + return GetInstances(null, condition, null); + } + + public static KvpExchangeComponentCollection GetInstances(string[] selectedProperties) { + return GetInstances(null, null, selectedProperties); + } + + public static KvpExchangeComponentCollection GetInstances(string condition, string[] selectedProperties) { + return GetInstances(null, condition, selectedProperties); + } + + public static KvpExchangeComponentCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); + pathObj.ClassName = "Msvm_KvpExchangeComponent"; + pathObj.NamespacePath = "root\\virtualization\\v2"; + System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); + if ((enumOptions == null)) { + enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + } + return new KvpExchangeComponentCollection(clsObject.GetInstances(enumOptions)); + } + + public static KvpExchangeComponentCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { + return GetInstances(mgmtScope, condition, null); + } + + public static KvpExchangeComponentCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { + return GetInstances(mgmtScope, null, selectedProperties); + } + + public static KvpExchangeComponentCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_KvpExchangeComponent", condition, selectedProperties)); + System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + ObjectSearcher.Options = enumOptions; + return new KvpExchangeComponentCollection(ObjectSearcher.Get()); + } + + [Browsable(true)] + public static KvpExchangeComponent CreateInstance() { + System.Management.ManagementScope mgmtScope = null; + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = CreatedWmiNamespace; + } + else { + mgmtScope = statMgmtScope; + } + System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); + System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); + return new KvpExchangeComponent(tmpMgmtClass.CreateInstance()); + } + + [Browsable(true)] + public void Delete() { + PrivateLateBoundObject.Delete(); + } + + public uint EnableDevice(bool Enabled) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("EnableDevice"); + inParams["Enabled"] = ((bool)(Enabled)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("EnableDevice", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + public uint OnlineDevice(bool Online) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("OnlineDevice"); + inParams["Online"] = ((bool)(Online)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("OnlineDevice", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + public uint QuiesceDevice(bool Quiesce) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("QuiesceDevice"); + inParams["Quiesce"] = ((bool)(Quiesce)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("QuiesceDevice", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + public uint RequestStateChange(ushort RequestedState, System.DateTime TimeoutPeriod, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("RequestStateChange"); + inParams["RequestedState"] = ((ushort)(RequestedState)); + inParams["TimeoutPeriod"] = ToDmtfDateTime(((System.DateTime)(TimeoutPeriod))); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RequestStateChange", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null)) + { + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + return System.Convert.ToUInt32(0); + } + } + + public uint Reset() { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("Reset", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + public uint RestoreProperties() { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RestoreProperties", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + public uint SaveProperties() { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("SaveProperties", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + public uint SetPowerState(ushort PowerState, System.DateTime Time) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("SetPowerState"); + inParams["PowerState"] = ((ushort)(PowerState)); + inParams["Time"] = ToDmtfDateTime(((System.DateTime)(Time))); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("SetPowerState", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + // Enumerator implementation for enumerating instances of the class. + public class KvpExchangeComponentCollection : object, ICollection { + + private ManagementObjectCollection privColObj; + + public KvpExchangeComponentCollection(ManagementObjectCollection objCollection) { + privColObj = objCollection; + } + + public virtual int Count { + get { + return privColObj.Count; + } + } + + public virtual bool IsSynchronized { + get { + return privColObj.IsSynchronized; + } + } + + public virtual object SyncRoot { + get { + return this; + } + } + + public virtual void CopyTo(System.Array array, int index) { + privColObj.CopyTo(array, index); + int nCtr; + for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { + array.SetValue(new KvpExchangeComponent(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); + } + } + + public virtual System.Collections.IEnumerator GetEnumerator() { + return new KvpExchangeComponentEnumerator(privColObj.GetEnumerator()); + } + + public class KvpExchangeComponentEnumerator : object, System.Collections.IEnumerator { + + private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; + + public KvpExchangeComponentEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { + privObjEnum = objEnum; + } + + public virtual object Current { + get { + return new KvpExchangeComponent(((System.Management.ManagementObject)(privObjEnum.Current))); + } + } + + public virtual bool MoveNext() { + return privObjEnum.MoveNext(); + } + + public virtual void Reset() { + privObjEnum.Reset(); + } + } + } + + // TypeConverter to handle null values for ValueType properties + public class WMIValueTypeConverter : TypeConverter { + + private TypeConverter baseConverter; + + private System.Type baseType; + + public WMIValueTypeConverter(System.Type inBaseType) { + baseConverter = TypeDescriptor.GetConverter(inBaseType); + baseType = inBaseType; + } + + public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { + return baseConverter.CanConvertFrom(context, srcType); + } + + public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { + return baseConverter.CanConvertTo(context, destinationType); + } + + public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { + return baseConverter.ConvertFrom(context, culture, value); + } + + public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { + return baseConverter.CreateInstance(context, dictionary); + } + + public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetCreateInstanceSupported(context); + } + + public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { + return baseConverter.GetProperties(context, value, attributeVar); + } + + public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetPropertiesSupported(context); + } + + public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValues(context); + } + + public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesExclusive(context); + } + + public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesSupported(context); + } + + public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { + if ((baseType.BaseType == typeof(System.Enum))) { + if ((value.GetType() == destinationType)) { + return value; + } + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return "NULL_ENUM_VALUE" ; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((baseType == typeof(bool)) + && (baseType.BaseType == typeof(System.ValueType)))) { + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((context != null) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + } + + // Embedded class to represent WMI system Properties. + [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] + public class ManagementSystemProperties { + + private System.Management.ManagementBaseObject PrivateLateBoundObject; + + public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { + PrivateLateBoundObject = ManagedObject; + } + + [Browsable(true)] + public int GENUS { + get { + return ((int)(PrivateLateBoundObject["__GENUS"])); + } + } + + [Browsable(true)] + public string CLASS { + get { + return ((string)(PrivateLateBoundObject["__CLASS"])); + } + } + + [Browsable(true)] + public string SUPERCLASS { + get { + return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); + } + } + + [Browsable(true)] + public string DYNASTY { + get { + return ((string)(PrivateLateBoundObject["__DYNASTY"])); + } + } + + [Browsable(true)] + public string RELPATH { + get { + return ((string)(PrivateLateBoundObject["__RELPATH"])); + } + } + + [Browsable(true)] + public int PROPERTY_COUNT { + get { + return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); + } + } + + [Browsable(true)] + public string[] DERIVATION { + get { + return ((string[])(PrivateLateBoundObject["__DERIVATION"])); + } + } + + [Browsable(true)] + public string SERVER { + get { + return ((string)(PrivateLateBoundObject["__SERVER"])); + } + } + + [Browsable(true)] + public string NAMESPACE { + get { + return ((string)(PrivateLateBoundObject["__NAMESPACE"])); + } + } + + [Browsable(true)] + public string PATH { + get { + return ((string)(PrivateLateBoundObject["__PATH"])); + } + } + } + } +} diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_KvpExchangeComponentSettingData.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_KvpExchangeComponentSettingData.cs index 0832e3c9228..de15266595e 100644 --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_KvpExchangeComponentSettingData.cs +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_KvpExchangeComponentSettingData.cs @@ -15,1040 +15,1040 @@ // specific language governing permissions and limitations // under the License. -namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2 -{ - using System; - using System.ComponentModel; - using System.Management; - using System.Collections; - using System.Globalization; - using System.ComponentModel.Design.Serialization; - using System.Reflection; - - - // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. - // Functions IsNull() are used to check if a property is NULL. - // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. - // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. - // An Early Bound class generated for the WMI class.Msvm_KvpExchangeComponentSettingData - public class KvpExchangeComponentSettingData : System.ComponentModel.Component { - - // Private property to hold the WMI namespace in which the class resides. - private static string CreatedWmiNamespace = "ROOT\\virtualization\\v2"; - - // Private property to hold the name of WMI class which created this class. - public static string CreatedClassName = "Msvm_KvpExchangeComponentSettingData"; - - // Private member variable to hold the ManagementScope which is used by the various methods. - private static System.Management.ManagementScope statMgmtScope = null; - - private ManagementSystemProperties PrivateSystemProperties; - - // Underlying lateBound WMI object. - private System.Management.ManagementObject PrivateLateBoundObject; - - // Member variable to store the 'automatic commit' behavior for the class. - private bool AutoCommitProp; - - // Private variable to hold the embedded property representing the instance. - private System.Management.ManagementBaseObject embeddedObj; - - // The current WMI object used - private System.Management.ManagementBaseObject curObj; - - // Flag to indicate if the instance is an embedded object. - private bool isEmbedded; - - // Below are different overloads of constructors to initialize an instance of the class with a WMI object. - public KvpExchangeComponentSettingData() { - this.InitializeObject(null, null, null); - } - - public KvpExchangeComponentSettingData(string keyInstanceID) { - this.InitializeObject(null, new System.Management.ManagementPath(KvpExchangeComponentSettingData.ConstructPath(keyInstanceID)), null); - } - - public KvpExchangeComponentSettingData(System.Management.ManagementScope mgmtScope, string keyInstanceID) { - this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(KvpExchangeComponentSettingData.ConstructPath(keyInstanceID)), null); - } - - public KvpExchangeComponentSettingData(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(null, path, getOptions); - } - - public KvpExchangeComponentSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { - this.InitializeObject(mgmtScope, path, null); - } - - public KvpExchangeComponentSettingData(System.Management.ManagementPath path) { - this.InitializeObject(null, path, null); - } - - public KvpExchangeComponentSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(mgmtScope, path, getOptions); - } - - public KvpExchangeComponentSettingData(System.Management.ManagementObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - PrivateLateBoundObject = theObject; - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - public KvpExchangeComponentSettingData(System.Management.ManagementBaseObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - embeddedObj = theObject; - PrivateSystemProperties = new ManagementSystemProperties(theObject); - curObj = embeddedObj; - isEmbedded = true; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - // Property returns the namespace of the WMI class. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OriginatingNamespace { - get { - return "ROOT\\virtualization\\v2"; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ManagementClassName { - get { - string strRet = CreatedClassName; - if ((curObj != null)) { - if ((curObj.ClassPath != null)) { - strRet = ((string)(curObj["__CLASS"])); - if (((strRet == null) - || (strRet == string.Empty))) { - strRet = CreatedClassName; - } - } - } - return strRet; - } - } - - // Property pointing to an embedded object to get System properties of the WMI object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ManagementSystemProperties SystemProperties { - get { - return PrivateSystemProperties; - } - } - - // Property returning the underlying lateBound object. - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementBaseObject LateBoundObject { - get { - return curObj; - } - } - - // ManagementScope of the object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementScope Scope { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Scope; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Scope = value; - } - } - } - - // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool AutoCommit { - get { - return AutoCommitProp; - } - set { - AutoCommitProp = value; - } - } - - // The ManagementPath of the underlying WMI object. - [Browsable(true)] - public System.Management.ManagementPath Path { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Path; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - if ((CheckIfProperClass(null, value, null) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - PrivateLateBoundObject.Path = value; - } - } - } - - // Public static scope property which is used by the various methods. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public static System.Management.ManagementScope StaticScope { - get { - return statMgmtScope; - } - set { - statMgmtScope = value; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Address { - get { - return ((string)(curObj["Address"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string AddressOnParent { - get { - return ((string)(curObj["AddressOnParent"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string AllocationUnits { - get { - return ((string)(curObj["AllocationUnits"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsAutomaticAllocationNull { - get { - if ((curObj["AutomaticAllocation"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool AutomaticAllocation { - get { - if ((curObj["AutomaticAllocation"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["AutomaticAllocation"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsAutomaticDeallocationNull { - get { - if ((curObj["AutomaticDeallocation"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool AutomaticDeallocation { - get { - if ((curObj["AutomaticDeallocation"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["AutomaticDeallocation"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Caption { - get { - return ((string)(curObj["Caption"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] Connection { - get { - return ((string[])(curObj["Connection"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsConsumerVisibilityNull { - get { - if ((curObj["ConsumerVisibility"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort ConsumerVisibility { - get { - if ((curObj["ConsumerVisibility"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["ConsumerVisibility"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Description { - get { - return ((string)(curObj["Description"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ElementName { - get { - return ((string)(curObj["ElementName"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsEnabledStateNull { - get { - if ((curObj["EnabledState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] +namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2 +{ + using System; + using System.ComponentModel; + using System.Management; + using System.Collections; + using System.Globalization; + using System.ComponentModel.Design.Serialization; + using System.Reflection; + + + // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. + // Functions IsNull() are used to check if a property is NULL. + // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. + // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. + // An Early Bound class generated for the WMI class.Msvm_KvpExchangeComponentSettingData + public class KvpExchangeComponentSettingData : System.ComponentModel.Component { + + // Private property to hold the WMI namespace in which the class resides. + private static string CreatedWmiNamespace = "ROOT\\virtualization\\v2"; + + // Private property to hold the name of WMI class which created this class. + public static string CreatedClassName = "Msvm_KvpExchangeComponentSettingData"; + + // Private member variable to hold the ManagementScope which is used by the various methods. + private static System.Management.ManagementScope statMgmtScope = null; + + private ManagementSystemProperties PrivateSystemProperties; + + // Underlying lateBound WMI object. + private System.Management.ManagementObject PrivateLateBoundObject; + + // Member variable to store the 'automatic commit' behavior for the class. + private bool AutoCommitProp; + + // Private variable to hold the embedded property representing the instance. + private System.Management.ManagementBaseObject embeddedObj; + + // The current WMI object used + private System.Management.ManagementBaseObject curObj; + + // Flag to indicate if the instance is an embedded object. + private bool isEmbedded; + + // Below are different overloads of constructors to initialize an instance of the class with a WMI object. + public KvpExchangeComponentSettingData() { + this.InitializeObject(null, null, null); + } + + public KvpExchangeComponentSettingData(string keyInstanceID) { + this.InitializeObject(null, new System.Management.ManagementPath(KvpExchangeComponentSettingData.ConstructPath(keyInstanceID)), null); + } + + public KvpExchangeComponentSettingData(System.Management.ManagementScope mgmtScope, string keyInstanceID) { + this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(KvpExchangeComponentSettingData.ConstructPath(keyInstanceID)), null); + } + + public KvpExchangeComponentSettingData(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(null, path, getOptions); + } + + public KvpExchangeComponentSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { + this.InitializeObject(mgmtScope, path, null); + } + + public KvpExchangeComponentSettingData(System.Management.ManagementPath path) { + this.InitializeObject(null, path, null); + } + + public KvpExchangeComponentSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(mgmtScope, path, getOptions); + } + + public KvpExchangeComponentSettingData(System.Management.ManagementObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + PrivateLateBoundObject = theObject; + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + public KvpExchangeComponentSettingData(System.Management.ManagementBaseObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + embeddedObj = theObject; + PrivateSystemProperties = new ManagementSystemProperties(theObject); + curObj = embeddedObj; + isEmbedded = true; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + // Property returns the namespace of the WMI class. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OriginatingNamespace { + get { + return "ROOT\\virtualization\\v2"; + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ManagementClassName { + get { + string strRet = CreatedClassName; + if ((curObj != null)) { + if ((curObj.ClassPath != null)) { + strRet = ((string)(curObj["__CLASS"])); + if (((strRet == null) + || (strRet == string.Empty))) { + strRet = CreatedClassName; + } + } + } + return strRet; + } + } + + // Property pointing to an embedded object to get System properties of the WMI object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ManagementSystemProperties SystemProperties { + get { + return PrivateSystemProperties; + } + } + + // Property returning the underlying lateBound object. + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementBaseObject LateBoundObject { + get { + return curObj; + } + } + + // ManagementScope of the object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementScope Scope { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Scope; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Scope = value; + } + } + } + + // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool AutoCommit { + get { + return AutoCommitProp; + } + set { + AutoCommitProp = value; + } + } + + // The ManagementPath of the underlying WMI object. + [Browsable(true)] + public System.Management.ManagementPath Path { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Path; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + if ((CheckIfProperClass(null, value, null) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + PrivateLateBoundObject.Path = value; + } + } + } + + // Public static scope property which is used by the various methods. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public static System.Management.ManagementScope StaticScope { + get { + return statMgmtScope; + } + set { + statMgmtScope = value; + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Address { + get { + return ((string)(curObj["Address"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string AddressOnParent { + get { + return ((string)(curObj["AddressOnParent"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string AllocationUnits { + get { + return ((string)(curObj["AllocationUnits"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAutomaticAllocationNull { + get { + if ((curObj["AutomaticAllocation"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool AutomaticAllocation { + get { + if ((curObj["AutomaticAllocation"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["AutomaticAllocation"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAutomaticDeallocationNull { + get { + if ((curObj["AutomaticDeallocation"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool AutomaticDeallocation { + get { + if ((curObj["AutomaticDeallocation"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["AutomaticDeallocation"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Caption { + get { + return ((string)(curObj["Caption"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] Connection { + get { + return ((string[])(curObj["Connection"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsConsumerVisibilityNull { + get { + if ((curObj["ConsumerVisibility"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort ConsumerVisibility { + get { + if ((curObj["ConsumerVisibility"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["ConsumerVisibility"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Description { + get { + return ((string)(curObj["Description"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ElementName { + get { + return ((string)(curObj["ElementName"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsEnabledStateNull { + get { + if ((curObj["EnabledState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [Description(@"The enabled and disabled states of an element. Valid values are 2 (enabled) and 3 (disabled). The default value is 2 (enabled). -This is a read-only property, but it can be changed using the ModifyVirtualSystemResources method of the Msvm_VirtualSystemManagementService class.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort EnabledState { - get { - if ((curObj["EnabledState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["EnabledState"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("An array of Msvm_KvpExchangeDataItem instances.\nThis is a read-only property, but" + - " it can be changed using the AddKvpItems, ModifyKvpItems, and RemoveKvpItems met" + - "hods of the Msvm_VirtualSystemManagementService class.")] - public string[] HostExchangeItems { - get { - return ((string[])(curObj["HostExchangeItems"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description(@"An array of Msvm_KvpExchangeDataItem instances containing the key/value pairs that are stored in the configuration file but not exchanged with the guest OS. This allows applications to store VM-specific data that does not need to be visible to the guest OS. The items are formatted the same as the items in the HostExchangeItems property except the Source property of the Msvm_KvpExchangeDataItem instance is set to 4. Each configuration file is limited to 128 key/value pairs, where each value field is allowed to be up to 16 KB in size and the key field is allowed to be up to512 bytes.")] - public string[] HostOnlyItems { - get { - return ((string[])(curObj["HostOnlyItems"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] HostResource { - get { - return ((string[])(curObj["HostResource"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string InstanceID { - get { - return ((string)(curObj["InstanceID"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsLimitNull { - get { - if ((curObj["Limit"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong Limit { - get { - if ((curObj["Limit"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["Limit"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsMappingBehaviorNull { - get { - if ((curObj["MappingBehavior"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort MappingBehavior { - get { - if ((curObj["MappingBehavior"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["MappingBehavior"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OtherResourceType { - get { - return ((string)(curObj["OtherResourceType"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Parent { - get { - return ((string)(curObj["Parent"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string PoolID { - get { - return ((string)(curObj["PoolID"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsReservationNull { - get { - if ((curObj["Reservation"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong Reservation { - get { - if ((curObj["Reservation"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["Reservation"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ResourceSubType { - get { - return ((string)(curObj["ResourceSubType"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsResourceTypeNull { - get { - if ((curObj["ResourceType"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort ResourceType { - get { - if ((curObj["ResourceType"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["ResourceType"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsVirtualQuantityNull { - get { - if ((curObj["VirtualQuantity"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong VirtualQuantity { - get { - if ((curObj["VirtualQuantity"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["VirtualQuantity"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string VirtualQuantityUnits { - get { - return ((string)(curObj["VirtualQuantityUnits"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsWeightNull { - get { - if ((curObj["Weight"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public uint Weight { - get { - if ((curObj["Weight"] == null)) { - return System.Convert.ToUInt32(0); - } - return ((uint)(curObj["Weight"])); - } - } - - private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { - if (((path != null) - && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); - } - } - - private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { - if (((theObj != null) - && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); - if ((parentClasses != null)) { - int count = 0; - for (count = 0; (count < parentClasses.Length); count = (count + 1)) { - if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { - return true; - } - } - } - } - return false; - } - - private bool ShouldSerializeAutomaticAllocation() { - if ((this.IsAutomaticAllocationNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeAutomaticDeallocation() { - if ((this.IsAutomaticDeallocationNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeConsumerVisibility() { - if ((this.IsConsumerVisibilityNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeEnabledState() { - if ((this.IsEnabledStateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeLimit() { - if ((this.IsLimitNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeMappingBehavior() { - if ((this.IsMappingBehaviorNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeReservation() { - if ((this.IsReservationNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeResourceType() { - if ((this.IsResourceTypeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeVirtualQuantity() { - if ((this.IsVirtualQuantityNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeWeight() { - if ((this.IsWeightNull == false)) { - return true; - } - return false; - } - - [Browsable(true)] - public void CommitObject() { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(); - } - } - - [Browsable(true)] - public void CommitObject(System.Management.PutOptions putOptions) { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(putOptions); - } - } - - private void Initialize() { - AutoCommitProp = true; - isEmbedded = false; - } - - private static string ConstructPath(string keyInstanceID) { - string strPath = "ROOT\\virtualization\\v2:Msvm_KvpExchangeComponentSettingData"; - strPath = string.Concat(strPath, string.Concat(".InstanceID=", string.Concat("\"", string.Concat(keyInstanceID, "\"")))); - return strPath; - } - - private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - Initialize(); - if ((path != null)) { - if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - } - PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - - // Different overloads of GetInstances() help in enumerating instances of the WMI class. - public static KvpExchangeComponentSettingDataCollection GetInstances() { - return GetInstances(null, null, null); - } - - public static KvpExchangeComponentSettingDataCollection GetInstances(string condition) { - return GetInstances(null, condition, null); - } - - public static KvpExchangeComponentSettingDataCollection GetInstances(string[] selectedProperties) { - return GetInstances(null, null, selectedProperties); - } - - public static KvpExchangeComponentSettingDataCollection GetInstances(string condition, string[] selectedProperties) { - return GetInstances(null, condition, selectedProperties); - } - - public static KvpExchangeComponentSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); - pathObj.ClassName = "Msvm_KvpExchangeComponentSettingData"; - pathObj.NamespacePath = "root\\virtualization\\v2"; - System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); - if ((enumOptions == null)) { - enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - } - return new KvpExchangeComponentSettingDataCollection(clsObject.GetInstances(enumOptions)); - } - - public static KvpExchangeComponentSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { - return GetInstances(mgmtScope, condition, null); - } - - public static KvpExchangeComponentSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { - return GetInstances(mgmtScope, null, selectedProperties); - } - - public static KvpExchangeComponentSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_KvpExchangeComponentSettingData", condition, selectedProperties)); - System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - ObjectSearcher.Options = enumOptions; - return new KvpExchangeComponentSettingDataCollection(ObjectSearcher.Get()); - } - - [Browsable(true)] - public static KvpExchangeComponentSettingData CreateInstance() { - System.Management.ManagementScope mgmtScope = null; - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = CreatedWmiNamespace; - } - else { - mgmtScope = statMgmtScope; - } - System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); - System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); - return new KvpExchangeComponentSettingData(tmpMgmtClass.CreateInstance()); - } - - [Browsable(true)] - public void Delete() { - PrivateLateBoundObject.Delete(); - } - - // Enumerator implementation for enumerating instances of the class. - public class KvpExchangeComponentSettingDataCollection : object, ICollection { - - private ManagementObjectCollection privColObj; - - public KvpExchangeComponentSettingDataCollection(ManagementObjectCollection objCollection) { - privColObj = objCollection; - } - - public virtual int Count { - get { - return privColObj.Count; - } - } - - public virtual bool IsSynchronized { - get { - return privColObj.IsSynchronized; - } - } - - public virtual object SyncRoot { - get { - return this; - } - } - - public virtual void CopyTo(System.Array array, int index) { - privColObj.CopyTo(array, index); - int nCtr; - for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { - array.SetValue(new KvpExchangeComponentSettingData(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); - } - } - - public virtual System.Collections.IEnumerator GetEnumerator() { - return new KvpExchangeComponentSettingDataEnumerator(privColObj.GetEnumerator()); - } - - public class KvpExchangeComponentSettingDataEnumerator : object, System.Collections.IEnumerator { - - private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; - - public KvpExchangeComponentSettingDataEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { - privObjEnum = objEnum; - } - - public virtual object Current { - get { - return new KvpExchangeComponentSettingData(((System.Management.ManagementObject)(privObjEnum.Current))); - } - } - - public virtual bool MoveNext() { - return privObjEnum.MoveNext(); - } - - public virtual void Reset() { - privObjEnum.Reset(); - } - } - } - - // TypeConverter to handle null values for ValueType properties - public class WMIValueTypeConverter : TypeConverter { - - private TypeConverter baseConverter; - - private System.Type baseType; - - public WMIValueTypeConverter(System.Type inBaseType) { - baseConverter = TypeDescriptor.GetConverter(inBaseType); - baseType = inBaseType; - } - - public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { - return baseConverter.CanConvertFrom(context, srcType); - } - - public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { - return baseConverter.CanConvertTo(context, destinationType); - } - - public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { - return baseConverter.ConvertFrom(context, culture, value); - } - - public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { - return baseConverter.CreateInstance(context, dictionary); - } - - public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetCreateInstanceSupported(context); - } - - public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { - return baseConverter.GetProperties(context, value, attributeVar); - } - - public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetPropertiesSupported(context); - } - - public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValues(context); - } - - public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesExclusive(context); - } - - public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesSupported(context); - } - - public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { - if ((baseType.BaseType == typeof(System.Enum))) { - if ((value.GetType() == destinationType)) { - return value; - } - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return "NULL_ENUM_VALUE" ; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((baseType == typeof(bool)) - && (baseType.BaseType == typeof(System.ValueType)))) { - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((context != null) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - } - - // Embedded class to represent WMI system Properties. - [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] - public class ManagementSystemProperties { - - private System.Management.ManagementBaseObject PrivateLateBoundObject; - - public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { - PrivateLateBoundObject = ManagedObject; - } - - [Browsable(true)] - public int GENUS { - get { - return ((int)(PrivateLateBoundObject["__GENUS"])); - } - } - - [Browsable(true)] - public string CLASS { - get { - return ((string)(PrivateLateBoundObject["__CLASS"])); - } - } - - [Browsable(true)] - public string SUPERCLASS { - get { - return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); - } - } - - [Browsable(true)] - public string DYNASTY { - get { - return ((string)(PrivateLateBoundObject["__DYNASTY"])); - } - } - - [Browsable(true)] - public string RELPATH { - get { - return ((string)(PrivateLateBoundObject["__RELPATH"])); - } - } - - [Browsable(true)] - public int PROPERTY_COUNT { - get { - return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); - } - } - - [Browsable(true)] - public string[] DERIVATION { - get { - return ((string[])(PrivateLateBoundObject["__DERIVATION"])); - } - } - - [Browsable(true)] - public string SERVER { - get { - return ((string)(PrivateLateBoundObject["__SERVER"])); - } - } - - [Browsable(true)] - public string NAMESPACE { - get { - return ((string)(PrivateLateBoundObject["__NAMESPACE"])); - } - } - - [Browsable(true)] - public string PATH { - get { - return ((string)(PrivateLateBoundObject["__PATH"])); - } - } - } - } -} +This is a read-only property, but it can be changed using the ModifyVirtualSystemResources method of the Msvm_VirtualSystemManagementService class.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort EnabledState { + get { + if ((curObj["EnabledState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["EnabledState"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("An array of Msvm_KvpExchangeDataItem instances.\nThis is a read-only property, but" + + " it can be changed using the AddKvpItems, ModifyKvpItems, and RemoveKvpItems met" + + "hods of the Msvm_VirtualSystemManagementService class.")] + public string[] HostExchangeItems { + get { + return ((string[])(curObj["HostExchangeItems"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"An array of Msvm_KvpExchangeDataItem instances containing the key/value pairs that are stored in the configuration file but not exchanged with the guest OS. This allows applications to store VM-specific data that does not need to be visible to the guest OS. The items are formatted the same as the items in the HostExchangeItems property except the Source property of the Msvm_KvpExchangeDataItem instance is set to 4. Each configuration file is limited to 128 key/value pairs, where each value field is allowed to be up to 16 KB in size and the key field is allowed to be up to512 bytes.")] + public string[] HostOnlyItems { + get { + return ((string[])(curObj["HostOnlyItems"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] HostResource { + get { + return ((string[])(curObj["HostResource"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string InstanceID { + get { + return ((string)(curObj["InstanceID"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsLimitNull { + get { + if ((curObj["Limit"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong Limit { + get { + if ((curObj["Limit"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["Limit"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsMappingBehaviorNull { + get { + if ((curObj["MappingBehavior"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort MappingBehavior { + get { + if ((curObj["MappingBehavior"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["MappingBehavior"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherResourceType { + get { + return ((string)(curObj["OtherResourceType"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Parent { + get { + return ((string)(curObj["Parent"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string PoolID { + get { + return ((string)(curObj["PoolID"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsReservationNull { + get { + if ((curObj["Reservation"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong Reservation { + get { + if ((curObj["Reservation"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["Reservation"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ResourceSubType { + get { + return ((string)(curObj["ResourceSubType"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsResourceTypeNull { + get { + if ((curObj["ResourceType"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort ResourceType { + get { + if ((curObj["ResourceType"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["ResourceType"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsVirtualQuantityNull { + get { + if ((curObj["VirtualQuantity"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong VirtualQuantity { + get { + if ((curObj["VirtualQuantity"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["VirtualQuantity"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string VirtualQuantityUnits { + get { + return ((string)(curObj["VirtualQuantityUnits"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsWeightNull { + get { + if ((curObj["Weight"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint Weight { + get { + if ((curObj["Weight"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["Weight"])); + } + } + + private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { + if (((path != null) + && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); + } + } + + private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { + if (((theObj != null) + && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); + if ((parentClasses != null)) { + int count = 0; + for (count = 0; (count < parentClasses.Length); count = (count + 1)) { + if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { + return true; + } + } + } + } + return false; + } + + private bool ShouldSerializeAutomaticAllocation() { + if ((this.IsAutomaticAllocationNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeAutomaticDeallocation() { + if ((this.IsAutomaticDeallocationNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeConsumerVisibility() { + if ((this.IsConsumerVisibilityNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeEnabledState() { + if ((this.IsEnabledStateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeLimit() { + if ((this.IsLimitNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeMappingBehavior() { + if ((this.IsMappingBehaviorNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeReservation() { + if ((this.IsReservationNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeResourceType() { + if ((this.IsResourceTypeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeVirtualQuantity() { + if ((this.IsVirtualQuantityNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeWeight() { + if ((this.IsWeightNull == false)) { + return true; + } + return false; + } + + [Browsable(true)] + public void CommitObject() { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(); + } + } + + [Browsable(true)] + public void CommitObject(System.Management.PutOptions putOptions) { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(putOptions); + } + } + + private void Initialize() { + AutoCommitProp = true; + isEmbedded = false; + } + + private static string ConstructPath(string keyInstanceID) { + string strPath = "ROOT\\virtualization\\v2:Msvm_KvpExchangeComponentSettingData"; + strPath = string.Concat(strPath, string.Concat(".InstanceID=", string.Concat("\"", string.Concat(keyInstanceID, "\"")))); + return strPath; + } + + private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + Initialize(); + if ((path != null)) { + if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + } + PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + + // Different overloads of GetInstances() help in enumerating instances of the WMI class. + public static KvpExchangeComponentSettingDataCollection GetInstances() { + return GetInstances(null, null, null); + } + + public static KvpExchangeComponentSettingDataCollection GetInstances(string condition) { + return GetInstances(null, condition, null); + } + + public static KvpExchangeComponentSettingDataCollection GetInstances(string[] selectedProperties) { + return GetInstances(null, null, selectedProperties); + } + + public static KvpExchangeComponentSettingDataCollection GetInstances(string condition, string[] selectedProperties) { + return GetInstances(null, condition, selectedProperties); + } + + public static KvpExchangeComponentSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); + pathObj.ClassName = "Msvm_KvpExchangeComponentSettingData"; + pathObj.NamespacePath = "root\\virtualization\\v2"; + System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); + if ((enumOptions == null)) { + enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + } + return new KvpExchangeComponentSettingDataCollection(clsObject.GetInstances(enumOptions)); + } + + public static KvpExchangeComponentSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { + return GetInstances(mgmtScope, condition, null); + } + + public static KvpExchangeComponentSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { + return GetInstances(mgmtScope, null, selectedProperties); + } + + public static KvpExchangeComponentSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_KvpExchangeComponentSettingData", condition, selectedProperties)); + System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + ObjectSearcher.Options = enumOptions; + return new KvpExchangeComponentSettingDataCollection(ObjectSearcher.Get()); + } + + [Browsable(true)] + public static KvpExchangeComponentSettingData CreateInstance() { + System.Management.ManagementScope mgmtScope = null; + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = CreatedWmiNamespace; + } + else { + mgmtScope = statMgmtScope; + } + System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); + System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); + return new KvpExchangeComponentSettingData(tmpMgmtClass.CreateInstance()); + } + + [Browsable(true)] + public void Delete() { + PrivateLateBoundObject.Delete(); + } + + // Enumerator implementation for enumerating instances of the class. + public class KvpExchangeComponentSettingDataCollection : object, ICollection { + + private ManagementObjectCollection privColObj; + + public KvpExchangeComponentSettingDataCollection(ManagementObjectCollection objCollection) { + privColObj = objCollection; + } + + public virtual int Count { + get { + return privColObj.Count; + } + } + + public virtual bool IsSynchronized { + get { + return privColObj.IsSynchronized; + } + } + + public virtual object SyncRoot { + get { + return this; + } + } + + public virtual void CopyTo(System.Array array, int index) { + privColObj.CopyTo(array, index); + int nCtr; + for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { + array.SetValue(new KvpExchangeComponentSettingData(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); + } + } + + public virtual System.Collections.IEnumerator GetEnumerator() { + return new KvpExchangeComponentSettingDataEnumerator(privColObj.GetEnumerator()); + } + + public class KvpExchangeComponentSettingDataEnumerator : object, System.Collections.IEnumerator { + + private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; + + public KvpExchangeComponentSettingDataEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { + privObjEnum = objEnum; + } + + public virtual object Current { + get { + return new KvpExchangeComponentSettingData(((System.Management.ManagementObject)(privObjEnum.Current))); + } + } + + public virtual bool MoveNext() { + return privObjEnum.MoveNext(); + } + + public virtual void Reset() { + privObjEnum.Reset(); + } + } + } + + // TypeConverter to handle null values for ValueType properties + public class WMIValueTypeConverter : TypeConverter { + + private TypeConverter baseConverter; + + private System.Type baseType; + + public WMIValueTypeConverter(System.Type inBaseType) { + baseConverter = TypeDescriptor.GetConverter(inBaseType); + baseType = inBaseType; + } + + public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { + return baseConverter.CanConvertFrom(context, srcType); + } + + public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { + return baseConverter.CanConvertTo(context, destinationType); + } + + public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { + return baseConverter.ConvertFrom(context, culture, value); + } + + public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { + return baseConverter.CreateInstance(context, dictionary); + } + + public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetCreateInstanceSupported(context); + } + + public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { + return baseConverter.GetProperties(context, value, attributeVar); + } + + public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetPropertiesSupported(context); + } + + public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValues(context); + } + + public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesExclusive(context); + } + + public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesSupported(context); + } + + public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { + if ((baseType.BaseType == typeof(System.Enum))) { + if ((value.GetType() == destinationType)) { + return value; + } + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return "NULL_ENUM_VALUE" ; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((baseType == typeof(bool)) + && (baseType.BaseType == typeof(System.ValueType)))) { + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((context != null) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + } + + // Embedded class to represent WMI system Properties. + [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] + public class ManagementSystemProperties { + + private System.Management.ManagementBaseObject PrivateLateBoundObject; + + public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { + PrivateLateBoundObject = ManagedObject; + } + + [Browsable(true)] + public int GENUS { + get { + return ((int)(PrivateLateBoundObject["__GENUS"])); + } + } + + [Browsable(true)] + public string CLASS { + get { + return ((string)(PrivateLateBoundObject["__CLASS"])); + } + } + + [Browsable(true)] + public string SUPERCLASS { + get { + return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); + } + } + + [Browsable(true)] + public string DYNASTY { + get { + return ((string)(PrivateLateBoundObject["__DYNASTY"])); + } + } + + [Browsable(true)] + public string RELPATH { + get { + return ((string)(PrivateLateBoundObject["__RELPATH"])); + } + } + + [Browsable(true)] + public int PROPERTY_COUNT { + get { + return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); + } + } + + [Browsable(true)] + public string[] DERIVATION { + get { + return ((string[])(PrivateLateBoundObject["__DERIVATION"])); + } + } + + [Browsable(true)] + public string SERVER { + get { + return ((string)(PrivateLateBoundObject["__SERVER"])); + } + } + + [Browsable(true)] + public string NAMESPACE { + get { + return ((string)(PrivateLateBoundObject["__NAMESPACE"])); + } + } + + [Browsable(true)] + public string PATH { + get { + return ((string)(PrivateLateBoundObject["__PATH"])); + } + } + } + } +} diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_KvpExchangeDataItem.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_KvpExchangeDataItem.cs index bf5eaae8e7c..ffc1e9888ac 100644 --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_KvpExchangeDataItem.cs +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_KvpExchangeDataItem.cs @@ -1,670 +1,670 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2 -{ - using System; - using System.ComponentModel; - using System.Management; - using System.Collections; - using System.Globalization; - using System.ComponentModel.Design.Serialization; - using System.Reflection; - - - // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. - // Functions IsNull() are used to check if a property is NULL. - // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. - // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. - // An Early Bound class generated for the WMI class.Msvm_KvpExchangeDataItem - public class KvpExchangeDataItem : System.ComponentModel.Component { - - // Private property to hold the WMI namespace in which the class resides. - private static string CreatedWmiNamespace = "ROOT\\virtualization\\v2"; - - // Private property to hold the name of WMI class which created this class. - private static string CreatedClassName = "Msvm_KvpExchangeDataItem"; - - // Private member variable to hold the ManagementScope which is used by the various methods. - private static System.Management.ManagementScope statMgmtScope = null; - - private ManagementSystemProperties PrivateSystemProperties; - - // Underlying lateBound WMI object. - private System.Management.ManagementObject PrivateLateBoundObject; - - // Member variable to store the 'automatic commit' behavior for the class. - private bool AutoCommitProp; - - // Private variable to hold the embedded property representing the instance. - private System.Management.ManagementBaseObject embeddedObj; - - // The current WMI object used - private System.Management.ManagementBaseObject curObj; - - // Flag to indicate if the instance is an embedded object. - private bool isEmbedded; - - // Below are different overloads of constructors to initialize an instance of the class with a WMI object. - public KvpExchangeDataItem() { - this.InitializeObject(null, null, null); - } - - public KvpExchangeDataItem(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(null, path, getOptions); - } - - public KvpExchangeDataItem(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { - this.InitializeObject(mgmtScope, path, null); - } - - public KvpExchangeDataItem(System.Management.ManagementPath path) { - this.InitializeObject(null, path, null); - } - - public KvpExchangeDataItem(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(mgmtScope, path, getOptions); - } - - public KvpExchangeDataItem(System.Management.ManagementObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - PrivateLateBoundObject = theObject; - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - public KvpExchangeDataItem(System.Management.ManagementBaseObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - embeddedObj = theObject; - PrivateSystemProperties = new ManagementSystemProperties(theObject); - curObj = embeddedObj; - isEmbedded = true; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - // Property returns the namespace of the WMI class. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OriginatingNamespace { - get { - return "ROOT\\virtualization\\v2"; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ManagementClassName { - get { - string strRet = CreatedClassName; - if ((curObj != null)) { - if ((curObj.ClassPath != null)) { - strRet = ((string)(curObj["__CLASS"])); - if (((strRet == null) - || (strRet == string.Empty))) { - strRet = CreatedClassName; - } - } - } - return strRet; - } - } - - // Property pointing to an embedded object to get System properties of the WMI object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ManagementSystemProperties SystemProperties { - get { - return PrivateSystemProperties; - } - } - - // Property returning the underlying lateBound object. - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementBaseObject LateBoundObject { - get { - return curObj; - } - } - - // ManagementScope of the object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementScope Scope { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Scope; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Scope = value; - } - } - } - - // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool AutoCommit { - get { - return AutoCommitProp; - } - set { - AutoCommitProp = value; - } - } - - // The ManagementPath of the underlying WMI object. - [Browsable(true)] - public System.Management.ManagementPath Path { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Path; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - if ((CheckIfProperClass(null, value, null) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - PrivateLateBoundObject.Path = value; - } - } - } - - // Public static scope property which is used by the various methods. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public static System.Management.ManagementScope StaticScope { - get { - return statMgmtScope; - } - set { - statMgmtScope = value; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Caption { - get { - return ((string)(curObj["Caption"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Data { - get { - return ((string)(curObj["Data"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Description { - get { - return ((string)(curObj["Description"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ElementName { - get { - return ((string)(curObj["ElementName"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string InstanceID { - get { - return ((string)(curObj["InstanceID"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Name { - get { - return ((string)(curObj["Name"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsSourceNull { - get { - if ((curObj["Source"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort Source { - get { - if ((curObj["Source"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["Source"])); - } - } - - private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { - if (((path != null) - && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); - } - } - - private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { - if (((theObj != null) - && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); - if ((parentClasses != null)) { - int count = 0; - for (count = 0; (count < parentClasses.Length); count = (count + 1)) { - if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { - return true; - } - } - } - } - return false; - } - - private bool ShouldSerializeSource() { - if ((this.IsSourceNull == false)) { - return true; - } - return false; - } - - [Browsable(true)] - public void CommitObject() { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(); - } - } - - [Browsable(true)] - public void CommitObject(System.Management.PutOptions putOptions) { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(putOptions); - } - } - - private void Initialize() { - AutoCommitProp = true; - isEmbedded = false; - } - - private static string ConstructPath() { - string strPath = "ROOT\\virtualization\\v2:Msvm_KvpExchangeDataItem"; - return strPath; - } - - private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - Initialize(); - if ((path != null)) { - if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - } - PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - - // Different overloads of GetInstances() help in enumerating instances of the WMI class. - public static KvpExchangeDataItemCollection GetInstances() { - return GetInstances(null, null, null); - } - - public static KvpExchangeDataItemCollection GetInstances(string condition) { - return GetInstances(null, condition, null); - } - - public static KvpExchangeDataItemCollection GetInstances(string[] selectedProperties) { - return GetInstances(null, null, selectedProperties); - } - - public static KvpExchangeDataItemCollection GetInstances(string condition, string[] selectedProperties) { - return GetInstances(null, condition, selectedProperties); - } - - public static KvpExchangeDataItemCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); - pathObj.ClassName = "Msvm_KvpExchangeDataItem"; - pathObj.NamespacePath = "root\\virtualization\\v2"; - System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); - if ((enumOptions == null)) { - enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - } - return new KvpExchangeDataItemCollection(clsObject.GetInstances(enumOptions)); - } - - public static KvpExchangeDataItemCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { - return GetInstances(mgmtScope, condition, null); - } - - public static KvpExchangeDataItemCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { - return GetInstances(mgmtScope, null, selectedProperties); - } - - public static KvpExchangeDataItemCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_KvpExchangeDataItem", condition, selectedProperties)); - System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - ObjectSearcher.Options = enumOptions; - return new KvpExchangeDataItemCollection(ObjectSearcher.Get()); - } - - [Browsable(true)] - public static KvpExchangeDataItem CreateInstance() { - System.Management.ManagementScope mgmtScope = null; - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = CreatedWmiNamespace; - } - else { - mgmtScope = statMgmtScope; - } - System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); - System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); - return new KvpExchangeDataItem(tmpMgmtClass.CreateInstance()); - } - - [Browsable(true)] - public void Delete() { - PrivateLateBoundObject.Delete(); - } - - // Enumerator implementation for enumerating instances of the class. - public class KvpExchangeDataItemCollection : object, ICollection { - - private ManagementObjectCollection privColObj; - - public KvpExchangeDataItemCollection(ManagementObjectCollection objCollection) { - privColObj = objCollection; - } - - public virtual int Count { - get { - return privColObj.Count; - } - } - - public virtual bool IsSynchronized { - get { - return privColObj.IsSynchronized; - } - } - - public virtual object SyncRoot { - get { - return this; - } - } - - public virtual void CopyTo(System.Array array, int index) { - privColObj.CopyTo(array, index); - int nCtr; - for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { - array.SetValue(new KvpExchangeDataItem(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); - } - } - - public virtual System.Collections.IEnumerator GetEnumerator() { - return new KvpExchangeDataItemEnumerator(privColObj.GetEnumerator()); - } - - public class KvpExchangeDataItemEnumerator : object, System.Collections.IEnumerator { - - private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; - - public KvpExchangeDataItemEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { - privObjEnum = objEnum; - } - - public virtual object Current { - get { - return new KvpExchangeDataItem(((System.Management.ManagementObject)(privObjEnum.Current))); - } - } - - public virtual bool MoveNext() { - return privObjEnum.MoveNext(); - } - - public virtual void Reset() { - privObjEnum.Reset(); - } - } - } - - // TypeConverter to handle null values for ValueType properties - public class WMIValueTypeConverter : TypeConverter { - - private TypeConverter baseConverter; - - private System.Type baseType; - - public WMIValueTypeConverter(System.Type inBaseType) { - baseConverter = TypeDescriptor.GetConverter(inBaseType); - baseType = inBaseType; - } - - public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { - return baseConverter.CanConvertFrom(context, srcType); - } - - public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { - return baseConverter.CanConvertTo(context, destinationType); - } - - public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { - return baseConverter.ConvertFrom(context, culture, value); - } - - public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { - return baseConverter.CreateInstance(context, dictionary); - } - - public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetCreateInstanceSupported(context); - } - - public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { - return baseConverter.GetProperties(context, value, attributeVar); - } - - public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetPropertiesSupported(context); - } - - public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValues(context); - } - - public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesExclusive(context); - } - - public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesSupported(context); - } - - public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { - if ((baseType.BaseType == typeof(System.Enum))) { - if ((value.GetType() == destinationType)) { - return value; - } - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return "NULL_ENUM_VALUE" ; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((baseType == typeof(bool)) - && (baseType.BaseType == typeof(System.ValueType)))) { - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((context != null) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - } - - // Embedded class to represent WMI system Properties. - [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] - public class ManagementSystemProperties { - - private System.Management.ManagementBaseObject PrivateLateBoundObject; - - public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { - PrivateLateBoundObject = ManagedObject; - } - - [Browsable(true)] - public int GENUS { - get { - return ((int)(PrivateLateBoundObject["__GENUS"])); - } - } - - [Browsable(true)] - public string CLASS { - get { - return ((string)(PrivateLateBoundObject["__CLASS"])); - } - } - - [Browsable(true)] - public string SUPERCLASS { - get { - return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); - } - } - - [Browsable(true)] - public string DYNASTY { - get { - return ((string)(PrivateLateBoundObject["__DYNASTY"])); - } - } - - [Browsable(true)] - public string RELPATH { - get { - return ((string)(PrivateLateBoundObject["__RELPATH"])); - } - } - - [Browsable(true)] - public int PROPERTY_COUNT { - get { - return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); - } - } - - [Browsable(true)] - public string[] DERIVATION { - get { - return ((string[])(PrivateLateBoundObject["__DERIVATION"])); - } - } - - [Browsable(true)] - public string SERVER { - get { - return ((string)(PrivateLateBoundObject["__SERVER"])); - } - } - - [Browsable(true)] - public string NAMESPACE { - get { - return ((string)(PrivateLateBoundObject["__NAMESPACE"])); - } - } - - [Browsable(true)] - public string PATH { - get { - return ((string)(PrivateLateBoundObject["__PATH"])); - } - } - } - } -} +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2 +{ + using System; + using System.ComponentModel; + using System.Management; + using System.Collections; + using System.Globalization; + using System.ComponentModel.Design.Serialization; + using System.Reflection; + + + // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. + // Functions IsNull() are used to check if a property is NULL. + // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. + // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. + // An Early Bound class generated for the WMI class.Msvm_KvpExchangeDataItem + public class KvpExchangeDataItem : System.ComponentModel.Component { + + // Private property to hold the WMI namespace in which the class resides. + private static string CreatedWmiNamespace = "ROOT\\virtualization\\v2"; + + // Private property to hold the name of WMI class which created this class. + private static string CreatedClassName = "Msvm_KvpExchangeDataItem"; + + // Private member variable to hold the ManagementScope which is used by the various methods. + private static System.Management.ManagementScope statMgmtScope = null; + + private ManagementSystemProperties PrivateSystemProperties; + + // Underlying lateBound WMI object. + private System.Management.ManagementObject PrivateLateBoundObject; + + // Member variable to store the 'automatic commit' behavior for the class. + private bool AutoCommitProp; + + // Private variable to hold the embedded property representing the instance. + private System.Management.ManagementBaseObject embeddedObj; + + // The current WMI object used + private System.Management.ManagementBaseObject curObj; + + // Flag to indicate if the instance is an embedded object. + private bool isEmbedded; + + // Below are different overloads of constructors to initialize an instance of the class with a WMI object. + public KvpExchangeDataItem() { + this.InitializeObject(null, null, null); + } + + public KvpExchangeDataItem(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(null, path, getOptions); + } + + public KvpExchangeDataItem(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { + this.InitializeObject(mgmtScope, path, null); + } + + public KvpExchangeDataItem(System.Management.ManagementPath path) { + this.InitializeObject(null, path, null); + } + + public KvpExchangeDataItem(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(mgmtScope, path, getOptions); + } + + public KvpExchangeDataItem(System.Management.ManagementObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + PrivateLateBoundObject = theObject; + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + public KvpExchangeDataItem(System.Management.ManagementBaseObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + embeddedObj = theObject; + PrivateSystemProperties = new ManagementSystemProperties(theObject); + curObj = embeddedObj; + isEmbedded = true; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + // Property returns the namespace of the WMI class. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OriginatingNamespace { + get { + return "ROOT\\virtualization\\v2"; + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ManagementClassName { + get { + string strRet = CreatedClassName; + if ((curObj != null)) { + if ((curObj.ClassPath != null)) { + strRet = ((string)(curObj["__CLASS"])); + if (((strRet == null) + || (strRet == string.Empty))) { + strRet = CreatedClassName; + } + } + } + return strRet; + } + } + + // Property pointing to an embedded object to get System properties of the WMI object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ManagementSystemProperties SystemProperties { + get { + return PrivateSystemProperties; + } + } + + // Property returning the underlying lateBound object. + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementBaseObject LateBoundObject { + get { + return curObj; + } + } + + // ManagementScope of the object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementScope Scope { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Scope; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Scope = value; + } + } + } + + // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool AutoCommit { + get { + return AutoCommitProp; + } + set { + AutoCommitProp = value; + } + } + + // The ManagementPath of the underlying WMI object. + [Browsable(true)] + public System.Management.ManagementPath Path { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Path; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + if ((CheckIfProperClass(null, value, null) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + PrivateLateBoundObject.Path = value; + } + } + } + + // Public static scope property which is used by the various methods. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public static System.Management.ManagementScope StaticScope { + get { + return statMgmtScope; + } + set { + statMgmtScope = value; + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Caption { + get { + return ((string)(curObj["Caption"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Data { + get { + return ((string)(curObj["Data"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Description { + get { + return ((string)(curObj["Description"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ElementName { + get { + return ((string)(curObj["ElementName"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string InstanceID { + get { + return ((string)(curObj["InstanceID"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Name { + get { + return ((string)(curObj["Name"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsSourceNull { + get { + if ((curObj["Source"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort Source { + get { + if ((curObj["Source"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["Source"])); + } + } + + private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { + if (((path != null) + && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); + } + } + + private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { + if (((theObj != null) + && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); + if ((parentClasses != null)) { + int count = 0; + for (count = 0; (count < parentClasses.Length); count = (count + 1)) { + if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { + return true; + } + } + } + } + return false; + } + + private bool ShouldSerializeSource() { + if ((this.IsSourceNull == false)) { + return true; + } + return false; + } + + [Browsable(true)] + public void CommitObject() { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(); + } + } + + [Browsable(true)] + public void CommitObject(System.Management.PutOptions putOptions) { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(putOptions); + } + } + + private void Initialize() { + AutoCommitProp = true; + isEmbedded = false; + } + + private static string ConstructPath() { + string strPath = "ROOT\\virtualization\\v2:Msvm_KvpExchangeDataItem"; + return strPath; + } + + private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + Initialize(); + if ((path != null)) { + if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + } + PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + + // Different overloads of GetInstances() help in enumerating instances of the WMI class. + public static KvpExchangeDataItemCollection GetInstances() { + return GetInstances(null, null, null); + } + + public static KvpExchangeDataItemCollection GetInstances(string condition) { + return GetInstances(null, condition, null); + } + + public static KvpExchangeDataItemCollection GetInstances(string[] selectedProperties) { + return GetInstances(null, null, selectedProperties); + } + + public static KvpExchangeDataItemCollection GetInstances(string condition, string[] selectedProperties) { + return GetInstances(null, condition, selectedProperties); + } + + public static KvpExchangeDataItemCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); + pathObj.ClassName = "Msvm_KvpExchangeDataItem"; + pathObj.NamespacePath = "root\\virtualization\\v2"; + System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); + if ((enumOptions == null)) { + enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + } + return new KvpExchangeDataItemCollection(clsObject.GetInstances(enumOptions)); + } + + public static KvpExchangeDataItemCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { + return GetInstances(mgmtScope, condition, null); + } + + public static KvpExchangeDataItemCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { + return GetInstances(mgmtScope, null, selectedProperties); + } + + public static KvpExchangeDataItemCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_KvpExchangeDataItem", condition, selectedProperties)); + System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + ObjectSearcher.Options = enumOptions; + return new KvpExchangeDataItemCollection(ObjectSearcher.Get()); + } + + [Browsable(true)] + public static KvpExchangeDataItem CreateInstance() { + System.Management.ManagementScope mgmtScope = null; + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = CreatedWmiNamespace; + } + else { + mgmtScope = statMgmtScope; + } + System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); + System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); + return new KvpExchangeDataItem(tmpMgmtClass.CreateInstance()); + } + + [Browsable(true)] + public void Delete() { + PrivateLateBoundObject.Delete(); + } + + // Enumerator implementation for enumerating instances of the class. + public class KvpExchangeDataItemCollection : object, ICollection { + + private ManagementObjectCollection privColObj; + + public KvpExchangeDataItemCollection(ManagementObjectCollection objCollection) { + privColObj = objCollection; + } + + public virtual int Count { + get { + return privColObj.Count; + } + } + + public virtual bool IsSynchronized { + get { + return privColObj.IsSynchronized; + } + } + + public virtual object SyncRoot { + get { + return this; + } + } + + public virtual void CopyTo(System.Array array, int index) { + privColObj.CopyTo(array, index); + int nCtr; + for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { + array.SetValue(new KvpExchangeDataItem(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); + } + } + + public virtual System.Collections.IEnumerator GetEnumerator() { + return new KvpExchangeDataItemEnumerator(privColObj.GetEnumerator()); + } + + public class KvpExchangeDataItemEnumerator : object, System.Collections.IEnumerator { + + private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; + + public KvpExchangeDataItemEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { + privObjEnum = objEnum; + } + + public virtual object Current { + get { + return new KvpExchangeDataItem(((System.Management.ManagementObject)(privObjEnum.Current))); + } + } + + public virtual bool MoveNext() { + return privObjEnum.MoveNext(); + } + + public virtual void Reset() { + privObjEnum.Reset(); + } + } + } + + // TypeConverter to handle null values for ValueType properties + public class WMIValueTypeConverter : TypeConverter { + + private TypeConverter baseConverter; + + private System.Type baseType; + + public WMIValueTypeConverter(System.Type inBaseType) { + baseConverter = TypeDescriptor.GetConverter(inBaseType); + baseType = inBaseType; + } + + public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { + return baseConverter.CanConvertFrom(context, srcType); + } + + public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { + return baseConverter.CanConvertTo(context, destinationType); + } + + public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { + return baseConverter.ConvertFrom(context, culture, value); + } + + public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { + return baseConverter.CreateInstance(context, dictionary); + } + + public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetCreateInstanceSupported(context); + } + + public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { + return baseConverter.GetProperties(context, value, attributeVar); + } + + public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetPropertiesSupported(context); + } + + public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValues(context); + } + + public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesExclusive(context); + } + + public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesSupported(context); + } + + public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { + if ((baseType.BaseType == typeof(System.Enum))) { + if ((value.GetType() == destinationType)) { + return value; + } + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return "NULL_ENUM_VALUE" ; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((baseType == typeof(bool)) + && (baseType.BaseType == typeof(System.ValueType)))) { + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((context != null) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + } + + // Embedded class to represent WMI system Properties. + [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] + public class ManagementSystemProperties { + + private System.Management.ManagementBaseObject PrivateLateBoundObject; + + public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { + PrivateLateBoundObject = ManagedObject; + } + + [Browsable(true)] + public int GENUS { + get { + return ((int)(PrivateLateBoundObject["__GENUS"])); + } + } + + [Browsable(true)] + public string CLASS { + get { + return ((string)(PrivateLateBoundObject["__CLASS"])); + } + } + + [Browsable(true)] + public string SUPERCLASS { + get { + return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); + } + } + + [Browsable(true)] + public string DYNASTY { + get { + return ((string)(PrivateLateBoundObject["__DYNASTY"])); + } + } + + [Browsable(true)] + public string RELPATH { + get { + return ((string)(PrivateLateBoundObject["__RELPATH"])); + } + } + + [Browsable(true)] + public int PROPERTY_COUNT { + get { + return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); + } + } + + [Browsable(true)] + public string[] DERIVATION { + get { + return ((string[])(PrivateLateBoundObject["__DERIVATION"])); + } + } + + [Browsable(true)] + public string SERVER { + get { + return ((string)(PrivateLateBoundObject["__SERVER"])); + } + } + + [Browsable(true)] + public string NAMESPACE { + get { + return ((string)(PrivateLateBoundObject["__NAMESPACE"])); + } + } + + [Browsable(true)] + public string PATH { + get { + return ((string)(PrivateLateBoundObject["__PATH"])); + } + } + } + } +} diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_LANEndpoint.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_LANEndpoint.cs index 453f528d497..ee8563aadc5 100644 --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_LANEndpoint.cs +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_LANEndpoint.cs @@ -1,1422 +1,1422 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2 { - using System; - using System.ComponentModel; - using System.Management; - using System.Collections; - using System.Globalization; - using System.ComponentModel.Design.Serialization; - using System.Reflection; - - - // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. - // Functions IsNull() are used to check if a property is NULL. - // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. - // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. - // Datetime conversion functions ToDateTime and ToDmtfDateTime are added to the class to convert DMTF datetime to System.DateTime and vice-versa. - // An Early Bound class generated for the WMI class.Msvm_LANEndpoint - public class LANEndpoint : System.ComponentModel.Component { - - // Private property to hold the WMI namespace in which the class resides. - private static string CreatedWmiNamespace = "ROOT\\virtualization\\v2"; - - // Private property to hold the name of WMI class which created this class. - public static string CreatedClassName = "Msvm_LANEndpoint"; - - // Private member variable to hold the ManagementScope which is used by the various methods. - private static System.Management.ManagementScope statMgmtScope = null; - - private ManagementSystemProperties PrivateSystemProperties; - - // Underlying lateBound WMI object. - private System.Management.ManagementObject PrivateLateBoundObject; - - // Member variable to store the 'automatic commit' behavior for the class. - private bool AutoCommitProp; - - // Private variable to hold the embedded property representing the instance. - private System.Management.ManagementBaseObject embeddedObj; - - // The current WMI object used - private System.Management.ManagementBaseObject curObj; - - // Flag to indicate if the instance is an embedded object. - private bool isEmbedded; - - // Below are different overloads of constructors to initialize an instance of the class with a WMI object. - public LANEndpoint() { - this.InitializeObject(null, null, null); - } - - public LANEndpoint(string keyCreationClassName, string keyName, string keySystemCreationClassName, string keySystemName) { - this.InitializeObject(null, new System.Management.ManagementPath(LANEndpoint.ConstructPath(keyCreationClassName, keyName, keySystemCreationClassName, keySystemName)), null); - } - - public LANEndpoint(System.Management.ManagementScope mgmtScope, string keyCreationClassName, string keyName, string keySystemCreationClassName, string keySystemName) { - this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(LANEndpoint.ConstructPath(keyCreationClassName, keyName, keySystemCreationClassName, keySystemName)), null); - } - - public LANEndpoint(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(null, path, getOptions); - } - - public LANEndpoint(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { - this.InitializeObject(mgmtScope, path, null); - } - - public LANEndpoint(System.Management.ManagementPath path) { - this.InitializeObject(null, path, null); - } - - public LANEndpoint(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(mgmtScope, path, getOptions); - } - - public LANEndpoint(System.Management.ManagementObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - PrivateLateBoundObject = theObject; - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - public LANEndpoint(System.Management.ManagementBaseObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - embeddedObj = theObject; - PrivateSystemProperties = new ManagementSystemProperties(theObject); - curObj = embeddedObj; - isEmbedded = true; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - // Property returns the namespace of the WMI class. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OriginatingNamespace { - get { - return "ROOT\\virtualization\\v2"; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ManagementClassName { - get { - string strRet = CreatedClassName; - if ((curObj != null)) { - if ((curObj.ClassPath != null)) { - strRet = ((string)(curObj["__CLASS"])); - if (((strRet == null) - || (strRet == string.Empty))) { - strRet = CreatedClassName; - } - } - } - return strRet; - } - } - - // Property pointing to an embedded object to get System properties of the WMI object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ManagementSystemProperties SystemProperties { - get { - return PrivateSystemProperties; - } - } - - // Property returning the underlying lateBound object. - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementBaseObject LateBoundObject { - get { - return curObj; - } - } - - // ManagementScope of the object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementScope Scope { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Scope; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Scope = value; - } - } - } - - // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool AutoCommit { - get { - return AutoCommitProp; - } - set { - AutoCommitProp = value; - } - } - - // The ManagementPath of the underlying WMI object. - [Browsable(true)] - public System.Management.ManagementPath Path { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Path; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - if ((CheckIfProperClass(null, value, null) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - PrivateLateBoundObject.Path = value; - } - } - } - - // Public static scope property which is used by the various methods. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public static System.Management.ManagementScope StaticScope { - get { - return statMgmtScope; - } - set { - statMgmtScope = value; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] AliasAddresses { - get { - return ((string[])(curObj["AliasAddresses"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ushort[] AvailableRequestedStates { - get { - return ((ushort[])(curObj["AvailableRequestedStates"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Caption { - get { - return ((string)(curObj["Caption"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsCommunicationStatusNull { - get { - if ((curObj["CommunicationStatus"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort CommunicationStatus { - get { - if ((curObj["CommunicationStatus"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["CommunicationStatus"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsConnectedNull { - get { - if ((curObj["Connected"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("This property is set to TRUE if the LAN endpoint is connected to a switch port.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool Connected { - get { - if ((curObj["Connected"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["Connected"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string CreationClassName { - get { - return ((string)(curObj["CreationClassName"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Description { - get { - return ((string)(curObj["Description"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsDetailedStatusNull { - get { - if ((curObj["DetailedStatus"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort DetailedStatus { - get { - if ((curObj["DetailedStatus"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["DetailedStatus"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ElementName { - get { - return ((string)(curObj["ElementName"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsEnabledDefaultNull { - get { - if ((curObj["EnabledDefault"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort EnabledDefault { - get { - if ((curObj["EnabledDefault"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["EnabledDefault"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsEnabledStateNull { - get { - if ((curObj["EnabledState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort EnabledState { - get { - if ((curObj["EnabledState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["EnabledState"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] GroupAddresses { - get { - return ((string[])(curObj["GroupAddresses"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsHealthStateNull { - get { - if ((curObj["HealthState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort HealthState { - get { - if ((curObj["HealthState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["HealthState"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsInstallDateNull { - get { - if ((curObj["InstallDate"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public System.DateTime InstallDate { - get { - if ((curObj["InstallDate"] != null)) { - return ToDateTime(((string)(curObj["InstallDate"]))); - } - else { - return System.DateTime.MinValue; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string InstanceID { - get { - return ((string)(curObj["InstanceID"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string LANID { - get { - return ((string)(curObj["LANID"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsLANTypeNull { - get { - if ((curObj["LANType"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort LANType { - get { - if ((curObj["LANType"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["LANType"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string MACAddress { - get { - return ((string)(curObj["MACAddress"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsMaxDataSizeNull { - get { - if ((curObj["MaxDataSize"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public uint MaxDataSize { - get { - if ((curObj["MaxDataSize"] == null)) { - return System.Convert.ToUInt32(0); - } - return ((uint)(curObj["MaxDataSize"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Name { - get { - return ((string)(curObj["Name"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string NameFormat { - get { - return ((string)(curObj["NameFormat"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsOperatingStatusNull { - get { - if ((curObj["OperatingStatus"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort OperatingStatus { - get { - if ((curObj["OperatingStatus"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["OperatingStatus"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ushort[] OperationalStatus { - get { - return ((ushort[])(curObj["OperationalStatus"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OtherEnabledState { - get { - return ((string)(curObj["OtherEnabledState"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OtherLANType { - get { - return ((string)(curObj["OtherLANType"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OtherTypeDescription { - get { - return ((string)(curObj["OtherTypeDescription"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsPrimaryStatusNull { - get { - if ((curObj["PrimaryStatus"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort PrimaryStatus { - get { - if ((curObj["PrimaryStatus"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["PrimaryStatus"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsProtocolIFTypeNull { - get { - if ((curObj["ProtocolIFType"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort ProtocolIFType { - get { - if ((curObj["ProtocolIFType"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["ProtocolIFType"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsProtocolTypeNull { - get { - if ((curObj["ProtocolType"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort ProtocolType { - get { - if ((curObj["ProtocolType"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["ProtocolType"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsRequestedStateNull { - get { - if ((curObj["RequestedState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort RequestedState { - get { - if ((curObj["RequestedState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["RequestedState"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Status { - get { - return ((string)(curObj["Status"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] StatusDescriptions { - get { - return ((string[])(curObj["StatusDescriptions"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string SystemCreationClassName { - get { - return ((string)(curObj["SystemCreationClassName"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string SystemName { - get { - return ((string)(curObj["SystemName"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsTimeOfLastStateChangeNull { - get { - if ((curObj["TimeOfLastStateChange"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public System.DateTime TimeOfLastStateChange { - get { - if ((curObj["TimeOfLastStateChange"] != null)) { - return ToDateTime(((string)(curObj["TimeOfLastStateChange"]))); - } - else { - return System.DateTime.MinValue; - } - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsTransitioningToStateNull { - get { - if ((curObj["TransitioningToState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort TransitioningToState { - get { - if ((curObj["TransitioningToState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["TransitioningToState"])); - } - } - - private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { - if (((path != null) - && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); - } - } - - private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { - if (((theObj != null) - && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); - if ((parentClasses != null)) { - int count = 0; - for (count = 0; (count < parentClasses.Length); count = (count + 1)) { - if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { - return true; - } - } - } - } - return false; - } - - private bool ShouldSerializeCommunicationStatus() { - if ((this.IsCommunicationStatusNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeConnected() { - if ((this.IsConnectedNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeDetailedStatus() { - if ((this.IsDetailedStatusNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeEnabledDefault() { - if ((this.IsEnabledDefaultNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeEnabledState() { - if ((this.IsEnabledStateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeHealthState() { - if ((this.IsHealthStateNull == false)) { - return true; - } - return false; - } - - // Converts a given datetime in DMTF format to System.DateTime object. - static System.DateTime ToDateTime(string dmtfDate) { - System.DateTime initializer = System.DateTime.MinValue; - int year = initializer.Year; - int month = initializer.Month; - int day = initializer.Day; - int hour = initializer.Hour; - int minute = initializer.Minute; - int second = initializer.Second; - long ticks = 0; - string dmtf = dmtfDate; - System.DateTime datetime = System.DateTime.MinValue; - string tempString = string.Empty; - if ((dmtf == null)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtf.Length == 0)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtf.Length != 25)) { - throw new System.ArgumentOutOfRangeException(); - } - try { - tempString = dmtf.Substring(0, 4); - if (("****" != tempString)) { - year = int.Parse(tempString); - } - tempString = dmtf.Substring(4, 2); - if (("**" != tempString)) { - month = int.Parse(tempString); - } - tempString = dmtf.Substring(6, 2); - if (("**" != tempString)) { - day = int.Parse(tempString); - } - tempString = dmtf.Substring(8, 2); - if (("**" != tempString)) { - hour = int.Parse(tempString); - } - tempString = dmtf.Substring(10, 2); - if (("**" != tempString)) { - minute = int.Parse(tempString); - } - tempString = dmtf.Substring(12, 2); - if (("**" != tempString)) { - second = int.Parse(tempString); - } - tempString = dmtf.Substring(15, 6); - if (("******" != tempString)) { - ticks = (long.Parse(tempString) * ((long)((System.TimeSpan.TicksPerMillisecond / 1000)))); - } - if (((((((((year < 0) - || (month < 0)) - || (day < 0)) - || (hour < 0)) - || (minute < 0)) - || (minute < 0)) - || (second < 0)) - || (ticks < 0))) { - throw new System.ArgumentOutOfRangeException(); - } - } - catch (System.Exception e) { - throw new System.ArgumentOutOfRangeException(null, e.Message); - } - datetime = new System.DateTime(year, month, day, hour, minute, second, 0); - datetime = datetime.AddTicks(ticks); - System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(datetime); - int UTCOffset = 0; - int OffsetToBeAdjusted = 0; - long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); - tempString = dmtf.Substring(22, 3); - if ((tempString != "******")) { - tempString = dmtf.Substring(21, 4); - try { - UTCOffset = int.Parse(tempString); - } - catch (System.Exception e) { - throw new System.ArgumentOutOfRangeException(null, e.Message); - } - OffsetToBeAdjusted = ((int)((OffsetMins - UTCOffset))); - datetime = datetime.AddMinutes(((double)(OffsetToBeAdjusted))); - } - return datetime; - } - - // Converts a given System.DateTime object to DMTF datetime format. - static string ToDmtfDateTime(System.DateTime date) { - string utcString = string.Empty; - System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(date); - long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); - if ((System.Math.Abs(OffsetMins) > 999)) { - date = date.ToUniversalTime(); - utcString = "+000"; - } - else { - if ((tickOffset.Ticks >= 0)) { - utcString = string.Concat("+", ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))).ToString().PadLeft(3, '0')); - } - else { - string strTemp = ((long)(OffsetMins)).ToString(); - utcString = string.Concat("-", strTemp.Substring(1, (strTemp.Length - 1)).PadLeft(3, '0')); - } - } - string dmtfDateTime = ((int)(date.Year)).ToString().PadLeft(4, '0'); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Month)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Day)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Hour)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Minute)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Second)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, "."); - System.DateTime dtTemp = new System.DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, 0); - long microsec = ((long)((((date.Ticks - dtTemp.Ticks) - * 1000) - / System.TimeSpan.TicksPerMillisecond))); - string strMicrosec = ((long)(microsec)).ToString(); - if ((strMicrosec.Length > 6)) { - strMicrosec = strMicrosec.Substring(0, 6); - } - dmtfDateTime = string.Concat(dmtfDateTime, strMicrosec.PadLeft(6, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, utcString); - return dmtfDateTime; - } - - private bool ShouldSerializeInstallDate() { - if ((this.IsInstallDateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeLANType() { - if ((this.IsLANTypeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeMaxDataSize() { - if ((this.IsMaxDataSizeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeOperatingStatus() { - if ((this.IsOperatingStatusNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializePrimaryStatus() { - if ((this.IsPrimaryStatusNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeProtocolIFType() { - if ((this.IsProtocolIFTypeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeProtocolType() { - if ((this.IsProtocolTypeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeRequestedState() { - if ((this.IsRequestedStateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeTimeOfLastStateChange() { - if ((this.IsTimeOfLastStateChangeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeTransitioningToState() { - if ((this.IsTransitioningToStateNull == false)) { - return true; - } - return false; - } - - [Browsable(true)] - public void CommitObject() { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(); - } - } - - [Browsable(true)] - public void CommitObject(System.Management.PutOptions putOptions) { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(putOptions); - } - } - - private void Initialize() { - AutoCommitProp = true; - isEmbedded = false; - } - - private static string ConstructPath(string keyCreationClassName, string keyName, string keySystemCreationClassName, string keySystemName) { - string strPath = "ROOT\\virtualization\\v2:Msvm_LANEndpoint"; - strPath = string.Concat(strPath, string.Concat(".CreationClassName=", string.Concat("\"", string.Concat(keyCreationClassName, "\"")))); - strPath = string.Concat(strPath, string.Concat(",Name=", string.Concat("\"", string.Concat(keyName, "\"")))); - strPath = string.Concat(strPath, string.Concat(",SystemCreationClassName=", string.Concat("\"", string.Concat(keySystemCreationClassName, "\"")))); - strPath = string.Concat(strPath, string.Concat(",SystemName=", string.Concat("\"", string.Concat(keySystemName, "\"")))); - return strPath; - } - - private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - Initialize(); - if ((path != null)) { - if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - } - PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - - // Different overloads of GetInstances() help in enumerating instances of the WMI class. - public static LANEndpointCollection GetInstances() { - return GetInstances(null, null, null); - } - - public static LANEndpointCollection GetInstances(string condition) { - return GetInstances(null, condition, null); - } - - public static LANEndpointCollection GetInstances(string[] selectedProperties) { - return GetInstances(null, null, selectedProperties); - } - - public static LANEndpointCollection GetInstances(string condition, string[] selectedProperties) { - return GetInstances(null, condition, selectedProperties); - } - - public static LANEndpointCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); - pathObj.ClassName = "Msvm_LANEndpoint"; - pathObj.NamespacePath = "root\\virtualization\\v2"; - System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); - if ((enumOptions == null)) { - enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - } - return new LANEndpointCollection(clsObject.GetInstances(enumOptions)); - } - - public static LANEndpointCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { - return GetInstances(mgmtScope, condition, null); - } - - public static LANEndpointCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { - return GetInstances(mgmtScope, null, selectedProperties); - } - - public static LANEndpointCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_LANEndpoint", condition, selectedProperties)); - System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - ObjectSearcher.Options = enumOptions; - return new LANEndpointCollection(ObjectSearcher.Get()); - } - - [Browsable(true)] - public static LANEndpoint CreateInstance() { - System.Management.ManagementScope mgmtScope = null; - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = CreatedWmiNamespace; - } - else { - mgmtScope = statMgmtScope; - } - System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); - System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); - return new LANEndpoint(tmpMgmtClass.CreateInstance()); - } - - [Browsable(true)] - public void Delete() { - PrivateLateBoundObject.Delete(); - } - - public uint RequestStateChange(ushort RequestedState, System.DateTime TimeoutPeriod, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("RequestStateChange"); - inParams["RequestedState"] = ((ushort)(RequestedState)); - inParams["TimeoutPeriod"] = ToDmtfDateTime(((System.DateTime)(TimeoutPeriod))); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RequestStateChange", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null) && outParams.Properties["Job"].Value != null) { - Job = new System.Management.ManagementPath(outParams.Properties["Job"].Value.ToString()); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - return System.Convert.ToUInt32(0); - } - } - - // Enumerator implementation for enumerating instances of the class. - public class LANEndpointCollection : object, ICollection { - - private ManagementObjectCollection privColObj; - - public LANEndpointCollection(ManagementObjectCollection objCollection) { - privColObj = objCollection; - } - - public virtual int Count { - get { - return privColObj.Count; - } - } - - public virtual bool IsSynchronized { - get { - return privColObj.IsSynchronized; - } - } - - public virtual object SyncRoot { - get { - return this; - } - } - - public virtual void CopyTo(System.Array array, int index) { - privColObj.CopyTo(array, index); - int nCtr; - for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { - array.SetValue(new LANEndpoint(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); - } - } - - public virtual System.Collections.IEnumerator GetEnumerator() { - return new LANEndpointEnumerator(privColObj.GetEnumerator()); - } - - public class LANEndpointEnumerator : object, System.Collections.IEnumerator { - - private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; - - public LANEndpointEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { - privObjEnum = objEnum; - } - - public virtual object Current { - get { - return new LANEndpoint(((System.Management.ManagementObject)(privObjEnum.Current))); - } - } - - public virtual bool MoveNext() { - return privObjEnum.MoveNext(); - } - - public virtual void Reset() { - privObjEnum.Reset(); - } - } - } - - // TypeConverter to handle null values for ValueType properties - public class WMIValueTypeConverter : TypeConverter { - - private TypeConverter baseConverter; - - private System.Type baseType; - - public WMIValueTypeConverter(System.Type inBaseType) { - baseConverter = TypeDescriptor.GetConverter(inBaseType); - baseType = inBaseType; - } - - public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { - return baseConverter.CanConvertFrom(context, srcType); - } - - public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { - return baseConverter.CanConvertTo(context, destinationType); - } - - public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { - return baseConverter.ConvertFrom(context, culture, value); - } - - public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { - return baseConverter.CreateInstance(context, dictionary); - } - - public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetCreateInstanceSupported(context); - } - - public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { - return baseConverter.GetProperties(context, value, attributeVar); - } - - public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetPropertiesSupported(context); - } - - public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValues(context); - } - - public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesExclusive(context); - } - - public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesSupported(context); - } - - public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { - if ((baseType.BaseType == typeof(System.Enum))) { - if ((value.GetType() == destinationType)) { - return value; - } - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return "NULL_ENUM_VALUE" ; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((baseType == typeof(bool)) - && (baseType.BaseType == typeof(System.ValueType)))) { - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((context != null) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - } - - // Embedded class to represent WMI system Properties. - [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] - public class ManagementSystemProperties { - - private System.Management.ManagementBaseObject PrivateLateBoundObject; - - public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { - PrivateLateBoundObject = ManagedObject; - } - - [Browsable(true)] - public int GENUS { - get { - return ((int)(PrivateLateBoundObject["__GENUS"])); - } - } - - [Browsable(true)] - public string CLASS { - get { - return ((string)(PrivateLateBoundObject["__CLASS"])); - } - } - - [Browsable(true)] - public string SUPERCLASS { - get { - return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); - } - } - - [Browsable(true)] - public string DYNASTY { - get { - return ((string)(PrivateLateBoundObject["__DYNASTY"])); - } - } - - [Browsable(true)] - public string RELPATH { - get { - return ((string)(PrivateLateBoundObject["__RELPATH"])); - } - } - - [Browsable(true)] - public int PROPERTY_COUNT { - get { - return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); - } - } - - [Browsable(true)] - public string[] DERIVATION { - get { - return ((string[])(PrivateLateBoundObject["__DERIVATION"])); - } - } - - [Browsable(true)] - public string SERVER { - get { - return ((string)(PrivateLateBoundObject["__SERVER"])); - } - } - - [Browsable(true)] - public string NAMESPACE { - get { - return ((string)(PrivateLateBoundObject["__NAMESPACE"])); - } - } - - [Browsable(true)] - public string PATH { - get { - return ((string)(PrivateLateBoundObject["__PATH"])); - } - } - } - } -} +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2 { + using System; + using System.ComponentModel; + using System.Management; + using System.Collections; + using System.Globalization; + using System.ComponentModel.Design.Serialization; + using System.Reflection; + + + // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. + // Functions IsNull() are used to check if a property is NULL. + // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. + // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. + // Datetime conversion functions ToDateTime and ToDmtfDateTime are added to the class to convert DMTF datetime to System.DateTime and vice-versa. + // An Early Bound class generated for the WMI class.Msvm_LANEndpoint + public class LANEndpoint : System.ComponentModel.Component { + + // Private property to hold the WMI namespace in which the class resides. + private static string CreatedWmiNamespace = "ROOT\\virtualization\\v2"; + + // Private property to hold the name of WMI class which created this class. + public static string CreatedClassName = "Msvm_LANEndpoint"; + + // Private member variable to hold the ManagementScope which is used by the various methods. + private static System.Management.ManagementScope statMgmtScope = null; + + private ManagementSystemProperties PrivateSystemProperties; + + // Underlying lateBound WMI object. + private System.Management.ManagementObject PrivateLateBoundObject; + + // Member variable to store the 'automatic commit' behavior for the class. + private bool AutoCommitProp; + + // Private variable to hold the embedded property representing the instance. + private System.Management.ManagementBaseObject embeddedObj; + + // The current WMI object used + private System.Management.ManagementBaseObject curObj; + + // Flag to indicate if the instance is an embedded object. + private bool isEmbedded; + + // Below are different overloads of constructors to initialize an instance of the class with a WMI object. + public LANEndpoint() { + this.InitializeObject(null, null, null); + } + + public LANEndpoint(string keyCreationClassName, string keyName, string keySystemCreationClassName, string keySystemName) { + this.InitializeObject(null, new System.Management.ManagementPath(LANEndpoint.ConstructPath(keyCreationClassName, keyName, keySystemCreationClassName, keySystemName)), null); + } + + public LANEndpoint(System.Management.ManagementScope mgmtScope, string keyCreationClassName, string keyName, string keySystemCreationClassName, string keySystemName) { + this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(LANEndpoint.ConstructPath(keyCreationClassName, keyName, keySystemCreationClassName, keySystemName)), null); + } + + public LANEndpoint(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(null, path, getOptions); + } + + public LANEndpoint(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { + this.InitializeObject(mgmtScope, path, null); + } + + public LANEndpoint(System.Management.ManagementPath path) { + this.InitializeObject(null, path, null); + } + + public LANEndpoint(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(mgmtScope, path, getOptions); + } + + public LANEndpoint(System.Management.ManagementObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + PrivateLateBoundObject = theObject; + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + public LANEndpoint(System.Management.ManagementBaseObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + embeddedObj = theObject; + PrivateSystemProperties = new ManagementSystemProperties(theObject); + curObj = embeddedObj; + isEmbedded = true; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + // Property returns the namespace of the WMI class. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OriginatingNamespace { + get { + return "ROOT\\virtualization\\v2"; + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ManagementClassName { + get { + string strRet = CreatedClassName; + if ((curObj != null)) { + if ((curObj.ClassPath != null)) { + strRet = ((string)(curObj["__CLASS"])); + if (((strRet == null) + || (strRet == string.Empty))) { + strRet = CreatedClassName; + } + } + } + return strRet; + } + } + + // Property pointing to an embedded object to get System properties of the WMI object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ManagementSystemProperties SystemProperties { + get { + return PrivateSystemProperties; + } + } + + // Property returning the underlying lateBound object. + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementBaseObject LateBoundObject { + get { + return curObj; + } + } + + // ManagementScope of the object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementScope Scope { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Scope; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Scope = value; + } + } + } + + // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool AutoCommit { + get { + return AutoCommitProp; + } + set { + AutoCommitProp = value; + } + } + + // The ManagementPath of the underlying WMI object. + [Browsable(true)] + public System.Management.ManagementPath Path { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Path; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + if ((CheckIfProperClass(null, value, null) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + PrivateLateBoundObject.Path = value; + } + } + } + + // Public static scope property which is used by the various methods. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public static System.Management.ManagementScope StaticScope { + get { + return statMgmtScope; + } + set { + statMgmtScope = value; + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] AliasAddresses { + get { + return ((string[])(curObj["AliasAddresses"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ushort[] AvailableRequestedStates { + get { + return ((ushort[])(curObj["AvailableRequestedStates"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Caption { + get { + return ((string)(curObj["Caption"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsCommunicationStatusNull { + get { + if ((curObj["CommunicationStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort CommunicationStatus { + get { + if ((curObj["CommunicationStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["CommunicationStatus"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsConnectedNull { + get { + if ((curObj["Connected"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("This property is set to TRUE if the LAN endpoint is connected to a switch port.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool Connected { + get { + if ((curObj["Connected"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["Connected"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string CreationClassName { + get { + return ((string)(curObj["CreationClassName"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Description { + get { + return ((string)(curObj["Description"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsDetailedStatusNull { + get { + if ((curObj["DetailedStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort DetailedStatus { + get { + if ((curObj["DetailedStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["DetailedStatus"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ElementName { + get { + return ((string)(curObj["ElementName"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsEnabledDefaultNull { + get { + if ((curObj["EnabledDefault"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort EnabledDefault { + get { + if ((curObj["EnabledDefault"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["EnabledDefault"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsEnabledStateNull { + get { + if ((curObj["EnabledState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort EnabledState { + get { + if ((curObj["EnabledState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["EnabledState"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] GroupAddresses { + get { + return ((string[])(curObj["GroupAddresses"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsHealthStateNull { + get { + if ((curObj["HealthState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort HealthState { + get { + if ((curObj["HealthState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["HealthState"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsInstallDateNull { + get { + if ((curObj["InstallDate"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime InstallDate { + get { + if ((curObj["InstallDate"] != null)) { + return ToDateTime(((string)(curObj["InstallDate"]))); + } + else { + return System.DateTime.MinValue; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string InstanceID { + get { + return ((string)(curObj["InstanceID"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string LANID { + get { + return ((string)(curObj["LANID"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsLANTypeNull { + get { + if ((curObj["LANType"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort LANType { + get { + if ((curObj["LANType"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["LANType"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string MACAddress { + get { + return ((string)(curObj["MACAddress"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsMaxDataSizeNull { + get { + if ((curObj["MaxDataSize"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint MaxDataSize { + get { + if ((curObj["MaxDataSize"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["MaxDataSize"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Name { + get { + return ((string)(curObj["Name"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string NameFormat { + get { + return ((string)(curObj["NameFormat"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsOperatingStatusNull { + get { + if ((curObj["OperatingStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort OperatingStatus { + get { + if ((curObj["OperatingStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["OperatingStatus"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ushort[] OperationalStatus { + get { + return ((ushort[])(curObj["OperationalStatus"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherEnabledState { + get { + return ((string)(curObj["OtherEnabledState"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherLANType { + get { + return ((string)(curObj["OtherLANType"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherTypeDescription { + get { + return ((string)(curObj["OtherTypeDescription"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPrimaryStatusNull { + get { + if ((curObj["PrimaryStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort PrimaryStatus { + get { + if ((curObj["PrimaryStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["PrimaryStatus"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsProtocolIFTypeNull { + get { + if ((curObj["ProtocolIFType"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort ProtocolIFType { + get { + if ((curObj["ProtocolIFType"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["ProtocolIFType"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsProtocolTypeNull { + get { + if ((curObj["ProtocolType"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort ProtocolType { + get { + if ((curObj["ProtocolType"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["ProtocolType"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsRequestedStateNull { + get { + if ((curObj["RequestedState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort RequestedState { + get { + if ((curObj["RequestedState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["RequestedState"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Status { + get { + return ((string)(curObj["Status"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] StatusDescriptions { + get { + return ((string[])(curObj["StatusDescriptions"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string SystemCreationClassName { + get { + return ((string)(curObj["SystemCreationClassName"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string SystemName { + get { + return ((string)(curObj["SystemName"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsTimeOfLastStateChangeNull { + get { + if ((curObj["TimeOfLastStateChange"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime TimeOfLastStateChange { + get { + if ((curObj["TimeOfLastStateChange"] != null)) { + return ToDateTime(((string)(curObj["TimeOfLastStateChange"]))); + } + else { + return System.DateTime.MinValue; + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsTransitioningToStateNull { + get { + if ((curObj["TransitioningToState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort TransitioningToState { + get { + if ((curObj["TransitioningToState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["TransitioningToState"])); + } + } + + private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { + if (((path != null) + && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); + } + } + + private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { + if (((theObj != null) + && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); + if ((parentClasses != null)) { + int count = 0; + for (count = 0; (count < parentClasses.Length); count = (count + 1)) { + if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { + return true; + } + } + } + } + return false; + } + + private bool ShouldSerializeCommunicationStatus() { + if ((this.IsCommunicationStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeConnected() { + if ((this.IsConnectedNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeDetailedStatus() { + if ((this.IsDetailedStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeEnabledDefault() { + if ((this.IsEnabledDefaultNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeEnabledState() { + if ((this.IsEnabledStateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeHealthState() { + if ((this.IsHealthStateNull == false)) { + return true; + } + return false; + } + + // Converts a given datetime in DMTF format to System.DateTime object. + static System.DateTime ToDateTime(string dmtfDate) { + System.DateTime initializer = System.DateTime.MinValue; + int year = initializer.Year; + int month = initializer.Month; + int day = initializer.Day; + int hour = initializer.Hour; + int minute = initializer.Minute; + int second = initializer.Second; + long ticks = 0; + string dmtf = dmtfDate; + System.DateTime datetime = System.DateTime.MinValue; + string tempString = string.Empty; + if ((dmtf == null)) { + throw new System.ArgumentOutOfRangeException(); + } + if ((dmtf.Length == 0)) { + throw new System.ArgumentOutOfRangeException(); + } + if ((dmtf.Length != 25)) { + throw new System.ArgumentOutOfRangeException(); + } + try { + tempString = dmtf.Substring(0, 4); + if (("****" != tempString)) { + year = int.Parse(tempString); + } + tempString = dmtf.Substring(4, 2); + if (("**" != tempString)) { + month = int.Parse(tempString); + } + tempString = dmtf.Substring(6, 2); + if (("**" != tempString)) { + day = int.Parse(tempString); + } + tempString = dmtf.Substring(8, 2); + if (("**" != tempString)) { + hour = int.Parse(tempString); + } + tempString = dmtf.Substring(10, 2); + if (("**" != tempString)) { + minute = int.Parse(tempString); + } + tempString = dmtf.Substring(12, 2); + if (("**" != tempString)) { + second = int.Parse(tempString); + } + tempString = dmtf.Substring(15, 6); + if (("******" != tempString)) { + ticks = (long.Parse(tempString) * ((long)((System.TimeSpan.TicksPerMillisecond / 1000)))); + } + if (((((((((year < 0) + || (month < 0)) + || (day < 0)) + || (hour < 0)) + || (minute < 0)) + || (minute < 0)) + || (second < 0)) + || (ticks < 0))) { + throw new System.ArgumentOutOfRangeException(); + } + } + catch (System.Exception e) { + throw new System.ArgumentOutOfRangeException(null, e.Message); + } + datetime = new System.DateTime(year, month, day, hour, minute, second, 0); + datetime = datetime.AddTicks(ticks); + System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(datetime); + int UTCOffset = 0; + int OffsetToBeAdjusted = 0; + long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); + tempString = dmtf.Substring(22, 3); + if ((tempString != "******")) { + tempString = dmtf.Substring(21, 4); + try { + UTCOffset = int.Parse(tempString); + } + catch (System.Exception e) { + throw new System.ArgumentOutOfRangeException(null, e.Message); + } + OffsetToBeAdjusted = ((int)((OffsetMins - UTCOffset))); + datetime = datetime.AddMinutes(((double)(OffsetToBeAdjusted))); + } + return datetime; + } + + // Converts a given System.DateTime object to DMTF datetime format. + static string ToDmtfDateTime(System.DateTime date) { + string utcString = string.Empty; + System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(date); + long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); + if ((System.Math.Abs(OffsetMins) > 999)) { + date = date.ToUniversalTime(); + utcString = "+000"; + } + else { + if ((tickOffset.Ticks >= 0)) { + utcString = string.Concat("+", ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))).ToString().PadLeft(3, '0')); + } + else { + string strTemp = ((long)(OffsetMins)).ToString(); + utcString = string.Concat("-", strTemp.Substring(1, (strTemp.Length - 1)).PadLeft(3, '0')); + } + } + string dmtfDateTime = ((int)(date.Year)).ToString().PadLeft(4, '0'); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Month)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Day)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Hour)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Minute)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Second)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, "."); + System.DateTime dtTemp = new System.DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, 0); + long microsec = ((long)((((date.Ticks - dtTemp.Ticks) + * 1000) + / System.TimeSpan.TicksPerMillisecond))); + string strMicrosec = ((long)(microsec)).ToString(); + if ((strMicrosec.Length > 6)) { + strMicrosec = strMicrosec.Substring(0, 6); + } + dmtfDateTime = string.Concat(dmtfDateTime, strMicrosec.PadLeft(6, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, utcString); + return dmtfDateTime; + } + + private bool ShouldSerializeInstallDate() { + if ((this.IsInstallDateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeLANType() { + if ((this.IsLANTypeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeMaxDataSize() { + if ((this.IsMaxDataSizeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeOperatingStatus() { + if ((this.IsOperatingStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePrimaryStatus() { + if ((this.IsPrimaryStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeProtocolIFType() { + if ((this.IsProtocolIFTypeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeProtocolType() { + if ((this.IsProtocolTypeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeRequestedState() { + if ((this.IsRequestedStateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeTimeOfLastStateChange() { + if ((this.IsTimeOfLastStateChangeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeTransitioningToState() { + if ((this.IsTransitioningToStateNull == false)) { + return true; + } + return false; + } + + [Browsable(true)] + public void CommitObject() { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(); + } + } + + [Browsable(true)] + public void CommitObject(System.Management.PutOptions putOptions) { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(putOptions); + } + } + + private void Initialize() { + AutoCommitProp = true; + isEmbedded = false; + } + + private static string ConstructPath(string keyCreationClassName, string keyName, string keySystemCreationClassName, string keySystemName) { + string strPath = "ROOT\\virtualization\\v2:Msvm_LANEndpoint"; + strPath = string.Concat(strPath, string.Concat(".CreationClassName=", string.Concat("\"", string.Concat(keyCreationClassName, "\"")))); + strPath = string.Concat(strPath, string.Concat(",Name=", string.Concat("\"", string.Concat(keyName, "\"")))); + strPath = string.Concat(strPath, string.Concat(",SystemCreationClassName=", string.Concat("\"", string.Concat(keySystemCreationClassName, "\"")))); + strPath = string.Concat(strPath, string.Concat(",SystemName=", string.Concat("\"", string.Concat(keySystemName, "\"")))); + return strPath; + } + + private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + Initialize(); + if ((path != null)) { + if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + } + PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + + // Different overloads of GetInstances() help in enumerating instances of the WMI class. + public static LANEndpointCollection GetInstances() { + return GetInstances(null, null, null); + } + + public static LANEndpointCollection GetInstances(string condition) { + return GetInstances(null, condition, null); + } + + public static LANEndpointCollection GetInstances(string[] selectedProperties) { + return GetInstances(null, null, selectedProperties); + } + + public static LANEndpointCollection GetInstances(string condition, string[] selectedProperties) { + return GetInstances(null, condition, selectedProperties); + } + + public static LANEndpointCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); + pathObj.ClassName = "Msvm_LANEndpoint"; + pathObj.NamespacePath = "root\\virtualization\\v2"; + System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); + if ((enumOptions == null)) { + enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + } + return new LANEndpointCollection(clsObject.GetInstances(enumOptions)); + } + + public static LANEndpointCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { + return GetInstances(mgmtScope, condition, null); + } + + public static LANEndpointCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { + return GetInstances(mgmtScope, null, selectedProperties); + } + + public static LANEndpointCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_LANEndpoint", condition, selectedProperties)); + System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + ObjectSearcher.Options = enumOptions; + return new LANEndpointCollection(ObjectSearcher.Get()); + } + + [Browsable(true)] + public static LANEndpoint CreateInstance() { + System.Management.ManagementScope mgmtScope = null; + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = CreatedWmiNamespace; + } + else { + mgmtScope = statMgmtScope; + } + System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); + System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); + return new LANEndpoint(tmpMgmtClass.CreateInstance()); + } + + [Browsable(true)] + public void Delete() { + PrivateLateBoundObject.Delete(); + } + + public uint RequestStateChange(ushort RequestedState, System.DateTime TimeoutPeriod, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("RequestStateChange"); + inParams["RequestedState"] = ((ushort)(RequestedState)); + inParams["TimeoutPeriod"] = ToDmtfDateTime(((System.DateTime)(TimeoutPeriod))); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RequestStateChange", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null) && outParams.Properties["Job"].Value != null) { + Job = new System.Management.ManagementPath(outParams.Properties["Job"].Value.ToString()); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + return System.Convert.ToUInt32(0); + } + } + + // Enumerator implementation for enumerating instances of the class. + public class LANEndpointCollection : object, ICollection { + + private ManagementObjectCollection privColObj; + + public LANEndpointCollection(ManagementObjectCollection objCollection) { + privColObj = objCollection; + } + + public virtual int Count { + get { + return privColObj.Count; + } + } + + public virtual bool IsSynchronized { + get { + return privColObj.IsSynchronized; + } + } + + public virtual object SyncRoot { + get { + return this; + } + } + + public virtual void CopyTo(System.Array array, int index) { + privColObj.CopyTo(array, index); + int nCtr; + for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { + array.SetValue(new LANEndpoint(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); + } + } + + public virtual System.Collections.IEnumerator GetEnumerator() { + return new LANEndpointEnumerator(privColObj.GetEnumerator()); + } + + public class LANEndpointEnumerator : object, System.Collections.IEnumerator { + + private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; + + public LANEndpointEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { + privObjEnum = objEnum; + } + + public virtual object Current { + get { + return new LANEndpoint(((System.Management.ManagementObject)(privObjEnum.Current))); + } + } + + public virtual bool MoveNext() { + return privObjEnum.MoveNext(); + } + + public virtual void Reset() { + privObjEnum.Reset(); + } + } + } + + // TypeConverter to handle null values for ValueType properties + public class WMIValueTypeConverter : TypeConverter { + + private TypeConverter baseConverter; + + private System.Type baseType; + + public WMIValueTypeConverter(System.Type inBaseType) { + baseConverter = TypeDescriptor.GetConverter(inBaseType); + baseType = inBaseType; + } + + public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { + return baseConverter.CanConvertFrom(context, srcType); + } + + public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { + return baseConverter.CanConvertTo(context, destinationType); + } + + public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { + return baseConverter.ConvertFrom(context, culture, value); + } + + public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { + return baseConverter.CreateInstance(context, dictionary); + } + + public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetCreateInstanceSupported(context); + } + + public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { + return baseConverter.GetProperties(context, value, attributeVar); + } + + public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetPropertiesSupported(context); + } + + public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValues(context); + } + + public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesExclusive(context); + } + + public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesSupported(context); + } + + public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { + if ((baseType.BaseType == typeof(System.Enum))) { + if ((value.GetType() == destinationType)) { + return value; + } + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return "NULL_ENUM_VALUE" ; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((baseType == typeof(bool)) + && (baseType.BaseType == typeof(System.ValueType)))) { + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((context != null) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + } + + // Embedded class to represent WMI system Properties. + [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] + public class ManagementSystemProperties { + + private System.Management.ManagementBaseObject PrivateLateBoundObject; + + public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { + PrivateLateBoundObject = ManagedObject; + } + + [Browsable(true)] + public int GENUS { + get { + return ((int)(PrivateLateBoundObject["__GENUS"])); + } + } + + [Browsable(true)] + public string CLASS { + get { + return ((string)(PrivateLateBoundObject["__CLASS"])); + } + } + + [Browsable(true)] + public string SUPERCLASS { + get { + return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); + } + } + + [Browsable(true)] + public string DYNASTY { + get { + return ((string)(PrivateLateBoundObject["__DYNASTY"])); + } + } + + [Browsable(true)] + public string RELPATH { + get { + return ((string)(PrivateLateBoundObject["__RELPATH"])); + } + } + + [Browsable(true)] + public int PROPERTY_COUNT { + get { + return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); + } + } + + [Browsable(true)] + public string[] DERIVATION { + get { + return ((string[])(PrivateLateBoundObject["__DERIVATION"])); + } + } + + [Browsable(true)] + public string SERVER { + get { + return ((string)(PrivateLateBoundObject["__SERVER"])); + } + } + + [Browsable(true)] + public string NAMESPACE { + get { + return ((string)(PrivateLateBoundObject["__NAMESPACE"])); + } + } + + [Browsable(true)] + public string PATH { + get { + return ((string)(PrivateLateBoundObject["__PATH"])); + } + } + } + } +} diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_MemorySettingData.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_MemorySettingData.cs index f57655ff8e8..d6cda05931d 100644 --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_MemorySettingData.cs +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_MemorySettingData.cs @@ -1,1163 +1,1163 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2 { - using System; - using System.ComponentModel; - using System.Management; - using System.Collections; - using System.Globalization; - using System.ComponentModel.Design.Serialization; - using System.Reflection; - - - // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. - // Functions IsNull() are used to check if a property is NULL. - // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. - // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. - // An Early Bound class generated for the WMI class.Msvm_MemorySettingData - public class MemorySettingData : System.ComponentModel.Component { - - // Private property to hold the WMI namespace in which the class resides. - private static string CreatedWmiNamespace = "ROOT\\virtualization\\v2"; - - // Private property to hold the name of WMI class which created this class. - public static string CreatedClassName = "Msvm_MemorySettingData"; - - // Private member variable to hold the ManagementScope which is used by the various methods. - private static System.Management.ManagementScope statMgmtScope = null; - - private ManagementSystemProperties PrivateSystemProperties; - - // Underlying lateBound WMI object. - private System.Management.ManagementObject PrivateLateBoundObject; - - // Member variable to store the 'automatic commit' behavior for the class. - private bool AutoCommitProp; - - // Private variable to hold the embedded property representing the instance. - private System.Management.ManagementBaseObject embeddedObj; - - // The current WMI object used - private System.Management.ManagementBaseObject curObj; - - // Flag to indicate if the instance is an embedded object. - private bool isEmbedded; - - // Below are different overloads of constructors to initialize an instance of the class with a WMI object. - public MemorySettingData() { - this.InitializeObject(null, null, null); - } - - public MemorySettingData(string keyInstanceID) { - this.InitializeObject(null, new System.Management.ManagementPath(MemorySettingData.ConstructPath(keyInstanceID)), null); - } - - public MemorySettingData(System.Management.ManagementScope mgmtScope, string keyInstanceID) { - this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(MemorySettingData.ConstructPath(keyInstanceID)), null); - } - - public MemorySettingData(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(null, path, getOptions); - } - - public MemorySettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { - this.InitializeObject(mgmtScope, path, null); - } - - public MemorySettingData(System.Management.ManagementPath path) { - this.InitializeObject(null, path, null); - } - - public MemorySettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(mgmtScope, path, getOptions); - } - - public MemorySettingData(System.Management.ManagementObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - PrivateLateBoundObject = theObject; - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - public MemorySettingData(System.Management.ManagementBaseObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - embeddedObj = theObject; - PrivateSystemProperties = new ManagementSystemProperties(theObject); - curObj = embeddedObj; - isEmbedded = true; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - // Property returns the namespace of the WMI class. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OriginatingNamespace { - get { - return "ROOT\\virtualization\\v2"; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ManagementClassName { - get { - string strRet = CreatedClassName; - if ((curObj != null)) { - if ((curObj.ClassPath != null)) { - strRet = ((string)(curObj["__CLASS"])); - if (((strRet == null) - || (strRet == string.Empty))) { - strRet = CreatedClassName; - } - } - } - return strRet; - } - } - - // Property pointing to an embedded object to get System properties of the WMI object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ManagementSystemProperties SystemProperties { - get { - return PrivateSystemProperties; - } - } - - // Property returning the underlying lateBound object. - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementBaseObject LateBoundObject { - get { - return curObj; - } - } - - // ManagementScope of the object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementScope Scope { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Scope; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Scope = value; - } - } - } - - // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool AutoCommit { - get { - return AutoCommitProp; - } - set { - AutoCommitProp = value; - } - } - - // The ManagementPath of the underlying WMI object. - [Browsable(true)] - public System.Management.ManagementPath Path { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Path; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - if ((CheckIfProperClass(null, value, null) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - PrivateLateBoundObject.Path = value; - } - } - } - - // Public static scope property which is used by the various methods. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public static System.Management.ManagementScope StaticScope { - get { - return statMgmtScope; - } - set { - statMgmtScope = value; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Address { - get { - return ((string)(curObj["Address"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string AddressOnParent { - get { - return ((string)(curObj["AddressOnParent"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string AllocationUnits { - get { - return ((string)(curObj["AllocationUnits"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsAutomaticAllocationNull { - get { - if ((curObj["AutomaticAllocation"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool AutomaticAllocation { - get { - if ((curObj["AutomaticAllocation"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["AutomaticAllocation"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsAutomaticDeallocationNull { - get { - if ((curObj["AutomaticDeallocation"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool AutomaticDeallocation { - get { - if ((curObj["AutomaticDeallocation"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["AutomaticDeallocation"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Caption { - get { - return ((string)(curObj["Caption"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] Connection { - get { - return ((string[])(curObj["Connection"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsConsumerVisibilityNull { - get { - if ((curObj["ConsumerVisibility"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort ConsumerVisibility { - get { - if ((curObj["ConsumerVisibility"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["ConsumerVisibility"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Description { - get { - return ((string)(curObj["Description"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsDynamicMemoryEnabledNull { - get { - if ((curObj["DynamicMemoryEnabled"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("Indicates if dynamic memory is enabled.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool DynamicMemoryEnabled { - get { - if ((curObj["DynamicMemoryEnabled"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["DynamicMemoryEnabled"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ElementName { - get { - return ((string)(curObj["ElementName"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] HostResource { - get { - return ((string[])(curObj["HostResource"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string InstanceID { - get { - return ((string)(curObj["InstanceID"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsIsVirtualizedNull { - get { - if ((curObj["IsVirtualized"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description(@"Indicates whether this device is virtualized or passed through, possibly using partitioning. When set to False, the underlying or host resource is utilized. At least one item shall be present in the DeviceID property. When set to True, the resource is virtualized and may not map directly to an underlying/host resource. Some implementations may support specific assignment for virtualized resources, in which case the host resource(s) are exposed using the DeviceID property. This property is always set to True.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool IsVirtualized { - get { - if ((curObj["IsVirtualized"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["IsVirtualized"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsLimitNull { - get { - if ((curObj["Limit"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong Limit { - get { - if ((curObj["Limit"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["Limit"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsMappingBehaviorNull { - get { - if ((curObj["MappingBehavior"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort MappingBehavior { - get { - if ((curObj["MappingBehavior"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["MappingBehavior"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsMaxMemoryBlocksPerNumaNodeNull { - get { - if ((curObj["MaxMemoryBlocksPerNumaNode"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The maximum amount of memory that can be observed within the VM as belonging to a" + - " single NUMA node.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong MaxMemoryBlocksPerNumaNode { - get { - if ((curObj["MaxMemoryBlocksPerNumaNode"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["MaxMemoryBlocksPerNumaNode"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OtherResourceType { - get { - return ((string)(curObj["OtherResourceType"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Parent { - get { - return ((string)(curObj["Parent"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string PoolID { - get { - return ((string)(curObj["PoolID"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsReservationNull { - get { - if ((curObj["Reservation"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong Reservation { - get { - if ((curObj["Reservation"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["Reservation"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ResourceSubType { - get { - return ((string)(curObj["ResourceSubType"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsResourceTypeNull { - get { - if ((curObj["ResourceType"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort ResourceType { - get { - if ((curObj["ResourceType"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["ResourceType"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsSwapFilesInUseNull { - get { - if ((curObj["SwapFilesInUse"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("Indicates if smart paging is active.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool SwapFilesInUse { - get { - if ((curObj["SwapFilesInUse"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["SwapFilesInUse"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsTargetMemoryBufferNull { - get { - if ((curObj["TargetMemoryBuffer"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public uint TargetMemoryBuffer { - get { - if ((curObj["TargetMemoryBuffer"] == null)) { - return System.Convert.ToUInt32(0); - } - return ((uint)(curObj["TargetMemoryBuffer"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsVirtualQuantityNull { - get { - if ((curObj["VirtualQuantity"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong VirtualQuantity { - get { - if ((curObj["VirtualQuantity"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["VirtualQuantity"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string VirtualQuantityUnits { - get { - return ((string)(curObj["VirtualQuantityUnits"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsWeightNull { - get { - if ((curObj["Weight"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public uint Weight { - get { - if ((curObj["Weight"] == null)) { - return System.Convert.ToUInt32(0); - } - return ((uint)(curObj["Weight"])); - } - } - - private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { - if (((path != null) - && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); - } - } - - private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { - if (((theObj != null) - && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); - if ((parentClasses != null)) { - int count = 0; - for (count = 0; (count < parentClasses.Length); count = (count + 1)) { - if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { - return true; - } - } - } - } - return false; - } - - private bool ShouldSerializeAutomaticAllocation() { - if ((this.IsAutomaticAllocationNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeAutomaticDeallocation() { - if ((this.IsAutomaticDeallocationNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeConsumerVisibility() { - if ((this.IsConsumerVisibilityNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeDynamicMemoryEnabled() { - if ((this.IsDynamicMemoryEnabledNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeIsVirtualized() { - if ((this.IsIsVirtualizedNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeLimit() { - if ((this.IsLimitNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeMappingBehavior() { - if ((this.IsMappingBehaviorNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeMaxMemoryBlocksPerNumaNode() { - if ((this.IsMaxMemoryBlocksPerNumaNodeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeReservation() { - if ((this.IsReservationNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeResourceType() { - if ((this.IsResourceTypeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeSwapFilesInUse() { - if ((this.IsSwapFilesInUseNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeTargetMemoryBuffer() { - if ((this.IsTargetMemoryBufferNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeVirtualQuantity() { - if ((this.IsVirtualQuantityNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeWeight() { - if ((this.IsWeightNull == false)) { - return true; - } - return false; - } - - [Browsable(true)] - public void CommitObject() { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(); - } - } - - [Browsable(true)] - public void CommitObject(System.Management.PutOptions putOptions) { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(putOptions); - } - } - - private void Initialize() { - AutoCommitProp = true; - isEmbedded = false; - } - - private static string ConstructPath(string keyInstanceID) { - string strPath = "ROOT\\virtualization\\v2:Msvm_MemorySettingData"; - strPath = string.Concat(strPath, string.Concat(".InstanceID=", string.Concat("\"", string.Concat(keyInstanceID, "\"")))); - return strPath; - } - - private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - Initialize(); - if ((path != null)) { - if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - } - PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - - // Different overloads of GetInstances() help in enumerating instances of the WMI class. - public static MemorySettingDataCollection GetInstances() { - return GetInstances(null, null, null); - } - - public static MemorySettingDataCollection GetInstances(string condition) { - return GetInstances(null, condition, null); - } - - public static MemorySettingDataCollection GetInstances(string[] selectedProperties) { - return GetInstances(null, null, selectedProperties); - } - - public static MemorySettingDataCollection GetInstances(string condition, string[] selectedProperties) { - return GetInstances(null, condition, selectedProperties); - } - - public static MemorySettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); - pathObj.ClassName = "Msvm_MemorySettingData"; - pathObj.NamespacePath = "root\\virtualization\\v2"; - System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); - if ((enumOptions == null)) { - enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - } - return new MemorySettingDataCollection(clsObject.GetInstances(enumOptions)); - } - - public static MemorySettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { - return GetInstances(mgmtScope, condition, null); - } - - public static MemorySettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { - return GetInstances(mgmtScope, null, selectedProperties); - } - - public static MemorySettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_MemorySettingData", condition, selectedProperties)); - System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - ObjectSearcher.Options = enumOptions; - return new MemorySettingDataCollection(ObjectSearcher.Get()); - } - - [Browsable(true)] - public static MemorySettingData CreateInstance() { - System.Management.ManagementScope mgmtScope = null; - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = CreatedWmiNamespace; - } - else { - mgmtScope = statMgmtScope; - } - System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); - System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); - return new MemorySettingData(tmpMgmtClass.CreateInstance()); - } - - [Browsable(true)] - public void Delete() { - PrivateLateBoundObject.Delete(); - } - - // Enumerator implementation for enumerating instances of the class. - public class MemorySettingDataCollection : object, ICollection { - - private ManagementObjectCollection privColObj; - - public MemorySettingDataCollection(ManagementObjectCollection objCollection) { - privColObj = objCollection; - } - - public virtual int Count { - get { - return privColObj.Count; - } - } - - public virtual bool IsSynchronized { - get { - return privColObj.IsSynchronized; - } - } - - public virtual object SyncRoot { - get { - return this; - } - } - - public virtual void CopyTo(System.Array array, int index) { - privColObj.CopyTo(array, index); - int nCtr; - for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { - array.SetValue(new MemorySettingData(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); - } - } - - public virtual System.Collections.IEnumerator GetEnumerator() { - return new MemorySettingDataEnumerator(privColObj.GetEnumerator()); - } - - public class MemorySettingDataEnumerator : object, System.Collections.IEnumerator { - - private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; - - public MemorySettingDataEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { - privObjEnum = objEnum; - } - - public virtual object Current { - get { - return new MemorySettingData(((System.Management.ManagementObject)(privObjEnum.Current))); - } - } - - public virtual bool MoveNext() { - return privObjEnum.MoveNext(); - } - - public virtual void Reset() { - privObjEnum.Reset(); - } - } - } - - // TypeConverter to handle null values for ValueType properties - public class WMIValueTypeConverter : TypeConverter { - - private TypeConverter baseConverter; - - private System.Type baseType; - - public WMIValueTypeConverter(System.Type inBaseType) { - baseConverter = TypeDescriptor.GetConverter(inBaseType); - baseType = inBaseType; - } - - public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { - return baseConverter.CanConvertFrom(context, srcType); - } - - public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { - return baseConverter.CanConvertTo(context, destinationType); - } - - public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { - return baseConverter.ConvertFrom(context, culture, value); - } - - public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { - return baseConverter.CreateInstance(context, dictionary); - } - - public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetCreateInstanceSupported(context); - } - - public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { - return baseConverter.GetProperties(context, value, attributeVar); - } - - public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetPropertiesSupported(context); - } - - public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValues(context); - } - - public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesExclusive(context); - } - - public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesSupported(context); - } - - public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { - if ((baseType.BaseType == typeof(System.Enum))) { - if ((value.GetType() == destinationType)) { - return value; - } - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return "NULL_ENUM_VALUE" ; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((baseType == typeof(bool)) - && (baseType.BaseType == typeof(System.ValueType)))) { - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((context != null) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - } - - // Embedded class to represent WMI system Properties. - [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] - public class ManagementSystemProperties { - - private System.Management.ManagementBaseObject PrivateLateBoundObject; - - public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { - PrivateLateBoundObject = ManagedObject; - } - - [Browsable(true)] - public int GENUS { - get { - return ((int)(PrivateLateBoundObject["__GENUS"])); - } - } - - [Browsable(true)] - public string CLASS { - get { - return ((string)(PrivateLateBoundObject["__CLASS"])); - } - } - - [Browsable(true)] - public string SUPERCLASS { - get { - return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); - } - } - - [Browsable(true)] - public string DYNASTY { - get { - return ((string)(PrivateLateBoundObject["__DYNASTY"])); - } - } - - [Browsable(true)] - public string RELPATH { - get { - return ((string)(PrivateLateBoundObject["__RELPATH"])); - } - } - - [Browsable(true)] - public int PROPERTY_COUNT { - get { - return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); - } - } - - [Browsable(true)] - public string[] DERIVATION { - get { - return ((string[])(PrivateLateBoundObject["__DERIVATION"])); - } - } - - [Browsable(true)] - public string SERVER { - get { - return ((string)(PrivateLateBoundObject["__SERVER"])); - } - } - - [Browsable(true)] - public string NAMESPACE { - get { - return ((string)(PrivateLateBoundObject["__NAMESPACE"])); - } - } - - [Browsable(true)] - public string PATH { - get { - return ((string)(PrivateLateBoundObject["__PATH"])); - } - } - } - } -} +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2 { + using System; + using System.ComponentModel; + using System.Management; + using System.Collections; + using System.Globalization; + using System.ComponentModel.Design.Serialization; + using System.Reflection; + + + // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. + // Functions IsNull() are used to check if a property is NULL. + // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. + // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. + // An Early Bound class generated for the WMI class.Msvm_MemorySettingData + public class MemorySettingData : System.ComponentModel.Component { + + // Private property to hold the WMI namespace in which the class resides. + private static string CreatedWmiNamespace = "ROOT\\virtualization\\v2"; + + // Private property to hold the name of WMI class which created this class. + public static string CreatedClassName = "Msvm_MemorySettingData"; + + // Private member variable to hold the ManagementScope which is used by the various methods. + private static System.Management.ManagementScope statMgmtScope = null; + + private ManagementSystemProperties PrivateSystemProperties; + + // Underlying lateBound WMI object. + private System.Management.ManagementObject PrivateLateBoundObject; + + // Member variable to store the 'automatic commit' behavior for the class. + private bool AutoCommitProp; + + // Private variable to hold the embedded property representing the instance. + private System.Management.ManagementBaseObject embeddedObj; + + // The current WMI object used + private System.Management.ManagementBaseObject curObj; + + // Flag to indicate if the instance is an embedded object. + private bool isEmbedded; + + // Below are different overloads of constructors to initialize an instance of the class with a WMI object. + public MemorySettingData() { + this.InitializeObject(null, null, null); + } + + public MemorySettingData(string keyInstanceID) { + this.InitializeObject(null, new System.Management.ManagementPath(MemorySettingData.ConstructPath(keyInstanceID)), null); + } + + public MemorySettingData(System.Management.ManagementScope mgmtScope, string keyInstanceID) { + this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(MemorySettingData.ConstructPath(keyInstanceID)), null); + } + + public MemorySettingData(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(null, path, getOptions); + } + + public MemorySettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { + this.InitializeObject(mgmtScope, path, null); + } + + public MemorySettingData(System.Management.ManagementPath path) { + this.InitializeObject(null, path, null); + } + + public MemorySettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(mgmtScope, path, getOptions); + } + + public MemorySettingData(System.Management.ManagementObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + PrivateLateBoundObject = theObject; + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + public MemorySettingData(System.Management.ManagementBaseObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + embeddedObj = theObject; + PrivateSystemProperties = new ManagementSystemProperties(theObject); + curObj = embeddedObj; + isEmbedded = true; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + // Property returns the namespace of the WMI class. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OriginatingNamespace { + get { + return "ROOT\\virtualization\\v2"; + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ManagementClassName { + get { + string strRet = CreatedClassName; + if ((curObj != null)) { + if ((curObj.ClassPath != null)) { + strRet = ((string)(curObj["__CLASS"])); + if (((strRet == null) + || (strRet == string.Empty))) { + strRet = CreatedClassName; + } + } + } + return strRet; + } + } + + // Property pointing to an embedded object to get System properties of the WMI object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ManagementSystemProperties SystemProperties { + get { + return PrivateSystemProperties; + } + } + + // Property returning the underlying lateBound object. + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementBaseObject LateBoundObject { + get { + return curObj; + } + } + + // ManagementScope of the object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementScope Scope { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Scope; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Scope = value; + } + } + } + + // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool AutoCommit { + get { + return AutoCommitProp; + } + set { + AutoCommitProp = value; + } + } + + // The ManagementPath of the underlying WMI object. + [Browsable(true)] + public System.Management.ManagementPath Path { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Path; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + if ((CheckIfProperClass(null, value, null) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + PrivateLateBoundObject.Path = value; + } + } + } + + // Public static scope property which is used by the various methods. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public static System.Management.ManagementScope StaticScope { + get { + return statMgmtScope; + } + set { + statMgmtScope = value; + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Address { + get { + return ((string)(curObj["Address"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string AddressOnParent { + get { + return ((string)(curObj["AddressOnParent"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string AllocationUnits { + get { + return ((string)(curObj["AllocationUnits"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAutomaticAllocationNull { + get { + if ((curObj["AutomaticAllocation"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool AutomaticAllocation { + get { + if ((curObj["AutomaticAllocation"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["AutomaticAllocation"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAutomaticDeallocationNull { + get { + if ((curObj["AutomaticDeallocation"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool AutomaticDeallocation { + get { + if ((curObj["AutomaticDeallocation"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["AutomaticDeallocation"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Caption { + get { + return ((string)(curObj["Caption"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] Connection { + get { + return ((string[])(curObj["Connection"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsConsumerVisibilityNull { + get { + if ((curObj["ConsumerVisibility"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort ConsumerVisibility { + get { + if ((curObj["ConsumerVisibility"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["ConsumerVisibility"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Description { + get { + return ((string)(curObj["Description"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsDynamicMemoryEnabledNull { + get { + if ((curObj["DynamicMemoryEnabled"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Indicates if dynamic memory is enabled.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool DynamicMemoryEnabled { + get { + if ((curObj["DynamicMemoryEnabled"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["DynamicMemoryEnabled"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ElementName { + get { + return ((string)(curObj["ElementName"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] HostResource { + get { + return ((string[])(curObj["HostResource"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string InstanceID { + get { + return ((string)(curObj["InstanceID"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsIsVirtualizedNull { + get { + if ((curObj["IsVirtualized"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"Indicates whether this device is virtualized or passed through, possibly using partitioning. When set to False, the underlying or host resource is utilized. At least one item shall be present in the DeviceID property. When set to True, the resource is virtualized and may not map directly to an underlying/host resource. Some implementations may support specific assignment for virtualized resources, in which case the host resource(s) are exposed using the DeviceID property. This property is always set to True.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool IsVirtualized { + get { + if ((curObj["IsVirtualized"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["IsVirtualized"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsLimitNull { + get { + if ((curObj["Limit"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong Limit { + get { + if ((curObj["Limit"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["Limit"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsMappingBehaviorNull { + get { + if ((curObj["MappingBehavior"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort MappingBehavior { + get { + if ((curObj["MappingBehavior"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["MappingBehavior"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsMaxMemoryBlocksPerNumaNodeNull { + get { + if ((curObj["MaxMemoryBlocksPerNumaNode"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The maximum amount of memory that can be observed within the VM as belonging to a" + + " single NUMA node.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong MaxMemoryBlocksPerNumaNode { + get { + if ((curObj["MaxMemoryBlocksPerNumaNode"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["MaxMemoryBlocksPerNumaNode"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherResourceType { + get { + return ((string)(curObj["OtherResourceType"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Parent { + get { + return ((string)(curObj["Parent"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string PoolID { + get { + return ((string)(curObj["PoolID"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsReservationNull { + get { + if ((curObj["Reservation"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong Reservation { + get { + if ((curObj["Reservation"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["Reservation"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ResourceSubType { + get { + return ((string)(curObj["ResourceSubType"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsResourceTypeNull { + get { + if ((curObj["ResourceType"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort ResourceType { + get { + if ((curObj["ResourceType"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["ResourceType"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsSwapFilesInUseNull { + get { + if ((curObj["SwapFilesInUse"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Indicates if smart paging is active.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool SwapFilesInUse { + get { + if ((curObj["SwapFilesInUse"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["SwapFilesInUse"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsTargetMemoryBufferNull { + get { + if ((curObj["TargetMemoryBuffer"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint TargetMemoryBuffer { + get { + if ((curObj["TargetMemoryBuffer"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["TargetMemoryBuffer"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsVirtualQuantityNull { + get { + if ((curObj["VirtualQuantity"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong VirtualQuantity { + get { + if ((curObj["VirtualQuantity"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["VirtualQuantity"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string VirtualQuantityUnits { + get { + return ((string)(curObj["VirtualQuantityUnits"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsWeightNull { + get { + if ((curObj["Weight"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint Weight { + get { + if ((curObj["Weight"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["Weight"])); + } + } + + private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { + if (((path != null) + && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); + } + } + + private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { + if (((theObj != null) + && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); + if ((parentClasses != null)) { + int count = 0; + for (count = 0; (count < parentClasses.Length); count = (count + 1)) { + if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { + return true; + } + } + } + } + return false; + } + + private bool ShouldSerializeAutomaticAllocation() { + if ((this.IsAutomaticAllocationNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeAutomaticDeallocation() { + if ((this.IsAutomaticDeallocationNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeConsumerVisibility() { + if ((this.IsConsumerVisibilityNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeDynamicMemoryEnabled() { + if ((this.IsDynamicMemoryEnabledNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeIsVirtualized() { + if ((this.IsIsVirtualizedNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeLimit() { + if ((this.IsLimitNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeMappingBehavior() { + if ((this.IsMappingBehaviorNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeMaxMemoryBlocksPerNumaNode() { + if ((this.IsMaxMemoryBlocksPerNumaNodeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeReservation() { + if ((this.IsReservationNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeResourceType() { + if ((this.IsResourceTypeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeSwapFilesInUse() { + if ((this.IsSwapFilesInUseNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeTargetMemoryBuffer() { + if ((this.IsTargetMemoryBufferNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeVirtualQuantity() { + if ((this.IsVirtualQuantityNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeWeight() { + if ((this.IsWeightNull == false)) { + return true; + } + return false; + } + + [Browsable(true)] + public void CommitObject() { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(); + } + } + + [Browsable(true)] + public void CommitObject(System.Management.PutOptions putOptions) { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(putOptions); + } + } + + private void Initialize() { + AutoCommitProp = true; + isEmbedded = false; + } + + private static string ConstructPath(string keyInstanceID) { + string strPath = "ROOT\\virtualization\\v2:Msvm_MemorySettingData"; + strPath = string.Concat(strPath, string.Concat(".InstanceID=", string.Concat("\"", string.Concat(keyInstanceID, "\"")))); + return strPath; + } + + private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + Initialize(); + if ((path != null)) { + if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + } + PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + + // Different overloads of GetInstances() help in enumerating instances of the WMI class. + public static MemorySettingDataCollection GetInstances() { + return GetInstances(null, null, null); + } + + public static MemorySettingDataCollection GetInstances(string condition) { + return GetInstances(null, condition, null); + } + + public static MemorySettingDataCollection GetInstances(string[] selectedProperties) { + return GetInstances(null, null, selectedProperties); + } + + public static MemorySettingDataCollection GetInstances(string condition, string[] selectedProperties) { + return GetInstances(null, condition, selectedProperties); + } + + public static MemorySettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); + pathObj.ClassName = "Msvm_MemorySettingData"; + pathObj.NamespacePath = "root\\virtualization\\v2"; + System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); + if ((enumOptions == null)) { + enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + } + return new MemorySettingDataCollection(clsObject.GetInstances(enumOptions)); + } + + public static MemorySettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { + return GetInstances(mgmtScope, condition, null); + } + + public static MemorySettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { + return GetInstances(mgmtScope, null, selectedProperties); + } + + public static MemorySettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_MemorySettingData", condition, selectedProperties)); + System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + ObjectSearcher.Options = enumOptions; + return new MemorySettingDataCollection(ObjectSearcher.Get()); + } + + [Browsable(true)] + public static MemorySettingData CreateInstance() { + System.Management.ManagementScope mgmtScope = null; + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = CreatedWmiNamespace; + } + else { + mgmtScope = statMgmtScope; + } + System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); + System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); + return new MemorySettingData(tmpMgmtClass.CreateInstance()); + } + + [Browsable(true)] + public void Delete() { + PrivateLateBoundObject.Delete(); + } + + // Enumerator implementation for enumerating instances of the class. + public class MemorySettingDataCollection : object, ICollection { + + private ManagementObjectCollection privColObj; + + public MemorySettingDataCollection(ManagementObjectCollection objCollection) { + privColObj = objCollection; + } + + public virtual int Count { + get { + return privColObj.Count; + } + } + + public virtual bool IsSynchronized { + get { + return privColObj.IsSynchronized; + } + } + + public virtual object SyncRoot { + get { + return this; + } + } + + public virtual void CopyTo(System.Array array, int index) { + privColObj.CopyTo(array, index); + int nCtr; + for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { + array.SetValue(new MemorySettingData(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); + } + } + + public virtual System.Collections.IEnumerator GetEnumerator() { + return new MemorySettingDataEnumerator(privColObj.GetEnumerator()); + } + + public class MemorySettingDataEnumerator : object, System.Collections.IEnumerator { + + private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; + + public MemorySettingDataEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { + privObjEnum = objEnum; + } + + public virtual object Current { + get { + return new MemorySettingData(((System.Management.ManagementObject)(privObjEnum.Current))); + } + } + + public virtual bool MoveNext() { + return privObjEnum.MoveNext(); + } + + public virtual void Reset() { + privObjEnum.Reset(); + } + } + } + + // TypeConverter to handle null values for ValueType properties + public class WMIValueTypeConverter : TypeConverter { + + private TypeConverter baseConverter; + + private System.Type baseType; + + public WMIValueTypeConverter(System.Type inBaseType) { + baseConverter = TypeDescriptor.GetConverter(inBaseType); + baseType = inBaseType; + } + + public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { + return baseConverter.CanConvertFrom(context, srcType); + } + + public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { + return baseConverter.CanConvertTo(context, destinationType); + } + + public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { + return baseConverter.ConvertFrom(context, culture, value); + } + + public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { + return baseConverter.CreateInstance(context, dictionary); + } + + public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetCreateInstanceSupported(context); + } + + public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { + return baseConverter.GetProperties(context, value, attributeVar); + } + + public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetPropertiesSupported(context); + } + + public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValues(context); + } + + public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesExclusive(context); + } + + public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesSupported(context); + } + + public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { + if ((baseType.BaseType == typeof(System.Enum))) { + if ((value.GetType() == destinationType)) { + return value; + } + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return "NULL_ENUM_VALUE" ; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((baseType == typeof(bool)) + && (baseType.BaseType == typeof(System.ValueType)))) { + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((context != null) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + } + + // Embedded class to represent WMI system Properties. + [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] + public class ManagementSystemProperties { + + private System.Management.ManagementBaseObject PrivateLateBoundObject; + + public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { + PrivateLateBoundObject = ManagedObject; + } + + [Browsable(true)] + public int GENUS { + get { + return ((int)(PrivateLateBoundObject["__GENUS"])); + } + } + + [Browsable(true)] + public string CLASS { + get { + return ((string)(PrivateLateBoundObject["__CLASS"])); + } + } + + [Browsable(true)] + public string SUPERCLASS { + get { + return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); + } + } + + [Browsable(true)] + public string DYNASTY { + get { + return ((string)(PrivateLateBoundObject["__DYNASTY"])); + } + } + + [Browsable(true)] + public string RELPATH { + get { + return ((string)(PrivateLateBoundObject["__RELPATH"])); + } + } + + [Browsable(true)] + public int PROPERTY_COUNT { + get { + return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); + } + } + + [Browsable(true)] + public string[] DERIVATION { + get { + return ((string[])(PrivateLateBoundObject["__DERIVATION"])); + } + } + + [Browsable(true)] + public string SERVER { + get { + return ((string)(PrivateLateBoundObject["__SERVER"])); + } + } + + [Browsable(true)] + public string NAMESPACE { + get { + return ((string)(PrivateLateBoundObject["__NAMESPACE"])); + } + } + + [Browsable(true)] + public string PATH { + get { + return ((string)(PrivateLateBoundObject["__PATH"])); + } + } + } + } +} diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_ProcessorSettingData.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_ProcessorSettingData.cs index 0962e7e6f91..f26a1f168c9 100644 --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_ProcessorSettingData.cs +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_ProcessorSettingData.cs @@ -1,1134 +1,1134 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2 { - using System; - using System.ComponentModel; - using System.Management; - using System.Collections; - using System.Globalization; - using System.ComponentModel.Design.Serialization; - using System.Reflection; - - - // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. - // Functions IsNull() are used to check if a property is NULL. - // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. - // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. - // An Early Bound class generated for the WMI class.Msvm_ProcessorSettingData - public class ProcessorSettingData : System.ComponentModel.Component { - - // Private property to hold the WMI namespace in which the class resides. - private static string CreatedWmiNamespace = "ROOT\\virtualization\\v2"; - - // Private property to hold the name of WMI class which created this class. - public static string CreatedClassName = "Msvm_ProcessorSettingData"; - - // Private member variable to hold the ManagementScope which is used by the various methods. - private static System.Management.ManagementScope statMgmtScope = null; - - private ManagementSystemProperties PrivateSystemProperties; - - // Underlying lateBound WMI object. - private System.Management.ManagementObject PrivateLateBoundObject; - - // Member variable to store the 'automatic commit' behavior for the class. - private bool AutoCommitProp; - - // Private variable to hold the embedded property representing the instance. - private System.Management.ManagementBaseObject embeddedObj; - - // The current WMI object used - private System.Management.ManagementBaseObject curObj; - - // Flag to indicate if the instance is an embedded object. - private bool isEmbedded; - - // Below are different overloads of constructors to initialize an instance of the class with a WMI object. - public ProcessorSettingData() { - this.InitializeObject(null, null, null); - } - - public ProcessorSettingData(string keyInstanceID) { - this.InitializeObject(null, new System.Management.ManagementPath(ProcessorSettingData.ConstructPath(keyInstanceID)), null); - } - - public ProcessorSettingData(System.Management.ManagementScope mgmtScope, string keyInstanceID) { - this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(ProcessorSettingData.ConstructPath(keyInstanceID)), null); - } - - public ProcessorSettingData(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(null, path, getOptions); - } - - public ProcessorSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { - this.InitializeObject(mgmtScope, path, null); - } - - public ProcessorSettingData(System.Management.ManagementPath path) { - this.InitializeObject(null, path, null); - } - - public ProcessorSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(mgmtScope, path, getOptions); - } - - public ProcessorSettingData(System.Management.ManagementObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - PrivateLateBoundObject = theObject; - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - public ProcessorSettingData(System.Management.ManagementBaseObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - embeddedObj = theObject; - PrivateSystemProperties = new ManagementSystemProperties(theObject); - curObj = embeddedObj; - isEmbedded = true; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - // Property returns the namespace of the WMI class. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OriginatingNamespace { - get { - return "ROOT\\virtualization\\v2"; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ManagementClassName { - get { - string strRet = CreatedClassName; - if ((curObj != null)) { - if ((curObj.ClassPath != null)) { - strRet = ((string)(curObj["__CLASS"])); - if (((strRet == null) - || (strRet == string.Empty))) { - strRet = CreatedClassName; - } - } - } - return strRet; - } - } - - // Property pointing to an embedded object to get System properties of the WMI object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ManagementSystemProperties SystemProperties { - get { - return PrivateSystemProperties; - } - } - - // Property returning the underlying lateBound object. - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementBaseObject LateBoundObject { - get { - return curObj; - } - } - - // ManagementScope of the object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementScope Scope { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Scope; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Scope = value; - } - } - } - - // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool AutoCommit { - get { - return AutoCommitProp; - } - set { - AutoCommitProp = value; - } - } - - // The ManagementPath of the underlying WMI object. - [Browsable(true)] - public System.Management.ManagementPath Path { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Path; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - if ((CheckIfProperClass(null, value, null) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - PrivateLateBoundObject.Path = value; - } - } - } - - // Public static scope property which is used by the various methods. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public static System.Management.ManagementScope StaticScope { - get { - return statMgmtScope; - } - set { - statMgmtScope = value; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Address { - get { - return ((string)(curObj["Address"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string AddressOnParent { - get { - return ((string)(curObj["AddressOnParent"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string AllocationUnits { - get { - return ((string)(curObj["AllocationUnits"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsAutomaticAllocationNull { - get { - if ((curObj["AutomaticAllocation"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool AutomaticAllocation { - get { - if ((curObj["AutomaticAllocation"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["AutomaticAllocation"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsAutomaticDeallocationNull { - get { - if ((curObj["AutomaticDeallocation"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool AutomaticDeallocation { - get { - if ((curObj["AutomaticDeallocation"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["AutomaticDeallocation"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Caption { - get { - return ((string)(curObj["Caption"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] Connection { - get { - return ((string[])(curObj["Connection"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsConsumerVisibilityNull { - get { - if ((curObj["ConsumerVisibility"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort ConsumerVisibility { - get { - if ((curObj["ConsumerVisibility"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["ConsumerVisibility"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Description { - get { - return ((string)(curObj["Description"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ElementName { - get { - return ((string)(curObj["ElementName"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] HostResource { - get { - return ((string[])(curObj["HostResource"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string InstanceID { - get { - return ((string)(curObj["InstanceID"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsLimitNull { - get { - if ((curObj["Limit"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong Limit { - get { - if ((curObj["Limit"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["Limit"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsLimitCPUIDNull { - get { - if ((curObj["LimitCPUID"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("Indicates whether the virtual machine should lower the CPU identifier. Some older" + - " operating systems may require you to limit processor functionality in this way " + - "in order to run.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool LimitCPUID { - get { - if ((curObj["LimitCPUID"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["LimitCPUID"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsLimitProcessorFeaturesNull { - get { - if ((curObj["LimitProcessorFeatures"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description(@"Indicates whether the VM should limit the CPU features exposed to the operating system. Limiting the processor features enables the VM to be migrated to different host computer systems with different processors. Migrating VMs between computers with processors from different vendors is not supported.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool LimitProcessorFeatures { - get { - if ((curObj["LimitProcessorFeatures"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["LimitProcessorFeatures"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsMappingBehaviorNull { - get { - if ((curObj["MappingBehavior"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort MappingBehavior { - get { - if ((curObj["MappingBehavior"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["MappingBehavior"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsMaxNumaNodesPerSocketNull { - get { - if ((curObj["MaxNumaNodesPerSocket"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The maximum number of NUMA nodes that can be observed within the VM as belonging " + - "to a single processor socket.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong MaxNumaNodesPerSocket { - get { - if ((curObj["MaxNumaNodesPerSocket"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["MaxNumaNodesPerSocket"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsMaxProcessorsPerNumaNodeNull { - get { - if ((curObj["MaxProcessorsPerNumaNode"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The maximum number of virtual processors that can be observed within the VM as be" + - "longing to a single virtual NUMA node.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong MaxProcessorsPerNumaNode { - get { - if ((curObj["MaxProcessorsPerNumaNode"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["MaxProcessorsPerNumaNode"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OtherResourceType { - get { - return ((string)(curObj["OtherResourceType"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Parent { - get { - return ((string)(curObj["Parent"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string PoolID { - get { - return ((string)(curObj["PoolID"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsReservationNull { - get { - if ((curObj["Reservation"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong Reservation { - get { - if ((curObj["Reservation"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["Reservation"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ResourceSubType { - get { - return ((string)(curObj["ResourceSubType"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsResourceTypeNull { - get { - if ((curObj["ResourceType"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort ResourceType { - get { - if ((curObj["ResourceType"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["ResourceType"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsVirtualQuantityNull { - get { - if ((curObj["VirtualQuantity"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong VirtualQuantity { - get { - if ((curObj["VirtualQuantity"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["VirtualQuantity"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string VirtualQuantityUnits { - get { - return ((string)(curObj["VirtualQuantityUnits"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsWeightNull { - get { - if ((curObj["Weight"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public uint Weight { - get { - if ((curObj["Weight"] == null)) { - return System.Convert.ToUInt32(0); - } - return ((uint)(curObj["Weight"])); - } - } - - private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { - if (((path != null) - && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); - } - } - - private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { - if (((theObj != null) - && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); - if ((parentClasses != null)) { - int count = 0; - for (count = 0; (count < parentClasses.Length); count = (count + 1)) { - if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { - return true; - } - } - } - } - return false; - } - - private bool ShouldSerializeAutomaticAllocation() { - if ((this.IsAutomaticAllocationNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeAutomaticDeallocation() { - if ((this.IsAutomaticDeallocationNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeConsumerVisibility() { - if ((this.IsConsumerVisibilityNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeLimit() { - if ((this.IsLimitNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeLimitCPUID() { - if ((this.IsLimitCPUIDNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeLimitProcessorFeatures() { - if ((this.IsLimitProcessorFeaturesNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeMappingBehavior() { - if ((this.IsMappingBehaviorNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeMaxNumaNodesPerSocket() { - if ((this.IsMaxNumaNodesPerSocketNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeMaxProcessorsPerNumaNode() { - if ((this.IsMaxProcessorsPerNumaNodeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeReservation() { - if ((this.IsReservationNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeResourceType() { - if ((this.IsResourceTypeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeVirtualQuantity() { - if ((this.IsVirtualQuantityNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeWeight() { - if ((this.IsWeightNull == false)) { - return true; - } - return false; - } - - [Browsable(true)] - public void CommitObject() { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(); - } - } - - [Browsable(true)] - public void CommitObject(System.Management.PutOptions putOptions) { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(putOptions); - } - } - - private void Initialize() { - AutoCommitProp = true; - isEmbedded = false; - } - - private static string ConstructPath(string keyInstanceID) { - string strPath = "ROOT\\virtualization\\v2:Msvm_ProcessorSettingData"; - strPath = string.Concat(strPath, string.Concat(".InstanceID=", string.Concat("\"", string.Concat(keyInstanceID, "\"")))); - return strPath; - } - - private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - Initialize(); - if ((path != null)) { - if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - } - PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - - // Different overloads of GetInstances() help in enumerating instances of the WMI class. - public static ProcessorSettingDataCollection GetInstances() { - return GetInstances(null, null, null); - } - - public static ProcessorSettingDataCollection GetInstances(string condition) { - return GetInstances(null, condition, null); - } - - public static ProcessorSettingDataCollection GetInstances(string[] selectedProperties) { - return GetInstances(null, null, selectedProperties); - } - - public static ProcessorSettingDataCollection GetInstances(string condition, string[] selectedProperties) { - return GetInstances(null, condition, selectedProperties); - } - - public static ProcessorSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); - pathObj.ClassName = "Msvm_ProcessorSettingData"; - pathObj.NamespacePath = "root\\virtualization\\v2"; - System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); - if ((enumOptions == null)) { - enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - } - return new ProcessorSettingDataCollection(clsObject.GetInstances(enumOptions)); - } - - public static ProcessorSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { - return GetInstances(mgmtScope, condition, null); - } - - public static ProcessorSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { - return GetInstances(mgmtScope, null, selectedProperties); - } - - public static ProcessorSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_ProcessorSettingData", condition, selectedProperties)); - System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - ObjectSearcher.Options = enumOptions; - return new ProcessorSettingDataCollection(ObjectSearcher.Get()); - } - - [Browsable(true)] - public static ProcessorSettingData CreateInstance() { - System.Management.ManagementScope mgmtScope = null; - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = CreatedWmiNamespace; - } - else { - mgmtScope = statMgmtScope; - } - System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); - System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); - return new ProcessorSettingData(tmpMgmtClass.CreateInstance()); - } - - [Browsable(true)] - public void Delete() { - PrivateLateBoundObject.Delete(); - } - - // Enumerator implementation for enumerating instances of the class. - public class ProcessorSettingDataCollection : object, ICollection { - - private ManagementObjectCollection privColObj; - - public ProcessorSettingDataCollection(ManagementObjectCollection objCollection) { - privColObj = objCollection; - } - - public virtual int Count { - get { - return privColObj.Count; - } - } - - public virtual bool IsSynchronized { - get { - return privColObj.IsSynchronized; - } - } - - public virtual object SyncRoot { - get { - return this; - } - } - - public virtual void CopyTo(System.Array array, int index) { - privColObj.CopyTo(array, index); - int nCtr; - for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { - array.SetValue(new ProcessorSettingData(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); - } - } - - public virtual System.Collections.IEnumerator GetEnumerator() { - return new ProcessorSettingDataEnumerator(privColObj.GetEnumerator()); - } - - public class ProcessorSettingDataEnumerator : object, System.Collections.IEnumerator { - - private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; - - public ProcessorSettingDataEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { - privObjEnum = objEnum; - } - - public virtual object Current { - get { - return new ProcessorSettingData(((System.Management.ManagementObject)(privObjEnum.Current))); - } - } - - public virtual bool MoveNext() { - return privObjEnum.MoveNext(); - } - - public virtual void Reset() { - privObjEnum.Reset(); - } - } - } - - // TypeConverter to handle null values for ValueType properties - public class WMIValueTypeConverter : TypeConverter { - - private TypeConverter baseConverter; - - private System.Type baseType; - - public WMIValueTypeConverter(System.Type inBaseType) { - baseConverter = TypeDescriptor.GetConverter(inBaseType); - baseType = inBaseType; - } - - public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { - return baseConverter.CanConvertFrom(context, srcType); - } - - public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { - return baseConverter.CanConvertTo(context, destinationType); - } - - public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { - return baseConverter.ConvertFrom(context, culture, value); - } - - public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { - return baseConverter.CreateInstance(context, dictionary); - } - - public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetCreateInstanceSupported(context); - } - - public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { - return baseConverter.GetProperties(context, value, attributeVar); - } - - public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetPropertiesSupported(context); - } - - public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValues(context); - } - - public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesExclusive(context); - } - - public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesSupported(context); - } - - public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { - if ((baseType.BaseType == typeof(System.Enum))) { - if ((value.GetType() == destinationType)) { - return value; - } - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return "NULL_ENUM_VALUE" ; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((baseType == typeof(bool)) - && (baseType.BaseType == typeof(System.ValueType)))) { - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((context != null) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - } - - // Embedded class to represent WMI system Properties. - [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] - public class ManagementSystemProperties { - - private System.Management.ManagementBaseObject PrivateLateBoundObject; - - public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { - PrivateLateBoundObject = ManagedObject; - } - - [Browsable(true)] - public int GENUS { - get { - return ((int)(PrivateLateBoundObject["__GENUS"])); - } - } - - [Browsable(true)] - public string CLASS { - get { - return ((string)(PrivateLateBoundObject["__CLASS"])); - } - } - - [Browsable(true)] - public string SUPERCLASS { - get { - return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); - } - } - - [Browsable(true)] - public string DYNASTY { - get { - return ((string)(PrivateLateBoundObject["__DYNASTY"])); - } - } - - [Browsable(true)] - public string RELPATH { - get { - return ((string)(PrivateLateBoundObject["__RELPATH"])); - } - } - - [Browsable(true)] - public int PROPERTY_COUNT { - get { - return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); - } - } - - [Browsable(true)] - public string[] DERIVATION { - get { - return ((string[])(PrivateLateBoundObject["__DERIVATION"])); - } - } - - [Browsable(true)] - public string SERVER { - get { - return ((string)(PrivateLateBoundObject["__SERVER"])); - } - } - - [Browsable(true)] - public string NAMESPACE { - get { - return ((string)(PrivateLateBoundObject["__NAMESPACE"])); - } - } - - [Browsable(true)] - public string PATH { - get { - return ((string)(PrivateLateBoundObject["__PATH"])); - } - } - } - } -} +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2 { + using System; + using System.ComponentModel; + using System.Management; + using System.Collections; + using System.Globalization; + using System.ComponentModel.Design.Serialization; + using System.Reflection; + + + // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. + // Functions IsNull() are used to check if a property is NULL. + // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. + // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. + // An Early Bound class generated for the WMI class.Msvm_ProcessorSettingData + public class ProcessorSettingData : System.ComponentModel.Component { + + // Private property to hold the WMI namespace in which the class resides. + private static string CreatedWmiNamespace = "ROOT\\virtualization\\v2"; + + // Private property to hold the name of WMI class which created this class. + public static string CreatedClassName = "Msvm_ProcessorSettingData"; + + // Private member variable to hold the ManagementScope which is used by the various methods. + private static System.Management.ManagementScope statMgmtScope = null; + + private ManagementSystemProperties PrivateSystemProperties; + + // Underlying lateBound WMI object. + private System.Management.ManagementObject PrivateLateBoundObject; + + // Member variable to store the 'automatic commit' behavior for the class. + private bool AutoCommitProp; + + // Private variable to hold the embedded property representing the instance. + private System.Management.ManagementBaseObject embeddedObj; + + // The current WMI object used + private System.Management.ManagementBaseObject curObj; + + // Flag to indicate if the instance is an embedded object. + private bool isEmbedded; + + // Below are different overloads of constructors to initialize an instance of the class with a WMI object. + public ProcessorSettingData() { + this.InitializeObject(null, null, null); + } + + public ProcessorSettingData(string keyInstanceID) { + this.InitializeObject(null, new System.Management.ManagementPath(ProcessorSettingData.ConstructPath(keyInstanceID)), null); + } + + public ProcessorSettingData(System.Management.ManagementScope mgmtScope, string keyInstanceID) { + this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(ProcessorSettingData.ConstructPath(keyInstanceID)), null); + } + + public ProcessorSettingData(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(null, path, getOptions); + } + + public ProcessorSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { + this.InitializeObject(mgmtScope, path, null); + } + + public ProcessorSettingData(System.Management.ManagementPath path) { + this.InitializeObject(null, path, null); + } + + public ProcessorSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(mgmtScope, path, getOptions); + } + + public ProcessorSettingData(System.Management.ManagementObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + PrivateLateBoundObject = theObject; + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + public ProcessorSettingData(System.Management.ManagementBaseObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + embeddedObj = theObject; + PrivateSystemProperties = new ManagementSystemProperties(theObject); + curObj = embeddedObj; + isEmbedded = true; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + // Property returns the namespace of the WMI class. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OriginatingNamespace { + get { + return "ROOT\\virtualization\\v2"; + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ManagementClassName { + get { + string strRet = CreatedClassName; + if ((curObj != null)) { + if ((curObj.ClassPath != null)) { + strRet = ((string)(curObj["__CLASS"])); + if (((strRet == null) + || (strRet == string.Empty))) { + strRet = CreatedClassName; + } + } + } + return strRet; + } + } + + // Property pointing to an embedded object to get System properties of the WMI object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ManagementSystemProperties SystemProperties { + get { + return PrivateSystemProperties; + } + } + + // Property returning the underlying lateBound object. + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementBaseObject LateBoundObject { + get { + return curObj; + } + } + + // ManagementScope of the object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementScope Scope { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Scope; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Scope = value; + } + } + } + + // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool AutoCommit { + get { + return AutoCommitProp; + } + set { + AutoCommitProp = value; + } + } + + // The ManagementPath of the underlying WMI object. + [Browsable(true)] + public System.Management.ManagementPath Path { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Path; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + if ((CheckIfProperClass(null, value, null) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + PrivateLateBoundObject.Path = value; + } + } + } + + // Public static scope property which is used by the various methods. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public static System.Management.ManagementScope StaticScope { + get { + return statMgmtScope; + } + set { + statMgmtScope = value; + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Address { + get { + return ((string)(curObj["Address"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string AddressOnParent { + get { + return ((string)(curObj["AddressOnParent"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string AllocationUnits { + get { + return ((string)(curObj["AllocationUnits"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAutomaticAllocationNull { + get { + if ((curObj["AutomaticAllocation"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool AutomaticAllocation { + get { + if ((curObj["AutomaticAllocation"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["AutomaticAllocation"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAutomaticDeallocationNull { + get { + if ((curObj["AutomaticDeallocation"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool AutomaticDeallocation { + get { + if ((curObj["AutomaticDeallocation"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["AutomaticDeallocation"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Caption { + get { + return ((string)(curObj["Caption"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] Connection { + get { + return ((string[])(curObj["Connection"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsConsumerVisibilityNull { + get { + if ((curObj["ConsumerVisibility"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort ConsumerVisibility { + get { + if ((curObj["ConsumerVisibility"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["ConsumerVisibility"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Description { + get { + return ((string)(curObj["Description"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ElementName { + get { + return ((string)(curObj["ElementName"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] HostResource { + get { + return ((string[])(curObj["HostResource"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string InstanceID { + get { + return ((string)(curObj["InstanceID"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsLimitNull { + get { + if ((curObj["Limit"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong Limit { + get { + if ((curObj["Limit"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["Limit"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsLimitCPUIDNull { + get { + if ((curObj["LimitCPUID"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Indicates whether the virtual machine should lower the CPU identifier. Some older" + + " operating systems may require you to limit processor functionality in this way " + + "in order to run.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool LimitCPUID { + get { + if ((curObj["LimitCPUID"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["LimitCPUID"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsLimitProcessorFeaturesNull { + get { + if ((curObj["LimitProcessorFeatures"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"Indicates whether the VM should limit the CPU features exposed to the operating system. Limiting the processor features enables the VM to be migrated to different host computer systems with different processors. Migrating VMs between computers with processors from different vendors is not supported.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool LimitProcessorFeatures { + get { + if ((curObj["LimitProcessorFeatures"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["LimitProcessorFeatures"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsMappingBehaviorNull { + get { + if ((curObj["MappingBehavior"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort MappingBehavior { + get { + if ((curObj["MappingBehavior"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["MappingBehavior"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsMaxNumaNodesPerSocketNull { + get { + if ((curObj["MaxNumaNodesPerSocket"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The maximum number of NUMA nodes that can be observed within the VM as belonging " + + "to a single processor socket.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong MaxNumaNodesPerSocket { + get { + if ((curObj["MaxNumaNodesPerSocket"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["MaxNumaNodesPerSocket"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsMaxProcessorsPerNumaNodeNull { + get { + if ((curObj["MaxProcessorsPerNumaNode"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The maximum number of virtual processors that can be observed within the VM as be" + + "longing to a single virtual NUMA node.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong MaxProcessorsPerNumaNode { + get { + if ((curObj["MaxProcessorsPerNumaNode"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["MaxProcessorsPerNumaNode"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherResourceType { + get { + return ((string)(curObj["OtherResourceType"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Parent { + get { + return ((string)(curObj["Parent"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string PoolID { + get { + return ((string)(curObj["PoolID"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsReservationNull { + get { + if ((curObj["Reservation"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong Reservation { + get { + if ((curObj["Reservation"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["Reservation"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ResourceSubType { + get { + return ((string)(curObj["ResourceSubType"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsResourceTypeNull { + get { + if ((curObj["ResourceType"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort ResourceType { + get { + if ((curObj["ResourceType"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["ResourceType"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsVirtualQuantityNull { + get { + if ((curObj["VirtualQuantity"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong VirtualQuantity { + get { + if ((curObj["VirtualQuantity"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["VirtualQuantity"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string VirtualQuantityUnits { + get { + return ((string)(curObj["VirtualQuantityUnits"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsWeightNull { + get { + if ((curObj["Weight"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint Weight { + get { + if ((curObj["Weight"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["Weight"])); + } + } + + private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { + if (((path != null) + && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); + } + } + + private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { + if (((theObj != null) + && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); + if ((parentClasses != null)) { + int count = 0; + for (count = 0; (count < parentClasses.Length); count = (count + 1)) { + if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { + return true; + } + } + } + } + return false; + } + + private bool ShouldSerializeAutomaticAllocation() { + if ((this.IsAutomaticAllocationNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeAutomaticDeallocation() { + if ((this.IsAutomaticDeallocationNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeConsumerVisibility() { + if ((this.IsConsumerVisibilityNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeLimit() { + if ((this.IsLimitNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeLimitCPUID() { + if ((this.IsLimitCPUIDNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeLimitProcessorFeatures() { + if ((this.IsLimitProcessorFeaturesNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeMappingBehavior() { + if ((this.IsMappingBehaviorNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeMaxNumaNodesPerSocket() { + if ((this.IsMaxNumaNodesPerSocketNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeMaxProcessorsPerNumaNode() { + if ((this.IsMaxProcessorsPerNumaNodeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeReservation() { + if ((this.IsReservationNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeResourceType() { + if ((this.IsResourceTypeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeVirtualQuantity() { + if ((this.IsVirtualQuantityNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeWeight() { + if ((this.IsWeightNull == false)) { + return true; + } + return false; + } + + [Browsable(true)] + public void CommitObject() { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(); + } + } + + [Browsable(true)] + public void CommitObject(System.Management.PutOptions putOptions) { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(putOptions); + } + } + + private void Initialize() { + AutoCommitProp = true; + isEmbedded = false; + } + + private static string ConstructPath(string keyInstanceID) { + string strPath = "ROOT\\virtualization\\v2:Msvm_ProcessorSettingData"; + strPath = string.Concat(strPath, string.Concat(".InstanceID=", string.Concat("\"", string.Concat(keyInstanceID, "\"")))); + return strPath; + } + + private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + Initialize(); + if ((path != null)) { + if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + } + PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + + // Different overloads of GetInstances() help in enumerating instances of the WMI class. + public static ProcessorSettingDataCollection GetInstances() { + return GetInstances(null, null, null); + } + + public static ProcessorSettingDataCollection GetInstances(string condition) { + return GetInstances(null, condition, null); + } + + public static ProcessorSettingDataCollection GetInstances(string[] selectedProperties) { + return GetInstances(null, null, selectedProperties); + } + + public static ProcessorSettingDataCollection GetInstances(string condition, string[] selectedProperties) { + return GetInstances(null, condition, selectedProperties); + } + + public static ProcessorSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); + pathObj.ClassName = "Msvm_ProcessorSettingData"; + pathObj.NamespacePath = "root\\virtualization\\v2"; + System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); + if ((enumOptions == null)) { + enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + } + return new ProcessorSettingDataCollection(clsObject.GetInstances(enumOptions)); + } + + public static ProcessorSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { + return GetInstances(mgmtScope, condition, null); + } + + public static ProcessorSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { + return GetInstances(mgmtScope, null, selectedProperties); + } + + public static ProcessorSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_ProcessorSettingData", condition, selectedProperties)); + System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + ObjectSearcher.Options = enumOptions; + return new ProcessorSettingDataCollection(ObjectSearcher.Get()); + } + + [Browsable(true)] + public static ProcessorSettingData CreateInstance() { + System.Management.ManagementScope mgmtScope = null; + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = CreatedWmiNamespace; + } + else { + mgmtScope = statMgmtScope; + } + System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); + System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); + return new ProcessorSettingData(tmpMgmtClass.CreateInstance()); + } + + [Browsable(true)] + public void Delete() { + PrivateLateBoundObject.Delete(); + } + + // Enumerator implementation for enumerating instances of the class. + public class ProcessorSettingDataCollection : object, ICollection { + + private ManagementObjectCollection privColObj; + + public ProcessorSettingDataCollection(ManagementObjectCollection objCollection) { + privColObj = objCollection; + } + + public virtual int Count { + get { + return privColObj.Count; + } + } + + public virtual bool IsSynchronized { + get { + return privColObj.IsSynchronized; + } + } + + public virtual object SyncRoot { + get { + return this; + } + } + + public virtual void CopyTo(System.Array array, int index) { + privColObj.CopyTo(array, index); + int nCtr; + for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { + array.SetValue(new ProcessorSettingData(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); + } + } + + public virtual System.Collections.IEnumerator GetEnumerator() { + return new ProcessorSettingDataEnumerator(privColObj.GetEnumerator()); + } + + public class ProcessorSettingDataEnumerator : object, System.Collections.IEnumerator { + + private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; + + public ProcessorSettingDataEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { + privObjEnum = objEnum; + } + + public virtual object Current { + get { + return new ProcessorSettingData(((System.Management.ManagementObject)(privObjEnum.Current))); + } + } + + public virtual bool MoveNext() { + return privObjEnum.MoveNext(); + } + + public virtual void Reset() { + privObjEnum.Reset(); + } + } + } + + // TypeConverter to handle null values for ValueType properties + public class WMIValueTypeConverter : TypeConverter { + + private TypeConverter baseConverter; + + private System.Type baseType; + + public WMIValueTypeConverter(System.Type inBaseType) { + baseConverter = TypeDescriptor.GetConverter(inBaseType); + baseType = inBaseType; + } + + public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { + return baseConverter.CanConvertFrom(context, srcType); + } + + public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { + return baseConverter.CanConvertTo(context, destinationType); + } + + public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { + return baseConverter.ConvertFrom(context, culture, value); + } + + public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { + return baseConverter.CreateInstance(context, dictionary); + } + + public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetCreateInstanceSupported(context); + } + + public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { + return baseConverter.GetProperties(context, value, attributeVar); + } + + public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetPropertiesSupported(context); + } + + public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValues(context); + } + + public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesExclusive(context); + } + + public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesSupported(context); + } + + public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { + if ((baseType.BaseType == typeof(System.Enum))) { + if ((value.GetType() == destinationType)) { + return value; + } + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return "NULL_ENUM_VALUE" ; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((baseType == typeof(bool)) + && (baseType.BaseType == typeof(System.ValueType)))) { + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((context != null) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + } + + // Embedded class to represent WMI system Properties. + [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] + public class ManagementSystemProperties { + + private System.Management.ManagementBaseObject PrivateLateBoundObject; + + public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { + PrivateLateBoundObject = ManagedObject; + } + + [Browsable(true)] + public int GENUS { + get { + return ((int)(PrivateLateBoundObject["__GENUS"])); + } + } + + [Browsable(true)] + public string CLASS { + get { + return ((string)(PrivateLateBoundObject["__CLASS"])); + } + } + + [Browsable(true)] + public string SUPERCLASS { + get { + return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); + } + } + + [Browsable(true)] + public string DYNASTY { + get { + return ((string)(PrivateLateBoundObject["__DYNASTY"])); + } + } + + [Browsable(true)] + public string RELPATH { + get { + return ((string)(PrivateLateBoundObject["__RELPATH"])); + } + } + + [Browsable(true)] + public int PROPERTY_COUNT { + get { + return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); + } + } + + [Browsable(true)] + public string[] DERIVATION { + get { + return ((string[])(PrivateLateBoundObject["__DERIVATION"])); + } + } + + [Browsable(true)] + public string SERVER { + get { + return ((string)(PrivateLateBoundObject["__SERVER"])); + } + } + + [Browsable(true)] + public string NAMESPACE { + get { + return ((string)(PrivateLateBoundObject["__NAMESPACE"])); + } + } + + [Browsable(true)] + public string PATH { + get { + return ((string)(PrivateLateBoundObject["__PATH"])); + } + } + } + } +} diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_ResourceAllocationSettingData.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_ResourceAllocationSettingData.cs index de4ce9320fb..18483c71893 100644 --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_ResourceAllocationSettingData.cs +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_ResourceAllocationSettingData.cs @@ -1,1010 +1,1010 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2 -{ - using System; - using System.ComponentModel; - using System.Management; - using System.Collections; - using System.Globalization; - using System.ComponentModel.Design.Serialization; - using System.Reflection; - - - // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. - // Functions IsNull() are used to check if a property is NULL. - // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. - // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. - // An Early Bound class generated for the WMI class.Msvm_ResourceAllocationSettingData - public class ResourceAllocationSettingData : System.ComponentModel.Component { - - // Private property to hold the WMI namespace in which the class resides. - private static string CreatedWmiNamespace = "ROOT\\virtualization\\v2"; - - // Private property to hold the name of WMI class which created this class. - public static string CreatedClassName = "Msvm_ResourceAllocationSettingData"; - - // Private member variable to hold the ManagementScope which is used by the various methods. - private static System.Management.ManagementScope statMgmtScope = null; - - private ManagementSystemProperties PrivateSystemProperties; - - // Underlying lateBound WMI object. - private System.Management.ManagementObject PrivateLateBoundObject; - - // Member variable to store the 'automatic commit' behavior for the class. - private bool AutoCommitProp; - - // Private variable to hold the embedded property representing the instance. - private System.Management.ManagementBaseObject embeddedObj; - - // The current WMI object used - private System.Management.ManagementBaseObject curObj; - - // Flag to indicate if the instance is an embedded object. - private bool isEmbedded; - - // Below are different overloads of constructors to initialize an instance of the class with a WMI object. - public ResourceAllocationSettingData() { - this.InitializeObject(null, null, null); - } - - public ResourceAllocationSettingData(string keyInstanceID) { - this.InitializeObject(null, new System.Management.ManagementPath(ResourceAllocationSettingData.ConstructPath(keyInstanceID)), null); - } - - public ResourceAllocationSettingData(System.Management.ManagementScope mgmtScope, string keyInstanceID) { - this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(ResourceAllocationSettingData.ConstructPath(keyInstanceID)), null); - } - - public ResourceAllocationSettingData(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(null, path, getOptions); - } - - public ResourceAllocationSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { - this.InitializeObject(mgmtScope, path, null); - } - - public ResourceAllocationSettingData(System.Management.ManagementPath path) { - this.InitializeObject(null, path, null); - } - - public ResourceAllocationSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(mgmtScope, path, getOptions); - } - - public ResourceAllocationSettingData(System.Management.ManagementObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - PrivateLateBoundObject = theObject; - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - public ResourceAllocationSettingData(System.Management.ManagementBaseObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - embeddedObj = theObject; - PrivateSystemProperties = new ManagementSystemProperties(theObject); - curObj = embeddedObj; - isEmbedded = true; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - // Property returns the namespace of the WMI class. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OriginatingNamespace { - get { - return "ROOT\\virtualization\\v2"; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ManagementClassName { - get { - string strRet = CreatedClassName; - if ((curObj != null)) { - if ((curObj.ClassPath != null)) { - strRet = ((string)(curObj["__CLASS"])); - if (((strRet == null) - || (strRet == string.Empty))) { - strRet = CreatedClassName; - } - } - } - return strRet; - } - } - - // Property pointing to an embedded object to get System properties of the WMI object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ManagementSystemProperties SystemProperties { - get { - return PrivateSystemProperties; - } - } - - // Property returning the underlying lateBound object. - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementBaseObject LateBoundObject { - get { - return curObj; - } - } - - // ManagementScope of the object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementScope Scope { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Scope; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Scope = value; - } - } - } - - // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool AutoCommit { - get { - return AutoCommitProp; - } - set { - AutoCommitProp = value; - } - } - - // The ManagementPath of the underlying WMI object. - [Browsable(true)] - public System.Management.ManagementPath Path { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Path; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - if ((CheckIfProperClass(null, value, null) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - PrivateLateBoundObject.Path = value; - } - } - } - - // Public static scope property which is used by the various methods. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public static System.Management.ManagementScope StaticScope { - get { - return statMgmtScope; - } - set { - statMgmtScope = value; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Address { - get { - return ((string)(curObj["Address"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string AddressOnParent { - get { - return ((string)(curObj["AddressOnParent"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string AllocationUnits { - get { - return ((string)(curObj["AllocationUnits"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsAutomaticAllocationNull { - get { - if ((curObj["AutomaticAllocation"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool AutomaticAllocation { - get { - if ((curObj["AutomaticAllocation"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["AutomaticAllocation"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsAutomaticDeallocationNull { - get { - if ((curObj["AutomaticDeallocation"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool AutomaticDeallocation { - get { - if ((curObj["AutomaticDeallocation"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["AutomaticDeallocation"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Caption { - get { - return ((string)(curObj["Caption"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] Connection { - get { - return ((string[])(curObj["Connection"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsConsumerVisibilityNull { - get { - if ((curObj["ConsumerVisibility"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort ConsumerVisibility { - get { - if ((curObj["ConsumerVisibility"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["ConsumerVisibility"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Description { - get { - return ((string)(curObj["Description"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ElementName { - get { - return ((string)(curObj["ElementName"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] HostResource { - get { - return ((string[])(curObj["HostResource"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string InstanceID { - get { - return ((string)(curObj["InstanceID"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsLimitNull { - get { - if ((curObj["Limit"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong Limit { - get { - if ((curObj["Limit"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["Limit"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsMappingBehaviorNull { - get { - if ((curObj["MappingBehavior"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort MappingBehavior { - get { - if ((curObj["MappingBehavior"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["MappingBehavior"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OtherResourceType { - get { - return ((string)(curObj["OtherResourceType"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Parent { - get { - return ((string)(curObj["Parent"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string PoolID { - get { - return ((string)(curObj["PoolID"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsReservationNull { - get { - if ((curObj["Reservation"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong Reservation { - get { - if ((curObj["Reservation"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["Reservation"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ResourceSubType { - get { - return ((string)(curObj["ResourceSubType"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsResourceTypeNull { - get { - if ((curObj["ResourceType"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort ResourceType { - get { - if ((curObj["ResourceType"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["ResourceType"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsVirtualQuantityNull { - get { - if ((curObj["VirtualQuantity"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong VirtualQuantity { - get { - if ((curObj["VirtualQuantity"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["VirtualQuantity"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string VirtualQuantityUnits { - get { - return ((string)(curObj["VirtualQuantityUnits"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description(@"A free-form string array of identifiers of this resource presented to the virtual computer system's operating system. These values are only used if the ResourceType property is set to 6 (Parallel SCSI HBA) and the ResourceSubType property is set to ""Microsoft Synthetic SCSI Controller"". This property is set to ""GUID"". -This is a read-only property, but it can be changed using the ModifyVirtualSystemResources method of the Msvm_VirtualSystemManagementService class. -Windows Server 2008: The VirtualSystemIdentifiers property is not supported until Windows Server 2008 R2.")] - public string[] VirtualSystemIdentifiers { - get { - return ((string[])(curObj["VirtualSystemIdentifiers"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsWeightNull { - get { - if ((curObj["Weight"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public uint Weight { - get { - if ((curObj["Weight"] == null)) { - return System.Convert.ToUInt32(0); - } - return ((uint)(curObj["Weight"])); - } - } - - private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { - if (((path != null) - && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); - } - } - - private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { - if (((theObj != null) - && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); - if ((parentClasses != null)) { - int count = 0; - for (count = 0; (count < parentClasses.Length); count = (count + 1)) { - if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { - return true; - } - } - } - } - return false; - } - - private bool ShouldSerializeAutomaticAllocation() { - if ((this.IsAutomaticAllocationNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeAutomaticDeallocation() { - if ((this.IsAutomaticDeallocationNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeConsumerVisibility() { - if ((this.IsConsumerVisibilityNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeLimit() { - if ((this.IsLimitNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeMappingBehavior() { - if ((this.IsMappingBehaviorNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeReservation() { - if ((this.IsReservationNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeResourceType() { - if ((this.IsResourceTypeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeVirtualQuantity() { - if ((this.IsVirtualQuantityNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeWeight() { - if ((this.IsWeightNull == false)) { - return true; - } - return false; - } - - [Browsable(true)] - public void CommitObject() { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(); - } - } - - [Browsable(true)] - public void CommitObject(System.Management.PutOptions putOptions) { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(putOptions); - } - } - - private void Initialize() { - AutoCommitProp = true; - isEmbedded = false; - } - - private static string ConstructPath(string keyInstanceID) { - string strPath = "ROOT\\virtualization\\v2:Msvm_ResourceAllocationSettingData"; - strPath = string.Concat(strPath, string.Concat(".InstanceID=", string.Concat("\"", string.Concat(keyInstanceID, "\"")))); - return strPath; - } - - private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - Initialize(); - if ((path != null)) { - if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - } - PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - - // Different overloads of GetInstances() help in enumerating instances of the WMI class. - public static ResourceAllocationSettingDataCollection GetInstances() { - return GetInstances(null, null, null); - } - - public static ResourceAllocationSettingDataCollection GetInstances(string condition) { - return GetInstances(null, condition, null); - } - - public static ResourceAllocationSettingDataCollection GetInstances(string[] selectedProperties) { - return GetInstances(null, null, selectedProperties); - } - - public static ResourceAllocationSettingDataCollection GetInstances(string condition, string[] selectedProperties) { - return GetInstances(null, condition, selectedProperties); - } - - public static ResourceAllocationSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); - pathObj.ClassName = "Msvm_ResourceAllocationSettingData"; - pathObj.NamespacePath = "root\\virtualization\\v2"; - System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); - if ((enumOptions == null)) { - enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - } - return new ResourceAllocationSettingDataCollection(clsObject.GetInstances(enumOptions)); - } - - public static ResourceAllocationSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { - return GetInstances(mgmtScope, condition, null); - } - - public static ResourceAllocationSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { - return GetInstances(mgmtScope, null, selectedProperties); - } - - public static ResourceAllocationSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_ResourceAllocationSettingData", condition, selectedProperties)); - System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - ObjectSearcher.Options = enumOptions; - return new ResourceAllocationSettingDataCollection(ObjectSearcher.Get()); - } - - [Browsable(true)] - public static ResourceAllocationSettingData CreateInstance() { - System.Management.ManagementScope mgmtScope = null; - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = CreatedWmiNamespace; - } - else { - mgmtScope = statMgmtScope; - } - System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); - System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); - return new ResourceAllocationSettingData(tmpMgmtClass.CreateInstance()); - } - - [Browsable(true)] - public void Delete() { - PrivateLateBoundObject.Delete(); - } - - // Enumerator implementation for enumerating instances of the class. - public class ResourceAllocationSettingDataCollection : object, ICollection { - - private ManagementObjectCollection privColObj; - - public ResourceAllocationSettingDataCollection(ManagementObjectCollection objCollection) { - privColObj = objCollection; - } - - public virtual int Count { - get { - return privColObj.Count; - } - } - - public virtual bool IsSynchronized { - get { - return privColObj.IsSynchronized; - } - } - - public virtual object SyncRoot { - get { - return this; - } - } - - public virtual void CopyTo(System.Array array, int index) { - privColObj.CopyTo(array, index); - int nCtr; - for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { - array.SetValue(new ResourceAllocationSettingData(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); - } - } - - public virtual System.Collections.IEnumerator GetEnumerator() { - return new ResourceAllocationSettingDataEnumerator(privColObj.GetEnumerator()); - } - - public class ResourceAllocationSettingDataEnumerator : object, System.Collections.IEnumerator { - - private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; - - public ResourceAllocationSettingDataEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { - privObjEnum = objEnum; - } - - public virtual object Current { - get { - return new ResourceAllocationSettingData(((System.Management.ManagementObject)(privObjEnum.Current))); - } - } - - public virtual bool MoveNext() { - return privObjEnum.MoveNext(); - } - - public virtual void Reset() { - privObjEnum.Reset(); - } - } - } - - // TypeConverter to handle null values for ValueType properties - public class WMIValueTypeConverter : TypeConverter { - - private TypeConverter baseConverter; - - private System.Type baseType; - - public WMIValueTypeConverter(System.Type inBaseType) { - baseConverter = TypeDescriptor.GetConverter(inBaseType); - baseType = inBaseType; - } - - public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { - return baseConverter.CanConvertFrom(context, srcType); - } - - public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { - return baseConverter.CanConvertTo(context, destinationType); - } - - public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { - return baseConverter.ConvertFrom(context, culture, value); - } - - public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { - return baseConverter.CreateInstance(context, dictionary); - } - - public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetCreateInstanceSupported(context); - } - - public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { - return baseConverter.GetProperties(context, value, attributeVar); - } - - public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetPropertiesSupported(context); - } - - public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValues(context); - } - - public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesExclusive(context); - } - - public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesSupported(context); - } - - public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { - if ((baseType.BaseType == typeof(System.Enum))) { - if ((value.GetType() == destinationType)) { - return value; - } - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return "NULL_ENUM_VALUE" ; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((baseType == typeof(bool)) - && (baseType.BaseType == typeof(System.ValueType)))) { - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((context != null) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - } - - // Embedded class to represent WMI system Properties. - [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] - public class ManagementSystemProperties { - - private System.Management.ManagementBaseObject PrivateLateBoundObject; - - public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { - PrivateLateBoundObject = ManagedObject; - } - - [Browsable(true)] - public int GENUS { - get { - return ((int)(PrivateLateBoundObject["__GENUS"])); - } - } - - [Browsable(true)] - public string CLASS { - get { - return ((string)(PrivateLateBoundObject["__CLASS"])); - } - } - - [Browsable(true)] - public string SUPERCLASS { - get { - return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); - } - } - - [Browsable(true)] - public string DYNASTY { - get { - return ((string)(PrivateLateBoundObject["__DYNASTY"])); - } - } - - [Browsable(true)] - public string RELPATH { - get { - return ((string)(PrivateLateBoundObject["__RELPATH"])); - } - } - - [Browsable(true)] - public int PROPERTY_COUNT { - get { - return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); - } - } - - [Browsable(true)] - public string[] DERIVATION { - get { - return ((string[])(PrivateLateBoundObject["__DERIVATION"])); - } - } - - [Browsable(true)] - public string SERVER { - get { - return ((string)(PrivateLateBoundObject["__SERVER"])); - } - } - - [Browsable(true)] - public string NAMESPACE { - get { - return ((string)(PrivateLateBoundObject["__NAMESPACE"])); - } - } - - [Browsable(true)] - public string PATH { - get { - return ((string)(PrivateLateBoundObject["__PATH"])); - } - } - } - } -} +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2 +{ + using System; + using System.ComponentModel; + using System.Management; + using System.Collections; + using System.Globalization; + using System.ComponentModel.Design.Serialization; + using System.Reflection; + + + // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. + // Functions IsNull() are used to check if a property is NULL. + // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. + // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. + // An Early Bound class generated for the WMI class.Msvm_ResourceAllocationSettingData + public class ResourceAllocationSettingData : System.ComponentModel.Component { + + // Private property to hold the WMI namespace in which the class resides. + private static string CreatedWmiNamespace = "ROOT\\virtualization\\v2"; + + // Private property to hold the name of WMI class which created this class. + public static string CreatedClassName = "Msvm_ResourceAllocationSettingData"; + + // Private member variable to hold the ManagementScope which is used by the various methods. + private static System.Management.ManagementScope statMgmtScope = null; + + private ManagementSystemProperties PrivateSystemProperties; + + // Underlying lateBound WMI object. + private System.Management.ManagementObject PrivateLateBoundObject; + + // Member variable to store the 'automatic commit' behavior for the class. + private bool AutoCommitProp; + + // Private variable to hold the embedded property representing the instance. + private System.Management.ManagementBaseObject embeddedObj; + + // The current WMI object used + private System.Management.ManagementBaseObject curObj; + + // Flag to indicate if the instance is an embedded object. + private bool isEmbedded; + + // Below are different overloads of constructors to initialize an instance of the class with a WMI object. + public ResourceAllocationSettingData() { + this.InitializeObject(null, null, null); + } + + public ResourceAllocationSettingData(string keyInstanceID) { + this.InitializeObject(null, new System.Management.ManagementPath(ResourceAllocationSettingData.ConstructPath(keyInstanceID)), null); + } + + public ResourceAllocationSettingData(System.Management.ManagementScope mgmtScope, string keyInstanceID) { + this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(ResourceAllocationSettingData.ConstructPath(keyInstanceID)), null); + } + + public ResourceAllocationSettingData(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(null, path, getOptions); + } + + public ResourceAllocationSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { + this.InitializeObject(mgmtScope, path, null); + } + + public ResourceAllocationSettingData(System.Management.ManagementPath path) { + this.InitializeObject(null, path, null); + } + + public ResourceAllocationSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(mgmtScope, path, getOptions); + } + + public ResourceAllocationSettingData(System.Management.ManagementObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + PrivateLateBoundObject = theObject; + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + public ResourceAllocationSettingData(System.Management.ManagementBaseObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + embeddedObj = theObject; + PrivateSystemProperties = new ManagementSystemProperties(theObject); + curObj = embeddedObj; + isEmbedded = true; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + // Property returns the namespace of the WMI class. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OriginatingNamespace { + get { + return "ROOT\\virtualization\\v2"; + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ManagementClassName { + get { + string strRet = CreatedClassName; + if ((curObj != null)) { + if ((curObj.ClassPath != null)) { + strRet = ((string)(curObj["__CLASS"])); + if (((strRet == null) + || (strRet == string.Empty))) { + strRet = CreatedClassName; + } + } + } + return strRet; + } + } + + // Property pointing to an embedded object to get System properties of the WMI object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ManagementSystemProperties SystemProperties { + get { + return PrivateSystemProperties; + } + } + + // Property returning the underlying lateBound object. + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementBaseObject LateBoundObject { + get { + return curObj; + } + } + + // ManagementScope of the object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementScope Scope { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Scope; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Scope = value; + } + } + } + + // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool AutoCommit { + get { + return AutoCommitProp; + } + set { + AutoCommitProp = value; + } + } + + // The ManagementPath of the underlying WMI object. + [Browsable(true)] + public System.Management.ManagementPath Path { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Path; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + if ((CheckIfProperClass(null, value, null) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + PrivateLateBoundObject.Path = value; + } + } + } + + // Public static scope property which is used by the various methods. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public static System.Management.ManagementScope StaticScope { + get { + return statMgmtScope; + } + set { + statMgmtScope = value; + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Address { + get { + return ((string)(curObj["Address"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string AddressOnParent { + get { + return ((string)(curObj["AddressOnParent"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string AllocationUnits { + get { + return ((string)(curObj["AllocationUnits"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAutomaticAllocationNull { + get { + if ((curObj["AutomaticAllocation"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool AutomaticAllocation { + get { + if ((curObj["AutomaticAllocation"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["AutomaticAllocation"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAutomaticDeallocationNull { + get { + if ((curObj["AutomaticDeallocation"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool AutomaticDeallocation { + get { + if ((curObj["AutomaticDeallocation"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["AutomaticDeallocation"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Caption { + get { + return ((string)(curObj["Caption"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] Connection { + get { + return ((string[])(curObj["Connection"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsConsumerVisibilityNull { + get { + if ((curObj["ConsumerVisibility"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort ConsumerVisibility { + get { + if ((curObj["ConsumerVisibility"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["ConsumerVisibility"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Description { + get { + return ((string)(curObj["Description"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ElementName { + get { + return ((string)(curObj["ElementName"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] HostResource { + get { + return ((string[])(curObj["HostResource"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string InstanceID { + get { + return ((string)(curObj["InstanceID"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsLimitNull { + get { + if ((curObj["Limit"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong Limit { + get { + if ((curObj["Limit"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["Limit"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsMappingBehaviorNull { + get { + if ((curObj["MappingBehavior"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort MappingBehavior { + get { + if ((curObj["MappingBehavior"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["MappingBehavior"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherResourceType { + get { + return ((string)(curObj["OtherResourceType"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Parent { + get { + return ((string)(curObj["Parent"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string PoolID { + get { + return ((string)(curObj["PoolID"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsReservationNull { + get { + if ((curObj["Reservation"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong Reservation { + get { + if ((curObj["Reservation"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["Reservation"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ResourceSubType { + get { + return ((string)(curObj["ResourceSubType"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsResourceTypeNull { + get { + if ((curObj["ResourceType"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort ResourceType { + get { + if ((curObj["ResourceType"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["ResourceType"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsVirtualQuantityNull { + get { + if ((curObj["VirtualQuantity"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong VirtualQuantity { + get { + if ((curObj["VirtualQuantity"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["VirtualQuantity"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string VirtualQuantityUnits { + get { + return ((string)(curObj["VirtualQuantityUnits"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"A free-form string array of identifiers of this resource presented to the virtual computer system's operating system. These values are only used if the ResourceType property is set to 6 (Parallel SCSI HBA) and the ResourceSubType property is set to ""Microsoft Synthetic SCSI Controller"". This property is set to ""GUID"". +This is a read-only property, but it can be changed using the ModifyVirtualSystemResources method of the Msvm_VirtualSystemManagementService class. +Windows Server 2008: The VirtualSystemIdentifiers property is not supported until Windows Server 2008 R2.")] + public string[] VirtualSystemIdentifiers { + get { + return ((string[])(curObj["VirtualSystemIdentifiers"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsWeightNull { + get { + if ((curObj["Weight"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint Weight { + get { + if ((curObj["Weight"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["Weight"])); + } + } + + private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { + if (((path != null) + && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); + } + } + + private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { + if (((theObj != null) + && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); + if ((parentClasses != null)) { + int count = 0; + for (count = 0; (count < parentClasses.Length); count = (count + 1)) { + if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { + return true; + } + } + } + } + return false; + } + + private bool ShouldSerializeAutomaticAllocation() { + if ((this.IsAutomaticAllocationNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeAutomaticDeallocation() { + if ((this.IsAutomaticDeallocationNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeConsumerVisibility() { + if ((this.IsConsumerVisibilityNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeLimit() { + if ((this.IsLimitNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeMappingBehavior() { + if ((this.IsMappingBehaviorNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeReservation() { + if ((this.IsReservationNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeResourceType() { + if ((this.IsResourceTypeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeVirtualQuantity() { + if ((this.IsVirtualQuantityNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeWeight() { + if ((this.IsWeightNull == false)) { + return true; + } + return false; + } + + [Browsable(true)] + public void CommitObject() { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(); + } + } + + [Browsable(true)] + public void CommitObject(System.Management.PutOptions putOptions) { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(putOptions); + } + } + + private void Initialize() { + AutoCommitProp = true; + isEmbedded = false; + } + + private static string ConstructPath(string keyInstanceID) { + string strPath = "ROOT\\virtualization\\v2:Msvm_ResourceAllocationSettingData"; + strPath = string.Concat(strPath, string.Concat(".InstanceID=", string.Concat("\"", string.Concat(keyInstanceID, "\"")))); + return strPath; + } + + private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + Initialize(); + if ((path != null)) { + if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + } + PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + + // Different overloads of GetInstances() help in enumerating instances of the WMI class. + public static ResourceAllocationSettingDataCollection GetInstances() { + return GetInstances(null, null, null); + } + + public static ResourceAllocationSettingDataCollection GetInstances(string condition) { + return GetInstances(null, condition, null); + } + + public static ResourceAllocationSettingDataCollection GetInstances(string[] selectedProperties) { + return GetInstances(null, null, selectedProperties); + } + + public static ResourceAllocationSettingDataCollection GetInstances(string condition, string[] selectedProperties) { + return GetInstances(null, condition, selectedProperties); + } + + public static ResourceAllocationSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); + pathObj.ClassName = "Msvm_ResourceAllocationSettingData"; + pathObj.NamespacePath = "root\\virtualization\\v2"; + System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); + if ((enumOptions == null)) { + enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + } + return new ResourceAllocationSettingDataCollection(clsObject.GetInstances(enumOptions)); + } + + public static ResourceAllocationSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { + return GetInstances(mgmtScope, condition, null); + } + + public static ResourceAllocationSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { + return GetInstances(mgmtScope, null, selectedProperties); + } + + public static ResourceAllocationSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_ResourceAllocationSettingData", condition, selectedProperties)); + System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + ObjectSearcher.Options = enumOptions; + return new ResourceAllocationSettingDataCollection(ObjectSearcher.Get()); + } + + [Browsable(true)] + public static ResourceAllocationSettingData CreateInstance() { + System.Management.ManagementScope mgmtScope = null; + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = CreatedWmiNamespace; + } + else { + mgmtScope = statMgmtScope; + } + System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); + System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); + return new ResourceAllocationSettingData(tmpMgmtClass.CreateInstance()); + } + + [Browsable(true)] + public void Delete() { + PrivateLateBoundObject.Delete(); + } + + // Enumerator implementation for enumerating instances of the class. + public class ResourceAllocationSettingDataCollection : object, ICollection { + + private ManagementObjectCollection privColObj; + + public ResourceAllocationSettingDataCollection(ManagementObjectCollection objCollection) { + privColObj = objCollection; + } + + public virtual int Count { + get { + return privColObj.Count; + } + } + + public virtual bool IsSynchronized { + get { + return privColObj.IsSynchronized; + } + } + + public virtual object SyncRoot { + get { + return this; + } + } + + public virtual void CopyTo(System.Array array, int index) { + privColObj.CopyTo(array, index); + int nCtr; + for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { + array.SetValue(new ResourceAllocationSettingData(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); + } + } + + public virtual System.Collections.IEnumerator GetEnumerator() { + return new ResourceAllocationSettingDataEnumerator(privColObj.GetEnumerator()); + } + + public class ResourceAllocationSettingDataEnumerator : object, System.Collections.IEnumerator { + + private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; + + public ResourceAllocationSettingDataEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { + privObjEnum = objEnum; + } + + public virtual object Current { + get { + return new ResourceAllocationSettingData(((System.Management.ManagementObject)(privObjEnum.Current))); + } + } + + public virtual bool MoveNext() { + return privObjEnum.MoveNext(); + } + + public virtual void Reset() { + privObjEnum.Reset(); + } + } + } + + // TypeConverter to handle null values for ValueType properties + public class WMIValueTypeConverter : TypeConverter { + + private TypeConverter baseConverter; + + private System.Type baseType; + + public WMIValueTypeConverter(System.Type inBaseType) { + baseConverter = TypeDescriptor.GetConverter(inBaseType); + baseType = inBaseType; + } + + public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { + return baseConverter.CanConvertFrom(context, srcType); + } + + public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { + return baseConverter.CanConvertTo(context, destinationType); + } + + public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { + return baseConverter.ConvertFrom(context, culture, value); + } + + public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { + return baseConverter.CreateInstance(context, dictionary); + } + + public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetCreateInstanceSupported(context); + } + + public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { + return baseConverter.GetProperties(context, value, attributeVar); + } + + public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetPropertiesSupported(context); + } + + public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValues(context); + } + + public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesExclusive(context); + } + + public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesSupported(context); + } + + public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { + if ((baseType.BaseType == typeof(System.Enum))) { + if ((value.GetType() == destinationType)) { + return value; + } + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return "NULL_ENUM_VALUE" ; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((baseType == typeof(bool)) + && (baseType.BaseType == typeof(System.ValueType)))) { + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((context != null) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + } + + // Embedded class to represent WMI system Properties. + [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] + public class ManagementSystemProperties { + + private System.Management.ManagementBaseObject PrivateLateBoundObject; + + public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { + PrivateLateBoundObject = ManagedObject; + } + + [Browsable(true)] + public int GENUS { + get { + return ((int)(PrivateLateBoundObject["__GENUS"])); + } + } + + [Browsable(true)] + public string CLASS { + get { + return ((string)(PrivateLateBoundObject["__CLASS"])); + } + } + + [Browsable(true)] + public string SUPERCLASS { + get { + return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); + } + } + + [Browsable(true)] + public string DYNASTY { + get { + return ((string)(PrivateLateBoundObject["__DYNASTY"])); + } + } + + [Browsable(true)] + public string RELPATH { + get { + return ((string)(PrivateLateBoundObject["__RELPATH"])); + } + } + + [Browsable(true)] + public int PROPERTY_COUNT { + get { + return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); + } + } + + [Browsable(true)] + public string[] DERIVATION { + get { + return ((string[])(PrivateLateBoundObject["__DERIVATION"])); + } + } + + [Browsable(true)] + public string SERVER { + get { + return ((string)(PrivateLateBoundObject["__SERVER"])); + } + } + + [Browsable(true)] + public string NAMESPACE { + get { + return ((string)(PrivateLateBoundObject["__NAMESPACE"])); + } + } + + [Browsable(true)] + public string PATH { + get { + return ((string)(PrivateLateBoundObject["__PATH"])); + } + } + } + } +} diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_StorageAllocationSettingData.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_StorageAllocationSettingData.cs index 45f6b06ae4a..b24d2cfcc26 100644 --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_StorageAllocationSettingData.cs +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_StorageAllocationSettingData.cs @@ -1,1214 +1,1214 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2 { - using System; - using System.ComponentModel; - using System.Management; - using System.Collections; - using System.Globalization; - using System.ComponentModel.Design.Serialization; - using System.Reflection; - - - // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. - // Functions IsNull() are used to check if a property is NULL. - // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. - // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. - // An Early Bound class generated for the WMI class.Msvm_StorageAllocationSettingData - public class StorageAllocationSettingData : System.ComponentModel.Component { - - // Private property to hold the WMI namespace in which the class resides. - private static string CreatedWmiNamespace = "ROOT\\virtualization\\v2"; - - // Private property to hold the name of WMI class which created this class. - public static string CreatedClassName = "Msvm_StorageAllocationSettingData"; - - // Private member variable to hold the ManagementScope which is used by the various methods. - private static System.Management.ManagementScope statMgmtScope = null; - - private ManagementSystemProperties PrivateSystemProperties; - - // Underlying lateBound WMI object. - private System.Management.ManagementObject PrivateLateBoundObject; - - // Member variable to store the 'automatic commit' behavior for the class. - private bool AutoCommitProp; - - // Private variable to hold the embedded property representing the instance. - private System.Management.ManagementBaseObject embeddedObj; - - // The current WMI object used - private System.Management.ManagementBaseObject curObj; - - // Flag to indicate if the instance is an embedded object. - private bool isEmbedded; - - // Below are different overloads of constructors to initialize an instance of the class with a WMI object. - public StorageAllocationSettingData() { - this.InitializeObject(null, null, null); - } - - public StorageAllocationSettingData(string keyInstanceID) { - this.InitializeObject(null, new System.Management.ManagementPath(StorageAllocationSettingData.ConstructPath(keyInstanceID)), null); - } - - public StorageAllocationSettingData(System.Management.ManagementScope mgmtScope, string keyInstanceID) { - this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(StorageAllocationSettingData.ConstructPath(keyInstanceID)), null); - } - - public StorageAllocationSettingData(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(null, path, getOptions); - } - - public StorageAllocationSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { - this.InitializeObject(mgmtScope, path, null); - } - - public StorageAllocationSettingData(System.Management.ManagementPath path) { - this.InitializeObject(null, path, null); - } - - public StorageAllocationSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(mgmtScope, path, getOptions); - } - - public StorageAllocationSettingData(System.Management.ManagementObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - PrivateLateBoundObject = theObject; - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - public StorageAllocationSettingData(System.Management.ManagementBaseObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - embeddedObj = theObject; - PrivateSystemProperties = new ManagementSystemProperties(theObject); - curObj = embeddedObj; - isEmbedded = true; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - // Property returns the namespace of the WMI class. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OriginatingNamespace { - get { - return "ROOT\\virtualization\\v2"; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ManagementClassName { - get { - string strRet = CreatedClassName; - if ((curObj != null)) { - if ((curObj.ClassPath != null)) { - strRet = ((string)(curObj["__CLASS"])); - if (((strRet == null) - || (strRet == string.Empty))) { - strRet = CreatedClassName; - } - } - } - return strRet; - } - } - - // Property pointing to an embedded object to get System properties of the WMI object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ManagementSystemProperties SystemProperties { - get { - return PrivateSystemProperties; - } - } - - // Property returning the underlying lateBound object. - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementBaseObject LateBoundObject { - get { - return curObj; - } - } - - // ManagementScope of the object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementScope Scope { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Scope; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Scope = value; - } - } - } - - // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool AutoCommit { - get { - return AutoCommitProp; - } - set { - AutoCommitProp = value; - } - } - - // The ManagementPath of the underlying WMI object. - [Browsable(true)] - public System.Management.ManagementPath Path { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Path; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - if ((CheckIfProperClass(null, value, null) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - PrivateLateBoundObject.Path = value; - } - } - } - - // Public static scope property which is used by the various methods. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public static System.Management.ManagementScope StaticScope { - get { - return statMgmtScope; - } - set { - statMgmtScope = value; - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsAccessNull { - get { - if ((curObj["Access"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort Access { - get { - if ((curObj["Access"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["Access"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Address { - get { - return ((string)(curObj["Address"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string AddressOnParent { - get { - return ((string)(curObj["AddressOnParent"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string AllocationUnits { - get { - return ((string)(curObj["AllocationUnits"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsAutomaticAllocationNull { - get { - if ((curObj["AutomaticAllocation"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool AutomaticAllocation { - get { - if ((curObj["AutomaticAllocation"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["AutomaticAllocation"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsAutomaticDeallocationNull { - get { - if ((curObj["AutomaticDeallocation"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool AutomaticDeallocation { - get { - if ((curObj["AutomaticDeallocation"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["AutomaticDeallocation"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Caption { - get { - return ((string)(curObj["Caption"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] Connection { - get { - return ((string[])(curObj["Connection"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsConsumerVisibilityNull { - get { - if ((curObj["ConsumerVisibility"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort ConsumerVisibility { - get { - if ((curObj["ConsumerVisibility"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["ConsumerVisibility"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Description { - get { - return ((string)(curObj["Description"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ElementName { - get { - return ((string)(curObj["ElementName"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string HostExtentName { - get { - return ((string)(curObj["HostExtentName"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsHostExtentNameFormatNull { - get { - if ((curObj["HostExtentNameFormat"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort HostExtentNameFormat { - get { - if ((curObj["HostExtentNameFormat"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["HostExtentNameFormat"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsHostExtentNameNamespaceNull { - get { - if ((curObj["HostExtentNameNamespace"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort HostExtentNameNamespace { - get { - if ((curObj["HostExtentNameNamespace"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["HostExtentNameNamespace"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsHostExtentStartingAddressNull { - get { - if ((curObj["HostExtentStartingAddress"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong HostExtentStartingAddress { - get { - if ((curObj["HostExtentStartingAddress"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["HostExtentStartingAddress"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] HostResource { - get { - return ((string[])(curObj["HostResource"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsHostResourceBlockSizeNull { - get { - if ((curObj["HostResourceBlockSize"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong HostResourceBlockSize { - get { - if ((curObj["HostResourceBlockSize"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["HostResourceBlockSize"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string InstanceID { - get { - return ((string)(curObj["InstanceID"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsLimitNull { - get { - if ((curObj["Limit"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong Limit { - get { - if ((curObj["Limit"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["Limit"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsMappingBehaviorNull { - get { - if ((curObj["MappingBehavior"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort MappingBehavior { - get { - if ((curObj["MappingBehavior"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["MappingBehavior"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OtherHostExtentNameFormat { - get { - return ((string)(curObj["OtherHostExtentNameFormat"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OtherHostExtentNameNamespace { - get { - return ((string)(curObj["OtherHostExtentNameNamespace"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OtherResourceType { - get { - return ((string)(curObj["OtherResourceType"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Parent { - get { - return ((string)(curObj["Parent"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string PoolID { - get { - return ((string)(curObj["PoolID"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsReservationNull { - get { - if ((curObj["Reservation"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong Reservation { - get { - if ((curObj["Reservation"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["Reservation"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ResourceSubType { - get { - return ((string)(curObj["ResourceSubType"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsResourceTypeNull { - get { - if ((curObj["ResourceType"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort ResourceType { - get { - if ((curObj["ResourceType"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["ResourceType"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsVirtualQuantityNull { - get { - if ((curObj["VirtualQuantity"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong VirtualQuantity { - get { - if ((curObj["VirtualQuantity"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["VirtualQuantity"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string VirtualQuantityUnits { - get { - return ((string)(curObj["VirtualQuantityUnits"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsVirtualResourceBlockSizeNull { - get { - if ((curObj["VirtualResourceBlockSize"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong VirtualResourceBlockSize { - get { - if ((curObj["VirtualResourceBlockSize"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["VirtualResourceBlockSize"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsWeightNull { - get { - if ((curObj["Weight"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public uint Weight { - get { - if ((curObj["Weight"] == null)) { - return System.Convert.ToUInt32(0); - } - return ((uint)(curObj["Weight"])); - } - } - - private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { - if (((path != null) - && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); - } - } - - private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { - if (((theObj != null) - && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); - if ((parentClasses != null)) { - int count = 0; - for (count = 0; (count < parentClasses.Length); count = (count + 1)) { - if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { - return true; - } - } - } - } - return false; - } - - private bool ShouldSerializeAccess() { - if ((this.IsAccessNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeAutomaticAllocation() { - if ((this.IsAutomaticAllocationNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeAutomaticDeallocation() { - if ((this.IsAutomaticDeallocationNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeConsumerVisibility() { - if ((this.IsConsumerVisibilityNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeHostExtentNameFormat() { - if ((this.IsHostExtentNameFormatNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeHostExtentNameNamespace() { - if ((this.IsHostExtentNameNamespaceNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeHostExtentStartingAddress() { - if ((this.IsHostExtentStartingAddressNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeHostResourceBlockSize() { - if ((this.IsHostResourceBlockSizeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeLimit() { - if ((this.IsLimitNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeMappingBehavior() { - if ((this.IsMappingBehaviorNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeReservation() { - if ((this.IsReservationNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeResourceType() { - if ((this.IsResourceTypeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeVirtualQuantity() { - if ((this.IsVirtualQuantityNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeVirtualResourceBlockSize() { - if ((this.IsVirtualResourceBlockSizeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeWeight() { - if ((this.IsWeightNull == false)) { - return true; - } - return false; - } - - [Browsable(true)] - public void CommitObject() { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(); - } - } - - [Browsable(true)] - public void CommitObject(System.Management.PutOptions putOptions) { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(putOptions); - } - } - - private void Initialize() { - AutoCommitProp = true; - isEmbedded = false; - } - - private static string ConstructPath(string keyInstanceID) { - string strPath = "ROOT\\virtualization\\v2:Msvm_StorageAllocationSettingData"; - strPath = string.Concat(strPath, string.Concat(".InstanceID=", string.Concat("\"", string.Concat(keyInstanceID, "\"")))); - return strPath; - } - - private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - Initialize(); - if ((path != null)) { - if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - } - PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - - // Different overloads of GetInstances() help in enumerating instances of the WMI class. - public static StorageAllocationSettingDataCollection GetInstances() { - return GetInstances(null, null, null); - } - - public static StorageAllocationSettingDataCollection GetInstances(string condition) { - return GetInstances(null, condition, null); - } - - public static StorageAllocationSettingDataCollection GetInstances(string[] selectedProperties) { - return GetInstances(null, null, selectedProperties); - } - - public static StorageAllocationSettingDataCollection GetInstances(string condition, string[] selectedProperties) { - return GetInstances(null, condition, selectedProperties); - } - - public static StorageAllocationSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); - pathObj.ClassName = "Msvm_StorageAllocationSettingData"; - pathObj.NamespacePath = "root\\virtualization\\v2"; - System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); - if ((enumOptions == null)) { - enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - } - return new StorageAllocationSettingDataCollection(clsObject.GetInstances(enumOptions)); - } - - public static StorageAllocationSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { - return GetInstances(mgmtScope, condition, null); - } - - public static StorageAllocationSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { - return GetInstances(mgmtScope, null, selectedProperties); - } - - public static StorageAllocationSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_StorageAllocationSettingData", condition, selectedProperties)); - System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - ObjectSearcher.Options = enumOptions; - return new StorageAllocationSettingDataCollection(ObjectSearcher.Get()); - } - - [Browsable(true)] - public static StorageAllocationSettingData CreateInstance() { - System.Management.ManagementScope mgmtScope = null; - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = CreatedWmiNamespace; - } - else { - mgmtScope = statMgmtScope; - } - System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); - System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); - return new StorageAllocationSettingData(tmpMgmtClass.CreateInstance()); - } - - [Browsable(true)] - public void Delete() { - PrivateLateBoundObject.Delete(); - } - - // Enumerator implementation for enumerating instances of the class. - public class StorageAllocationSettingDataCollection : object, ICollection { - - private ManagementObjectCollection privColObj; - - public StorageAllocationSettingDataCollection(ManagementObjectCollection objCollection) { - privColObj = objCollection; - } - - public virtual int Count { - get { - return privColObj.Count; - } - } - - public virtual bool IsSynchronized { - get { - return privColObj.IsSynchronized; - } - } - - public virtual object SyncRoot { - get { - return this; - } - } - - public virtual void CopyTo(System.Array array, int index) { - privColObj.CopyTo(array, index); - int nCtr; - for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { - array.SetValue(new StorageAllocationSettingData(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); - } - } - - public virtual System.Collections.IEnumerator GetEnumerator() { - return new StorageAllocationSettingDataEnumerator(privColObj.GetEnumerator()); - } - - public class StorageAllocationSettingDataEnumerator : object, System.Collections.IEnumerator { - - private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; - - public StorageAllocationSettingDataEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { - privObjEnum = objEnum; - } - - public virtual object Current { - get { - return new StorageAllocationSettingData(((System.Management.ManagementObject)(privObjEnum.Current))); - } - } - - public virtual bool MoveNext() { - return privObjEnum.MoveNext(); - } - - public virtual void Reset() { - privObjEnum.Reset(); - } - } - } - - // TypeConverter to handle null values for ValueType properties - public class WMIValueTypeConverter : TypeConverter { - - private TypeConverter baseConverter; - - private System.Type baseType; - - public WMIValueTypeConverter(System.Type inBaseType) { - baseConverter = TypeDescriptor.GetConverter(inBaseType); - baseType = inBaseType; - } - - public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { - return baseConverter.CanConvertFrom(context, srcType); - } - - public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { - return baseConverter.CanConvertTo(context, destinationType); - } - - public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { - return baseConverter.ConvertFrom(context, culture, value); - } - - public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { - return baseConverter.CreateInstance(context, dictionary); - } - - public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetCreateInstanceSupported(context); - } - - public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { - return baseConverter.GetProperties(context, value, attributeVar); - } - - public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetPropertiesSupported(context); - } - - public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValues(context); - } - - public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesExclusive(context); - } - - public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesSupported(context); - } - - public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { - if ((baseType.BaseType == typeof(System.Enum))) { - if ((value.GetType() == destinationType)) { - return value; - } - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return "NULL_ENUM_VALUE" ; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((baseType == typeof(bool)) - && (baseType.BaseType == typeof(System.ValueType)))) { - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((context != null) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - } - - // Embedded class to represent WMI system Properties. - [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] - public class ManagementSystemProperties { - - private System.Management.ManagementBaseObject PrivateLateBoundObject; - - public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { - PrivateLateBoundObject = ManagedObject; - } - - [Browsable(true)] - public int GENUS { - get { - return ((int)(PrivateLateBoundObject["__GENUS"])); - } - } - - [Browsable(true)] - public string CLASS { - get { - return ((string)(PrivateLateBoundObject["__CLASS"])); - } - } - - [Browsable(true)] - public string SUPERCLASS { - get { - return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); - } - } - - [Browsable(true)] - public string DYNASTY { - get { - return ((string)(PrivateLateBoundObject["__DYNASTY"])); - } - } - - [Browsable(true)] - public string RELPATH { - get { - return ((string)(PrivateLateBoundObject["__RELPATH"])); - } - } - - [Browsable(true)] - public int PROPERTY_COUNT { - get { - return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); - } - } - - [Browsable(true)] - public string[] DERIVATION { - get { - return ((string[])(PrivateLateBoundObject["__DERIVATION"])); - } - } - - [Browsable(true)] - public string SERVER { - get { - return ((string)(PrivateLateBoundObject["__SERVER"])); - } - } - - [Browsable(true)] - public string NAMESPACE { - get { - return ((string)(PrivateLateBoundObject["__NAMESPACE"])); - } - } - - [Browsable(true)] - public string PATH { - get { - return ((string)(PrivateLateBoundObject["__PATH"])); - } - } - } - } -} +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2 { + using System; + using System.ComponentModel; + using System.Management; + using System.Collections; + using System.Globalization; + using System.ComponentModel.Design.Serialization; + using System.Reflection; + + + // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. + // Functions IsNull() are used to check if a property is NULL. + // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. + // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. + // An Early Bound class generated for the WMI class.Msvm_StorageAllocationSettingData + public class StorageAllocationSettingData : System.ComponentModel.Component { + + // Private property to hold the WMI namespace in which the class resides. + private static string CreatedWmiNamespace = "ROOT\\virtualization\\v2"; + + // Private property to hold the name of WMI class which created this class. + public static string CreatedClassName = "Msvm_StorageAllocationSettingData"; + + // Private member variable to hold the ManagementScope which is used by the various methods. + private static System.Management.ManagementScope statMgmtScope = null; + + private ManagementSystemProperties PrivateSystemProperties; + + // Underlying lateBound WMI object. + private System.Management.ManagementObject PrivateLateBoundObject; + + // Member variable to store the 'automatic commit' behavior for the class. + private bool AutoCommitProp; + + // Private variable to hold the embedded property representing the instance. + private System.Management.ManagementBaseObject embeddedObj; + + // The current WMI object used + private System.Management.ManagementBaseObject curObj; + + // Flag to indicate if the instance is an embedded object. + private bool isEmbedded; + + // Below are different overloads of constructors to initialize an instance of the class with a WMI object. + public StorageAllocationSettingData() { + this.InitializeObject(null, null, null); + } + + public StorageAllocationSettingData(string keyInstanceID) { + this.InitializeObject(null, new System.Management.ManagementPath(StorageAllocationSettingData.ConstructPath(keyInstanceID)), null); + } + + public StorageAllocationSettingData(System.Management.ManagementScope mgmtScope, string keyInstanceID) { + this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(StorageAllocationSettingData.ConstructPath(keyInstanceID)), null); + } + + public StorageAllocationSettingData(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(null, path, getOptions); + } + + public StorageAllocationSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { + this.InitializeObject(mgmtScope, path, null); + } + + public StorageAllocationSettingData(System.Management.ManagementPath path) { + this.InitializeObject(null, path, null); + } + + public StorageAllocationSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(mgmtScope, path, getOptions); + } + + public StorageAllocationSettingData(System.Management.ManagementObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + PrivateLateBoundObject = theObject; + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + public StorageAllocationSettingData(System.Management.ManagementBaseObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + embeddedObj = theObject; + PrivateSystemProperties = new ManagementSystemProperties(theObject); + curObj = embeddedObj; + isEmbedded = true; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + // Property returns the namespace of the WMI class. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OriginatingNamespace { + get { + return "ROOT\\virtualization\\v2"; + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ManagementClassName { + get { + string strRet = CreatedClassName; + if ((curObj != null)) { + if ((curObj.ClassPath != null)) { + strRet = ((string)(curObj["__CLASS"])); + if (((strRet == null) + || (strRet == string.Empty))) { + strRet = CreatedClassName; + } + } + } + return strRet; + } + } + + // Property pointing to an embedded object to get System properties of the WMI object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ManagementSystemProperties SystemProperties { + get { + return PrivateSystemProperties; + } + } + + // Property returning the underlying lateBound object. + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementBaseObject LateBoundObject { + get { + return curObj; + } + } + + // ManagementScope of the object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementScope Scope { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Scope; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Scope = value; + } + } + } + + // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool AutoCommit { + get { + return AutoCommitProp; + } + set { + AutoCommitProp = value; + } + } + + // The ManagementPath of the underlying WMI object. + [Browsable(true)] + public System.Management.ManagementPath Path { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Path; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + if ((CheckIfProperClass(null, value, null) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + PrivateLateBoundObject.Path = value; + } + } + } + + // Public static scope property which is used by the various methods. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public static System.Management.ManagementScope StaticScope { + get { + return statMgmtScope; + } + set { + statMgmtScope = value; + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAccessNull { + get { + if ((curObj["Access"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort Access { + get { + if ((curObj["Access"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["Access"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Address { + get { + return ((string)(curObj["Address"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string AddressOnParent { + get { + return ((string)(curObj["AddressOnParent"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string AllocationUnits { + get { + return ((string)(curObj["AllocationUnits"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAutomaticAllocationNull { + get { + if ((curObj["AutomaticAllocation"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool AutomaticAllocation { + get { + if ((curObj["AutomaticAllocation"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["AutomaticAllocation"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAutomaticDeallocationNull { + get { + if ((curObj["AutomaticDeallocation"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool AutomaticDeallocation { + get { + if ((curObj["AutomaticDeallocation"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["AutomaticDeallocation"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Caption { + get { + return ((string)(curObj["Caption"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] Connection { + get { + return ((string[])(curObj["Connection"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsConsumerVisibilityNull { + get { + if ((curObj["ConsumerVisibility"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort ConsumerVisibility { + get { + if ((curObj["ConsumerVisibility"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["ConsumerVisibility"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Description { + get { + return ((string)(curObj["Description"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ElementName { + get { + return ((string)(curObj["ElementName"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string HostExtentName { + get { + return ((string)(curObj["HostExtentName"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsHostExtentNameFormatNull { + get { + if ((curObj["HostExtentNameFormat"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort HostExtentNameFormat { + get { + if ((curObj["HostExtentNameFormat"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["HostExtentNameFormat"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsHostExtentNameNamespaceNull { + get { + if ((curObj["HostExtentNameNamespace"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort HostExtentNameNamespace { + get { + if ((curObj["HostExtentNameNamespace"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["HostExtentNameNamespace"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsHostExtentStartingAddressNull { + get { + if ((curObj["HostExtentStartingAddress"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong HostExtentStartingAddress { + get { + if ((curObj["HostExtentStartingAddress"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["HostExtentStartingAddress"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] HostResource { + get { + return ((string[])(curObj["HostResource"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsHostResourceBlockSizeNull { + get { + if ((curObj["HostResourceBlockSize"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong HostResourceBlockSize { + get { + if ((curObj["HostResourceBlockSize"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["HostResourceBlockSize"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string InstanceID { + get { + return ((string)(curObj["InstanceID"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsLimitNull { + get { + if ((curObj["Limit"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong Limit { + get { + if ((curObj["Limit"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["Limit"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsMappingBehaviorNull { + get { + if ((curObj["MappingBehavior"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort MappingBehavior { + get { + if ((curObj["MappingBehavior"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["MappingBehavior"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherHostExtentNameFormat { + get { + return ((string)(curObj["OtherHostExtentNameFormat"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherHostExtentNameNamespace { + get { + return ((string)(curObj["OtherHostExtentNameNamespace"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherResourceType { + get { + return ((string)(curObj["OtherResourceType"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Parent { + get { + return ((string)(curObj["Parent"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string PoolID { + get { + return ((string)(curObj["PoolID"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsReservationNull { + get { + if ((curObj["Reservation"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong Reservation { + get { + if ((curObj["Reservation"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["Reservation"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ResourceSubType { + get { + return ((string)(curObj["ResourceSubType"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsResourceTypeNull { + get { + if ((curObj["ResourceType"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort ResourceType { + get { + if ((curObj["ResourceType"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["ResourceType"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsVirtualQuantityNull { + get { + if ((curObj["VirtualQuantity"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong VirtualQuantity { + get { + if ((curObj["VirtualQuantity"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["VirtualQuantity"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string VirtualQuantityUnits { + get { + return ((string)(curObj["VirtualQuantityUnits"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsVirtualResourceBlockSizeNull { + get { + if ((curObj["VirtualResourceBlockSize"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong VirtualResourceBlockSize { + get { + if ((curObj["VirtualResourceBlockSize"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["VirtualResourceBlockSize"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsWeightNull { + get { + if ((curObj["Weight"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint Weight { + get { + if ((curObj["Weight"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["Weight"])); + } + } + + private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { + if (((path != null) + && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); + } + } + + private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { + if (((theObj != null) + && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); + if ((parentClasses != null)) { + int count = 0; + for (count = 0; (count < parentClasses.Length); count = (count + 1)) { + if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { + return true; + } + } + } + } + return false; + } + + private bool ShouldSerializeAccess() { + if ((this.IsAccessNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeAutomaticAllocation() { + if ((this.IsAutomaticAllocationNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeAutomaticDeallocation() { + if ((this.IsAutomaticDeallocationNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeConsumerVisibility() { + if ((this.IsConsumerVisibilityNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeHostExtentNameFormat() { + if ((this.IsHostExtentNameFormatNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeHostExtentNameNamespace() { + if ((this.IsHostExtentNameNamespaceNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeHostExtentStartingAddress() { + if ((this.IsHostExtentStartingAddressNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeHostResourceBlockSize() { + if ((this.IsHostResourceBlockSizeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeLimit() { + if ((this.IsLimitNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeMappingBehavior() { + if ((this.IsMappingBehaviorNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeReservation() { + if ((this.IsReservationNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeResourceType() { + if ((this.IsResourceTypeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeVirtualQuantity() { + if ((this.IsVirtualQuantityNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeVirtualResourceBlockSize() { + if ((this.IsVirtualResourceBlockSizeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeWeight() { + if ((this.IsWeightNull == false)) { + return true; + } + return false; + } + + [Browsable(true)] + public void CommitObject() { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(); + } + } + + [Browsable(true)] + public void CommitObject(System.Management.PutOptions putOptions) { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(putOptions); + } + } + + private void Initialize() { + AutoCommitProp = true; + isEmbedded = false; + } + + private static string ConstructPath(string keyInstanceID) { + string strPath = "ROOT\\virtualization\\v2:Msvm_StorageAllocationSettingData"; + strPath = string.Concat(strPath, string.Concat(".InstanceID=", string.Concat("\"", string.Concat(keyInstanceID, "\"")))); + return strPath; + } + + private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + Initialize(); + if ((path != null)) { + if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + } + PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + + // Different overloads of GetInstances() help in enumerating instances of the WMI class. + public static StorageAllocationSettingDataCollection GetInstances() { + return GetInstances(null, null, null); + } + + public static StorageAllocationSettingDataCollection GetInstances(string condition) { + return GetInstances(null, condition, null); + } + + public static StorageAllocationSettingDataCollection GetInstances(string[] selectedProperties) { + return GetInstances(null, null, selectedProperties); + } + + public static StorageAllocationSettingDataCollection GetInstances(string condition, string[] selectedProperties) { + return GetInstances(null, condition, selectedProperties); + } + + public static StorageAllocationSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); + pathObj.ClassName = "Msvm_StorageAllocationSettingData"; + pathObj.NamespacePath = "root\\virtualization\\v2"; + System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); + if ((enumOptions == null)) { + enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + } + return new StorageAllocationSettingDataCollection(clsObject.GetInstances(enumOptions)); + } + + public static StorageAllocationSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { + return GetInstances(mgmtScope, condition, null); + } + + public static StorageAllocationSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { + return GetInstances(mgmtScope, null, selectedProperties); + } + + public static StorageAllocationSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_StorageAllocationSettingData", condition, selectedProperties)); + System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + ObjectSearcher.Options = enumOptions; + return new StorageAllocationSettingDataCollection(ObjectSearcher.Get()); + } + + [Browsable(true)] + public static StorageAllocationSettingData CreateInstance() { + System.Management.ManagementScope mgmtScope = null; + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = CreatedWmiNamespace; + } + else { + mgmtScope = statMgmtScope; + } + System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); + System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); + return new StorageAllocationSettingData(tmpMgmtClass.CreateInstance()); + } + + [Browsable(true)] + public void Delete() { + PrivateLateBoundObject.Delete(); + } + + // Enumerator implementation for enumerating instances of the class. + public class StorageAllocationSettingDataCollection : object, ICollection { + + private ManagementObjectCollection privColObj; + + public StorageAllocationSettingDataCollection(ManagementObjectCollection objCollection) { + privColObj = objCollection; + } + + public virtual int Count { + get { + return privColObj.Count; + } + } + + public virtual bool IsSynchronized { + get { + return privColObj.IsSynchronized; + } + } + + public virtual object SyncRoot { + get { + return this; + } + } + + public virtual void CopyTo(System.Array array, int index) { + privColObj.CopyTo(array, index); + int nCtr; + for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { + array.SetValue(new StorageAllocationSettingData(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); + } + } + + public virtual System.Collections.IEnumerator GetEnumerator() { + return new StorageAllocationSettingDataEnumerator(privColObj.GetEnumerator()); + } + + public class StorageAllocationSettingDataEnumerator : object, System.Collections.IEnumerator { + + private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; + + public StorageAllocationSettingDataEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { + privObjEnum = objEnum; + } + + public virtual object Current { + get { + return new StorageAllocationSettingData(((System.Management.ManagementObject)(privObjEnum.Current))); + } + } + + public virtual bool MoveNext() { + return privObjEnum.MoveNext(); + } + + public virtual void Reset() { + privObjEnum.Reset(); + } + } + } + + // TypeConverter to handle null values for ValueType properties + public class WMIValueTypeConverter : TypeConverter { + + private TypeConverter baseConverter; + + private System.Type baseType; + + public WMIValueTypeConverter(System.Type inBaseType) { + baseConverter = TypeDescriptor.GetConverter(inBaseType); + baseType = inBaseType; + } + + public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { + return baseConverter.CanConvertFrom(context, srcType); + } + + public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { + return baseConverter.CanConvertTo(context, destinationType); + } + + public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { + return baseConverter.ConvertFrom(context, culture, value); + } + + public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { + return baseConverter.CreateInstance(context, dictionary); + } + + public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetCreateInstanceSupported(context); + } + + public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { + return baseConverter.GetProperties(context, value, attributeVar); + } + + public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetPropertiesSupported(context); + } + + public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValues(context); + } + + public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesExclusive(context); + } + + public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesSupported(context); + } + + public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { + if ((baseType.BaseType == typeof(System.Enum))) { + if ((value.GetType() == destinationType)) { + return value; + } + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return "NULL_ENUM_VALUE" ; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((baseType == typeof(bool)) + && (baseType.BaseType == typeof(System.ValueType)))) { + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((context != null) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + } + + // Embedded class to represent WMI system Properties. + [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] + public class ManagementSystemProperties { + + private System.Management.ManagementBaseObject PrivateLateBoundObject; + + public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { + PrivateLateBoundObject = ManagedObject; + } + + [Browsable(true)] + public int GENUS { + get { + return ((int)(PrivateLateBoundObject["__GENUS"])); + } + } + + [Browsable(true)] + public string CLASS { + get { + return ((string)(PrivateLateBoundObject["__CLASS"])); + } + } + + [Browsable(true)] + public string SUPERCLASS { + get { + return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); + } + } + + [Browsable(true)] + public string DYNASTY { + get { + return ((string)(PrivateLateBoundObject["__DYNASTY"])); + } + } + + [Browsable(true)] + public string RELPATH { + get { + return ((string)(PrivateLateBoundObject["__RELPATH"])); + } + } + + [Browsable(true)] + public int PROPERTY_COUNT { + get { + return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); + } + } + + [Browsable(true)] + public string[] DERIVATION { + get { + return ((string[])(PrivateLateBoundObject["__DERIVATION"])); + } + } + + [Browsable(true)] + public string SERVER { + get { + return ((string)(PrivateLateBoundObject["__SERVER"])); + } + } + + [Browsable(true)] + public string NAMESPACE { + get { + return ((string)(PrivateLateBoundObject["__NAMESPACE"])); + } + } + + [Browsable(true)] + public string PATH { + get { + return ((string)(PrivateLateBoundObject["__PATH"])); + } + } + } + } +} diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_SummaryInformation.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_SummaryInformation.cs index 604005be2ff..343f4122eb0 100644 --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_SummaryInformation.cs +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_SummaryInformation.cs @@ -1,1537 +1,1537 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2 { - using System; - using System.ComponentModel; - using System.Management; - using System.Collections; - using System.Globalization; - using System.ComponentModel.Design.Serialization; - using System.Reflection; - - - // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. - // Functions IsNull() are used to check if a property is NULL. - // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. - // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. - // Datetime conversion functions ToDateTime and ToDmtfDateTime are added to the class to convert DMTF datetime to System.DateTime and vice-versa. - // - // - // - // - // If the embedded property is strongly typed then, to strongly type the property to the type of - // the embedded object, you have to do the following things. - // 1. Generate Managed class for the WMI class of the embedded property. This can be done with MgmtClassGen.exe tool or from Server Explorer. - // 2. Include the namespace of the generated class. - // 3. Change the property get/set functions so as return the instance of the Managed class. - // Below is a sample code. - // - // VB Code - // - // - // - // Property name - // Managed class name of Embedded Property - // - // - // - // - // - // - // C# Code - // - // - // - // Managed class name of Embedded property - // Property name - // - // - // - // - // - // - // - // - // - // - // An Early Bound class generated for the WMI class.Msvm_SummaryInformation - public class SummaryInformation : System.ComponentModel.Component { - - // Private property to hold the WMI namespace in which the class resides. - private static string CreatedWmiNamespace = "ROOT\\virtualization\\v2"; - - // Private property to hold the name of WMI class which created this class. - private static string CreatedClassName = "Msvm_SummaryInformation"; - - // Private member variable to hold the ManagementScope which is used by the various methods. - private static System.Management.ManagementScope statMgmtScope = null; - - private ManagementSystemProperties PrivateSystemProperties; - - // Underlying lateBound WMI object. - private System.Management.ManagementObject PrivateLateBoundObject; - - // Member variable to store the 'automatic commit' behavior for the class. - private bool AutoCommitProp; - - // Private variable to hold the embedded property representing the instance. - private System.Management.ManagementBaseObject embeddedObj; - - // The current WMI object used - private System.Management.ManagementBaseObject curObj; - - // Flag to indicate if the instance is an embedded object. - private bool isEmbedded; - - // Below are different overloads of constructors to initialize an instance of the class with a WMI object. - public SummaryInformation() { - this.InitializeObject(null, null, null); - } - - public SummaryInformation(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(null, path, getOptions); - } - - public SummaryInformation(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { - this.InitializeObject(mgmtScope, path, null); - } - - public SummaryInformation(System.Management.ManagementPath path) { - this.InitializeObject(null, path, null); - } - - public SummaryInformation(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(mgmtScope, path, getOptions); - } - - public SummaryInformation(System.Management.ManagementObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - PrivateLateBoundObject = theObject; - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - public SummaryInformation(System.Management.ManagementBaseObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - embeddedObj = theObject; - PrivateSystemProperties = new ManagementSystemProperties(theObject); - curObj = embeddedObj; - isEmbedded = true; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - // Property returns the namespace of the WMI class. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OriginatingNamespace { - get { - return "ROOT\\virtualization\\v2"; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ManagementClassName { - get { - string strRet = CreatedClassName; - if ((curObj != null)) { - if ((curObj.ClassPath != null)) { - strRet = ((string)(curObj["__CLASS"])); - if (((strRet == null) - || (strRet == string.Empty))) { - strRet = CreatedClassName; - } - } - } - return strRet; - } - } - - // Property pointing to an embedded object to get System properties of the WMI object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ManagementSystemProperties SystemProperties { - get { - return PrivateSystemProperties; - } - } - - // Property returning the underlying lateBound object. - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementBaseObject LateBoundObject { - get { - return curObj; - } - } - - // ManagementScope of the object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementScope Scope { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Scope; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Scope = value; - } - } - } - - // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool AutoCommit { - get { - return AutoCommitProp; - } - set { - AutoCommitProp = value; - } - } - - // The ManagementPath of the underlying WMI object. - [Browsable(true)] - public System.Management.ManagementPath Path { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Path; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - if ((CheckIfProperClass(null, value, null) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - PrivateLateBoundObject.Path = value; - } - } - } - - // Public static scope property which is used by the various methods. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public static System.Management.ManagementScope StaticScope { - get { - return statMgmtScope; - } - set { - statMgmtScope = value; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The identifier of the physical graphics processing unit (GPU) allocated to this v" + - "irtual machine (VM). This property only applies to VMs that use RemoteFX.")] - public string AllocatedGPU { - get { - return ((string)(curObj["AllocatedGPU"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsApplicationHealthNull { - get { - if ((curObj["ApplicationHealth"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description(@"The current application health status for the virtual system. This property may be one of the following values: ""OK""; ""Application Critical""; ""Disabled"".For more information, see the documentation for the StatusDescriptions property of the Msvm_HeartbeatComponent class. This property is not valid for instances of Msvm_SummaryInformation representing a virtual system snapshot.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ApplicationHealthValues ApplicationHealth { - get { - if ((curObj["ApplicationHealth"] == null)) { - return ((ApplicationHealthValues)(System.Convert.ToInt32(0))); - } - return ((ApplicationHealthValues)(System.Convert.ToInt32(curObj["ApplicationHealth"]))); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("An array of Msvm_ConcreteJob instances representing any asynchronous operations r" + - "elated to the virtual system which are currently executing. This property is not" + - " valid for instances of Msvm_SummaryInformation representing a virtual system sn" + - "apshot.")] - public System.Management.ManagementBaseObject[] AsynchronousTasks { - get { - return ((System.Management.ManagementBaseObject[])(curObj["AsynchronousTasks"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsAvailableMemoryBufferNull { - get { - if ((curObj["AvailableMemoryBuffer"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The available memory buffer percentage in the virtual system.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public int AvailableMemoryBuffer { - get { - if ((curObj["AvailableMemoryBuffer"] == null)) { - return System.Convert.ToInt32(0); - } - return ((int)(curObj["AvailableMemoryBuffer"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsCreationTimeNull { - get { - if ((curObj["CreationTime"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The time at which the virtual system or snapshot was created.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public System.DateTime CreationTime { - get { - if ((curObj["CreationTime"] != null)) { - return ToDateTime(((string)(curObj["CreationTime"]))); - } - else { - return System.DateTime.MinValue; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The friendly name for the virtual system or snapshot.")] - public string ElementName { - get { - return ((string)(curObj["ElementName"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsEnabledStateNull { - get { - if ((curObj["EnabledState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The current state of the virtual system or snapshot.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort EnabledState { - get { - if ((curObj["EnabledState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["EnabledState"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The name of the guest operating system, if available. If this information is not " + - "available, the value of this property is NULL. This property is not valid for in" + - "stances of Msvm_SummaryInformation representing a virtual system snapshot.")] - public string GuestOperatingSystem { - get { - return ((string)(curObj["GuestOperatingSystem"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsHealthStateNull { - get { - if ((curObj["HealthState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The current health state for the virtual system. This property is not valid for i" + - "nstances of Msvm_SummaryInformation representing a virtual system snapshot.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort HealthState { - get { - if ((curObj["HealthState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["HealthState"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsHeartbeatNull { - get { - if ((curObj["Heartbeat"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description(@"The current heartbeat status for the virtual system. This property may be one of the following values: ""OK""; ""Error""; ""No Contact""; or ""Lost Communication"". For more information, see the documentation for the StatusDescriptions property of the Msvm_HeartbeatComponent class. This property is not valid for instances of Msvm_SummaryInformation representing a virtual system snapshot.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort Heartbeat { - get { - if ((curObj["Heartbeat"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["Heartbeat"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsIntegrationServicesVersionStateNull { - get { - if ((curObj["IntegrationServicesVersionState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("Whether or not the integration services installed in the virtual machine are up t" + - "o date")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public IntegrationServicesVersionStateValues IntegrationServicesVersionState { - get { - if ((curObj["IntegrationServicesVersionState"] == null)) { - return ((IntegrationServicesVersionStateValues)(System.Convert.ToInt32(3))); - } - return ((IntegrationServicesVersionStateValues)(System.Convert.ToInt32(curObj["IntegrationServicesVersionState"]))); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsMemoryAvailableNull { - get { - if ((curObj["MemoryAvailable"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The memory available percentage in the virtual system.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public int MemoryAvailable { - get { - if ((curObj["MemoryAvailable"] == null)) { - return System.Convert.ToInt32(0); - } - return ((int)(curObj["MemoryAvailable"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsMemorySpansPhysicalNumaNodesNull { - get { - if ((curObj["MemorySpansPhysicalNumaNodes"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("Indicates whether or not the memory of the one or more of the virtual non-uniform" + - " memory access (NUMA) nodes of the virtual machine spans multiple physical NUMA " + - "nodes of the hosting computer system.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool MemorySpansPhysicalNumaNodes { - get { - if ((curObj["MemorySpansPhysicalNumaNodes"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["MemorySpansPhysicalNumaNodes"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsMemoryUsageNull { - get { - if ((curObj["MemoryUsage"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The current memory usage of the virtual system. This property is not valid for in" + - "stances of Msvm_SummaryInformation representing a virtual system snapshot.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong MemoryUsage { - get { - if ((curObj["MemoryUsage"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["MemoryUsage"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The unique name for the virtual system or snapshot.")] - public string Name { - get { - return ((string)(curObj["Name"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The notes associated with the virtual system or snapshot.")] - public string Notes { - get { - return ((string)(curObj["Notes"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsNumberOfProcessorsNull { - get { - if ((curObj["NumberOfProcessors"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The total number of virtual processors allocated to the virtual system or snapsho" + - "t.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort NumberOfProcessors { - get { - if ((curObj["NumberOfProcessors"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["NumberOfProcessors"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The current status of the element.")] - public ushort[] OperationalStatus { - get { - return ((ushort[])(curObj["OperationalStatus"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("A string that describes the enabled or disabled state of the element when the Ena" + - "bledState property is set to 1 (\"Other\"). This property must be set to null when" + - " EnabledState is any value other than 1.")] - public string OtherEnabledState { - get { - return ((string)(curObj["OtherEnabledState"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsProcessorLoadNull { - get { - if ((curObj["ProcessorLoad"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The current processor usage of the virtual system. This property is not valid for" + - " instances of Msvm_SummaryInformation representing a virtual system snapshot.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort ProcessorLoad { - get { - if ((curObj["ProcessorLoad"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["ProcessorLoad"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("An array of the previous 100 samples of the processor usage for the virtual syste" + - "m. This property is not valid for instances of Msvm_SummaryInformation represent" + - "ing a virtual system snapshot.")] - public ushort[] ProcessorLoadHistory { - get { - return ((ushort[])(curObj["ProcessorLoadHistory"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsReplicationHealthNull { - get { - if ((curObj["ReplicationHealth"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("Replication health for the virtual machine.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ReplicationHealthValues ReplicationHealth { - get { - if ((curObj["ReplicationHealth"] == null)) { - return ((ReplicationHealthValues)(System.Convert.ToInt32(4))); - } - return ((ReplicationHealthValues)(System.Convert.ToInt32(curObj["ReplicationHealth"]))); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsReplicationModeNull { - get { - if ((curObj["ReplicationMode"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("Identifies replication type for the virtual machine.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ReplicationModeValues ReplicationMode { - get { - if ((curObj["ReplicationMode"] == null)) { - return ((ReplicationModeValues)(System.Convert.ToInt32(4))); - } - return ((ReplicationModeValues)(System.Convert.ToInt32(curObj["ReplicationMode"]))); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsReplicationStateNull { - get { - if ((curObj["ReplicationState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("Replication state for the virtual machine.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ReplicationStateValues ReplicationState { - get { - if ((curObj["ReplicationState"] == null)) { - return ((ReplicationStateValues)(System.Convert.ToInt32(12))); - } - return ((ReplicationStateValues)(System.Convert.ToInt32(curObj["ReplicationState"]))); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("An array of Msvm_VirtualSystemSettingData instances representing the snapshots fo" + - "r the virtual system. This property is not valid for instances of Msvm_SummaryIn" + - "formation representing a virtual system snapshot.")] - public System.Management.ManagementBaseObject[] Snapshots { - get { - return ((System.Management.ManagementBaseObject[])(curObj["Snapshots"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("Strings that describe the various OperationalStatus array values.")] - public string[] StatusDescriptions { - get { - return ((string[])(curObj["StatusDescriptions"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsSwapFilesInUseNull { - get { - if ((curObj["SwapFilesInUse"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("Indecates if smart paging is active.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool SwapFilesInUse { - get { - if ((curObj["SwapFilesInUse"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["SwapFilesInUse"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("Reference to the CIM_ComputerSystem instance representing the test replica virtua" + - "l system for the virtual machine. This property is not valid for instances of Ms" + - "vm_SummaryInformation representing a virtual system snapshot.")] - public System.Management.ManagementPath TestReplicaSystem { - get { - if ((curObj["TestReplicaSystem"] != null)) { - return new System.Management.ManagementPath(curObj["TestReplicaSystem"].ToString()); - } - return null; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("An array containing a small, thumbnail-sized image of the desktop for the virtual" + - " system or snapshot in RGB565 format.")] - public byte[] ThumbnailImage { - get { - return ((byte[])(curObj["ThumbnailImage"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsUpTimeNull { - get { - if ((curObj["UpTime"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The amount of time since the virtual system was last booted. This property is not" + - " valid for instances of Msvm_SummaryInformation representing a virtual system sn" + - "apshot.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong UpTime { - get { - if ((curObj["UpTime"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["UpTime"])); - } - } - - private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { - if (((path != null) - && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); - } - } - - private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { - if (((theObj != null) - && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); - if ((parentClasses != null)) { - int count = 0; - for (count = 0; (count < parentClasses.Length); count = (count + 1)) { - if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { - return true; - } - } - } - } - return false; - } - - private bool ShouldSerializeApplicationHealth() { - if ((this.IsApplicationHealthNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeAvailableMemoryBuffer() { - if ((this.IsAvailableMemoryBufferNull == false)) { - return true; - } - return false; - } - - // Converts a given datetime in DMTF format to System.DateTime object. - static System.DateTime ToDateTime(string dmtfDate) { - System.DateTime initializer = System.DateTime.MinValue; - int year = initializer.Year; - int month = initializer.Month; - int day = initializer.Day; - int hour = initializer.Hour; - int minute = initializer.Minute; - int second = initializer.Second; - long ticks = 0; - string dmtf = dmtfDate; - System.DateTime datetime = System.DateTime.MinValue; - string tempString = string.Empty; - if ((dmtf == null)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtf.Length == 0)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtf.Length != 25)) { - throw new System.ArgumentOutOfRangeException(); - } - try { - tempString = dmtf.Substring(0, 4); - if (("****" != tempString)) { - year = int.Parse(tempString); - } - tempString = dmtf.Substring(4, 2); - if (("**" != tempString)) { - month = int.Parse(tempString); - } - tempString = dmtf.Substring(6, 2); - if (("**" != tempString)) { - day = int.Parse(tempString); - } - tempString = dmtf.Substring(8, 2); - if (("**" != tempString)) { - hour = int.Parse(tempString); - } - tempString = dmtf.Substring(10, 2); - if (("**" != tempString)) { - minute = int.Parse(tempString); - } - tempString = dmtf.Substring(12, 2); - if (("**" != tempString)) { - second = int.Parse(tempString); - } - tempString = dmtf.Substring(15, 6); - if (("******" != tempString)) { - ticks = (long.Parse(tempString) * ((long)((System.TimeSpan.TicksPerMillisecond / 1000)))); - } - if (((((((((year < 0) - || (month < 0)) - || (day < 0)) - || (hour < 0)) - || (minute < 0)) - || (minute < 0)) - || (second < 0)) - || (ticks < 0))) { - throw new System.ArgumentOutOfRangeException(); - } - } - catch (System.Exception e) { - throw new System.ArgumentOutOfRangeException(null, e.Message); - } - datetime = new System.DateTime(year, month, day, hour, minute, second, 0); - datetime = datetime.AddTicks(ticks); - System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(datetime); - int UTCOffset = 0; - int OffsetToBeAdjusted = 0; - long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); - tempString = dmtf.Substring(22, 3); - if ((tempString != "******")) { - tempString = dmtf.Substring(21, 4); - try { - UTCOffset = int.Parse(tempString); - } - catch (System.Exception e) { - throw new System.ArgumentOutOfRangeException(null, e.Message); - } - OffsetToBeAdjusted = ((int)((OffsetMins - UTCOffset))); - datetime = datetime.AddMinutes(((double)(OffsetToBeAdjusted))); - } - return datetime; - } - - // Converts a given System.DateTime object to DMTF datetime format. - static string ToDmtfDateTime(System.DateTime date) { - string utcString = string.Empty; - System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(date); - long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); - if ((System.Math.Abs(OffsetMins) > 999)) { - date = date.ToUniversalTime(); - utcString = "+000"; - } - else { - if ((tickOffset.Ticks >= 0)) { - utcString = string.Concat("+", ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))).ToString().PadLeft(3, '0')); - } - else { - string strTemp = ((long)(OffsetMins)).ToString(); - utcString = string.Concat("-", strTemp.Substring(1, (strTemp.Length - 1)).PadLeft(3, '0')); - } - } - string dmtfDateTime = ((int)(date.Year)).ToString().PadLeft(4, '0'); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Month)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Day)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Hour)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Minute)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Second)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, "."); - System.DateTime dtTemp = new System.DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, 0); - long microsec = ((long)((((date.Ticks - dtTemp.Ticks) - * 1000) - / System.TimeSpan.TicksPerMillisecond))); - string strMicrosec = ((long)(microsec)).ToString(); - if ((strMicrosec.Length > 6)) { - strMicrosec = strMicrosec.Substring(0, 6); - } - dmtfDateTime = string.Concat(dmtfDateTime, strMicrosec.PadLeft(6, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, utcString); - return dmtfDateTime; - } - - private bool ShouldSerializeCreationTime() { - if ((this.IsCreationTimeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeEnabledState() { - if ((this.IsEnabledStateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeHealthState() { - if ((this.IsHealthStateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeHeartbeat() { - if ((this.IsHeartbeatNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeIntegrationServicesVersionState() { - if ((this.IsIntegrationServicesVersionStateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeMemoryAvailable() { - if ((this.IsMemoryAvailableNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeMemorySpansPhysicalNumaNodes() { - if ((this.IsMemorySpansPhysicalNumaNodesNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeMemoryUsage() { - if ((this.IsMemoryUsageNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeNumberOfProcessors() { - if ((this.IsNumberOfProcessorsNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeProcessorLoad() { - if ((this.IsProcessorLoadNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeReplicationHealth() { - if ((this.IsReplicationHealthNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeReplicationMode() { - if ((this.IsReplicationModeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeReplicationState() { - if ((this.IsReplicationStateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeSwapFilesInUse() { - if ((this.IsSwapFilesInUseNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeUpTime() { - if ((this.IsUpTimeNull == false)) { - return true; - } - return false; - } - - [Browsable(true)] - public void CommitObject() { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(); - } - } - - [Browsable(true)] - public void CommitObject(System.Management.PutOptions putOptions) { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(putOptions); - } - } - - private void Initialize() { - AutoCommitProp = true; - isEmbedded = false; - } - - private static string ConstructPath() { - string strPath = "ROOT\\virtualization\\v2:Msvm_SummaryInformation"; - return strPath; - } - - private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - Initialize(); - if ((path != null)) { - if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - } - PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - - // Different overloads of GetInstances() help in enumerating instances of the WMI class. - public static SummaryInformationCollection GetInstances() { - return GetInstances(null, null, null); - } - - public static SummaryInformationCollection GetInstances(string condition) { - return GetInstances(null, condition, null); - } - - public static SummaryInformationCollection GetInstances(string[] selectedProperties) { - return GetInstances(null, null, selectedProperties); - } - - public static SummaryInformationCollection GetInstances(string condition, string[] selectedProperties) { - return GetInstances(null, condition, selectedProperties); - } - - public static SummaryInformationCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); - pathObj.ClassName = "Msvm_SummaryInformation"; - pathObj.NamespacePath = "root\\virtualization\\v2"; - System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); - if ((enumOptions == null)) { - enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - } - return new SummaryInformationCollection(clsObject.GetInstances(enumOptions)); - } - - public static SummaryInformationCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { - return GetInstances(mgmtScope, condition, null); - } - - public static SummaryInformationCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { - return GetInstances(mgmtScope, null, selectedProperties); - } - - public static SummaryInformationCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_SummaryInformation", condition, selectedProperties)); - System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - ObjectSearcher.Options = enumOptions; - return new SummaryInformationCollection(ObjectSearcher.Get()); - } - - [Browsable(true)] - public static SummaryInformation CreateInstance() { - System.Management.ManagementScope mgmtScope = null; - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = CreatedWmiNamespace; - } - else { - mgmtScope = statMgmtScope; - } - System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); - System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); - return new SummaryInformation(tmpMgmtClass.CreateInstance()); - } - - [Browsable(true)] - public void Delete() { - PrivateLateBoundObject.Delete(); - } - - public enum ApplicationHealthValues { - - OK = 2, - - Application_Critical = 32782, - - Disabled = 32896, - - NULL_ENUM_VALUE = 0, - } - - public enum IntegrationServicesVersionStateValues { - - Unknown0 = 0, - - UpToDate = 1, - - Mismatch = 2, - - NULL_ENUM_VALUE = 3, - } - - public enum ReplicationHealthValues { - - Not_applicable = 0, - - Ok = 1, - - Warning = 2, - - Critical = 3, - - NULL_ENUM_VALUE = 4, - } - - public enum ReplicationModeValues { - - None = 0, - - Primary = 1, - - Recovery = 2, - - Test_Replica = 3, - - NULL_ENUM_VALUE = 4, - } - - public enum ReplicationStateValues { - - Disabled = 0, - - Ready_for_replication = 1, - - Waiting_to_complete_initial_replication = 2, - - Replicating = 3, - - Synced_replication_complete = 4, - - Recovered = 5, - - Committed = 6, - - Suspended = 7, - - Critical = 8, - - Waiting_to_start_resynchronization = 9, - - Resynchronizing = 10, - - Resynchronization_suspended = 11, - - NULL_ENUM_VALUE = 12, - } - - // Enumerator implementation for enumerating instances of the class. - public class SummaryInformationCollection : object, ICollection { - - private ManagementObjectCollection privColObj; - - public SummaryInformationCollection(ManagementObjectCollection objCollection) { - privColObj = objCollection; - } - - public virtual int Count { - get { - return privColObj.Count; - } - } - - public virtual bool IsSynchronized { - get { - return privColObj.IsSynchronized; - } - } - - public virtual object SyncRoot { - get { - return this; - } - } - - public virtual void CopyTo(System.Array array, int index) { - privColObj.CopyTo(array, index); - int nCtr; - for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { - array.SetValue(new SummaryInformation(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); - } - } - - public virtual System.Collections.IEnumerator GetEnumerator() { - return new SummaryInformationEnumerator(privColObj.GetEnumerator()); - } - - public class SummaryInformationEnumerator : object, System.Collections.IEnumerator { - - private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; - - public SummaryInformationEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { - privObjEnum = objEnum; - } - - public virtual object Current { - get { - return new SummaryInformation(((System.Management.ManagementObject)(privObjEnum.Current))); - } - } - - public virtual bool MoveNext() { - return privObjEnum.MoveNext(); - } - - public virtual void Reset() { - privObjEnum.Reset(); - } - } - } - - // TypeConverter to handle null values for ValueType properties - public class WMIValueTypeConverter : TypeConverter { - - private TypeConverter baseConverter; - - private System.Type baseType; - - public WMIValueTypeConverter(System.Type inBaseType) { - baseConverter = TypeDescriptor.GetConverter(inBaseType); - baseType = inBaseType; - } - - public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { - return baseConverter.CanConvertFrom(context, srcType); - } - - public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { - return baseConverter.CanConvertTo(context, destinationType); - } - - public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { - return baseConverter.ConvertFrom(context, culture, value); - } - - public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { - return baseConverter.CreateInstance(context, dictionary); - } - - public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetCreateInstanceSupported(context); - } - - public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { - return baseConverter.GetProperties(context, value, attributeVar); - } - - public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetPropertiesSupported(context); - } - - public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValues(context); - } - - public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesExclusive(context); - } - - public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesSupported(context); - } - - public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { - if ((baseType.BaseType == typeof(System.Enum))) { - if ((value.GetType() == destinationType)) { - return value; - } - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return "NULL_ENUM_VALUE" ; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((baseType == typeof(bool)) - && (baseType.BaseType == typeof(System.ValueType)))) { - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((context != null) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - } - - // Embedded class to represent WMI system Properties. - [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] - public class ManagementSystemProperties { - - private System.Management.ManagementBaseObject PrivateLateBoundObject; - - public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { - PrivateLateBoundObject = ManagedObject; - } - - [Browsable(true)] - public int GENUS { - get { - return ((int)(PrivateLateBoundObject["__GENUS"])); - } - } - - [Browsable(true)] - public string CLASS { - get { - return ((string)(PrivateLateBoundObject["__CLASS"])); - } - } - - [Browsable(true)] - public string SUPERCLASS { - get { - return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); - } - } - - [Browsable(true)] - public string DYNASTY { - get { - return ((string)(PrivateLateBoundObject["__DYNASTY"])); - } - } - - [Browsable(true)] - public string RELPATH { - get { - return ((string)(PrivateLateBoundObject["__RELPATH"])); - } - } - - [Browsable(true)] - public int PROPERTY_COUNT { - get { - return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); - } - } - - [Browsable(true)] - public string[] DERIVATION { - get { - return ((string[])(PrivateLateBoundObject["__DERIVATION"])); - } - } - - [Browsable(true)] - public string SERVER { - get { - return ((string)(PrivateLateBoundObject["__SERVER"])); - } - } - - [Browsable(true)] - public string NAMESPACE { - get { - return ((string)(PrivateLateBoundObject["__NAMESPACE"])); - } - } - - [Browsable(true)] - public string PATH { - get { - return ((string)(PrivateLateBoundObject["__PATH"])); - } - } - } - } -} +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2 { + using System; + using System.ComponentModel; + using System.Management; + using System.Collections; + using System.Globalization; + using System.ComponentModel.Design.Serialization; + using System.Reflection; + + + // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. + // Functions IsNull() are used to check if a property is NULL. + // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. + // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. + // Datetime conversion functions ToDateTime and ToDmtfDateTime are added to the class to convert DMTF datetime to System.DateTime and vice-versa. + // + // + // + // + // If the embedded property is strongly typed then, to strongly type the property to the type of + // the embedded object, you have to do the following things. + // 1. Generate Managed class for the WMI class of the embedded property. This can be done with MgmtClassGen.exe tool or from Server Explorer. + // 2. Include the namespace of the generated class. + // 3. Change the property get/set functions so as return the instance of the Managed class. + // Below is a sample code. + // + // VB Code + // + // + // + // Property name + // Managed class name of Embedded Property + // + // + // + // + // + // + // C# Code + // + // + // + // Managed class name of Embedded property + // Property name + // + // + // + // + // + // + // + // + // + // + // An Early Bound class generated for the WMI class.Msvm_SummaryInformation + public class SummaryInformation : System.ComponentModel.Component { + + // Private property to hold the WMI namespace in which the class resides. + private static string CreatedWmiNamespace = "ROOT\\virtualization\\v2"; + + // Private property to hold the name of WMI class which created this class. + private static string CreatedClassName = "Msvm_SummaryInformation"; + + // Private member variable to hold the ManagementScope which is used by the various methods. + private static System.Management.ManagementScope statMgmtScope = null; + + private ManagementSystemProperties PrivateSystemProperties; + + // Underlying lateBound WMI object. + private System.Management.ManagementObject PrivateLateBoundObject; + + // Member variable to store the 'automatic commit' behavior for the class. + private bool AutoCommitProp; + + // Private variable to hold the embedded property representing the instance. + private System.Management.ManagementBaseObject embeddedObj; + + // The current WMI object used + private System.Management.ManagementBaseObject curObj; + + // Flag to indicate if the instance is an embedded object. + private bool isEmbedded; + + // Below are different overloads of constructors to initialize an instance of the class with a WMI object. + public SummaryInformation() { + this.InitializeObject(null, null, null); + } + + public SummaryInformation(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(null, path, getOptions); + } + + public SummaryInformation(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { + this.InitializeObject(mgmtScope, path, null); + } + + public SummaryInformation(System.Management.ManagementPath path) { + this.InitializeObject(null, path, null); + } + + public SummaryInformation(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(mgmtScope, path, getOptions); + } + + public SummaryInformation(System.Management.ManagementObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + PrivateLateBoundObject = theObject; + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + public SummaryInformation(System.Management.ManagementBaseObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + embeddedObj = theObject; + PrivateSystemProperties = new ManagementSystemProperties(theObject); + curObj = embeddedObj; + isEmbedded = true; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + // Property returns the namespace of the WMI class. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OriginatingNamespace { + get { + return "ROOT\\virtualization\\v2"; + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ManagementClassName { + get { + string strRet = CreatedClassName; + if ((curObj != null)) { + if ((curObj.ClassPath != null)) { + strRet = ((string)(curObj["__CLASS"])); + if (((strRet == null) + || (strRet == string.Empty))) { + strRet = CreatedClassName; + } + } + } + return strRet; + } + } + + // Property pointing to an embedded object to get System properties of the WMI object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ManagementSystemProperties SystemProperties { + get { + return PrivateSystemProperties; + } + } + + // Property returning the underlying lateBound object. + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementBaseObject LateBoundObject { + get { + return curObj; + } + } + + // ManagementScope of the object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementScope Scope { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Scope; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Scope = value; + } + } + } + + // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool AutoCommit { + get { + return AutoCommitProp; + } + set { + AutoCommitProp = value; + } + } + + // The ManagementPath of the underlying WMI object. + [Browsable(true)] + public System.Management.ManagementPath Path { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Path; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + if ((CheckIfProperClass(null, value, null) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + PrivateLateBoundObject.Path = value; + } + } + } + + // Public static scope property which is used by the various methods. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public static System.Management.ManagementScope StaticScope { + get { + return statMgmtScope; + } + set { + statMgmtScope = value; + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The identifier of the physical graphics processing unit (GPU) allocated to this v" + + "irtual machine (VM). This property only applies to VMs that use RemoteFX.")] + public string AllocatedGPU { + get { + return ((string)(curObj["AllocatedGPU"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsApplicationHealthNull { + get { + if ((curObj["ApplicationHealth"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"The current application health status for the virtual system. This property may be one of the following values: ""OK""; ""Application Critical""; ""Disabled"".For more information, see the documentation for the StatusDescriptions property of the Msvm_HeartbeatComponent class. This property is not valid for instances of Msvm_SummaryInformation representing a virtual system snapshot.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ApplicationHealthValues ApplicationHealth { + get { + if ((curObj["ApplicationHealth"] == null)) { + return ((ApplicationHealthValues)(System.Convert.ToInt32(0))); + } + return ((ApplicationHealthValues)(System.Convert.ToInt32(curObj["ApplicationHealth"]))); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("An array of Msvm_ConcreteJob instances representing any asynchronous operations r" + + "elated to the virtual system which are currently executing. This property is not" + + " valid for instances of Msvm_SummaryInformation representing a virtual system sn" + + "apshot.")] + public System.Management.ManagementBaseObject[] AsynchronousTasks { + get { + return ((System.Management.ManagementBaseObject[])(curObj["AsynchronousTasks"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAvailableMemoryBufferNull { + get { + if ((curObj["AvailableMemoryBuffer"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The available memory buffer percentage in the virtual system.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public int AvailableMemoryBuffer { + get { + if ((curObj["AvailableMemoryBuffer"] == null)) { + return System.Convert.ToInt32(0); + } + return ((int)(curObj["AvailableMemoryBuffer"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsCreationTimeNull { + get { + if ((curObj["CreationTime"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The time at which the virtual system or snapshot was created.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime CreationTime { + get { + if ((curObj["CreationTime"] != null)) { + return ToDateTime(((string)(curObj["CreationTime"]))); + } + else { + return System.DateTime.MinValue; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The friendly name for the virtual system or snapshot.")] + public string ElementName { + get { + return ((string)(curObj["ElementName"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsEnabledStateNull { + get { + if ((curObj["EnabledState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The current state of the virtual system or snapshot.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort EnabledState { + get { + if ((curObj["EnabledState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["EnabledState"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The name of the guest operating system, if available. If this information is not " + + "available, the value of this property is NULL. This property is not valid for in" + + "stances of Msvm_SummaryInformation representing a virtual system snapshot.")] + public string GuestOperatingSystem { + get { + return ((string)(curObj["GuestOperatingSystem"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsHealthStateNull { + get { + if ((curObj["HealthState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The current health state for the virtual system. This property is not valid for i" + + "nstances of Msvm_SummaryInformation representing a virtual system snapshot.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort HealthState { + get { + if ((curObj["HealthState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["HealthState"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsHeartbeatNull { + get { + if ((curObj["Heartbeat"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"The current heartbeat status for the virtual system. This property may be one of the following values: ""OK""; ""Error""; ""No Contact""; or ""Lost Communication"". For more information, see the documentation for the StatusDescriptions property of the Msvm_HeartbeatComponent class. This property is not valid for instances of Msvm_SummaryInformation representing a virtual system snapshot.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort Heartbeat { + get { + if ((curObj["Heartbeat"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["Heartbeat"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsIntegrationServicesVersionStateNull { + get { + if ((curObj["IntegrationServicesVersionState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Whether or not the integration services installed in the virtual machine are up t" + + "o date")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public IntegrationServicesVersionStateValues IntegrationServicesVersionState { + get { + if ((curObj["IntegrationServicesVersionState"] == null)) { + return ((IntegrationServicesVersionStateValues)(System.Convert.ToInt32(3))); + } + return ((IntegrationServicesVersionStateValues)(System.Convert.ToInt32(curObj["IntegrationServicesVersionState"]))); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsMemoryAvailableNull { + get { + if ((curObj["MemoryAvailable"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The memory available percentage in the virtual system.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public int MemoryAvailable { + get { + if ((curObj["MemoryAvailable"] == null)) { + return System.Convert.ToInt32(0); + } + return ((int)(curObj["MemoryAvailable"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsMemorySpansPhysicalNumaNodesNull { + get { + if ((curObj["MemorySpansPhysicalNumaNodes"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Indicates whether or not the memory of the one or more of the virtual non-uniform" + + " memory access (NUMA) nodes of the virtual machine spans multiple physical NUMA " + + "nodes of the hosting computer system.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool MemorySpansPhysicalNumaNodes { + get { + if ((curObj["MemorySpansPhysicalNumaNodes"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["MemorySpansPhysicalNumaNodes"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsMemoryUsageNull { + get { + if ((curObj["MemoryUsage"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The current memory usage of the virtual system. This property is not valid for in" + + "stances of Msvm_SummaryInformation representing a virtual system snapshot.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong MemoryUsage { + get { + if ((curObj["MemoryUsage"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["MemoryUsage"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The unique name for the virtual system or snapshot.")] + public string Name { + get { + return ((string)(curObj["Name"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The notes associated with the virtual system or snapshot.")] + public string Notes { + get { + return ((string)(curObj["Notes"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsNumberOfProcessorsNull { + get { + if ((curObj["NumberOfProcessors"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The total number of virtual processors allocated to the virtual system or snapsho" + + "t.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort NumberOfProcessors { + get { + if ((curObj["NumberOfProcessors"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["NumberOfProcessors"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The current status of the element.")] + public ushort[] OperationalStatus { + get { + return ((ushort[])(curObj["OperationalStatus"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("A string that describes the enabled or disabled state of the element when the Ena" + + "bledState property is set to 1 (\"Other\"). This property must be set to null when" + + " EnabledState is any value other than 1.")] + public string OtherEnabledState { + get { + return ((string)(curObj["OtherEnabledState"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsProcessorLoadNull { + get { + if ((curObj["ProcessorLoad"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The current processor usage of the virtual system. This property is not valid for" + + " instances of Msvm_SummaryInformation representing a virtual system snapshot.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort ProcessorLoad { + get { + if ((curObj["ProcessorLoad"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["ProcessorLoad"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("An array of the previous 100 samples of the processor usage for the virtual syste" + + "m. This property is not valid for instances of Msvm_SummaryInformation represent" + + "ing a virtual system snapshot.")] + public ushort[] ProcessorLoadHistory { + get { + return ((ushort[])(curObj["ProcessorLoadHistory"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsReplicationHealthNull { + get { + if ((curObj["ReplicationHealth"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Replication health for the virtual machine.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ReplicationHealthValues ReplicationHealth { + get { + if ((curObj["ReplicationHealth"] == null)) { + return ((ReplicationHealthValues)(System.Convert.ToInt32(4))); + } + return ((ReplicationHealthValues)(System.Convert.ToInt32(curObj["ReplicationHealth"]))); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsReplicationModeNull { + get { + if ((curObj["ReplicationMode"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Identifies replication type for the virtual machine.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ReplicationModeValues ReplicationMode { + get { + if ((curObj["ReplicationMode"] == null)) { + return ((ReplicationModeValues)(System.Convert.ToInt32(4))); + } + return ((ReplicationModeValues)(System.Convert.ToInt32(curObj["ReplicationMode"]))); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsReplicationStateNull { + get { + if ((curObj["ReplicationState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Replication state for the virtual machine.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ReplicationStateValues ReplicationState { + get { + if ((curObj["ReplicationState"] == null)) { + return ((ReplicationStateValues)(System.Convert.ToInt32(12))); + } + return ((ReplicationStateValues)(System.Convert.ToInt32(curObj["ReplicationState"]))); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("An array of Msvm_VirtualSystemSettingData instances representing the snapshots fo" + + "r the virtual system. This property is not valid for instances of Msvm_SummaryIn" + + "formation representing a virtual system snapshot.")] + public System.Management.ManagementBaseObject[] Snapshots { + get { + return ((System.Management.ManagementBaseObject[])(curObj["Snapshots"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Strings that describe the various OperationalStatus array values.")] + public string[] StatusDescriptions { + get { + return ((string[])(curObj["StatusDescriptions"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsSwapFilesInUseNull { + get { + if ((curObj["SwapFilesInUse"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Indecates if smart paging is active.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool SwapFilesInUse { + get { + if ((curObj["SwapFilesInUse"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["SwapFilesInUse"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Reference to the CIM_ComputerSystem instance representing the test replica virtua" + + "l system for the virtual machine. This property is not valid for instances of Ms" + + "vm_SummaryInformation representing a virtual system snapshot.")] + public System.Management.ManagementPath TestReplicaSystem { + get { + if ((curObj["TestReplicaSystem"] != null)) { + return new System.Management.ManagementPath(curObj["TestReplicaSystem"].ToString()); + } + return null; + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("An array containing a small, thumbnail-sized image of the desktop for the virtual" + + " system or snapshot in RGB565 format.")] + public byte[] ThumbnailImage { + get { + return ((byte[])(curObj["ThumbnailImage"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsUpTimeNull { + get { + if ((curObj["UpTime"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The amount of time since the virtual system was last booted. This property is not" + + " valid for instances of Msvm_SummaryInformation representing a virtual system sn" + + "apshot.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong UpTime { + get { + if ((curObj["UpTime"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["UpTime"])); + } + } + + private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { + if (((path != null) + && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); + } + } + + private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { + if (((theObj != null) + && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); + if ((parentClasses != null)) { + int count = 0; + for (count = 0; (count < parentClasses.Length); count = (count + 1)) { + if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { + return true; + } + } + } + } + return false; + } + + private bool ShouldSerializeApplicationHealth() { + if ((this.IsApplicationHealthNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeAvailableMemoryBuffer() { + if ((this.IsAvailableMemoryBufferNull == false)) { + return true; + } + return false; + } + + // Converts a given datetime in DMTF format to System.DateTime object. + static System.DateTime ToDateTime(string dmtfDate) { + System.DateTime initializer = System.DateTime.MinValue; + int year = initializer.Year; + int month = initializer.Month; + int day = initializer.Day; + int hour = initializer.Hour; + int minute = initializer.Minute; + int second = initializer.Second; + long ticks = 0; + string dmtf = dmtfDate; + System.DateTime datetime = System.DateTime.MinValue; + string tempString = string.Empty; + if ((dmtf == null)) { + throw new System.ArgumentOutOfRangeException(); + } + if ((dmtf.Length == 0)) { + throw new System.ArgumentOutOfRangeException(); + } + if ((dmtf.Length != 25)) { + throw new System.ArgumentOutOfRangeException(); + } + try { + tempString = dmtf.Substring(0, 4); + if (("****" != tempString)) { + year = int.Parse(tempString); + } + tempString = dmtf.Substring(4, 2); + if (("**" != tempString)) { + month = int.Parse(tempString); + } + tempString = dmtf.Substring(6, 2); + if (("**" != tempString)) { + day = int.Parse(tempString); + } + tempString = dmtf.Substring(8, 2); + if (("**" != tempString)) { + hour = int.Parse(tempString); + } + tempString = dmtf.Substring(10, 2); + if (("**" != tempString)) { + minute = int.Parse(tempString); + } + tempString = dmtf.Substring(12, 2); + if (("**" != tempString)) { + second = int.Parse(tempString); + } + tempString = dmtf.Substring(15, 6); + if (("******" != tempString)) { + ticks = (long.Parse(tempString) * ((long)((System.TimeSpan.TicksPerMillisecond / 1000)))); + } + if (((((((((year < 0) + || (month < 0)) + || (day < 0)) + || (hour < 0)) + || (minute < 0)) + || (minute < 0)) + || (second < 0)) + || (ticks < 0))) { + throw new System.ArgumentOutOfRangeException(); + } + } + catch (System.Exception e) { + throw new System.ArgumentOutOfRangeException(null, e.Message); + } + datetime = new System.DateTime(year, month, day, hour, minute, second, 0); + datetime = datetime.AddTicks(ticks); + System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(datetime); + int UTCOffset = 0; + int OffsetToBeAdjusted = 0; + long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); + tempString = dmtf.Substring(22, 3); + if ((tempString != "******")) { + tempString = dmtf.Substring(21, 4); + try { + UTCOffset = int.Parse(tempString); + } + catch (System.Exception e) { + throw new System.ArgumentOutOfRangeException(null, e.Message); + } + OffsetToBeAdjusted = ((int)((OffsetMins - UTCOffset))); + datetime = datetime.AddMinutes(((double)(OffsetToBeAdjusted))); + } + return datetime; + } + + // Converts a given System.DateTime object to DMTF datetime format. + static string ToDmtfDateTime(System.DateTime date) { + string utcString = string.Empty; + System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(date); + long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); + if ((System.Math.Abs(OffsetMins) > 999)) { + date = date.ToUniversalTime(); + utcString = "+000"; + } + else { + if ((tickOffset.Ticks >= 0)) { + utcString = string.Concat("+", ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))).ToString().PadLeft(3, '0')); + } + else { + string strTemp = ((long)(OffsetMins)).ToString(); + utcString = string.Concat("-", strTemp.Substring(1, (strTemp.Length - 1)).PadLeft(3, '0')); + } + } + string dmtfDateTime = ((int)(date.Year)).ToString().PadLeft(4, '0'); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Month)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Day)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Hour)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Minute)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Second)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, "."); + System.DateTime dtTemp = new System.DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, 0); + long microsec = ((long)((((date.Ticks - dtTemp.Ticks) + * 1000) + / System.TimeSpan.TicksPerMillisecond))); + string strMicrosec = ((long)(microsec)).ToString(); + if ((strMicrosec.Length > 6)) { + strMicrosec = strMicrosec.Substring(0, 6); + } + dmtfDateTime = string.Concat(dmtfDateTime, strMicrosec.PadLeft(6, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, utcString); + return dmtfDateTime; + } + + private bool ShouldSerializeCreationTime() { + if ((this.IsCreationTimeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeEnabledState() { + if ((this.IsEnabledStateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeHealthState() { + if ((this.IsHealthStateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeHeartbeat() { + if ((this.IsHeartbeatNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeIntegrationServicesVersionState() { + if ((this.IsIntegrationServicesVersionStateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeMemoryAvailable() { + if ((this.IsMemoryAvailableNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeMemorySpansPhysicalNumaNodes() { + if ((this.IsMemorySpansPhysicalNumaNodesNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeMemoryUsage() { + if ((this.IsMemoryUsageNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeNumberOfProcessors() { + if ((this.IsNumberOfProcessorsNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeProcessorLoad() { + if ((this.IsProcessorLoadNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeReplicationHealth() { + if ((this.IsReplicationHealthNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeReplicationMode() { + if ((this.IsReplicationModeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeReplicationState() { + if ((this.IsReplicationStateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeSwapFilesInUse() { + if ((this.IsSwapFilesInUseNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeUpTime() { + if ((this.IsUpTimeNull == false)) { + return true; + } + return false; + } + + [Browsable(true)] + public void CommitObject() { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(); + } + } + + [Browsable(true)] + public void CommitObject(System.Management.PutOptions putOptions) { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(putOptions); + } + } + + private void Initialize() { + AutoCommitProp = true; + isEmbedded = false; + } + + private static string ConstructPath() { + string strPath = "ROOT\\virtualization\\v2:Msvm_SummaryInformation"; + return strPath; + } + + private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + Initialize(); + if ((path != null)) { + if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + } + PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + + // Different overloads of GetInstances() help in enumerating instances of the WMI class. + public static SummaryInformationCollection GetInstances() { + return GetInstances(null, null, null); + } + + public static SummaryInformationCollection GetInstances(string condition) { + return GetInstances(null, condition, null); + } + + public static SummaryInformationCollection GetInstances(string[] selectedProperties) { + return GetInstances(null, null, selectedProperties); + } + + public static SummaryInformationCollection GetInstances(string condition, string[] selectedProperties) { + return GetInstances(null, condition, selectedProperties); + } + + public static SummaryInformationCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); + pathObj.ClassName = "Msvm_SummaryInformation"; + pathObj.NamespacePath = "root\\virtualization\\v2"; + System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); + if ((enumOptions == null)) { + enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + } + return new SummaryInformationCollection(clsObject.GetInstances(enumOptions)); + } + + public static SummaryInformationCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { + return GetInstances(mgmtScope, condition, null); + } + + public static SummaryInformationCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { + return GetInstances(mgmtScope, null, selectedProperties); + } + + public static SummaryInformationCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_SummaryInformation", condition, selectedProperties)); + System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + ObjectSearcher.Options = enumOptions; + return new SummaryInformationCollection(ObjectSearcher.Get()); + } + + [Browsable(true)] + public static SummaryInformation CreateInstance() { + System.Management.ManagementScope mgmtScope = null; + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = CreatedWmiNamespace; + } + else { + mgmtScope = statMgmtScope; + } + System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); + System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); + return new SummaryInformation(tmpMgmtClass.CreateInstance()); + } + + [Browsable(true)] + public void Delete() { + PrivateLateBoundObject.Delete(); + } + + public enum ApplicationHealthValues { + + OK = 2, + + Application_Critical = 32782, + + Disabled = 32896, + + NULL_ENUM_VALUE = 0, + } + + public enum IntegrationServicesVersionStateValues { + + Unknown0 = 0, + + UpToDate = 1, + + Mismatch = 2, + + NULL_ENUM_VALUE = 3, + } + + public enum ReplicationHealthValues { + + Not_applicable = 0, + + Ok = 1, + + Warning = 2, + + Critical = 3, + + NULL_ENUM_VALUE = 4, + } + + public enum ReplicationModeValues { + + None = 0, + + Primary = 1, + + Recovery = 2, + + Test_Replica = 3, + + NULL_ENUM_VALUE = 4, + } + + public enum ReplicationStateValues { + + Disabled = 0, + + Ready_for_replication = 1, + + Waiting_to_complete_initial_replication = 2, + + Replicating = 3, + + Synced_replication_complete = 4, + + Recovered = 5, + + Committed = 6, + + Suspended = 7, + + Critical = 8, + + Waiting_to_start_resynchronization = 9, + + Resynchronizing = 10, + + Resynchronization_suspended = 11, + + NULL_ENUM_VALUE = 12, + } + + // Enumerator implementation for enumerating instances of the class. + public class SummaryInformationCollection : object, ICollection { + + private ManagementObjectCollection privColObj; + + public SummaryInformationCollection(ManagementObjectCollection objCollection) { + privColObj = objCollection; + } + + public virtual int Count { + get { + return privColObj.Count; + } + } + + public virtual bool IsSynchronized { + get { + return privColObj.IsSynchronized; + } + } + + public virtual object SyncRoot { + get { + return this; + } + } + + public virtual void CopyTo(System.Array array, int index) { + privColObj.CopyTo(array, index); + int nCtr; + for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { + array.SetValue(new SummaryInformation(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); + } + } + + public virtual System.Collections.IEnumerator GetEnumerator() { + return new SummaryInformationEnumerator(privColObj.GetEnumerator()); + } + + public class SummaryInformationEnumerator : object, System.Collections.IEnumerator { + + private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; + + public SummaryInformationEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { + privObjEnum = objEnum; + } + + public virtual object Current { + get { + return new SummaryInformation(((System.Management.ManagementObject)(privObjEnum.Current))); + } + } + + public virtual bool MoveNext() { + return privObjEnum.MoveNext(); + } + + public virtual void Reset() { + privObjEnum.Reset(); + } + } + } + + // TypeConverter to handle null values for ValueType properties + public class WMIValueTypeConverter : TypeConverter { + + private TypeConverter baseConverter; + + private System.Type baseType; + + public WMIValueTypeConverter(System.Type inBaseType) { + baseConverter = TypeDescriptor.GetConverter(inBaseType); + baseType = inBaseType; + } + + public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { + return baseConverter.CanConvertFrom(context, srcType); + } + + public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { + return baseConverter.CanConvertTo(context, destinationType); + } + + public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { + return baseConverter.ConvertFrom(context, culture, value); + } + + public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { + return baseConverter.CreateInstance(context, dictionary); + } + + public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetCreateInstanceSupported(context); + } + + public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { + return baseConverter.GetProperties(context, value, attributeVar); + } + + public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetPropertiesSupported(context); + } + + public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValues(context); + } + + public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesExclusive(context); + } + + public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesSupported(context); + } + + public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { + if ((baseType.BaseType == typeof(System.Enum))) { + if ((value.GetType() == destinationType)) { + return value; + } + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return "NULL_ENUM_VALUE" ; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((baseType == typeof(bool)) + && (baseType.BaseType == typeof(System.ValueType)))) { + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((context != null) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + } + + // Embedded class to represent WMI system Properties. + [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] + public class ManagementSystemProperties { + + private System.Management.ManagementBaseObject PrivateLateBoundObject; + + public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { + PrivateLateBoundObject = ManagedObject; + } + + [Browsable(true)] + public int GENUS { + get { + return ((int)(PrivateLateBoundObject["__GENUS"])); + } + } + + [Browsable(true)] + public string CLASS { + get { + return ((string)(PrivateLateBoundObject["__CLASS"])); + } + } + + [Browsable(true)] + public string SUPERCLASS { + get { + return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); + } + } + + [Browsable(true)] + public string DYNASTY { + get { + return ((string)(PrivateLateBoundObject["__DYNASTY"])); + } + } + + [Browsable(true)] + public string RELPATH { + get { + return ((string)(PrivateLateBoundObject["__RELPATH"])); + } + } + + [Browsable(true)] + public int PROPERTY_COUNT { + get { + return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); + } + } + + [Browsable(true)] + public string[] DERIVATION { + get { + return ((string[])(PrivateLateBoundObject["__DERIVATION"])); + } + } + + [Browsable(true)] + public string SERVER { + get { + return ((string)(PrivateLateBoundObject["__SERVER"])); + } + } + + [Browsable(true)] + public string NAMESPACE { + get { + return ((string)(PrivateLateBoundObject["__NAMESPACE"])); + } + } + + [Browsable(true)] + public string PATH { + get { + return ((string)(PrivateLateBoundObject["__PATH"])); + } + } + } + } +} diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_SyntheticEthernetPortSettingData.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_SyntheticEthernetPortSettingData.cs index 86be3a9d62a..8759568d6c3 100644 --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_SyntheticEthernetPortSettingData.cs +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_SyntheticEthernetPortSettingData.cs @@ -15,1069 +15,1069 @@ // specific language governing permissions and limitations // under the License. -namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2 { - using System; - using System.ComponentModel; - using System.Management; - using System.Collections; - using System.Globalization; - using System.ComponentModel.Design.Serialization; - using System.Reflection; - - - // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. - // Functions IsNull() are used to check if a property is NULL. - // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. - // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. - // An Early Bound class generated for the WMI class.Msvm_SyntheticEthernetPortSettingData - public class SyntheticEthernetPortSettingData : System.ComponentModel.Component { - - // Private property to hold the WMI namespace in which the class resides. - private static string CreatedWmiNamespace = "ROOT\\virtualization\\v2"; - - // Private property to hold the name of WMI class which created this class. - public static string CreatedClassName = "Msvm_SyntheticEthernetPortSettingData"; - - // Private member variable to hold the ManagementScope which is used by the various methods. - private static System.Management.ManagementScope statMgmtScope = null; - - private ManagementSystemProperties PrivateSystemProperties; - - // Underlying lateBound WMI object. - private System.Management.ManagementObject PrivateLateBoundObject; - - // Member variable to store the 'automatic commit' behavior for the class. - private bool AutoCommitProp; - - // Private variable to hold the embedded property representing the instance. - private System.Management.ManagementBaseObject embeddedObj; - - // The current WMI object used - private System.Management.ManagementBaseObject curObj; - - // Flag to indicate if the instance is an embedded object. - private bool isEmbedded; - - // Below are different overloads of constructors to initialize an instance of the class with a WMI object. - public SyntheticEthernetPortSettingData() { - this.InitializeObject(null, null, null); - } - - public SyntheticEthernetPortSettingData(string keyInstanceID) { - this.InitializeObject(null, new System.Management.ManagementPath(SyntheticEthernetPortSettingData.ConstructPath(keyInstanceID)), null); - } - - public SyntheticEthernetPortSettingData(System.Management.ManagementScope mgmtScope, string keyInstanceID) { - this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(SyntheticEthernetPortSettingData.ConstructPath(keyInstanceID)), null); - } - - public SyntheticEthernetPortSettingData(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(null, path, getOptions); - } - - public SyntheticEthernetPortSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { - this.InitializeObject(mgmtScope, path, null); - } - - public SyntheticEthernetPortSettingData(System.Management.ManagementPath path) { - this.InitializeObject(null, path, null); - } - - public SyntheticEthernetPortSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(mgmtScope, path, getOptions); - } - - public SyntheticEthernetPortSettingData(System.Management.ManagementObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - PrivateLateBoundObject = theObject; - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - public SyntheticEthernetPortSettingData(System.Management.ManagementBaseObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - embeddedObj = theObject; - PrivateSystemProperties = new ManagementSystemProperties(theObject); - curObj = embeddedObj; - isEmbedded = true; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - // Property returns the namespace of the WMI class. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OriginatingNamespace { - get { - return "ROOT\\virtualization\\v2"; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ManagementClassName { - get { - string strRet = CreatedClassName; - if ((curObj != null)) { - if ((curObj.ClassPath != null)) { - strRet = ((string)(curObj["__CLASS"])); - if (((strRet == null) - || (strRet == string.Empty))) { - strRet = CreatedClassName; - } - } - } - return strRet; - } - } - - // Property pointing to an embedded object to get System properties of the WMI object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ManagementSystemProperties SystemProperties { - get { - return PrivateSystemProperties; - } - } - - // Property returning the underlying lateBound object. - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementBaseObject LateBoundObject { - get { - return curObj; - } - } - - // ManagementScope of the object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementScope Scope { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Scope; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Scope = value; - } - } - } - - // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool AutoCommit { - get { - return AutoCommitProp; - } - set { - AutoCommitProp = value; - } - } - - // The ManagementPath of the underlying WMI object. - [Browsable(true)] - public System.Management.ManagementPath Path { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Path; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - if ((CheckIfProperClass(null, value, null) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - PrivateLateBoundObject.Path = value; - } - } - } - - // Public static scope property which is used by the various methods. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public static System.Management.ManagementScope StaticScope { - get { - return statMgmtScope; - } - set { - statMgmtScope = value; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Address { - get { - return ((string)(curObj["Address"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string AddressOnParent { - get { - return ((string)(curObj["AddressOnParent"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string AllocationUnits { - get { - return ((string)(curObj["AllocationUnits"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsAutomaticAllocationNull { - get { - if ((curObj["AutomaticAllocation"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool AutomaticAllocation { - get { - if ((curObj["AutomaticAllocation"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["AutomaticAllocation"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsAutomaticDeallocationNull { - get { - if ((curObj["AutomaticDeallocation"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool AutomaticDeallocation { - get { - if ((curObj["AutomaticDeallocation"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["AutomaticDeallocation"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Caption { - get { - return ((string)(curObj["Caption"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] Connection { - get { - return ((string[])(curObj["Connection"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsConsumerVisibilityNull { - get { - if ((curObj["ConsumerVisibility"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort ConsumerVisibility { - get { - if ((curObj["ConsumerVisibility"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["ConsumerVisibility"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Description { - get { - return ((string)(curObj["Description"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsDesiredVLANEndpointModeNull { - get { - if ((curObj["DesiredVLANEndpointMode"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort DesiredVLANEndpointMode { - get { - if ((curObj["DesiredVLANEndpointMode"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["DesiredVLANEndpointMode"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ElementName { - get { - return ((string)(curObj["ElementName"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] HostResource { - get { - return ((string[])(curObj["HostResource"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string InstanceID { - get { - return ((string)(curObj["InstanceID"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsLimitNull { - get { - if ((curObj["Limit"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong Limit { - get { - if ((curObj["Limit"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["Limit"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsMappingBehaviorNull { - get { - if ((curObj["MappingBehavior"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort MappingBehavior { - get { - if ((curObj["MappingBehavior"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["MappingBehavior"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OtherEndpointMode { - get { - return ((string)(curObj["OtherEndpointMode"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OtherResourceType { - get { - return ((string)(curObj["OtherResourceType"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Parent { - get { - return ((string)(curObj["Parent"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string PoolID { - get { - return ((string)(curObj["PoolID"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsReservationNull { - get { - if ((curObj["Reservation"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong Reservation { - get { - if ((curObj["Reservation"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["Reservation"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ResourceSubType { - get { - return ((string)(curObj["ResourceSubType"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsResourceTypeNull { - get { - if ((curObj["ResourceType"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort ResourceType { - get { - if ((curObj["ResourceType"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["ResourceType"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsStaticMacAddressNull { - get { - if ((curObj["StaticMacAddress"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("Indicates a static MAC address.\nThis is a read-only property, but it can be chang" + - "ed using the ModifyVirtualSystemResources method of the Msvm_VirtualSystemManage" + - "mentService class.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool StaticMacAddress { - get { - if ((curObj["StaticMacAddress"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["StaticMacAddress"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsVirtualQuantityNull { - get { - if ((curObj["VirtualQuantity"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong VirtualQuantity { - get { - if ((curObj["VirtualQuantity"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["VirtualQuantity"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string VirtualQuantityUnits { - get { - return ((string)(curObj["VirtualQuantityUnits"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] +namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2 { + using System; + using System.ComponentModel; + using System.Management; + using System.Collections; + using System.Globalization; + using System.ComponentModel.Design.Serialization; + using System.Reflection; + + + // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. + // Functions IsNull() are used to check if a property is NULL. + // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. + // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. + // An Early Bound class generated for the WMI class.Msvm_SyntheticEthernetPortSettingData + public class SyntheticEthernetPortSettingData : System.ComponentModel.Component { + + // Private property to hold the WMI namespace in which the class resides. + private static string CreatedWmiNamespace = "ROOT\\virtualization\\v2"; + + // Private property to hold the name of WMI class which created this class. + public static string CreatedClassName = "Msvm_SyntheticEthernetPortSettingData"; + + // Private member variable to hold the ManagementScope which is used by the various methods. + private static System.Management.ManagementScope statMgmtScope = null; + + private ManagementSystemProperties PrivateSystemProperties; + + // Underlying lateBound WMI object. + private System.Management.ManagementObject PrivateLateBoundObject; + + // Member variable to store the 'automatic commit' behavior for the class. + private bool AutoCommitProp; + + // Private variable to hold the embedded property representing the instance. + private System.Management.ManagementBaseObject embeddedObj; + + // The current WMI object used + private System.Management.ManagementBaseObject curObj; + + // Flag to indicate if the instance is an embedded object. + private bool isEmbedded; + + // Below are different overloads of constructors to initialize an instance of the class with a WMI object. + public SyntheticEthernetPortSettingData() { + this.InitializeObject(null, null, null); + } + + public SyntheticEthernetPortSettingData(string keyInstanceID) { + this.InitializeObject(null, new System.Management.ManagementPath(SyntheticEthernetPortSettingData.ConstructPath(keyInstanceID)), null); + } + + public SyntheticEthernetPortSettingData(System.Management.ManagementScope mgmtScope, string keyInstanceID) { + this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(SyntheticEthernetPortSettingData.ConstructPath(keyInstanceID)), null); + } + + public SyntheticEthernetPortSettingData(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(null, path, getOptions); + } + + public SyntheticEthernetPortSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { + this.InitializeObject(mgmtScope, path, null); + } + + public SyntheticEthernetPortSettingData(System.Management.ManagementPath path) { + this.InitializeObject(null, path, null); + } + + public SyntheticEthernetPortSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(mgmtScope, path, getOptions); + } + + public SyntheticEthernetPortSettingData(System.Management.ManagementObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + PrivateLateBoundObject = theObject; + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + public SyntheticEthernetPortSettingData(System.Management.ManagementBaseObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + embeddedObj = theObject; + PrivateSystemProperties = new ManagementSystemProperties(theObject); + curObj = embeddedObj; + isEmbedded = true; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + // Property returns the namespace of the WMI class. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OriginatingNamespace { + get { + return "ROOT\\virtualization\\v2"; + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ManagementClassName { + get { + string strRet = CreatedClassName; + if ((curObj != null)) { + if ((curObj.ClassPath != null)) { + strRet = ((string)(curObj["__CLASS"])); + if (((strRet == null) + || (strRet == string.Empty))) { + strRet = CreatedClassName; + } + } + } + return strRet; + } + } + + // Property pointing to an embedded object to get System properties of the WMI object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ManagementSystemProperties SystemProperties { + get { + return PrivateSystemProperties; + } + } + + // Property returning the underlying lateBound object. + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementBaseObject LateBoundObject { + get { + return curObj; + } + } + + // ManagementScope of the object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementScope Scope { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Scope; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Scope = value; + } + } + } + + // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool AutoCommit { + get { + return AutoCommitProp; + } + set { + AutoCommitProp = value; + } + } + + // The ManagementPath of the underlying WMI object. + [Browsable(true)] + public System.Management.ManagementPath Path { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Path; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + if ((CheckIfProperClass(null, value, null) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + PrivateLateBoundObject.Path = value; + } + } + } + + // Public static scope property which is used by the various methods. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public static System.Management.ManagementScope StaticScope { + get { + return statMgmtScope; + } + set { + statMgmtScope = value; + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Address { + get { + return ((string)(curObj["Address"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string AddressOnParent { + get { + return ((string)(curObj["AddressOnParent"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string AllocationUnits { + get { + return ((string)(curObj["AllocationUnits"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAutomaticAllocationNull { + get { + if ((curObj["AutomaticAllocation"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool AutomaticAllocation { + get { + if ((curObj["AutomaticAllocation"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["AutomaticAllocation"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAutomaticDeallocationNull { + get { + if ((curObj["AutomaticDeallocation"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool AutomaticDeallocation { + get { + if ((curObj["AutomaticDeallocation"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["AutomaticDeallocation"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Caption { + get { + return ((string)(curObj["Caption"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] Connection { + get { + return ((string[])(curObj["Connection"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsConsumerVisibilityNull { + get { + if ((curObj["ConsumerVisibility"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort ConsumerVisibility { + get { + if ((curObj["ConsumerVisibility"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["ConsumerVisibility"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Description { + get { + return ((string)(curObj["Description"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsDesiredVLANEndpointModeNull { + get { + if ((curObj["DesiredVLANEndpointMode"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort DesiredVLANEndpointMode { + get { + if ((curObj["DesiredVLANEndpointMode"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["DesiredVLANEndpointMode"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ElementName { + get { + return ((string)(curObj["ElementName"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] HostResource { + get { + return ((string[])(curObj["HostResource"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string InstanceID { + get { + return ((string)(curObj["InstanceID"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsLimitNull { + get { + if ((curObj["Limit"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong Limit { + get { + if ((curObj["Limit"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["Limit"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsMappingBehaviorNull { + get { + if ((curObj["MappingBehavior"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort MappingBehavior { + get { + if ((curObj["MappingBehavior"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["MappingBehavior"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherEndpointMode { + get { + return ((string)(curObj["OtherEndpointMode"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherResourceType { + get { + return ((string)(curObj["OtherResourceType"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Parent { + get { + return ((string)(curObj["Parent"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string PoolID { + get { + return ((string)(curObj["PoolID"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsReservationNull { + get { + if ((curObj["Reservation"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong Reservation { + get { + if ((curObj["Reservation"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["Reservation"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ResourceSubType { + get { + return ((string)(curObj["ResourceSubType"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsResourceTypeNull { + get { + if ((curObj["ResourceType"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort ResourceType { + get { + if ((curObj["ResourceType"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["ResourceType"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsStaticMacAddressNull { + get { + if ((curObj["StaticMacAddress"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Indicates a static MAC address.\nThis is a read-only property, but it can be chang" + + "ed using the ModifyVirtualSystemResources method of the Msvm_VirtualSystemManage" + + "mentService class.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool StaticMacAddress { + get { + if ((curObj["StaticMacAddress"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["StaticMacAddress"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsVirtualQuantityNull { + get { + if ((curObj["VirtualQuantity"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong VirtualQuantity { + get { + if ((curObj["VirtualQuantity"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["VirtualQuantity"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string VirtualQuantityUnits { + get { + return ((string)(curObj["VirtualQuantityUnits"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [Description(@"A free-form string array of identifiers of this resource presented to the virtual computer system's operating system. The indexes and values per index are defined on a per resource basis (that is, for each enumerated ResourceType value). This property is set to ""GUID"". -This is a read-only property, but it can be changed using the ModifyVirtualSystemResources method of the sd class.")] - public string[] VirtualSystemIdentifiers { - get { - return ((string[])(curObj["VirtualSystemIdentifiers"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsWeightNull { - get { - if ((curObj["Weight"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public uint Weight { - get { - if ((curObj["Weight"] == null)) { - return System.Convert.ToUInt32(0); - } - return ((uint)(curObj["Weight"])); - } - } - - private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { - if (((path != null) - && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); - } - } - - private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { - if (((theObj != null) - && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); - if ((parentClasses != null)) { - int count = 0; - for (count = 0; (count < parentClasses.Length); count = (count + 1)) { - if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { - return true; - } - } - } - } - return false; - } - - private bool ShouldSerializeAutomaticAllocation() { - if ((this.IsAutomaticAllocationNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeAutomaticDeallocation() { - if ((this.IsAutomaticDeallocationNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeConsumerVisibility() { - if ((this.IsConsumerVisibilityNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeDesiredVLANEndpointMode() { - if ((this.IsDesiredVLANEndpointModeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeLimit() { - if ((this.IsLimitNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeMappingBehavior() { - if ((this.IsMappingBehaviorNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeReservation() { - if ((this.IsReservationNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeResourceType() { - if ((this.IsResourceTypeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeStaticMacAddress() { - if ((this.IsStaticMacAddressNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeVirtualQuantity() { - if ((this.IsVirtualQuantityNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeWeight() { - if ((this.IsWeightNull == false)) { - return true; - } - return false; - } - - [Browsable(true)] - public void CommitObject() { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(); - } - } - - [Browsable(true)] - public void CommitObject(System.Management.PutOptions putOptions) { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(putOptions); - } - } - - private void Initialize() { - AutoCommitProp = true; - isEmbedded = false; - } - - private static string ConstructPath(string keyInstanceID) { - string strPath = "ROOT\\virtualization\\v2:Msvm_SyntheticEthernetPortSettingData"; - strPath = string.Concat(strPath, string.Concat(".InstanceID=", string.Concat("\"", string.Concat(keyInstanceID, "\"")))); - return strPath; - } - - private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - Initialize(); - if ((path != null)) { - if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - } - PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - - // Different overloads of GetInstances() help in enumerating instances of the WMI class. - public static SyntheticEthernetPortSettingDataCollection GetInstances() { - return GetInstances(null, null, null); - } - - public static SyntheticEthernetPortSettingDataCollection GetInstances(string condition) { - return GetInstances(null, condition, null); - } - - public static SyntheticEthernetPortSettingDataCollection GetInstances(string[] selectedProperties) { - return GetInstances(null, null, selectedProperties); - } - - public static SyntheticEthernetPortSettingDataCollection GetInstances(string condition, string[] selectedProperties) { - return GetInstances(null, condition, selectedProperties); - } - - public static SyntheticEthernetPortSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); - pathObj.ClassName = "Msvm_SyntheticEthernetPortSettingData"; - pathObj.NamespacePath = "root\\virtualization\\v2"; - System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); - if ((enumOptions == null)) { - enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - } - return new SyntheticEthernetPortSettingDataCollection(clsObject.GetInstances(enumOptions)); - } - - public static SyntheticEthernetPortSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { - return GetInstances(mgmtScope, condition, null); - } - - public static SyntheticEthernetPortSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { - return GetInstances(mgmtScope, null, selectedProperties); - } - - public static SyntheticEthernetPortSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_SyntheticEthernetPortSettingData", condition, selectedProperties)); - System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - ObjectSearcher.Options = enumOptions; - return new SyntheticEthernetPortSettingDataCollection(ObjectSearcher.Get()); - } - - [Browsable(true)] - public static SyntheticEthernetPortSettingData CreateInstance() { - System.Management.ManagementScope mgmtScope = null; - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = CreatedWmiNamespace; - } - else { - mgmtScope = statMgmtScope; - } - System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); - System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); - return new SyntheticEthernetPortSettingData(tmpMgmtClass.CreateInstance()); - } - - [Browsable(true)] - public void Delete() { - PrivateLateBoundObject.Delete(); - } - - // Enumerator implementation for enumerating instances of the class. - public class SyntheticEthernetPortSettingDataCollection : object, ICollection { - - private ManagementObjectCollection privColObj; - - public SyntheticEthernetPortSettingDataCollection(ManagementObjectCollection objCollection) { - privColObj = objCollection; - } - - public virtual int Count { - get { - return privColObj.Count; - } - } - - public virtual bool IsSynchronized { - get { - return privColObj.IsSynchronized; - } - } - - public virtual object SyncRoot { - get { - return this; - } - } - - public virtual void CopyTo(System.Array array, int index) { - privColObj.CopyTo(array, index); - int nCtr; - for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { - array.SetValue(new SyntheticEthernetPortSettingData(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); - } - } - - public virtual System.Collections.IEnumerator GetEnumerator() { - return new SyntheticEthernetPortSettingDataEnumerator(privColObj.GetEnumerator()); - } - - public class SyntheticEthernetPortSettingDataEnumerator : object, System.Collections.IEnumerator { - - private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; - - public SyntheticEthernetPortSettingDataEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { - privObjEnum = objEnum; - } - - public virtual object Current { - get { - return new SyntheticEthernetPortSettingData(((System.Management.ManagementObject)(privObjEnum.Current))); - } - } - - public virtual bool MoveNext() { - return privObjEnum.MoveNext(); - } - - public virtual void Reset() { - privObjEnum.Reset(); - } - } - } - - // TypeConverter to handle null values for ValueType properties - public class WMIValueTypeConverter : TypeConverter { - - private TypeConverter baseConverter; - - private System.Type baseType; - - public WMIValueTypeConverter(System.Type inBaseType) { - baseConverter = TypeDescriptor.GetConverter(inBaseType); - baseType = inBaseType; - } - - public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { - return baseConverter.CanConvertFrom(context, srcType); - } - - public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { - return baseConverter.CanConvertTo(context, destinationType); - } - - public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { - return baseConverter.ConvertFrom(context, culture, value); - } - - public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { - return baseConverter.CreateInstance(context, dictionary); - } - - public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetCreateInstanceSupported(context); - } - - public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { - return baseConverter.GetProperties(context, value, attributeVar); - } - - public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetPropertiesSupported(context); - } - - public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValues(context); - } - - public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesExclusive(context); - } - - public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesSupported(context); - } - - public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { - if ((baseType.BaseType == typeof(System.Enum))) { - if ((value.GetType() == destinationType)) { - return value; - } - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return "NULL_ENUM_VALUE" ; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((baseType == typeof(bool)) - && (baseType.BaseType == typeof(System.ValueType)))) { - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((context != null) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - } - - // Embedded class to represent WMI system Properties. - [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] - public class ManagementSystemProperties { - - private System.Management.ManagementBaseObject PrivateLateBoundObject; - - public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { - PrivateLateBoundObject = ManagedObject; - } - - [Browsable(true)] - public int GENUS { - get { - return ((int)(PrivateLateBoundObject["__GENUS"])); - } - } - - [Browsable(true)] - public string CLASS { - get { - return ((string)(PrivateLateBoundObject["__CLASS"])); - } - } - - [Browsable(true)] - public string SUPERCLASS { - get { - return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); - } - } - - [Browsable(true)] - public string DYNASTY { - get { - return ((string)(PrivateLateBoundObject["__DYNASTY"])); - } - } - - [Browsable(true)] - public string RELPATH { - get { - return ((string)(PrivateLateBoundObject["__RELPATH"])); - } - } - - [Browsable(true)] - public int PROPERTY_COUNT { - get { - return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); - } - } - - [Browsable(true)] - public string[] DERIVATION { - get { - return ((string[])(PrivateLateBoundObject["__DERIVATION"])); - } - } - - [Browsable(true)] - public string SERVER { - get { - return ((string)(PrivateLateBoundObject["__SERVER"])); - } - } - - [Browsable(true)] - public string NAMESPACE { - get { - return ((string)(PrivateLateBoundObject["__NAMESPACE"])); - } - } - - [Browsable(true)] - public string PATH { - get { - return ((string)(PrivateLateBoundObject["__PATH"])); - } - } - } - } -} +This is a read-only property, but it can be changed using the ModifyVirtualSystemResources method of the sd class.")] + public string[] VirtualSystemIdentifiers { + get { + return ((string[])(curObj["VirtualSystemIdentifiers"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsWeightNull { + get { + if ((curObj["Weight"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint Weight { + get { + if ((curObj["Weight"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["Weight"])); + } + } + + private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { + if (((path != null) + && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); + } + } + + private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { + if (((theObj != null) + && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); + if ((parentClasses != null)) { + int count = 0; + for (count = 0; (count < parentClasses.Length); count = (count + 1)) { + if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { + return true; + } + } + } + } + return false; + } + + private bool ShouldSerializeAutomaticAllocation() { + if ((this.IsAutomaticAllocationNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeAutomaticDeallocation() { + if ((this.IsAutomaticDeallocationNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeConsumerVisibility() { + if ((this.IsConsumerVisibilityNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeDesiredVLANEndpointMode() { + if ((this.IsDesiredVLANEndpointModeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeLimit() { + if ((this.IsLimitNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeMappingBehavior() { + if ((this.IsMappingBehaviorNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeReservation() { + if ((this.IsReservationNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeResourceType() { + if ((this.IsResourceTypeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeStaticMacAddress() { + if ((this.IsStaticMacAddressNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeVirtualQuantity() { + if ((this.IsVirtualQuantityNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeWeight() { + if ((this.IsWeightNull == false)) { + return true; + } + return false; + } + + [Browsable(true)] + public void CommitObject() { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(); + } + } + + [Browsable(true)] + public void CommitObject(System.Management.PutOptions putOptions) { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(putOptions); + } + } + + private void Initialize() { + AutoCommitProp = true; + isEmbedded = false; + } + + private static string ConstructPath(string keyInstanceID) { + string strPath = "ROOT\\virtualization\\v2:Msvm_SyntheticEthernetPortSettingData"; + strPath = string.Concat(strPath, string.Concat(".InstanceID=", string.Concat("\"", string.Concat(keyInstanceID, "\"")))); + return strPath; + } + + private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + Initialize(); + if ((path != null)) { + if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + } + PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + + // Different overloads of GetInstances() help in enumerating instances of the WMI class. + public static SyntheticEthernetPortSettingDataCollection GetInstances() { + return GetInstances(null, null, null); + } + + public static SyntheticEthernetPortSettingDataCollection GetInstances(string condition) { + return GetInstances(null, condition, null); + } + + public static SyntheticEthernetPortSettingDataCollection GetInstances(string[] selectedProperties) { + return GetInstances(null, null, selectedProperties); + } + + public static SyntheticEthernetPortSettingDataCollection GetInstances(string condition, string[] selectedProperties) { + return GetInstances(null, condition, selectedProperties); + } + + public static SyntheticEthernetPortSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); + pathObj.ClassName = "Msvm_SyntheticEthernetPortSettingData"; + pathObj.NamespacePath = "root\\virtualization\\v2"; + System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); + if ((enumOptions == null)) { + enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + } + return new SyntheticEthernetPortSettingDataCollection(clsObject.GetInstances(enumOptions)); + } + + public static SyntheticEthernetPortSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { + return GetInstances(mgmtScope, condition, null); + } + + public static SyntheticEthernetPortSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { + return GetInstances(mgmtScope, null, selectedProperties); + } + + public static SyntheticEthernetPortSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_SyntheticEthernetPortSettingData", condition, selectedProperties)); + System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + ObjectSearcher.Options = enumOptions; + return new SyntheticEthernetPortSettingDataCollection(ObjectSearcher.Get()); + } + + [Browsable(true)] + public static SyntheticEthernetPortSettingData CreateInstance() { + System.Management.ManagementScope mgmtScope = null; + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = CreatedWmiNamespace; + } + else { + mgmtScope = statMgmtScope; + } + System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); + System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); + return new SyntheticEthernetPortSettingData(tmpMgmtClass.CreateInstance()); + } + + [Browsable(true)] + public void Delete() { + PrivateLateBoundObject.Delete(); + } + + // Enumerator implementation for enumerating instances of the class. + public class SyntheticEthernetPortSettingDataCollection : object, ICollection { + + private ManagementObjectCollection privColObj; + + public SyntheticEthernetPortSettingDataCollection(ManagementObjectCollection objCollection) { + privColObj = objCollection; + } + + public virtual int Count { + get { + return privColObj.Count; + } + } + + public virtual bool IsSynchronized { + get { + return privColObj.IsSynchronized; + } + } + + public virtual object SyncRoot { + get { + return this; + } + } + + public virtual void CopyTo(System.Array array, int index) { + privColObj.CopyTo(array, index); + int nCtr; + for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { + array.SetValue(new SyntheticEthernetPortSettingData(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); + } + } + + public virtual System.Collections.IEnumerator GetEnumerator() { + return new SyntheticEthernetPortSettingDataEnumerator(privColObj.GetEnumerator()); + } + + public class SyntheticEthernetPortSettingDataEnumerator : object, System.Collections.IEnumerator { + + private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; + + public SyntheticEthernetPortSettingDataEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { + privObjEnum = objEnum; + } + + public virtual object Current { + get { + return new SyntheticEthernetPortSettingData(((System.Management.ManagementObject)(privObjEnum.Current))); + } + } + + public virtual bool MoveNext() { + return privObjEnum.MoveNext(); + } + + public virtual void Reset() { + privObjEnum.Reset(); + } + } + } + + // TypeConverter to handle null values for ValueType properties + public class WMIValueTypeConverter : TypeConverter { + + private TypeConverter baseConverter; + + private System.Type baseType; + + public WMIValueTypeConverter(System.Type inBaseType) { + baseConverter = TypeDescriptor.GetConverter(inBaseType); + baseType = inBaseType; + } + + public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { + return baseConverter.CanConvertFrom(context, srcType); + } + + public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { + return baseConverter.CanConvertTo(context, destinationType); + } + + public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { + return baseConverter.ConvertFrom(context, culture, value); + } + + public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { + return baseConverter.CreateInstance(context, dictionary); + } + + public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetCreateInstanceSupported(context); + } + + public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { + return baseConverter.GetProperties(context, value, attributeVar); + } + + public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetPropertiesSupported(context); + } + + public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValues(context); + } + + public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesExclusive(context); + } + + public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesSupported(context); + } + + public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { + if ((baseType.BaseType == typeof(System.Enum))) { + if ((value.GetType() == destinationType)) { + return value; + } + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return "NULL_ENUM_VALUE" ; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((baseType == typeof(bool)) + && (baseType.BaseType == typeof(System.ValueType)))) { + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((context != null) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + } + + // Embedded class to represent WMI system Properties. + [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] + public class ManagementSystemProperties { + + private System.Management.ManagementBaseObject PrivateLateBoundObject; + + public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { + PrivateLateBoundObject = ManagedObject; + } + + [Browsable(true)] + public int GENUS { + get { + return ((int)(PrivateLateBoundObject["__GENUS"])); + } + } + + [Browsable(true)] + public string CLASS { + get { + return ((string)(PrivateLateBoundObject["__CLASS"])); + } + } + + [Browsable(true)] + public string SUPERCLASS { + get { + return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); + } + } + + [Browsable(true)] + public string DYNASTY { + get { + return ((string)(PrivateLateBoundObject["__DYNASTY"])); + } + } + + [Browsable(true)] + public string RELPATH { + get { + return ((string)(PrivateLateBoundObject["__RELPATH"])); + } + } + + [Browsable(true)] + public int PROPERTY_COUNT { + get { + return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); + } + } + + [Browsable(true)] + public string[] DERIVATION { + get { + return ((string[])(PrivateLateBoundObject["__DERIVATION"])); + } + } + + [Browsable(true)] + public string SERVER { + get { + return ((string)(PrivateLateBoundObject["__SERVER"])); + } + } + + [Browsable(true)] + public string NAMESPACE { + get { + return ((string)(PrivateLateBoundObject["__NAMESPACE"])); + } + } + + [Browsable(true)] + public string PATH { + get { + return ((string)(PrivateLateBoundObject["__PATH"])); + } + } + } + } +} diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_VirtualEthernetSwitch.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_VirtualEthernetSwitch.cs index 6ab4069bbe8..28ab749e828 100644 --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_VirtualEthernetSwitch.cs +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_VirtualEthernetSwitch.cs @@ -1,1386 +1,1386 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2 { - using System; - using System.ComponentModel; - using System.Management; - using System.Collections; - using System.Globalization; - using System.ComponentModel.Design.Serialization; - using System.Reflection; - - - // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. - // Functions IsNull() are used to check if a property is NULL. - // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. - // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. - // Datetime conversion functions ToDateTime and ToDmtfDateTime are added to the class to convert DMTF datetime to System.DateTime and vice-versa. - // An Early Bound class generated for the WMI class.Msvm_VirtualEthernetSwitch - public class VirtualEthernetSwitch : System.ComponentModel.Component { - - // Private property to hold the WMI namespace in which the class resides. - private static string CreatedWmiNamespace = "ROOT\\virtualization\\v2"; - - // Private property to hold the name of WMI class which created this class. - public static string CreatedClassName = "Msvm_VirtualEthernetSwitch"; - - // Private member variable to hold the ManagementScope which is used by the various methods. - private static System.Management.ManagementScope statMgmtScope = null; - - private ManagementSystemProperties PrivateSystemProperties; - - // Underlying lateBound WMI object. - private System.Management.ManagementObject PrivateLateBoundObject; - - // Member variable to store the 'automatic commit' behavior for the class. - private bool AutoCommitProp; - - // Private variable to hold the embedded property representing the instance. - private System.Management.ManagementBaseObject embeddedObj; - - // The current WMI object used - private System.Management.ManagementBaseObject curObj; - - // Flag to indicate if the instance is an embedded object. - private bool isEmbedded; - - // Below are different overloads of constructors to initialize an instance of the class with a WMI object. - public VirtualEthernetSwitch() { - this.InitializeObject(null, null, null); - } - - public VirtualEthernetSwitch(string keyCreationClassName, string keyName) { - this.InitializeObject(null, new System.Management.ManagementPath(VirtualEthernetSwitch.ConstructPath(keyCreationClassName, keyName)), null); - } - - public VirtualEthernetSwitch(System.Management.ManagementScope mgmtScope, string keyCreationClassName, string keyName) { - this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(VirtualEthernetSwitch.ConstructPath(keyCreationClassName, keyName)), null); - } - - public VirtualEthernetSwitch(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(null, path, getOptions); - } - - public VirtualEthernetSwitch(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { - this.InitializeObject(mgmtScope, path, null); - } - - public VirtualEthernetSwitch(System.Management.ManagementPath path) { - this.InitializeObject(null, path, null); - } - - public VirtualEthernetSwitch(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(mgmtScope, path, getOptions); - } - - public VirtualEthernetSwitch(System.Management.ManagementObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - PrivateLateBoundObject = theObject; - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - public VirtualEthernetSwitch(System.Management.ManagementBaseObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - embeddedObj = theObject; - PrivateSystemProperties = new ManagementSystemProperties(theObject); - curObj = embeddedObj; - isEmbedded = true; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - // Property returns the namespace of the WMI class. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OriginatingNamespace { - get { - return "ROOT\\virtualization\\v2"; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ManagementClassName { - get { - string strRet = CreatedClassName; - if ((curObj != null)) { - if ((curObj.ClassPath != null)) { - strRet = ((string)(curObj["__CLASS"])); - if (((strRet == null) - || (strRet == string.Empty))) { - strRet = CreatedClassName; - } - } - } - return strRet; - } - } - - // Property pointing to an embedded object to get System properties of the WMI object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ManagementSystemProperties SystemProperties { - get { - return PrivateSystemProperties; - } - } - - // Property returning the underlying lateBound object. - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementBaseObject LateBoundObject { - get { - return curObj; - } - } - - // ManagementScope of the object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementScope Scope { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Scope; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Scope = value; - } - } - } - - // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool AutoCommit { - get { - return AutoCommitProp; - } - set { - AutoCommitProp = value; - } - } - - // The ManagementPath of the underlying WMI object. - [Browsable(true)] - public System.Management.ManagementPath Path { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Path; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - if ((CheckIfProperClass(null, value, null) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - PrivateLateBoundObject.Path = value; - } - } - } - - // Public static scope property which is used by the various methods. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public static System.Management.ManagementScope StaticScope { - get { - return statMgmtScope; - } - set { - statMgmtScope = value; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ushort[] AvailableRequestedStates { - get { - return ((ushort[])(curObj["AvailableRequestedStates"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Caption { - get { - return ((string)(curObj["Caption"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsCommunicationStatusNull { - get { - if ((curObj["CommunicationStatus"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort CommunicationStatus { - get { - if ((curObj["CommunicationStatus"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["CommunicationStatus"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string CreationClassName { - get { - return ((string)(curObj["CreationClassName"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ushort[] Dedicated { - get { - return ((ushort[])(curObj["Dedicated"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Description { - get { - return ((string)(curObj["Description"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsDetailedStatusNull { - get { - if ((curObj["DetailedStatus"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort DetailedStatus { - get { - if ((curObj["DetailedStatus"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["DetailedStatus"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ElementName { - get { - return ((string)(curObj["ElementName"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsEnabledDefaultNull { - get { - if ((curObj["EnabledDefault"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort EnabledDefault { - get { - if ((curObj["EnabledDefault"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["EnabledDefault"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsEnabledStateNull { - get { - if ((curObj["EnabledState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort EnabledState { - get { - if ((curObj["EnabledState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["EnabledState"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsHealthStateNull { - get { - if ((curObj["HealthState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort HealthState { - get { - if ((curObj["HealthState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["HealthState"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] IdentifyingDescriptions { - get { - return ((string[])(curObj["IdentifyingDescriptions"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsInstallDateNull { - get { - if ((curObj["InstallDate"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public System.DateTime InstallDate { - get { - if ((curObj["InstallDate"] != null)) { - return ToDateTime(((string)(curObj["InstallDate"]))); - } - else { - return System.DateTime.MinValue; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string InstanceID { - get { - return ((string)(curObj["InstanceID"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsMaxIOVOffloadsNull { - get { - if ((curObj["MaxIOVOffloads"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The maximum number of SR-IOV Virtual Function offloads available on this switch.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public uint MaxIOVOffloads { - get { - if ((curObj["MaxIOVOffloads"] == null)) { - return System.Convert.ToUInt32(0); - } - return ((uint)(curObj["MaxIOVOffloads"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsMaxVMQOffloadsNull { - get { - if ((curObj["MaxVMQOffloads"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The maximum number of VMQ offloads allowed for a port on this switch.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public uint MaxVMQOffloads { - get { - if ((curObj["MaxVMQOffloads"] == null)) { - return System.Convert.ToUInt32(0); - } - return ((uint)(curObj["MaxVMQOffloads"])); - } - set { - curObj["MaxVMQOffloads"] = value; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Name { - get { - return ((string)(curObj["Name"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string NameFormat { - get { - return ((string)(curObj["NameFormat"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsOperatingStatusNull { - get { - if ((curObj["OperatingStatus"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort OperatingStatus { - get { - if ((curObj["OperatingStatus"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["OperatingStatus"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ushort[] OperationalStatus { - get { - return ((ushort[])(curObj["OperationalStatus"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] OtherDedicatedDescriptions { - get { - return ((string[])(curObj["OtherDedicatedDescriptions"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OtherEnabledState { - get { - return ((string)(curObj["OtherEnabledState"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] OtherIdentifyingInfo { - get { - return ((string[])(curObj["OtherIdentifyingInfo"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ushort[] PowerManagementCapabilities { - get { - return ((ushort[])(curObj["PowerManagementCapabilities"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string PrimaryOwnerContact { - get { - return ((string)(curObj["PrimaryOwnerContact"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string PrimaryOwnerName { - get { - return ((string)(curObj["PrimaryOwnerName"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsPrimaryStatusNull { - get { - if ((curObj["PrimaryStatus"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort PrimaryStatus { - get { - if ((curObj["PrimaryStatus"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["PrimaryStatus"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsRequestedStateNull { - get { - if ((curObj["RequestedState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort RequestedState { - get { - if ((curObj["RequestedState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["RequestedState"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsResetCapabilityNull { - get { - if ((curObj["ResetCapability"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort ResetCapability { - get { - if ((curObj["ResetCapability"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["ResetCapability"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] Roles { - get { - return ((string[])(curObj["Roles"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Status { - get { - return ((string)(curObj["Status"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] StatusDescriptions { - get { - return ((string[])(curObj["StatusDescriptions"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsTimeOfLastStateChangeNull { - get { - if ((curObj["TimeOfLastStateChange"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public System.DateTime TimeOfLastStateChange { - get { - if ((curObj["TimeOfLastStateChange"] != null)) { - return ToDateTime(((string)(curObj["TimeOfLastStateChange"]))); - } - else { - return System.DateTime.MinValue; - } - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsTransitioningToStateNull { - get { - if ((curObj["TransitioningToState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort TransitioningToState { - get { - if ((curObj["TransitioningToState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["TransitioningToState"])); - } - } - - private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { - if (((path != null) - && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); - } - } - - private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { - if (((theObj != null) - && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); - if ((parentClasses != null)) { - int count = 0; - for (count = 0; (count < parentClasses.Length); count = (count + 1)) { - if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { - return true; - } - } - } - } - return false; - } - - private bool ShouldSerializeCommunicationStatus() { - if ((this.IsCommunicationStatusNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeDetailedStatus() { - if ((this.IsDetailedStatusNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeEnabledDefault() { - if ((this.IsEnabledDefaultNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeEnabledState() { - if ((this.IsEnabledStateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeHealthState() { - if ((this.IsHealthStateNull == false)) { - return true; - } - return false; - } - - // Converts a given datetime in DMTF format to System.DateTime object. - static System.DateTime ToDateTime(string dmtfDate) { - System.DateTime initializer = System.DateTime.MinValue; - int year = initializer.Year; - int month = initializer.Month; - int day = initializer.Day; - int hour = initializer.Hour; - int minute = initializer.Minute; - int second = initializer.Second; - long ticks = 0; - string dmtf = dmtfDate; - System.DateTime datetime = System.DateTime.MinValue; - string tempString = string.Empty; - if ((dmtf == null)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtf.Length == 0)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtf.Length != 25)) { - throw new System.ArgumentOutOfRangeException(); - } - try { - tempString = dmtf.Substring(0, 4); - if (("****" != tempString)) { - year = int.Parse(tempString); - } - tempString = dmtf.Substring(4, 2); - if (("**" != tempString)) { - month = int.Parse(tempString); - } - tempString = dmtf.Substring(6, 2); - if (("**" != tempString)) { - day = int.Parse(tempString); - } - tempString = dmtf.Substring(8, 2); - if (("**" != tempString)) { - hour = int.Parse(tempString); - } - tempString = dmtf.Substring(10, 2); - if (("**" != tempString)) { - minute = int.Parse(tempString); - } - tempString = dmtf.Substring(12, 2); - if (("**" != tempString)) { - second = int.Parse(tempString); - } - tempString = dmtf.Substring(15, 6); - if (("******" != tempString)) { - ticks = (long.Parse(tempString) * ((long)((System.TimeSpan.TicksPerMillisecond / 1000)))); - } - if (((((((((year < 0) - || (month < 0)) - || (day < 0)) - || (hour < 0)) - || (minute < 0)) - || (minute < 0)) - || (second < 0)) - || (ticks < 0))) { - throw new System.ArgumentOutOfRangeException(); - } - } - catch (System.Exception e) { - throw new System.ArgumentOutOfRangeException(null, e.Message); - } - datetime = new System.DateTime(year, month, day, hour, minute, second, 0); - datetime = datetime.AddTicks(ticks); - System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(datetime); - int UTCOffset = 0; - int OffsetToBeAdjusted = 0; - long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); - tempString = dmtf.Substring(22, 3); - if ((tempString != "******")) { - tempString = dmtf.Substring(21, 4); - try { - UTCOffset = int.Parse(tempString); - } - catch (System.Exception e) { - throw new System.ArgumentOutOfRangeException(null, e.Message); - } - OffsetToBeAdjusted = ((int)((OffsetMins - UTCOffset))); - datetime = datetime.AddMinutes(((double)(OffsetToBeAdjusted))); - } - return datetime; - } - - // Converts a given System.DateTime object to DMTF datetime format. - static string ToDmtfDateTime(System.DateTime date) { - string utcString = string.Empty; - System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(date); - long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); - if ((System.Math.Abs(OffsetMins) > 999)) { - date = date.ToUniversalTime(); - utcString = "+000"; - } - else { - if ((tickOffset.Ticks >= 0)) { - utcString = string.Concat("+", ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))).ToString().PadLeft(3, '0')); - } - else { - string strTemp = ((long)(OffsetMins)).ToString(); - utcString = string.Concat("-", strTemp.Substring(1, (strTemp.Length - 1)).PadLeft(3, '0')); - } - } - string dmtfDateTime = ((int)(date.Year)).ToString().PadLeft(4, '0'); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Month)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Day)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Hour)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Minute)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Second)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, "."); - System.DateTime dtTemp = new System.DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, 0); - long microsec = ((long)((((date.Ticks - dtTemp.Ticks) - * 1000) - / System.TimeSpan.TicksPerMillisecond))); - string strMicrosec = ((long)(microsec)).ToString(); - if ((strMicrosec.Length > 6)) { - strMicrosec = strMicrosec.Substring(0, 6); - } - dmtfDateTime = string.Concat(dmtfDateTime, strMicrosec.PadLeft(6, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, utcString); - return dmtfDateTime; - } - - private bool ShouldSerializeInstallDate() { - if ((this.IsInstallDateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeMaxIOVOffloads() { - if ((this.IsMaxIOVOffloadsNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeMaxVMQOffloads() { - if ((this.IsMaxVMQOffloadsNull == false)) { - return true; - } - return false; - } - - private void ResetMaxVMQOffloads() { - curObj["MaxVMQOffloads"] = null; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - - private bool ShouldSerializeOperatingStatus() { - if ((this.IsOperatingStatusNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializePrimaryStatus() { - if ((this.IsPrimaryStatusNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeRequestedState() { - if ((this.IsRequestedStateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeResetCapability() { - if ((this.IsResetCapabilityNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeTimeOfLastStateChange() { - if ((this.IsTimeOfLastStateChangeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeTransitioningToState() { - if ((this.IsTransitioningToStateNull == false)) { - return true; - } - return false; - } - - [Browsable(true)] - public void CommitObject() { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(); - } - } - - [Browsable(true)] - public void CommitObject(System.Management.PutOptions putOptions) { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(putOptions); - } - } - - private void Initialize() { - AutoCommitProp = true; - isEmbedded = false; - } - - private static string ConstructPath(string keyCreationClassName, string keyName) { - string strPath = "ROOT\\virtualization\\v2:Msvm_VirtualEthernetSwitch"; - strPath = string.Concat(strPath, string.Concat(".CreationClassName=", string.Concat("\"", string.Concat(keyCreationClassName, "\"")))); - strPath = string.Concat(strPath, string.Concat(",Name=", string.Concat("\"", string.Concat(keyName, "\"")))); - return strPath; - } - - private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - Initialize(); - if ((path != null)) { - if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - } - PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - - // Different overloads of GetInstances() help in enumerating instances of the WMI class. - public static VirtualEthernetSwitchCollection GetInstances() { - return GetInstances(null, null, null); - } - - public static VirtualEthernetSwitchCollection GetInstances(string condition) { - return GetInstances(null, condition, null); - } - - public static VirtualEthernetSwitchCollection GetInstances(string[] selectedProperties) { - return GetInstances(null, null, selectedProperties); - } - - public static VirtualEthernetSwitchCollection GetInstances(string condition, string[] selectedProperties) { - return GetInstances(null, condition, selectedProperties); - } - - public static VirtualEthernetSwitchCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); - pathObj.ClassName = "Msvm_VirtualEthernetSwitch"; - pathObj.NamespacePath = "root\\virtualization\\v2"; - System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); - if ((enumOptions == null)) { - enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - } - return new VirtualEthernetSwitchCollection(clsObject.GetInstances(enumOptions)); - } - - public static VirtualEthernetSwitchCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { - return GetInstances(mgmtScope, condition, null); - } - - public static VirtualEthernetSwitchCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { - return GetInstances(mgmtScope, null, selectedProperties); - } - - public static VirtualEthernetSwitchCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_VirtualEthernetSwitch", condition, selectedProperties)); - System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - ObjectSearcher.Options = enumOptions; - return new VirtualEthernetSwitchCollection(ObjectSearcher.Get()); - } - - [Browsable(true)] - public static VirtualEthernetSwitch CreateInstance() { - System.Management.ManagementScope mgmtScope = null; - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = CreatedWmiNamespace; - } - else { - mgmtScope = statMgmtScope; - } - System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); - System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); - return new VirtualEthernetSwitch(tmpMgmtClass.CreateInstance()); - } - - [Browsable(true)] - public void Delete() { - PrivateLateBoundObject.Delete(); - } - - public uint RequestStateChange(ushort RequestedState, System.DateTime TimeoutPeriod, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("RequestStateChange"); - inParams["RequestedState"] = ((ushort)(RequestedState)); - inParams["TimeoutPeriod"] = ToDmtfDateTime(((System.DateTime)(TimeoutPeriod))); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RequestStateChange", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null) && outParams.Properties["Job"].Value != null) { - Job = new System.Management.ManagementPath(outParams.Properties["Job"].Value.ToString()); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - return System.Convert.ToUInt32(0); - } - } - - public uint SetPowerState(uint PowerState, System.DateTime Time) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("SetPowerState"); - inParams["PowerState"] = ((uint)(PowerState)); - inParams["Time"] = ToDmtfDateTime(((System.DateTime)(Time))); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("SetPowerState", inParams, null); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - return System.Convert.ToUInt32(0); - } - } - - // Enumerator implementation for enumerating instances of the class. - public class VirtualEthernetSwitchCollection : object, ICollection { - - private ManagementObjectCollection privColObj; - - public VirtualEthernetSwitchCollection(ManagementObjectCollection objCollection) { - privColObj = objCollection; - } - - public virtual int Count { - get { - return privColObj.Count; - } - } - - public virtual bool IsSynchronized { - get { - return privColObj.IsSynchronized; - } - } - - public virtual object SyncRoot { - get { - return this; - } - } - - public virtual void CopyTo(System.Array array, int index) { - privColObj.CopyTo(array, index); - int nCtr; - for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { - array.SetValue(new VirtualEthernetSwitch(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); - } - } - - public virtual System.Collections.IEnumerator GetEnumerator() { - return new VirtualEthernetSwitchEnumerator(privColObj.GetEnumerator()); - } - - public class VirtualEthernetSwitchEnumerator : object, System.Collections.IEnumerator { - - private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; - - public VirtualEthernetSwitchEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { - privObjEnum = objEnum; - } - - public virtual object Current { - get { - return new VirtualEthernetSwitch(((System.Management.ManagementObject)(privObjEnum.Current))); - } - } - - public virtual bool MoveNext() { - return privObjEnum.MoveNext(); - } - - public virtual void Reset() { - privObjEnum.Reset(); - } - } - } - - // TypeConverter to handle null values for ValueType properties - public class WMIValueTypeConverter : TypeConverter { - - private TypeConverter baseConverter; - - private System.Type baseType; - - public WMIValueTypeConverter(System.Type inBaseType) { - baseConverter = TypeDescriptor.GetConverter(inBaseType); - baseType = inBaseType; - } - - public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { - return baseConverter.CanConvertFrom(context, srcType); - } - - public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { - return baseConverter.CanConvertTo(context, destinationType); - } - - public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { - return baseConverter.ConvertFrom(context, culture, value); - } - - public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { - return baseConverter.CreateInstance(context, dictionary); - } - - public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetCreateInstanceSupported(context); - } - - public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { - return baseConverter.GetProperties(context, value, attributeVar); - } - - public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetPropertiesSupported(context); - } - - public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValues(context); - } - - public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesExclusive(context); - } - - public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesSupported(context); - } - - public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { - if ((baseType.BaseType == typeof(System.Enum))) { - if ((value.GetType() == destinationType)) { - return value; - } - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return "NULL_ENUM_VALUE" ; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((baseType == typeof(bool)) - && (baseType.BaseType == typeof(System.ValueType)))) { - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((context != null) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - } - - // Embedded class to represent WMI system Properties. - [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] - public class ManagementSystemProperties { - - private System.Management.ManagementBaseObject PrivateLateBoundObject; - - public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { - PrivateLateBoundObject = ManagedObject; - } - - [Browsable(true)] - public int GENUS { - get { - return ((int)(PrivateLateBoundObject["__GENUS"])); - } - } - - [Browsable(true)] - public string CLASS { - get { - return ((string)(PrivateLateBoundObject["__CLASS"])); - } - } - - [Browsable(true)] - public string SUPERCLASS { - get { - return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); - } - } - - [Browsable(true)] - public string DYNASTY { - get { - return ((string)(PrivateLateBoundObject["__DYNASTY"])); - } - } - - [Browsable(true)] - public string RELPATH { - get { - return ((string)(PrivateLateBoundObject["__RELPATH"])); - } - } - - [Browsable(true)] - public int PROPERTY_COUNT { - get { - return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); - } - } - - [Browsable(true)] - public string[] DERIVATION { - get { - return ((string[])(PrivateLateBoundObject["__DERIVATION"])); - } - } - - [Browsable(true)] - public string SERVER { - get { - return ((string)(PrivateLateBoundObject["__SERVER"])); - } - } - - [Browsable(true)] - public string NAMESPACE { - get { - return ((string)(PrivateLateBoundObject["__NAMESPACE"])); - } - } - - [Browsable(true)] - public string PATH { - get { - return ((string)(PrivateLateBoundObject["__PATH"])); - } - } - } - } -} +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2 { + using System; + using System.ComponentModel; + using System.Management; + using System.Collections; + using System.Globalization; + using System.ComponentModel.Design.Serialization; + using System.Reflection; + + + // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. + // Functions IsNull() are used to check if a property is NULL. + // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. + // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. + // Datetime conversion functions ToDateTime and ToDmtfDateTime are added to the class to convert DMTF datetime to System.DateTime and vice-versa. + // An Early Bound class generated for the WMI class.Msvm_VirtualEthernetSwitch + public class VirtualEthernetSwitch : System.ComponentModel.Component { + + // Private property to hold the WMI namespace in which the class resides. + private static string CreatedWmiNamespace = "ROOT\\virtualization\\v2"; + + // Private property to hold the name of WMI class which created this class. + public static string CreatedClassName = "Msvm_VirtualEthernetSwitch"; + + // Private member variable to hold the ManagementScope which is used by the various methods. + private static System.Management.ManagementScope statMgmtScope = null; + + private ManagementSystemProperties PrivateSystemProperties; + + // Underlying lateBound WMI object. + private System.Management.ManagementObject PrivateLateBoundObject; + + // Member variable to store the 'automatic commit' behavior for the class. + private bool AutoCommitProp; + + // Private variable to hold the embedded property representing the instance. + private System.Management.ManagementBaseObject embeddedObj; + + // The current WMI object used + private System.Management.ManagementBaseObject curObj; + + // Flag to indicate if the instance is an embedded object. + private bool isEmbedded; + + // Below are different overloads of constructors to initialize an instance of the class with a WMI object. + public VirtualEthernetSwitch() { + this.InitializeObject(null, null, null); + } + + public VirtualEthernetSwitch(string keyCreationClassName, string keyName) { + this.InitializeObject(null, new System.Management.ManagementPath(VirtualEthernetSwitch.ConstructPath(keyCreationClassName, keyName)), null); + } + + public VirtualEthernetSwitch(System.Management.ManagementScope mgmtScope, string keyCreationClassName, string keyName) { + this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(VirtualEthernetSwitch.ConstructPath(keyCreationClassName, keyName)), null); + } + + public VirtualEthernetSwitch(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(null, path, getOptions); + } + + public VirtualEthernetSwitch(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { + this.InitializeObject(mgmtScope, path, null); + } + + public VirtualEthernetSwitch(System.Management.ManagementPath path) { + this.InitializeObject(null, path, null); + } + + public VirtualEthernetSwitch(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(mgmtScope, path, getOptions); + } + + public VirtualEthernetSwitch(System.Management.ManagementObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + PrivateLateBoundObject = theObject; + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + public VirtualEthernetSwitch(System.Management.ManagementBaseObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + embeddedObj = theObject; + PrivateSystemProperties = new ManagementSystemProperties(theObject); + curObj = embeddedObj; + isEmbedded = true; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + // Property returns the namespace of the WMI class. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OriginatingNamespace { + get { + return "ROOT\\virtualization\\v2"; + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ManagementClassName { + get { + string strRet = CreatedClassName; + if ((curObj != null)) { + if ((curObj.ClassPath != null)) { + strRet = ((string)(curObj["__CLASS"])); + if (((strRet == null) + || (strRet == string.Empty))) { + strRet = CreatedClassName; + } + } + } + return strRet; + } + } + + // Property pointing to an embedded object to get System properties of the WMI object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ManagementSystemProperties SystemProperties { + get { + return PrivateSystemProperties; + } + } + + // Property returning the underlying lateBound object. + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementBaseObject LateBoundObject { + get { + return curObj; + } + } + + // ManagementScope of the object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementScope Scope { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Scope; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Scope = value; + } + } + } + + // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool AutoCommit { + get { + return AutoCommitProp; + } + set { + AutoCommitProp = value; + } + } + + // The ManagementPath of the underlying WMI object. + [Browsable(true)] + public System.Management.ManagementPath Path { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Path; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + if ((CheckIfProperClass(null, value, null) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + PrivateLateBoundObject.Path = value; + } + } + } + + // Public static scope property which is used by the various methods. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public static System.Management.ManagementScope StaticScope { + get { + return statMgmtScope; + } + set { + statMgmtScope = value; + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ushort[] AvailableRequestedStates { + get { + return ((ushort[])(curObj["AvailableRequestedStates"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Caption { + get { + return ((string)(curObj["Caption"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsCommunicationStatusNull { + get { + if ((curObj["CommunicationStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort CommunicationStatus { + get { + if ((curObj["CommunicationStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["CommunicationStatus"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string CreationClassName { + get { + return ((string)(curObj["CreationClassName"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ushort[] Dedicated { + get { + return ((ushort[])(curObj["Dedicated"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Description { + get { + return ((string)(curObj["Description"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsDetailedStatusNull { + get { + if ((curObj["DetailedStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort DetailedStatus { + get { + if ((curObj["DetailedStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["DetailedStatus"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ElementName { + get { + return ((string)(curObj["ElementName"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsEnabledDefaultNull { + get { + if ((curObj["EnabledDefault"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort EnabledDefault { + get { + if ((curObj["EnabledDefault"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["EnabledDefault"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsEnabledStateNull { + get { + if ((curObj["EnabledState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort EnabledState { + get { + if ((curObj["EnabledState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["EnabledState"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsHealthStateNull { + get { + if ((curObj["HealthState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort HealthState { + get { + if ((curObj["HealthState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["HealthState"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] IdentifyingDescriptions { + get { + return ((string[])(curObj["IdentifyingDescriptions"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsInstallDateNull { + get { + if ((curObj["InstallDate"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime InstallDate { + get { + if ((curObj["InstallDate"] != null)) { + return ToDateTime(((string)(curObj["InstallDate"]))); + } + else { + return System.DateTime.MinValue; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string InstanceID { + get { + return ((string)(curObj["InstanceID"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsMaxIOVOffloadsNull { + get { + if ((curObj["MaxIOVOffloads"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The maximum number of SR-IOV Virtual Function offloads available on this switch.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint MaxIOVOffloads { + get { + if ((curObj["MaxIOVOffloads"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["MaxIOVOffloads"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsMaxVMQOffloadsNull { + get { + if ((curObj["MaxVMQOffloads"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The maximum number of VMQ offloads allowed for a port on this switch.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint MaxVMQOffloads { + get { + if ((curObj["MaxVMQOffloads"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["MaxVMQOffloads"])); + } + set { + curObj["MaxVMQOffloads"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Name { + get { + return ((string)(curObj["Name"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string NameFormat { + get { + return ((string)(curObj["NameFormat"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsOperatingStatusNull { + get { + if ((curObj["OperatingStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort OperatingStatus { + get { + if ((curObj["OperatingStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["OperatingStatus"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ushort[] OperationalStatus { + get { + return ((ushort[])(curObj["OperationalStatus"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] OtherDedicatedDescriptions { + get { + return ((string[])(curObj["OtherDedicatedDescriptions"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherEnabledState { + get { + return ((string)(curObj["OtherEnabledState"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] OtherIdentifyingInfo { + get { + return ((string[])(curObj["OtherIdentifyingInfo"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ushort[] PowerManagementCapabilities { + get { + return ((ushort[])(curObj["PowerManagementCapabilities"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string PrimaryOwnerContact { + get { + return ((string)(curObj["PrimaryOwnerContact"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string PrimaryOwnerName { + get { + return ((string)(curObj["PrimaryOwnerName"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPrimaryStatusNull { + get { + if ((curObj["PrimaryStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort PrimaryStatus { + get { + if ((curObj["PrimaryStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["PrimaryStatus"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsRequestedStateNull { + get { + if ((curObj["RequestedState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort RequestedState { + get { + if ((curObj["RequestedState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["RequestedState"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsResetCapabilityNull { + get { + if ((curObj["ResetCapability"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort ResetCapability { + get { + if ((curObj["ResetCapability"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["ResetCapability"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] Roles { + get { + return ((string[])(curObj["Roles"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Status { + get { + return ((string)(curObj["Status"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] StatusDescriptions { + get { + return ((string[])(curObj["StatusDescriptions"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsTimeOfLastStateChangeNull { + get { + if ((curObj["TimeOfLastStateChange"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime TimeOfLastStateChange { + get { + if ((curObj["TimeOfLastStateChange"] != null)) { + return ToDateTime(((string)(curObj["TimeOfLastStateChange"]))); + } + else { + return System.DateTime.MinValue; + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsTransitioningToStateNull { + get { + if ((curObj["TransitioningToState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort TransitioningToState { + get { + if ((curObj["TransitioningToState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["TransitioningToState"])); + } + } + + private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { + if (((path != null) + && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); + } + } + + private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { + if (((theObj != null) + && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); + if ((parentClasses != null)) { + int count = 0; + for (count = 0; (count < parentClasses.Length); count = (count + 1)) { + if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { + return true; + } + } + } + } + return false; + } + + private bool ShouldSerializeCommunicationStatus() { + if ((this.IsCommunicationStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeDetailedStatus() { + if ((this.IsDetailedStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeEnabledDefault() { + if ((this.IsEnabledDefaultNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeEnabledState() { + if ((this.IsEnabledStateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeHealthState() { + if ((this.IsHealthStateNull == false)) { + return true; + } + return false; + } + + // Converts a given datetime in DMTF format to System.DateTime object. + static System.DateTime ToDateTime(string dmtfDate) { + System.DateTime initializer = System.DateTime.MinValue; + int year = initializer.Year; + int month = initializer.Month; + int day = initializer.Day; + int hour = initializer.Hour; + int minute = initializer.Minute; + int second = initializer.Second; + long ticks = 0; + string dmtf = dmtfDate; + System.DateTime datetime = System.DateTime.MinValue; + string tempString = string.Empty; + if ((dmtf == null)) { + throw new System.ArgumentOutOfRangeException(); + } + if ((dmtf.Length == 0)) { + throw new System.ArgumentOutOfRangeException(); + } + if ((dmtf.Length != 25)) { + throw new System.ArgumentOutOfRangeException(); + } + try { + tempString = dmtf.Substring(0, 4); + if (("****" != tempString)) { + year = int.Parse(tempString); + } + tempString = dmtf.Substring(4, 2); + if (("**" != tempString)) { + month = int.Parse(tempString); + } + tempString = dmtf.Substring(6, 2); + if (("**" != tempString)) { + day = int.Parse(tempString); + } + tempString = dmtf.Substring(8, 2); + if (("**" != tempString)) { + hour = int.Parse(tempString); + } + tempString = dmtf.Substring(10, 2); + if (("**" != tempString)) { + minute = int.Parse(tempString); + } + tempString = dmtf.Substring(12, 2); + if (("**" != tempString)) { + second = int.Parse(tempString); + } + tempString = dmtf.Substring(15, 6); + if (("******" != tempString)) { + ticks = (long.Parse(tempString) * ((long)((System.TimeSpan.TicksPerMillisecond / 1000)))); + } + if (((((((((year < 0) + || (month < 0)) + || (day < 0)) + || (hour < 0)) + || (minute < 0)) + || (minute < 0)) + || (second < 0)) + || (ticks < 0))) { + throw new System.ArgumentOutOfRangeException(); + } + } + catch (System.Exception e) { + throw new System.ArgumentOutOfRangeException(null, e.Message); + } + datetime = new System.DateTime(year, month, day, hour, minute, second, 0); + datetime = datetime.AddTicks(ticks); + System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(datetime); + int UTCOffset = 0; + int OffsetToBeAdjusted = 0; + long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); + tempString = dmtf.Substring(22, 3); + if ((tempString != "******")) { + tempString = dmtf.Substring(21, 4); + try { + UTCOffset = int.Parse(tempString); + } + catch (System.Exception e) { + throw new System.ArgumentOutOfRangeException(null, e.Message); + } + OffsetToBeAdjusted = ((int)((OffsetMins - UTCOffset))); + datetime = datetime.AddMinutes(((double)(OffsetToBeAdjusted))); + } + return datetime; + } + + // Converts a given System.DateTime object to DMTF datetime format. + static string ToDmtfDateTime(System.DateTime date) { + string utcString = string.Empty; + System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(date); + long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); + if ((System.Math.Abs(OffsetMins) > 999)) { + date = date.ToUniversalTime(); + utcString = "+000"; + } + else { + if ((tickOffset.Ticks >= 0)) { + utcString = string.Concat("+", ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))).ToString().PadLeft(3, '0')); + } + else { + string strTemp = ((long)(OffsetMins)).ToString(); + utcString = string.Concat("-", strTemp.Substring(1, (strTemp.Length - 1)).PadLeft(3, '0')); + } + } + string dmtfDateTime = ((int)(date.Year)).ToString().PadLeft(4, '0'); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Month)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Day)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Hour)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Minute)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Second)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, "."); + System.DateTime dtTemp = new System.DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, 0); + long microsec = ((long)((((date.Ticks - dtTemp.Ticks) + * 1000) + / System.TimeSpan.TicksPerMillisecond))); + string strMicrosec = ((long)(microsec)).ToString(); + if ((strMicrosec.Length > 6)) { + strMicrosec = strMicrosec.Substring(0, 6); + } + dmtfDateTime = string.Concat(dmtfDateTime, strMicrosec.PadLeft(6, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, utcString); + return dmtfDateTime; + } + + private bool ShouldSerializeInstallDate() { + if ((this.IsInstallDateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeMaxIOVOffloads() { + if ((this.IsMaxIOVOffloadsNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeMaxVMQOffloads() { + if ((this.IsMaxVMQOffloadsNull == false)) { + return true; + } + return false; + } + + private void ResetMaxVMQOffloads() { + curObj["MaxVMQOffloads"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private bool ShouldSerializeOperatingStatus() { + if ((this.IsOperatingStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePrimaryStatus() { + if ((this.IsPrimaryStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeRequestedState() { + if ((this.IsRequestedStateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeResetCapability() { + if ((this.IsResetCapabilityNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeTimeOfLastStateChange() { + if ((this.IsTimeOfLastStateChangeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeTransitioningToState() { + if ((this.IsTransitioningToStateNull == false)) { + return true; + } + return false; + } + + [Browsable(true)] + public void CommitObject() { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(); + } + } + + [Browsable(true)] + public void CommitObject(System.Management.PutOptions putOptions) { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(putOptions); + } + } + + private void Initialize() { + AutoCommitProp = true; + isEmbedded = false; + } + + private static string ConstructPath(string keyCreationClassName, string keyName) { + string strPath = "ROOT\\virtualization\\v2:Msvm_VirtualEthernetSwitch"; + strPath = string.Concat(strPath, string.Concat(".CreationClassName=", string.Concat("\"", string.Concat(keyCreationClassName, "\"")))); + strPath = string.Concat(strPath, string.Concat(",Name=", string.Concat("\"", string.Concat(keyName, "\"")))); + return strPath; + } + + private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + Initialize(); + if ((path != null)) { + if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + } + PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + + // Different overloads of GetInstances() help in enumerating instances of the WMI class. + public static VirtualEthernetSwitchCollection GetInstances() { + return GetInstances(null, null, null); + } + + public static VirtualEthernetSwitchCollection GetInstances(string condition) { + return GetInstances(null, condition, null); + } + + public static VirtualEthernetSwitchCollection GetInstances(string[] selectedProperties) { + return GetInstances(null, null, selectedProperties); + } + + public static VirtualEthernetSwitchCollection GetInstances(string condition, string[] selectedProperties) { + return GetInstances(null, condition, selectedProperties); + } + + public static VirtualEthernetSwitchCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); + pathObj.ClassName = "Msvm_VirtualEthernetSwitch"; + pathObj.NamespacePath = "root\\virtualization\\v2"; + System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); + if ((enumOptions == null)) { + enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + } + return new VirtualEthernetSwitchCollection(clsObject.GetInstances(enumOptions)); + } + + public static VirtualEthernetSwitchCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { + return GetInstances(mgmtScope, condition, null); + } + + public static VirtualEthernetSwitchCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { + return GetInstances(mgmtScope, null, selectedProperties); + } + + public static VirtualEthernetSwitchCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_VirtualEthernetSwitch", condition, selectedProperties)); + System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + ObjectSearcher.Options = enumOptions; + return new VirtualEthernetSwitchCollection(ObjectSearcher.Get()); + } + + [Browsable(true)] + public static VirtualEthernetSwitch CreateInstance() { + System.Management.ManagementScope mgmtScope = null; + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = CreatedWmiNamespace; + } + else { + mgmtScope = statMgmtScope; + } + System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); + System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); + return new VirtualEthernetSwitch(tmpMgmtClass.CreateInstance()); + } + + [Browsable(true)] + public void Delete() { + PrivateLateBoundObject.Delete(); + } + + public uint RequestStateChange(ushort RequestedState, System.DateTime TimeoutPeriod, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("RequestStateChange"); + inParams["RequestedState"] = ((ushort)(RequestedState)); + inParams["TimeoutPeriod"] = ToDmtfDateTime(((System.DateTime)(TimeoutPeriod))); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RequestStateChange", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null) && outParams.Properties["Job"].Value != null) { + Job = new System.Management.ManagementPath(outParams.Properties["Job"].Value.ToString()); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + return System.Convert.ToUInt32(0); + } + } + + public uint SetPowerState(uint PowerState, System.DateTime Time) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("SetPowerState"); + inParams["PowerState"] = ((uint)(PowerState)); + inParams["Time"] = ToDmtfDateTime(((System.DateTime)(Time))); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("SetPowerState", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + // Enumerator implementation for enumerating instances of the class. + public class VirtualEthernetSwitchCollection : object, ICollection { + + private ManagementObjectCollection privColObj; + + public VirtualEthernetSwitchCollection(ManagementObjectCollection objCollection) { + privColObj = objCollection; + } + + public virtual int Count { + get { + return privColObj.Count; + } + } + + public virtual bool IsSynchronized { + get { + return privColObj.IsSynchronized; + } + } + + public virtual object SyncRoot { + get { + return this; + } + } + + public virtual void CopyTo(System.Array array, int index) { + privColObj.CopyTo(array, index); + int nCtr; + for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { + array.SetValue(new VirtualEthernetSwitch(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); + } + } + + public virtual System.Collections.IEnumerator GetEnumerator() { + return new VirtualEthernetSwitchEnumerator(privColObj.GetEnumerator()); + } + + public class VirtualEthernetSwitchEnumerator : object, System.Collections.IEnumerator { + + private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; + + public VirtualEthernetSwitchEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { + privObjEnum = objEnum; + } + + public virtual object Current { + get { + return new VirtualEthernetSwitch(((System.Management.ManagementObject)(privObjEnum.Current))); + } + } + + public virtual bool MoveNext() { + return privObjEnum.MoveNext(); + } + + public virtual void Reset() { + privObjEnum.Reset(); + } + } + } + + // TypeConverter to handle null values for ValueType properties + public class WMIValueTypeConverter : TypeConverter { + + private TypeConverter baseConverter; + + private System.Type baseType; + + public WMIValueTypeConverter(System.Type inBaseType) { + baseConverter = TypeDescriptor.GetConverter(inBaseType); + baseType = inBaseType; + } + + public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { + return baseConverter.CanConvertFrom(context, srcType); + } + + public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { + return baseConverter.CanConvertTo(context, destinationType); + } + + public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { + return baseConverter.ConvertFrom(context, culture, value); + } + + public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { + return baseConverter.CreateInstance(context, dictionary); + } + + public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetCreateInstanceSupported(context); + } + + public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { + return baseConverter.GetProperties(context, value, attributeVar); + } + + public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetPropertiesSupported(context); + } + + public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValues(context); + } + + public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesExclusive(context); + } + + public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesSupported(context); + } + + public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { + if ((baseType.BaseType == typeof(System.Enum))) { + if ((value.GetType() == destinationType)) { + return value; + } + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return "NULL_ENUM_VALUE" ; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((baseType == typeof(bool)) + && (baseType.BaseType == typeof(System.ValueType)))) { + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((context != null) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + } + + // Embedded class to represent WMI system Properties. + [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] + public class ManagementSystemProperties { + + private System.Management.ManagementBaseObject PrivateLateBoundObject; + + public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { + PrivateLateBoundObject = ManagedObject; + } + + [Browsable(true)] + public int GENUS { + get { + return ((int)(PrivateLateBoundObject["__GENUS"])); + } + } + + [Browsable(true)] + public string CLASS { + get { + return ((string)(PrivateLateBoundObject["__CLASS"])); + } + } + + [Browsable(true)] + public string SUPERCLASS { + get { + return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); + } + } + + [Browsable(true)] + public string DYNASTY { + get { + return ((string)(PrivateLateBoundObject["__DYNASTY"])); + } + } + + [Browsable(true)] + public string RELPATH { + get { + return ((string)(PrivateLateBoundObject["__RELPATH"])); + } + } + + [Browsable(true)] + public int PROPERTY_COUNT { + get { + return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); + } + } + + [Browsable(true)] + public string[] DERIVATION { + get { + return ((string[])(PrivateLateBoundObject["__DERIVATION"])); + } + } + + [Browsable(true)] + public string SERVER { + get { + return ((string)(PrivateLateBoundObject["__SERVER"])); + } + } + + [Browsable(true)] + public string NAMESPACE { + get { + return ((string)(PrivateLateBoundObject["__NAMESPACE"])); + } + } + + [Browsable(true)] + public string PATH { + get { + return ((string)(PrivateLateBoundObject["__PATH"])); + } + } + } + } +} diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_VirtualEthernetSwitchManagementService.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_VirtualEthernetSwitchManagementService.cs index ee167a7cd81..31166815945 100644 --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_VirtualEthernetSwitchManagementService.cs +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_VirtualEthernetSwitchManagementService.cs @@ -1,1515 +1,1515 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2 { - using System; - using System.ComponentModel; - using System.Management; - using System.Collections; - using System.Globalization; - using System.ComponentModel.Design.Serialization; - using System.Reflection; - - - // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. - // Functions IsNull() are used to check if a property is NULL. - // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. - // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. - // Datetime conversion functions ToDateTime and ToDmtfDateTime are added to the class to convert DMTF datetime to System.DateTime and vice-versa. - // An Early Bound class generated for the WMI class.Msvm_VirtualEthernetSwitchManagementService - public class VirtualEthernetSwitchManagementService : System.ComponentModel.Component { - - // Private property to hold the WMI namespace in which the class resides. - private static string CreatedWmiNamespace = "ROOT\\virtualization\\v2"; - - // Private property to hold the name of WMI class which created this class. - private static string CreatedClassName = "Msvm_VirtualEthernetSwitchManagementService"; - - // Private member variable to hold the ManagementScope which is used by the various methods. - private static System.Management.ManagementScope statMgmtScope = null; - - private ManagementSystemProperties PrivateSystemProperties; - - // Underlying lateBound WMI object. - private System.Management.ManagementObject PrivateLateBoundObject; - - // Member variable to store the 'automatic commit' behavior for the class. - private bool AutoCommitProp; - - // Private variable to hold the embedded property representing the instance. - private System.Management.ManagementBaseObject embeddedObj; - - // The current WMI object used - private System.Management.ManagementBaseObject curObj; - - // Flag to indicate if the instance is an embedded object. - private bool isEmbedded; - - // Below are different overloads of constructors to initialize an instance of the class with a WMI object. - public VirtualEthernetSwitchManagementService() { - this.InitializeObject(null, null, null); - } - - public VirtualEthernetSwitchManagementService(string keyCreationClassName, string keyName, string keySystemCreationClassName, string keySystemName) { - this.InitializeObject(null, new System.Management.ManagementPath(VirtualEthernetSwitchManagementService.ConstructPath(keyCreationClassName, keyName, keySystemCreationClassName, keySystemName)), null); - } - - public VirtualEthernetSwitchManagementService(System.Management.ManagementScope mgmtScope, string keyCreationClassName, string keyName, string keySystemCreationClassName, string keySystemName) { - this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(VirtualEthernetSwitchManagementService.ConstructPath(keyCreationClassName, keyName, keySystemCreationClassName, keySystemName)), null); - } - - public VirtualEthernetSwitchManagementService(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(null, path, getOptions); - } - - public VirtualEthernetSwitchManagementService(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { - this.InitializeObject(mgmtScope, path, null); - } - - public VirtualEthernetSwitchManagementService(System.Management.ManagementPath path) { - this.InitializeObject(null, path, null); - } - - public VirtualEthernetSwitchManagementService(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(mgmtScope, path, getOptions); - } - - public VirtualEthernetSwitchManagementService(System.Management.ManagementObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - PrivateLateBoundObject = theObject; - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - public VirtualEthernetSwitchManagementService(System.Management.ManagementBaseObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - embeddedObj = theObject; - PrivateSystemProperties = new ManagementSystemProperties(theObject); - curObj = embeddedObj; - isEmbedded = true; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - // Property returns the namespace of the WMI class. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OriginatingNamespace { - get { - return "ROOT\\virtualization\\v2"; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ManagementClassName { - get { - string strRet = CreatedClassName; - if ((curObj != null)) { - if ((curObj.ClassPath != null)) { - strRet = ((string)(curObj["__CLASS"])); - if (((strRet == null) - || (strRet == string.Empty))) { - strRet = CreatedClassName; - } - } - } - return strRet; - } - } - - // Property pointing to an embedded object to get System properties of the WMI object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ManagementSystemProperties SystemProperties { - get { - return PrivateSystemProperties; - } - } - - // Property returning the underlying lateBound object. - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementBaseObject LateBoundObject { - get { - return curObj; - } - } - - // ManagementScope of the object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementScope Scope { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Scope; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Scope = value; - } - } - } - - // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool AutoCommit { - get { - return AutoCommitProp; - } - set { - AutoCommitProp = value; - } - } - - // The ManagementPath of the underlying WMI object. - [Browsable(true)] - public System.Management.ManagementPath Path { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Path; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - if ((CheckIfProperClass(null, value, null) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - PrivateLateBoundObject.Path = value; - } - } - } - - // Public static scope property which is used by the various methods. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public static System.Management.ManagementScope StaticScope { - get { - return statMgmtScope; - } - set { - statMgmtScope = value; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ushort[] AvailableRequestedStates { - get { - return ((ushort[])(curObj["AvailableRequestedStates"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Caption { - get { - return ((string)(curObj["Caption"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsCommunicationStatusNull { - get { - if ((curObj["CommunicationStatus"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort CommunicationStatus { - get { - if ((curObj["CommunicationStatus"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["CommunicationStatus"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string CreationClassName { - get { - return ((string)(curObj["CreationClassName"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Description { - get { - return ((string)(curObj["Description"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsDetailedStatusNull { - get { - if ((curObj["DetailedStatus"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort DetailedStatus { - get { - if ((curObj["DetailedStatus"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["DetailedStatus"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ElementName { - get { - return ((string)(curObj["ElementName"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsEnabledDefaultNull { - get { - if ((curObj["EnabledDefault"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort EnabledDefault { - get { - if ((curObj["EnabledDefault"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["EnabledDefault"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsEnabledStateNull { - get { - if ((curObj["EnabledState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort EnabledState { - get { - if ((curObj["EnabledState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["EnabledState"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsHealthStateNull { - get { - if ((curObj["HealthState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort HealthState { - get { - if ((curObj["HealthState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["HealthState"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsInstallDateNull { - get { - if ((curObj["InstallDate"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public System.DateTime InstallDate { - get { - if ((curObj["InstallDate"] != null)) { - return ToDateTime(((string)(curObj["InstallDate"]))); - } - else { - return System.DateTime.MinValue; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string InstanceID { - get { - return ((string)(curObj["InstanceID"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Name { - get { - return ((string)(curObj["Name"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsOperatingStatusNull { - get { - if ((curObj["OperatingStatus"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort OperatingStatus { - get { - if ((curObj["OperatingStatus"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["OperatingStatus"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ushort[] OperationalStatus { - get { - return ((ushort[])(curObj["OperationalStatus"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OtherEnabledState { - get { - return ((string)(curObj["OtherEnabledState"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string PrimaryOwnerContact { - get { - return ((string)(curObj["PrimaryOwnerContact"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string PrimaryOwnerName { - get { - return ((string)(curObj["PrimaryOwnerName"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsPrimaryStatusNull { - get { - if ((curObj["PrimaryStatus"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort PrimaryStatus { - get { - if ((curObj["PrimaryStatus"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["PrimaryStatus"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsRequestedStateNull { - get { - if ((curObj["RequestedState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort RequestedState { - get { - if ((curObj["RequestedState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["RequestedState"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsStartedNull { - get { - if ((curObj["Started"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool Started { - get { - if ((curObj["Started"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["Started"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string StartMode { - get { - return ((string)(curObj["StartMode"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Status { - get { - return ((string)(curObj["Status"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] StatusDescriptions { - get { - return ((string[])(curObj["StatusDescriptions"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string SystemCreationClassName { - get { - return ((string)(curObj["SystemCreationClassName"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string SystemName { - get { - return ((string)(curObj["SystemName"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsTimeOfLastStateChangeNull { - get { - if ((curObj["TimeOfLastStateChange"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public System.DateTime TimeOfLastStateChange { - get { - if ((curObj["TimeOfLastStateChange"] != null)) { - return ToDateTime(((string)(curObj["TimeOfLastStateChange"]))); - } - else { - return System.DateTime.MinValue; - } - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsTransitioningToStateNull { - get { - if ((curObj["TransitioningToState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort TransitioningToState { - get { - if ((curObj["TransitioningToState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["TransitioningToState"])); - } - } - - private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { - if (((path != null) - && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); - } - } - - private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { - if (((theObj != null) - && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); - if ((parentClasses != null)) { - int count = 0; - for (count = 0; (count < parentClasses.Length); count = (count + 1)) { - if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { - return true; - } - } - } - } - return false; - } - - private bool ShouldSerializeCommunicationStatus() { - if ((this.IsCommunicationStatusNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeDetailedStatus() { - if ((this.IsDetailedStatusNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeEnabledDefault() { - if ((this.IsEnabledDefaultNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeEnabledState() { - if ((this.IsEnabledStateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeHealthState() { - if ((this.IsHealthStateNull == false)) { - return true; - } - return false; - } - - // Converts a given datetime in DMTF format to System.DateTime object. - static System.DateTime ToDateTime(string dmtfDate) { - System.DateTime initializer = System.DateTime.MinValue; - int year = initializer.Year; - int month = initializer.Month; - int day = initializer.Day; - int hour = initializer.Hour; - int minute = initializer.Minute; - int second = initializer.Second; - long ticks = 0; - string dmtf = dmtfDate; - System.DateTime datetime = System.DateTime.MinValue; - string tempString = string.Empty; - if ((dmtf == null)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtf.Length == 0)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtf.Length != 25)) { - throw new System.ArgumentOutOfRangeException(); - } - try { - tempString = dmtf.Substring(0, 4); - if (("****" != tempString)) { - year = int.Parse(tempString); - } - tempString = dmtf.Substring(4, 2); - if (("**" != tempString)) { - month = int.Parse(tempString); - } - tempString = dmtf.Substring(6, 2); - if (("**" != tempString)) { - day = int.Parse(tempString); - } - tempString = dmtf.Substring(8, 2); - if (("**" != tempString)) { - hour = int.Parse(tempString); - } - tempString = dmtf.Substring(10, 2); - if (("**" != tempString)) { - minute = int.Parse(tempString); - } - tempString = dmtf.Substring(12, 2); - if (("**" != tempString)) { - second = int.Parse(tempString); - } - tempString = dmtf.Substring(15, 6); - if (("******" != tempString)) { - ticks = (long.Parse(tempString) * ((long)((System.TimeSpan.TicksPerMillisecond / 1000)))); - } - if (((((((((year < 0) - || (month < 0)) - || (day < 0)) - || (hour < 0)) - || (minute < 0)) - || (minute < 0)) - || (second < 0)) - || (ticks < 0))) { - throw new System.ArgumentOutOfRangeException(); - } - } - catch (System.Exception e) { - throw new System.ArgumentOutOfRangeException(null, e.Message); - } - datetime = new System.DateTime(year, month, day, hour, minute, second, 0); - datetime = datetime.AddTicks(ticks); - System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(datetime); - int UTCOffset = 0; - int OffsetToBeAdjusted = 0; - long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); - tempString = dmtf.Substring(22, 3); - if ((tempString != "******")) { - tempString = dmtf.Substring(21, 4); - try { - UTCOffset = int.Parse(tempString); - } - catch (System.Exception e) { - throw new System.ArgumentOutOfRangeException(null, e.Message); - } - OffsetToBeAdjusted = ((int)((OffsetMins - UTCOffset))); - datetime = datetime.AddMinutes(((double)(OffsetToBeAdjusted))); - } - return datetime; - } - - // Converts a given System.DateTime object to DMTF datetime format. - static string ToDmtfDateTime(System.DateTime date) { - string utcString = string.Empty; - System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(date); - long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); - if ((System.Math.Abs(OffsetMins) > 999)) { - date = date.ToUniversalTime(); - utcString = "+000"; - } - else { - if ((tickOffset.Ticks >= 0)) { - utcString = string.Concat("+", ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))).ToString().PadLeft(3, '0')); - } - else { - string strTemp = ((long)(OffsetMins)).ToString(); - utcString = string.Concat("-", strTemp.Substring(1, (strTemp.Length - 1)).PadLeft(3, '0')); - } - } - string dmtfDateTime = ((int)(date.Year)).ToString().PadLeft(4, '0'); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Month)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Day)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Hour)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Minute)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Second)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, "."); - System.DateTime dtTemp = new System.DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, 0); - long microsec = ((long)((((date.Ticks - dtTemp.Ticks) - * 1000) - / System.TimeSpan.TicksPerMillisecond))); - string strMicrosec = ((long)(microsec)).ToString(); - if ((strMicrosec.Length > 6)) { - strMicrosec = strMicrosec.Substring(0, 6); - } - dmtfDateTime = string.Concat(dmtfDateTime, strMicrosec.PadLeft(6, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, utcString); - return dmtfDateTime; - } - - private bool ShouldSerializeInstallDate() { - if ((this.IsInstallDateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeOperatingStatus() { - if ((this.IsOperatingStatusNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializePrimaryStatus() { - if ((this.IsPrimaryStatusNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeRequestedState() { - if ((this.IsRequestedStateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeStarted() { - if ((this.IsStartedNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeTimeOfLastStateChange() { - if ((this.IsTimeOfLastStateChangeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeTransitioningToState() { - if ((this.IsTransitioningToStateNull == false)) { - return true; - } - return false; - } - - [Browsable(true)] - public void CommitObject() { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(); - } - } - - [Browsable(true)] - public void CommitObject(System.Management.PutOptions putOptions) { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(putOptions); - } - } - - private void Initialize() { - AutoCommitProp = true; - isEmbedded = false; - } - - private static string ConstructPath(string keyCreationClassName, string keyName, string keySystemCreationClassName, string keySystemName) { - string strPath = "ROOT\\virtualization\\v2:Msvm_VirtualEthernetSwitchManagementService"; - strPath = string.Concat(strPath, string.Concat(".CreationClassName=", string.Concat("\"", string.Concat(keyCreationClassName, "\"")))); - strPath = string.Concat(strPath, string.Concat(",Name=", string.Concat("\"", string.Concat(keyName, "\"")))); - strPath = string.Concat(strPath, string.Concat(",SystemCreationClassName=", string.Concat("\"", string.Concat(keySystemCreationClassName, "\"")))); - strPath = string.Concat(strPath, string.Concat(",SystemName=", string.Concat("\"", string.Concat(keySystemName, "\"")))); - return strPath; - } - - private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - Initialize(); - if ((path != null)) { - if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - } - PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - - // Different overloads of GetInstances() help in enumerating instances of the WMI class. - public static VirtualEthernetSwitchManagementServiceCollection GetInstances() { - return GetInstances(null, null, null); - } - - public static VirtualEthernetSwitchManagementServiceCollection GetInstances(string condition) { - return GetInstances(null, condition, null); - } - - public static VirtualEthernetSwitchManagementServiceCollection GetInstances(string[] selectedProperties) { - return GetInstances(null, null, selectedProperties); - } - - public static VirtualEthernetSwitchManagementServiceCollection GetInstances(string condition, string[] selectedProperties) { - return GetInstances(null, condition, selectedProperties); - } - - public static VirtualEthernetSwitchManagementServiceCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); - pathObj.ClassName = "Msvm_VirtualEthernetSwitchManagementService"; - pathObj.NamespacePath = "root\\virtualization\\v2"; - System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); - if ((enumOptions == null)) { - enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - } - return new VirtualEthernetSwitchManagementServiceCollection(clsObject.GetInstances(enumOptions)); - } - - public static VirtualEthernetSwitchManagementServiceCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { - return GetInstances(mgmtScope, condition, null); - } - - public static VirtualEthernetSwitchManagementServiceCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { - return GetInstances(mgmtScope, null, selectedProperties); - } - - public static VirtualEthernetSwitchManagementServiceCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_VirtualEthernetSwitchManagementService", condition, selectedProperties)); - System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - ObjectSearcher.Options = enumOptions; - return new VirtualEthernetSwitchManagementServiceCollection(ObjectSearcher.Get()); - } - - [Browsable(true)] - public static VirtualEthernetSwitchManagementService CreateInstance() { - System.Management.ManagementScope mgmtScope = null; - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = CreatedWmiNamespace; - } - else { - mgmtScope = statMgmtScope; - } - System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); - System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); - return new VirtualEthernetSwitchManagementService(tmpMgmtClass.CreateInstance()); - } - - [Browsable(true)] - public void Delete() { - PrivateLateBoundObject.Delete(); - } - - public uint AddFeatureSettings(System.Management.ManagementPath AffectedConfiguration, string[] FeatureSettings, out System.Management.ManagementPath Job, out System.Management.ManagementPath[] ResultingFeatureSettings) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("AddFeatureSettings"); - inParams["AffectedConfiguration"] = ((System.Management.ManagementPath)(AffectedConfiguration)).Path; - inParams["FeatureSettings"] = ((string[])(FeatureSettings)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("AddFeatureSettings", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null) && outParams.Properties["Job"].Value != null) { - Job = new System.Management.ManagementPath(outParams.Properties["Job"].Value.ToString()); - } - ResultingFeatureSettings = null; - if ((outParams.Properties["ResultingFeatureSettings"] != null)) { - int len = ((System.Array)(outParams.Properties["ResultingFeatureSettings"].Value)).Length; - System.Management.ManagementPath[] arrToRet = new System.Management.ManagementPath[len]; - for (int iCounter = 0; (iCounter < len); iCounter = (iCounter + 1)) { - arrToRet[iCounter] = new System.Management.ManagementPath(((System.Array)(outParams.Properties["ResultingFeatureSettings"].Value)).GetValue(iCounter).ToString()); - } - ResultingFeatureSettings = arrToRet; - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - ResultingFeatureSettings = null; - return System.Convert.ToUInt32(0); - } - } - - public uint AddResourceSettings(System.Management.ManagementPath AffectedConfiguration, string[] ResourceSettings, out System.Management.ManagementPath Job, out System.Management.ManagementPath[] ResultingResourceSettings) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("AddResourceSettings"); - inParams["AffectedConfiguration"] = ((System.Management.ManagementPath)(AffectedConfiguration)).Path; - inParams["ResourceSettings"] = ((string[])(ResourceSettings)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("AddResourceSettings", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null) && outParams.Properties["Job"].Value != null) { - Job = new System.Management.ManagementPath(outParams.Properties["Job"].Value.ToString()); - } - ResultingResourceSettings = null; - if ((outParams.Properties["ResultingResourceSettings"] != null)) { - int len = ((System.Array)(outParams.Properties["ResultingResourceSettings"].Value)).Length; - System.Management.ManagementPath[] arrToRet = new System.Management.ManagementPath[len]; - for (int iCounter = 0; (iCounter < len); iCounter = (iCounter + 1)) { - arrToRet[iCounter] = new System.Management.ManagementPath(((System.Array)(outParams.Properties["ResultingResourceSettings"].Value)).GetValue(iCounter).ToString()); - } - ResultingResourceSettings = arrToRet; - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - ResultingResourceSettings = null; - return System.Convert.ToUInt32(0); - } - } - - public uint DefineSystem(System.Management.ManagementPath ReferenceConfiguration, string[] ResourceSettings, string SystemSettings, out System.Management.ManagementPath Job, out System.Management.ManagementPath ResultingSystem) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("DefineSystem"); - inParams["ReferenceConfiguration"] = ((System.Management.ManagementPath)(ReferenceConfiguration)).Path; - inParams["ResourceSettings"] = ((string[])(ResourceSettings)); - inParams["SystemSettings"] = ((string)(SystemSettings)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("DefineSystem", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null) && outParams.Properties["Job"].Value != null) { - Job = new System.Management.ManagementPath(outParams.Properties["Job"].Value.ToString()); - } - ResultingSystem = null; - if ((outParams.Properties["ResultingSystem"] != null)) { - ResultingSystem = new System.Management.ManagementPath(outParams.Properties["ResultingSystem"].ToString()); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - ResultingSystem = null; - return System.Convert.ToUInt32(0); - } - } - - public uint DestroySystem(System.Management.ManagementPath AffectedSystem, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("DestroySystem"); - inParams["AffectedSystem"] = ((System.Management.ManagementPath)(AffectedSystem)).Path; - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("DestroySystem", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null) && outParams.Properties["Job"].Value != null) { - Job = new System.Management.ManagementPath(outParams.Properties["Job"].Value.ToString()); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - return System.Convert.ToUInt32(0); - } - } - - public uint ModifyFeatureSettings(string[] FeatureSettings, out System.Management.ManagementPath Job, out System.Management.ManagementPath[] ResultingFeatureSettings) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("ModifyFeatureSettings"); - inParams["FeatureSettings"] = ((string[])(FeatureSettings)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ModifyFeatureSettings", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null) && outParams.Properties["Job"].Value != null) { - Job = new System.Management.ManagementPath(outParams.Properties["Job"].Value.ToString()); - } - ResultingFeatureSettings = null; - if ((outParams.Properties["ResultingFeatureSettings"] != null)) { - int len = ((System.Array)(outParams.Properties["ResultingFeatureSettings"].Value)).Length; - System.Management.ManagementPath[] arrToRet = new System.Management.ManagementPath[len]; - for (int iCounter = 0; (iCounter < len); iCounter = (iCounter + 1)) { - arrToRet[iCounter] = new System.Management.ManagementPath(((System.Array)(outParams.Properties["ResultingFeatureSettings"].Value)).GetValue(iCounter).ToString()); - } - ResultingFeatureSettings = arrToRet; - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - ResultingFeatureSettings = null; - return System.Convert.ToUInt32(0); - } - } - - public uint ModifyResourceSettings(string[] ResourceSettings, out System.Management.ManagementPath Job, out System.Management.ManagementPath[] ResultingResourceSettings) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("ModifyResourceSettings"); - inParams["ResourceSettings"] = ((string[])(ResourceSettings)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ModifyResourceSettings", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null) && outParams.Properties["Job"].Value != null) { - Job = new System.Management.ManagementPath(outParams.Properties["Job"].Value.ToString()); - } - ResultingResourceSettings = null; - if ((outParams.Properties["ResultingResourceSettings"] != null)) { - int len = ((System.Array)(outParams.Properties["ResultingResourceSettings"].Value)).Length; - System.Management.ManagementPath[] arrToRet = new System.Management.ManagementPath[len]; - for (int iCounter = 0; (iCounter < len); iCounter = (iCounter + 1)) { - arrToRet[iCounter] = new System.Management.ManagementPath(((System.Array)(outParams.Properties["ResultingResourceSettings"].Value)).GetValue(iCounter).ToString()); - } - ResultingResourceSettings = arrToRet; - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - ResultingResourceSettings = null; - return System.Convert.ToUInt32(0); - } - } - - public uint ModifySystemSettings(string SystemSettings, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("ModifySystemSettings"); - inParams["SystemSettings"] = ((string)(SystemSettings)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ModifySystemSettings", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null) && outParams.Properties["Job"].Value != null) { - Job = new System.Management.ManagementPath(outParams.Properties["Job"].Value.ToString()); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - return System.Convert.ToUInt32(0); - } - } - - public uint RemoveFeatureSettings(System.Management.ManagementPath[] FeatureSettings, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("RemoveFeatureSettings"); - if ((FeatureSettings != null)) { - int len = ((System.Array)(FeatureSettings)).Length; - string[] arrProp = new string[len]; - for (int iCounter = 0; (iCounter < len); iCounter = (iCounter + 1)) { - arrProp[iCounter] = ((System.Management.ManagementPath)(((System.Array)(FeatureSettings)).GetValue(iCounter))).Path; - } - inParams["FeatureSettings"] = arrProp; - } - else { - inParams["FeatureSettings"] = null; - } - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RemoveFeatureSettings", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null) && outParams.Properties["Job"].Value != null) { - Job = new System.Management.ManagementPath(outParams.Properties["Job"].Value.ToString()); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - return System.Convert.ToUInt32(0); - } - } - - public uint RemoveResourceSettings(System.Management.ManagementPath[] ResourceSettings, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("RemoveResourceSettings"); - if ((ResourceSettings != null)) { - int len = ((System.Array)(ResourceSettings)).Length; - string[] arrProp = new string[len]; - for (int iCounter = 0; (iCounter < len); iCounter = (iCounter + 1)) { - arrProp[iCounter] = ((System.Management.ManagementPath)(((System.Array)(ResourceSettings)).GetValue(iCounter))).Path; - } - inParams["ResourceSettings"] = arrProp; - } - else { - inParams["ResourceSettings"] = null; - } - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RemoveResourceSettings", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null) && outParams.Properties["Job"].Value != null) - { - Job = new System.Management.ManagementPath(outParams.Properties["Job"].Value.ToString()); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - return System.Convert.ToUInt32(0); - } - } - - public uint RequestStateChange(ushort RequestedState, System.DateTime TimeoutPeriod, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("RequestStateChange"); - inParams["RequestedState"] = ((ushort)(RequestedState)); - inParams["TimeoutPeriod"] = ToDmtfDateTime(((System.DateTime)(TimeoutPeriod))); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RequestStateChange", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null) && outParams.Properties["Job"].Value != null) { - Job = new System.Management.ManagementPath(outParams.Properties["Job"].Value.ToString()); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - return System.Convert.ToUInt32(0); - } - } - - public uint StartService() { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("StartService", inParams, null); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - return System.Convert.ToUInt32(0); - } - } - - public uint StopService() { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("StopService", inParams, null); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - return System.Convert.ToUInt32(0); - } - } - - // Enumerator implementation for enumerating instances of the class. - public class VirtualEthernetSwitchManagementServiceCollection : object, ICollection { - - private ManagementObjectCollection privColObj; - - public VirtualEthernetSwitchManagementServiceCollection(ManagementObjectCollection objCollection) { - privColObj = objCollection; - } - - public virtual int Count { - get { - return privColObj.Count; - } - } - - public virtual bool IsSynchronized { - get { - return privColObj.IsSynchronized; - } - } - - public virtual object SyncRoot { - get { - return this; - } - } - - public virtual void CopyTo(System.Array array, int index) { - privColObj.CopyTo(array, index); - int nCtr; - for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { - array.SetValue(new VirtualEthernetSwitchManagementService(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); - } - } - - public virtual System.Collections.IEnumerator GetEnumerator() { - return new VirtualEthernetSwitchManagementServiceEnumerator(privColObj.GetEnumerator()); - } - - public class VirtualEthernetSwitchManagementServiceEnumerator : object, System.Collections.IEnumerator { - - private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; - - public VirtualEthernetSwitchManagementServiceEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { - privObjEnum = objEnum; - } - - public virtual object Current { - get { - return new VirtualEthernetSwitchManagementService(((System.Management.ManagementObject)(privObjEnum.Current))); - } - } - - public virtual bool MoveNext() { - return privObjEnum.MoveNext(); - } - - public virtual void Reset() { - privObjEnum.Reset(); - } - } - } - - // TypeConverter to handle null values for ValueType properties - public class WMIValueTypeConverter : TypeConverter { - - private TypeConverter baseConverter; - - private System.Type baseType; - - public WMIValueTypeConverter(System.Type inBaseType) { - baseConverter = TypeDescriptor.GetConverter(inBaseType); - baseType = inBaseType; - } - - public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { - return baseConverter.CanConvertFrom(context, srcType); - } - - public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { - return baseConverter.CanConvertTo(context, destinationType); - } - - public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { - return baseConverter.ConvertFrom(context, culture, value); - } - - public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { - return baseConverter.CreateInstance(context, dictionary); - } - - public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetCreateInstanceSupported(context); - } - - public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { - return baseConverter.GetProperties(context, value, attributeVar); - } - - public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetPropertiesSupported(context); - } - - public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValues(context); - } - - public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesExclusive(context); - } - - public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesSupported(context); - } - - public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { - if ((baseType.BaseType == typeof(System.Enum))) { - if ((value.GetType() == destinationType)) { - return value; - } - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return "NULL_ENUM_VALUE" ; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((baseType == typeof(bool)) - && (baseType.BaseType == typeof(System.ValueType)))) { - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((context != null) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - } - - // Embedded class to represent WMI system Properties. - [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] - public class ManagementSystemProperties { - - private System.Management.ManagementBaseObject PrivateLateBoundObject; - - public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { - PrivateLateBoundObject = ManagedObject; - } - - [Browsable(true)] - public int GENUS { - get { - return ((int)(PrivateLateBoundObject["__GENUS"])); - } - } - - [Browsable(true)] - public string CLASS { - get { - return ((string)(PrivateLateBoundObject["__CLASS"])); - } - } - - [Browsable(true)] - public string SUPERCLASS { - get { - return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); - } - } - - [Browsable(true)] - public string DYNASTY { - get { - return ((string)(PrivateLateBoundObject["__DYNASTY"])); - } - } - - [Browsable(true)] - public string RELPATH { - get { - return ((string)(PrivateLateBoundObject["__RELPATH"])); - } - } - - [Browsable(true)] - public int PROPERTY_COUNT { - get { - return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); - } - } - - [Browsable(true)] - public string[] DERIVATION { - get { - return ((string[])(PrivateLateBoundObject["__DERIVATION"])); - } - } - - [Browsable(true)] - public string SERVER { - get { - return ((string)(PrivateLateBoundObject["__SERVER"])); - } - } - - [Browsable(true)] - public string NAMESPACE { - get { - return ((string)(PrivateLateBoundObject["__NAMESPACE"])); - } - } - - [Browsable(true)] - public string PATH { - get { - return ((string)(PrivateLateBoundObject["__PATH"])); - } - } - } - } -} +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2 { + using System; + using System.ComponentModel; + using System.Management; + using System.Collections; + using System.Globalization; + using System.ComponentModel.Design.Serialization; + using System.Reflection; + + + // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. + // Functions IsNull() are used to check if a property is NULL. + // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. + // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. + // Datetime conversion functions ToDateTime and ToDmtfDateTime are added to the class to convert DMTF datetime to System.DateTime and vice-versa. + // An Early Bound class generated for the WMI class.Msvm_VirtualEthernetSwitchManagementService + public class VirtualEthernetSwitchManagementService : System.ComponentModel.Component { + + // Private property to hold the WMI namespace in which the class resides. + private static string CreatedWmiNamespace = "ROOT\\virtualization\\v2"; + + // Private property to hold the name of WMI class which created this class. + private static string CreatedClassName = "Msvm_VirtualEthernetSwitchManagementService"; + + // Private member variable to hold the ManagementScope which is used by the various methods. + private static System.Management.ManagementScope statMgmtScope = null; + + private ManagementSystemProperties PrivateSystemProperties; + + // Underlying lateBound WMI object. + private System.Management.ManagementObject PrivateLateBoundObject; + + // Member variable to store the 'automatic commit' behavior for the class. + private bool AutoCommitProp; + + // Private variable to hold the embedded property representing the instance. + private System.Management.ManagementBaseObject embeddedObj; + + // The current WMI object used + private System.Management.ManagementBaseObject curObj; + + // Flag to indicate if the instance is an embedded object. + private bool isEmbedded; + + // Below are different overloads of constructors to initialize an instance of the class with a WMI object. + public VirtualEthernetSwitchManagementService() { + this.InitializeObject(null, null, null); + } + + public VirtualEthernetSwitchManagementService(string keyCreationClassName, string keyName, string keySystemCreationClassName, string keySystemName) { + this.InitializeObject(null, new System.Management.ManagementPath(VirtualEthernetSwitchManagementService.ConstructPath(keyCreationClassName, keyName, keySystemCreationClassName, keySystemName)), null); + } + + public VirtualEthernetSwitchManagementService(System.Management.ManagementScope mgmtScope, string keyCreationClassName, string keyName, string keySystemCreationClassName, string keySystemName) { + this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(VirtualEthernetSwitchManagementService.ConstructPath(keyCreationClassName, keyName, keySystemCreationClassName, keySystemName)), null); + } + + public VirtualEthernetSwitchManagementService(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(null, path, getOptions); + } + + public VirtualEthernetSwitchManagementService(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { + this.InitializeObject(mgmtScope, path, null); + } + + public VirtualEthernetSwitchManagementService(System.Management.ManagementPath path) { + this.InitializeObject(null, path, null); + } + + public VirtualEthernetSwitchManagementService(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(mgmtScope, path, getOptions); + } + + public VirtualEthernetSwitchManagementService(System.Management.ManagementObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + PrivateLateBoundObject = theObject; + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + public VirtualEthernetSwitchManagementService(System.Management.ManagementBaseObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + embeddedObj = theObject; + PrivateSystemProperties = new ManagementSystemProperties(theObject); + curObj = embeddedObj; + isEmbedded = true; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + // Property returns the namespace of the WMI class. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OriginatingNamespace { + get { + return "ROOT\\virtualization\\v2"; + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ManagementClassName { + get { + string strRet = CreatedClassName; + if ((curObj != null)) { + if ((curObj.ClassPath != null)) { + strRet = ((string)(curObj["__CLASS"])); + if (((strRet == null) + || (strRet == string.Empty))) { + strRet = CreatedClassName; + } + } + } + return strRet; + } + } + + // Property pointing to an embedded object to get System properties of the WMI object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ManagementSystemProperties SystemProperties { + get { + return PrivateSystemProperties; + } + } + + // Property returning the underlying lateBound object. + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementBaseObject LateBoundObject { + get { + return curObj; + } + } + + // ManagementScope of the object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementScope Scope { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Scope; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Scope = value; + } + } + } + + // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool AutoCommit { + get { + return AutoCommitProp; + } + set { + AutoCommitProp = value; + } + } + + // The ManagementPath of the underlying WMI object. + [Browsable(true)] + public System.Management.ManagementPath Path { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Path; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + if ((CheckIfProperClass(null, value, null) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + PrivateLateBoundObject.Path = value; + } + } + } + + // Public static scope property which is used by the various methods. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public static System.Management.ManagementScope StaticScope { + get { + return statMgmtScope; + } + set { + statMgmtScope = value; + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ushort[] AvailableRequestedStates { + get { + return ((ushort[])(curObj["AvailableRequestedStates"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Caption { + get { + return ((string)(curObj["Caption"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsCommunicationStatusNull { + get { + if ((curObj["CommunicationStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort CommunicationStatus { + get { + if ((curObj["CommunicationStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["CommunicationStatus"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string CreationClassName { + get { + return ((string)(curObj["CreationClassName"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Description { + get { + return ((string)(curObj["Description"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsDetailedStatusNull { + get { + if ((curObj["DetailedStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort DetailedStatus { + get { + if ((curObj["DetailedStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["DetailedStatus"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ElementName { + get { + return ((string)(curObj["ElementName"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsEnabledDefaultNull { + get { + if ((curObj["EnabledDefault"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort EnabledDefault { + get { + if ((curObj["EnabledDefault"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["EnabledDefault"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsEnabledStateNull { + get { + if ((curObj["EnabledState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort EnabledState { + get { + if ((curObj["EnabledState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["EnabledState"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsHealthStateNull { + get { + if ((curObj["HealthState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort HealthState { + get { + if ((curObj["HealthState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["HealthState"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsInstallDateNull { + get { + if ((curObj["InstallDate"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime InstallDate { + get { + if ((curObj["InstallDate"] != null)) { + return ToDateTime(((string)(curObj["InstallDate"]))); + } + else { + return System.DateTime.MinValue; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string InstanceID { + get { + return ((string)(curObj["InstanceID"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Name { + get { + return ((string)(curObj["Name"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsOperatingStatusNull { + get { + if ((curObj["OperatingStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort OperatingStatus { + get { + if ((curObj["OperatingStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["OperatingStatus"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ushort[] OperationalStatus { + get { + return ((ushort[])(curObj["OperationalStatus"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherEnabledState { + get { + return ((string)(curObj["OtherEnabledState"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string PrimaryOwnerContact { + get { + return ((string)(curObj["PrimaryOwnerContact"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string PrimaryOwnerName { + get { + return ((string)(curObj["PrimaryOwnerName"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPrimaryStatusNull { + get { + if ((curObj["PrimaryStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort PrimaryStatus { + get { + if ((curObj["PrimaryStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["PrimaryStatus"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsRequestedStateNull { + get { + if ((curObj["RequestedState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort RequestedState { + get { + if ((curObj["RequestedState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["RequestedState"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsStartedNull { + get { + if ((curObj["Started"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool Started { + get { + if ((curObj["Started"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["Started"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string StartMode { + get { + return ((string)(curObj["StartMode"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Status { + get { + return ((string)(curObj["Status"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] StatusDescriptions { + get { + return ((string[])(curObj["StatusDescriptions"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string SystemCreationClassName { + get { + return ((string)(curObj["SystemCreationClassName"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string SystemName { + get { + return ((string)(curObj["SystemName"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsTimeOfLastStateChangeNull { + get { + if ((curObj["TimeOfLastStateChange"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime TimeOfLastStateChange { + get { + if ((curObj["TimeOfLastStateChange"] != null)) { + return ToDateTime(((string)(curObj["TimeOfLastStateChange"]))); + } + else { + return System.DateTime.MinValue; + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsTransitioningToStateNull { + get { + if ((curObj["TransitioningToState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort TransitioningToState { + get { + if ((curObj["TransitioningToState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["TransitioningToState"])); + } + } + + private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { + if (((path != null) + && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); + } + } + + private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { + if (((theObj != null) + && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); + if ((parentClasses != null)) { + int count = 0; + for (count = 0; (count < parentClasses.Length); count = (count + 1)) { + if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { + return true; + } + } + } + } + return false; + } + + private bool ShouldSerializeCommunicationStatus() { + if ((this.IsCommunicationStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeDetailedStatus() { + if ((this.IsDetailedStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeEnabledDefault() { + if ((this.IsEnabledDefaultNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeEnabledState() { + if ((this.IsEnabledStateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeHealthState() { + if ((this.IsHealthStateNull == false)) { + return true; + } + return false; + } + + // Converts a given datetime in DMTF format to System.DateTime object. + static System.DateTime ToDateTime(string dmtfDate) { + System.DateTime initializer = System.DateTime.MinValue; + int year = initializer.Year; + int month = initializer.Month; + int day = initializer.Day; + int hour = initializer.Hour; + int minute = initializer.Minute; + int second = initializer.Second; + long ticks = 0; + string dmtf = dmtfDate; + System.DateTime datetime = System.DateTime.MinValue; + string tempString = string.Empty; + if ((dmtf == null)) { + throw new System.ArgumentOutOfRangeException(); + } + if ((dmtf.Length == 0)) { + throw new System.ArgumentOutOfRangeException(); + } + if ((dmtf.Length != 25)) { + throw new System.ArgumentOutOfRangeException(); + } + try { + tempString = dmtf.Substring(0, 4); + if (("****" != tempString)) { + year = int.Parse(tempString); + } + tempString = dmtf.Substring(4, 2); + if (("**" != tempString)) { + month = int.Parse(tempString); + } + tempString = dmtf.Substring(6, 2); + if (("**" != tempString)) { + day = int.Parse(tempString); + } + tempString = dmtf.Substring(8, 2); + if (("**" != tempString)) { + hour = int.Parse(tempString); + } + tempString = dmtf.Substring(10, 2); + if (("**" != tempString)) { + minute = int.Parse(tempString); + } + tempString = dmtf.Substring(12, 2); + if (("**" != tempString)) { + second = int.Parse(tempString); + } + tempString = dmtf.Substring(15, 6); + if (("******" != tempString)) { + ticks = (long.Parse(tempString) * ((long)((System.TimeSpan.TicksPerMillisecond / 1000)))); + } + if (((((((((year < 0) + || (month < 0)) + || (day < 0)) + || (hour < 0)) + || (minute < 0)) + || (minute < 0)) + || (second < 0)) + || (ticks < 0))) { + throw new System.ArgumentOutOfRangeException(); + } + } + catch (System.Exception e) { + throw new System.ArgumentOutOfRangeException(null, e.Message); + } + datetime = new System.DateTime(year, month, day, hour, minute, second, 0); + datetime = datetime.AddTicks(ticks); + System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(datetime); + int UTCOffset = 0; + int OffsetToBeAdjusted = 0; + long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); + tempString = dmtf.Substring(22, 3); + if ((tempString != "******")) { + tempString = dmtf.Substring(21, 4); + try { + UTCOffset = int.Parse(tempString); + } + catch (System.Exception e) { + throw new System.ArgumentOutOfRangeException(null, e.Message); + } + OffsetToBeAdjusted = ((int)((OffsetMins - UTCOffset))); + datetime = datetime.AddMinutes(((double)(OffsetToBeAdjusted))); + } + return datetime; + } + + // Converts a given System.DateTime object to DMTF datetime format. + static string ToDmtfDateTime(System.DateTime date) { + string utcString = string.Empty; + System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(date); + long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); + if ((System.Math.Abs(OffsetMins) > 999)) { + date = date.ToUniversalTime(); + utcString = "+000"; + } + else { + if ((tickOffset.Ticks >= 0)) { + utcString = string.Concat("+", ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))).ToString().PadLeft(3, '0')); + } + else { + string strTemp = ((long)(OffsetMins)).ToString(); + utcString = string.Concat("-", strTemp.Substring(1, (strTemp.Length - 1)).PadLeft(3, '0')); + } + } + string dmtfDateTime = ((int)(date.Year)).ToString().PadLeft(4, '0'); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Month)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Day)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Hour)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Minute)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Second)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, "."); + System.DateTime dtTemp = new System.DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, 0); + long microsec = ((long)((((date.Ticks - dtTemp.Ticks) + * 1000) + / System.TimeSpan.TicksPerMillisecond))); + string strMicrosec = ((long)(microsec)).ToString(); + if ((strMicrosec.Length > 6)) { + strMicrosec = strMicrosec.Substring(0, 6); + } + dmtfDateTime = string.Concat(dmtfDateTime, strMicrosec.PadLeft(6, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, utcString); + return dmtfDateTime; + } + + private bool ShouldSerializeInstallDate() { + if ((this.IsInstallDateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeOperatingStatus() { + if ((this.IsOperatingStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePrimaryStatus() { + if ((this.IsPrimaryStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeRequestedState() { + if ((this.IsRequestedStateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeStarted() { + if ((this.IsStartedNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeTimeOfLastStateChange() { + if ((this.IsTimeOfLastStateChangeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeTransitioningToState() { + if ((this.IsTransitioningToStateNull == false)) { + return true; + } + return false; + } + + [Browsable(true)] + public void CommitObject() { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(); + } + } + + [Browsable(true)] + public void CommitObject(System.Management.PutOptions putOptions) { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(putOptions); + } + } + + private void Initialize() { + AutoCommitProp = true; + isEmbedded = false; + } + + private static string ConstructPath(string keyCreationClassName, string keyName, string keySystemCreationClassName, string keySystemName) { + string strPath = "ROOT\\virtualization\\v2:Msvm_VirtualEthernetSwitchManagementService"; + strPath = string.Concat(strPath, string.Concat(".CreationClassName=", string.Concat("\"", string.Concat(keyCreationClassName, "\"")))); + strPath = string.Concat(strPath, string.Concat(",Name=", string.Concat("\"", string.Concat(keyName, "\"")))); + strPath = string.Concat(strPath, string.Concat(",SystemCreationClassName=", string.Concat("\"", string.Concat(keySystemCreationClassName, "\"")))); + strPath = string.Concat(strPath, string.Concat(",SystemName=", string.Concat("\"", string.Concat(keySystemName, "\"")))); + return strPath; + } + + private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + Initialize(); + if ((path != null)) { + if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + } + PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + + // Different overloads of GetInstances() help in enumerating instances of the WMI class. + public static VirtualEthernetSwitchManagementServiceCollection GetInstances() { + return GetInstances(null, null, null); + } + + public static VirtualEthernetSwitchManagementServiceCollection GetInstances(string condition) { + return GetInstances(null, condition, null); + } + + public static VirtualEthernetSwitchManagementServiceCollection GetInstances(string[] selectedProperties) { + return GetInstances(null, null, selectedProperties); + } + + public static VirtualEthernetSwitchManagementServiceCollection GetInstances(string condition, string[] selectedProperties) { + return GetInstances(null, condition, selectedProperties); + } + + public static VirtualEthernetSwitchManagementServiceCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); + pathObj.ClassName = "Msvm_VirtualEthernetSwitchManagementService"; + pathObj.NamespacePath = "root\\virtualization\\v2"; + System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); + if ((enumOptions == null)) { + enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + } + return new VirtualEthernetSwitchManagementServiceCollection(clsObject.GetInstances(enumOptions)); + } + + public static VirtualEthernetSwitchManagementServiceCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { + return GetInstances(mgmtScope, condition, null); + } + + public static VirtualEthernetSwitchManagementServiceCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { + return GetInstances(mgmtScope, null, selectedProperties); + } + + public static VirtualEthernetSwitchManagementServiceCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_VirtualEthernetSwitchManagementService", condition, selectedProperties)); + System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + ObjectSearcher.Options = enumOptions; + return new VirtualEthernetSwitchManagementServiceCollection(ObjectSearcher.Get()); + } + + [Browsable(true)] + public static VirtualEthernetSwitchManagementService CreateInstance() { + System.Management.ManagementScope mgmtScope = null; + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = CreatedWmiNamespace; + } + else { + mgmtScope = statMgmtScope; + } + System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); + System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); + return new VirtualEthernetSwitchManagementService(tmpMgmtClass.CreateInstance()); + } + + [Browsable(true)] + public void Delete() { + PrivateLateBoundObject.Delete(); + } + + public uint AddFeatureSettings(System.Management.ManagementPath AffectedConfiguration, string[] FeatureSettings, out System.Management.ManagementPath Job, out System.Management.ManagementPath[] ResultingFeatureSettings) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("AddFeatureSettings"); + inParams["AffectedConfiguration"] = ((System.Management.ManagementPath)(AffectedConfiguration)).Path; + inParams["FeatureSettings"] = ((string[])(FeatureSettings)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("AddFeatureSettings", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null) && outParams.Properties["Job"].Value != null) { + Job = new System.Management.ManagementPath(outParams.Properties["Job"].Value.ToString()); + } + ResultingFeatureSettings = null; + if ((outParams.Properties["ResultingFeatureSettings"] != null)) { + int len = ((System.Array)(outParams.Properties["ResultingFeatureSettings"].Value)).Length; + System.Management.ManagementPath[] arrToRet = new System.Management.ManagementPath[len]; + for (int iCounter = 0; (iCounter < len); iCounter = (iCounter + 1)) { + arrToRet[iCounter] = new System.Management.ManagementPath(((System.Array)(outParams.Properties["ResultingFeatureSettings"].Value)).GetValue(iCounter).ToString()); + } + ResultingFeatureSettings = arrToRet; + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + ResultingFeatureSettings = null; + return System.Convert.ToUInt32(0); + } + } + + public uint AddResourceSettings(System.Management.ManagementPath AffectedConfiguration, string[] ResourceSettings, out System.Management.ManagementPath Job, out System.Management.ManagementPath[] ResultingResourceSettings) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("AddResourceSettings"); + inParams["AffectedConfiguration"] = ((System.Management.ManagementPath)(AffectedConfiguration)).Path; + inParams["ResourceSettings"] = ((string[])(ResourceSettings)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("AddResourceSettings", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null) && outParams.Properties["Job"].Value != null) { + Job = new System.Management.ManagementPath(outParams.Properties["Job"].Value.ToString()); + } + ResultingResourceSettings = null; + if ((outParams.Properties["ResultingResourceSettings"] != null)) { + int len = ((System.Array)(outParams.Properties["ResultingResourceSettings"].Value)).Length; + System.Management.ManagementPath[] arrToRet = new System.Management.ManagementPath[len]; + for (int iCounter = 0; (iCounter < len); iCounter = (iCounter + 1)) { + arrToRet[iCounter] = new System.Management.ManagementPath(((System.Array)(outParams.Properties["ResultingResourceSettings"].Value)).GetValue(iCounter).ToString()); + } + ResultingResourceSettings = arrToRet; + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + ResultingResourceSettings = null; + return System.Convert.ToUInt32(0); + } + } + + public uint DefineSystem(System.Management.ManagementPath ReferenceConfiguration, string[] ResourceSettings, string SystemSettings, out System.Management.ManagementPath Job, out System.Management.ManagementPath ResultingSystem) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("DefineSystem"); + inParams["ReferenceConfiguration"] = ((System.Management.ManagementPath)(ReferenceConfiguration)).Path; + inParams["ResourceSettings"] = ((string[])(ResourceSettings)); + inParams["SystemSettings"] = ((string)(SystemSettings)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("DefineSystem", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null) && outParams.Properties["Job"].Value != null) { + Job = new System.Management.ManagementPath(outParams.Properties["Job"].Value.ToString()); + } + ResultingSystem = null; + if ((outParams.Properties["ResultingSystem"] != null)) { + ResultingSystem = new System.Management.ManagementPath(outParams.Properties["ResultingSystem"].ToString()); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + ResultingSystem = null; + return System.Convert.ToUInt32(0); + } + } + + public uint DestroySystem(System.Management.ManagementPath AffectedSystem, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("DestroySystem"); + inParams["AffectedSystem"] = ((System.Management.ManagementPath)(AffectedSystem)).Path; + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("DestroySystem", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null) && outParams.Properties["Job"].Value != null) { + Job = new System.Management.ManagementPath(outParams.Properties["Job"].Value.ToString()); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + return System.Convert.ToUInt32(0); + } + } + + public uint ModifyFeatureSettings(string[] FeatureSettings, out System.Management.ManagementPath Job, out System.Management.ManagementPath[] ResultingFeatureSettings) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("ModifyFeatureSettings"); + inParams["FeatureSettings"] = ((string[])(FeatureSettings)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ModifyFeatureSettings", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null) && outParams.Properties["Job"].Value != null) { + Job = new System.Management.ManagementPath(outParams.Properties["Job"].Value.ToString()); + } + ResultingFeatureSettings = null; + if ((outParams.Properties["ResultingFeatureSettings"] != null)) { + int len = ((System.Array)(outParams.Properties["ResultingFeatureSettings"].Value)).Length; + System.Management.ManagementPath[] arrToRet = new System.Management.ManagementPath[len]; + for (int iCounter = 0; (iCounter < len); iCounter = (iCounter + 1)) { + arrToRet[iCounter] = new System.Management.ManagementPath(((System.Array)(outParams.Properties["ResultingFeatureSettings"].Value)).GetValue(iCounter).ToString()); + } + ResultingFeatureSettings = arrToRet; + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + ResultingFeatureSettings = null; + return System.Convert.ToUInt32(0); + } + } + + public uint ModifyResourceSettings(string[] ResourceSettings, out System.Management.ManagementPath Job, out System.Management.ManagementPath[] ResultingResourceSettings) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("ModifyResourceSettings"); + inParams["ResourceSettings"] = ((string[])(ResourceSettings)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ModifyResourceSettings", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null) && outParams.Properties["Job"].Value != null) { + Job = new System.Management.ManagementPath(outParams.Properties["Job"].Value.ToString()); + } + ResultingResourceSettings = null; + if ((outParams.Properties["ResultingResourceSettings"] != null)) { + int len = ((System.Array)(outParams.Properties["ResultingResourceSettings"].Value)).Length; + System.Management.ManagementPath[] arrToRet = new System.Management.ManagementPath[len]; + for (int iCounter = 0; (iCounter < len); iCounter = (iCounter + 1)) { + arrToRet[iCounter] = new System.Management.ManagementPath(((System.Array)(outParams.Properties["ResultingResourceSettings"].Value)).GetValue(iCounter).ToString()); + } + ResultingResourceSettings = arrToRet; + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + ResultingResourceSettings = null; + return System.Convert.ToUInt32(0); + } + } + + public uint ModifySystemSettings(string SystemSettings, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("ModifySystemSettings"); + inParams["SystemSettings"] = ((string)(SystemSettings)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ModifySystemSettings", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null) && outParams.Properties["Job"].Value != null) { + Job = new System.Management.ManagementPath(outParams.Properties["Job"].Value.ToString()); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + return System.Convert.ToUInt32(0); + } + } + + public uint RemoveFeatureSettings(System.Management.ManagementPath[] FeatureSettings, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("RemoveFeatureSettings"); + if ((FeatureSettings != null)) { + int len = ((System.Array)(FeatureSettings)).Length; + string[] arrProp = new string[len]; + for (int iCounter = 0; (iCounter < len); iCounter = (iCounter + 1)) { + arrProp[iCounter] = ((System.Management.ManagementPath)(((System.Array)(FeatureSettings)).GetValue(iCounter))).Path; + } + inParams["FeatureSettings"] = arrProp; + } + else { + inParams["FeatureSettings"] = null; + } + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RemoveFeatureSettings", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null) && outParams.Properties["Job"].Value != null) { + Job = new System.Management.ManagementPath(outParams.Properties["Job"].Value.ToString()); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + return System.Convert.ToUInt32(0); + } + } + + public uint RemoveResourceSettings(System.Management.ManagementPath[] ResourceSettings, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("RemoveResourceSettings"); + if ((ResourceSettings != null)) { + int len = ((System.Array)(ResourceSettings)).Length; + string[] arrProp = new string[len]; + for (int iCounter = 0; (iCounter < len); iCounter = (iCounter + 1)) { + arrProp[iCounter] = ((System.Management.ManagementPath)(((System.Array)(ResourceSettings)).GetValue(iCounter))).Path; + } + inParams["ResourceSettings"] = arrProp; + } + else { + inParams["ResourceSettings"] = null; + } + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RemoveResourceSettings", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null) && outParams.Properties["Job"].Value != null) + { + Job = new System.Management.ManagementPath(outParams.Properties["Job"].Value.ToString()); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + return System.Convert.ToUInt32(0); + } + } + + public uint RequestStateChange(ushort RequestedState, System.DateTime TimeoutPeriod, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("RequestStateChange"); + inParams["RequestedState"] = ((ushort)(RequestedState)); + inParams["TimeoutPeriod"] = ToDmtfDateTime(((System.DateTime)(TimeoutPeriod))); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RequestStateChange", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null) && outParams.Properties["Job"].Value != null) { + Job = new System.Management.ManagementPath(outParams.Properties["Job"].Value.ToString()); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + return System.Convert.ToUInt32(0); + } + } + + public uint StartService() { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("StartService", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + public uint StopService() { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("StopService", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + // Enumerator implementation for enumerating instances of the class. + public class VirtualEthernetSwitchManagementServiceCollection : object, ICollection { + + private ManagementObjectCollection privColObj; + + public VirtualEthernetSwitchManagementServiceCollection(ManagementObjectCollection objCollection) { + privColObj = objCollection; + } + + public virtual int Count { + get { + return privColObj.Count; + } + } + + public virtual bool IsSynchronized { + get { + return privColObj.IsSynchronized; + } + } + + public virtual object SyncRoot { + get { + return this; + } + } + + public virtual void CopyTo(System.Array array, int index) { + privColObj.CopyTo(array, index); + int nCtr; + for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { + array.SetValue(new VirtualEthernetSwitchManagementService(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); + } + } + + public virtual System.Collections.IEnumerator GetEnumerator() { + return new VirtualEthernetSwitchManagementServiceEnumerator(privColObj.GetEnumerator()); + } + + public class VirtualEthernetSwitchManagementServiceEnumerator : object, System.Collections.IEnumerator { + + private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; + + public VirtualEthernetSwitchManagementServiceEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { + privObjEnum = objEnum; + } + + public virtual object Current { + get { + return new VirtualEthernetSwitchManagementService(((System.Management.ManagementObject)(privObjEnum.Current))); + } + } + + public virtual bool MoveNext() { + return privObjEnum.MoveNext(); + } + + public virtual void Reset() { + privObjEnum.Reset(); + } + } + } + + // TypeConverter to handle null values for ValueType properties + public class WMIValueTypeConverter : TypeConverter { + + private TypeConverter baseConverter; + + private System.Type baseType; + + public WMIValueTypeConverter(System.Type inBaseType) { + baseConverter = TypeDescriptor.GetConverter(inBaseType); + baseType = inBaseType; + } + + public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { + return baseConverter.CanConvertFrom(context, srcType); + } + + public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { + return baseConverter.CanConvertTo(context, destinationType); + } + + public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { + return baseConverter.ConvertFrom(context, culture, value); + } + + public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { + return baseConverter.CreateInstance(context, dictionary); + } + + public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetCreateInstanceSupported(context); + } + + public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { + return baseConverter.GetProperties(context, value, attributeVar); + } + + public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetPropertiesSupported(context); + } + + public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValues(context); + } + + public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesExclusive(context); + } + + public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesSupported(context); + } + + public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { + if ((baseType.BaseType == typeof(System.Enum))) { + if ((value.GetType() == destinationType)) { + return value; + } + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return "NULL_ENUM_VALUE" ; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((baseType == typeof(bool)) + && (baseType.BaseType == typeof(System.ValueType)))) { + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((context != null) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + } + + // Embedded class to represent WMI system Properties. + [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] + public class ManagementSystemProperties { + + private System.Management.ManagementBaseObject PrivateLateBoundObject; + + public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { + PrivateLateBoundObject = ManagedObject; + } + + [Browsable(true)] + public int GENUS { + get { + return ((int)(PrivateLateBoundObject["__GENUS"])); + } + } + + [Browsable(true)] + public string CLASS { + get { + return ((string)(PrivateLateBoundObject["__CLASS"])); + } + } + + [Browsable(true)] + public string SUPERCLASS { + get { + return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); + } + } + + [Browsable(true)] + public string DYNASTY { + get { + return ((string)(PrivateLateBoundObject["__DYNASTY"])); + } + } + + [Browsable(true)] + public string RELPATH { + get { + return ((string)(PrivateLateBoundObject["__RELPATH"])); + } + } + + [Browsable(true)] + public int PROPERTY_COUNT { + get { + return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); + } + } + + [Browsable(true)] + public string[] DERIVATION { + get { + return ((string[])(PrivateLateBoundObject["__DERIVATION"])); + } + } + + [Browsable(true)] + public string SERVER { + get { + return ((string)(PrivateLateBoundObject["__SERVER"])); + } + } + + [Browsable(true)] + public string NAMESPACE { + get { + return ((string)(PrivateLateBoundObject["__NAMESPACE"])); + } + } + + [Browsable(true)] + public string PATH { + get { + return ((string)(PrivateLateBoundObject["__PATH"])); + } + } + } + } +} diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_VirtualHardDiskSettingData.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_VirtualHardDiskSettingData.cs index 94851c54cc7..9f1a738e4eb 100644 --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_VirtualHardDiskSettingData.cs +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_VirtualHardDiskSettingData.cs @@ -1,1051 +1,1051 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2 { - using System; - using System.ComponentModel; - using System.Management; - using System.Collections; - using System.Globalization; - using System.ComponentModel.Design.Serialization; - using System.Reflection; - - - // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. - // Functions IsNull() are used to check if a property is NULL. - // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. - // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. - // An Early Bound class generated for the WMI class.Msvm_VirtualHardDiskSettingData - public class VirtualHardDiskSettingData : System.ComponentModel.Component { - - // Private property to hold the WMI namespace in which the class resides. - private static string CreatedWmiNamespace = "ROOT\\virtualization\\v2"; - - // Private property to hold the name of WMI class which created this class. - private static string CreatedClassName = "Msvm_VirtualHardDiskSettingData"; - - // Private member variable to hold the ManagementScope which is used by the various methods. - private static System.Management.ManagementScope statMgmtScope = null; - - private ManagementSystemProperties PrivateSystemProperties; - - // Underlying lateBound WMI object. - private System.Management.ManagementObject PrivateLateBoundObject; - - // Member variable to store the 'automatic commit' behavior for the class. - private bool AutoCommitProp; - - // Private variable to hold the embedded property representing the instance. - private System.Management.ManagementBaseObject embeddedObj; - - // The current WMI object used - private System.Management.ManagementBaseObject curObj; - - // Flag to indicate if the instance is an embedded object. - private bool isEmbedded; - - // Below are different overloads of constructors to initialize an instance of the class with a WMI object. - public VirtualHardDiskSettingData() { - this.InitializeObject(null, null, null); - } - - public VirtualHardDiskSettingData(string keyInstanceID) { - this.InitializeObject(null, new System.Management.ManagementPath(VirtualHardDiskSettingData.ConstructPath(keyInstanceID)), null); - } - - public VirtualHardDiskSettingData(System.Management.ManagementScope mgmtScope, string keyInstanceID) { - this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(VirtualHardDiskSettingData.ConstructPath(keyInstanceID)), null); - } - - public VirtualHardDiskSettingData(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(null, path, getOptions); - } - - public VirtualHardDiskSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { - this.InitializeObject(mgmtScope, path, null); - } - - public VirtualHardDiskSettingData(System.Management.ManagementPath path) { - this.InitializeObject(null, path, null); - } - - public VirtualHardDiskSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(mgmtScope, path, getOptions); - } - - public VirtualHardDiskSettingData(System.Management.ManagementObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - PrivateLateBoundObject = theObject; - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - public VirtualHardDiskSettingData(System.Management.ManagementBaseObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - embeddedObj = theObject; - PrivateSystemProperties = new ManagementSystemProperties(theObject); - curObj = embeddedObj; - isEmbedded = true; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - // Property returns the namespace of the WMI class. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OriginatingNamespace { - get { - return "ROOT\\virtualization\\v2"; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ManagementClassName { - get { - string strRet = CreatedClassName; - if ((curObj != null)) { - if ((curObj.ClassPath != null)) { - strRet = ((string)(curObj["__CLASS"])); - if (((strRet == null) - || (strRet == string.Empty))) { - strRet = CreatedClassName; - } - } - } - return strRet; - } - } - - // Property pointing to an embedded object to get System properties of the WMI object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ManagementSystemProperties SystemProperties { - get { - return PrivateSystemProperties; - } - } - - // Property returning the underlying lateBound object. - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementBaseObject LateBoundObject { - get { - return curObj; - } - } - - // ManagementScope of the object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementScope Scope { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Scope; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Scope = value; - } - } - } - - // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool AutoCommit { - get { - return AutoCommitProp; - } - set { - AutoCommitProp = value; - } - } - - // The ManagementPath of the underlying WMI object. - [Browsable(true)] - public System.Management.ManagementPath Path { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Path; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - if ((CheckIfProperClass(null, value, null) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - PrivateLateBoundObject.Path = value; - } - } - } - - // Public static scope property which is used by the various methods. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public static System.Management.ManagementScope StaticScope { - get { - return statMgmtScope; - } - set { - statMgmtScope = value; - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsBlockSizeNull { - get { - if ((curObj["BlockSize"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The block size used by the virtual hard disk")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public uint BlockSize { - get { - if ((curObj["BlockSize"] == null)) { - return System.Convert.ToUInt32(0); - } - return ((uint)(curObj["BlockSize"])); - } - set { - curObj["BlockSize"] = value; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Caption { - get { - return ((string)(curObj["Caption"])); - } - set { - curObj["Caption"] = value; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Description { - get { - return ((string)(curObj["Description"])); - } - set { - curObj["Description"] = value; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ElementName { - get { - return ((string)(curObj["ElementName"])); - } - set { - curObj["ElementName"] = value; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsFormatNull { - get { - if ((curObj["Format"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The format for the virtual hard disk.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public FormatValues Format { - get { - if ((curObj["Format"] == null)) { - return ((FormatValues)(System.Convert.ToInt32(0))); - } - return ((FormatValues)(System.Convert.ToInt32(curObj["Format"]))); - } - set { - if ((FormatValues.NULL_ENUM_VALUE == value)) { - curObj["Format"] = null; - } - else { - curObj["Format"] = value; - } - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string InstanceID { - get { - return ((string)(curObj["InstanceID"])); - } - set { - curObj["InstanceID"] = value; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsLogicalSectorSizeNull { - get { - if ((curObj["LogicalSectorSize"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The logical sector size used by the virtual hard disk")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public uint LogicalSectorSize { - get { - if ((curObj["LogicalSectorSize"] == null)) { - return System.Convert.ToUInt32(0); - } - return ((uint)(curObj["LogicalSectorSize"])); - } - set { - curObj["LogicalSectorSize"] = value; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsMaxInternalSizeNull { - get { - if ((curObj["MaxInternalSize"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The maximum size of the virtual hard disk as viewable by the virtual machine, in " + - "bytes. The specified size will be rounded up to the next largest multiple of the" + - " sector size.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ulong MaxInternalSize { - get { - if ((curObj["MaxInternalSize"] == null)) { - return System.Convert.ToUInt64(0); - } - return ((ulong)(curObj["MaxInternalSize"])); - } - set { - curObj["MaxInternalSize"] = value; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The parent of the virtual hard disk. If the virtual hard disk does not have a par" + - "ent, then this field is empty.")] - public string ParentPath { - get { - return ((string)(curObj["ParentPath"])); - } - set { - curObj["ParentPath"] = value; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The path of the virtual hard disk.")] - public string Path0 { - get { - return ((string)(curObj["Path"])); - } - set { - curObj["Path"] = value; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsPhysicalSectorSizeNull { - get { - if ((curObj["PhysicalSectorSize"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The physical sector size used by the virtual hard disk")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public uint PhysicalSectorSize { - get { - if ((curObj["PhysicalSectorSize"] == null)) { - return System.Convert.ToUInt32(0); - } - return ((uint)(curObj["PhysicalSectorSize"])); - } - set { - curObj["PhysicalSectorSize"] = value; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsTypeNull { - get { - if ((curObj["Type"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The type of virtual hard disk.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public TypeValues Type { - get { - if ((curObj["Type"] == null)) { - return ((TypeValues)(System.Convert.ToInt32(0))); - } - return ((TypeValues)(System.Convert.ToInt32(curObj["Type"]))); - } - set { - if ((TypeValues.NULL_ENUM_VALUE == value)) { - curObj["Type"] = null; - } - else { - curObj["Type"] = value; - } - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - } - - private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { - if (((path != null) - && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); - } - } - - private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { - if (((theObj != null) - && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); - if ((parentClasses != null)) { - int count = 0; - for (count = 0; (count < parentClasses.Length); count = (count + 1)) { - if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { - return true; - } - } - } - } - return false; - } - - private bool ShouldSerializeBlockSize() { - if ((this.IsBlockSizeNull == false)) { - return true; - } - return false; - } - - private void ResetBlockSize() { - curObj["BlockSize"] = null; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - - private void ResetCaption() { - curObj["Caption"] = null; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - - private void ResetDescription() { - curObj["Description"] = null; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - - private void ResetElementName() { - curObj["ElementName"] = null; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - - private bool ShouldSerializeFormat() { - if ((this.IsFormatNull == false)) { - return true; - } - return false; - } - - private void ResetFormat() { - curObj["Format"] = null; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - - private bool ShouldSerializeLogicalSectorSize() { - if ((this.IsLogicalSectorSizeNull == false)) { - return true; - } - return false; - } - - private void ResetLogicalSectorSize() { - curObj["LogicalSectorSize"] = null; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - - private bool ShouldSerializeMaxInternalSize() { - if ((this.IsMaxInternalSizeNull == false)) { - return true; - } - return false; - } - - private void ResetMaxInternalSize() { - curObj["MaxInternalSize"] = null; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - - private void ResetParentPath() { - curObj["ParentPath"] = null; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - - private void ResetPath0() { - curObj["Path"] = null; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - - private bool ShouldSerializePhysicalSectorSize() { - if ((this.IsPhysicalSectorSizeNull == false)) { - return true; - } - return false; - } - - private void ResetPhysicalSectorSize() { - curObj["PhysicalSectorSize"] = null; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - - private bool ShouldSerializeType() { - if ((this.IsTypeNull == false)) { - return true; - } - return false; - } - - private void ResetType() { - curObj["Type"] = null; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - - [Browsable(true)] - public void CommitObject() { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(); - } - } - - [Browsable(true)] - public void CommitObject(System.Management.PutOptions putOptions) { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(putOptions); - } - } - - private void Initialize() { - AutoCommitProp = true; - isEmbedded = false; - } - - private static string ConstructPath(string keyInstanceID) { - string strPath = "ROOT\\virtualization\\v2:Msvm_VirtualHardDiskSettingData"; - strPath = string.Concat(strPath, string.Concat(".InstanceID=", string.Concat("\"", string.Concat(keyInstanceID, "\"")))); - return strPath; - } - - private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - Initialize(); - if ((path != null)) { - if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - } - PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - - // Different overloads of GetInstances() help in enumerating instances of the WMI class. - public static VirtualHardDiskSettingDataCollection GetInstances() { - return GetInstances(null, null, null); - } - - public static VirtualHardDiskSettingDataCollection GetInstances(string condition) { - return GetInstances(null, condition, null); - } - - public static VirtualHardDiskSettingDataCollection GetInstances(string[] selectedProperties) { - return GetInstances(null, null, selectedProperties); - } - - public static VirtualHardDiskSettingDataCollection GetInstances(string condition, string[] selectedProperties) { - return GetInstances(null, condition, selectedProperties); - } - - public static VirtualHardDiskSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); - pathObj.ClassName = "Msvm_VirtualHardDiskSettingData"; - pathObj.NamespacePath = "root\\virtualization\\v2"; - System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); - if ((enumOptions == null)) { - enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - } - return new VirtualHardDiskSettingDataCollection(clsObject.GetInstances(enumOptions)); - } - - public static VirtualHardDiskSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { - return GetInstances(mgmtScope, condition, null); - } - - public static VirtualHardDiskSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { - return GetInstances(mgmtScope, null, selectedProperties); - } - - public static VirtualHardDiskSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_VirtualHardDiskSettingData", condition, selectedProperties)); - System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - ObjectSearcher.Options = enumOptions; - return new VirtualHardDiskSettingDataCollection(ObjectSearcher.Get()); - } - - [Browsable(true)] - public static VirtualHardDiskSettingData CreateInstance() { - System.Management.ManagementScope mgmtScope = null; - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = CreatedWmiNamespace; - } - else { - mgmtScope = statMgmtScope; - } - System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); - System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); - return new VirtualHardDiskSettingData(tmpMgmtClass.CreateInstance()); - } - - [Browsable(true)] - public void Delete() { - PrivateLateBoundObject.Delete(); - } - - public enum FormatValues { - - VHD = 2, - - VHDX = 3, - - NULL_ENUM_VALUE = 0, - } - - public enum TypeValues { - - Fixed = 2, - - Dynamic = 3, - - Differencing = 4, - - NULL_ENUM_VALUE = 0, - } - - // Enumerator implementation for enumerating instances of the class. - public class VirtualHardDiskSettingDataCollection : object, ICollection { - - private ManagementObjectCollection privColObj; - - public VirtualHardDiskSettingDataCollection(ManagementObjectCollection objCollection) { - privColObj = objCollection; - } - - public virtual int Count { - get { - return privColObj.Count; - } - } - - public virtual bool IsSynchronized { - get { - return privColObj.IsSynchronized; - } - } - - public virtual object SyncRoot { - get { - return this; - } - } - - public virtual void CopyTo(System.Array array, int index) { - privColObj.CopyTo(array, index); - int nCtr; - for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { - array.SetValue(new VirtualHardDiskSettingData(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); - } - } - - public virtual System.Collections.IEnumerator GetEnumerator() { - return new VirtualHardDiskSettingDataEnumerator(privColObj.GetEnumerator()); - } - - public class VirtualHardDiskSettingDataEnumerator : object, System.Collections.IEnumerator { - - private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; - - public VirtualHardDiskSettingDataEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { - privObjEnum = objEnum; - } - - public virtual object Current { - get { - return new VirtualHardDiskSettingData(((System.Management.ManagementObject)(privObjEnum.Current))); - } - } - - public virtual bool MoveNext() { - return privObjEnum.MoveNext(); - } - - public virtual void Reset() { - privObjEnum.Reset(); - } - } - } - - // TypeConverter to handle null values for ValueType properties - public class WMIValueTypeConverter : TypeConverter { - - private TypeConverter baseConverter; - - private System.Type baseType; - - public WMIValueTypeConverter(System.Type inBaseType) { - baseConverter = TypeDescriptor.GetConverter(inBaseType); - baseType = inBaseType; - } - - public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { - return baseConverter.CanConvertFrom(context, srcType); - } - - public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { - return baseConverter.CanConvertTo(context, destinationType); - } - - public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { - return baseConverter.ConvertFrom(context, culture, value); - } - - public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { - return baseConverter.CreateInstance(context, dictionary); - } - - public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetCreateInstanceSupported(context); - } - - public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { - return baseConverter.GetProperties(context, value, attributeVar); - } - - public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetPropertiesSupported(context); - } - - public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValues(context); - } - - public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesExclusive(context); - } - - public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesSupported(context); - } - - public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { - if ((baseType.BaseType == typeof(System.Enum))) { - if ((value.GetType() == destinationType)) { - return value; - } - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return "NULL_ENUM_VALUE" ; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((baseType == typeof(bool)) - && (baseType.BaseType == typeof(System.ValueType)))) { - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((context != null) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - } - - // Embedded class to represent WMI system Properties. - [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] - public class ManagementSystemProperties { - - private System.Management.ManagementBaseObject PrivateLateBoundObject; - - public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { - PrivateLateBoundObject = ManagedObject; - } - - [Browsable(true)] - public int GENUS { - get { - return ((int)(PrivateLateBoundObject["__GENUS"])); - } - } - - [Browsable(true)] - public string CLASS { - get { - return ((string)(PrivateLateBoundObject["__CLASS"])); - } - } - - [Browsable(true)] - public string SUPERCLASS { - get { - return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); - } - } - - [Browsable(true)] - public string DYNASTY { - get { - return ((string)(PrivateLateBoundObject["__DYNASTY"])); - } - } - - [Browsable(true)] - public string RELPATH { - get { - return ((string)(PrivateLateBoundObject["__RELPATH"])); - } - } - - [Browsable(true)] - public int PROPERTY_COUNT { - get { - return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); - } - } - - [Browsable(true)] - public string[] DERIVATION { - get { - return ((string[])(PrivateLateBoundObject["__DERIVATION"])); - } - } - - [Browsable(true)] - public string SERVER { - get { - return ((string)(PrivateLateBoundObject["__SERVER"])); - } - } - - [Browsable(true)] - public string NAMESPACE { - get { - return ((string)(PrivateLateBoundObject["__NAMESPACE"])); - } - } - - [Browsable(true)] - public string PATH { - get { - return ((string)(PrivateLateBoundObject["__PATH"])); - } - } - } - } -} +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2 { + using System; + using System.ComponentModel; + using System.Management; + using System.Collections; + using System.Globalization; + using System.ComponentModel.Design.Serialization; + using System.Reflection; + + + // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. + // Functions IsNull() are used to check if a property is NULL. + // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. + // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. + // An Early Bound class generated for the WMI class.Msvm_VirtualHardDiskSettingData + public class VirtualHardDiskSettingData : System.ComponentModel.Component { + + // Private property to hold the WMI namespace in which the class resides. + private static string CreatedWmiNamespace = "ROOT\\virtualization\\v2"; + + // Private property to hold the name of WMI class which created this class. + private static string CreatedClassName = "Msvm_VirtualHardDiskSettingData"; + + // Private member variable to hold the ManagementScope which is used by the various methods. + private static System.Management.ManagementScope statMgmtScope = null; + + private ManagementSystemProperties PrivateSystemProperties; + + // Underlying lateBound WMI object. + private System.Management.ManagementObject PrivateLateBoundObject; + + // Member variable to store the 'automatic commit' behavior for the class. + private bool AutoCommitProp; + + // Private variable to hold the embedded property representing the instance. + private System.Management.ManagementBaseObject embeddedObj; + + // The current WMI object used + private System.Management.ManagementBaseObject curObj; + + // Flag to indicate if the instance is an embedded object. + private bool isEmbedded; + + // Below are different overloads of constructors to initialize an instance of the class with a WMI object. + public VirtualHardDiskSettingData() { + this.InitializeObject(null, null, null); + } + + public VirtualHardDiskSettingData(string keyInstanceID) { + this.InitializeObject(null, new System.Management.ManagementPath(VirtualHardDiskSettingData.ConstructPath(keyInstanceID)), null); + } + + public VirtualHardDiskSettingData(System.Management.ManagementScope mgmtScope, string keyInstanceID) { + this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(VirtualHardDiskSettingData.ConstructPath(keyInstanceID)), null); + } + + public VirtualHardDiskSettingData(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(null, path, getOptions); + } + + public VirtualHardDiskSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { + this.InitializeObject(mgmtScope, path, null); + } + + public VirtualHardDiskSettingData(System.Management.ManagementPath path) { + this.InitializeObject(null, path, null); + } + + public VirtualHardDiskSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(mgmtScope, path, getOptions); + } + + public VirtualHardDiskSettingData(System.Management.ManagementObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + PrivateLateBoundObject = theObject; + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + public VirtualHardDiskSettingData(System.Management.ManagementBaseObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + embeddedObj = theObject; + PrivateSystemProperties = new ManagementSystemProperties(theObject); + curObj = embeddedObj; + isEmbedded = true; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + // Property returns the namespace of the WMI class. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OriginatingNamespace { + get { + return "ROOT\\virtualization\\v2"; + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ManagementClassName { + get { + string strRet = CreatedClassName; + if ((curObj != null)) { + if ((curObj.ClassPath != null)) { + strRet = ((string)(curObj["__CLASS"])); + if (((strRet == null) + || (strRet == string.Empty))) { + strRet = CreatedClassName; + } + } + } + return strRet; + } + } + + // Property pointing to an embedded object to get System properties of the WMI object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ManagementSystemProperties SystemProperties { + get { + return PrivateSystemProperties; + } + } + + // Property returning the underlying lateBound object. + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementBaseObject LateBoundObject { + get { + return curObj; + } + } + + // ManagementScope of the object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementScope Scope { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Scope; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Scope = value; + } + } + } + + // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool AutoCommit { + get { + return AutoCommitProp; + } + set { + AutoCommitProp = value; + } + } + + // The ManagementPath of the underlying WMI object. + [Browsable(true)] + public System.Management.ManagementPath Path { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Path; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + if ((CheckIfProperClass(null, value, null) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + PrivateLateBoundObject.Path = value; + } + } + } + + // Public static scope property which is used by the various methods. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public static System.Management.ManagementScope StaticScope { + get { + return statMgmtScope; + } + set { + statMgmtScope = value; + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsBlockSizeNull { + get { + if ((curObj["BlockSize"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The block size used by the virtual hard disk")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint BlockSize { + get { + if ((curObj["BlockSize"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["BlockSize"])); + } + set { + curObj["BlockSize"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Caption { + get { + return ((string)(curObj["Caption"])); + } + set { + curObj["Caption"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Description { + get { + return ((string)(curObj["Description"])); + } + set { + curObj["Description"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ElementName { + get { + return ((string)(curObj["ElementName"])); + } + set { + curObj["ElementName"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsFormatNull { + get { + if ((curObj["Format"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The format for the virtual hard disk.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public FormatValues Format { + get { + if ((curObj["Format"] == null)) { + return ((FormatValues)(System.Convert.ToInt32(0))); + } + return ((FormatValues)(System.Convert.ToInt32(curObj["Format"]))); + } + set { + if ((FormatValues.NULL_ENUM_VALUE == value)) { + curObj["Format"] = null; + } + else { + curObj["Format"] = value; + } + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string InstanceID { + get { + return ((string)(curObj["InstanceID"])); + } + set { + curObj["InstanceID"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsLogicalSectorSizeNull { + get { + if ((curObj["LogicalSectorSize"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The logical sector size used by the virtual hard disk")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint LogicalSectorSize { + get { + if ((curObj["LogicalSectorSize"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["LogicalSectorSize"])); + } + set { + curObj["LogicalSectorSize"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsMaxInternalSizeNull { + get { + if ((curObj["MaxInternalSize"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The maximum size of the virtual hard disk as viewable by the virtual machine, in " + + "bytes. The specified size will be rounded up to the next largest multiple of the" + + " sector size.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ulong MaxInternalSize { + get { + if ((curObj["MaxInternalSize"] == null)) { + return System.Convert.ToUInt64(0); + } + return ((ulong)(curObj["MaxInternalSize"])); + } + set { + curObj["MaxInternalSize"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The parent of the virtual hard disk. If the virtual hard disk does not have a par" + + "ent, then this field is empty.")] + public string ParentPath { + get { + return ((string)(curObj["ParentPath"])); + } + set { + curObj["ParentPath"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The path of the virtual hard disk.")] + public string Path0 { + get { + return ((string)(curObj["Path"])); + } + set { + curObj["Path"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPhysicalSectorSizeNull { + get { + if ((curObj["PhysicalSectorSize"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The physical sector size used by the virtual hard disk")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint PhysicalSectorSize { + get { + if ((curObj["PhysicalSectorSize"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["PhysicalSectorSize"])); + } + set { + curObj["PhysicalSectorSize"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsTypeNull { + get { + if ((curObj["Type"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The type of virtual hard disk.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public TypeValues Type { + get { + if ((curObj["Type"] == null)) { + return ((TypeValues)(System.Convert.ToInt32(0))); + } + return ((TypeValues)(System.Convert.ToInt32(curObj["Type"]))); + } + set { + if ((TypeValues.NULL_ENUM_VALUE == value)) { + curObj["Type"] = null; + } + else { + curObj["Type"] = value; + } + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { + if (((path != null) + && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); + } + } + + private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { + if (((theObj != null) + && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); + if ((parentClasses != null)) { + int count = 0; + for (count = 0; (count < parentClasses.Length); count = (count + 1)) { + if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { + return true; + } + } + } + } + return false; + } + + private bool ShouldSerializeBlockSize() { + if ((this.IsBlockSizeNull == false)) { + return true; + } + return false; + } + + private void ResetBlockSize() { + curObj["BlockSize"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private void ResetCaption() { + curObj["Caption"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private void ResetDescription() { + curObj["Description"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private void ResetElementName() { + curObj["ElementName"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private bool ShouldSerializeFormat() { + if ((this.IsFormatNull == false)) { + return true; + } + return false; + } + + private void ResetFormat() { + curObj["Format"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private bool ShouldSerializeLogicalSectorSize() { + if ((this.IsLogicalSectorSizeNull == false)) { + return true; + } + return false; + } + + private void ResetLogicalSectorSize() { + curObj["LogicalSectorSize"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private bool ShouldSerializeMaxInternalSize() { + if ((this.IsMaxInternalSizeNull == false)) { + return true; + } + return false; + } + + private void ResetMaxInternalSize() { + curObj["MaxInternalSize"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private void ResetParentPath() { + curObj["ParentPath"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private void ResetPath0() { + curObj["Path"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private bool ShouldSerializePhysicalSectorSize() { + if ((this.IsPhysicalSectorSizeNull == false)) { + return true; + } + return false; + } + + private void ResetPhysicalSectorSize() { + curObj["PhysicalSectorSize"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private bool ShouldSerializeType() { + if ((this.IsTypeNull == false)) { + return true; + } + return false; + } + + private void ResetType() { + curObj["Type"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + [Browsable(true)] + public void CommitObject() { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(); + } + } + + [Browsable(true)] + public void CommitObject(System.Management.PutOptions putOptions) { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(putOptions); + } + } + + private void Initialize() { + AutoCommitProp = true; + isEmbedded = false; + } + + private static string ConstructPath(string keyInstanceID) { + string strPath = "ROOT\\virtualization\\v2:Msvm_VirtualHardDiskSettingData"; + strPath = string.Concat(strPath, string.Concat(".InstanceID=", string.Concat("\"", string.Concat(keyInstanceID, "\"")))); + return strPath; + } + + private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + Initialize(); + if ((path != null)) { + if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + } + PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + + // Different overloads of GetInstances() help in enumerating instances of the WMI class. + public static VirtualHardDiskSettingDataCollection GetInstances() { + return GetInstances(null, null, null); + } + + public static VirtualHardDiskSettingDataCollection GetInstances(string condition) { + return GetInstances(null, condition, null); + } + + public static VirtualHardDiskSettingDataCollection GetInstances(string[] selectedProperties) { + return GetInstances(null, null, selectedProperties); + } + + public static VirtualHardDiskSettingDataCollection GetInstances(string condition, string[] selectedProperties) { + return GetInstances(null, condition, selectedProperties); + } + + public static VirtualHardDiskSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); + pathObj.ClassName = "Msvm_VirtualHardDiskSettingData"; + pathObj.NamespacePath = "root\\virtualization\\v2"; + System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); + if ((enumOptions == null)) { + enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + } + return new VirtualHardDiskSettingDataCollection(clsObject.GetInstances(enumOptions)); + } + + public static VirtualHardDiskSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { + return GetInstances(mgmtScope, condition, null); + } + + public static VirtualHardDiskSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { + return GetInstances(mgmtScope, null, selectedProperties); + } + + public static VirtualHardDiskSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_VirtualHardDiskSettingData", condition, selectedProperties)); + System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + ObjectSearcher.Options = enumOptions; + return new VirtualHardDiskSettingDataCollection(ObjectSearcher.Get()); + } + + [Browsable(true)] + public static VirtualHardDiskSettingData CreateInstance() { + System.Management.ManagementScope mgmtScope = null; + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = CreatedWmiNamespace; + } + else { + mgmtScope = statMgmtScope; + } + System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); + System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); + return new VirtualHardDiskSettingData(tmpMgmtClass.CreateInstance()); + } + + [Browsable(true)] + public void Delete() { + PrivateLateBoundObject.Delete(); + } + + public enum FormatValues { + + VHD = 2, + + VHDX = 3, + + NULL_ENUM_VALUE = 0, + } + + public enum TypeValues { + + Fixed = 2, + + Dynamic = 3, + + Differencing = 4, + + NULL_ENUM_VALUE = 0, + } + + // Enumerator implementation for enumerating instances of the class. + public class VirtualHardDiskSettingDataCollection : object, ICollection { + + private ManagementObjectCollection privColObj; + + public VirtualHardDiskSettingDataCollection(ManagementObjectCollection objCollection) { + privColObj = objCollection; + } + + public virtual int Count { + get { + return privColObj.Count; + } + } + + public virtual bool IsSynchronized { + get { + return privColObj.IsSynchronized; + } + } + + public virtual object SyncRoot { + get { + return this; + } + } + + public virtual void CopyTo(System.Array array, int index) { + privColObj.CopyTo(array, index); + int nCtr; + for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { + array.SetValue(new VirtualHardDiskSettingData(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); + } + } + + public virtual System.Collections.IEnumerator GetEnumerator() { + return new VirtualHardDiskSettingDataEnumerator(privColObj.GetEnumerator()); + } + + public class VirtualHardDiskSettingDataEnumerator : object, System.Collections.IEnumerator { + + private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; + + public VirtualHardDiskSettingDataEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { + privObjEnum = objEnum; + } + + public virtual object Current { + get { + return new VirtualHardDiskSettingData(((System.Management.ManagementObject)(privObjEnum.Current))); + } + } + + public virtual bool MoveNext() { + return privObjEnum.MoveNext(); + } + + public virtual void Reset() { + privObjEnum.Reset(); + } + } + } + + // TypeConverter to handle null values for ValueType properties + public class WMIValueTypeConverter : TypeConverter { + + private TypeConverter baseConverter; + + private System.Type baseType; + + public WMIValueTypeConverter(System.Type inBaseType) { + baseConverter = TypeDescriptor.GetConverter(inBaseType); + baseType = inBaseType; + } + + public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { + return baseConverter.CanConvertFrom(context, srcType); + } + + public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { + return baseConverter.CanConvertTo(context, destinationType); + } + + public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { + return baseConverter.ConvertFrom(context, culture, value); + } + + public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { + return baseConverter.CreateInstance(context, dictionary); + } + + public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetCreateInstanceSupported(context); + } + + public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { + return baseConverter.GetProperties(context, value, attributeVar); + } + + public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetPropertiesSupported(context); + } + + public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValues(context); + } + + public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesExclusive(context); + } + + public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesSupported(context); + } + + public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { + if ((baseType.BaseType == typeof(System.Enum))) { + if ((value.GetType() == destinationType)) { + return value; + } + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return "NULL_ENUM_VALUE" ; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((baseType == typeof(bool)) + && (baseType.BaseType == typeof(System.ValueType)))) { + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((context != null) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + } + + // Embedded class to represent WMI system Properties. + [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] + public class ManagementSystemProperties { + + private System.Management.ManagementBaseObject PrivateLateBoundObject; + + public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { + PrivateLateBoundObject = ManagedObject; + } + + [Browsable(true)] + public int GENUS { + get { + return ((int)(PrivateLateBoundObject["__GENUS"])); + } + } + + [Browsable(true)] + public string CLASS { + get { + return ((string)(PrivateLateBoundObject["__CLASS"])); + } + } + + [Browsable(true)] + public string SUPERCLASS { + get { + return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); + } + } + + [Browsable(true)] + public string DYNASTY { + get { + return ((string)(PrivateLateBoundObject["__DYNASTY"])); + } + } + + [Browsable(true)] + public string RELPATH { + get { + return ((string)(PrivateLateBoundObject["__RELPATH"])); + } + } + + [Browsable(true)] + public int PROPERTY_COUNT { + get { + return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); + } + } + + [Browsable(true)] + public string[] DERIVATION { + get { + return ((string[])(PrivateLateBoundObject["__DERIVATION"])); + } + } + + [Browsable(true)] + public string SERVER { + get { + return ((string)(PrivateLateBoundObject["__SERVER"])); + } + } + + [Browsable(true)] + public string NAMESPACE { + get { + return ((string)(PrivateLateBoundObject["__NAMESPACE"])); + } + } + + [Browsable(true)] + public string PATH { + get { + return ((string)(PrivateLateBoundObject["__PATH"])); + } + } + } + } +} diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_VirtualSystemManagementService.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_VirtualSystemManagementService.cs index 124cda26ca1..0aca9977e44 100644 --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_VirtualSystemManagementService.cs +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_VirtualSystemManagementService.cs @@ -1,1916 +1,1916 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2 -{ - using System; - using System.ComponentModel; - using System.Management; - using System.Collections; - using System.Globalization; - using System.ComponentModel.Design.Serialization; - using System.Reflection; - - - // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. - // Functions IsNull() are used to check if a property is NULL. - // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. - // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. - // Datetime conversion functions ToDateTime and ToDmtfDateTime are added to the class to convert DMTF datetime to System.DateTime and vice-versa. - // An Early Bound class generated for the WMI class.Msvm_VirtualSystemManagementService - public class VirtualSystemManagementService : System.ComponentModel.Component { - - // Private property to hold the WMI namespace in which the class resides. - private static string CreatedWmiNamespace = "ROOT\\virtualization\\v2"; - - // Private property to hold the name of WMI class which created this class. - private static string CreatedClassName = "Msvm_VirtualSystemManagementService"; - - // Private member variable to hold the ManagementScope which is used by the various methods. - private static System.Management.ManagementScope statMgmtScope = null; - - private ManagementSystemProperties PrivateSystemProperties; - - // Underlying lateBound WMI object. - private System.Management.ManagementObject PrivateLateBoundObject; - - // Member variable to store the 'automatic commit' behavior for the class. - private bool AutoCommitProp; - - // Private variable to hold the embedded property representing the instance. - private System.Management.ManagementBaseObject embeddedObj; - - // The current WMI object used - private System.Management.ManagementBaseObject curObj; - - // Flag to indicate if the instance is an embedded object. - private bool isEmbedded; - - // Below are different overloads of constructors to initialize an instance of the class with a WMI object. - public VirtualSystemManagementService() { - this.InitializeObject(null, null, null); - } - - public VirtualSystemManagementService(string keyCreationClassName, string keyName, string keySystemCreationClassName, string keySystemName) { - this.InitializeObject(null, new System.Management.ManagementPath(VirtualSystemManagementService.ConstructPath(keyCreationClassName, keyName, keySystemCreationClassName, keySystemName)), null); - } - - public VirtualSystemManagementService(System.Management.ManagementScope mgmtScope, string keyCreationClassName, string keyName, string keySystemCreationClassName, string keySystemName) { - this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(VirtualSystemManagementService.ConstructPath(keyCreationClassName, keyName, keySystemCreationClassName, keySystemName)), null); - } - - public VirtualSystemManagementService(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(null, path, getOptions); - } - - public VirtualSystemManagementService(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { - this.InitializeObject(mgmtScope, path, null); - } - - public VirtualSystemManagementService(System.Management.ManagementPath path) { - this.InitializeObject(null, path, null); - } - - public VirtualSystemManagementService(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(mgmtScope, path, getOptions); - } - - public VirtualSystemManagementService(System.Management.ManagementObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - PrivateLateBoundObject = theObject; - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - public VirtualSystemManagementService(System.Management.ManagementBaseObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - embeddedObj = theObject; - PrivateSystemProperties = new ManagementSystemProperties(theObject); - curObj = embeddedObj; - isEmbedded = true; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - // Property returns the namespace of the WMI class. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OriginatingNamespace { - get { - return "ROOT\\virtualization\\v2"; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ManagementClassName { - get { - string strRet = CreatedClassName; - if ((curObj != null)) { - if ((curObj.ClassPath != null)) { - strRet = ((string)(curObj["__CLASS"])); - if (((strRet == null) - || (strRet == string.Empty))) { - strRet = CreatedClassName; - } - } - } - return strRet; - } - } - - // Property pointing to an embedded object to get System properties of the WMI object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ManagementSystemProperties SystemProperties { - get { - return PrivateSystemProperties; - } - } - - // Property returning the underlying lateBound object. - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementBaseObject LateBoundObject { - get { - return curObj; - } - } - - // ManagementScope of the object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementScope Scope { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Scope; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Scope = value; - } - } - } - - // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool AutoCommit { - get { - return AutoCommitProp; - } - set { - AutoCommitProp = value; - } - } - - // The ManagementPath of the underlying WMI object. - [Browsable(true)] - public System.Management.ManagementPath Path { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Path; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - if ((CheckIfProperClass(null, value, null) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - PrivateLateBoundObject.Path = value; - } - } - } - - // Public static scope property which is used by the various methods. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public static System.Management.ManagementScope StaticScope { - get { - return statMgmtScope; - } - set { - statMgmtScope = value; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ushort[] AvailableRequestedStates { - get { - return ((ushort[])(curObj["AvailableRequestedStates"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Caption { - get { - return ((string)(curObj["Caption"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsCommunicationStatusNull { - get { - if ((curObj["CommunicationStatus"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort CommunicationStatus { - get { - if ((curObj["CommunicationStatus"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["CommunicationStatus"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string CreationClassName { - get { - return ((string)(curObj["CreationClassName"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Description { - get { - return ((string)(curObj["Description"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsDetailedStatusNull { - get { - if ((curObj["DetailedStatus"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort DetailedStatus { - get { - if ((curObj["DetailedStatus"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["DetailedStatus"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ElementName { - get { - return ((string)(curObj["ElementName"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsEnabledDefaultNull { - get { - if ((curObj["EnabledDefault"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort EnabledDefault { - get { - if ((curObj["EnabledDefault"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["EnabledDefault"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsEnabledStateNull { - get { - if ((curObj["EnabledState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort EnabledState { - get { - if ((curObj["EnabledState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["EnabledState"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsHealthStateNull { - get { - if ((curObj["HealthState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort HealthState { - get { - if ((curObj["HealthState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["HealthState"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsInstallDateNull { - get { - if ((curObj["InstallDate"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public System.DateTime InstallDate { - get { - if ((curObj["InstallDate"] != null)) { - return ToDateTime(((string)(curObj["InstallDate"]))); - } - else { - return System.DateTime.MinValue; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string InstanceID { - get { - return ((string)(curObj["InstanceID"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Name { - get { - return ((string)(curObj["Name"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsOperatingStatusNull { - get { - if ((curObj["OperatingStatus"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort OperatingStatus { - get { - if ((curObj["OperatingStatus"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["OperatingStatus"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ushort[] OperationalStatus { - get { - return ((ushort[])(curObj["OperationalStatus"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OtherEnabledState { - get { - return ((string)(curObj["OtherEnabledState"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string PrimaryOwnerContact { - get { - return ((string)(curObj["PrimaryOwnerContact"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string PrimaryOwnerName { - get { - return ((string)(curObj["PrimaryOwnerName"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsPrimaryStatusNull { - get { - if ((curObj["PrimaryStatus"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort PrimaryStatus { - get { - if ((curObj["PrimaryStatus"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["PrimaryStatus"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsRequestedStateNull { - get { - if ((curObj["RequestedState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort RequestedState { - get { - if ((curObj["RequestedState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["RequestedState"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsStartedNull { - get { - if ((curObj["Started"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool Started { - get { - if ((curObj["Started"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["Started"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string StartMode { - get { - return ((string)(curObj["StartMode"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Status { - get { - return ((string)(curObj["Status"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] StatusDescriptions { - get { - return ((string[])(curObj["StatusDescriptions"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string SystemCreationClassName { - get { - return ((string)(curObj["SystemCreationClassName"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string SystemName { - get { - return ((string)(curObj["SystemName"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsTimeOfLastStateChangeNull { - get { - if ((curObj["TimeOfLastStateChange"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public System.DateTime TimeOfLastStateChange { - get { - if ((curObj["TimeOfLastStateChange"] != null)) { - return ToDateTime(((string)(curObj["TimeOfLastStateChange"]))); - } - else { - return System.DateTime.MinValue; - } - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsTransitioningToStateNull { - get { - if ((curObj["TransitioningToState"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort TransitioningToState { - get { - if ((curObj["TransitioningToState"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["TransitioningToState"])); - } - } - - private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { - if (((path != null) - && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); - } - } - - private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { - if (((theObj != null) - && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); - if ((parentClasses != null)) { - int count = 0; - for (count = 0; (count < parentClasses.Length); count = (count + 1)) { - if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { - return true; - } - } - } - } - return false; - } - - private bool ShouldSerializeCommunicationStatus() { - if ((this.IsCommunicationStatusNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeDetailedStatus() { - if ((this.IsDetailedStatusNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeEnabledDefault() { - if ((this.IsEnabledDefaultNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeEnabledState() { - if ((this.IsEnabledStateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeHealthState() { - if ((this.IsHealthStateNull == false)) { - return true; - } - return false; - } - - // Converts a given datetime in DMTF format to System.DateTime object. - static System.DateTime ToDateTime(string dmtfDate) { - System.DateTime initializer = System.DateTime.MinValue; - int year = initializer.Year; - int month = initializer.Month; - int day = initializer.Day; - int hour = initializer.Hour; - int minute = initializer.Minute; - int second = initializer.Second; - long ticks = 0; - string dmtf = dmtfDate; - System.DateTime datetime = System.DateTime.MinValue; - string tempString = string.Empty; - if ((dmtf == null)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtf.Length == 0)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtf.Length != 25)) { - throw new System.ArgumentOutOfRangeException(); - } - try { - tempString = dmtf.Substring(0, 4); - if (("****" != tempString)) { - year = int.Parse(tempString); - } - tempString = dmtf.Substring(4, 2); - if (("**" != tempString)) { - month = int.Parse(tempString); - } - tempString = dmtf.Substring(6, 2); - if (("**" != tempString)) { - day = int.Parse(tempString); - } - tempString = dmtf.Substring(8, 2); - if (("**" != tempString)) { - hour = int.Parse(tempString); - } - tempString = dmtf.Substring(10, 2); - if (("**" != tempString)) { - minute = int.Parse(tempString); - } - tempString = dmtf.Substring(12, 2); - if (("**" != tempString)) { - second = int.Parse(tempString); - } - tempString = dmtf.Substring(15, 6); - if (("******" != tempString)) { - ticks = (long.Parse(tempString) * ((long)((System.TimeSpan.TicksPerMillisecond / 1000)))); - } - if (((((((((year < 0) - || (month < 0)) - || (day < 0)) - || (hour < 0)) - || (minute < 0)) - || (minute < 0)) - || (second < 0)) - || (ticks < 0))) { - throw new System.ArgumentOutOfRangeException(); - } - } - catch (System.Exception e) { - throw new System.ArgumentOutOfRangeException(null, e.Message); - } - datetime = new System.DateTime(year, month, day, hour, minute, second, 0); - datetime = datetime.AddTicks(ticks); - System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(datetime); - int UTCOffset = 0; - int OffsetToBeAdjusted = 0; - long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); - tempString = dmtf.Substring(22, 3); - if ((tempString != "******")) { - tempString = dmtf.Substring(21, 4); - try { - UTCOffset = int.Parse(tempString); - } - catch (System.Exception e) { - throw new System.ArgumentOutOfRangeException(null, e.Message); - } - OffsetToBeAdjusted = ((int)((OffsetMins - UTCOffset))); - datetime = datetime.AddMinutes(((double)(OffsetToBeAdjusted))); - } - return datetime; - } - - // Converts a given System.DateTime object to DMTF datetime format. - static string ToDmtfDateTime(System.DateTime date) { - string utcString = string.Empty; - System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(date); - long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); - if ((System.Math.Abs(OffsetMins) > 999)) { - date = date.ToUniversalTime(); - utcString = "+000"; - } - else { - if ((tickOffset.Ticks >= 0)) { - utcString = string.Concat("+", ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))).ToString().PadLeft(3, '0')); - } - else { - string strTemp = ((long)(OffsetMins)).ToString(); - utcString = string.Concat("-", strTemp.Substring(1, (strTemp.Length - 1)).PadLeft(3, '0')); - } - } - string dmtfDateTime = ((int)(date.Year)).ToString().PadLeft(4, '0'); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Month)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Day)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Hour)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Minute)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Second)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, "."); - System.DateTime dtTemp = new System.DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, 0); - long microsec = ((long)((((date.Ticks - dtTemp.Ticks) - * 1000) - / System.TimeSpan.TicksPerMillisecond))); - string strMicrosec = ((long)(microsec)).ToString(); - if ((strMicrosec.Length > 6)) { - strMicrosec = strMicrosec.Substring(0, 6); - } - dmtfDateTime = string.Concat(dmtfDateTime, strMicrosec.PadLeft(6, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, utcString); - return dmtfDateTime; - } - - private bool ShouldSerializeInstallDate() { - if ((this.IsInstallDateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeOperatingStatus() { - if ((this.IsOperatingStatusNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializePrimaryStatus() { - if ((this.IsPrimaryStatusNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeRequestedState() { - if ((this.IsRequestedStateNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeStarted() { - if ((this.IsStartedNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeTimeOfLastStateChange() { - if ((this.IsTimeOfLastStateChangeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeTransitioningToState() { - if ((this.IsTransitioningToStateNull == false)) { - return true; - } - return false; - } - - [Browsable(true)] - public void CommitObject() { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(); - } - } - - [Browsable(true)] - public void CommitObject(System.Management.PutOptions putOptions) { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(putOptions); - } - } - - private void Initialize() { - AutoCommitProp = true; - isEmbedded = false; - } - - private static string ConstructPath(string keyCreationClassName, string keyName, string keySystemCreationClassName, string keySystemName) { - string strPath = "ROOT\\virtualization\\v2:Msvm_VirtualSystemManagementService"; - strPath = string.Concat(strPath, string.Concat(".CreationClassName=", string.Concat("\"", string.Concat(keyCreationClassName, "\"")))); - strPath = string.Concat(strPath, string.Concat(",Name=", string.Concat("\"", string.Concat(keyName, "\"")))); - strPath = string.Concat(strPath, string.Concat(",SystemCreationClassName=", string.Concat("\"", string.Concat(keySystemCreationClassName, "\"")))); - strPath = string.Concat(strPath, string.Concat(",SystemName=", string.Concat("\"", string.Concat(keySystemName, "\"")))); - return strPath; - } - - private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - Initialize(); - if ((path != null)) { - if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - } - PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - - // Different overloads of GetInstances() help in enumerating instances of the WMI class. - public static VirtualSystemManagementServiceCollection GetInstances() { - return GetInstances(null, null, null); - } - - public static VirtualSystemManagementServiceCollection GetInstances(string condition) { - return GetInstances(null, condition, null); - } - - public static VirtualSystemManagementServiceCollection GetInstances(string[] selectedProperties) { - return GetInstances(null, null, selectedProperties); - } - - public static VirtualSystemManagementServiceCollection GetInstances(string condition, string[] selectedProperties) { - return GetInstances(null, condition, selectedProperties); - } - - public static VirtualSystemManagementServiceCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); - pathObj.ClassName = "Msvm_VirtualSystemManagementService"; - pathObj.NamespacePath = "root\\virtualization\\v2"; - System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); - if ((enumOptions == null)) { - enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - } - return new VirtualSystemManagementServiceCollection(clsObject.GetInstances(enumOptions)); - } - - public static VirtualSystemManagementServiceCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { - return GetInstances(mgmtScope, condition, null); - } - - public static VirtualSystemManagementServiceCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { - return GetInstances(mgmtScope, null, selectedProperties); - } - - public static VirtualSystemManagementServiceCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_VirtualSystemManagementService", condition, selectedProperties)); - System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - ObjectSearcher.Options = enumOptions; - return new VirtualSystemManagementServiceCollection(ObjectSearcher.Get()); - } - - [Browsable(true)] - public static VirtualSystemManagementService CreateInstance() { - System.Management.ManagementScope mgmtScope = null; - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = CreatedWmiNamespace; - } - else { - mgmtScope = statMgmtScope; - } - System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); - System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); - return new VirtualSystemManagementService(tmpMgmtClass.CreateInstance()); - } - - [Browsable(true)] - public void Delete() { - PrivateLateBoundObject.Delete(); - } - - public uint AddFeatureSettings(System.Management.ManagementPath AffectedConfiguration, string[] FeatureSettings, out System.Management.ManagementPath Job, out System.Management.ManagementPath[] ResultingFeatureSettings) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("AddFeatureSettings"); - inParams["AffectedConfiguration"] = ((System.Management.ManagementPath)(AffectedConfiguration)).Path; - inParams["FeatureSettings"] = ((string[])(FeatureSettings)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("AddFeatureSettings", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null)) - { - Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); - } - ResultingFeatureSettings = null; - if ((outParams.Properties["ResultingFeatureSettings"] != null && outParams.Properties["ResultingFeatureSettings"].Value != null)) - { - int len = ((System.Array)(outParams.Properties["ResultingFeatureSettings"].Value)).Length; - System.Management.ManagementPath[] arrToRet = new System.Management.ManagementPath[len]; - for (int iCounter = 0; (iCounter < len); iCounter = (iCounter + 1)) { - arrToRet[iCounter] = new System.Management.ManagementPath(((System.Array)(outParams.Properties["ResultingFeatureSettings"].Value)).GetValue(iCounter).ToString()); - } - ResultingFeatureSettings = arrToRet; - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - ResultingFeatureSettings = null; - return System.Convert.ToUInt32(0); - } - } - - public uint AddFibreChannelChap(string[] FcPortSettings, byte SecretEncoding, byte[] SharedSecret) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("AddFibreChannelChap"); - inParams["FcPortSettings"] = ((string[])(FcPortSettings)); - inParams["SecretEncoding"] = ((byte)(SecretEncoding)); - inParams["SharedSecret"] = ((byte[])(SharedSecret)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("AddFibreChannelChap", inParams, null); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - return System.Convert.ToUInt32(0); - } - } - - public uint AddKvpItems(string[] DataItems, System.Management.ManagementPath TargetSystem, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("AddKvpItems"); - inParams["DataItems"] = ((string[])(DataItems)); - inParams["TargetSystem"] = ((System.Management.ManagementPath)(TargetSystem)).Path; - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("AddKvpItems", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null)) - { - Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - return System.Convert.ToUInt32(0); - } - } - - public uint AddResourceSettings(System.Management.ManagementPath AffectedConfiguration, string[] ResourceSettings, out System.Management.ManagementPath Job, out System.Management.ManagementPath[] ResultingResourceSettings) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("AddResourceSettings"); - inParams["AffectedConfiguration"] = ((System.Management.ManagementPath)(AffectedConfiguration)).Path; - inParams["ResourceSettings"] = ((string[])(ResourceSettings)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("AddResourceSettings", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null)) - { - Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); - } - ResultingResourceSettings = null; - if ((outParams.Properties["ResultingResourceSettings"] != null && outParams.Properties["ResultingResourceSettings"].Value != null)) - { - int len = ((System.Array)(outParams.Properties["ResultingResourceSettings"].Value)).Length; - System.Management.ManagementPath[] arrToRet = new System.Management.ManagementPath[len]; - for (int iCounter = 0; (iCounter < len); iCounter = (iCounter + 1)) { - arrToRet[iCounter] = new System.Management.ManagementPath(((System.Array)(outParams.Properties["ResultingResourceSettings"].Value)).GetValue(iCounter).ToString()); - } - ResultingResourceSettings = arrToRet; - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - ResultingResourceSettings = null; - return System.Convert.ToUInt32(0); - } - } - - public uint DefineSystem(string ReferenceConfigurationPath, string[] ResourceSettings, string SystemSettings, out System.Management.ManagementPath Job, out System.Management.ManagementPath ResultingSystem) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("DefineSystem"); - inParams["ReferenceConfiguration"] = ReferenceConfigurationPath; - inParams["ResourceSettings"] = ResourceSettings; - inParams["SystemSettings"] = SystemSettings; - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("DefineSystem", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null) && outParams.Properties["Job"].Value != null) - { - Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); - } - ResultingSystem = null; - if ((outParams.Properties["ResultingSystem"] != null && outParams.Properties["ResultingSystem"].Value != null)) - { - ResultingSystem = new System.Management.ManagementPath((string)outParams.Properties["ResultingSystem"].Value); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - ResultingSystem = null; - return System.Convert.ToUInt32(0); - } - } - - public uint DestroySystem(System.Management.ManagementPath AffectedSystem, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("DestroySystem"); - inParams["AffectedSystem"] = ((System.Management.ManagementPath)(AffectedSystem)).Path; - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("DestroySystem", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null)) - { - Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - return System.Convert.ToUInt32(0); - } - } - - public uint ExportSystemDefinition(System.Management.ManagementPath ComputerSystem, string ExportDirectory, string ExportSettingData, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("ExportSystemDefinition"); - inParams["ComputerSystem"] = ((System.Management.ManagementPath)(ComputerSystem)).Path; - inParams["ExportDirectory"] = ((string)(ExportDirectory)); - inParams["ExportSettingData"] = ((string)(ExportSettingData)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ExportSystemDefinition", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null)) - { - Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); - } - - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - return System.Convert.ToUInt32(0); - } - } - - public uint FormatError(string[] Errors, out string ErrorMessage) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("FormatError"); - inParams["Errors"] = ((string[])(Errors)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("FormatError", inParams, null); - ErrorMessage = System.Convert.ToString(outParams.Properties["ErrorMessage"].Value); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - ErrorMessage = null; - return System.Convert.ToUInt32(0); - } - } - - public uint GenerateWwpn(uint NumberOfWwpns, out string[] GeneratedWwpn) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("GenerateWwpn"); - inParams["NumberOfWwpns"] = ((uint)(NumberOfWwpns)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("GenerateWwpn", inParams, null); - GeneratedWwpn = ((string[])(outParams.Properties["GeneratedWwpn"].Value)); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - GeneratedWwpn = null; - return System.Convert.ToUInt32(0); - } - } - - public uint GetCurrentWwpnFromGenerator(out string CurrentWwpn) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("GetCurrentWwpnFromGenerator", inParams, null); - CurrentWwpn = System.Convert.ToString(outParams.Properties["CurrentWwpn"].Value); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - CurrentWwpn = null; - return System.Convert.ToUInt32(0); - } - } - - public uint GetDefinitionFileSummaryInformation(string[] DefinitionFiles, out System.Management.ManagementBaseObject[] SummaryInformation) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("GetDefinitionFileSummaryInformation"); - inParams["DefinitionFiles"] = ((string[])(DefinitionFiles)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("GetDefinitionFileSummaryInformation", inParams, null); - SummaryInformation = ((System.Management.ManagementBaseObject[])(outParams.Properties["SummaryInformation"].Value)); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - SummaryInformation = null; - return System.Convert.ToUInt32(0); - } - } - - public uint GetSizeOfSystemFiles(System.Management.ManagementPath Vssd, out ulong Size) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("GetSizeOfSystemFiles"); - inParams["Vssd"] = ((System.Management.ManagementPath)(Vssd)).Path; - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("GetSizeOfSystemFiles", inParams, null); - Size = System.Convert.ToUInt64(outParams.Properties["Size"].Value); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Size = System.Convert.ToUInt64(0); - return System.Convert.ToUInt32(0); - } - } - - public uint GetSummaryInformation(uint[] RequestedInformation, System.Management.ManagementPath[] SettingData, out System.Management.ManagementBaseObject[] SummaryInformation) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("GetSummaryInformation"); - inParams["RequestedInformation"] = ((uint[])(RequestedInformation)); - if ((SettingData != null)) { - int len = ((System.Array)(SettingData)).Length; - string[] arrProp = new string[len]; - for (int iCounter = 0; (iCounter < len); iCounter = (iCounter + 1)) { - arrProp[iCounter] = ((System.Management.ManagementPath)(((System.Array)(SettingData)).GetValue(iCounter))).Path; - } - inParams["SettingData"] = arrProp; - } - else { - inParams["SettingData"] = null; - } - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("GetSummaryInformation", inParams, null); - SummaryInformation = ((System.Management.ManagementBaseObject[])(outParams.Properties["SummaryInformation"].Value)); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - SummaryInformation = null; - return System.Convert.ToUInt32(0); - } - } - - public uint GetVirtualSystemThumbnailImage(ushort HeightPixels, System.Management.ManagementPath TargetSystem, ushort WidthPixels, out byte[] ImageData) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("GetVirtualSystemThumbnailImage"); - inParams["HeightPixels"] = ((ushort)(HeightPixels)); - inParams["TargetSystem"] = ((System.Management.ManagementPath)(TargetSystem)).Path; - inParams["WidthPixels"] = ((ushort)(WidthPixels)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("GetVirtualSystemThumbnailImage", inParams, null); - ImageData = ((byte[])(outParams.Properties["ImageData"].Value)); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - ImageData = null; - return System.Convert.ToUInt32(0); - } - } - - public uint ImportSnapshotDefinitions(System.Management.ManagementPath PlannedSystem, string SnapshotFolder, out System.Management.ManagementPath[] ImportedSnapshots, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("ImportSnapshotDefinitions"); - inParams["PlannedSystem"] = ((System.Management.ManagementPath)(PlannedSystem)).Path; - inParams["SnapshotFolder"] = ((string)(SnapshotFolder)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ImportSnapshotDefinitions", inParams, null); - ImportedSnapshots = null; - if ((outParams.Properties["ImportedSnapshots"] != null && outParams.Properties["ImportedSnapshots"].Value != null)) - { - int len = ((System.Array)(outParams.Properties["ImportedSnapshots"].Value)).Length; - System.Management.ManagementPath[] arrToRet = new System.Management.ManagementPath[len]; - for (int iCounter = 0; (iCounter < len); iCounter = (iCounter + 1)) { - arrToRet[iCounter] = new System.Management.ManagementPath(((System.Array)(outParams.Properties["ImportedSnapshots"].Value)).GetValue(iCounter).ToString()); - } - ImportedSnapshots = arrToRet; - } - Job = null; - if ((outParams.Properties["Job"] != null)) - { - Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - ImportedSnapshots = null; - Job = null; - return System.Convert.ToUInt32(0); - } - } - - public uint ImportSystemDefinition(bool GenerateNewSystemIdentifier, string SnapshotFolder, string SystemDefinitionFile, out System.Management.ManagementPath ImportedSystem, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("ImportSystemDefinition"); - inParams["GenerateNewSystemIdentifier"] = ((bool)(GenerateNewSystemIdentifier)); - inParams["SnapshotFolder"] = ((string)(SnapshotFolder)); - inParams["SystemDefinitionFile"] = ((string)(SystemDefinitionFile)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ImportSystemDefinition", inParams, null); - ImportedSystem = null; - if ((outParams.Properties["ImportedSystem"] != null && outParams.Properties["ImportedSystem"].Value != null)) - { - ImportedSystem = new System.Management.ManagementPath(outParams.Properties["ImportedSystem"].ToString()); - } - Job = null; - if ((outParams.Properties["Job"] != null)) - { - Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); - } - - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - ImportedSystem = null; - Job = null; - return System.Convert.ToUInt32(0); - } - } - - public uint ModifyDiskMergeSettings(string SettingData, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("ModifyDiskMergeSettings"); - inParams["SettingData"] = ((string)(SettingData)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ModifyDiskMergeSettings", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null)) - { - Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - return System.Convert.ToUInt32(0); - } - } - - public uint ModifyFeatureSettings(string[] FeatureSettings, out System.Management.ManagementPath Job, out System.Management.ManagementPath[] ResultingFeatureSettings) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("ModifyFeatureSettings"); - inParams["FeatureSettings"] = ((string[])(FeatureSettings)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ModifyFeatureSettings", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null)) - { - Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); - } - ResultingFeatureSettings = null; - if ((outParams.Properties["ResultingFeatureSettings"] != null && outParams.Properties["ResultingFeatureSettings"].Value != null)) - { - int len = ((System.Array)(outParams.Properties["ResultingFeatureSettings"].Value)).Length; - System.Management.ManagementPath[] arrToRet = new System.Management.ManagementPath[len]; - for (int iCounter = 0; (iCounter < len); iCounter = (iCounter + 1)) { - arrToRet[iCounter] = new System.Management.ManagementPath(((System.Array)(outParams.Properties["ResultingFeatureSettings"].Value)).GetValue(iCounter).ToString()); - } - ResultingFeatureSettings = arrToRet; - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - ResultingFeatureSettings = null; - return System.Convert.ToUInt32(0); - } - } - - public uint ModifyKvpItems(string[] DataItems, System.Management.ManagementPath TargetSystem, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("ModifyKvpItems"); - inParams["DataItems"] = ((string[])(DataItems)); - inParams["TargetSystem"] = ((System.Management.ManagementPath)(TargetSystem)).Path; - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ModifyKvpItems", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null)) - { - Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - return System.Convert.ToUInt32(0); - } - } - - public uint ModifyResourceSettings(string[] ResourceSettings, out System.Management.ManagementPath Job, out System.Management.ManagementPath[] ResultingResourceSettings) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("ModifyResourceSettings"); - inParams["ResourceSettings"] = ((string[])(ResourceSettings)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ModifyResourceSettings", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null) && outParams.Properties["Job"].Value != null) - { - Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); - } - ResultingResourceSettings = null; - if ((outParams.Properties["ResultingResourceSettings"] != null && outParams.Properties["ResultingResourceSettings"].Value != null)) - { - int len = ((System.Array)(outParams.Properties["ResultingResourceSettings"].Value)).Length; - System.Management.ManagementPath[] arrToRet = new System.Management.ManagementPath[len]; - for (int iCounter = 0; (iCounter < len); iCounter = (iCounter + 1)) { - arrToRet[iCounter] = new System.Management.ManagementPath(((System.Array)(outParams.Properties["ResultingResourceSettings"].Value)).GetValue(iCounter).ToString()); - } - ResultingResourceSettings = arrToRet; - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - ResultingResourceSettings = null; - return System.Convert.ToUInt32(0); - } - } - - public uint ModifyServiceSettings(string SettingData, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("ModifyServiceSettings"); - inParams["SettingData"] = ((string)(SettingData)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ModifyServiceSettings", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null)) - { - Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - return System.Convert.ToUInt32(0); - } - } - - public uint ModifySystemSettings(string SystemSettings, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("ModifySystemSettings"); - inParams["SystemSettings"] = ((string)(SystemSettings)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ModifySystemSettings", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null)) - { - Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - return System.Convert.ToUInt32(0); - } - } - - public uint RealizePlannedSystem(System.Management.ManagementPath PlannedSystem, out System.Management.ManagementPath Job, out System.Management.ManagementPath ResultingSystem) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("RealizePlannedSystem"); - inParams["PlannedSystem"] = ((System.Management.ManagementPath)(PlannedSystem)).Path; - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RealizePlannedSystem", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null)) - { - Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); - } - ResultingSystem = null; - if ((outParams.Properties["ResultingSystem"] != null)) { - ResultingSystem = new System.Management.ManagementPath(outParams.Properties["ResultingSystem"].ToString()); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - ResultingSystem = null; - return System.Convert.ToUInt32(0); - } - } - - public uint RemoveFeatureSettings(System.Management.ManagementPath[] FeatureSettings, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("RemoveFeatureSettings"); - if ((FeatureSettings != null)) { - int len = ((System.Array)(FeatureSettings)).Length; - string[] arrProp = new string[len]; - for (int iCounter = 0; (iCounter < len); iCounter = (iCounter + 1)) { - arrProp[iCounter] = ((System.Management.ManagementPath)(((System.Array)(FeatureSettings)).GetValue(iCounter))).Path; - } - inParams["FeatureSettings"] = arrProp; - } - else { - inParams["FeatureSettings"] = null; - } - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RemoveFeatureSettings", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null)) - { - Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - return System.Convert.ToUInt32(0); - } - } - - public uint RemoveFibreChannelChap(string[] FcPortSettings) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("RemoveFibreChannelChap"); - inParams["FcPortSettings"] = ((string[])(FcPortSettings)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RemoveFibreChannelChap", inParams, null); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - return System.Convert.ToUInt32(0); - } - } - - public uint RemoveKvpItems(string[] DataItems, System.Management.ManagementPath TargetSystem, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("RemoveKvpItems"); - inParams["DataItems"] = ((string[])(DataItems)); - inParams["TargetSystem"] = ((System.Management.ManagementPath)(TargetSystem)).Path; - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RemoveKvpItems", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null)) - { - Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - return System.Convert.ToUInt32(0); - } - } - - public uint RemoveResourceSettings(System.Management.ManagementPath[] ResourceSettings, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("RemoveResourceSettings"); - if ((ResourceSettings != null)) { - int len = ((System.Array)(ResourceSettings)).Length; - string[] arrProp = new string[len]; - for (int iCounter = 0; (iCounter < len); iCounter = (iCounter + 1)) { - arrProp[iCounter] = ((System.Management.ManagementPath)(((System.Array)(ResourceSettings)).GetValue(iCounter))).Path; - } - inParams["ResourceSettings"] = arrProp; - } - else { - inParams["ResourceSettings"] = null; - } - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RemoveResourceSettings", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null)) - { - Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - return System.Convert.ToUInt32(0); - } - } - - public uint RequestStateChange(ushort RequestedState, System.DateTime TimeoutPeriod, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("RequestStateChange"); - inParams["RequestedState"] = ((ushort)(RequestedState)); - inParams["TimeoutPeriod"] = ToDmtfDateTime(((System.DateTime)(TimeoutPeriod))); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RequestStateChange", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null)) - { - Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - return System.Convert.ToUInt32(0); - } - } - - public uint SetGuestNetworkAdapterConfiguration(System.Management.ManagementPath ComputerSystem, string[] NetworkConfiguration, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("SetGuestNetworkAdapterConfiguration"); - inParams["ComputerSystem"] = ((System.Management.ManagementPath)(ComputerSystem)).Path; - inParams["NetworkConfiguration"] = ((string[])(NetworkConfiguration)); - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("SetGuestNetworkAdapterConfiguration", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null)) - { - Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - return System.Convert.ToUInt32(0); - } - } - - public uint StartService() { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("StartService", inParams, null); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - return System.Convert.ToUInt32(0); - } - } - - public uint StopService() { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("StopService", inParams, null); - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - return System.Convert.ToUInt32(0); - } - } - - public uint ValidatePlannedSystem(System.Management.ManagementPath PlannedSystem, out System.Management.ManagementPath Job) { - if ((isEmbedded == false)) { - System.Management.ManagementBaseObject inParams = null; - inParams = PrivateLateBoundObject.GetMethodParameters("ValidatePlannedSystem"); - inParams["PlannedSystem"] = ((System.Management.ManagementPath)(PlannedSystem)).Path; - System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ValidatePlannedSystem", inParams, null); - Job = null; - if ((outParams.Properties["Job"] != null)) - { - Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); - } - return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); - } - else { - Job = null; - return System.Convert.ToUInt32(0); - } - } - - // Enumerator implementation for enumerating instances of the class. - public class VirtualSystemManagementServiceCollection : object, ICollection { - - private ManagementObjectCollection privColObj; - - public VirtualSystemManagementServiceCollection(ManagementObjectCollection objCollection) { - privColObj = objCollection; - } - - public virtual int Count { - get { - return privColObj.Count; - } - } - - public virtual bool IsSynchronized { - get { - return privColObj.IsSynchronized; - } - } - - public virtual object SyncRoot { - get { - return this; - } - } - - public virtual void CopyTo(System.Array array, int index) { - privColObj.CopyTo(array, index); - int nCtr; - for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { - array.SetValue(new VirtualSystemManagementService(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); - } - } - - public virtual System.Collections.IEnumerator GetEnumerator() { - return new VirtualSystemManagementServiceEnumerator(privColObj.GetEnumerator()); - } - - public class VirtualSystemManagementServiceEnumerator : object, System.Collections.IEnumerator { - - private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; - - public VirtualSystemManagementServiceEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { - privObjEnum = objEnum; - } - - public virtual object Current { - get { - return new VirtualSystemManagementService(((System.Management.ManagementObject)(privObjEnum.Current))); - } - } - - public virtual bool MoveNext() { - return privObjEnum.MoveNext(); - } - - public virtual void Reset() { - privObjEnum.Reset(); - } - } - } - - // TypeConverter to handle null values for ValueType properties - public class WMIValueTypeConverter : TypeConverter { - - private TypeConverter baseConverter; - - private System.Type baseType; - - public WMIValueTypeConverter(System.Type inBaseType) { - baseConverter = TypeDescriptor.GetConverter(inBaseType); - baseType = inBaseType; - } - - public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { - return baseConverter.CanConvertFrom(context, srcType); - } - - public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { - return baseConverter.CanConvertTo(context, destinationType); - } - - public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { - return baseConverter.ConvertFrom(context, culture, value); - } - - public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { - return baseConverter.CreateInstance(context, dictionary); - } - - public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetCreateInstanceSupported(context); - } - - public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { - return baseConverter.GetProperties(context, value, attributeVar); - } - - public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetPropertiesSupported(context); - } - - public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValues(context); - } - - public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesExclusive(context); - } - - public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesSupported(context); - } - - public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { - if ((baseType.BaseType == typeof(System.Enum))) { - if ((value.GetType() == destinationType)) { - return value; - } - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return "NULL_ENUM_VALUE" ; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((baseType == typeof(bool)) - && (baseType.BaseType == typeof(System.ValueType)))) { - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((context != null) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - } - - // Embedded class to represent WMI system Properties. - [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] - public class ManagementSystemProperties { - - private System.Management.ManagementBaseObject PrivateLateBoundObject; - - public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { - PrivateLateBoundObject = ManagedObject; - } - - [Browsable(true)] - public int GENUS { - get { - return ((int)(PrivateLateBoundObject["__GENUS"])); - } - } - - [Browsable(true)] - public string CLASS { - get { - return ((string)(PrivateLateBoundObject["__CLASS"])); - } - } - - [Browsable(true)] - public string SUPERCLASS { - get { - return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); - } - } - - [Browsable(true)] - public string DYNASTY { - get { - return ((string)(PrivateLateBoundObject["__DYNASTY"])); - } - } - - [Browsable(true)] - public string RELPATH { - get { - return ((string)(PrivateLateBoundObject["__RELPATH"])); - } - } - - [Browsable(true)] - public int PROPERTY_COUNT { - get { - return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); - } - } - - [Browsable(true)] - public string[] DERIVATION { - get { - return ((string[])(PrivateLateBoundObject["__DERIVATION"])); - } - } - - [Browsable(true)] - public string SERVER { - get { - return ((string)(PrivateLateBoundObject["__SERVER"])); - } - } - - [Browsable(true)] - public string NAMESPACE { - get { - return ((string)(PrivateLateBoundObject["__NAMESPACE"])); - } - } - - [Browsable(true)] - public string PATH { - get { - return ((string)(PrivateLateBoundObject["__PATH"])); - } - } - } - } -} +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2 +{ + using System; + using System.ComponentModel; + using System.Management; + using System.Collections; + using System.Globalization; + using System.ComponentModel.Design.Serialization; + using System.Reflection; + + + // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. + // Functions IsNull() are used to check if a property is NULL. + // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. + // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. + // Datetime conversion functions ToDateTime and ToDmtfDateTime are added to the class to convert DMTF datetime to System.DateTime and vice-versa. + // An Early Bound class generated for the WMI class.Msvm_VirtualSystemManagementService + public class VirtualSystemManagementService : System.ComponentModel.Component { + + // Private property to hold the WMI namespace in which the class resides. + private static string CreatedWmiNamespace = "ROOT\\virtualization\\v2"; + + // Private property to hold the name of WMI class which created this class. + private static string CreatedClassName = "Msvm_VirtualSystemManagementService"; + + // Private member variable to hold the ManagementScope which is used by the various methods. + private static System.Management.ManagementScope statMgmtScope = null; + + private ManagementSystemProperties PrivateSystemProperties; + + // Underlying lateBound WMI object. + private System.Management.ManagementObject PrivateLateBoundObject; + + // Member variable to store the 'automatic commit' behavior for the class. + private bool AutoCommitProp; + + // Private variable to hold the embedded property representing the instance. + private System.Management.ManagementBaseObject embeddedObj; + + // The current WMI object used + private System.Management.ManagementBaseObject curObj; + + // Flag to indicate if the instance is an embedded object. + private bool isEmbedded; + + // Below are different overloads of constructors to initialize an instance of the class with a WMI object. + public VirtualSystemManagementService() { + this.InitializeObject(null, null, null); + } + + public VirtualSystemManagementService(string keyCreationClassName, string keyName, string keySystemCreationClassName, string keySystemName) { + this.InitializeObject(null, new System.Management.ManagementPath(VirtualSystemManagementService.ConstructPath(keyCreationClassName, keyName, keySystemCreationClassName, keySystemName)), null); + } + + public VirtualSystemManagementService(System.Management.ManagementScope mgmtScope, string keyCreationClassName, string keyName, string keySystemCreationClassName, string keySystemName) { + this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(VirtualSystemManagementService.ConstructPath(keyCreationClassName, keyName, keySystemCreationClassName, keySystemName)), null); + } + + public VirtualSystemManagementService(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(null, path, getOptions); + } + + public VirtualSystemManagementService(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { + this.InitializeObject(mgmtScope, path, null); + } + + public VirtualSystemManagementService(System.Management.ManagementPath path) { + this.InitializeObject(null, path, null); + } + + public VirtualSystemManagementService(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(mgmtScope, path, getOptions); + } + + public VirtualSystemManagementService(System.Management.ManagementObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + PrivateLateBoundObject = theObject; + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + public VirtualSystemManagementService(System.Management.ManagementBaseObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + embeddedObj = theObject; + PrivateSystemProperties = new ManagementSystemProperties(theObject); + curObj = embeddedObj; + isEmbedded = true; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + // Property returns the namespace of the WMI class. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OriginatingNamespace { + get { + return "ROOT\\virtualization\\v2"; + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ManagementClassName { + get { + string strRet = CreatedClassName; + if ((curObj != null)) { + if ((curObj.ClassPath != null)) { + strRet = ((string)(curObj["__CLASS"])); + if (((strRet == null) + || (strRet == string.Empty))) { + strRet = CreatedClassName; + } + } + } + return strRet; + } + } + + // Property pointing to an embedded object to get System properties of the WMI object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ManagementSystemProperties SystemProperties { + get { + return PrivateSystemProperties; + } + } + + // Property returning the underlying lateBound object. + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementBaseObject LateBoundObject { + get { + return curObj; + } + } + + // ManagementScope of the object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementScope Scope { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Scope; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Scope = value; + } + } + } + + // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool AutoCommit { + get { + return AutoCommitProp; + } + set { + AutoCommitProp = value; + } + } + + // The ManagementPath of the underlying WMI object. + [Browsable(true)] + public System.Management.ManagementPath Path { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Path; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + if ((CheckIfProperClass(null, value, null) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + PrivateLateBoundObject.Path = value; + } + } + } + + // Public static scope property which is used by the various methods. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public static System.Management.ManagementScope StaticScope { + get { + return statMgmtScope; + } + set { + statMgmtScope = value; + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ushort[] AvailableRequestedStates { + get { + return ((ushort[])(curObj["AvailableRequestedStates"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Caption { + get { + return ((string)(curObj["Caption"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsCommunicationStatusNull { + get { + if ((curObj["CommunicationStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort CommunicationStatus { + get { + if ((curObj["CommunicationStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["CommunicationStatus"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string CreationClassName { + get { + return ((string)(curObj["CreationClassName"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Description { + get { + return ((string)(curObj["Description"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsDetailedStatusNull { + get { + if ((curObj["DetailedStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort DetailedStatus { + get { + if ((curObj["DetailedStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["DetailedStatus"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ElementName { + get { + return ((string)(curObj["ElementName"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsEnabledDefaultNull { + get { + if ((curObj["EnabledDefault"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort EnabledDefault { + get { + if ((curObj["EnabledDefault"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["EnabledDefault"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsEnabledStateNull { + get { + if ((curObj["EnabledState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort EnabledState { + get { + if ((curObj["EnabledState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["EnabledState"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsHealthStateNull { + get { + if ((curObj["HealthState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort HealthState { + get { + if ((curObj["HealthState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["HealthState"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsInstallDateNull { + get { + if ((curObj["InstallDate"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime InstallDate { + get { + if ((curObj["InstallDate"] != null)) { + return ToDateTime(((string)(curObj["InstallDate"]))); + } + else { + return System.DateTime.MinValue; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string InstanceID { + get { + return ((string)(curObj["InstanceID"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Name { + get { + return ((string)(curObj["Name"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsOperatingStatusNull { + get { + if ((curObj["OperatingStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort OperatingStatus { + get { + if ((curObj["OperatingStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["OperatingStatus"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ushort[] OperationalStatus { + get { + return ((ushort[])(curObj["OperationalStatus"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OtherEnabledState { + get { + return ((string)(curObj["OtherEnabledState"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string PrimaryOwnerContact { + get { + return ((string)(curObj["PrimaryOwnerContact"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string PrimaryOwnerName { + get { + return ((string)(curObj["PrimaryOwnerName"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsPrimaryStatusNull { + get { + if ((curObj["PrimaryStatus"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort PrimaryStatus { + get { + if ((curObj["PrimaryStatus"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["PrimaryStatus"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsRequestedStateNull { + get { + if ((curObj["RequestedState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort RequestedState { + get { + if ((curObj["RequestedState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["RequestedState"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsStartedNull { + get { + if ((curObj["Started"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool Started { + get { + if ((curObj["Started"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["Started"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string StartMode { + get { + return ((string)(curObj["StartMode"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Status { + get { + return ((string)(curObj["Status"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] StatusDescriptions { + get { + return ((string[])(curObj["StatusDescriptions"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string SystemCreationClassName { + get { + return ((string)(curObj["SystemCreationClassName"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string SystemName { + get { + return ((string)(curObj["SystemName"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsTimeOfLastStateChangeNull { + get { + if ((curObj["TimeOfLastStateChange"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime TimeOfLastStateChange { + get { + if ((curObj["TimeOfLastStateChange"] != null)) { + return ToDateTime(((string)(curObj["TimeOfLastStateChange"]))); + } + else { + return System.DateTime.MinValue; + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsTransitioningToStateNull { + get { + if ((curObj["TransitioningToState"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort TransitioningToState { + get { + if ((curObj["TransitioningToState"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["TransitioningToState"])); + } + } + + private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { + if (((path != null) + && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); + } + } + + private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { + if (((theObj != null) + && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); + if ((parentClasses != null)) { + int count = 0; + for (count = 0; (count < parentClasses.Length); count = (count + 1)) { + if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { + return true; + } + } + } + } + return false; + } + + private bool ShouldSerializeCommunicationStatus() { + if ((this.IsCommunicationStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeDetailedStatus() { + if ((this.IsDetailedStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeEnabledDefault() { + if ((this.IsEnabledDefaultNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeEnabledState() { + if ((this.IsEnabledStateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeHealthState() { + if ((this.IsHealthStateNull == false)) { + return true; + } + return false; + } + + // Converts a given datetime in DMTF format to System.DateTime object. + static System.DateTime ToDateTime(string dmtfDate) { + System.DateTime initializer = System.DateTime.MinValue; + int year = initializer.Year; + int month = initializer.Month; + int day = initializer.Day; + int hour = initializer.Hour; + int minute = initializer.Minute; + int second = initializer.Second; + long ticks = 0; + string dmtf = dmtfDate; + System.DateTime datetime = System.DateTime.MinValue; + string tempString = string.Empty; + if ((dmtf == null)) { + throw new System.ArgumentOutOfRangeException(); + } + if ((dmtf.Length == 0)) { + throw new System.ArgumentOutOfRangeException(); + } + if ((dmtf.Length != 25)) { + throw new System.ArgumentOutOfRangeException(); + } + try { + tempString = dmtf.Substring(0, 4); + if (("****" != tempString)) { + year = int.Parse(tempString); + } + tempString = dmtf.Substring(4, 2); + if (("**" != tempString)) { + month = int.Parse(tempString); + } + tempString = dmtf.Substring(6, 2); + if (("**" != tempString)) { + day = int.Parse(tempString); + } + tempString = dmtf.Substring(8, 2); + if (("**" != tempString)) { + hour = int.Parse(tempString); + } + tempString = dmtf.Substring(10, 2); + if (("**" != tempString)) { + minute = int.Parse(tempString); + } + tempString = dmtf.Substring(12, 2); + if (("**" != tempString)) { + second = int.Parse(tempString); + } + tempString = dmtf.Substring(15, 6); + if (("******" != tempString)) { + ticks = (long.Parse(tempString) * ((long)((System.TimeSpan.TicksPerMillisecond / 1000)))); + } + if (((((((((year < 0) + || (month < 0)) + || (day < 0)) + || (hour < 0)) + || (minute < 0)) + || (minute < 0)) + || (second < 0)) + || (ticks < 0))) { + throw new System.ArgumentOutOfRangeException(); + } + } + catch (System.Exception e) { + throw new System.ArgumentOutOfRangeException(null, e.Message); + } + datetime = new System.DateTime(year, month, day, hour, minute, second, 0); + datetime = datetime.AddTicks(ticks); + System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(datetime); + int UTCOffset = 0; + int OffsetToBeAdjusted = 0; + long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); + tempString = dmtf.Substring(22, 3); + if ((tempString != "******")) { + tempString = dmtf.Substring(21, 4); + try { + UTCOffset = int.Parse(tempString); + } + catch (System.Exception e) { + throw new System.ArgumentOutOfRangeException(null, e.Message); + } + OffsetToBeAdjusted = ((int)((OffsetMins - UTCOffset))); + datetime = datetime.AddMinutes(((double)(OffsetToBeAdjusted))); + } + return datetime; + } + + // Converts a given System.DateTime object to DMTF datetime format. + static string ToDmtfDateTime(System.DateTime date) { + string utcString = string.Empty; + System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(date); + long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); + if ((System.Math.Abs(OffsetMins) > 999)) { + date = date.ToUniversalTime(); + utcString = "+000"; + } + else { + if ((tickOffset.Ticks >= 0)) { + utcString = string.Concat("+", ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))).ToString().PadLeft(3, '0')); + } + else { + string strTemp = ((long)(OffsetMins)).ToString(); + utcString = string.Concat("-", strTemp.Substring(1, (strTemp.Length - 1)).PadLeft(3, '0')); + } + } + string dmtfDateTime = ((int)(date.Year)).ToString().PadLeft(4, '0'); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Month)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Day)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Hour)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Minute)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Second)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, "."); + System.DateTime dtTemp = new System.DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, 0); + long microsec = ((long)((((date.Ticks - dtTemp.Ticks) + * 1000) + / System.TimeSpan.TicksPerMillisecond))); + string strMicrosec = ((long)(microsec)).ToString(); + if ((strMicrosec.Length > 6)) { + strMicrosec = strMicrosec.Substring(0, 6); + } + dmtfDateTime = string.Concat(dmtfDateTime, strMicrosec.PadLeft(6, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, utcString); + return dmtfDateTime; + } + + private bool ShouldSerializeInstallDate() { + if ((this.IsInstallDateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeOperatingStatus() { + if ((this.IsOperatingStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializePrimaryStatus() { + if ((this.IsPrimaryStatusNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeRequestedState() { + if ((this.IsRequestedStateNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeStarted() { + if ((this.IsStartedNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeTimeOfLastStateChange() { + if ((this.IsTimeOfLastStateChangeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeTransitioningToState() { + if ((this.IsTransitioningToStateNull == false)) { + return true; + } + return false; + } + + [Browsable(true)] + public void CommitObject() { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(); + } + } + + [Browsable(true)] + public void CommitObject(System.Management.PutOptions putOptions) { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(putOptions); + } + } + + private void Initialize() { + AutoCommitProp = true; + isEmbedded = false; + } + + private static string ConstructPath(string keyCreationClassName, string keyName, string keySystemCreationClassName, string keySystemName) { + string strPath = "ROOT\\virtualization\\v2:Msvm_VirtualSystemManagementService"; + strPath = string.Concat(strPath, string.Concat(".CreationClassName=", string.Concat("\"", string.Concat(keyCreationClassName, "\"")))); + strPath = string.Concat(strPath, string.Concat(",Name=", string.Concat("\"", string.Concat(keyName, "\"")))); + strPath = string.Concat(strPath, string.Concat(",SystemCreationClassName=", string.Concat("\"", string.Concat(keySystemCreationClassName, "\"")))); + strPath = string.Concat(strPath, string.Concat(",SystemName=", string.Concat("\"", string.Concat(keySystemName, "\"")))); + return strPath; + } + + private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + Initialize(); + if ((path != null)) { + if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + } + PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + + // Different overloads of GetInstances() help in enumerating instances of the WMI class. + public static VirtualSystemManagementServiceCollection GetInstances() { + return GetInstances(null, null, null); + } + + public static VirtualSystemManagementServiceCollection GetInstances(string condition) { + return GetInstances(null, condition, null); + } + + public static VirtualSystemManagementServiceCollection GetInstances(string[] selectedProperties) { + return GetInstances(null, null, selectedProperties); + } + + public static VirtualSystemManagementServiceCollection GetInstances(string condition, string[] selectedProperties) { + return GetInstances(null, condition, selectedProperties); + } + + public static VirtualSystemManagementServiceCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); + pathObj.ClassName = "Msvm_VirtualSystemManagementService"; + pathObj.NamespacePath = "root\\virtualization\\v2"; + System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); + if ((enumOptions == null)) { + enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + } + return new VirtualSystemManagementServiceCollection(clsObject.GetInstances(enumOptions)); + } + + public static VirtualSystemManagementServiceCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { + return GetInstances(mgmtScope, condition, null); + } + + public static VirtualSystemManagementServiceCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { + return GetInstances(mgmtScope, null, selectedProperties); + } + + public static VirtualSystemManagementServiceCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_VirtualSystemManagementService", condition, selectedProperties)); + System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + ObjectSearcher.Options = enumOptions; + return new VirtualSystemManagementServiceCollection(ObjectSearcher.Get()); + } + + [Browsable(true)] + public static VirtualSystemManagementService CreateInstance() { + System.Management.ManagementScope mgmtScope = null; + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = CreatedWmiNamespace; + } + else { + mgmtScope = statMgmtScope; + } + System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); + System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); + return new VirtualSystemManagementService(tmpMgmtClass.CreateInstance()); + } + + [Browsable(true)] + public void Delete() { + PrivateLateBoundObject.Delete(); + } + + public uint AddFeatureSettings(System.Management.ManagementPath AffectedConfiguration, string[] FeatureSettings, out System.Management.ManagementPath Job, out System.Management.ManagementPath[] ResultingFeatureSettings) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("AddFeatureSettings"); + inParams["AffectedConfiguration"] = ((System.Management.ManagementPath)(AffectedConfiguration)).Path; + inParams["FeatureSettings"] = ((string[])(FeatureSettings)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("AddFeatureSettings", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null)) + { + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); + } + ResultingFeatureSettings = null; + if ((outParams.Properties["ResultingFeatureSettings"] != null && outParams.Properties["ResultingFeatureSettings"].Value != null)) + { + int len = ((System.Array)(outParams.Properties["ResultingFeatureSettings"].Value)).Length; + System.Management.ManagementPath[] arrToRet = new System.Management.ManagementPath[len]; + for (int iCounter = 0; (iCounter < len); iCounter = (iCounter + 1)) { + arrToRet[iCounter] = new System.Management.ManagementPath(((System.Array)(outParams.Properties["ResultingFeatureSettings"].Value)).GetValue(iCounter).ToString()); + } + ResultingFeatureSettings = arrToRet; + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + ResultingFeatureSettings = null; + return System.Convert.ToUInt32(0); + } + } + + public uint AddFibreChannelChap(string[] FcPortSettings, byte SecretEncoding, byte[] SharedSecret) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("AddFibreChannelChap"); + inParams["FcPortSettings"] = ((string[])(FcPortSettings)); + inParams["SecretEncoding"] = ((byte)(SecretEncoding)); + inParams["SharedSecret"] = ((byte[])(SharedSecret)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("AddFibreChannelChap", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + public uint AddKvpItems(string[] DataItems, System.Management.ManagementPath TargetSystem, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("AddKvpItems"); + inParams["DataItems"] = ((string[])(DataItems)); + inParams["TargetSystem"] = ((System.Management.ManagementPath)(TargetSystem)).Path; + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("AddKvpItems", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null)) + { + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + return System.Convert.ToUInt32(0); + } + } + + public uint AddResourceSettings(System.Management.ManagementPath AffectedConfiguration, string[] ResourceSettings, out System.Management.ManagementPath Job, out System.Management.ManagementPath[] ResultingResourceSettings) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("AddResourceSettings"); + inParams["AffectedConfiguration"] = ((System.Management.ManagementPath)(AffectedConfiguration)).Path; + inParams["ResourceSettings"] = ((string[])(ResourceSettings)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("AddResourceSettings", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null)) + { + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); + } + ResultingResourceSettings = null; + if ((outParams.Properties["ResultingResourceSettings"] != null && outParams.Properties["ResultingResourceSettings"].Value != null)) + { + int len = ((System.Array)(outParams.Properties["ResultingResourceSettings"].Value)).Length; + System.Management.ManagementPath[] arrToRet = new System.Management.ManagementPath[len]; + for (int iCounter = 0; (iCounter < len); iCounter = (iCounter + 1)) { + arrToRet[iCounter] = new System.Management.ManagementPath(((System.Array)(outParams.Properties["ResultingResourceSettings"].Value)).GetValue(iCounter).ToString()); + } + ResultingResourceSettings = arrToRet; + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + ResultingResourceSettings = null; + return System.Convert.ToUInt32(0); + } + } + + public uint DefineSystem(string ReferenceConfigurationPath, string[] ResourceSettings, string SystemSettings, out System.Management.ManagementPath Job, out System.Management.ManagementPath ResultingSystem) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("DefineSystem"); + inParams["ReferenceConfiguration"] = ReferenceConfigurationPath; + inParams["ResourceSettings"] = ResourceSettings; + inParams["SystemSettings"] = SystemSettings; + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("DefineSystem", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null) && outParams.Properties["Job"].Value != null) + { + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); + } + ResultingSystem = null; + if ((outParams.Properties["ResultingSystem"] != null && outParams.Properties["ResultingSystem"].Value != null)) + { + ResultingSystem = new System.Management.ManagementPath((string)outParams.Properties["ResultingSystem"].Value); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + ResultingSystem = null; + return System.Convert.ToUInt32(0); + } + } + + public uint DestroySystem(System.Management.ManagementPath AffectedSystem, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("DestroySystem"); + inParams["AffectedSystem"] = ((System.Management.ManagementPath)(AffectedSystem)).Path; + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("DestroySystem", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null)) + { + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + return System.Convert.ToUInt32(0); + } + } + + public uint ExportSystemDefinition(System.Management.ManagementPath ComputerSystem, string ExportDirectory, string ExportSettingData, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("ExportSystemDefinition"); + inParams["ComputerSystem"] = ((System.Management.ManagementPath)(ComputerSystem)).Path; + inParams["ExportDirectory"] = ((string)(ExportDirectory)); + inParams["ExportSettingData"] = ((string)(ExportSettingData)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ExportSystemDefinition", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null)) + { + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); + } + + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + return System.Convert.ToUInt32(0); + } + } + + public uint FormatError(string[] Errors, out string ErrorMessage) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("FormatError"); + inParams["Errors"] = ((string[])(Errors)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("FormatError", inParams, null); + ErrorMessage = System.Convert.ToString(outParams.Properties["ErrorMessage"].Value); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + ErrorMessage = null; + return System.Convert.ToUInt32(0); + } + } + + public uint GenerateWwpn(uint NumberOfWwpns, out string[] GeneratedWwpn) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("GenerateWwpn"); + inParams["NumberOfWwpns"] = ((uint)(NumberOfWwpns)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("GenerateWwpn", inParams, null); + GeneratedWwpn = ((string[])(outParams.Properties["GeneratedWwpn"].Value)); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + GeneratedWwpn = null; + return System.Convert.ToUInt32(0); + } + } + + public uint GetCurrentWwpnFromGenerator(out string CurrentWwpn) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("GetCurrentWwpnFromGenerator", inParams, null); + CurrentWwpn = System.Convert.ToString(outParams.Properties["CurrentWwpn"].Value); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + CurrentWwpn = null; + return System.Convert.ToUInt32(0); + } + } + + public uint GetDefinitionFileSummaryInformation(string[] DefinitionFiles, out System.Management.ManagementBaseObject[] SummaryInformation) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("GetDefinitionFileSummaryInformation"); + inParams["DefinitionFiles"] = ((string[])(DefinitionFiles)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("GetDefinitionFileSummaryInformation", inParams, null); + SummaryInformation = ((System.Management.ManagementBaseObject[])(outParams.Properties["SummaryInformation"].Value)); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + SummaryInformation = null; + return System.Convert.ToUInt32(0); + } + } + + public uint GetSizeOfSystemFiles(System.Management.ManagementPath Vssd, out ulong Size) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("GetSizeOfSystemFiles"); + inParams["Vssd"] = ((System.Management.ManagementPath)(Vssd)).Path; + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("GetSizeOfSystemFiles", inParams, null); + Size = System.Convert.ToUInt64(outParams.Properties["Size"].Value); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Size = System.Convert.ToUInt64(0); + return System.Convert.ToUInt32(0); + } + } + + public uint GetSummaryInformation(uint[] RequestedInformation, System.Management.ManagementPath[] SettingData, out System.Management.ManagementBaseObject[] SummaryInformation) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("GetSummaryInformation"); + inParams["RequestedInformation"] = ((uint[])(RequestedInformation)); + if ((SettingData != null)) { + int len = ((System.Array)(SettingData)).Length; + string[] arrProp = new string[len]; + for (int iCounter = 0; (iCounter < len); iCounter = (iCounter + 1)) { + arrProp[iCounter] = ((System.Management.ManagementPath)(((System.Array)(SettingData)).GetValue(iCounter))).Path; + } + inParams["SettingData"] = arrProp; + } + else { + inParams["SettingData"] = null; + } + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("GetSummaryInformation", inParams, null); + SummaryInformation = ((System.Management.ManagementBaseObject[])(outParams.Properties["SummaryInformation"].Value)); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + SummaryInformation = null; + return System.Convert.ToUInt32(0); + } + } + + public uint GetVirtualSystemThumbnailImage(ushort HeightPixels, System.Management.ManagementPath TargetSystem, ushort WidthPixels, out byte[] ImageData) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("GetVirtualSystemThumbnailImage"); + inParams["HeightPixels"] = ((ushort)(HeightPixels)); + inParams["TargetSystem"] = ((System.Management.ManagementPath)(TargetSystem)).Path; + inParams["WidthPixels"] = ((ushort)(WidthPixels)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("GetVirtualSystemThumbnailImage", inParams, null); + ImageData = ((byte[])(outParams.Properties["ImageData"].Value)); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + ImageData = null; + return System.Convert.ToUInt32(0); + } + } + + public uint ImportSnapshotDefinitions(System.Management.ManagementPath PlannedSystem, string SnapshotFolder, out System.Management.ManagementPath[] ImportedSnapshots, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("ImportSnapshotDefinitions"); + inParams["PlannedSystem"] = ((System.Management.ManagementPath)(PlannedSystem)).Path; + inParams["SnapshotFolder"] = ((string)(SnapshotFolder)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ImportSnapshotDefinitions", inParams, null); + ImportedSnapshots = null; + if ((outParams.Properties["ImportedSnapshots"] != null && outParams.Properties["ImportedSnapshots"].Value != null)) + { + int len = ((System.Array)(outParams.Properties["ImportedSnapshots"].Value)).Length; + System.Management.ManagementPath[] arrToRet = new System.Management.ManagementPath[len]; + for (int iCounter = 0; (iCounter < len); iCounter = (iCounter + 1)) { + arrToRet[iCounter] = new System.Management.ManagementPath(((System.Array)(outParams.Properties["ImportedSnapshots"].Value)).GetValue(iCounter).ToString()); + } + ImportedSnapshots = arrToRet; + } + Job = null; + if ((outParams.Properties["Job"] != null)) + { + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + ImportedSnapshots = null; + Job = null; + return System.Convert.ToUInt32(0); + } + } + + public uint ImportSystemDefinition(bool GenerateNewSystemIdentifier, string SnapshotFolder, string SystemDefinitionFile, out System.Management.ManagementPath ImportedSystem, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("ImportSystemDefinition"); + inParams["GenerateNewSystemIdentifier"] = ((bool)(GenerateNewSystemIdentifier)); + inParams["SnapshotFolder"] = ((string)(SnapshotFolder)); + inParams["SystemDefinitionFile"] = ((string)(SystemDefinitionFile)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ImportSystemDefinition", inParams, null); + ImportedSystem = null; + if ((outParams.Properties["ImportedSystem"] != null && outParams.Properties["ImportedSystem"].Value != null)) + { + ImportedSystem = new System.Management.ManagementPath(outParams.Properties["ImportedSystem"].ToString()); + } + Job = null; + if ((outParams.Properties["Job"] != null)) + { + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); + } + + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + ImportedSystem = null; + Job = null; + return System.Convert.ToUInt32(0); + } + } + + public uint ModifyDiskMergeSettings(string SettingData, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("ModifyDiskMergeSettings"); + inParams["SettingData"] = ((string)(SettingData)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ModifyDiskMergeSettings", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null)) + { + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + return System.Convert.ToUInt32(0); + } + } + + public uint ModifyFeatureSettings(string[] FeatureSettings, out System.Management.ManagementPath Job, out System.Management.ManagementPath[] ResultingFeatureSettings) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("ModifyFeatureSettings"); + inParams["FeatureSettings"] = ((string[])(FeatureSettings)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ModifyFeatureSettings", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null)) + { + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); + } + ResultingFeatureSettings = null; + if ((outParams.Properties["ResultingFeatureSettings"] != null && outParams.Properties["ResultingFeatureSettings"].Value != null)) + { + int len = ((System.Array)(outParams.Properties["ResultingFeatureSettings"].Value)).Length; + System.Management.ManagementPath[] arrToRet = new System.Management.ManagementPath[len]; + for (int iCounter = 0; (iCounter < len); iCounter = (iCounter + 1)) { + arrToRet[iCounter] = new System.Management.ManagementPath(((System.Array)(outParams.Properties["ResultingFeatureSettings"].Value)).GetValue(iCounter).ToString()); + } + ResultingFeatureSettings = arrToRet; + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + ResultingFeatureSettings = null; + return System.Convert.ToUInt32(0); + } + } + + public uint ModifyKvpItems(string[] DataItems, System.Management.ManagementPath TargetSystem, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("ModifyKvpItems"); + inParams["DataItems"] = ((string[])(DataItems)); + inParams["TargetSystem"] = ((System.Management.ManagementPath)(TargetSystem)).Path; + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ModifyKvpItems", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null)) + { + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + return System.Convert.ToUInt32(0); + } + } + + public uint ModifyResourceSettings(string[] ResourceSettings, out System.Management.ManagementPath Job, out System.Management.ManagementPath[] ResultingResourceSettings) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("ModifyResourceSettings"); + inParams["ResourceSettings"] = ((string[])(ResourceSettings)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ModifyResourceSettings", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null) && outParams.Properties["Job"].Value != null) + { + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); + } + ResultingResourceSettings = null; + if ((outParams.Properties["ResultingResourceSettings"] != null && outParams.Properties["ResultingResourceSettings"].Value != null)) + { + int len = ((System.Array)(outParams.Properties["ResultingResourceSettings"].Value)).Length; + System.Management.ManagementPath[] arrToRet = new System.Management.ManagementPath[len]; + for (int iCounter = 0; (iCounter < len); iCounter = (iCounter + 1)) { + arrToRet[iCounter] = new System.Management.ManagementPath(((System.Array)(outParams.Properties["ResultingResourceSettings"].Value)).GetValue(iCounter).ToString()); + } + ResultingResourceSettings = arrToRet; + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + ResultingResourceSettings = null; + return System.Convert.ToUInt32(0); + } + } + + public uint ModifyServiceSettings(string SettingData, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("ModifyServiceSettings"); + inParams["SettingData"] = ((string)(SettingData)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ModifyServiceSettings", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null)) + { + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + return System.Convert.ToUInt32(0); + } + } + + public uint ModifySystemSettings(string SystemSettings, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("ModifySystemSettings"); + inParams["SystemSettings"] = ((string)(SystemSettings)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ModifySystemSettings", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null)) + { + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + return System.Convert.ToUInt32(0); + } + } + + public uint RealizePlannedSystem(System.Management.ManagementPath PlannedSystem, out System.Management.ManagementPath Job, out System.Management.ManagementPath ResultingSystem) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("RealizePlannedSystem"); + inParams["PlannedSystem"] = ((System.Management.ManagementPath)(PlannedSystem)).Path; + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RealizePlannedSystem", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null)) + { + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); + } + ResultingSystem = null; + if ((outParams.Properties["ResultingSystem"] != null)) { + ResultingSystem = new System.Management.ManagementPath(outParams.Properties["ResultingSystem"].ToString()); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + ResultingSystem = null; + return System.Convert.ToUInt32(0); + } + } + + public uint RemoveFeatureSettings(System.Management.ManagementPath[] FeatureSettings, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("RemoveFeatureSettings"); + if ((FeatureSettings != null)) { + int len = ((System.Array)(FeatureSettings)).Length; + string[] arrProp = new string[len]; + for (int iCounter = 0; (iCounter < len); iCounter = (iCounter + 1)) { + arrProp[iCounter] = ((System.Management.ManagementPath)(((System.Array)(FeatureSettings)).GetValue(iCounter))).Path; + } + inParams["FeatureSettings"] = arrProp; + } + else { + inParams["FeatureSettings"] = null; + } + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RemoveFeatureSettings", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null)) + { + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + return System.Convert.ToUInt32(0); + } + } + + public uint RemoveFibreChannelChap(string[] FcPortSettings) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("RemoveFibreChannelChap"); + inParams["FcPortSettings"] = ((string[])(FcPortSettings)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RemoveFibreChannelChap", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + public uint RemoveKvpItems(string[] DataItems, System.Management.ManagementPath TargetSystem, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("RemoveKvpItems"); + inParams["DataItems"] = ((string[])(DataItems)); + inParams["TargetSystem"] = ((System.Management.ManagementPath)(TargetSystem)).Path; + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RemoveKvpItems", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null)) + { + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + return System.Convert.ToUInt32(0); + } + } + + public uint RemoveResourceSettings(System.Management.ManagementPath[] ResourceSettings, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("RemoveResourceSettings"); + if ((ResourceSettings != null)) { + int len = ((System.Array)(ResourceSettings)).Length; + string[] arrProp = new string[len]; + for (int iCounter = 0; (iCounter < len); iCounter = (iCounter + 1)) { + arrProp[iCounter] = ((System.Management.ManagementPath)(((System.Array)(ResourceSettings)).GetValue(iCounter))).Path; + } + inParams["ResourceSettings"] = arrProp; + } + else { + inParams["ResourceSettings"] = null; + } + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RemoveResourceSettings", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null)) + { + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + return System.Convert.ToUInt32(0); + } + } + + public uint RequestStateChange(ushort RequestedState, System.DateTime TimeoutPeriod, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("RequestStateChange"); + inParams["RequestedState"] = ((ushort)(RequestedState)); + inParams["TimeoutPeriod"] = ToDmtfDateTime(((System.DateTime)(TimeoutPeriod))); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("RequestStateChange", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null)) + { + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + return System.Convert.ToUInt32(0); + } + } + + public uint SetGuestNetworkAdapterConfiguration(System.Management.ManagementPath ComputerSystem, string[] NetworkConfiguration, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("SetGuestNetworkAdapterConfiguration"); + inParams["ComputerSystem"] = ((System.Management.ManagementPath)(ComputerSystem)).Path; + inParams["NetworkConfiguration"] = ((string[])(NetworkConfiguration)); + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("SetGuestNetworkAdapterConfiguration", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null)) + { + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + return System.Convert.ToUInt32(0); + } + } + + public uint StartService() { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("StartService", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + public uint StopService() { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("StopService", inParams, null); + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + return System.Convert.ToUInt32(0); + } + } + + public uint ValidatePlannedSystem(System.Management.ManagementPath PlannedSystem, out System.Management.ManagementPath Job) { + if ((isEmbedded == false)) { + System.Management.ManagementBaseObject inParams = null; + inParams = PrivateLateBoundObject.GetMethodParameters("ValidatePlannedSystem"); + inParams["PlannedSystem"] = ((System.Management.ManagementPath)(PlannedSystem)).Path; + System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("ValidatePlannedSystem", inParams, null); + Job = null; + if ((outParams.Properties["Job"] != null)) + { + Job = new System.Management.ManagementPath((string)outParams.Properties["Job"].Value); + } + return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); + } + else { + Job = null; + return System.Convert.ToUInt32(0); + } + } + + // Enumerator implementation for enumerating instances of the class. + public class VirtualSystemManagementServiceCollection : object, ICollection { + + private ManagementObjectCollection privColObj; + + public VirtualSystemManagementServiceCollection(ManagementObjectCollection objCollection) { + privColObj = objCollection; + } + + public virtual int Count { + get { + return privColObj.Count; + } + } + + public virtual bool IsSynchronized { + get { + return privColObj.IsSynchronized; + } + } + + public virtual object SyncRoot { + get { + return this; + } + } + + public virtual void CopyTo(System.Array array, int index) { + privColObj.CopyTo(array, index); + int nCtr; + for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { + array.SetValue(new VirtualSystemManagementService(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); + } + } + + public virtual System.Collections.IEnumerator GetEnumerator() { + return new VirtualSystemManagementServiceEnumerator(privColObj.GetEnumerator()); + } + + public class VirtualSystemManagementServiceEnumerator : object, System.Collections.IEnumerator { + + private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; + + public VirtualSystemManagementServiceEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { + privObjEnum = objEnum; + } + + public virtual object Current { + get { + return new VirtualSystemManagementService(((System.Management.ManagementObject)(privObjEnum.Current))); + } + } + + public virtual bool MoveNext() { + return privObjEnum.MoveNext(); + } + + public virtual void Reset() { + privObjEnum.Reset(); + } + } + } + + // TypeConverter to handle null values for ValueType properties + public class WMIValueTypeConverter : TypeConverter { + + private TypeConverter baseConverter; + + private System.Type baseType; + + public WMIValueTypeConverter(System.Type inBaseType) { + baseConverter = TypeDescriptor.GetConverter(inBaseType); + baseType = inBaseType; + } + + public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { + return baseConverter.CanConvertFrom(context, srcType); + } + + public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { + return baseConverter.CanConvertTo(context, destinationType); + } + + public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { + return baseConverter.ConvertFrom(context, culture, value); + } + + public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { + return baseConverter.CreateInstance(context, dictionary); + } + + public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetCreateInstanceSupported(context); + } + + public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { + return baseConverter.GetProperties(context, value, attributeVar); + } + + public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetPropertiesSupported(context); + } + + public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValues(context); + } + + public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesExclusive(context); + } + + public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesSupported(context); + } + + public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { + if ((baseType.BaseType == typeof(System.Enum))) { + if ((value.GetType() == destinationType)) { + return value; + } + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return "NULL_ENUM_VALUE" ; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((baseType == typeof(bool)) + && (baseType.BaseType == typeof(System.ValueType)))) { + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((context != null) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + } + + // Embedded class to represent WMI system Properties. + [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] + public class ManagementSystemProperties { + + private System.Management.ManagementBaseObject PrivateLateBoundObject; + + public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { + PrivateLateBoundObject = ManagedObject; + } + + [Browsable(true)] + public int GENUS { + get { + return ((int)(PrivateLateBoundObject["__GENUS"])); + } + } + + [Browsable(true)] + public string CLASS { + get { + return ((string)(PrivateLateBoundObject["__CLASS"])); + } + } + + [Browsable(true)] + public string SUPERCLASS { + get { + return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); + } + } + + [Browsable(true)] + public string DYNASTY { + get { + return ((string)(PrivateLateBoundObject["__DYNASTY"])); + } + } + + [Browsable(true)] + public string RELPATH { + get { + return ((string)(PrivateLateBoundObject["__RELPATH"])); + } + } + + [Browsable(true)] + public int PROPERTY_COUNT { + get { + return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); + } + } + + [Browsable(true)] + public string[] DERIVATION { + get { + return ((string[])(PrivateLateBoundObject["__DERIVATION"])); + } + } + + [Browsable(true)] + public string SERVER { + get { + return ((string)(PrivateLateBoundObject["__SERVER"])); + } + } + + [Browsable(true)] + public string NAMESPACE { + get { + return ((string)(PrivateLateBoundObject["__NAMESPACE"])); + } + } + + [Browsable(true)] + public string PATH { + get { + return ((string)(PrivateLateBoundObject["__PATH"])); + } + } + } + } +} diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_VirtualSystemManagementServiceSettingData.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_VirtualSystemManagementServiceSettingData.cs index 98f0eff6383..7347df9b095 100644 --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_VirtualSystemManagementServiceSettingData.cs +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_VirtualSystemManagementServiceSettingData.cs @@ -1,809 +1,809 @@ -// Licensed to the Apache Software Foundation (ASF) under one -// or more contributor license agreements. See the NOTICE file -// distributed with this work for additional information -// regarding copyright ownership. The ASF licenses this file -// to you under the Apache License, Version 2.0 (the -// "License"); you may not use this file except in compliance -// with the License. You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, -// software distributed under the License is distributed on an -// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -// KIND, either express or implied. See the License for the -// specific language governing permissions and limitations -// under the License. - -namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2 -{ - using System; - using System.ComponentModel; - using System.Management; - using System.Collections; - using System.Globalization; - using System.ComponentModel.Design.Serialization; - using System.Reflection; - - - // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. - // Functions IsNull() are used to check if a property is NULL. - // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. - // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. - // An Early Bound class generated for the WMI class.Msvm_VirtualSystemManagementServiceSettingData - public class VirtualSystemManagementServiceSettingData : System.ComponentModel.Component { - - // Private property to hold the WMI namespace in which the class resides. - private static string CreatedWmiNamespace = "ROOT\\virtualization\\v2"; - - // Private property to hold the name of WMI class which created this class. - public static string CreatedClassName = "Msvm_VirtualSystemManagementServiceSettingData"; - - // Private member variable to hold the ManagementScope which is used by the various methods. - private static System.Management.ManagementScope statMgmtScope = null; - - private ManagementSystemProperties PrivateSystemProperties; - - // Underlying lateBound WMI object. - private System.Management.ManagementObject PrivateLateBoundObject; - - // Member variable to store the 'automatic commit' behavior for the class. - private bool AutoCommitProp; - - // Private variable to hold the embedded property representing the instance. - private System.Management.ManagementBaseObject embeddedObj; - - // The current WMI object used - private System.Management.ManagementBaseObject curObj; - - // Flag to indicate if the instance is an embedded object. - private bool isEmbedded; - - // Below are different overloads of constructors to initialize an instance of the class with a WMI object. - public VirtualSystemManagementServiceSettingData() { - this.InitializeObject(null, null, null); - } - - public VirtualSystemManagementServiceSettingData(string keyInstanceID) { - this.InitializeObject(null, new System.Management.ManagementPath(VirtualSystemManagementServiceSettingData.ConstructPath(keyInstanceID)), null); - } - - public VirtualSystemManagementServiceSettingData(System.Management.ManagementScope mgmtScope, string keyInstanceID) { - this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(VirtualSystemManagementServiceSettingData.ConstructPath(keyInstanceID)), null); - } - - public VirtualSystemManagementServiceSettingData(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(null, path, getOptions); - } - - public VirtualSystemManagementServiceSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { - this.InitializeObject(mgmtScope, path, null); - } - - public VirtualSystemManagementServiceSettingData(System.Management.ManagementPath path) { - this.InitializeObject(null, path, null); - } - - public VirtualSystemManagementServiceSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(mgmtScope, path, getOptions); - } - - public VirtualSystemManagementServiceSettingData(System.Management.ManagementObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - PrivateLateBoundObject = theObject; - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - public VirtualSystemManagementServiceSettingData(System.Management.ManagementBaseObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - embeddedObj = theObject; - PrivateSystemProperties = new ManagementSystemProperties(theObject); - curObj = embeddedObj; - isEmbedded = true; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - // Property returns the namespace of the WMI class. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OriginatingNamespace { - get { - return "ROOT\\virtualization\\v2"; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ManagementClassName { - get { - string strRet = CreatedClassName; - if ((curObj != null)) { - if ((curObj.ClassPath != null)) { - strRet = ((string)(curObj["__CLASS"])); - if (((strRet == null) - || (strRet == string.Empty))) { - strRet = CreatedClassName; - } - } - } - return strRet; - } - } - - // Property pointing to an embedded object to get System properties of the WMI object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ManagementSystemProperties SystemProperties { - get { - return PrivateSystemProperties; - } - } - - // Property returning the underlying lateBound object. - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementBaseObject LateBoundObject { - get { - return curObj; - } - } - - // ManagementScope of the object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementScope Scope { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Scope; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Scope = value; - } - } - } - - // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool AutoCommit { - get { - return AutoCommitProp; - } - set { - AutoCommitProp = value; - } - } - - // The ManagementPath of the underlying WMI object. - [Browsable(true)] - public System.Management.ManagementPath Path { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Path; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - if ((CheckIfProperClass(null, value, null) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - PrivateLateBoundObject.Path = value; - } - } - } - - // Public static scope property which is used by the various methods. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public static System.Management.ManagementScope StaticScope { - get { - return statMgmtScope; - } - set { - statMgmtScope = value; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description(@"Used by OEMs to allow BIOS-locked Windows operating systems to run in the virtual machine. This string must be exactly 32 characters in length. -This is a read-only property, but it can be changed using the ModifyServiceSettings method of the Msvm_VirtualSystemManagementService class.")] - public string BiosLockString { - get { - return ((string)(curObj["BiosLockString"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Caption { - get { - return ((string)(curObj["Caption"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The WorldWideNodeName address for dynamically generated WorldWideName addresses u" + - "sed for Synthetic HBAs.\nThis is a read-only property, but it can be changed usin" + - "g the ModifyServiceSettings method of the Msvm_VirtualSystemManagementService cl" + - "ass.")] - public string CurrentWWNNAddress { - get { - return ((string)(curObj["CurrentWWNNAddress"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The default external data root. By default, \"root\\ProgramData\\Microsoft\\Windows\\V" + - "irtualization\".\nThis is a read-only property, but it can be changed using the Mo" + - "difyServiceSettings method of the Msvm_VirtualSystemManagementService class.")] - public string DefaultExternalDataRoot { - get { - return ((string)(curObj["DefaultExternalDataRoot"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The default virtual hard disk path. By default, \"root\\Users\\Public\\Documents\\Virt" + - "ual Hard Disks\".\nThis is a read-only property, but it can be changed using the M" + - "odifyServiceSettings method of the Msvm_VirtualSystemManagementService class.")] - public string DefaultVirtualHardDiskPath { - get { - return ((string)(curObj["DefaultVirtualHardDiskPath"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Description { - get { - return ((string)(curObj["Description"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ElementName { - get { - return ((string)(curObj["ElementName"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsHbaLunTimeoutNull { - get { - if ((curObj["HbaLunTimeout"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description(@"This property describes the amount of time that the Synthetic FC virtual device will wait for a LUN to appear before starting a virtual machine. -This is a read-only property, but it can be changed using the ModifyServiceSettings method of the Msvm_VirtualSystemManagementService class.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public uint HbaLunTimeout { - get { - if ((curObj["HbaLunTimeout"] == null)) { - return System.Convert.ToUInt32(0); - } - return ((uint)(curObj["HbaLunTimeout"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string InstanceID { - get { - return ((string)(curObj["InstanceID"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The maximum MAC address for dynamically generated MAC addresses.\nThis is a read-o" + - "nly property, but it can be changed using the ModifyServiceSettings method of th" + - "e Msvm_VirtualSystemManagementService class.")] - public string MaximumMacAddress { - get { - return ((string)(curObj["MaximumMacAddress"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The maximum WorldWidePortName address for dynamically generated WorldWideName add" + - "resses used for Synthetic HBAs.\nThis is a read-only property, but it can be chan" + - "ged using the ModifyServiceSettings method of the Msvm_VirtualSystemManagementSe" + - "rvice class.")] - public string MaximumWWPNAddress { - get { - return ((string)(curObj["MaximumWWPNAddress"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The minimum MAC address for dynamically generated MAC addresses.\nThis is a read-o" + - "nly property, but it can be changed using the ModifyServiceSettings method of th" + - "e Msvm_VirtualSystemManagementService class.")] - public string MinimumMacAddress { - get { - return ((string)(curObj["MinimumMacAddress"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The minimum WorldWidePortName address for dynamically generated WorldWideName add" + - "resses used for Synthetic HBAs.\nThis is a read-only property, but it can be chan" + - "ged using the ModifyServiceSettings method of the Msvm_VirtualSystemManagementSe" + - "rvice class.")] - public string MinimumWWPNAddress { - get { - return ((string)(curObj["MinimumWWPNAddress"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsNumaSpanningEnabledNull { - get { - if ((curObj["NumaSpanningEnabled"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("Reserved for future use.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool NumaSpanningEnabled { - get { - if ((curObj["NumaSpanningEnabled"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["NumaSpanningEnabled"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("Controls memory allocation for the VMs on non-uniform memory access (NUMA) system" + - "s.\nThis is a read-only property, but it can be changed using the ModifyServiceSe" + - "ttings method of the Msvm_VirtualSystemManagementService class.")] - public string PrimaryOwnerContact { - get { - return ((string)(curObj["PrimaryOwnerContact"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description(@"Describes how the primary system owner can be reached (for example, phone number or e-mail address). By default, empty. This name may not exceed 256 characters in length. -This is a read-only property, but it can be changed using the ModifyServiceSettings method of the Msvm_VirtualSystemManagementService class.")] - public string PrimaryOwnerName { - get { - return ((string)(curObj["PrimaryOwnerName"])); - } - } - - private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { - if (((path != null) - && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); - } - } - - private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { - if (((theObj != null) - && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); - if ((parentClasses != null)) { - int count = 0; - for (count = 0; (count < parentClasses.Length); count = (count + 1)) { - if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { - return true; - } - } - } - } - return false; - } - - private bool ShouldSerializeHbaLunTimeout() { - if ((this.IsHbaLunTimeoutNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeNumaSpanningEnabled() { - if ((this.IsNumaSpanningEnabledNull == false)) { - return true; - } - return false; - } - - [Browsable(true)] - public void CommitObject() { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(); - } - } - - [Browsable(true)] - public void CommitObject(System.Management.PutOptions putOptions) { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(putOptions); - } - } - - private void Initialize() { - AutoCommitProp = true; - isEmbedded = false; - } - - private static string ConstructPath(string keyInstanceID) { - string strPath = "ROOT\\virtualization\\v2:Msvm_VirtualSystemManagementServiceSettingData"; - strPath = string.Concat(strPath, string.Concat(".InstanceID=", string.Concat("\"", string.Concat(keyInstanceID, "\"")))); - return strPath; - } - - private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - Initialize(); - if ((path != null)) { - if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - } - PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - - // Different overloads of GetInstances() help in enumerating instances of the WMI class. - public static VirtualSystemManagementServiceSettingDataCollection GetInstances() { - return GetInstances(null, null, null); - } - - public static VirtualSystemManagementServiceSettingDataCollection GetInstances(string condition) { - return GetInstances(null, condition, null); - } - - public static VirtualSystemManagementServiceSettingDataCollection GetInstances(string[] selectedProperties) { - return GetInstances(null, null, selectedProperties); - } - - public static VirtualSystemManagementServiceSettingDataCollection GetInstances(string condition, string[] selectedProperties) { - return GetInstances(null, condition, selectedProperties); - } - - public static VirtualSystemManagementServiceSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); - pathObj.ClassName = "Msvm_VirtualSystemManagementServiceSettingData"; - pathObj.NamespacePath = "root\\virtualization\\v2"; - System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); - if ((enumOptions == null)) { - enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - } - return new VirtualSystemManagementServiceSettingDataCollection(clsObject.GetInstances(enumOptions)); - } - - public static VirtualSystemManagementServiceSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { - return GetInstances(mgmtScope, condition, null); - } - - public static VirtualSystemManagementServiceSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { - return GetInstances(mgmtScope, null, selectedProperties); - } - - public static VirtualSystemManagementServiceSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_VirtualSystemManagementServiceSettingData", condition, selectedProperties)); - System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - ObjectSearcher.Options = enumOptions; - return new VirtualSystemManagementServiceSettingDataCollection(ObjectSearcher.Get()); - } - - [Browsable(true)] - public static VirtualSystemManagementServiceSettingData CreateInstance() { - System.Management.ManagementScope mgmtScope = null; - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = CreatedWmiNamespace; - } - else { - mgmtScope = statMgmtScope; - } - System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); - System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); - return new VirtualSystemManagementServiceSettingData(tmpMgmtClass.CreateInstance()); - } - - [Browsable(true)] - public void Delete() { - PrivateLateBoundObject.Delete(); - } - - // Enumerator implementation for enumerating instances of the class. - public class VirtualSystemManagementServiceSettingDataCollection : object, ICollection { - - private ManagementObjectCollection privColObj; - - public VirtualSystemManagementServiceSettingDataCollection(ManagementObjectCollection objCollection) { - privColObj = objCollection; - } - - public virtual int Count { - get { - return privColObj.Count; - } - } - - public virtual bool IsSynchronized { - get { - return privColObj.IsSynchronized; - } - } - - public virtual object SyncRoot { - get { - return this; - } - } - - public virtual void CopyTo(System.Array array, int index) { - privColObj.CopyTo(array, index); - int nCtr; - for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { - array.SetValue(new VirtualSystemManagementServiceSettingData(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); - } - } - - public virtual System.Collections.IEnumerator GetEnumerator() { - return new VirtualSystemManagementServiceSettingDataEnumerator(privColObj.GetEnumerator()); - } - - public class VirtualSystemManagementServiceSettingDataEnumerator : object, System.Collections.IEnumerator { - - private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; - - public VirtualSystemManagementServiceSettingDataEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { - privObjEnum = objEnum; - } - - public virtual object Current { - get { - return new VirtualSystemManagementServiceSettingData(((System.Management.ManagementObject)(privObjEnum.Current))); - } - } - - public virtual bool MoveNext() { - return privObjEnum.MoveNext(); - } - - public virtual void Reset() { - privObjEnum.Reset(); - } - } - } - - // TypeConverter to handle null values for ValueType properties - public class WMIValueTypeConverter : TypeConverter { - - private TypeConverter baseConverter; - - private System.Type baseType; - - public WMIValueTypeConverter(System.Type inBaseType) { - baseConverter = TypeDescriptor.GetConverter(inBaseType); - baseType = inBaseType; - } - - public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { - return baseConverter.CanConvertFrom(context, srcType); - } - - public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { - return baseConverter.CanConvertTo(context, destinationType); - } - - public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { - return baseConverter.ConvertFrom(context, culture, value); - } - - public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { - return baseConverter.CreateInstance(context, dictionary); - } - - public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetCreateInstanceSupported(context); - } - - public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { - return baseConverter.GetProperties(context, value, attributeVar); - } - - public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetPropertiesSupported(context); - } - - public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValues(context); - } - - public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesExclusive(context); - } - - public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesSupported(context); - } - - public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { - if ((baseType.BaseType == typeof(System.Enum))) { - if ((value.GetType() == destinationType)) { - return value; - } - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return "NULL_ENUM_VALUE" ; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((baseType == typeof(bool)) - && (baseType.BaseType == typeof(System.ValueType)))) { - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((context != null) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - } - - // Embedded class to represent WMI system Properties. - [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] - public class ManagementSystemProperties { - - private System.Management.ManagementBaseObject PrivateLateBoundObject; - - public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { - PrivateLateBoundObject = ManagedObject; - } - - [Browsable(true)] - public int GENUS { - get { - return ((int)(PrivateLateBoundObject["__GENUS"])); - } - } - - [Browsable(true)] - public string CLASS { - get { - return ((string)(PrivateLateBoundObject["__CLASS"])); - } - } - - [Browsable(true)] - public string SUPERCLASS { - get { - return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); - } - } - - [Browsable(true)] - public string DYNASTY { - get { - return ((string)(PrivateLateBoundObject["__DYNASTY"])); - } - } - - [Browsable(true)] - public string RELPATH { - get { - return ((string)(PrivateLateBoundObject["__RELPATH"])); - } - } - - [Browsable(true)] - public int PROPERTY_COUNT { - get { - return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); - } - } - - [Browsable(true)] - public string[] DERIVATION { - get { - return ((string[])(PrivateLateBoundObject["__DERIVATION"])); - } - } - - [Browsable(true)] - public string SERVER { - get { - return ((string)(PrivateLateBoundObject["__SERVER"])); - } - } - - [Browsable(true)] - public string NAMESPACE { - get { - return ((string)(PrivateLateBoundObject["__NAMESPACE"])); - } - } - - [Browsable(true)] - public string PATH { - get { - return ((string)(PrivateLateBoundObject["__PATH"])); - } - } - } - } -} +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2 +{ + using System; + using System.ComponentModel; + using System.Management; + using System.Collections; + using System.Globalization; + using System.ComponentModel.Design.Serialization; + using System.Reflection; + + + // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. + // Functions IsNull() are used to check if a property is NULL. + // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. + // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. + // An Early Bound class generated for the WMI class.Msvm_VirtualSystemManagementServiceSettingData + public class VirtualSystemManagementServiceSettingData : System.ComponentModel.Component { + + // Private property to hold the WMI namespace in which the class resides. + private static string CreatedWmiNamespace = "ROOT\\virtualization\\v2"; + + // Private property to hold the name of WMI class which created this class. + public static string CreatedClassName = "Msvm_VirtualSystemManagementServiceSettingData"; + + // Private member variable to hold the ManagementScope which is used by the various methods. + private static System.Management.ManagementScope statMgmtScope = null; + + private ManagementSystemProperties PrivateSystemProperties; + + // Underlying lateBound WMI object. + private System.Management.ManagementObject PrivateLateBoundObject; + + // Member variable to store the 'automatic commit' behavior for the class. + private bool AutoCommitProp; + + // Private variable to hold the embedded property representing the instance. + private System.Management.ManagementBaseObject embeddedObj; + + // The current WMI object used + private System.Management.ManagementBaseObject curObj; + + // Flag to indicate if the instance is an embedded object. + private bool isEmbedded; + + // Below are different overloads of constructors to initialize an instance of the class with a WMI object. + public VirtualSystemManagementServiceSettingData() { + this.InitializeObject(null, null, null); + } + + public VirtualSystemManagementServiceSettingData(string keyInstanceID) { + this.InitializeObject(null, new System.Management.ManagementPath(VirtualSystemManagementServiceSettingData.ConstructPath(keyInstanceID)), null); + } + + public VirtualSystemManagementServiceSettingData(System.Management.ManagementScope mgmtScope, string keyInstanceID) { + this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(VirtualSystemManagementServiceSettingData.ConstructPath(keyInstanceID)), null); + } + + public VirtualSystemManagementServiceSettingData(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(null, path, getOptions); + } + + public VirtualSystemManagementServiceSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { + this.InitializeObject(mgmtScope, path, null); + } + + public VirtualSystemManagementServiceSettingData(System.Management.ManagementPath path) { + this.InitializeObject(null, path, null); + } + + public VirtualSystemManagementServiceSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(mgmtScope, path, getOptions); + } + + public VirtualSystemManagementServiceSettingData(System.Management.ManagementObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + PrivateLateBoundObject = theObject; + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + public VirtualSystemManagementServiceSettingData(System.Management.ManagementBaseObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + embeddedObj = theObject; + PrivateSystemProperties = new ManagementSystemProperties(theObject); + curObj = embeddedObj; + isEmbedded = true; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + // Property returns the namespace of the WMI class. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OriginatingNamespace { + get { + return "ROOT\\virtualization\\v2"; + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ManagementClassName { + get { + string strRet = CreatedClassName; + if ((curObj != null)) { + if ((curObj.ClassPath != null)) { + strRet = ((string)(curObj["__CLASS"])); + if (((strRet == null) + || (strRet == string.Empty))) { + strRet = CreatedClassName; + } + } + } + return strRet; + } + } + + // Property pointing to an embedded object to get System properties of the WMI object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ManagementSystemProperties SystemProperties { + get { + return PrivateSystemProperties; + } + } + + // Property returning the underlying lateBound object. + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementBaseObject LateBoundObject { + get { + return curObj; + } + } + + // ManagementScope of the object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementScope Scope { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Scope; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Scope = value; + } + } + } + + // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool AutoCommit { + get { + return AutoCommitProp; + } + set { + AutoCommitProp = value; + } + } + + // The ManagementPath of the underlying WMI object. + [Browsable(true)] + public System.Management.ManagementPath Path { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Path; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + if ((CheckIfProperClass(null, value, null) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + PrivateLateBoundObject.Path = value; + } + } + } + + // Public static scope property which is used by the various methods. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public static System.Management.ManagementScope StaticScope { + get { + return statMgmtScope; + } + set { + statMgmtScope = value; + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"Used by OEMs to allow BIOS-locked Windows operating systems to run in the virtual machine. This string must be exactly 32 characters in length. +This is a read-only property, but it can be changed using the ModifyServiceSettings method of the Msvm_VirtualSystemManagementService class.")] + public string BiosLockString { + get { + return ((string)(curObj["BiosLockString"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Caption { + get { + return ((string)(curObj["Caption"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The WorldWideNodeName address for dynamically generated WorldWideName addresses u" + + "sed for Synthetic HBAs.\nThis is a read-only property, but it can be changed usin" + + "g the ModifyServiceSettings method of the Msvm_VirtualSystemManagementService cl" + + "ass.")] + public string CurrentWWNNAddress { + get { + return ((string)(curObj["CurrentWWNNAddress"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The default external data root. By default, \"root\\ProgramData\\Microsoft\\Windows\\V" + + "irtualization\".\nThis is a read-only property, but it can be changed using the Mo" + + "difyServiceSettings method of the Msvm_VirtualSystemManagementService class.")] + public string DefaultExternalDataRoot { + get { + return ((string)(curObj["DefaultExternalDataRoot"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The default virtual hard disk path. By default, \"root\\Users\\Public\\Documents\\Virt" + + "ual Hard Disks\".\nThis is a read-only property, but it can be changed using the M" + + "odifyServiceSettings method of the Msvm_VirtualSystemManagementService class.")] + public string DefaultVirtualHardDiskPath { + get { + return ((string)(curObj["DefaultVirtualHardDiskPath"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Description { + get { + return ((string)(curObj["Description"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ElementName { + get { + return ((string)(curObj["ElementName"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsHbaLunTimeoutNull { + get { + if ((curObj["HbaLunTimeout"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"This property describes the amount of time that the Synthetic FC virtual device will wait for a LUN to appear before starting a virtual machine. +This is a read-only property, but it can be changed using the ModifyServiceSettings method of the Msvm_VirtualSystemManagementService class.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint HbaLunTimeout { + get { + if ((curObj["HbaLunTimeout"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["HbaLunTimeout"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string InstanceID { + get { + return ((string)(curObj["InstanceID"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The maximum MAC address for dynamically generated MAC addresses.\nThis is a read-o" + + "nly property, but it can be changed using the ModifyServiceSettings method of th" + + "e Msvm_VirtualSystemManagementService class.")] + public string MaximumMacAddress { + get { + return ((string)(curObj["MaximumMacAddress"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The maximum WorldWidePortName address for dynamically generated WorldWideName add" + + "resses used for Synthetic HBAs.\nThis is a read-only property, but it can be chan" + + "ged using the ModifyServiceSettings method of the Msvm_VirtualSystemManagementSe" + + "rvice class.")] + public string MaximumWWPNAddress { + get { + return ((string)(curObj["MaximumWWPNAddress"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The minimum MAC address for dynamically generated MAC addresses.\nThis is a read-o" + + "nly property, but it can be changed using the ModifyServiceSettings method of th" + + "e Msvm_VirtualSystemManagementService class.")] + public string MinimumMacAddress { + get { + return ((string)(curObj["MinimumMacAddress"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The minimum WorldWidePortName address for dynamically generated WorldWideName add" + + "resses used for Synthetic HBAs.\nThis is a read-only property, but it can be chan" + + "ged using the ModifyServiceSettings method of the Msvm_VirtualSystemManagementSe" + + "rvice class.")] + public string MinimumWWPNAddress { + get { + return ((string)(curObj["MinimumWWPNAddress"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsNumaSpanningEnabledNull { + get { + if ((curObj["NumaSpanningEnabled"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Reserved for future use.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool NumaSpanningEnabled { + get { + if ((curObj["NumaSpanningEnabled"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["NumaSpanningEnabled"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Controls memory allocation for the VMs on non-uniform memory access (NUMA) system" + + "s.\nThis is a read-only property, but it can be changed using the ModifyServiceSe" + + "ttings method of the Msvm_VirtualSystemManagementService class.")] + public string PrimaryOwnerContact { + get { + return ((string)(curObj["PrimaryOwnerContact"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description(@"Describes how the primary system owner can be reached (for example, phone number or e-mail address). By default, empty. This name may not exceed 256 characters in length. +This is a read-only property, but it can be changed using the ModifyServiceSettings method of the Msvm_VirtualSystemManagementService class.")] + public string PrimaryOwnerName { + get { + return ((string)(curObj["PrimaryOwnerName"])); + } + } + + private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { + if (((path != null) + && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); + } + } + + private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { + if (((theObj != null) + && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); + if ((parentClasses != null)) { + int count = 0; + for (count = 0; (count < parentClasses.Length); count = (count + 1)) { + if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { + return true; + } + } + } + } + return false; + } + + private bool ShouldSerializeHbaLunTimeout() { + if ((this.IsHbaLunTimeoutNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeNumaSpanningEnabled() { + if ((this.IsNumaSpanningEnabledNull == false)) { + return true; + } + return false; + } + + [Browsable(true)] + public void CommitObject() { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(); + } + } + + [Browsable(true)] + public void CommitObject(System.Management.PutOptions putOptions) { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(putOptions); + } + } + + private void Initialize() { + AutoCommitProp = true; + isEmbedded = false; + } + + private static string ConstructPath(string keyInstanceID) { + string strPath = "ROOT\\virtualization\\v2:Msvm_VirtualSystemManagementServiceSettingData"; + strPath = string.Concat(strPath, string.Concat(".InstanceID=", string.Concat("\"", string.Concat(keyInstanceID, "\"")))); + return strPath; + } + + private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + Initialize(); + if ((path != null)) { + if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + } + PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + + // Different overloads of GetInstances() help in enumerating instances of the WMI class. + public static VirtualSystemManagementServiceSettingDataCollection GetInstances() { + return GetInstances(null, null, null); + } + + public static VirtualSystemManagementServiceSettingDataCollection GetInstances(string condition) { + return GetInstances(null, condition, null); + } + + public static VirtualSystemManagementServiceSettingDataCollection GetInstances(string[] selectedProperties) { + return GetInstances(null, null, selectedProperties); + } + + public static VirtualSystemManagementServiceSettingDataCollection GetInstances(string condition, string[] selectedProperties) { + return GetInstances(null, condition, selectedProperties); + } + + public static VirtualSystemManagementServiceSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); + pathObj.ClassName = "Msvm_VirtualSystemManagementServiceSettingData"; + pathObj.NamespacePath = "root\\virtualization\\v2"; + System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); + if ((enumOptions == null)) { + enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + } + return new VirtualSystemManagementServiceSettingDataCollection(clsObject.GetInstances(enumOptions)); + } + + public static VirtualSystemManagementServiceSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { + return GetInstances(mgmtScope, condition, null); + } + + public static VirtualSystemManagementServiceSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { + return GetInstances(mgmtScope, null, selectedProperties); + } + + public static VirtualSystemManagementServiceSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_VirtualSystemManagementServiceSettingData", condition, selectedProperties)); + System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + ObjectSearcher.Options = enumOptions; + return new VirtualSystemManagementServiceSettingDataCollection(ObjectSearcher.Get()); + } + + [Browsable(true)] + public static VirtualSystemManagementServiceSettingData CreateInstance() { + System.Management.ManagementScope mgmtScope = null; + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = CreatedWmiNamespace; + } + else { + mgmtScope = statMgmtScope; + } + System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); + System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); + return new VirtualSystemManagementServiceSettingData(tmpMgmtClass.CreateInstance()); + } + + [Browsable(true)] + public void Delete() { + PrivateLateBoundObject.Delete(); + } + + // Enumerator implementation for enumerating instances of the class. + public class VirtualSystemManagementServiceSettingDataCollection : object, ICollection { + + private ManagementObjectCollection privColObj; + + public VirtualSystemManagementServiceSettingDataCollection(ManagementObjectCollection objCollection) { + privColObj = objCollection; + } + + public virtual int Count { + get { + return privColObj.Count; + } + } + + public virtual bool IsSynchronized { + get { + return privColObj.IsSynchronized; + } + } + + public virtual object SyncRoot { + get { + return this; + } + } + + public virtual void CopyTo(System.Array array, int index) { + privColObj.CopyTo(array, index); + int nCtr; + for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { + array.SetValue(new VirtualSystemManagementServiceSettingData(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); + } + } + + public virtual System.Collections.IEnumerator GetEnumerator() { + return new VirtualSystemManagementServiceSettingDataEnumerator(privColObj.GetEnumerator()); + } + + public class VirtualSystemManagementServiceSettingDataEnumerator : object, System.Collections.IEnumerator { + + private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; + + public VirtualSystemManagementServiceSettingDataEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { + privObjEnum = objEnum; + } + + public virtual object Current { + get { + return new VirtualSystemManagementServiceSettingData(((System.Management.ManagementObject)(privObjEnum.Current))); + } + } + + public virtual bool MoveNext() { + return privObjEnum.MoveNext(); + } + + public virtual void Reset() { + privObjEnum.Reset(); + } + } + } + + // TypeConverter to handle null values for ValueType properties + public class WMIValueTypeConverter : TypeConverter { + + private TypeConverter baseConverter; + + private System.Type baseType; + + public WMIValueTypeConverter(System.Type inBaseType) { + baseConverter = TypeDescriptor.GetConverter(inBaseType); + baseType = inBaseType; + } + + public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { + return baseConverter.CanConvertFrom(context, srcType); + } + + public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { + return baseConverter.CanConvertTo(context, destinationType); + } + + public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { + return baseConverter.ConvertFrom(context, culture, value); + } + + public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { + return baseConverter.CreateInstance(context, dictionary); + } + + public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetCreateInstanceSupported(context); + } + + public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { + return baseConverter.GetProperties(context, value, attributeVar); + } + + public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetPropertiesSupported(context); + } + + public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValues(context); + } + + public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesExclusive(context); + } + + public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesSupported(context); + } + + public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { + if ((baseType.BaseType == typeof(System.Enum))) { + if ((value.GetType() == destinationType)) { + return value; + } + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return "NULL_ENUM_VALUE" ; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((baseType == typeof(bool)) + && (baseType.BaseType == typeof(System.ValueType)))) { + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((context != null) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + } + + // Embedded class to represent WMI system Properties. + [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] + public class ManagementSystemProperties { + + private System.Management.ManagementBaseObject PrivateLateBoundObject; + + public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { + PrivateLateBoundObject = ManagedObject; + } + + [Browsable(true)] + public int GENUS { + get { + return ((int)(PrivateLateBoundObject["__GENUS"])); + } + } + + [Browsable(true)] + public string CLASS { + get { + return ((string)(PrivateLateBoundObject["__CLASS"])); + } + } + + [Browsable(true)] + public string SUPERCLASS { + get { + return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); + } + } + + [Browsable(true)] + public string DYNASTY { + get { + return ((string)(PrivateLateBoundObject["__DYNASTY"])); + } + } + + [Browsable(true)] + public string RELPATH { + get { + return ((string)(PrivateLateBoundObject["__RELPATH"])); + } + } + + [Browsable(true)] + public int PROPERTY_COUNT { + get { + return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); + } + } + + [Browsable(true)] + public string[] DERIVATION { + get { + return ((string[])(PrivateLateBoundObject["__DERIVATION"])); + } + } + + [Browsable(true)] + public string SERVER { + get { + return ((string)(PrivateLateBoundObject["__SERVER"])); + } + } + + [Browsable(true)] + public string NAMESPACE { + get { + return ((string)(PrivateLateBoundObject["__NAMESPACE"])); + } + } + + [Browsable(true)] + public string PATH { + get { + return ((string)(PrivateLateBoundObject["__PATH"])); + } + } + } + } +} diff --git a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_VirtualSystemSettingData.cs b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_VirtualSystemSettingData.cs index 85babfee2eb..1dab7d0f811 100644 --- a/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_VirtualSystemSettingData.cs +++ b/plugins/hypervisors/hyperv/DotNet/ServerResource/WmiWrappers/ROOT.virtualization.v2.Msvm_VirtualSystemSettingData.cs @@ -15,517 +15,517 @@ // specific language governing permissions and limitations // under the License. -namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2 { - using System; - using System.ComponentModel; - using System.Management; - using System.Collections; - using System.Globalization; - using System.ComponentModel.Design.Serialization; - using System.Reflection; - - - // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. - // Functions IsNull() are used to check if a property is NULL. - // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. - // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. - // Datetime conversion functions ToDateTime and ToDmtfDateTime are added to the class to convert DMTF datetime to System.DateTime and vice-versa. - // An Early Bound class generated for the WMI class.Msvm_VirtualSystemSettingData - public class VirtualSystemSettingData : System.ComponentModel.Component { - - // Private property to hold the WMI namespace in which the class resides. - private static string CreatedWmiNamespace = "ROOT\\virtualization\\v2"; - - // Private property to hold the name of WMI class which created this class. - public static string CreatedClassName = "Msvm_VirtualSystemSettingData"; - - // Private member variable to hold the ManagementScope which is used by the various methods. - private static System.Management.ManagementScope statMgmtScope = null; - - private ManagementSystemProperties PrivateSystemProperties; - - // Underlying lateBound WMI object. - private System.Management.ManagementObject PrivateLateBoundObject; - - // Member variable to store the 'automatic commit' behavior for the class. - private bool AutoCommitProp; - - // Private variable to hold the embedded property representing the instance. - private System.Management.ManagementBaseObject embeddedObj; - - // The current WMI object used - private System.Management.ManagementBaseObject curObj; - - // Flag to indicate if the instance is an embedded object. - private bool isEmbedded; - - // Below are different overloads of constructors to initialize an instance of the class with a WMI object. - public VirtualSystemSettingData() { - this.InitializeObject(null, null, null); - } - - public VirtualSystemSettingData(string keyInstanceID) { - this.InitializeObject(null, new System.Management.ManagementPath(VirtualSystemSettingData.ConstructPath(keyInstanceID)), null); - } - - public VirtualSystemSettingData(System.Management.ManagementScope mgmtScope, string keyInstanceID) { - this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(VirtualSystemSettingData.ConstructPath(keyInstanceID)), null); - } - - public VirtualSystemSettingData(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(null, path, getOptions); - } - - public VirtualSystemSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { - this.InitializeObject(mgmtScope, path, null); - } - - public VirtualSystemSettingData(System.Management.ManagementPath path) { - this.InitializeObject(null, path, null); - } - - public VirtualSystemSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - this.InitializeObject(mgmtScope, path, getOptions); - } - - public VirtualSystemSettingData(System.Management.ManagementObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - PrivateLateBoundObject = theObject; - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - public VirtualSystemSettingData(System.Management.ManagementBaseObject theObject) { - Initialize(); - if ((CheckIfProperClass(theObject) == true)) { - embeddedObj = theObject; - PrivateSystemProperties = new ManagementSystemProperties(theObject); - curObj = embeddedObj; - isEmbedded = true; - } - else { - throw new System.ArgumentException("Class name does not match."); - } - } - - // Property returns the namespace of the WMI class. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string OriginatingNamespace { - get { - return "ROOT\\virtualization\\v2"; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ManagementClassName { - get { - string strRet = CreatedClassName; - if ((curObj != null)) { - if ((curObj.ClassPath != null)) { - strRet = ((string)(curObj["__CLASS"])); - if (((strRet == null) - || (strRet == string.Empty))) { - strRet = CreatedClassName; - } - } - } - return strRet; - } - } - - // Property pointing to an embedded object to get System properties of the WMI object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public ManagementSystemProperties SystemProperties { - get { - return PrivateSystemProperties; - } - } - - // Property returning the underlying lateBound object. - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementBaseObject LateBoundObject { - get { - return curObj; - } - } - - // ManagementScope of the object. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public System.Management.ManagementScope Scope { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Scope; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Scope = value; - } - } - } - - // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool AutoCommit { - get { - return AutoCommitProp; - } - set { - AutoCommitProp = value; - } - } - - // The ManagementPath of the underlying WMI object. - [Browsable(true)] - public System.Management.ManagementPath Path { - get { - if ((isEmbedded == false)) { - return PrivateLateBoundObject.Path; - } - else { - return null; - } - } - set { - if ((isEmbedded == false)) { - if ((CheckIfProperClass(null, value, null) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - PrivateLateBoundObject.Path = value; - } - } - } - - // Public static scope property which is used by the various methods. - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public static System.Management.ManagementScope StaticScope { - get { - return statMgmtScope; - } - set { - statMgmtScope = value; - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] +namespace CloudStack.Plugin.WmiWrappers.ROOT.VIRTUALIZATION.V2 { + using System; + using System.ComponentModel; + using System.Management; + using System.Collections; + using System.Globalization; + using System.ComponentModel.Design.Serialization; + using System.Reflection; + + + // Functions ShouldSerialize are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use IsNull function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. + // Functions IsNull() are used to check if a property is NULL. + // Functions Reset are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. + // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. + // Datetime conversion functions ToDateTime and ToDmtfDateTime are added to the class to convert DMTF datetime to System.DateTime and vice-versa. + // An Early Bound class generated for the WMI class.Msvm_VirtualSystemSettingData + public class VirtualSystemSettingData : System.ComponentModel.Component { + + // Private property to hold the WMI namespace in which the class resides. + private static string CreatedWmiNamespace = "ROOT\\virtualization\\v2"; + + // Private property to hold the name of WMI class which created this class. + public static string CreatedClassName = "Msvm_VirtualSystemSettingData"; + + // Private member variable to hold the ManagementScope which is used by the various methods. + private static System.Management.ManagementScope statMgmtScope = null; + + private ManagementSystemProperties PrivateSystemProperties; + + // Underlying lateBound WMI object. + private System.Management.ManagementObject PrivateLateBoundObject; + + // Member variable to store the 'automatic commit' behavior for the class. + private bool AutoCommitProp; + + // Private variable to hold the embedded property representing the instance. + private System.Management.ManagementBaseObject embeddedObj; + + // The current WMI object used + private System.Management.ManagementBaseObject curObj; + + // Flag to indicate if the instance is an embedded object. + private bool isEmbedded; + + // Below are different overloads of constructors to initialize an instance of the class with a WMI object. + public VirtualSystemSettingData() { + this.InitializeObject(null, null, null); + } + + public VirtualSystemSettingData(string keyInstanceID) { + this.InitializeObject(null, new System.Management.ManagementPath(VirtualSystemSettingData.ConstructPath(keyInstanceID)), null); + } + + public VirtualSystemSettingData(System.Management.ManagementScope mgmtScope, string keyInstanceID) { + this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(VirtualSystemSettingData.ConstructPath(keyInstanceID)), null); + } + + public VirtualSystemSettingData(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(null, path, getOptions); + } + + public VirtualSystemSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { + this.InitializeObject(mgmtScope, path, null); + } + + public VirtualSystemSettingData(System.Management.ManagementPath path) { + this.InitializeObject(null, path, null); + } + + public VirtualSystemSettingData(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + this.InitializeObject(mgmtScope, path, getOptions); + } + + public VirtualSystemSettingData(System.Management.ManagementObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + PrivateLateBoundObject = theObject; + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + public VirtualSystemSettingData(System.Management.ManagementBaseObject theObject) { + Initialize(); + if ((CheckIfProperClass(theObject) == true)) { + embeddedObj = theObject; + PrivateSystemProperties = new ManagementSystemProperties(theObject); + curObj = embeddedObj; + isEmbedded = true; + } + else { + throw new System.ArgumentException("Class name does not match."); + } + } + + // Property returns the namespace of the WMI class. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string OriginatingNamespace { + get { + return "ROOT\\virtualization\\v2"; + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ManagementClassName { + get { + string strRet = CreatedClassName; + if ((curObj != null)) { + if ((curObj.ClassPath != null)) { + strRet = ((string)(curObj["__CLASS"])); + if (((strRet == null) + || (strRet == string.Empty))) { + strRet = CreatedClassName; + } + } + } + return strRet; + } + } + + // Property pointing to an embedded object to get System properties of the WMI object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public ManagementSystemProperties SystemProperties { + get { + return PrivateSystemProperties; + } + } + + // Property returning the underlying lateBound object. + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementBaseObject LateBoundObject { + get { + return curObj; + } + } + + // ManagementScope of the object. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public System.Management.ManagementScope Scope { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Scope; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Scope = value; + } + } + } + + // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool AutoCommit { + get { + return AutoCommitProp; + } + set { + AutoCommitProp = value; + } + } + + // The ManagementPath of the underlying WMI object. + [Browsable(true)] + public System.Management.ManagementPath Path { + get { + if ((isEmbedded == false)) { + return PrivateLateBoundObject.Path; + } + else { + return null; + } + } + set { + if ((isEmbedded == false)) { + if ((CheckIfProperClass(null, value, null) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + PrivateLateBoundObject.Path = value; + } + } + } + + // Public static scope property which is used by the various methods. + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public static System.Management.ManagementScope StaticScope { + get { + return statMgmtScope; + } + set { + statMgmtScope = value; + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [Description(@"Any additional information provided to the recovery action. The meaning of this property is defined by the action in AutomaticRecoveryAction. If AutomaticRecoveryAction is 0 (""None"") or 1 (""Restart""), this value is NULL. If AutomaticRecoveryAction is 2 (""Revert to Snapshot""), this is the object path to a snapshot that should be applied on failure of the virtual machine worker process. -This is a read-only property, but it can be changed using the ModifyVirtualSystem method of the Msvm_VirtualSystemManagementService class.")] - public string AdditionalRecoveryInformation { - get { - return ((string)(curObj["AdditionalRecoveryInformation"])); - } - set { - curObj["AdditionalRecoveryInformation"] = value; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsAllowFullSCSICommandSetNull { - get { - if ((curObj["AllowFullSCSICommandSet"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] +This is a read-only property, but it can be changed using the ModifyVirtualSystem method of the Msvm_VirtualSystemManagementService class.")] + public string AdditionalRecoveryInformation { + get { + return ((string)(curObj["AdditionalRecoveryInformation"])); + } + set { + curObj["AdditionalRecoveryInformation"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAllowFullSCSICommandSetNull { + get { + if ((curObj["AllowFullSCSICommandSet"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [Description(@"Indicates whether SCSI commands from the guest operating system are passed to pass-through disks. If TRUE, SCSI commands emitted by the guest operating system to pass-through disks are not filtered.It is recommended that SCSI filtering remains enabled for production deployments. This is a read-only property, but it can be changed using the ModifyVirtualSystem method of the Msvm_VirtualSystemManagementService class. -Windows Server 2008: The AllowFullSCSICommandSet property is not supported.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool AllowFullSCSICommandSet { - get { - if ((curObj["AllowFullSCSICommandSet"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["AllowFullSCSICommandSet"])); - } - set { - curObj["AllowFullSCSICommandSet"] = value; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsAllowReducedFcRedundancyNull { - get { - if ((curObj["AllowReducedFcRedundancy"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] +Windows Server 2008: The AllowFullSCSICommandSet property is not supported.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool AllowFullSCSICommandSet { + get { + if ((curObj["AllowFullSCSICommandSet"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["AllowFullSCSICommandSet"])); + } + set { + curObj["AllowFullSCSICommandSet"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAllowReducedFcRedundancyNull { + get { + if ((curObj["AllowReducedFcRedundancy"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [Description(@"Indicates whether live migration of a virtual machine that is configured with a virtual FC adapter is allowed to a destination machine, without doing any checks for the existence of paths to the storage devices on the destination The default value of this property is FALSE. If set to TRUE, the VM can be live migrated to a target machine which may have no or reduced paths to the target FC devices. The guest operating system may lose connectivity to storage and may behave in an unpredictable manner. - This property should be cleared after a live migration")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool AllowReducedFcRedundancy { - get { - if ((curObj["AllowReducedFcRedundancy"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["AllowReducedFcRedundancy"])); - } - set { - curObj["AllowReducedFcRedundancy"] = value; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsAutomaticRecoveryActionNull { - get { - if ((curObj["AutomaticRecoveryAction"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort AutomaticRecoveryAction { - get { - if ((curObj["AutomaticRecoveryAction"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["AutomaticRecoveryAction"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsAutomaticShutdownActionNull { - get { - if ((curObj["AutomaticShutdownAction"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort AutomaticShutdownAction { - get { - if ((curObj["AutomaticShutdownAction"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["AutomaticShutdownAction"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsAutomaticStartupActionNull { - get { - if ((curObj["AutomaticStartupAction"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort AutomaticStartupAction { - get { - if ((curObj["AutomaticStartupAction"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["AutomaticStartupAction"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsAutomaticStartupActionDelayNull { - get { - if ((curObj["AutomaticStartupActionDelay"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public System.DateTime AutomaticStartupActionDelay { - get { - if ((curObj["AutomaticStartupActionDelay"] != null)) { - return ToDateTime(((string)(curObj["AutomaticStartupActionDelay"]))); - } - else { - return System.DateTime.MinValue; - } - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsAutomaticStartupActionSequenceNumberNull { - get { - if ((curObj["AutomaticStartupActionSequenceNumber"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public ushort AutomaticStartupActionSequenceNumber { - get { - if ((curObj["AutomaticStartupActionSequenceNumber"] == null)) { - return System.Convert.ToUInt16(0); - } - return ((ushort)(curObj["AutomaticStartupActionSequenceNumber"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The serial number of the base board for the virtual computer system.\nThis is a re" + - "ad-only property, but it can be changed using the ModifyVirtualSystem method of " + - "the Msvm_VirtualSystemManagementService class.")] - public string BaseBoardSerialNumber { - get { - return ((string)(curObj["BaseBoardSerialNumber"])); - } - set { - curObj["BaseBoardSerialNumber"] = value; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The globally-unique identifier for the BIOS of the virtual computer system.\nThis " + - "is a read-only property, but it can be changed using the ModifyVirtualSystem met" + - "hod of the Msvm_VirtualSystemManagementService class.")] - public string BIOSGUID { - get { - return ((string)(curObj["BIOSGUID"])); - } - set { - curObj["BIOSGUID"] = value; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsBIOSNumLockNull { - get { - if ((curObj["BIOSNumLock"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + This property should be cleared after a live migration")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool AllowReducedFcRedundancy { + get { + if ((curObj["AllowReducedFcRedundancy"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["AllowReducedFcRedundancy"])); + } + set { + curObj["AllowReducedFcRedundancy"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAutomaticRecoveryActionNull { + get { + if ((curObj["AutomaticRecoveryAction"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort AutomaticRecoveryAction { + get { + if ((curObj["AutomaticRecoveryAction"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["AutomaticRecoveryAction"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAutomaticShutdownActionNull { + get { + if ((curObj["AutomaticShutdownAction"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort AutomaticShutdownAction { + get { + if ((curObj["AutomaticShutdownAction"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["AutomaticShutdownAction"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAutomaticStartupActionNull { + get { + if ((curObj["AutomaticStartupAction"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort AutomaticStartupAction { + get { + if ((curObj["AutomaticStartupAction"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["AutomaticStartupAction"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAutomaticStartupActionDelayNull { + get { + if ((curObj["AutomaticStartupActionDelay"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime AutomaticStartupActionDelay { + get { + if ((curObj["AutomaticStartupActionDelay"] != null)) { + return ToDateTime(((string)(curObj["AutomaticStartupActionDelay"]))); + } + else { + return System.DateTime.MinValue; + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsAutomaticStartupActionSequenceNumberNull { + get { + if ((curObj["AutomaticStartupActionSequenceNumber"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public ushort AutomaticStartupActionSequenceNumber { + get { + if ((curObj["AutomaticStartupActionSequenceNumber"] == null)) { + return System.Convert.ToUInt16(0); + } + return ((ushort)(curObj["AutomaticStartupActionSequenceNumber"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The serial number of the base board for the virtual computer system.\nThis is a re" + + "ad-only property, but it can be changed using the ModifyVirtualSystem method of " + + "the Msvm_VirtualSystemManagementService class.")] + public string BaseBoardSerialNumber { + get { + return ((string)(curObj["BaseBoardSerialNumber"])); + } + set { + curObj["BaseBoardSerialNumber"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The globally-unique identifier for the BIOS of the virtual computer system.\nThis " + + "is a read-only property, but it can be changed using the ModifyVirtualSystem met" + + "hod of the Msvm_VirtualSystemManagementService class.")] + public string BIOSGUID { + get { + return ((string)(curObj["BIOSGUID"])); + } + set { + curObj["BIOSGUID"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsBIOSNumLockNull { + get { + if ((curObj["BIOSNumLock"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [Description(@"This property is set to TRUE if the num lock key is set to on by the BIOS, FALSE if the num lock key is set to off by the BIOS. -This is a read-only property, but it can be changed using the ModifyVirtualSystem method of the Msvm_VirtualSystemManagementService class.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool BIOSNumLock { - get { - if ((curObj["BIOSNumLock"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["BIOSNumLock"])); - } - set { - curObj["BIOSNumLock"] = value; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The serial number of the BIOS for the virtual computer system.\nThis is a read-onl" + - "y property, but it can be changed using the ModifyVirtualSystem method of the Ms" + - "vm_VirtualSystemManagementService class.")] - public string BIOSSerialNumber { - get { - return ((string)(curObj["BIOSSerialNumber"])); - } - set { - curObj["BIOSSerialNumber"] = value; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] +This is a read-only property, but it can be changed using the ModifyVirtualSystem method of the Msvm_VirtualSystemManagementService class.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool BIOSNumLock { + get { + if ((curObj["BIOSNumLock"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["BIOSNumLock"])); + } + set { + curObj["BIOSNumLock"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The serial number of the BIOS for the virtual computer system.\nThis is a read-onl" + + "y property, but it can be changed using the ModifyVirtualSystem method of the Ms" + + "vm_VirtualSystemManagementService class.")] + public string BIOSSerialNumber { + get { + return ((string)(curObj["BIOSSerialNumber"])); + } + set { + curObj["BIOSSerialNumber"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [Description(@"The boot order set within the BIOS of the virtual computer system. This property is an array of values, max length 4, where each value indicates a device to boot from. The virtual computer system will first attempt to boot from the device indicated by the first value within the array. If that device does not contain a boot sector, the virtual computer system will attempt to boot from the next device specified by the BootOrder property and so on. If no device specified within the BootOrder contains a boot sector the virtual computer system will fail to boot. The default value for a virtual computer system is [0, 1, 2, 3, 4]. Value definitions: 0 (Floppy): The virtual computer system will attempt to boot from the floppy disk within the floppy drive. @@ -534,1157 +534,1157 @@ Value definitions: 3 (PXE Boot): The virtual computer system will attempt to PXE boot from the network. 4 (SCSI Hard Drive): The virtual computer system will attempt to boot from the first hard drive found attached to a SCSI controller with a boot sector. 5-65535: Reserved -This is a read-only property, but it can be changed using the ModifyVirtualSystem method of the Msvm_VirtualSystemManagementService class.")] - public ushort[] BootOrder { - get { - return ((ushort[])(curObj["BootOrder"])); - } - set { - curObj["BootOrder"] = value; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Caption { - get { - return ((string)(curObj["Caption"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The asset tag of the chassis for the virtual computer system.\nThis is a read-only" + - " property, but it can be changed using the ModifyVirtualSystem method of the Msv" + - "m_VirtualSystemManagementService class.")] - public string ChassisAssetTag { - get { - return ((string)(curObj["ChassisAssetTag"])); - } - set { - curObj["ChassisAssetTag"] = value; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The serial number of the chassis for the virtual computer system.\nThis is a read-" + - "only property, but it can be changed using the ModifyVirtualSystem method of the" + - " Msvm_VirtualSystemManagementService class.")] - public string ChassisSerialNumber { - get { - return ((string)(curObj["ChassisSerialNumber"])); - } - set { - curObj["ChassisSerialNumber"] = value; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ConfigurationDataRoot { - get { - return ((string)(curObj["ConfigurationDataRoot"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ConfigurationFile { - get { - return ((string)(curObj["ConfigurationFile"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ConfigurationID { - get { - return ((string)(curObj["ConfigurationID"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsCreationTimeNull { - get { - if ((curObj["CreationTime"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [TypeConverter(typeof(WMIValueTypeConverter))] - public System.DateTime CreationTime { - get { - if ((curObj["CreationTime"] != null)) { - return ToDateTime(((string)(curObj["CreationTime"]))); - } - else { - return System.DateTime.MinValue; - } - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsDebugChannelIdNull { - get { - if ((curObj["DebugChannelId"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The channel identifier used to debug the virtual system using the VUD unified deb" + - "ugger.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public uint DebugChannelId { - get { - if ((curObj["DebugChannelId"] == null)) { - return System.Convert.ToUInt32(0); - } - return ((uint)(curObj["DebugChannelId"])); - } - set { - curObj["DebugChannelId"] = value; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsDebugPortNull { - get { - if ((curObj["DebugPort"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The tcpip port used to debug the virtual system using synthetic debugging.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public uint DebugPort { - get { - if ((curObj["DebugPort"] == null)) { - return System.Convert.ToUInt32(0); - } - return ((uint)(curObj["DebugPort"])); - } - set { - curObj["DebugPort"] = value; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsDebugPortEnabledNull { - get { - if ((curObj["DebugPortEnabled"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("Whether the virtual system is using synthetic debugging.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public DebugPortEnabledValues DebugPortEnabled { - get { - if ((curObj["DebugPortEnabled"] == null)) { - return ((DebugPortEnabledValues)(System.Convert.ToInt32(3))); - } - return ((DebugPortEnabledValues)(System.Convert.ToInt32(curObj["DebugPortEnabled"]))); - } - set { - if ((DebugPortEnabledValues.NULL_ENUM_VALUE == value)) { - curObj["DebugPortEnabled"] = null; - } - else { - curObj["DebugPortEnabled"] = value; - } - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string Description { - get { - return ((string)(curObj["Description"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string ElementName { - get { - return ((string)(curObj["ElementName"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsIncrementalBackupEnabledNull { - get { - if ((curObj["IncrementalBackupEnabled"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("Indicates whether the Hyper-V VSS writer supports taking incremental backup of th" + - "is Virtual machine.\nThis is a read-write property.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool IncrementalBackupEnabled { - get { - if ((curObj["IncrementalBackupEnabled"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["IncrementalBackupEnabled"])); - } - set { - curObj["IncrementalBackupEnabled"] = value; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string InstanceID { - get { - return ((string)(curObj["InstanceID"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsIsSavedNull { - get { - if ((curObj["IsSaved"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] +This is a read-only property, but it can be changed using the ModifyVirtualSystem method of the Msvm_VirtualSystemManagementService class.")] + public ushort[] BootOrder { + get { + return ((ushort[])(curObj["BootOrder"])); + } + set { + curObj["BootOrder"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Caption { + get { + return ((string)(curObj["Caption"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The asset tag of the chassis for the virtual computer system.\nThis is a read-only" + + " property, but it can be changed using the ModifyVirtualSystem method of the Msv" + + "m_VirtualSystemManagementService class.")] + public string ChassisAssetTag { + get { + return ((string)(curObj["ChassisAssetTag"])); + } + set { + curObj["ChassisAssetTag"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The serial number of the chassis for the virtual computer system.\nThis is a read-" + + "only property, but it can be changed using the ModifyVirtualSystem method of the" + + " Msvm_VirtualSystemManagementService class.")] + public string ChassisSerialNumber { + get { + return ((string)(curObj["ChassisSerialNumber"])); + } + set { + curObj["ChassisSerialNumber"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ConfigurationDataRoot { + get { + return ((string)(curObj["ConfigurationDataRoot"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ConfigurationFile { + get { + return ((string)(curObj["ConfigurationFile"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ConfigurationID { + get { + return ((string)(curObj["ConfigurationID"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsCreationTimeNull { + get { + if ((curObj["CreationTime"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [TypeConverter(typeof(WMIValueTypeConverter))] + public System.DateTime CreationTime { + get { + if ((curObj["CreationTime"] != null)) { + return ToDateTime(((string)(curObj["CreationTime"]))); + } + else { + return System.DateTime.MinValue; + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsDebugChannelIdNull { + get { + if ((curObj["DebugChannelId"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The channel identifier used to debug the virtual system using the VUD unified deb" + + "ugger.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint DebugChannelId { + get { + if ((curObj["DebugChannelId"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["DebugChannelId"])); + } + set { + curObj["DebugChannelId"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsDebugPortNull { + get { + if ((curObj["DebugPort"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The tcpip port used to debug the virtual system using synthetic debugging.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public uint DebugPort { + get { + if ((curObj["DebugPort"] == null)) { + return System.Convert.ToUInt32(0); + } + return ((uint)(curObj["DebugPort"])); + } + set { + curObj["DebugPort"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsDebugPortEnabledNull { + get { + if ((curObj["DebugPortEnabled"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Whether the virtual system is using synthetic debugging.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public DebugPortEnabledValues DebugPortEnabled { + get { + if ((curObj["DebugPortEnabled"] == null)) { + return ((DebugPortEnabledValues)(System.Convert.ToInt32(3))); + } + return ((DebugPortEnabledValues)(System.Convert.ToInt32(curObj["DebugPortEnabled"]))); + } + set { + if ((DebugPortEnabledValues.NULL_ENUM_VALUE == value)) { + curObj["DebugPortEnabled"] = null; + } + else { + curObj["DebugPortEnabled"] = value; + } + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string Description { + get { + return ((string)(curObj["Description"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string ElementName { + get { + return ((string)(curObj["ElementName"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsIncrementalBackupEnabledNull { + get { + if ((curObj["IncrementalBackupEnabled"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("Indicates whether the Hyper-V VSS writer supports taking incremental backup of th" + + "is Virtual machine.\nThis is a read-write property.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool IncrementalBackupEnabled { + get { + if ((curObj["IncrementalBackupEnabled"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["IncrementalBackupEnabled"])); + } + set { + curObj["IncrementalBackupEnabled"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string InstanceID { + get { + return ((string)(curObj["InstanceID"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsIsSavedNull { + get { + if ((curObj["IsSaved"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [Description(@"This property is set to TRUE if the configuration has a reference to a saved state file, FALSE if not. Note that this does not indicate the presence of such a file, only that the configuration specifies one. -This is a read-only property, it cannot be changed.")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool IsSaved { - get { - if ((curObj["IsSaved"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["IsSaved"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string LogDataRoot { - get { - return ((string)(curObj["LogDataRoot"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string[] Notes { - get { - return ((string[])(curObj["Notes"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The object path for the snapshot Msvm_VirtualSystemSettingData from which this ob" + - "ject is based. This property will be NULL if this object is not based off a snap" + - "shot.")] - public string Parent { - get { - return ((string)(curObj["Parent"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string RecoveryFile { - get { - return ((string)(curObj["RecoveryFile"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string SnapshotDataRoot { - get { - return ((string)(curObj["SnapshotDataRoot"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string SuspendDataRoot { - get { - return ((string)(curObj["SuspendDataRoot"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string SwapFileDataRoot { - get { - return ((string)(curObj["SwapFileDataRoot"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The version of the virtual system in a format of \"major.minor\", for example \"2.0\"" + - ".\nWindows Server 2008: The Version property is not supported.")] - public string Version { - get { - return ((string)(curObj["Version"])); - } - } - - [Browsable(false)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public bool IsVirtualNumaEnabledNull { - get { - if ((curObj["VirtualNumaEnabled"] == null)) { - return true; - } - else { - return false; - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] +This is a read-only property, it cannot be changed.")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool IsSaved { + get { + if ((curObj["IsSaved"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["IsSaved"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string LogDataRoot { + get { + return ((string)(curObj["LogDataRoot"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string[] Notes { + get { + return ((string[])(curObj["Notes"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The object path for the snapshot Msvm_VirtualSystemSettingData from which this ob" + + "ject is based. This property will be NULL if this object is not based off a snap" + + "shot.")] + public string Parent { + get { + return ((string)(curObj["Parent"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string RecoveryFile { + get { + return ((string)(curObj["RecoveryFile"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string SnapshotDataRoot { + get { + return ((string)(curObj["SnapshotDataRoot"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string SuspendDataRoot { + get { + return ((string)(curObj["SuspendDataRoot"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string SwapFileDataRoot { + get { + return ((string)(curObj["SwapFileDataRoot"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The version of the virtual system in a format of \"major.minor\", for example \"2.0\"" + + ".\nWindows Server 2008: The Version property is not supported.")] + public string Version { + get { + return ((string)(curObj["Version"])); + } + } + + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public bool IsVirtualNumaEnabledNull { + get { + if ((curObj["VirtualNumaEnabled"] == null)) { + return true; + } + else { + return false; + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [Description(@"Indicates whether virtual non-uniform memory access (NUMA) nodes are projected into the virtual machine. If FALSE, the virtual machine will have a single node. If TRUE, the number of virtual NUMA nodes projected into the virtual machine is determined from the values of the Msvm_ProcessorSettingData.MaxProcessorsPerNumaNode and Msvm_MemorySettingData.MaxMemoryBlocksPerNumaNode properties. -")] - [TypeConverter(typeof(WMIValueTypeConverter))] - public bool VirtualNumaEnabled { - get { - if ((curObj["VirtualNumaEnabled"] == null)) { - return System.Convert.ToBoolean(0); - } - return ((bool)(curObj["VirtualNumaEnabled"])); - } - set { - curObj["VirtualNumaEnabled"] = value; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - [Description("The name of the CIM_ComputerSystem to which this setting data belongs")] - public string VirtualSystemIdentifier { - get { - return ((string)(curObj["VirtualSystemIdentifier"])); - } - } - - [Browsable(true)] - [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] - public string VirtualSystemType { - get { - return ((string)(curObj["VirtualSystemType"])); - } - } - - private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { - if (((path != null) - && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); - } - } - - private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { - if (((theObj != null) - && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { - return true; - } - else { - System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); - if ((parentClasses != null)) { - int count = 0; - for (count = 0; (count < parentClasses.Length); count = (count + 1)) { - if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { - return true; - } - } - } - } - return false; - } - - private void ResetAdditionalRecoveryInformation() { - curObj["AdditionalRecoveryInformation"] = null; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - - private bool ShouldSerializeAllowFullSCSICommandSet() { - if ((this.IsAllowFullSCSICommandSetNull == false)) { - return true; - } - return false; - } - - private void ResetAllowFullSCSICommandSet() { - curObj["AllowFullSCSICommandSet"] = null; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - - private bool ShouldSerializeAllowReducedFcRedundancy() { - if ((this.IsAllowReducedFcRedundancyNull == false)) { - return true; - } - return false; - } - - private void ResetAllowReducedFcRedundancy() { - curObj["AllowReducedFcRedundancy"] = null; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - - private bool ShouldSerializeAutomaticRecoveryAction() { - if ((this.IsAutomaticRecoveryActionNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeAutomaticShutdownAction() { - if ((this.IsAutomaticShutdownActionNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeAutomaticStartupAction() { - if ((this.IsAutomaticStartupActionNull == false)) { - return true; - } - return false; - } - - // Converts a given datetime in DMTF format to System.DateTime object. - static System.DateTime ToDateTime(string dmtfDate) { - System.DateTime initializer = System.DateTime.MinValue; - int year = initializer.Year; - int month = initializer.Month; - int day = initializer.Day; - int hour = initializer.Hour; - int minute = initializer.Minute; - int second = initializer.Second; - long ticks = 0; - string dmtf = dmtfDate; - System.DateTime datetime = System.DateTime.MinValue; - string tempString = string.Empty; - if ((dmtf == null)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtf.Length == 0)) { - throw new System.ArgumentOutOfRangeException(); - } - if ((dmtf.Length != 25)) { - throw new System.ArgumentOutOfRangeException(); - } - try { - tempString = dmtf.Substring(0, 4); - if (("****" != tempString)) { - year = int.Parse(tempString); - } - tempString = dmtf.Substring(4, 2); - if (("**" != tempString)) { - month = int.Parse(tempString); - } - tempString = dmtf.Substring(6, 2); - if (("**" != tempString)) { - day = int.Parse(tempString); - } - tempString = dmtf.Substring(8, 2); - if (("**" != tempString)) { - hour = int.Parse(tempString); - } - tempString = dmtf.Substring(10, 2); - if (("**" != tempString)) { - minute = int.Parse(tempString); - } - tempString = dmtf.Substring(12, 2); - if (("**" != tempString)) { - second = int.Parse(tempString); - } - tempString = dmtf.Substring(15, 6); - if (("******" != tempString)) { - ticks = (long.Parse(tempString) * ((long)((System.TimeSpan.TicksPerMillisecond / 1000)))); - } - if (((((((((year < 0) - || (month < 0)) - || (day < 0)) - || (hour < 0)) - || (minute < 0)) - || (minute < 0)) - || (second < 0)) - || (ticks < 0))) { - throw new System.ArgumentOutOfRangeException(); - } - } - catch (System.Exception e) { - throw new System.ArgumentOutOfRangeException(null, e.Message); - } - datetime = new System.DateTime(year, month, day, hour, minute, second, 0); - datetime = datetime.AddTicks(ticks); - System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(datetime); - int UTCOffset = 0; - int OffsetToBeAdjusted = 0; - long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); - tempString = dmtf.Substring(22, 3); - if ((tempString != "******")) { - tempString = dmtf.Substring(21, 4); - try { - UTCOffset = int.Parse(tempString); - } - catch (System.Exception e) { - throw new System.ArgumentOutOfRangeException(null, e.Message); - } - OffsetToBeAdjusted = ((int)((OffsetMins - UTCOffset))); - datetime = datetime.AddMinutes(((double)(OffsetToBeAdjusted))); - } - return datetime; - } - - // Converts a given System.DateTime object to DMTF datetime format. - static string ToDmtfDateTime(System.DateTime date) { - string utcString = string.Empty; - System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(date); - long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); - if ((System.Math.Abs(OffsetMins) > 999)) { - date = date.ToUniversalTime(); - utcString = "+000"; - } - else { - if ((tickOffset.Ticks >= 0)) { - utcString = string.Concat("+", ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))).ToString().PadLeft(3, '0')); - } - else { - string strTemp = ((long)(OffsetMins)).ToString(); - utcString = string.Concat("-", strTemp.Substring(1, (strTemp.Length - 1)).PadLeft(3, '0')); - } - } - string dmtfDateTime = ((int)(date.Year)).ToString().PadLeft(4, '0'); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Month)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Day)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Hour)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Minute)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Second)).ToString().PadLeft(2, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, "."); - System.DateTime dtTemp = new System.DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, 0); - long microsec = ((long)((((date.Ticks - dtTemp.Ticks) - * 1000) - / System.TimeSpan.TicksPerMillisecond))); - string strMicrosec = ((long)(microsec)).ToString(); - if ((strMicrosec.Length > 6)) { - strMicrosec = strMicrosec.Substring(0, 6); - } - dmtfDateTime = string.Concat(dmtfDateTime, strMicrosec.PadLeft(6, '0')); - dmtfDateTime = string.Concat(dmtfDateTime, utcString); - return dmtfDateTime; - } - - private bool ShouldSerializeAutomaticStartupActionDelay() { - if ((this.IsAutomaticStartupActionDelayNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeAutomaticStartupActionSequenceNumber() { - if ((this.IsAutomaticStartupActionSequenceNumberNull == false)) { - return true; - } - return false; - } - - private void ResetBaseBoardSerialNumber() { - curObj["BaseBoardSerialNumber"] = null; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - - private void ResetBIOSGUID() { - curObj["BIOSGUID"] = null; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - - private bool ShouldSerializeBIOSNumLock() { - if ((this.IsBIOSNumLockNull == false)) { - return true; - } - return false; - } - - private void ResetBIOSNumLock() { - curObj["BIOSNumLock"] = null; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - - private void ResetBIOSSerialNumber() { - curObj["BIOSSerialNumber"] = null; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - - private void ResetBootOrder() { - curObj["BootOrder"] = null; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - - private void ResetChassisAssetTag() { - curObj["ChassisAssetTag"] = null; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - - private void ResetChassisSerialNumber() { - curObj["ChassisSerialNumber"] = null; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - - private bool ShouldSerializeCreationTime() { - if ((this.IsCreationTimeNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeDebugChannelId() { - if ((this.IsDebugChannelIdNull == false)) { - return true; - } - return false; - } - - private void ResetDebugChannelId() { - curObj["DebugChannelId"] = null; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - - private bool ShouldSerializeDebugPort() { - if ((this.IsDebugPortNull == false)) { - return true; - } - return false; - } - - private void ResetDebugPort() { - curObj["DebugPort"] = null; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - - private bool ShouldSerializeDebugPortEnabled() { - if ((this.IsDebugPortEnabledNull == false)) { - return true; - } - return false; - } - - private void ResetDebugPortEnabled() { - curObj["DebugPortEnabled"] = null; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - - private bool ShouldSerializeIncrementalBackupEnabled() { - if ((this.IsIncrementalBackupEnabledNull == false)) { - return true; - } - return false; - } - - private void ResetIncrementalBackupEnabled() { - curObj["IncrementalBackupEnabled"] = null; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - - private bool ShouldSerializeIsSaved() { - if ((this.IsIsSavedNull == false)) { - return true; - } - return false; - } - - private bool ShouldSerializeVirtualNumaEnabled() { - if ((this.IsVirtualNumaEnabledNull == false)) { - return true; - } - return false; - } - - private void ResetVirtualNumaEnabled() { - curObj["VirtualNumaEnabled"] = null; - if (((isEmbedded == false) - && (AutoCommitProp == true))) { - PrivateLateBoundObject.Put(); - } - } - - [Browsable(true)] - public void CommitObject() { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(); - } - } - - [Browsable(true)] - public void CommitObject(System.Management.PutOptions putOptions) { - if ((isEmbedded == false)) { - PrivateLateBoundObject.Put(putOptions); - } - } - - private void Initialize() { - AutoCommitProp = true; - isEmbedded = false; - } - - private static string ConstructPath(string keyInstanceID) { - string strPath = "ROOT\\virtualization\\v2:Msvm_VirtualSystemSettingData"; - strPath = string.Concat(strPath, string.Concat(".InstanceID=", string.Concat("\"", string.Concat(keyInstanceID, "\"")))); - return strPath; - } - - private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { - Initialize(); - if ((path != null)) { - if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { - throw new System.ArgumentException("Class name does not match."); - } - } - PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); - PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); - curObj = PrivateLateBoundObject; - } - - // Different overloads of GetInstances() help in enumerating instances of the WMI class. - public static VirtualSystemSettingDataCollection GetInstances() { - return GetInstances(null, null, null); - } - - public static VirtualSystemSettingDataCollection GetInstances(string condition) { - return GetInstances(null, condition, null); - } - - public static VirtualSystemSettingDataCollection GetInstances(string[] selectedProperties) { - return GetInstances(null, null, selectedProperties); - } - - public static VirtualSystemSettingDataCollection GetInstances(string condition, string[] selectedProperties) { - return GetInstances(null, condition, selectedProperties); - } - - public static VirtualSystemSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); - pathObj.ClassName = "Msvm_VirtualSystemSettingData"; - pathObj.NamespacePath = "root\\virtualization\\v2"; - System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); - if ((enumOptions == null)) { - enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - } - return new VirtualSystemSettingDataCollection(clsObject.GetInstances(enumOptions)); - } - - public static VirtualSystemSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { - return GetInstances(mgmtScope, condition, null); - } - - public static VirtualSystemSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { - return GetInstances(mgmtScope, null, selectedProperties); - } - - public static VirtualSystemSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { - if ((mgmtScope == null)) { - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; - } - else { - mgmtScope = statMgmtScope; - } - } - System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_VirtualSystemSettingData", condition, selectedProperties)); - System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); - enumOptions.EnsureLocatable = true; - ObjectSearcher.Options = enumOptions; - return new VirtualSystemSettingDataCollection(ObjectSearcher.Get()); - } - - [Browsable(true)] - public static VirtualSystemSettingData CreateInstance() { - System.Management.ManagementScope mgmtScope = null; - if ((statMgmtScope == null)) { - mgmtScope = new System.Management.ManagementScope(); - mgmtScope.Path.NamespacePath = CreatedWmiNamespace; - } - else { - mgmtScope = statMgmtScope; - } - System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); - System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); - return new VirtualSystemSettingData(tmpMgmtClass.CreateInstance()); - } - - [Browsable(true)] - public void Delete() { - PrivateLateBoundObject.Delete(); - } - - public enum DebugPortEnabledValues { - - Val__Off = 0, - - On = 1, - - OnAutoAssigned = 2, - - NULL_ENUM_VALUE = 3, - } - - // Enumerator implementation for enumerating instances of the class. - public class VirtualSystemSettingDataCollection : object, ICollection { - - private ManagementObjectCollection privColObj; - - public VirtualSystemSettingDataCollection(ManagementObjectCollection objCollection) { - privColObj = objCollection; - } - - public virtual int Count { - get { - return privColObj.Count; - } - } - - public virtual bool IsSynchronized { - get { - return privColObj.IsSynchronized; - } - } - - public virtual object SyncRoot { - get { - return this; - } - } - - public virtual void CopyTo(System.Array array, int index) { - privColObj.CopyTo(array, index); - int nCtr; - for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { - array.SetValue(new VirtualSystemSettingData(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); - } - } - - public virtual System.Collections.IEnumerator GetEnumerator() { - return new VirtualSystemSettingDataEnumerator(privColObj.GetEnumerator()); - } - - public class VirtualSystemSettingDataEnumerator : object, System.Collections.IEnumerator { - - private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; - - public VirtualSystemSettingDataEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { - privObjEnum = objEnum; - } - - public virtual object Current { - get { - return new VirtualSystemSettingData(((System.Management.ManagementObject)(privObjEnum.Current))); - } - } - - public virtual bool MoveNext() { - return privObjEnum.MoveNext(); - } - - public virtual void Reset() { - privObjEnum.Reset(); - } - } - } - - // TypeConverter to handle null values for ValueType properties - public class WMIValueTypeConverter : TypeConverter { - - private TypeConverter baseConverter; - - private System.Type baseType; - - public WMIValueTypeConverter(System.Type inBaseType) { - baseConverter = TypeDescriptor.GetConverter(inBaseType); - baseType = inBaseType; - } - - public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { - return baseConverter.CanConvertFrom(context, srcType); - } - - public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { - return baseConverter.CanConvertTo(context, destinationType); - } - - public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { - return baseConverter.ConvertFrom(context, culture, value); - } - - public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { - return baseConverter.CreateInstance(context, dictionary); - } - - public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetCreateInstanceSupported(context); - } - - public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { - return baseConverter.GetProperties(context, value, attributeVar); - } - - public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetPropertiesSupported(context); - } - - public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValues(context); - } - - public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesExclusive(context); - } - - public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { - return baseConverter.GetStandardValuesSupported(context); - } - - public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { - if ((baseType.BaseType == typeof(System.Enum))) { - if ((value.GetType() == destinationType)) { - return value; - } - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return "NULL_ENUM_VALUE" ; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((baseType == typeof(bool)) - && (baseType.BaseType == typeof(System.ValueType)))) { - if ((((value == null) - && (context != null)) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - if (((context != null) - && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { - return ""; - } - return baseConverter.ConvertTo(context, culture, value, destinationType); - } - } - - // Embedded class to represent WMI system Properties. - [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] - public class ManagementSystemProperties { - - private System.Management.ManagementBaseObject PrivateLateBoundObject; - - public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { - PrivateLateBoundObject = ManagedObject; - } - - [Browsable(true)] - public int GENUS { - get { - return ((int)(PrivateLateBoundObject["__GENUS"])); - } - } - - [Browsable(true)] - public string CLASS { - get { - return ((string)(PrivateLateBoundObject["__CLASS"])); - } - } - - [Browsable(true)] - public string SUPERCLASS { - get { - return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); - } - } - - [Browsable(true)] - public string DYNASTY { - get { - return ((string)(PrivateLateBoundObject["__DYNASTY"])); - } - } - - [Browsable(true)] - public string RELPATH { - get { - return ((string)(PrivateLateBoundObject["__RELPATH"])); - } - } - - [Browsable(true)] - public int PROPERTY_COUNT { - get { - return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); - } - } - - [Browsable(true)] - public string[] DERIVATION { - get { - return ((string[])(PrivateLateBoundObject["__DERIVATION"])); - } - } - - [Browsable(true)] - public string SERVER { - get { - return ((string)(PrivateLateBoundObject["__SERVER"])); - } - } - - [Browsable(true)] - public string NAMESPACE { - get { - return ((string)(PrivateLateBoundObject["__NAMESPACE"])); - } - } - - [Browsable(true)] - public string PATH { - get { - return ((string)(PrivateLateBoundObject["__PATH"])); - } - } - } - } -} +")] + [TypeConverter(typeof(WMIValueTypeConverter))] + public bool VirtualNumaEnabled { + get { + if ((curObj["VirtualNumaEnabled"] == null)) { + return System.Convert.ToBoolean(0); + } + return ((bool)(curObj["VirtualNumaEnabled"])); + } + set { + curObj["VirtualNumaEnabled"] = value; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + [Description("The name of the CIM_ComputerSystem to which this setting data belongs")] + public string VirtualSystemIdentifier { + get { + return ((string)(curObj["VirtualSystemIdentifier"])); + } + } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string VirtualSystemType { + get { + return ((string)(curObj["VirtualSystemType"])); + } + } + + private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { + if (((path != null) + && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); + } + } + + private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { + if (((theObj != null) + && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { + return true; + } + else { + System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); + if ((parentClasses != null)) { + int count = 0; + for (count = 0; (count < parentClasses.Length); count = (count + 1)) { + if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { + return true; + } + } + } + } + return false; + } + + private void ResetAdditionalRecoveryInformation() { + curObj["AdditionalRecoveryInformation"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private bool ShouldSerializeAllowFullSCSICommandSet() { + if ((this.IsAllowFullSCSICommandSetNull == false)) { + return true; + } + return false; + } + + private void ResetAllowFullSCSICommandSet() { + curObj["AllowFullSCSICommandSet"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private bool ShouldSerializeAllowReducedFcRedundancy() { + if ((this.IsAllowReducedFcRedundancyNull == false)) { + return true; + } + return false; + } + + private void ResetAllowReducedFcRedundancy() { + curObj["AllowReducedFcRedundancy"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private bool ShouldSerializeAutomaticRecoveryAction() { + if ((this.IsAutomaticRecoveryActionNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeAutomaticShutdownAction() { + if ((this.IsAutomaticShutdownActionNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeAutomaticStartupAction() { + if ((this.IsAutomaticStartupActionNull == false)) { + return true; + } + return false; + } + + // Converts a given datetime in DMTF format to System.DateTime object. + static System.DateTime ToDateTime(string dmtfDate) { + System.DateTime initializer = System.DateTime.MinValue; + int year = initializer.Year; + int month = initializer.Month; + int day = initializer.Day; + int hour = initializer.Hour; + int minute = initializer.Minute; + int second = initializer.Second; + long ticks = 0; + string dmtf = dmtfDate; + System.DateTime datetime = System.DateTime.MinValue; + string tempString = string.Empty; + if ((dmtf == null)) { + throw new System.ArgumentOutOfRangeException(); + } + if ((dmtf.Length == 0)) { + throw new System.ArgumentOutOfRangeException(); + } + if ((dmtf.Length != 25)) { + throw new System.ArgumentOutOfRangeException(); + } + try { + tempString = dmtf.Substring(0, 4); + if (("****" != tempString)) { + year = int.Parse(tempString); + } + tempString = dmtf.Substring(4, 2); + if (("**" != tempString)) { + month = int.Parse(tempString); + } + tempString = dmtf.Substring(6, 2); + if (("**" != tempString)) { + day = int.Parse(tempString); + } + tempString = dmtf.Substring(8, 2); + if (("**" != tempString)) { + hour = int.Parse(tempString); + } + tempString = dmtf.Substring(10, 2); + if (("**" != tempString)) { + minute = int.Parse(tempString); + } + tempString = dmtf.Substring(12, 2); + if (("**" != tempString)) { + second = int.Parse(tempString); + } + tempString = dmtf.Substring(15, 6); + if (("******" != tempString)) { + ticks = (long.Parse(tempString) * ((long)((System.TimeSpan.TicksPerMillisecond / 1000)))); + } + if (((((((((year < 0) + || (month < 0)) + || (day < 0)) + || (hour < 0)) + || (minute < 0)) + || (minute < 0)) + || (second < 0)) + || (ticks < 0))) { + throw new System.ArgumentOutOfRangeException(); + } + } + catch (System.Exception e) { + throw new System.ArgumentOutOfRangeException(null, e.Message); + } + datetime = new System.DateTime(year, month, day, hour, minute, second, 0); + datetime = datetime.AddTicks(ticks); + System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(datetime); + int UTCOffset = 0; + int OffsetToBeAdjusted = 0; + long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); + tempString = dmtf.Substring(22, 3); + if ((tempString != "******")) { + tempString = dmtf.Substring(21, 4); + try { + UTCOffset = int.Parse(tempString); + } + catch (System.Exception e) { + throw new System.ArgumentOutOfRangeException(null, e.Message); + } + OffsetToBeAdjusted = ((int)((OffsetMins - UTCOffset))); + datetime = datetime.AddMinutes(((double)(OffsetToBeAdjusted))); + } + return datetime; + } + + // Converts a given System.DateTime object to DMTF datetime format. + static string ToDmtfDateTime(System.DateTime date) { + string utcString = string.Empty; + System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(date); + long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); + if ((System.Math.Abs(OffsetMins) > 999)) { + date = date.ToUniversalTime(); + utcString = "+000"; + } + else { + if ((tickOffset.Ticks >= 0)) { + utcString = string.Concat("+", ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))).ToString().PadLeft(3, '0')); + } + else { + string strTemp = ((long)(OffsetMins)).ToString(); + utcString = string.Concat("-", strTemp.Substring(1, (strTemp.Length - 1)).PadLeft(3, '0')); + } + } + string dmtfDateTime = ((int)(date.Year)).ToString().PadLeft(4, '0'); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Month)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Day)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Hour)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Minute)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, ((int)(date.Second)).ToString().PadLeft(2, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, "."); + System.DateTime dtTemp = new System.DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, 0); + long microsec = ((long)((((date.Ticks - dtTemp.Ticks) + * 1000) + / System.TimeSpan.TicksPerMillisecond))); + string strMicrosec = ((long)(microsec)).ToString(); + if ((strMicrosec.Length > 6)) { + strMicrosec = strMicrosec.Substring(0, 6); + } + dmtfDateTime = string.Concat(dmtfDateTime, strMicrosec.PadLeft(6, '0')); + dmtfDateTime = string.Concat(dmtfDateTime, utcString); + return dmtfDateTime; + } + + private bool ShouldSerializeAutomaticStartupActionDelay() { + if ((this.IsAutomaticStartupActionDelayNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeAutomaticStartupActionSequenceNumber() { + if ((this.IsAutomaticStartupActionSequenceNumberNull == false)) { + return true; + } + return false; + } + + private void ResetBaseBoardSerialNumber() { + curObj["BaseBoardSerialNumber"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private void ResetBIOSGUID() { + curObj["BIOSGUID"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private bool ShouldSerializeBIOSNumLock() { + if ((this.IsBIOSNumLockNull == false)) { + return true; + } + return false; + } + + private void ResetBIOSNumLock() { + curObj["BIOSNumLock"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private void ResetBIOSSerialNumber() { + curObj["BIOSSerialNumber"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private void ResetBootOrder() { + curObj["BootOrder"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private void ResetChassisAssetTag() { + curObj["ChassisAssetTag"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private void ResetChassisSerialNumber() { + curObj["ChassisSerialNumber"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private bool ShouldSerializeCreationTime() { + if ((this.IsCreationTimeNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeDebugChannelId() { + if ((this.IsDebugChannelIdNull == false)) { + return true; + } + return false; + } + + private void ResetDebugChannelId() { + curObj["DebugChannelId"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private bool ShouldSerializeDebugPort() { + if ((this.IsDebugPortNull == false)) { + return true; + } + return false; + } + + private void ResetDebugPort() { + curObj["DebugPort"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private bool ShouldSerializeDebugPortEnabled() { + if ((this.IsDebugPortEnabledNull == false)) { + return true; + } + return false; + } + + private void ResetDebugPortEnabled() { + curObj["DebugPortEnabled"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private bool ShouldSerializeIncrementalBackupEnabled() { + if ((this.IsIncrementalBackupEnabledNull == false)) { + return true; + } + return false; + } + + private void ResetIncrementalBackupEnabled() { + curObj["IncrementalBackupEnabled"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + private bool ShouldSerializeIsSaved() { + if ((this.IsIsSavedNull == false)) { + return true; + } + return false; + } + + private bool ShouldSerializeVirtualNumaEnabled() { + if ((this.IsVirtualNumaEnabledNull == false)) { + return true; + } + return false; + } + + private void ResetVirtualNumaEnabled() { + curObj["VirtualNumaEnabled"] = null; + if (((isEmbedded == false) + && (AutoCommitProp == true))) { + PrivateLateBoundObject.Put(); + } + } + + [Browsable(true)] + public void CommitObject() { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(); + } + } + + [Browsable(true)] + public void CommitObject(System.Management.PutOptions putOptions) { + if ((isEmbedded == false)) { + PrivateLateBoundObject.Put(putOptions); + } + } + + private void Initialize() { + AutoCommitProp = true; + isEmbedded = false; + } + + private static string ConstructPath(string keyInstanceID) { + string strPath = "ROOT\\virtualization\\v2:Msvm_VirtualSystemSettingData"; + strPath = string.Concat(strPath, string.Concat(".InstanceID=", string.Concat("\"", string.Concat(keyInstanceID, "\"")))); + return strPath; + } + + private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { + Initialize(); + if ((path != null)) { + if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { + throw new System.ArgumentException("Class name does not match."); + } + } + PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); + PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); + curObj = PrivateLateBoundObject; + } + + // Different overloads of GetInstances() help in enumerating instances of the WMI class. + public static VirtualSystemSettingDataCollection GetInstances() { + return GetInstances(null, null, null); + } + + public static VirtualSystemSettingDataCollection GetInstances(string condition) { + return GetInstances(null, condition, null); + } + + public static VirtualSystemSettingDataCollection GetInstances(string[] selectedProperties) { + return GetInstances(null, null, selectedProperties); + } + + public static VirtualSystemSettingDataCollection GetInstances(string condition, string[] selectedProperties) { + return GetInstances(null, condition, selectedProperties); + } + + public static VirtualSystemSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); + pathObj.ClassName = "Msvm_VirtualSystemSettingData"; + pathObj.NamespacePath = "root\\virtualization\\v2"; + System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); + if ((enumOptions == null)) { + enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + } + return new VirtualSystemSettingDataCollection(clsObject.GetInstances(enumOptions)); + } + + public static VirtualSystemSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { + return GetInstances(mgmtScope, condition, null); + } + + public static VirtualSystemSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string[] selectedProperties) { + return GetInstances(mgmtScope, null, selectedProperties); + } + + public static VirtualSystemSettingDataCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, string[] selectedProperties) { + if ((mgmtScope == null)) { + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = "root\\virtualization\\v2"; + } + else { + mgmtScope = statMgmtScope; + } + } + System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("Msvm_VirtualSystemSettingData", condition, selectedProperties)); + System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); + enumOptions.EnsureLocatable = true; + ObjectSearcher.Options = enumOptions; + return new VirtualSystemSettingDataCollection(ObjectSearcher.Get()); + } + + [Browsable(true)] + public static VirtualSystemSettingData CreateInstance() { + System.Management.ManagementScope mgmtScope = null; + if ((statMgmtScope == null)) { + mgmtScope = new System.Management.ManagementScope(); + mgmtScope.Path.NamespacePath = CreatedWmiNamespace; + } + else { + mgmtScope = statMgmtScope; + } + System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); + System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); + return new VirtualSystemSettingData(tmpMgmtClass.CreateInstance()); + } + + [Browsable(true)] + public void Delete() { + PrivateLateBoundObject.Delete(); + } + + public enum DebugPortEnabledValues { + + Val__Off = 0, + + On = 1, + + OnAutoAssigned = 2, + + NULL_ENUM_VALUE = 3, + } + + // Enumerator implementation for enumerating instances of the class. + public class VirtualSystemSettingDataCollection : object, ICollection { + + private ManagementObjectCollection privColObj; + + public VirtualSystemSettingDataCollection(ManagementObjectCollection objCollection) { + privColObj = objCollection; + } + + public virtual int Count { + get { + return privColObj.Count; + } + } + + public virtual bool IsSynchronized { + get { + return privColObj.IsSynchronized; + } + } + + public virtual object SyncRoot { + get { + return this; + } + } + + public virtual void CopyTo(System.Array array, int index) { + privColObj.CopyTo(array, index); + int nCtr; + for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { + array.SetValue(new VirtualSystemSettingData(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); + } + } + + public virtual System.Collections.IEnumerator GetEnumerator() { + return new VirtualSystemSettingDataEnumerator(privColObj.GetEnumerator()); + } + + public class VirtualSystemSettingDataEnumerator : object, System.Collections.IEnumerator { + + private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; + + public VirtualSystemSettingDataEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { + privObjEnum = objEnum; + } + + public virtual object Current { + get { + return new VirtualSystemSettingData(((System.Management.ManagementObject)(privObjEnum.Current))); + } + } + + public virtual bool MoveNext() { + return privObjEnum.MoveNext(); + } + + public virtual void Reset() { + privObjEnum.Reset(); + } + } + } + + // TypeConverter to handle null values for ValueType properties + public class WMIValueTypeConverter : TypeConverter { + + private TypeConverter baseConverter; + + private System.Type baseType; + + public WMIValueTypeConverter(System.Type inBaseType) { + baseConverter = TypeDescriptor.GetConverter(inBaseType); + baseType = inBaseType; + } + + public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { + return baseConverter.CanConvertFrom(context, srcType); + } + + public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { + return baseConverter.CanConvertTo(context, destinationType); + } + + public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { + return baseConverter.ConvertFrom(context, culture, value); + } + + public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { + return baseConverter.CreateInstance(context, dictionary); + } + + public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetCreateInstanceSupported(context); + } + + public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { + return baseConverter.GetProperties(context, value, attributeVar); + } + + public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetPropertiesSupported(context); + } + + public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValues(context); + } + + public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesExclusive(context); + } + + public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { + return baseConverter.GetStandardValuesSupported(context); + } + + public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { + if ((baseType.BaseType == typeof(System.Enum))) { + if ((value.GetType() == destinationType)) { + return value; + } + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return "NULL_ENUM_VALUE" ; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((baseType == typeof(bool)) + && (baseType.BaseType == typeof(System.ValueType)))) { + if ((((value == null) + && (context != null)) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + if (((context != null) + && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { + return ""; + } + return baseConverter.ConvertTo(context, culture, value, destinationType); + } + } + + // Embedded class to represent WMI system Properties. + [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] + public class ManagementSystemProperties { + + private System.Management.ManagementBaseObject PrivateLateBoundObject; + + public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { + PrivateLateBoundObject = ManagedObject; + } + + [Browsable(true)] + public int GENUS { + get { + return ((int)(PrivateLateBoundObject["__GENUS"])); + } + } + + [Browsable(true)] + public string CLASS { + get { + return ((string)(PrivateLateBoundObject["__CLASS"])); + } + } + + [Browsable(true)] + public string SUPERCLASS { + get { + return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); + } + } + + [Browsable(true)] + public string DYNASTY { + get { + return ((string)(PrivateLateBoundObject["__DYNASTY"])); + } + } + + [Browsable(true)] + public string RELPATH { + get { + return ((string)(PrivateLateBoundObject["__RELPATH"])); + } + } + + [Browsable(true)] + public int PROPERTY_COUNT { + get { + return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); + } + } + + [Browsable(true)] + public string[] DERIVATION { + get { + return ((string[])(PrivateLateBoundObject["__DERIVATION"])); + } + } + + [Browsable(true)] + public string SERVER { + get { + return ((string)(PrivateLateBoundObject["__SERVER"])); + } + } + + [Browsable(true)] + public string NAMESPACE { + get { + return ((string)(PrivateLateBoundObject["__NAMESPACE"])); + } + } + + [Browsable(true)] + public string PATH { + get { + return ((string)(PrivateLateBoundObject["__PATH"])); + } + } + } + } +} diff --git a/plugins/hypervisors/hyperv/buildagent.sh b/plugins/hypervisors/hyperv/buildagent.sh index e5bff6e3153..536ba437ffc 100755 --- a/plugins/hypervisors/hyperv/buildagent.sh +++ b/plugins/hypervisors/hyperv/buildagent.sh @@ -1,20 +1,22 @@ #!/bin/bash -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at + +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at # -# http://www.apache.org/licenses/LICENSE-2.0 +# http://www.apache.org/licenses/LICENSE-2.0 # -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + export EnableNuGetPackageRestore=true wget http://nuget.org/nuget.exe mv nuget.exe ./DotNet/ServerResource/.nuget/NuGet.exe diff --git a/plugins/hypervisors/hyperv/pom.xml b/plugins/hypervisors/hyperv/pom.xml index 83157ce4c65..c67943ab243 100644 --- a/plugins/hypervisors/hyperv/pom.xml +++ b/plugins/hypervisors/hyperv/pom.xml @@ -24,7 +24,7 @@ org.apache.cloudstack cloudstack-plugins - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT ../../pom.xml diff --git a/plugins/hypervisors/hyperv/src/main/java/org/apache/cloudstack/storage/motion/HypervStorageMotionStrategy.java b/plugins/hypervisors/hyperv/src/main/java/org/apache/cloudstack/storage/motion/HypervStorageMotionStrategy.java index 0e189d05000..55944a08242 100644 --- a/plugins/hypervisors/hyperv/src/main/java/org/apache/cloudstack/storage/motion/HypervStorageMotionStrategy.java +++ b/plugins/hypervisors/hyperv/src/main/java/org/apache/cloudstack/storage/motion/HypervStorageMotionStrategy.java @@ -155,6 +155,7 @@ public class HypervStorageMotionStrategy implements DataMotionStrategy { volumeVO.setPath(volumeTo.getPath()); volumeVO.setPodId(pool.getPodId()); volumeVO.setPoolId(pool.getId()); + volumeVO.setPoolType(pool.getPoolType()); volumeVO.setLastPoolId(oldPoolId); // For SMB, pool credentials are also stored in the uri query string. We trim the query string // part here to make sure the credentials do not get stored in the db unencrypted. diff --git a/plugins/hypervisors/kvm/pom.xml b/plugins/hypervisors/kvm/pom.xml index ab25aa0ccc9..a7c5461e798 100644 --- a/plugins/hypervisors/kvm/pom.xml +++ b/plugins/hypervisors/kvm/pom.xml @@ -24,7 +24,7 @@ org.apache.cloudstack cloudstack-plugins - 4.22.0.0-SNAPSHOT + 4.23.0.0-SNAPSHOT ../../pom.xml diff --git a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java index a86efeb8a1f..fbfe3ef20eb 100644 --- a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java +++ b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java @@ -69,6 +69,7 @@ import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; +import com.cloud.agent.api.to.VirtualMachineMetadataTO; import org.apache.cloudstack.api.ApiConstants.IoDriverPolicy; import org.apache.cloudstack.command.CommandInfo; import org.apache.cloudstack.command.ReconcileCommandService; @@ -199,6 +200,7 @@ import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.VideoDef; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.WatchDogDef; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.WatchDogDef.WatchDogAction; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.WatchDogDef.WatchDogModel; +import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.MetadataDef; import com.cloud.hypervisor.kvm.resource.rolling.maintenance.RollingMaintenanceAgentExecutor; import com.cloud.hypervisor.kvm.resource.rolling.maintenance.RollingMaintenanceExecutor; import com.cloud.hypervisor.kvm.resource.rolling.maintenance.RollingMaintenanceServiceExecutor; @@ -882,6 +884,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv protected StorageSubsystemCommandHandler storageHandler; private boolean convertInstanceVerboseMode = false; + private String[] convertInstanceEnv = null; protected boolean dpdkSupport = false; protected String dpdkOvsPath; protected String directDownloadTemporaryDownloadPath; @@ -946,6 +949,10 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv return convertInstanceVerboseMode; } + public String[] getConvertInstanceEnv() { + return convertInstanceEnv; + } + /** * Defines resource's public and private network interface according to what is configured in agent.properties. */ @@ -1146,6 +1153,11 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv convertInstanceVerboseMode = BooleanUtils.isTrue(AgentPropertiesFileHandler.getPropertyValue(AgentProperties.VIRTV2V_VERBOSE_ENABLED)); + String convertEnvTmpDir = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.CONVERT_ENV_TMPDIR); + String convertEnvVirtv2vTmpDir = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.CONVERT_ENV_VIRTV2V_TMPDIR); + + setConvertInstanceEnv(convertEnvTmpDir, convertEnvVirtv2vTmpDir); + pool = (String)params.get("pool"); if (pool == null) { pool = "/root"; @@ -1422,6 +1434,22 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv return true; } + private void setConvertInstanceEnv(String convertEnvTmpDir, String convertEnvVirtv2vTmpDir) { + if (StringUtils.isAllBlank(convertEnvTmpDir, convertEnvVirtv2vTmpDir)) { + return; + } + if (StringUtils.isNotBlank(convertEnvTmpDir) && StringUtils.isNotBlank(convertEnvVirtv2vTmpDir)) { + convertInstanceEnv = new String[2]; + convertInstanceEnv[0] = String.format("%s=%s", "TMPDIR", convertEnvTmpDir); + convertInstanceEnv[1] = String.format("%s=%s", "VIRT_V2V_TMPDIR", convertEnvVirtv2vTmpDir); + } else { + convertInstanceEnv = new String[1]; + String key = StringUtils.isNotBlank(convertEnvTmpDir) ? "TMPDIR" : "VIRT_V2V_TMPDIR"; + String value = StringUtils.isNotBlank(convertEnvTmpDir) ? convertEnvTmpDir : convertEnvVirtv2vTmpDir; + convertInstanceEnv[0] = String.format("%s=%s", key, value); + } + } + /** * Parses a string containing whitespace-separated CPU feature names and converts it into a list. * @@ -2985,9 +3013,19 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv vm.addComp(createClockDef(vmTO)); vm.addComp(createDevicesDef(vmTO, guest, vcpus, isUefiEnabled)); + MetadataDef metaDef; + if ((metaDef = createMetadataDef(vmTO)) != null) { + vm.addComp(metaDef); + } + addExtraConfigsToVM(vmTO, vm, extraConfig); } + protected MetadataDef createMetadataDef(VirtualMachineTO vmTO) { + VirtualMachineMetadataTO metadata = vmTO.getMetadata(); + return (metadata != null) ? new MetadataDef(metadata) : null; + } + /** * Adds extra configuration to User VM Domain XML before starting. */ diff --git a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/LibvirtVMDef.java b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/LibvirtVMDef.java index 46a5024bf15..211395513d5 100644 --- a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/LibvirtVMDef.java +++ b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/LibvirtVMDef.java @@ -17,6 +17,10 @@ package com.cloud.hypervisor.kvm.resource; import java.io.File; +import java.io.StringWriter; +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneOffset; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; @@ -29,9 +33,25 @@ import org.apache.commons.lang.StringEscapeUtils; import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; +import com.cloud.agent.api.to.VirtualMachineMetadataTO; + import com.cloud.agent.properties.AgentProperties; import com.cloud.agent.properties.AgentPropertiesFileHandler; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.OutputKeys; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerConfigurationException; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; + +import static java.time.format.DateTimeFormatter.ISO_LOCAL_DATE_TIME; public class LibvirtVMDef { protected static Logger LOGGER = LogManager.getLogger(LibvirtVMDef.class); @@ -46,6 +66,157 @@ public class LibvirtVMDef { private final Map components = new HashMap(); private static final int NUMBER_OF_IOTHREADS = AgentPropertiesFileHandler.getPropertyValue(AgentProperties.IOTHREADS); + public static class MetadataDef { + private VirtualMachineMetadataTO metaTO; + + public MetadataDef(VirtualMachineMetadataTO data) { + metaTO = data; + } + + public VirtualMachineMetadataTO getMetadata() { + return metaTO; + } + + @Override + public String toString() { + DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); + docFactory.setNamespaceAware(true); + Document doc = null; + try { + doc = docFactory.newDocumentBuilder().newDocument(); + } catch (ParserConfigurationException e) { + LOGGER.warn("Could not create a new DOM XML document. The metadata will not be included in the libvirt domain XML: {}", e.getMessage()); + return ""; + } + Element metadata = doc.createElement("metadata"); // + Element instance = doc.createElementNS("http://cloudstack.apache.org/instance", "cloudstack:instance"); // + + Element zone = doc.createElement("cloudstack:zone"); + zone.setAttribute("uuid", metaTO.getZoneUuid()); + zone.setTextContent(metaTO.getZoneName()); + instance.appendChild(zone); + + Element pod = doc.createElement("cloudstack:pod"); + pod.setAttribute("uuid", metaTO.getPodUuid()); + pod.setTextContent(metaTO.getPodName()); + instance.appendChild(pod); + + Element cluster = doc.createElement("cloudstack:cluster"); + cluster.setAttribute("uuid", metaTO.getClusterUuid()); + cluster.setTextContent(metaTO.getClusterName()); + instance.appendChild(cluster); + + Element instanceName = doc.createElement("cloudstack:name"); + instanceName.setTextContent(metaTO.getName()); + instance.appendChild(instanceName); + + Element instanceInternalName = doc.createElement("cloudstack:internal_name"); + instanceInternalName.setTextContent(metaTO.getInternalName()); + instance.appendChild(instanceInternalName); + + Element instanceDisplayName = doc.createElement("cloudstack:display_name"); + instanceDisplayName.setTextContent(metaTO.getDisplayName()); + instance.appendChild(instanceDisplayName); + + Element instanceUuid = doc.createElement("cloudstack:uuid"); + instanceUuid.setTextContent(metaTO.getInstanceUuid()); + instance.appendChild(instanceUuid); + + Element serviceOffering = doc.createElement("cloudstack:service_offering"); // + + Element computeOfferingName = doc.createElement("cloudstack:name"); + computeOfferingName.setTextContent(metaTO.getserviceOfferingName()); + serviceOffering.appendChild(computeOfferingName); + + Element cpu = doc.createElement("cloudstack:cpu"); + cpu.setTextContent(metaTO.getCpuCores().toString()); + serviceOffering.appendChild(cpu); + + Element memory = doc.createElement("cloudstack:memory"); + memory.setTextContent(metaTO.getMemory().toString()); + serviceOffering.appendChild(memory); + + Element hostTags = doc.createElement("cloudstack:host_tags"); + List tags = metaTO.getserviceOfferingHostTags(); + if (tags != null) { + for (String i : metaTO.getserviceOfferingHostTags()) { + Element tag = doc.createElement("cloudstack:tag"); + tag.setTextContent(i); + hostTags.appendChild(tag); + } + } + serviceOffering.appendChild(hostTags); + + instance.appendChild(serviceOffering); // + + Element creationTime = doc.createElement("cloudstack:created_at"); + creationTime.setTextContent( + LocalDateTime.ofInstant(Instant.ofEpochSecond(metaTO.getCreated()), ZoneOffset.UTC).format(ISO_LOCAL_DATE_TIME) + ); + instance.appendChild(creationTime); + + Element startedTime = doc.createElement("cloudstack:started_at"); + startedTime.setTextContent( + LocalDateTime.ofInstant(Instant.ofEpochSecond(metaTO.getStarted()), ZoneOffset.UTC).format(ISO_LOCAL_DATE_TIME) + ); + instance.appendChild(startedTime); + + Element owner = doc.createElement("cloudstack:owner"); // + + Element domain = doc.createElement("cloudstack:domain"); + domain.setAttribute("uuid", metaTO.getOwnerDomainUuid()); + domain.setTextContent(metaTO.getOwnerDomainName()); + owner.appendChild(domain); + + Element account = doc.createElement("cloudstack:account"); + account.setAttribute("uuid", metaTO.getOwnerAccountUuid()); + account.setTextContent(metaTO.getOwnerAccountName()); + owner.appendChild(account); + + Element project = doc.createElement("cloudstack:project"); + project.setAttribute("uuid", metaTO.getOwnerProjectUuid()); + project.setTextContent(metaTO.getOwnerProjectName()); + owner.appendChild(project); + + instance.appendChild(owner); // + + Element resourceTags = doc.createElement("cloudstack:resource_tags"); // + for (Map.Entry entry : metaTO.getResourceTags().entrySet()) { + Element tag = doc.createElement("cloudstack:resource_tag"); // + tag.setAttribute("key", entry.getKey()); + tag.setTextContent(entry.getValue()); + resourceTags.appendChild(tag); // + } + instance.appendChild(resourceTags); // + + metadata.appendChild(instance); // + doc.appendChild(metadata); // + + Transformer transformer = null; + try { + transformer = TransformerFactory.newInstance().newTransformer(); + } catch (TransformerConfigurationException e) { + LOGGER.warn("Could not create an XML transformer. The metadata will not be included in the libvirt domain XML: {}", e.getMessage()); + return ""; + } + transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); + transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); + transformer.setOutputProperty(OutputKeys.INDENT, "yes"); + + DOMSource domSource = new DOMSource(doc); + StringWriter writer = new StringWriter(); + StreamResult result = new StreamResult(writer); + try { + transformer.transform(domSource, result); + } catch (TransformerException e) { + LOGGER.warn("Could not generate metadata XML. The metadata will not be included in the libvirt domain XML: {}", e.getMessage()); + return ""; + } + + return writer.toString(); + } + } + public static class GuestDef { enum GuestType { KVM, XEN, EXE, LXC @@ -707,7 +878,7 @@ public class LibvirtVMDef { } public enum DiskCacheMode { - NONE("none"), WRITEBACK("writeback"), WRITETHROUGH("writethrough"); + NONE("none"), WRITEBACK("writeback"), WRITETHROUGH("writethrough"), HYPERVISOR_DEFAULT("default"); String _diskCacheMode; DiskCacheMode(String cacheMode) { @@ -2163,34 +2334,6 @@ public class LibvirtVMDef { } } - public class MetadataDef { - Map customNodes = new HashMap<>(); - - public T getMetadataNode(Class fieldClass) { - T field = (T) customNodes.get(fieldClass.getName()); - if (field == null) { - try { - field = fieldClass.newInstance(); - customNodes.put(field.getClass().getName(), field); - } catch (InstantiationException | IllegalAccessException e) { - LOGGER.debug("No default constructor available in class " + fieldClass.getName() + ", ignoring exception", e); - } - } - return field; - } - - @Override - public String toString() { - StringBuilder fsBuilder = new StringBuilder(); - fsBuilder.append("\n"); - for (Object field : customNodes.values()) { - fsBuilder.append(field.toString()); - } - fsBuilder.append("\n"); - return fsBuilder.toString(); - } - } - public static class RngDef { enum RngModel { VIRTIO("virtio"); @@ -2493,15 +2636,6 @@ public class LibvirtVMDef { return null; } - public MetadataDef getMetaData() { - MetadataDef o = (MetadataDef) components.get(MetadataDef.class.toString()); - if (o == null) { - o = new MetadataDef(); - addComp(o); - } - return o; - } - @Override public String toString() { StringBuilder vmBuilder = new StringBuilder(); @@ -2513,6 +2647,7 @@ public class LibvirtVMDef { if (_desc != null) { vmBuilder.append("" + _desc + "\n"); } + for (Object o : components.values()) { vmBuilder.append(o.toString()); } diff --git a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtConvertInstanceCommandWrapper.java b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtConvertInstanceCommandWrapper.java index abc408f20f6..93895349a6e 100644 --- a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtConvertInstanceCommandWrapper.java +++ b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtConvertInstanceCommandWrapper.java @@ -20,6 +20,7 @@ package com.cloud.hypervisor.kvm.resource.wrapper; import java.net.URLEncoder; import java.nio.charset.Charset; +import java.util.Arrays; import java.util.List; import java.util.UUID; @@ -57,11 +58,13 @@ public class LibvirtConvertInstanceCommandWrapper extends CommandWrapper 1) { @@ -210,17 +215,18 @@ public class LibvirtConvertInstanceCommandWrapper extends CommandWrapper separatedArgs = Arrays.asList(extraParams.split(" ")); + int i = 0; + while (i < separatedArgs.size()) { + String current = separatedArgs.get(i); + String next = (i + 1) < separatedArgs.size() ? separatedArgs.get(i + 1) : null; + if (next == null || next.startsWith("-")) { + script.add(current); + i = i + 1; + } else { + script.add(current, next); + i = i + 2; + } + } + } + protected String encodeUsername(String username) { return URLEncoder.encode(username, Charset.defaultCharset()); } diff --git a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtDeleteVMSnapshotCommandWrapper.java b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtDeleteVMSnapshotCommandWrapper.java index 58a74d6e0f6..9f1b264ff71 100644 --- a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtDeleteVMSnapshotCommandWrapper.java +++ b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtDeleteVMSnapshotCommandWrapper.java @@ -40,6 +40,7 @@ import com.cloud.resource.CommandWrapper; import com.cloud.resource.ResourceWrapper; import com.cloud.storage.Storage.ImageFormat; import com.cloud.storage.Volume; +import com.cloud.utils.StringUtils; import com.cloud.utils.script.Script; @ResourceWrapper(handles = DeleteVMSnapshotCommand.class) @@ -104,7 +105,7 @@ public final class LibvirtDeleteVMSnapshotCommandWrapper extends CommandWrapper< commands.add(new String[]{Script.getExecutableAbsolutePath("awk"), "-F", " ", "{print $2}"}); commands.add(new String[]{Script.getExecutableAbsolutePath("grep"), "^" + sanitizeBashCommandArgument(cmd.getTarget().getSnapshotName()) + "$"}); String qemu_img_snapshot = Script.executePipedCommands(commands, 0).second(); - if (qemu_img_snapshot == null) { + if (StringUtils.isEmpty(qemu_img_snapshot)) { logger.info("Cannot find snapshot " + cmd.getTarget().getSnapshotName() + " in file " + rootDisk.getPath() + ", return true"); return new DeleteVMSnapshotAnswer(cmd, cmd.getVolumeTOs()); } diff --git a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtImportConvertedInstanceCommandWrapper.java b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtImportConvertedInstanceCommandWrapper.java index 0eec15cf733..5602da15679 100644 --- a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtImportConvertedInstanceCommandWrapper.java +++ b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtImportConvertedInstanceCommandWrapper.java @@ -67,6 +67,7 @@ public class LibvirtImportConvertedInstanceCommandWrapper extends CommandWrapper List destinationStoragePools = cmd.getDestinationStoragePools(); DataStoreTO conversionTemporaryLocation = cmd.getConversionTemporaryLocation(); final String temporaryConvertUuid = cmd.getTemporaryConvertUuid(); + final boolean forceConvertToPool = cmd.isForceConvertToPool(); final KVMStoragePoolManager storagePoolMgr = serverResource.getStoragePoolMgr(); KVMStoragePool temporaryStoragePool = getTemporaryStoragePool(conversionTemporaryLocation, storagePoolMgr); @@ -80,13 +81,18 @@ public class LibvirtImportConvertedInstanceCommandWrapper extends CommandWrapper getTemporaryDisksWithPrefixFromTemporaryPool(temporaryStoragePool, temporaryConvertPath, temporaryConvertUuid) : getTemporaryDisksFromParsedXml(temporaryStoragePool, xmlParser, convertedBasePath); - List destinationDisks = moveTemporaryDisksToDestination(temporaryDisks, - destinationStoragePools, storagePoolMgr); - - cleanupDisksAndDomainFromTemporaryLocation(temporaryDisks, temporaryStoragePool, temporaryConvertUuid); + List disks = null; + if (forceConvertToPool) { + // Force flag to use the conversion path, no need to move disks + disks = temporaryDisks; + } else { + disks = moveTemporaryDisksToDestination(temporaryDisks, + destinationStoragePools, storagePoolMgr); + cleanupDisksAndDomainFromTemporaryLocation(temporaryDisks, temporaryStoragePool, temporaryConvertUuid); + } UnmanagedInstanceTO convertedInstanceTO = getConvertedUnmanagedInstance(temporaryConvertUuid, - destinationDisks, xmlParser); + disks, xmlParser); return new ImportConvertedInstanceAnswer(cmd, convertedInstanceTO); } catch (Exception e) { String error = String.format("Error converting instance %s from %s, due to: %s", diff --git a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRestoreBackupCommandWrapper.java b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRestoreBackupCommandWrapper.java index 0e5091ebcf4..fd94013dd50 100644 --- a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRestoreBackupCommandWrapper.java +++ b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRestoreBackupCommandWrapper.java @@ -21,15 +21,25 @@ package com.cloud.hypervisor.kvm.resource.wrapper; import com.cloud.agent.api.Answer; import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource; +import com.cloud.hypervisor.kvm.storage.KVMPhysicalDisk; +import com.cloud.hypervisor.kvm.storage.KVMStoragePool; +import com.cloud.hypervisor.kvm.storage.KVMStoragePoolManager; import com.cloud.resource.CommandWrapper; import com.cloud.resource.ResourceWrapper; +import com.cloud.storage.Storage; import com.cloud.utils.Pair; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.script.Script; import com.cloud.vm.VirtualMachine; import org.apache.cloudstack.backup.BackupAnswer; import org.apache.cloudstack.backup.RestoreBackupCommand; +import org.apache.cloudstack.storage.to.PrimaryDataStoreTO; +import org.apache.cloudstack.utils.qemu.QemuImg; +import org.apache.cloudstack.utils.qemu.QemuImgException; +import org.apache.cloudstack.utils.qemu.QemuImgFile; import org.apache.commons.lang3.RandomStringUtils; +import org.apache.commons.lang3.StringUtils; +import org.libvirt.LibvirtException; import java.io.File; import java.io.IOException; @@ -45,7 +55,8 @@ public class LibvirtRestoreBackupCommandWrapper extends CommandWrapper backedVolumeUUIDs = command.getBackupVolumesUUIDs(); + List restoreVolumePools = command.getRestoreVolumePools(); List restoreVolumePaths = command.getRestoreVolumePaths(); String restoreVolumeUuid = command.getRestoreVolumeUUID(); + Integer mountTimeout = command.getMountTimeout() * 1000; + int timeout = command.getWait(); + KVMStoragePoolManager storagePoolMgr = serverResource.getStoragePoolMgr(); String newVolumeId = null; try { + String mountDirectory = mountBackupDirectory(backupRepoAddress, backupRepoType, mountOptions, mountTimeout); if (Objects.isNull(vmExists)) { + PrimaryDataStoreTO volumePool = restoreVolumePools.get(0); String volumePath = restoreVolumePaths.get(0); int lastIndex = volumePath.lastIndexOf("/"); newVolumeId = volumePath.substring(lastIndex + 1); - restoreVolume(backupPath, backupRepoType, backupRepoAddress, volumePath, diskType, restoreVolumeUuid, - new Pair<>(vmName, command.getVmState()), mountOptions); + restoreVolume(storagePoolMgr, backupPath, volumePool, volumePath, diskType, restoreVolumeUuid, + new Pair<>(vmName, command.getVmState()), mountDirectory, timeout); } else if (Boolean.TRUE.equals(vmExists)) { - restoreVolumesOfExistingVM(restoreVolumePaths, backedVolumeUUIDs, backupPath, backupRepoType, backupRepoAddress, mountOptions); + restoreVolumesOfExistingVM(storagePoolMgr, restoreVolumePools, restoreVolumePaths, backedVolumeUUIDs, backupPath, mountDirectory, timeout); } else { - restoreVolumesOfDestroyedVMs(restoreVolumePaths, vmName, backupPath, backupRepoType, backupRepoAddress, mountOptions); + restoreVolumesOfDestroyedVMs(storagePoolMgr, restoreVolumePools, restoreVolumePaths, vmName, backupPath, mountDirectory, timeout); } } catch (CloudRuntimeException e) { - String errorMessage = "Failed to restore backup for VM: " + vmName + "."; - if (e.getMessage() != null && !e.getMessage().isEmpty()) { - errorMessage += " Details: " + e.getMessage(); - } - logger.error(errorMessage); + String errorMessage = e.getMessage() != null ? e.getMessage() : ""; return new BackupAnswer(command, false, errorMessage); } return new BackupAnswer(command, true, newVolumeId); } - private void restoreVolumesOfExistingVM(List restoreVolumePaths, List backedVolumesUUIDs, String backupPath, - String backupRepoType, String backupRepoAddress, String mountOptions) { + private void verifyBackupFile(String backupPath, String volUuid) { + if (!checkBackupPathExists(backupPath)) { + throw new CloudRuntimeException(String.format("Backup file for the volume [%s] does not exist.", volUuid)); + } + if (!checkBackupFileImage(backupPath)) { + throw new CloudRuntimeException(String.format("Backup qcow2 file for the volume [%s] is corrupt.", volUuid)); + } + } + + private void restoreVolumesOfExistingVM(KVMStoragePoolManager storagePoolMgr, List restoreVolumePools, List restoreVolumePaths, List backedVolumesUUIDs, + String backupPath, String mountDirectory, int timeout) { String diskType = "root"; - String mountDirectory = mountBackupDirectory(backupRepoAddress, backupRepoType, mountOptions); try { for (int idx = 0; idx < restoreVolumePaths.size(); idx++) { + PrimaryDataStoreTO restoreVolumePool = restoreVolumePools.get(idx); String restoreVolumePath = restoreVolumePaths.get(idx); String backupVolumeUuid = backedVolumesUUIDs.get(idx); Pair bkpPathAndVolUuid = getBackupPath(mountDirectory, null, backupPath, diskType, backupVolumeUuid); diskType = "datadisk"; - if (!replaceVolumeWithBackup(restoreVolumePath, bkpPathAndVolUuid.first())) { + verifyBackupFile(bkpPathAndVolUuid.first(), bkpPathAndVolUuid.second()); + if (!replaceVolumeWithBackup(storagePoolMgr, restoreVolumePool, restoreVolumePath, bkpPathAndVolUuid.first(), timeout)) { throw new CloudRuntimeException(String.format("Unable to restore contents from the backup volume [%s].", bkpPathAndVolUuid.second())); } } @@ -107,16 +130,16 @@ public class LibvirtRestoreBackupCommandWrapper extends CommandWrapper volumePaths, String vmName, String backupPath, - String backupRepoType, String backupRepoAddress, String mountOptions) { - String mountDirectory = mountBackupDirectory(backupRepoAddress, backupRepoType, mountOptions); + private void restoreVolumesOfDestroyedVMs(KVMStoragePoolManager storagePoolMgr, List volumePools, List volumePaths, String vmName, String backupPath, String mountDirectory, int timeout) { String diskType = "root"; try { for (int i = 0; i < volumePaths.size(); i++) { + PrimaryDataStoreTO volumePool = volumePools.get(i); String volumePath = volumePaths.get(i); Pair bkpPathAndVolUuid = getBackupPath(mountDirectory, volumePath, backupPath, diskType, null); diskType = "datadisk"; - if (!replaceVolumeWithBackup(volumePath, bkpPathAndVolUuid.first())) { + verifyBackupFile(bkpPathAndVolUuid.first(), bkpPathAndVolUuid.second()); + if (!replaceVolumeWithBackup(storagePoolMgr, volumePool, volumePath, bkpPathAndVolUuid.first(), timeout)) { throw new CloudRuntimeException(String.format("Unable to restore contents from the backup volume [%s].", bkpPathAndVolUuid.second())); } } @@ -126,22 +149,20 @@ public class LibvirtRestoreBackupCommandWrapper extends CommandWrapper vmNameAndState, String mountOptions) { - String mountDirectory = mountBackupDirectory(backupRepoAddress, backupRepoType, mountOptions); + private void restoreVolume(KVMStoragePoolManager storagePoolMgr, String backupPath, PrimaryDataStoreTO volumePool, String volumePath, String diskType, String volumeUUID, + Pair vmNameAndState, String mountDirectory, int timeout) { Pair bkpPathAndVolUuid; try { bkpPathAndVolUuid = getBackupPath(mountDirectory, volumePath, backupPath, diskType, volumeUUID); - if (!replaceVolumeWithBackup(volumePath, bkpPathAndVolUuid.first())) { + verifyBackupFile(bkpPathAndVolUuid.first(), bkpPathAndVolUuid.second()); + if (!replaceVolumeWithBackup(storagePoolMgr, volumePool, volumePath, bkpPathAndVolUuid.first(), timeout, true)) { throw new CloudRuntimeException(String.format("Unable to restore contents from the backup volume [%s].", bkpPathAndVolUuid.second())); } if (VirtualMachine.State.Running.equals(vmNameAndState.second())) { - if (!attachVolumeToVm(vmNameAndState.first(), volumePath)) { + if (!attachVolumeToVm(storagePoolMgr, vmNameAndState.first(), volumePool, volumePath)) { throw new CloudRuntimeException(String.format("Failed to attach volume to VM: %s", vmNameAndState.first())); } } - } catch (Exception e) { - throw new CloudRuntimeException("Failed to restore volume", e); } finally { unmountBackupDirectory(mountDirectory); deleteTemporaryDirectory(mountDirectory); @@ -149,35 +170,43 @@ public class LibvirtRestoreBackupCommandWrapper extends CommandWrapper(bkpPath, volUuid); } - private boolean replaceVolumeWithBackup(String volumePath, String backupPath) { - int exitValue = Script.runSimpleBashScriptForExitValue(String.format(RSYNC_COMMAND, backupPath, volumePath)); + private boolean checkBackupFileImage(String backupPath) { + int exitValue = Script.runSimpleBashScriptForExitValue(String.format("qemu-img check %s", backupPath)); return exitValue == 0; } - private boolean attachVolumeToVm(String vmName, String volumePath) { + private boolean checkBackupPathExists(String backupPath) { + int exitValue = Script.runSimpleBashScriptForExitValue(String.format("ls %s", backupPath)); + return exitValue == 0; + } + + private boolean replaceVolumeWithBackup(KVMStoragePoolManager storagePoolMgr, PrimaryDataStoreTO volumePool, String volumePath, String backupPath, int timeout) { + return replaceVolumeWithBackup(storagePoolMgr, volumePool, volumePath, backupPath, timeout, false); + } + + private boolean replaceVolumeWithBackup(KVMStoragePoolManager storagePoolMgr, PrimaryDataStoreTO volumePool, String volumePath, String backupPath, int timeout, boolean createTargetVolume) { + if (volumePool.getPoolType() != Storage.StoragePoolType.RBD) { + int exitValue = Script.runSimpleBashScriptForExitValue(String.format(RSYNC_COMMAND, backupPath, volumePath)); + return exitValue == 0; + } + + return replaceRbdVolumeWithBackup(storagePoolMgr, volumePool, volumePath, backupPath, timeout, createTargetVolume); + } + + private boolean replaceRbdVolumeWithBackup(KVMStoragePoolManager storagePoolMgr, PrimaryDataStoreTO volumePool, String volumePath, String backupPath, int timeout, boolean createTargetVolume) { + KVMStoragePool volumeStoragePool = storagePoolMgr.getStoragePool(volumePool.getPoolType(), volumePool.getUuid()); + QemuImg qemu; + try { + qemu = new QemuImg(timeout * 1000, true, false); + if (!createTargetVolume) { + KVMPhysicalDisk rdbDisk = volumeStoragePool.getPhysicalDisk(volumePath); + logger.debug("Restoring RBD volume: {}", rdbDisk.toString()); + qemu.setSkipTargetVolumeCreation(true); + } + } catch (LibvirtException ex) { + throw new CloudRuntimeException("Failed to create qemu-img command to restore RBD volume with backup", ex); + } + + QemuImgFile srcBackupFile = null; + QemuImgFile destVolumeFile = null; + try { + srcBackupFile = new QemuImgFile(backupPath, QemuImg.PhysicalDiskFormat.QCOW2); + String rbdDestVolumeFile = KVMPhysicalDisk.RBDStringBuilder(volumeStoragePool, volumePath); + destVolumeFile = new QemuImgFile(rbdDestVolumeFile, QemuImg.PhysicalDiskFormat.RAW); + + logger.debug("Starting convert backup {} to RBD volume {}", backupPath, volumePath); + qemu.convert(srcBackupFile, destVolumeFile); + logger.debug("Successfully converted backup {} to RBD volume {}", backupPath, volumePath); + } catch (QemuImgException | LibvirtException e) { + String srcFilename = srcBackupFile != null ? srcBackupFile.getFileName() : null; + String destFilename = destVolumeFile != null ? destVolumeFile.getFileName() : null; + logger.error("Failed to convert backup {} to volume {}, the error was: {}", srcFilename, destFilename, e.getMessage()); + return false; + } + + return true; + } + + private boolean attachVolumeToVm(KVMStoragePoolManager storagePoolMgr, String vmName, PrimaryDataStoreTO volumePool, String volumePath) { String deviceToAttachDiskTo = getDeviceToAttachDisk(vmName); - int exitValue = Script.runSimpleBashScriptForExitValue(String.format(ATTACH_DISK_COMMAND, vmName, volumePath, deviceToAttachDiskTo)); + int exitValue; + if (volumePool.getPoolType() != Storage.StoragePoolType.RBD) { + exitValue = Script.runSimpleBashScriptForExitValue(String.format(ATTACH_QCOW2_DISK_COMMAND, vmName, volumePath, deviceToAttachDiskTo)); + } else { + String xmlForRbdDisk = getXmlForRbdDisk(storagePoolMgr, volumePool, volumePath, deviceToAttachDiskTo); + logger.debug("RBD disk xml to attach: {}", xmlForRbdDisk); + exitValue = Script.runSimpleBashScriptForExitValue(String.format(ATTACH_RBD_DISK_XML_COMMAND, vmName, xmlForRbdDisk)); + } return exitValue == 0; } @@ -214,4 +303,42 @@ public class LibvirtRestoreBackupCommandWrapper extends CommandWrapper\n"); + + diskBuilder.append("\n"); + for (String sourceHost : volumePool.getHost().split(",")) { + diskBuilder.append("\n"); + } + diskBuilder.append("\n"); + String authUserName = null; + final KVMStoragePool primaryPool = storagePoolMgr.getStoragePool(volumePool.getPoolType(), volumePool.getUuid()); + if (primaryPool != null) { + authUserName = primaryPool.getAuthUserName(); + } + if (StringUtils.isNotBlank(authUserName)) { + diskBuilder.append("\n"); + diskBuilder.append("\n"); + diskBuilder.append("\n"); + } + diskBuilder.append("\n"); + diskBuilder.append("\n"); + return diskBuilder.toString(); + } } diff --git a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtTakeBackupCommandWrapper.java b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtTakeBackupCommandWrapper.java index c7a67080fbf..11fa605908a 100644 --- a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtTakeBackupCommandWrapper.java +++ b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtTakeBackupCommandWrapper.java @@ -22,12 +22,17 @@ package com.cloud.hypervisor.kvm.resource.wrapper; import com.amazonaws.util.CollectionUtils; import com.cloud.agent.api.Answer; import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource; +import com.cloud.hypervisor.kvm.storage.KVMPhysicalDisk; +import com.cloud.hypervisor.kvm.storage.KVMStoragePool; +import com.cloud.hypervisor.kvm.storage.KVMStoragePoolManager; import com.cloud.resource.CommandWrapper; import com.cloud.resource.ResourceWrapper; +import com.cloud.storage.Storage; import com.cloud.utils.Pair; import com.cloud.utils.script.Script; import org.apache.cloudstack.backup.BackupAnswer; import org.apache.cloudstack.backup.TakeBackupCommand; +import org.apache.cloudstack.storage.to.PrimaryDataStoreTO; import java.util.ArrayList; import java.util.Arrays; @@ -44,7 +49,24 @@ public class LibvirtTakeBackupCommandWrapper extends CommandWrapper diskPaths = command.getVolumePaths(); + List volumePools = command.getVolumePools(); + final List volumePaths = command.getVolumePaths(); + KVMStoragePoolManager storagePoolMgr = libvirtComputingResource.getStoragePoolMgr(); + + List diskPaths = new ArrayList<>(); + if (Objects.nonNull(volumePaths)) { + for (int idx = 0; idx < volumePaths.size(); idx++) { + PrimaryDataStoreTO volumePool = volumePools.get(idx); + String volumePath = volumePaths.get(idx); + if (volumePool.getPoolType() != Storage.StoragePoolType.RBD) { + diskPaths.add(volumePath); + } else { + KVMStoragePool volumeStoragePool = storagePoolMgr.getStoragePool(volumePool.getPoolType(), volumePool.getUuid()); + String rbdDestVolumeFile = KVMPhysicalDisk.RBDStringBuilder(volumeStoragePool, volumePath); + diskPaths.add(rbdDestVolumeFile); + } + } + } List commands = new ArrayList<>(); commands.add(new String[]{ @@ -56,7 +78,7 @@ public class LibvirtTakeBackupCommandWrapper extends CommandWrapper result = Script.executePipedCommands(commands, libvirtComputingResource.getCmdsTimeout()); diff --git a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtUnmanageInstanceCommandWrapper.java b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtUnmanageInstanceCommandWrapper.java new file mode 100644 index 00000000000..33ad274b8d1 --- /dev/null +++ b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtUnmanageInstanceCommandWrapper.java @@ -0,0 +1,174 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package com.cloud.hypervisor.kvm.resource.wrapper; + +import java.io.IOException; +import java.io.InputStream; +import java.io.StringWriter; +import java.net.URISyntaxException; +import java.nio.charset.StandardCharsets; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; +import javax.xml.xpath.XPath; +import javax.xml.xpath.XPathConstants; +import javax.xml.xpath.XPathExpressionException; +import javax.xml.xpath.XPathFactory; + +import org.apache.cloudstack.utils.security.ParserUtils; +import org.apache.commons.io.IOUtils; +import org.libvirt.Connect; +import org.libvirt.Domain; +import org.libvirt.LibvirtException; +import org.w3c.dom.Document; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import org.xml.sax.SAXException; + +import com.cloud.agent.api.Answer; +import com.cloud.agent.api.UnmanageInstanceAnswer; +import com.cloud.agent.api.UnmanageInstanceCommand; +import com.cloud.agent.api.to.VirtualMachineTO; +import com.cloud.exception.InternalErrorException; +import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource; +import com.cloud.hypervisor.kvm.resource.LibvirtKvmAgentHook; +import com.cloud.hypervisor.kvm.resource.LibvirtVMDef; +import com.cloud.resource.CommandWrapper; +import com.cloud.resource.ResourceWrapper; + +@ResourceWrapper(handles = UnmanageInstanceCommand.class) +public final class LibvirtUnmanageInstanceCommandWrapper extends CommandWrapper { + + + @Override + public Answer execute(final UnmanageInstanceCommand command, final LibvirtComputingResource libvirtComputingResource) { + String instanceName = command.getInstanceName(); + VirtualMachineTO vmSpec = command.getVm(); + final LibvirtUtilitiesHelper libvirtUtilitiesHelper = libvirtComputingResource.getLibvirtUtilitiesHelper(); + logger.debug("Attempting to unmanage KVM instance: {}", instanceName); + Domain dom = null; + Connect conn = null; + String vmFinalSpecification; + try { + if (vmSpec == null) { + conn = libvirtUtilitiesHelper.getConnectionByVmName(instanceName); + dom = conn.domainLookupByName(instanceName); + vmFinalSpecification = dom.getXMLDesc(1); + if (command.isConfigDriveAttached()) { + vmFinalSpecification = cleanupConfigDrive(vmFinalSpecification, instanceName); + } + } else { + // define domain using reconstructed vmSpec + logger.debug("Unmanaging Stopped KVM instance: {}", instanceName); + LibvirtVMDef vm = libvirtComputingResource.createVMFromSpec(vmSpec); + libvirtComputingResource.createVbd(conn, vmSpec, instanceName, vm); + conn = libvirtUtilitiesHelper.getConnectionByType(vm.getHvsType()); + String vmInitialSpecification = vm.toString(); + vmFinalSpecification = performXmlTransformHook(vmInitialSpecification, libvirtComputingResource); + } + conn.domainDefineXML(vmFinalSpecification).free(); + logger.debug("Successfully unmanaged KVM instance: {} with domain XML: {}", instanceName, vmFinalSpecification); + return new UnmanageInstanceAnswer(command, true, "Successfully unmanaged"); + } catch (final LibvirtException e) { + logger.error("LibvirtException occurred during unmanaging instance: {} ", instanceName, e); + return new UnmanageInstanceAnswer(command, false, e.getMessage()); + } catch (final IOException + | ParserConfigurationException + | SAXException + | TransformerException + | XPathExpressionException + | InternalErrorException + | URISyntaxException e) { + + logger.error("Failed to unmanage Instance: {}.", instanceName, e); + return new UnmanageInstanceAnswer(command, false, e.getMessage()); + } finally { + if (dom != null) { + try { + dom.free(); + } catch (LibvirtException e) { + logger.error("Ignore libvirt error on free.", e); + } + } + } + } + + String cleanupConfigDrive(String domainXML, String instanceName) throws ParserConfigurationException, IOException, SAXException, XPathExpressionException, TransformerException { + String isoName = "/" + instanceName + ".iso"; + DocumentBuilderFactory docFactory = ParserUtils.getSaferDocumentBuilderFactory(); + DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); + Document document; + try (InputStream inputStream = IOUtils.toInputStream(domainXML, StandardCharsets.UTF_8)) { + document = docBuilder.parse(inputStream); + } + XPathFactory xPathFactory = XPathFactory.newInstance(); + XPath xpath = xPathFactory.newXPath(); + + // Find all elements with source file containing instanceName.iso + String expression = String.format("//disk[@device='cdrom'][source/@file[contains(., '%s')]]", isoName); + NodeList cdromDisks = (NodeList) xpath.evaluate(expression, document, XPathConstants.NODESET); + + // If nothing matched, return original XML + if (cdromDisks == null || cdromDisks.getLength() == 0) { + logger.debug("No config drive found in domain XML for Instance: {}", instanceName); + return domainXML; + } + + // Remove all matched config drive disks + for (int i = 0; i < cdromDisks.getLength(); i++) { + Node diskNode = cdromDisks.item(i); + if (diskNode != null && diskNode.getParentNode() != null) { + diskNode.getParentNode().removeChild(diskNode); + } + } + logger.debug("Removed {} config drive ISO CD-ROM entries for instance: {}", cdromDisks.getLength(), instanceName); + + TransformerFactory transformerFactory = ParserUtils.getSaferTransformerFactory(); + Transformer transformer = transformerFactory.newTransformer(); + DOMSource source = new DOMSource(document); + StringWriter output = new StringWriter(); + StreamResult result = new StreamResult(output); + transformer.transform(source, result); + return output.toString(); + } + + private String performXmlTransformHook(String vmInitialSpecification, final LibvirtComputingResource libvirtComputingResource) { + String vmFinalSpecification; + try { + // if transformer fails, everything must go as it's just skipped. + LibvirtKvmAgentHook t = libvirtComputingResource.getTransformer(); + vmFinalSpecification = (String) t.handle(vmInitialSpecification); + if (null == vmFinalSpecification) { + logger.warn("Libvirt XML transformer returned NULL, will use XML specification unchanged."); + vmFinalSpecification = vmInitialSpecification; + } + } catch(Exception e) { + logger.warn("Exception occurred when handling LibVirt XML transformer hook: {}", e); + vmFinalSpecification = vmInitialSpecification; + } + return vmFinalSpecification; + } +} diff --git a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/storage/KVMStorageProcessor.java b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/storage/KVMStorageProcessor.java index 3d95157d45c..7b56ba47db0 100644 --- a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/storage/KVMStorageProcessor.java +++ b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/storage/KVMStorageProcessor.java @@ -62,7 +62,7 @@ import org.apache.cloudstack.direct.download.DirectTemplateDownloader; import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotInfo; import org.apache.cloudstack.storage.command.AttachAnswer; import org.apache.cloudstack.storage.command.AttachCommand; -import org.apache.cloudstack.storage.command.CheckDataStoreStoragePolicyComplainceCommand; +import org.apache.cloudstack.storage.command.CheckDataStoreStoragePolicyComplianceCommand; import org.apache.cloudstack.storage.command.CopyCmdAnswer; import org.apache.cloudstack.storage.command.CopyCommand; import org.apache.cloudstack.storage.command.CreateObjectAnswer; @@ -364,16 +364,7 @@ public class KVMStorageProcessor implements StorageProcessor { final TemplateObjectTO newTemplate = new TemplateObjectTO(); newTemplate.setPath(primaryVol.getName()); newTemplate.setSize(primaryVol.getSize()); - - if(List.of( - StoragePoolType.RBD, - StoragePoolType.PowerFlex, - StoragePoolType.Linstor, - StoragePoolType.FiberChannel).contains(primaryPool.getType())) { - newTemplate.setFormat(ImageFormat.RAW); - } else { - newTemplate.setFormat(ImageFormat.QCOW2); - } + newTemplate.setFormat(getFormat(primaryPool.getType())); data = newTemplate; } else if (destData.getObjectType() == DataObjectType.VOLUME) { final VolumeObjectTO volumeObjectTO = new VolumeObjectTO(); @@ -654,7 +645,7 @@ public class KVMStorageProcessor implements StorageProcessor { try { final String volumeName = UUID.randomUUID().toString(); - final String destVolumeName = volumeName + "." + destFormat.getFileExtension(); + final String destVolumeName = volumeName + "." + ImageFormat.QCOW2.getFileExtension(); final KVMPhysicalDisk volume = storagePoolMgr.getPhysicalDisk(primaryStore.getPoolType(), primaryStore.getUuid(), srcVolumePath); volume.setFormat(PhysicalDiskFormat.valueOf(srcFormat.toString())); @@ -2990,7 +2981,7 @@ public class KVMStorageProcessor implements StorageProcessor { final VolumeObjectTO srcVol = (VolumeObjectTO)srcData; final VolumeObjectTO destVol = (VolumeObjectTO)destData; final ImageFormat srcFormat = srcVol.getFormat(); - final ImageFormat destFormat = destVol.getFormat(); + ImageFormat destFormat = destVol.getFormat(); final DataStoreTO srcStore = srcData.getDataStore(); final DataStoreTO destStore = destData.getDataStore(); final PrimaryDataStoreTO srcPrimaryStore = (PrimaryDataStoreTO)srcStore; @@ -3025,33 +3016,35 @@ public class KVMStorageProcessor implements StorageProcessor { volume.setFormat(PhysicalDiskFormat.valueOf(srcFormat.toString())); volume.setDispName(srcVol.getName()); volume.setVmName(srcVol.getVmName()); - - String destVolumeName = null; + KVMPhysicalDisk newVolume; + String destVolumeName; + destPool = storagePoolMgr.getStoragePool(destPrimaryStore.getPoolType(), destPrimaryStore.getUuid()); if (destPrimaryStore.isManaged()) { if (!storagePoolMgr.connectPhysicalDisk(destPrimaryStore.getPoolType(), destPrimaryStore.getUuid(), destVolumePath, destPrimaryStore.getDetails())) { logger.warn("Failed to connect dest volume {}, in storage pool {}", destVol, destPrimaryStore); } destVolumeName = derivePath(destPrimaryStore, destData, destPrimaryStore.getDetails()); } else { + PhysicalDiskFormat destPoolDefaultFormat = destPool.getDefaultFormat(); + destFormat = getFormat(destPoolDefaultFormat); final String volumeName = UUID.randomUUID().toString(); destVolumeName = volumeName + "." + destFormat.getFileExtension(); // Update path in the command for reconciliation - if (destData.getPath() == null) { + if (StringUtils.isBlank(destVolumePath)) { ((VolumeObjectTO) destData).setPath(destVolumeName); } } - destPool = storagePoolMgr.getStoragePool(destPrimaryStore.getPoolType(), destPrimaryStore.getUuid()); try { Volume.Type volumeType = srcVol.getVolumeType(); resource.createOrUpdateLogFileForCommand(cmd, Command.State.PROCESSING_IN_BACKEND); if (srcVol.getPassphrase() != null && (Volume.Type.ROOT.equals(volumeType) || Volume.Type.DATADISK.equals(volumeType))) { volume.setQemuEncryptFormat(QemuObject.EncryptFormat.LUKS); - storagePoolMgr.copyPhysicalDisk(volume, destVolumeName, destPool, cmd.getWaitInMillSeconds(), srcVol.getPassphrase(), destVol.getPassphrase(), srcVol.getProvisioningType()); + newVolume = storagePoolMgr.copyPhysicalDisk(volume, destVolumeName, destPool, cmd.getWaitInMillSeconds(), srcVol.getPassphrase(), destVol.getPassphrase(), srcVol.getProvisioningType()); } else { - storagePoolMgr.copyPhysicalDisk(volume, destVolumeName, destPool, cmd.getWaitInMillSeconds()); + newVolume = storagePoolMgr.copyPhysicalDisk(volume, destVolumeName, destPool, cmd.getWaitInMillSeconds()); } resource.createOrUpdateLogFileForCommand(cmd, Command.State.COMPLETED); } catch (Exception e) { // Any exceptions while copying the disk, should send failed answer with the error message @@ -3071,9 +3064,13 @@ public class KVMStorageProcessor implements StorageProcessor { } final VolumeObjectTO newVol = new VolumeObjectTO(); - String path = destPrimaryStore.isManaged() ? destVolumeName : destVolumePath + File.separator + destVolumeName; + String path = destVolumeName; + if (!destPrimaryStore.isManaged() && StringUtils.isNotBlank(destVolumePath)) { + path = destVolumePath + File.separator + destVolumeName; + } newVol.setPath(path); - newVol.setFormat(destFormat); + ImageFormat newVolumeFormat = getFormat(newVolume.getFormat()); + newVol.setFormat(newVolumeFormat); newVol.setEncryptFormat(destVol.getEncryptFormat()); return new CopyCmdAnswer(newVol); } catch (final CloudRuntimeException e) { @@ -3085,6 +3082,26 @@ public class KVMStorageProcessor implements StorageProcessor { } } + private Storage.ImageFormat getFormat(PhysicalDiskFormat format) { + if (format == null) { + return null; + } + + return ImageFormat.valueOf(format.toString().toUpperCase()); + } + + private Storage.ImageFormat getFormat(StoragePoolType poolType) { + if(List.of( + StoragePoolType.RBD, + StoragePoolType.PowerFlex, + StoragePoolType.Linstor, + StoragePoolType.FiberChannel).contains(poolType)) { + return ImageFormat.RAW; + } else { + return ImageFormat.QCOW2; + } + } + /** * True if location exists */ @@ -3116,8 +3133,8 @@ public class KVMStorageProcessor implements StorageProcessor { } @Override - public Answer checkDataStoreStoragePolicyCompliance(CheckDataStoreStoragePolicyComplainceCommand cmd) { - logger.info("'CheckDataStoreStoragePolicyComplainceCommand' not currently applicable for KVMStorageProcessor"); + public Answer checkDataStoreStoragePolicyCompliance(CheckDataStoreStoragePolicyComplianceCommand cmd) { + logger.info("'CheckDataStoreStoragePolicyComplianceCommand' not currently applicable for KVMStorageProcessor"); return new Answer(cmd,false,"Not currently applicable for KVMStorageProcessor"); } diff --git a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/storage/LibvirtStorageAdaptor.java b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/storage/LibvirtStorageAdaptor.java index d5119ea55b7..e8924ecf5eb 100644 --- a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/storage/LibvirtStorageAdaptor.java +++ b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/storage/LibvirtStorageAdaptor.java @@ -79,6 +79,7 @@ import com.cloud.storage.Storage.StoragePoolType; import com.cloud.storage.StorageLayer; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.script.Script; +import com.cloud.utils.storage.TemplateDownloaderUtil; public class LibvirtStorageAdaptor implements StorageAdaptor { protected Logger logger = LogManager.getLogger(getClass()); @@ -172,37 +173,11 @@ public class LibvirtStorageAdaptor implements StorageAdaptor { return null; } - /** - * Checks if downloaded template is extractable - * @return true if it should be extracted, false if not - */ - public static boolean isTemplateExtractable(String templatePath) { - String type = Script.runSimpleBashScript("file " + templatePath + " | awk -F' ' '{print $2}'"); - return type.equalsIgnoreCase("bzip2") || type.equalsIgnoreCase("gzip") || type.equalsIgnoreCase("zip"); - } - - /** - * Return extract command to execute given downloaded file - * @param downloadedTemplateFile - * @param templateUuid - */ - public static String getExtractCommandForDownloadedFile(String downloadedTemplateFile, String templateUuid) { - if (downloadedTemplateFile.endsWith(".zip")) { - return "unzip -p " + downloadedTemplateFile + " | cat > " + templateUuid; - } else if (downloadedTemplateFile.endsWith(".bz2")) { - return "bunzip2 -c " + downloadedTemplateFile + " > " + templateUuid; - } else if (downloadedTemplateFile.endsWith(".gz")) { - return "gunzip -c " + downloadedTemplateFile + " > " + templateUuid; - } else { - throw new CloudRuntimeException("Unable to extract template " + downloadedTemplateFile); - } - } - /** * Extract downloaded template into installPath, remove compressed file */ public static void extractDownloadedTemplate(String downloadedTemplateFile, KVMStoragePool destPool, String destinationFile) { - String extractCommand = getExtractCommandForDownloadedFile(downloadedTemplateFile, destinationFile); + String extractCommand = TemplateDownloaderUtil.getExtractCommandForDownloadedFile(downloadedTemplateFile, destinationFile); Script.runSimpleBashScript(extractCommand); Script.runSimpleBashScript("rm -f " + downloadedTemplateFile); } @@ -221,7 +196,7 @@ public class LibvirtStorageAdaptor implements StorageAdaptor { if (destPool.getType() == StoragePoolType.NetworkFilesystem || destPool.getType() == StoragePoolType.Filesystem || destPool.getType() == StoragePoolType.SharedMountPoint) { - if (!Storage.ImageFormat.ISO.equals(format) && isTemplateExtractable(templateFilePath)) { + if (!Storage.ImageFormat.ISO.equals(format) && TemplateDownloaderUtil.isTemplateExtractable(templateFilePath)) { extractDownloadedTemplate(templateFilePath, destPool, destinationFile); } else { Script.runSimpleBashScript("mv " + templateFilePath + " " + destinationFile); @@ -1116,7 +1091,7 @@ public class LibvirtStorageAdaptor implements StorageAdaptor { // make room for encryption header on raw format, use LUKS if (format == PhysicalDiskFormat.RAW) { - destFile.setSize(destFile.getSize() - (16<<20)); + destFile.setSize(destFile.getSize() - (16 << 20)); destFile.setFormat(PhysicalDiskFormat.LUKS); } @@ -1593,7 +1568,7 @@ public class LibvirtStorageAdaptor implements StorageAdaptor { String sourcePath = disk.getPath(); KVMPhysicalDisk newDisk; - logger.debug("copyPhysicalDisk: disk size:" + toHumanReadableSize(disk.getSize()) + ", virtualsize:" + toHumanReadableSize(disk.getVirtualSize())+" format:"+disk.getFormat()); + logger.debug("copyPhysicalDisk: disk size:{}, virtualsize:{} format:{}", toHumanReadableSize(disk.getSize()), toHumanReadableSize(disk.getVirtualSize()), disk.getFormat()); if (destPool.getType() != StoragePoolType.RBD) { if (disk.getFormat() == PhysicalDiskFormat.TAR) { newDisk = destPool.createPhysicalDisk(name, PhysicalDiskFormat.DIR, Storage.ProvisioningType.THIN, disk.getVirtualSize(), null); diff --git a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/storage/MultipathSCSIAdapterBase.java b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/storage/MultipathSCSIAdapterBase.java index 7ba29ffc26e..514e412559c 100644 --- a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/storage/MultipathSCSIAdapterBase.java +++ b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/storage/MultipathSCSIAdapterBase.java @@ -423,24 +423,6 @@ public abstract class MultipathSCSIAdapterBase implements StorageAdaptor { throw new UnsupportedOperationException("Unimplemented method 'createPhysicalDisk'"); } - boolean isTemplateExtractable(String templatePath) { - ScriptResult result = runScript("file", 5000L, templatePath, "| awk -F' ' '{print $2}'"); - String type = result.getResult(); - return type.equalsIgnoreCase("bzip2") || type.equalsIgnoreCase("gzip") || type.equalsIgnoreCase("zip"); - } - - String getExtractCommandForDownloadedFile(String downloadedTemplateFile, String templateFile) { - if (downloadedTemplateFile.endsWith(".zip")) { - return "unzip -p " + downloadedTemplateFile + " | cat > " + templateFile; - } else if (downloadedTemplateFile.endsWith(".bz2")) { - return "bunzip2 -c " + downloadedTemplateFile + " > " + templateFile; - } else if (downloadedTemplateFile.endsWith(".gz")) { - return "gunzip -c " + downloadedTemplateFile + " > " + templateFile; - } else { - throw new CloudRuntimeException("Unable to extract template " + downloadedTemplateFile); - } - } - boolean waitForDiskToBecomeAvailable(AddressInfo address, KVMStoragePool pool, long waitTimeInSec) { LOGGER.debug("Waiting for the volume with id: " + address.getPath() + " of the storage pool: " + pool.getUuid() + " to become available for " + waitTimeInSec + " secs"); diff --git a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/storage/ScaleIOStorageAdaptor.java b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/storage/ScaleIOStorageAdaptor.java index efa8024a34b..e336e0e5a54 100644 --- a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/storage/ScaleIOStorageAdaptor.java +++ b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/storage/ScaleIOStorageAdaptor.java @@ -53,6 +53,8 @@ import com.cloud.utils.Ternary; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.script.OutputInterpreter; import com.cloud.utils.script.Script; +import com.cloud.utils.storage.TemplateDownloaderUtil; + import org.apache.commons.lang3.StringUtils; public class ScaleIOStorageAdaptor implements StorageAdaptor { @@ -572,10 +574,10 @@ public class ScaleIOStorageAdaptor implements StorageAdaptor { throw new CloudRuntimeException("Failed to find the disk: " + destTemplatePath + " of the storage pool: " + destPool.getUuid()); } - if (isTemplateExtractable(templateFilePath)) { + if (TemplateDownloaderUtil.isTemplateExtractable(templateFilePath)) { srcTemplateFilePath = sourceFile.getParent() + "/" + UUID.randomUUID().toString(); logger.debug("Extract the downloaded template " + templateFilePath + " to " + srcTemplateFilePath); - String extractCommand = getExtractCommandForDownloadedFile(templateFilePath, srcTemplateFilePath); + String extractCommand = TemplateDownloaderUtil.getExtractCommandForDownloadedFile(templateFilePath, srcTemplateFilePath); Script.runSimpleBashScript(extractCommand); Script.runSimpleBashScript("rm -f " + templateFilePath); } @@ -611,23 +613,6 @@ public class ScaleIOStorageAdaptor implements StorageAdaptor { return destDisk; } - private boolean isTemplateExtractable(String templatePath) { - String type = Script.runSimpleBashScript("file " + templatePath + " | awk -F' ' '{print $2}'"); - return type.equalsIgnoreCase("bzip2") || type.equalsIgnoreCase("gzip") || type.equalsIgnoreCase("zip"); - } - - private String getExtractCommandForDownloadedFile(String downloadedTemplateFile, String templateFile) { - if (downloadedTemplateFile.endsWith(".zip")) { - return "unzip -p " + downloadedTemplateFile + " | cat > " + templateFile; - } else if (downloadedTemplateFile.endsWith(".bz2")) { - return "bunzip2 -c " + downloadedTemplateFile + " > " + templateFile; - } else if (downloadedTemplateFile.endsWith(".gz")) { - return "gunzip -c " + downloadedTemplateFile + " > " + templateFile; - } else { - throw new CloudRuntimeException("Unable to extract template " + downloadedTemplateFile); - } - } - public void resizeQcow2ToVolume(String volumePath, QemuImageOptions options, List objects, Integer timeout) throws QemuImgException, LibvirtException { long rawSizeBytes = getPhysicalDiskSize(volumePath); long usableSizeBytes = getUsableBytesFromRawBytes(rawSizeBytes); diff --git a/plugins/hypervisors/kvm/src/main/java/org/apache/cloudstack/utils/qemu/QemuImg.java b/plugins/hypervisors/kvm/src/main/java/org/apache/cloudstack/utils/qemu/QemuImg.java index beba0856241..0a8ea27cd49 100644 --- a/plugins/hypervisors/kvm/src/main/java/org/apache/cloudstack/utils/qemu/QemuImg.java +++ b/plugins/hypervisors/kvm/src/main/java/org/apache/cloudstack/utils/qemu/QemuImg.java @@ -61,6 +61,7 @@ public class QemuImg { private String cloudQemuImgPath = "cloud-qemu-img"; private int timeout; private boolean skipZero = false; + private boolean skipTargetVolumeCreation = false; private boolean noCache = false; private long version; @@ -435,6 +436,8 @@ public class QemuImg { // with target-is-zero we skip zeros in 1M chunks for compatibility script.add("-S"); script.add("1M"); + } else if (skipTargetVolumeCreation) { + script.add("-n"); } script.add("-O"); @@ -881,6 +884,10 @@ public class QemuImg { this.skipZero = skipZero; } + public void setSkipTargetVolumeCreation(boolean skipTargetVolumeCreation) { + this.skipTargetVolumeCreation = skipTargetVolumeCreation; + } + public boolean supportsImageFormat(QemuImg.PhysicalDiskFormat format) { final Script s = new Script(_qemuImgPath, timeout); s.add("--help"); diff --git a/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtConvertInstanceCommandWrapperTest.java b/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtConvertInstanceCommandWrapperTest.java index b369cf25f3d..4d55ac2bc73 100644 --- a/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtConvertInstanceCommandWrapperTest.java +++ b/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtConvertInstanceCommandWrapperTest.java @@ -128,6 +128,7 @@ public class LibvirtConvertInstanceCommandWrapperTest { Mockito.when(cmd.getWait()).thenReturn(14400); Mockito.when(cmd.getConversionTemporaryLocation()).thenReturn(secondaryDataStore); Mockito.when(cmd.getCheckConversionSupport()).thenReturn(checkConversionSupport); + Mockito.when(cmd.getOriginalVMName()).thenReturn(vmName); return cmd; } @@ -166,8 +167,26 @@ public class LibvirtConvertInstanceCommandWrapperTest { Answer answer = convertInstanceCommandWrapper.execute(cmd, libvirtComputingResourceMock); Assert.assertFalse(answer.getResult()); - Mockito.verify(convertInstanceCommandWrapper).performInstanceConversion(Mockito.anyString(), - Mockito.anyString(), Mockito.anyString(), Mockito.anyLong(), Mockito.anyBoolean()); + Mockito.verify(convertInstanceCommandWrapper).performInstanceConversion(Mockito.anyString(), Mockito.anyString(), + Mockito.anyString(), Mockito.anyString(), Mockito.anyLong(), Mockito.anyBoolean(), Mockito.nullable(String.class), Mockito.any(LibvirtComputingResource.class)); } } + + @Test + public void testAddExtraParamsToScriptSameKeysAndValues() { + Script script = Mockito.mock(Script.class); + String extraParams = "--mac 00:0c:29:e6:3d:9d:ip:192.168.0.89,192.168.0.1,24,192.168.0.254"; + convertInstanceCommandWrapper.addExtraParamsToScript(extraParams, script); + Mockito.verify(script).add("--mac", "00:0c:29:e6:3d:9d:ip:192.168.0.89,192.168.0.1,24,192.168.0.254"); + } + + @Test + public void testAddExtraParamsToScriptDifferentArgs() { + Script script = Mockito.mock(Script.class); + String extraParams = "--mac 00:0c:29:e6:3d:9d:ip:192.168.0.89,192.168.0.1,24,192.168.0.254 -x -v"; + convertInstanceCommandWrapper.addExtraParamsToScript(extraParams, script); + Mockito.verify(script).add("--mac", "00:0c:29:e6:3d:9d:ip:192.168.0.89,192.168.0.1,24,192.168.0.254"); + Mockito.verify(script).add("-x"); + Mockito.verify(script).add("-v"); + } } diff --git a/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRestoreBackupCommandWrapperTest.java b/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRestoreBackupCommandWrapperTest.java new file mode 100644 index 00000000000..7bcd0bf18e6 --- /dev/null +++ b/plugins/hypervisors/kvm/src/test/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRestoreBackupCommandWrapperTest.java @@ -0,0 +1,526 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.hypervisor.kvm.resource.wrapper; + +import com.cloud.agent.api.Answer; +import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource; +import com.cloud.utils.script.Script; +import com.cloud.vm.VirtualMachine; +import org.apache.cloudstack.backup.BackupAnswer; +import org.apache.cloudstack.backup.RestoreBackupCommand; +import org.apache.cloudstack.storage.to.PrimaryDataStoreTO; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.MockedStatic; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Arrays; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class LibvirtRestoreBackupCommandWrapperTest { + + private LibvirtRestoreBackupCommandWrapper wrapper; + private LibvirtComputingResource libvirtComputingResource; + private RestoreBackupCommand command; + + @Before + public void setUp() { + wrapper = new LibvirtRestoreBackupCommandWrapper(); + libvirtComputingResource = Mockito.mock(LibvirtComputingResource.class); + command = Mockito.mock(RestoreBackupCommand.class); + } + + @Test + public void testExecuteWithVmExistsNull() throws Exception { + when(command.getVmName()).thenReturn("test-vm"); + when(command.getBackupPath()).thenReturn("backup/path"); + when(command.getBackupRepoAddress()).thenReturn("192.168.1.100:/backup"); + when(command.getBackupRepoType()).thenReturn("nfs"); + when(command.getMountOptions()).thenReturn("rw"); + when(command.isVmExists()).thenReturn(null); + when(command.getDiskType()).thenReturn("root"); + PrimaryDataStoreTO primaryDataStore = Mockito.mock(PrimaryDataStoreTO.class); + when(command.getRestoreVolumePools()).thenReturn(Arrays.asList(primaryDataStore)); + when(command.getRestoreVolumePaths()).thenReturn(Arrays.asList("/var/lib/libvirt/images/volume-123")); + when(command.getRestoreVolumeUUID()).thenReturn("volume-123"); + when(command.getVmState()).thenReturn(VirtualMachine.State.Running); + when(command.getMountTimeout()).thenReturn(30); + + try (MockedStatic filesMock = mockStatic(Files.class)) { + Path tempPath = Mockito.mock(Path.class); + when(tempPath.toString()).thenReturn("/tmp/csbackup.abc123"); + filesMock.when(() -> Files.createTempDirectory(anyString())).thenReturn(tempPath); + + try (MockedStatic + + diff --git a/ui/src/views/compute/backup/FormSchedule.vue b/ui/src/views/compute/backup/FormSchedule.vue index 643ae116916..1833449c3cc 100644 --- a/ui/src/views/compute/backup/FormSchedule.vue +++ b/ui/src/views/compute/backup/FormSchedule.vue @@ -133,7 +133,7 @@ - +