PageRenderTime 27ms CodeModel.GetById 13ms app.highlight 11ms RepoModel.GetById 1ms app.codeStats 0ms

/MyVMPortal/CreateVM.aspx.cs

https://github.com/mwasham/wasvcmgmntapi
C# | 204 lines | 172 code | 31 blank | 1 comment | 20 complexity | 99fe2a1254d939f535e94a06f8e48c20 MD5 | raw file
  1using SMLibrary;
  2using System;
  3using System.Collections.Generic;
  4using System.Configuration;
  5using System.Linq;
  6using System.Text;
  7using System.Web;
  8using System.Web.UI;
  9using System.Web.UI.WebControls;
 10using System.Xml;
 11using System.Xml.Linq;
 12
 13namespace MyVMPortal
 14{
 15    public partial class CreateVM : System.Web.UI.Page
 16    {
 17        private String _StorageAccount = String.Empty;
 18
 19        private String GetStorageAccount()
 20        {
 21            string[] accounts = ConfigurationManager.AppSettings["StorageAccount"].Split(new char[] { ',' });
 22            Random r = new Random(DateTime.Now.Millisecond);
 23            return accounts[r.Next(0, accounts.Length)];
 24        }
 25
 26        async protected void Page_Load(object sender, EventArgs e)
 27        {
 28            if (!Page.IsPostBack)
 29            {
 30                VMManager vmm = GetVMM();
 31                List<String> images = await vmm.GetAzureVMImages();
 32                ddlImages.DataSource = images;
 33                ddlImages.DataBind();
 34
 35                lblStorageAccount.Text = GetStorageAccount();
 36                _StorageAccount = lblStorageAccount.Text;
 37                ViewState["StorageAccount"] = _StorageAccount; 
 38            }
 39            else
 40            {
 41                txtPassword.Attributes["value"] = txtPassword.Text;
 42                _StorageAccount = ViewState["StorageAccount"].ToString();
 43            }
 44
 45            GetQuota();
 46        }
 47
 48        private VMManager GetVMM()
 49        {
 50            return new VMManager(ConfigurationManager.AppSettings["SubcriptionID"], ConfigurationManager.AppSettings["CertificateThumbprint"]);
 51        }
 52
 53        private String GetOSDiskMediaLocation()
 54        {
 55            String osdiskmedialocation = String.Format("https://{0}.blob.core.windows.net/vhds/{1}-OS-{2}.vhd", _StorageAccount, txtVMName.Text, Guid.NewGuid().ToString());
 56            return osdiskmedialocation;
 57        }
 58        private String GetDataDiskMediaLocation()
 59        {
 60            String osdiskmedialocation = String.Format("https://{0}.blob.core.windows.net/vhds/{1}-Data-{2}.vhd", _StorageAccount, txtVMName.Text, Guid.NewGuid().ToString());
 61            return osdiskmedialocation;
 62        }
 63
 64        protected void cmdCreateVMConfig_Click(object sender, EventArgs e)
 65        {
 66            GenerateVMConfig(false);
 67        }
 68        
 69        async public void GenerateVMConfig(bool Create)
 70        {
 71            if (String.IsNullOrEmpty(txtServiceName.Text))
 72            {
 73                lblStatus.Text = "Missing Service Name";
 74                return;
 75            }
 76            if (String.IsNullOrEmpty(txtVMName.Text))
 77            {
 78                lblStatus.Text = "Missing VM Name";
 79                return;
 80            }
 81            if (String.IsNullOrEmpty(txtPassword.Text))
 82            {
 83                lblStatus.Text = "Missing Pasword";
 84                return;
 85            }
 86            if (ValidationHelpers.IsWindowsComputerNameValid(txtVMName.Text) == false)
 87            {
 88                lblStatus.Text = "VM Name is either too long or has invalid characters";
 89                return;
 90            }
 91            if (ValidationHelpers.IsWindowsPasswordValid(txtPassword.Text) == false)
 92            {
 93                lblStatus.Text = "Windows Password does not meet complexity requirements.";
 94                return;
 95            }
 96
 97            lblStatus.Text = "";
 98
 99            VMManager vmm = GetVMM();
100
101            if(await vmm.IsServiceNameAvailable(txtServiceName.Text) == false)
102            {
103                lblStatus.Text = "Service Name is not available. Must be unique";
104                return;
105            }
106
107            XDocument vm = vmm.NewAzureVMConfig(txtVMName.Text, ddlVMSize.Text, ddlImages.Text, GetOSDiskMediaLocation(), true);
108
109            vm = vmm.NewWindowsProvisioningConfig(vm, txtVMName.Text, txtPassword.Text);
110            vm = vmm.NewNetworkConfigurationSet(vm);
111
112            if (chkAddDataDisk.Checked == true)
113            {
114                vm = vmm.AddNewDataDisk(vm, 10, 0, "MyDataDisk", GetDataDiskMediaLocation());
115            }
116            if (chkAddHTTPEndpoint.Checked == true)
117            {
118                vm = vmm.AddNewInputEndpoint(vm, "web", "TCP", 80, 80);
119            }
120            if (chkAddRDPEndpoint.Checked == true)
121            {
122                vm = vmm.AddNewInputEndpoint(vm, "rdp", "TCP", 3389, 3389);
123            }
124
125            var builder = new StringBuilder();
126            var settings = new XmlWriterSettings()
127            {
128                Indent = true
129            };
130            using (var writer = XmlWriter.Create(builder, settings))
131            {
132                vm.WriteTo(writer);
133            }
134
135
136            divXML.Visible = true;
137            lblVMXML.Text = Server.HtmlEncode(builder.ToString());
138
139            tblConfig.Visible = true;
140            cmdCreateVM.Visible = true;
141            cmdCreateVMConfig.Visible = false;
142
143            if (Create == true)
144            {
145                String requestID_cloudService = await vmm.NewAzureCloudService(txtServiceName.Text, "West US", String.Empty);
146
147                OperationResult result = await vmm.PollGetOperationStatus(requestID_cloudService, 5, 120);
148
149                if (result.Status == OperationStatus.Succeeded)
150                {
151                    // VM creation takes too long so we'll check it later
152                    String requestID_createDeployment = await vmm.NewAzureVMDeployment(txtServiceName.Text, txtVMName.Text, String.Empty, vm, null);
153
154                    Response.Redirect("/GetOperationStatus.aspx?requestid=" + requestID_createDeployment);
155                }
156                else
157                {
158                    lblStatus.Text = String.Format("Creating Cloud Service Failed. Message: {0}", result.Message);
159                }
160            }
161        }
162
163        protected void chkAddDataDisk_Click(object sender, EventArgs e)
164        {
165            GenerateVMConfig(false);
166        }
167
168        protected void chkAddRDPEndpoint_Click(object sender, EventArgs e)
169        {
170            GenerateVMConfig(false);
171        }
172
173        protected void chkAddHTTPEndpoint_Click(object sender, EventArgs e)
174        {
175            GenerateVMConfig(false);
176        }
177
178        protected void cmdCreateVM_Click(object sender, EventArgs e)
179        {
180            GenerateVMConfig(true);
181        }
182
183        async protected void GetQuota()
184        {
185            VMManager vmm = GetVMM();
186
187            XDocument subscriptionXML = await vmm.GetAzureSubscription();
188            var quota = (from vm in subscriptionXML.Descendants(vmm.ns + "Subscription")
189                         select new
190                         {
191                             CurrentCoreCount = (string)vm.Element(vmm.ns + "CurrentCoreCount"),
192                             MaxCoreCount = (string)vm.Element(vmm.ns + "MaxCoreCount"),
193                             CurrentHostedServices = (string)vm.Element(vmm.ns + "CurrentHostedServices"),
194                             MaxHostedServices = (string)vm.Element(vmm.ns + "MaxHostedServices")
195                         }).FirstOrDefault();
196
197            lblCoreCountUsed.Text = quota.CurrentCoreCount;
198            lblCoreCountAvailable.Text = quota.MaxCoreCount;
199            lblHostedServicesUsed.Text = quota.CurrentHostedServices;
200            lblHostedServicesAvailable.Text = quota.MaxHostedServices;
201
202        }
203    }
204}