PageRenderTime 46ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

/Resources/Companion/AdminRole/Controllers/ApplicationsController.cs

https://bitbucket.org/zgramana/azure-accelerators-project
C# | 434 lines | 350 code | 42 blank | 42 comment | 36 complexity | b5833f734006b9e6e1730f7b92808e38 MD5 | raw file
Possible License(s): LGPL-2.0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.Mvc;
  6. using WindowsAzureCompanion.VMManagerService;
  7. using Microsoft.WindowsAzure.ServiceRuntime;
  8. using System.Xml;
  9. using System.ServiceModel.Syndication;
  10. using System.Diagnostics;
  11. using System.Xml.Linq;
  12. using System.Collections.Specialized;
  13. using System.IO;
  14. namespace Microsoft.WindowsAzure.Companion.Controllers
  15. {
  16. [HandleError]
  17. public class ApplicationsController : BaseProductsController
  18. {
  19. //
  20. // GET: /Applications/Applications/tabName
  21. [Authorize]
  22. public ActionResult Applications(string id)
  23. {
  24. // Check for error message
  25. string errorMessage = ViewData["ErrorMessage"] as string;
  26. if (!string.IsNullOrEmpty(errorMessage))
  27. {
  28. return RedirectToAction("Error", "Home", new { ErrorMessage = errorMessage });
  29. }
  30. // Set proper tab value
  31. string currentTab = null;
  32. if (!string.IsNullOrEmpty(id))
  33. {
  34. currentTab = id;
  35. }
  36. else if (Request.QueryString["CurrentTab"] != null)
  37. {
  38. currentTab = Request.QueryString["CurrentTab"];
  39. }
  40. ViewData["CurrentTab"] = currentTab;
  41. try
  42. {
  43. // Show progress information if installation/reset activities are being performed
  44. IVMManager vmManager = WindowsAzureVMManager.GetVMManager();
  45. IDictionary<string, string> progressInformation = vmManager.GetProgressInformation();
  46. if (progressInformation != null && progressInformation.Count > 0)
  47. {
  48. return RedirectToAction(
  49. "ProgressInformation",
  50. "Admin",
  51. new
  52. {
  53. ActionName = "Applications",
  54. ControllerName = "Applications",
  55. ActionSubtabName = "AvailableApplicationsList",
  56. CurrentTab = currentTab
  57. }
  58. );
  59. }
  60. if (Request.QueryString["Subtab"] == null
  61. || 0 == Request.QueryString["Subtab"].CompareTo("AvailableApplicationsList")
  62. )
  63. {
  64. ViewData["Subtab"] = "AvailableApplicationsList";
  65. string productIDsChecked = Request.QueryString["ProductIDsChecked"];
  66. if (!string.IsNullOrEmpty(productIDsChecked))
  67. {
  68. string[] productIDs = productIDsChecked.Split(',');
  69. List<string> productIDList = new List<string>(productIDs.Length);
  70. productIDList.AddRange(productIDs);
  71. ViewData["ProductIDsChecked"] = productIDList;
  72. }
  73. return PrepareViewData(currentTab);
  74. }
  75. else if (0 == Request.QueryString["Subtab"].CompareTo("PreparedApplicationsList"))
  76. {
  77. ViewData["Subtab"] = "PreparedApplicationsList";
  78. ViewData["ProductsToInstall"] = Request.QueryString["ProductsToInstall"];
  79. return PreparedApplicationssToInstallViewData();
  80. }
  81. else if (Request.QueryString["Subtab"].Equals("EditFile"))
  82. {
  83. try
  84. {
  85. string productId = Request.QueryString["ProductId"];
  86. string[] installInfo = vmManager.GetInstalledProductsInfo()[productId].Split(',');
  87. string installPath = installInfo[1];
  88. string editFileName = Request.QueryString["EditFileName"];
  89. // Get application root path
  90. string applicationInstallPath = Path.Combine(vmManager.GetApplicationsFolder(),
  91. installPath.Replace("/", "\\").Trim('\\'));
  92. string fileNameWithFullPath = Path.Combine(applicationInstallPath,
  93. editFileName.Replace("/", "\\").Trim('\\'));
  94. if (!System.IO.File.Exists(fileNameWithFullPath))
  95. {
  96. Trace.TraceError("Specified file does not exist.");
  97. return RedirectToAction("Error", "Home", new { ErrorMessage = "Specified file does not exist." });
  98. }
  99. var productTitles = from item in (IEnumerable<SyndicationItem>)ViewData["ProductListXmlFeedItems"]
  100. where item.ElementExtensions.ReadElementExtensions<string>("productId", "http://www.w3.org/2005/Atom")[0].Equals(productId)
  101. select item.Title.Text;
  102. ViewData["Subtab"] = "EditFile";
  103. ViewData["ProductId"] = productId;
  104. ViewData["ProductTitle"] = productTitles.First();
  105. ViewData["EditFileName"] = editFileName;
  106. ViewData["EditFileNameWithFullPath"] = fileNameWithFullPath;
  107. return View();
  108. }
  109. catch (Exception ex)
  110. {
  111. Trace.TraceError("Unable to edit file: {0}", ex.Message);
  112. return RedirectToAction("Error", "Home", new { ErrorMessage = "Unable to edit file." });
  113. }
  114. }
  115. else
  116. {
  117. ViewData["Subtab"] = Request.QueryString["Subtab"];
  118. return View();
  119. }
  120. }
  121. catch (Exception ex)
  122. {
  123. Trace.TraceError("Unknown error: {0}", ex.Message);
  124. return RedirectToAction("Error", "Home", new { ErrorMessage = string.Format("Unknown error: {0}", ex.Message)});
  125. }
  126. }
  127. #region Prepare Applications for Install
  128. /// <summary>
  129. /// Prepares platform listing for installation acceptance.
  130. /// </summary>
  131. /// <param name="form">The form.</param>
  132. /// <returns></returns>
  133. [AcceptVerbs(HttpVerbs.Post)]
  134. public ActionResult PreparedApplicationsList(FormCollection form)
  135. {
  136. // Get current tab
  137. string currentTab = form.Get("CurrentTab");
  138. List<string> editFileNameButtons = form.AllKeys.Where(k => k.StartsWith("EditFileNameButton_")).ToList<string>();
  139. if (editFileNameButtons.Count == 1)
  140. {
  141. string productId = editFileNameButtons[0].Split('_')[1];
  142. string editFileNameTextBoxName = "EditFileNameTextBox_" + productId;
  143. string editFileName = form.Get(editFileNameTextBoxName);
  144. return RedirectToAction(
  145. "Applications",
  146. "Applications",
  147. new
  148. {
  149. CurrentTab = currentTab,
  150. Subtab = "EditFile",
  151. ProductId = productId,
  152. EditFileName = editFileName
  153. }
  154. );
  155. }
  156. else
  157. {
  158. try
  159. {
  160. List<string> productsToInstall = new List<string>();
  161. List<string> keys = form.AllKeys.ToList<string>();
  162. if (0 < keys.Count())
  163. {
  164. // Prepare information about selected product
  165. for (int i = 0; i < keys.Count(); i++)
  166. {
  167. string productID = keys[i];
  168. if (form.Get(productID).StartsWith("true"))
  169. {
  170. productsToInstall.Add(productID);
  171. }
  172. }
  173. }
  174. return RedirectToAction(
  175. "Applications",
  176. "Applications",
  177. new
  178. {
  179. CurrentTab = currentTab,
  180. Subtab = "PreparedApplicationsList",
  181. ProductsToInstall = String.Join(",", productsToInstall.ToArray()),
  182. }
  183. );
  184. }
  185. catch (Exception ex)
  186. {
  187. Trace.TraceError("Unable to prepare platform listing for installation acceptance: {0}", ex.Message);
  188. return RedirectToAction("Error", "Home", new { ErrorMessage = "Unable to prepare platform listing for installation acceptance." });
  189. }
  190. }
  191. }
  192. /// <summary>
  193. /// Prepares the applications.
  194. /// </summary>
  195. /// <param name="form">The form.</param>
  196. /// <returns></returns>
  197. [AcceptVerbs(HttpVerbs.Post)]
  198. public ActionResult PreparedApplicationssToInstallViewData()
  199. {
  200. return PrepareProductsToInstallViewData();
  201. }
  202. #endregion
  203. /// <summary>
  204. /// Update the file
  205. /// </summary>
  206. /// <param name="form">The form.</param>
  207. /// <returns></returns>
  208. [Authorize, ValidateInput(false)]
  209. public ActionResult UpdateFile(FormCollection form)
  210. {
  211. try
  212. {
  213. // Get current tab
  214. string currentTab = form.Get("CurrentTab");
  215. string productId = form.Get("productId");
  216. string editFileName = form.Get("editFileName");
  217. IVMManager vmManager = WindowsAzureVMManager.GetVMManager();
  218. string[] installInfo = vmManager.GetInstalledProductsInfo()[productId].Split(',');
  219. string installPath = installInfo[1];
  220. // Get application root path
  221. string applicationInstallPath = Path.Combine(vmManager.GetApplicationsFolder(),
  222. installPath.Replace("/", "\\").Trim('\\'));
  223. string fileNameWithFullPath = Path.Combine(applicationInstallPath,
  224. editFileName.Replace("/", "\\").Trim('\\'));
  225. // Get updated file content
  226. string content = form.Get("FileContent");
  227. // Update file content
  228. StreamWriter streamWriter = System.IO.File.CreateText(fileNameWithFullPath);
  229. streamWriter.Write(content);
  230. streamWriter.Close();
  231. return RedirectToAction(
  232. "Applications",
  233. "Applications",
  234. new
  235. {
  236. CurrentTab = currentTab,
  237. ActionSubtabName = "AvailableApplicationsList"
  238. }
  239. );
  240. }
  241. catch (Exception ex)
  242. {
  243. Trace.TraceError("Unable to update file: {0}", ex.Message);
  244. return RedirectToAction("Error", "Home", new { ErrorMessage = "Unable to update file." });
  245. }
  246. }
  247. #region Install Applications
  248. /// <summary>
  249. /// Installs the applications.
  250. /// </summary>
  251. /// <param name="form">The form.</param>
  252. /// <returns></returns>
  253. [AcceptVerbs(HttpVerbs.Post)]
  254. public ActionResult InstallApplications(FormCollection form)
  255. {
  256. try
  257. {
  258. // Get current tab
  259. string currentTab = form.Get("CurrentTab");
  260. // All product download urls' versions (selected and not selected both)
  261. string[] productVersions = form.Get("downloadUrls").Split(',');
  262. // Remove unnecessary keys in order to preserve proper order
  263. form.Remove("downloadUrls");
  264. form.Remove("buttonAccept");
  265. form.Remove("CurrentTab");
  266. List<string> productIDs = form.AllKeys.Where(k => !k.StartsWith("Parameter_")).ToList<string>();
  267. Dictionary<string, string> productsToInstall = new Dictionary<string, string>();
  268. if (0 < productIDs.Count())
  269. {
  270. // Prepare information about selected product
  271. for (int i = 0; i < productIDs.Count(); i++)
  272. {
  273. string productID = productIDs[i];
  274. if (form.Get(productID).StartsWith("true"))
  275. {
  276. List<string> parameters = new List<string>();
  277. parameters.Add(productVersions[i]);
  278. foreach (string k in form.AllKeys.
  279. Where(k => k.StartsWith("Parameter_" + productID)).ToArray<string>())
  280. {
  281. string param = k.Split('=')[1];
  282. string value = form.Get(k);
  283. parameters.Add(param + "=" + value);
  284. }
  285. productsToInstall.Add(
  286. productID,
  287. string.Join(",",
  288. parameters.ToArray()
  289. )
  290. );
  291. }
  292. }
  293. }
  294. if (null != productsToInstall && 0 < productsToInstall.Count)
  295. {
  296. try
  297. {
  298. // Install applications
  299. IVMManager vmManager = WindowsAzureVMManager.GetVMManager();
  300. vmManager.InstallApplications(productsToInstall);
  301. }
  302. catch (Exception ex)
  303. {
  304. Trace.TraceError("Unable to install applications: {0}", ex.Message);
  305. return RedirectToAction("Error", "Home", new { ErrorMessage = "Unable to install applications." });
  306. }
  307. }
  308. return RedirectToAction(
  309. "ProgressInformation",
  310. "Admin",
  311. new
  312. {
  313. ActionName = "Applications",
  314. ControllerName = "Applications",
  315. ActionSubtabName = "AvailableApplicationsList",
  316. CurrentTab = currentTab
  317. }
  318. );
  319. }
  320. catch (Exception ex)
  321. {
  322. Trace.TraceError("Unable to gather information to install platform products: {0}", ex.Message);
  323. return RedirectToAction("Error", "Home", new { ErrorMessage = "Unable to gather information to install platform products." });
  324. }
  325. }
  326. #endregion
  327. protected override ActionResult PrepareViewData()
  328. {
  329. return null;
  330. }
  331. /// <summary>
  332. /// Prepares the view data.
  333. /// </summary>
  334. /// <returns></returns>
  335. protected ActionResult PrepareViewData(string tabName)
  336. {
  337. ActionResult viewResult = this.PrepareProductsViewData();
  338. if (null != viewResult)
  339. {
  340. return viewResult;
  341. }
  342. try
  343. {
  344. IEnumerable<ProductCategoryGroup> enumProductCategoryGroup
  345. = from item in (IEnumerable<SyndicationItem>)ViewData["ProductListXmlFeedItems"]
  346. where item.ElementExtensions.ReadElementExtensions<string>("tabName", "http://www.w3.org/2005/Atom")[0].Equals(tabName)
  347. group item by item.ElementExtensions.ReadElementExtensions<string>("productCategory", "http://www.w3.org/2005/Atom")[0] into g
  348. select new ProductCategoryGroup
  349. {
  350. Category = g.Key,
  351. Products = g
  352. };
  353. List<ProductCategoryGroup> listProductCategoryGroup = enumProductCategoryGroup.ToList();
  354. ViewData["UITabName"] = tabName;
  355. ViewData["ApplicationCategoryGroups"]
  356. = 0 < listProductCategoryGroup.Count
  357. ? listProductCategoryGroup
  358. : null;
  359. }
  360. catch (Exception ex)
  361. {
  362. Trace.TraceError("Unable to read list of Platform products: {0}", ex.Message);
  363. ViewData["ErrorMessage"] = "Unable to read list of Platform products";
  364. }
  365. ActionResult result = PrepareInstalledProductsViewData();
  366. if (null != result)
  367. {
  368. return result;
  369. }
  370. // Set PHP Web Site status
  371. try
  372. {
  373. IVMManager vmManager = WindowsAzureVMManager.GetVMManager();
  374. if (vmManager.IsPHPWebSiteStarted())
  375. {
  376. ViewData["PHPWebSiteStatus"] = "Started";
  377. }
  378. else
  379. {
  380. ViewData["PHPWebSiteStatus"] = "Stopped";
  381. }
  382. }
  383. catch (Exception ex)
  384. {
  385. ViewData["PHPWebSiteStatus"] = "Unknown";
  386. Trace.TraceError("Unable to get PHPWebSiteStatus. Error: {0}", ex.Message);
  387. }
  388. return PartialView();
  389. }
  390. }
  391. }