/// <summary> /// The Get Subscription operation returns account and resource /// allocation information for the specified subscription. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/hh403995.aspx /// for more information) /// </summary> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The Get Subscription operation response. /// </returns> public async Task <SubscriptionGetResponse> GetAsync(CancellationToken cancellationToken) { // Validate // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = "/" + (this.Client.Credentials.SubscriptionId == null ? "" : Uri.EscapeDataString(this.Client.Credentials.SubscriptionId)); string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2014-10-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result SubscriptionGetResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new SubscriptionGetResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement subscriptionElement = responseDoc.Element(XName.Get("Subscription", "http://schemas.microsoft.com/windowsazure")); if (subscriptionElement != null) { XElement subscriptionIDElement = subscriptionElement.Element(XName.Get("SubscriptionID", "http://schemas.microsoft.com/windowsazure")); if (subscriptionIDElement != null) { string subscriptionIDInstance = subscriptionIDElement.Value; result.SubscriptionID = subscriptionIDInstance; } XElement subscriptionNameElement = subscriptionElement.Element(XName.Get("SubscriptionName", "http://schemas.microsoft.com/windowsazure")); if (subscriptionNameElement != null) { string subscriptionNameInstance = subscriptionNameElement.Value; result.SubscriptionName = subscriptionNameInstance; } XElement subscriptionStatusElement = subscriptionElement.Element(XName.Get("SubscriptionStatus", "http://schemas.microsoft.com/windowsazure")); if (subscriptionStatusElement != null) { SubscriptionStatus subscriptionStatusInstance = ((SubscriptionStatus)Enum.Parse(typeof(SubscriptionStatus), subscriptionStatusElement.Value, true)); result.SubscriptionStatus = subscriptionStatusInstance; } XElement accountAdminLiveEmailIdElement = subscriptionElement.Element(XName.Get("AccountAdminLiveEmailId", "http://schemas.microsoft.com/windowsazure")); if (accountAdminLiveEmailIdElement != null) { string accountAdminLiveEmailIdInstance = accountAdminLiveEmailIdElement.Value; result.AccountAdminLiveEmailId = accountAdminLiveEmailIdInstance; } XElement serviceAdminLiveEmailIdElement = subscriptionElement.Element(XName.Get("ServiceAdminLiveEmailId", "http://schemas.microsoft.com/windowsazure")); if (serviceAdminLiveEmailIdElement != null) { string serviceAdminLiveEmailIdInstance = serviceAdminLiveEmailIdElement.Value; result.ServiceAdminLiveEmailId = serviceAdminLiveEmailIdInstance; } XElement maxCoreCountElement = subscriptionElement.Element(XName.Get("MaxCoreCount", "http://schemas.microsoft.com/windowsazure")); if (maxCoreCountElement != null) { int maxCoreCountInstance = int.Parse(maxCoreCountElement.Value, CultureInfo.InvariantCulture); result.MaximumCoreCount = maxCoreCountInstance; } XElement maxStorageAccountsElement = subscriptionElement.Element(XName.Get("MaxStorageAccounts", "http://schemas.microsoft.com/windowsazure")); if (maxStorageAccountsElement != null) { int maxStorageAccountsInstance = int.Parse(maxStorageAccountsElement.Value, CultureInfo.InvariantCulture); result.MaximumStorageAccounts = maxStorageAccountsInstance; } XElement maxHostedServicesElement = subscriptionElement.Element(XName.Get("MaxHostedServices", "http://schemas.microsoft.com/windowsazure")); if (maxHostedServicesElement != null) { int maxHostedServicesInstance = int.Parse(maxHostedServicesElement.Value, CultureInfo.InvariantCulture); result.MaximumHostedServices = maxHostedServicesInstance; } XElement currentCoreCountElement = subscriptionElement.Element(XName.Get("CurrentCoreCount", "http://schemas.microsoft.com/windowsazure")); if (currentCoreCountElement != null) { int currentCoreCountInstance = int.Parse(currentCoreCountElement.Value, CultureInfo.InvariantCulture); result.CurrentCoreCount = currentCoreCountInstance; } XElement currentStorageAccountsElement = subscriptionElement.Element(XName.Get("CurrentStorageAccounts", "http://schemas.microsoft.com/windowsazure")); if (currentStorageAccountsElement != null) { int currentStorageAccountsInstance = int.Parse(currentStorageAccountsElement.Value, CultureInfo.InvariantCulture); result.CurrentStorageAccounts = currentStorageAccountsInstance; } XElement currentHostedServicesElement = subscriptionElement.Element(XName.Get("CurrentHostedServices", "http://schemas.microsoft.com/windowsazure")); if (currentHostedServicesElement != null) { int currentHostedServicesInstance = int.Parse(currentHostedServicesElement.Value, CultureInfo.InvariantCulture); result.CurrentHostedServices = currentHostedServicesInstance; } XElement maxVirtualNetworkSitesElement = subscriptionElement.Element(XName.Get("MaxVirtualNetworkSites", "http://schemas.microsoft.com/windowsazure")); if (maxVirtualNetworkSitesElement != null) { int maxVirtualNetworkSitesInstance = int.Parse(maxVirtualNetworkSitesElement.Value, CultureInfo.InvariantCulture); result.MaximumVirtualNetworkSites = maxVirtualNetworkSitesInstance; } XElement currentVirtualNetworkSitesElement = subscriptionElement.Element(XName.Get("CurrentVirtualNetworkSites", "http://schemas.microsoft.com/windowsazure")); if (currentVirtualNetworkSitesElement != null) { int currentVirtualNetworkSitesInstance = int.Parse(currentVirtualNetworkSitesElement.Value, CultureInfo.InvariantCulture); result.CurrentVirtualNetworkSites = currentVirtualNetworkSitesInstance; } XElement maxLocalNetworkSitesElement = subscriptionElement.Element(XName.Get("MaxLocalNetworkSites", "http://schemas.microsoft.com/windowsazure")); if (maxLocalNetworkSitesElement != null) { int maxLocalNetworkSitesInstance = int.Parse(maxLocalNetworkSitesElement.Value, CultureInfo.InvariantCulture); result.MaximumLocalNetworkSites = maxLocalNetworkSitesInstance; } XElement maxDnsServersElement = subscriptionElement.Element(XName.Get("MaxDnsServers", "http://schemas.microsoft.com/windowsazure")); if (maxDnsServersElement != null) { int maxDnsServersInstance = int.Parse(maxDnsServersElement.Value, CultureInfo.InvariantCulture); result.MaximumDnsServers = maxDnsServersInstance; } XElement currentLocalNetworkSitesElement = subscriptionElement.Element(XName.Get("CurrentLocalNetworkSites", "http://schemas.microsoft.com/windowsazure")); if (currentLocalNetworkSitesElement != null) { int currentLocalNetworkSitesInstance = int.Parse(currentLocalNetworkSitesElement.Value, CultureInfo.InvariantCulture); result.CurrentLocalNetworkSites = currentLocalNetworkSitesInstance; } XElement currentDnsServersElement = subscriptionElement.Element(XName.Get("CurrentDnsServers", "http://schemas.microsoft.com/windowsazure")); if (currentDnsServersElement != null) { int currentDnsServersInstance = int.Parse(currentDnsServersElement.Value, CultureInfo.InvariantCulture); result.CurrentDnsServers = currentDnsServersInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return(result); } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } }
private void ProcessAddProjectItem(string relativeFileName, string itemType, string dependsOn, string copyToOutputDirectory) { relativeFileName = NormalizePath(relativeFileName); dependsOn = NormalizePath(dependsOn); if (string.IsNullOrWhiteSpace(relativeFileName)) { throw new Exception("relativeFileName is null"); } if (Path.GetExtension(relativeFileName).Equals(".config", StringComparison.InvariantCultureIgnoreCase)) { copyToOutputDirectory = "PreserveNewest"; } if (itemType == null) { var fileExtension = !string.IsNullOrEmpty(Path.GetExtension(relativeFileName)) ? Path.GetExtension(relativeFileName).Substring(1) : null; //remove the '.' switch (fileExtension) { case "cs": itemType = "Compile"; break; default: itemType = "Content"; break; } } var metadata = new Dictionary <string, string>(); if (copyToOutputDirectory != null) { metadata.Add("CopyToOutputDirectory", copyToOutputDirectory); } if (dependsOn != null) { metadata.Add("DependentUpon", dependsOn); } // GCB - not the most extensible / flexible way of doing this... if (Path.GetExtension(relativeFileName).Equals(".tt", StringComparison.InvariantCultureIgnoreCase)) { metadata.Add("Generator", "TextTemplatingFilePreprocessor"); metadata.Add("LastGenOutput", Path.GetFileNameWithoutExtension(relativeFileName) + ".cs"); } var codeItems = FindItemGroupForCodeFiles() ?? AddItemGroupForCodeFiles(); var projectItem = GetProjectItem(relativeFileName); if (projectItem == null) { var item = new XElement(XName.Get(itemType, _namespace.NamespaceName)); item.Add(new XAttribute("Include", relativeFileName)); foreach (var data in metadata) { var child = new XElement(XName.Get(data.Key, _namespace.NamespaceName)) { Value = data.Value }; item.Add(child); } codeItems.Add(item); } else { if (projectItem.Name.LocalName != itemType) { projectItem.Name = XName.Get(itemType, projectItem.Name.NamespaceName); } var children = projectItem.Elements().ToList(); projectItem.RemoveNodes(); foreach (var data in metadata) { var child = new XElement(XName.Get(data.Key, _namespace.NamespaceName)) { Value = data.Value }; projectItem.Add(child); } foreach (var userAddedMetaData in children.Where(x => metadata.All(y => XName.Get(y.Key, _namespace.NamespaceName) != x.Name))) { var child = new XElement(userAddedMetaData.Name) { Value = userAddedMetaData.Value }; projectItem.Add(child); } } }
/// <summary> /// The List Operating Systems operation lists the versions of the /// guest operating system that are currently available in Windows /// Azure. The 2010-10-28 version of List Operating Systems also /// indicates what family an operating system version belongs to. /// Currently Azure supports two operating system families: the Azure /// guest operating system that is substantially compatible with /// Windows Server 2008 SP2, and the Azure guest operating system that /// is substantially compatible with Windows Server 2008 R2. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/ff684168.aspx /// for more information) /// </summary> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The List Operating Systems operation response. /// </returns> public async System.Threading.Tasks.Task <Microsoft.WindowsAzure.Management.Compute.Models.OperatingSystemListResponse> ListAsync(CancellationToken cancellationToken) { // Validate // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); Tracing.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string baseUrl = this.Client.BaseUri.AbsoluteUri; string url = "/" + this.Client.Credentials.SubscriptionId.Trim() + "/operatingsystems"; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2014-04-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false), CloudExceptionType.Xml); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result OperatingSystemListResponse result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new OperatingSystemListResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement operatingSystemsSequenceElement = responseDoc.Element(XName.Get("OperatingSystems", "http://schemas.microsoft.com/windowsazure")); if (operatingSystemsSequenceElement != null && operatingSystemsSequenceElement.IsEmpty == false) { foreach (XElement operatingSystemsElement in operatingSystemsSequenceElement.Elements(XName.Get("OperatingSystem", "http://schemas.microsoft.com/windowsazure"))) { OperatingSystemListResponse.OperatingSystem operatingSystemInstance = new OperatingSystemListResponse.OperatingSystem(); result.OperatingSystems.Add(operatingSystemInstance); XElement versionElement = operatingSystemsElement.Element(XName.Get("Version", "http://schemas.microsoft.com/windowsazure")); if (versionElement != null && versionElement.IsEmpty == false) { string versionInstance = versionElement.Value; operatingSystemInstance.Version = versionInstance; } XElement labelElement = operatingSystemsElement.Element(XName.Get("Label", "http://schemas.microsoft.com/windowsazure")); if (labelElement != null && labelElement.IsEmpty == false) { string labelInstance = TypeConversion.FromBase64String(labelElement.Value); operatingSystemInstance.Label = labelInstance; } XElement isDefaultElement = operatingSystemsElement.Element(XName.Get("IsDefault", "http://schemas.microsoft.com/windowsazure")); if (isDefaultElement != null && isDefaultElement.IsEmpty == false) { bool isDefaultInstance = bool.Parse(isDefaultElement.Value); operatingSystemInstance.IsDefault = isDefaultInstance; } XElement isActiveElement = operatingSystemsElement.Element(XName.Get("IsActive", "http://schemas.microsoft.com/windowsazure")); if (isActiveElement != null && isActiveElement.IsEmpty == false) { bool isActiveInstance = bool.Parse(isActiveElement.Value); operatingSystemInstance.IsActive = isActiveInstance; } XElement familyElement = operatingSystemsElement.Element(XName.Get("Family", "http://schemas.microsoft.com/windowsazure")); if (familyElement != null && familyElement.IsEmpty == false) { int familyInstance = int.Parse(familyElement.Value, CultureInfo.InvariantCulture); operatingSystemInstance.Family = familyInstance; } XElement familyLabelElement = operatingSystemsElement.Element(XName.Get("FamilyLabel", "http://schemas.microsoft.com/windowsazure")); if (familyLabelElement != null && familyLabelElement.IsEmpty == false) { string familyLabelInstance = TypeConversion.FromBase64String(familyLabelElement.Value); operatingSystemInstance.FamilyLabel = familyLabelInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return(result); } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } }
private void GetResponseCallback(IAsyncResult asynchronousResult) { try { HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState; // End the operation HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult); Stream streamResponse = response.GetResponseStream(); StreamReader streamRead = new StreamReader(streamResponse); string responseString = streamRead.ReadToEnd(); XDocument doc = XDocument.Parse(responseString); XElement rsp = doc.Element("rsp"); string status = rsp.Attribute(XName.Get("status")) != null?rsp.Attribute(XName.Get("status")).Value : rsp.Attribute(XName.Get("stat")).Value; // Close the stream object streamResponse.Close(); streamRead.Close(); // Release the HttpWebResponse response.Close(); } catch (Exception ex) { Dispatcher.BeginInvoke(() => txtStatus.Text = ex.Message); } }
/// <summary> /// The Get Express Route operation status gets information on the /// status of Express Route operations in Windows Azure. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj154112.aspx /// for more information) /// </summary> /// <param name='operationId'> /// Required. The id of the operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> public async Task <ExpressRouteOperationStatusResponse> GetOperationStatusAsync(string operationId, CancellationToken cancellationToken) { // Validate if (operationId == null) { throw new ArgumentNullException("operationId"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("operationId", operationId); TracingAdapter.Enter(invocationId, this, "GetOperationStatusAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/services/networking/operation/"; url = url + Uri.EscapeDataString(operationId); string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2011-10-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ExpressRouteOperationStatusResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ExpressRouteOperationStatusResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement gatewayOperationElement = responseDoc.Element(XName.Get("GatewayOperation", "http://schemas.microsoft.com/windowsazure")); if (gatewayOperationElement != null) { XElement idElement = gatewayOperationElement.Element(XName.Get("ID", "http://schemas.microsoft.com/windowsazure")); if (idElement != null) { string idInstance = idElement.Value; result.Id = idInstance; } XElement statusElement = gatewayOperationElement.Element(XName.Get("Status", "http://schemas.microsoft.com/windowsazure")); if (statusElement != null) { ExpressRouteOperationStatus statusInstance = ((ExpressRouteOperationStatus)Enum.Parse(typeof(ExpressRouteOperationStatus), statusElement.Value, true)); result.Status = statusInstance; } XElement httpStatusCodeElement = gatewayOperationElement.Element(XName.Get("HttpStatusCode", "http://schemas.microsoft.com/windowsazure")); if (httpStatusCodeElement != null) { HttpStatusCode httpStatusCodeInstance = ((HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), httpStatusCodeElement.Value, true)); result.HttpStatusCode = httpStatusCodeInstance; } XElement dataElement = gatewayOperationElement.Element(XName.Get("Data", "http://schemas.microsoft.com/windowsazure")); if (dataElement != null) { string dataInstance = dataElement.Value; result.Data = dataInstance; } XElement errorElement = gatewayOperationElement.Element(XName.Get("Error", "http://schemas.microsoft.com/windowsazure")); if (errorElement != null) { ExpressRouteOperationStatusResponse.ErrorDetails errorInstance = new ExpressRouteOperationStatusResponse.ErrorDetails(); result.Error = errorInstance; XElement codeElement = errorElement.Element(XName.Get("Code", "http://schemas.microsoft.com/windowsazure")); if (codeElement != null) { string codeInstance = codeElement.Value; errorInstance.Code = codeInstance; } XElement messageElement = errorElement.Element(XName.Get("Message", "http://schemas.microsoft.com/windowsazure")); if (messageElement != null) { string messageInstance = messageElement.Value; errorInstance.Message = messageInstance; } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return(result); } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } }
/// <summary> /// The Get Dedicated Circuit Peering routeTableSummary operation /// retrieves the ARP information for specific BGP. /// </summary> /// <param name='serviceKey'> /// Required. The service key representing the circuit. /// </param> /// <param name='accessType'> /// Required. Whether the peering is private or public or microsoft. /// </param> /// <param name='devicePath'> /// Required. Whether the device is primary or secondary. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The Get Dedicated Circuit Peering Routing Summary operation /// response. /// </returns> public async Task <DedicatedCircuitPeeringRoutingSummaryGetResponse> GetAsync(string serviceKey, BgpPeeringAccessType accessType, DevicePath devicePath, CancellationToken cancellationToken) { // Validate if (serviceKey == null) { throw new ArgumentNullException("serviceKey"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("serviceKey", serviceKey); tracingParameters.Add("accessType", accessType); tracingParameters.Add("devicePath", devicePath); TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/services/networking/dedicatedcircuits/"; url = url + Uri.EscapeDataString(serviceKey); url = url + "/bgppeerings/"; url = url + Uri.EscapeDataString(ExpressRouteManagementClient.BgpPeeringAccessTypeToString(accessType)); url = url + "/routeTableSummary/"; url = url + Uri.EscapeDataString(ExpressRouteManagementClient.DevicePathToString(devicePath)); List <string> queryParameters = new List <string>(); queryParameters.Add("api-version=1.0"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2011-10-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result DedicatedCircuitPeeringRoutingSummaryGetResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new DedicatedCircuitPeeringRoutingSummaryGetResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement dedicatedCircuitPeeringRoutingSummaryElement = responseDoc.Element(XName.Get("DedicatedCircuitPeeringRoutingSummary", "http://schemas.microsoft.com/windowsazure")); if (dedicatedCircuitPeeringRoutingSummaryElement != null) { AzureDedicatedCircuitPeeringRoutingInfo dedicatedCircuitPeeringRoutingInfoInstance = new AzureDedicatedCircuitPeeringRoutingInfo(); result.DedicatedCircuitPeeringRoutingInfo = dedicatedCircuitPeeringRoutingInfoInstance; XElement networkElement = dedicatedCircuitPeeringRoutingSummaryElement.Element(XName.Get("Network", "http://schemas.microsoft.com/windowsazure")); if (networkElement != null) { string networkInstance = networkElement.Value; dedicatedCircuitPeeringRoutingInfoInstance.Network = networkInstance; } XElement nextHopElement = dedicatedCircuitPeeringRoutingSummaryElement.Element(XName.Get("NextHop", "http://schemas.microsoft.com/windowsazure")); if (nextHopElement != null) { string nextHopInstance = nextHopElement.Value; dedicatedCircuitPeeringRoutingInfoInstance.NextHop = nextHopInstance; } XElement locPrfElement = dedicatedCircuitPeeringRoutingSummaryElement.Element(XName.Get("LocPrf", "http://schemas.microsoft.com/windowsazure")); if (locPrfElement != null) { string locPrfInstance = locPrfElement.Value; dedicatedCircuitPeeringRoutingInfoInstance.LocPrf = locPrfInstance; } XElement weightElement = dedicatedCircuitPeeringRoutingSummaryElement.Element(XName.Get("Weight", "http://schemas.microsoft.com/windowsazure")); if (weightElement != null) { int weightInstance = int.Parse(weightElement.Value, CultureInfo.InvariantCulture); dedicatedCircuitPeeringRoutingInfoInstance.Weight = weightInstance; } XElement pathElement = dedicatedCircuitPeeringRoutingSummaryElement.Element(XName.Get("Path", "http://schemas.microsoft.com/windowsazure")); if (pathElement != null) { string pathInstance = pathElement.Value; dedicatedCircuitPeeringRoutingInfoInstance.Path = pathInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return(result); } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } }
/// <summary> /// The Get Operation Status operation returns the status of /// thespecified operation. After calling an asynchronous operation, /// you can call Get Operation Status to determine whether the /// operation has succeeded, failed, or is still in progress. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460783.aspx /// for more information) /// </summary> /// <param name='requestId'> /// The request ID for the request you wish to track. The request ID is /// returned in the x-ms-request-id response header for every request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> public async System.Threading.Tasks.Task <Microsoft.WindowsAzure.Management.Storage.Models.StorageOperationStatusResponse> GetOperationStatusAsync(string requestId, CancellationToken cancellationToken) { // Validate if (requestId == null) { throw new ArgumentNullException("requestId"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("requestId", requestId); Tracing.Enter(invocationId, this, "GetOperationStatusAsync", tracingParameters); } // Construct URL string url = new Uri(this.BaseUri, "/").ToString() + this.Credentials.SubscriptionId + "/operations/" + requestId; // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2013-03-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false), CloudExceptionType.Xml); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result StorageOperationStatusResponse result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new StorageOperationStatusResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement operationElement = responseDoc.Element(XName.Get("Operation", "http://schemas.microsoft.com/windowsazure")); if (operationElement != null) { XElement idElement = operationElement.Element(XName.Get("ID", "http://schemas.microsoft.com/windowsazure")); if (idElement != null) { string idInstance = idElement.Value; result.Id = idInstance; } XElement statusElement = operationElement.Element(XName.Get("Status", "http://schemas.microsoft.com/windowsazure")); if (statusElement != null) { OperationStatus statusInstance = (OperationStatus)Enum.Parse(typeof(OperationStatus), statusElement.Value, false); result.Status = statusInstance; } XElement httpStatusCodeElement = operationElement.Element(XName.Get("HttpStatusCode", "http://schemas.microsoft.com/windowsazure")); if (httpStatusCodeElement != null) { HttpStatusCode httpStatusCodeInstance = (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), httpStatusCodeElement.Value, false); result.HttpStatusCode = httpStatusCodeInstance; } XElement errorElement = operationElement.Element(XName.Get("Error", "http://schemas.microsoft.com/windowsazure")); if (errorElement != null) { StorageOperationStatusResponse.ErrorDetails errorInstance = new StorageOperationStatusResponse.ErrorDetails(); result.Error = errorInstance; XElement codeElement = errorElement.Element(XName.Get("Code", "http://schemas.microsoft.com/windowsazure")); if (codeElement != null) { string codeInstance = codeElement.Value; errorInstance.Code = codeInstance; } XElement messageElement = errorElement.Element(XName.Get("Message", "http://schemas.microsoft.com/windowsazure")); if (messageElement != null) { string messageInstance = messageElement.Value; errorInstance.Message = messageInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return(result); } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } }
internal DocProperty(DocX document, XElement xml) : base(document, xml) { string instr = Xml.Attribute(XName.Get("instr", "http://schemas.openxmlformats.org/wordprocessingml/2006/main")).Value; this.name = extractName.Match(instr.Trim()).Groups["name"].Value; }
/// <summary> /// Add an internal load balancer to a an existing deployment. When /// used by an input endpoint, the internal load balancer will provide /// an additional private VIP that can be used for load balancing to /// the roles in this deployment. /// </summary> /// <param name='serviceName'> /// Required. The name of the service. /// </param> /// <param name='deploymentName'> /// Required. The name of the deployment. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the Create Load Balancer operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request and error information regarding /// the failure. /// </returns> public async System.Threading.Tasks.Task <OperationStatusResponse> BeginCreatingAsync(string serviceName, string deploymentName, LoadBalancerCreateParameters parameters, CancellationToken cancellationToken) { // Validate if (serviceName == null) { throw new ArgumentNullException("serviceName"); } if (deploymentName == null) { throw new ArgumentNullException("deploymentName"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("serviceName", serviceName); tracingParameters.Add("deploymentName", deploymentName); tracingParameters.Add("parameters", parameters); Tracing.Enter(invocationId, this, "BeginCreatingAsync", tracingParameters); } // Construct URL string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/services/hostedservices/" + serviceName.Trim() + "/deployments/" + deploymentName.Trim() + "/loadbalancers"; string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Post; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2014-10-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; XDocument requestDoc = new XDocument(); XElement loadBalancerElement = new XElement(XName.Get("LoadBalancer", "http://schemas.microsoft.com/windowsazure")); requestDoc.Add(loadBalancerElement); if (parameters.Name != null) { XElement nameElement = new XElement(XName.Get("Name", "http://schemas.microsoft.com/windowsazure")); nameElement.Value = parameters.Name; loadBalancerElement.Add(nameElement); } if (parameters.FrontendIPConfiguration != null) { XElement frontendIpConfigurationElement = new XElement(XName.Get("FrontendIpConfiguration", "http://schemas.microsoft.com/windowsazure")); loadBalancerElement.Add(frontendIpConfigurationElement); if (parameters.FrontendIPConfiguration.Type != null) { XElement typeElement = new XElement(XName.Get("Type", "http://schemas.microsoft.com/windowsazure")); typeElement.Value = parameters.FrontendIPConfiguration.Type; frontendIpConfigurationElement.Add(typeElement); } if (parameters.FrontendIPConfiguration.SubnetName != null) { XElement subnetNameElement = new XElement(XName.Get("SubnetName", "http://schemas.microsoft.com/windowsazure")); subnetNameElement.Value = parameters.FrontendIPConfiguration.SubnetName; frontendIpConfigurationElement.Add(subnetNameElement); } if (parameters.FrontendIPConfiguration.StaticVirtualNetworkIPAddress != null) { XElement staticVirtualNetworkIPAddressElement = new XElement(XName.Get("StaticVirtualNetworkIPAddress", "http://schemas.microsoft.com/windowsazure")); staticVirtualNetworkIPAddressElement.Value = parameters.FrontendIPConfiguration.StaticVirtualNetworkIPAddress; frontendIpConfigurationElement.Add(staticVirtualNetworkIPAddressElement); } } requestContent = requestDoc.ToString(); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result OperationStatusResponse result = null; result = new OperationStatusResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return(result); } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } }
/// <summary> /// The List Resource Extensions operation lists the resource /// extensions that are available to add to a Virtual Machine. In /// Azure, a process can run as a resource extension of a Virtual /// Machine. For example, Remote Desktop Access or the Azure /// Diagnostics Agent can run as resource extensions to the Virtual /// Machine. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/dn495441.aspx /// for more information) /// </summary> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The List Resource Extensions operation response. /// </returns> public async Task <VirtualMachineExtensionListResponse> ListAsync(CancellationToken cancellationToken) { // Validate // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/services/resourceextensions"; string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2014-10-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result VirtualMachineExtensionListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new VirtualMachineExtensionListResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement resourceExtensionsSequenceElement = responseDoc.Element(XName.Get("ResourceExtensions", "http://schemas.microsoft.com/windowsazure")); if (resourceExtensionsSequenceElement != null) { foreach (XElement resourceExtensionsElement in resourceExtensionsSequenceElement.Elements(XName.Get("ResourceExtension", "http://schemas.microsoft.com/windowsazure"))) { VirtualMachineExtensionListResponse.ResourceExtension resourceExtensionInstance = new VirtualMachineExtensionListResponse.ResourceExtension(); result.ResourceExtensions.Add(resourceExtensionInstance); XElement publisherElement = resourceExtensionsElement.Element(XName.Get("Publisher", "http://schemas.microsoft.com/windowsazure")); if (publisherElement != null) { string publisherInstance = publisherElement.Value; resourceExtensionInstance.Publisher = publisherInstance; } XElement nameElement = resourceExtensionsElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure")); if (nameElement != null) { string nameInstance = nameElement.Value; resourceExtensionInstance.Name = nameInstance; } XElement versionElement = resourceExtensionsElement.Element(XName.Get("Version", "http://schemas.microsoft.com/windowsazure")); if (versionElement != null) { string versionInstance = versionElement.Value; resourceExtensionInstance.Version = versionInstance; } XElement labelElement = resourceExtensionsElement.Element(XName.Get("Label", "http://schemas.microsoft.com/windowsazure")); if (labelElement != null) { string labelInstance = labelElement.Value; resourceExtensionInstance.Label = labelInstance; } XElement descriptionElement = resourceExtensionsElement.Element(XName.Get("Description", "http://schemas.microsoft.com/windowsazure")); if (descriptionElement != null) { string descriptionInstance = descriptionElement.Value; resourceExtensionInstance.Description = descriptionInstance; } XElement publicConfigurationSchemaElement = resourceExtensionsElement.Element(XName.Get("PublicConfigurationSchema", "http://schemas.microsoft.com/windowsazure")); if (publicConfigurationSchemaElement != null) { string publicConfigurationSchemaInstance = TypeConversion.FromBase64String(publicConfigurationSchemaElement.Value); resourceExtensionInstance.PublicConfigurationSchema = publicConfigurationSchemaInstance; } XElement privateConfigurationSchemaElement = resourceExtensionsElement.Element(XName.Get("PrivateConfigurationSchema", "http://schemas.microsoft.com/windowsazure")); if (privateConfigurationSchemaElement != null) { string privateConfigurationSchemaInstance = TypeConversion.FromBase64String(privateConfigurationSchemaElement.Value); resourceExtensionInstance.PrivateConfigurationSchema = privateConfigurationSchemaInstance; } XElement sampleConfigElement = resourceExtensionsElement.Element(XName.Get("SampleConfig", "http://schemas.microsoft.com/windowsazure")); if (sampleConfigElement != null) { string sampleConfigInstance = TypeConversion.FromBase64String(sampleConfigElement.Value); resourceExtensionInstance.SampleConfig = sampleConfigInstance; } XElement replicationCompletedElement = resourceExtensionsElement.Element(XName.Get("ReplicationCompleted", "http://schemas.microsoft.com/windowsazure")); if (replicationCompletedElement != null && !string.IsNullOrEmpty(replicationCompletedElement.Value)) { bool replicationCompletedInstance = bool.Parse(replicationCompletedElement.Value); resourceExtensionInstance.ReplicationCompleted = replicationCompletedInstance; } XElement eulaElement = resourceExtensionsElement.Element(XName.Get("Eula", "http://schemas.microsoft.com/windowsazure")); if (eulaElement != null) { Uri eulaInstance = TypeConversion.TryParseUri(eulaElement.Value); resourceExtensionInstance.Eula = eulaInstance; } XElement privacyUriElement = resourceExtensionsElement.Element(XName.Get("PrivacyUri", "http://schemas.microsoft.com/windowsazure")); if (privacyUriElement != null) { Uri privacyUriInstance = TypeConversion.TryParseUri(privacyUriElement.Value); resourceExtensionInstance.PrivacyUri = privacyUriInstance; } XElement homepageUriElement = resourceExtensionsElement.Element(XName.Get("HomepageUri", "http://schemas.microsoft.com/windowsazure")); if (homepageUriElement != null) { Uri homepageUriInstance = TypeConversion.TryParseUri(homepageUriElement.Value); resourceExtensionInstance.HomepageUri = homepageUriInstance; } XElement isJsonExtensionElement = resourceExtensionsElement.Element(XName.Get("IsJsonExtension", "http://schemas.microsoft.com/windowsazure")); if (isJsonExtensionElement != null && !string.IsNullOrEmpty(isJsonExtensionElement.Value)) { bool isJsonExtensionInstance = bool.Parse(isJsonExtensionElement.Value); resourceExtensionInstance.IsJsonExtension = isJsonExtensionInstance; } XElement isInternalExtensionElement = resourceExtensionsElement.Element(XName.Get("IsInternalExtension", "http://schemas.microsoft.com/windowsazure")); if (isInternalExtensionElement != null && !string.IsNullOrEmpty(isInternalExtensionElement.Value)) { bool isInternalExtensionInstance = bool.Parse(isInternalExtensionElement.Value); resourceExtensionInstance.IsInternalExtension = isInternalExtensionInstance; } XElement disallowMajorVersionUpgradeElement = resourceExtensionsElement.Element(XName.Get("DisallowMajorVersionUpgrade", "http://schemas.microsoft.com/windowsazure")); if (disallowMajorVersionUpgradeElement != null && !string.IsNullOrEmpty(disallowMajorVersionUpgradeElement.Value)) { bool disallowMajorVersionUpgradeInstance = bool.Parse(disallowMajorVersionUpgradeElement.Value); resourceExtensionInstance.DisallowMajorVersionUpgrade = disallowMajorVersionUpgradeInstance; } XElement supportedOSElement = resourceExtensionsElement.Element(XName.Get("SupportedOS", "http://schemas.microsoft.com/windowsazure")); if (supportedOSElement != null) { string supportedOSInstance = supportedOSElement.Value; resourceExtensionInstance.SupportedOS = supportedOSInstance; } XElement companyNameElement = resourceExtensionsElement.Element(XName.Get("CompanyName", "http://schemas.microsoft.com/windowsazure")); if (companyNameElement != null) { string companyNameInstance = companyNameElement.Value; resourceExtensionInstance.CompanyName = companyNameInstance; } XElement publishedDateElement = resourceExtensionsElement.Element(XName.Get("PublishedDate", "http://schemas.microsoft.com/windowsazure")); if (publishedDateElement != null && !string.IsNullOrEmpty(publishedDateElement.Value)) { DateTime publishedDateInstance = DateTime.Parse(publishedDateElement.Value, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal).ToLocalTime(); resourceExtensionInstance.PublishedDate = publishedDateInstance; } XElement regionsElement = resourceExtensionsElement.Element(XName.Get("Regions", "http://schemas.microsoft.com/windowsazure")); if (regionsElement != null) { string regionsInstance = regionsElement.Value; resourceExtensionInstance.Regions = regionsInstance; } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return(result); } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } }
private void CreatePlanningData() { Tracing.Tracer.LogText("Creating Persons"); Person john = CreatePerson("Nilsen", "John", GetEmbeddedResourceByteArray("m01.jpg"), "*****@*****.**"); Person sam = CreatePerson("Peterson", "Sam", GetEmbeddedResourceByteArray("m03.jpg"), "*****@*****.**"); Person mary = CreatePerson("Tellitson", "Mary", GetEmbeddedResourceByteArray("w02.jpg"), "*****@*****.**"); Person lily = CreatePerson("Johnson", "Lily", GetEmbeddedResourceByteArray("w04.jpg"), "*****@*****.**"); Tracing.Tracer.LogText("Creating 'General DevExpress XAF Evaluation' Project & Tasks"); Project generalEvaluationProject = CreateProject("General DevExpress XAF Evaluation", mary); CreateProjectTask(generalEvaluationProject, "1. Check general product and company information, licensing and pricing", "http://www.devexpress.com/xaf", ProjectTaskStatus.Completed, mary); CreateProjectTask(generalEvaluationProject, "2. Check features of the DevExpress WinForms, ASP.NET WebForms & DevExtreme HTML5/JavaScript controls used in XAF", "http://www.devexpress.com/asp\r\nhttp://www.devexpress.com/winforms\r\nhttps://js.devexpress.com/", ProjectTaskStatus.NotStarted, mary); CreateProjectTask(generalEvaluationProject, "3. Download a free 30-day trial (free technical support included)", "http://www.devexpress.com/Home/Try.xml", ProjectTaskStatus.Completed, mary); CreateProjectTask(generalEvaluationProject, "4. Play with online demo applications on the web site and research local demos in the Demo Center from the installation", "SimpleProjectManager, MainDemo, XCRM, XVideoRental, FeatureCenter, SecurityDemo, WorkflowDemo, etc. at %public%\\Documents\\", ProjectTaskStatus.InProgress, mary); CreateProjectTask(generalEvaluationProject, "5. Analyze key characteristics (look & feel, features set, performance, usability, etc.)", "http://www.devexpress.com/xaf", ProjectTaskStatus.InProgress, mary); CreateProjectTask(generalEvaluationProject, "6. Try the Getting Started tutorials and build a few a prototypes", "https://documentation.devexpress.com/#eXpressAppFramework/CustomDocument113577", ProjectTaskStatus.InProgress, mary); CreateProjectTask(generalEvaluationProject, "7. Check support options and learning materials (documentation, examples, videos, blogs, webinars, etc.)", "http://www.devexpress.com/support/\r\n", ProjectTaskStatus.Completed, mary); CreateProjectTask(generalEvaluationProject, "8. Learn more about the Universal subscription features", "http://www.devexpress.com/Subscriptions/Universal.xml", ProjectTaskStatus.Completed, mary); CreateProjectTask(generalEvaluationProject, "9. Consider using a live chat on site or emailing at [email protected] if you have any pre-sales questions", "http://www.devexpress.com/Home/ContactUs.xml", ProjectTaskStatus.Deferred, mary); Tracing.Tracer.LogText("Creating 'DevExpress XAF Features Overview' Project & Tasks"); Project featuresOverviewProject = CreateProject("DevExpress XAF Features Overview", sam); try { XDocument doc = XDocument.Load(GetEmbeddedResourceStream("ProjectTasks.xml")); foreach (XElement el in doc.Root.Elements()) { XAttribute subject = el.Attribute("Subject"); if (subject != null) { ProjectTask task = ObjectSpace.FindObject <ProjectTask>(new BinaryOperator("Subject", subject.Value)); if (task == null) { task = ObjectSpace.CreateObject <ProjectTask>(); task.Subject = subject.Value; XElement notes = el.Element(XName.Get("Notes")); if (notes != null) { task.Notes = notes.Value.Replace("\n", Environment.NewLine); } task.AssignedTo = rnd.Next(5) % 2 == 0 ? (rnd.Next(6) % 2 == 0 ? sam : lily) : john; task.Project = featuresOverviewProject; task.Status = rnd.Next(7) % 2 == 0 ? (rnd.Next(8) % 2 == 0 ? ProjectTaskStatus.InProgress : ProjectTaskStatus.Completed) : (rnd.Next(9) % 2 == 0 ? ProjectTaskStatus.NotStarted : ProjectTaskStatus.Completed); if (task.Status == ProjectTaskStatus.InProgress || task.Status == ProjectTaskStatus.Completed) { task.StartDate = DateTime.Now.AddDays(rnd.Next(1) * (-1)); } if (task.Status == ProjectTaskStatus.Completed) { task.EndDate = DateTime.Now.AddDays(rnd.Next(2)); } } } ObjectSpace.CommitChanges(); } } catch (Exception ex) { Tracing.Tracer.LogError(ex); } }
/// <summary> /// Write a zip file to a stream. /// </summary> public static async Task CreatePackageAsync(Stream stream, SimpleTestPackageContext packageContext) { var id = packageContext.Id; var version = packageContext.Version; var runtimeJson = packageContext.RuntimeJson; var pathResolver = new VersionFolderPathResolver(null); var testLogger = new TestLogger(); var tempStream = stream; var isUsingTempStream = false; if (packageContext.IsPrimarySigned) { tempStream = new MemoryStream(); isUsingTempStream = true; } using (var zip = new ZipArchive(tempStream, ZipArchiveMode.Create, leaveOpen: true)) { if (packageContext.Files.Any()) { foreach (var entryFile in packageContext.Files) { zip.AddEntry(entryFile.Key, entryFile.Value); } } else { zip.AddEntry("contentFiles/any/any/config.xml", new byte[] { 0 }); zip.AddEntry("contentFiles/cs/net45/code.cs", new byte[] { 0 }); zip.AddEntry("lib/net45/a.dll", new byte[] { 0 }); zip.AddEntry("lib/netstandard1.0/a.dll", new byte[] { 0 }); zip.AddEntry($"build/net45/{id}.targets", @"<Project />", Encoding.UTF8); zip.AddEntry("runtimes/any/native/a.dll", new byte[] { 0 }); zip.AddEntry("tools/a.exe", new byte[] { 0 }); } if (!string.IsNullOrEmpty(runtimeJson)) { zip.AddEntry("runtime.json", runtimeJson, Encoding.UTF8); } var frameworkAssembliesAndContentFiles = packageContext.UseDefaultRuntimeAssemblies ? $@"<frameworkAssemblies> <frameworkAssembly assemblyName=""System.Runtime""/> </frameworkAssemblies> <contentFiles> <files include=""cs/net45/config/config.xml"" buildAction=""none"" /> <files include=""cs/net45/config/config.xml"" copyToOutput=""true"" flatten=""false"" /> <files include=""cs/net45/images/image.jpg"" buildAction=""embeddedresource"" /> </contentFiles>" : string.Empty; var nuspecXml = packageContext.Nuspec?.ToString() ?? $@"<?xml version=""1.0"" encoding=""utf-8""?> <package> <metadata> <id>{id}</id> <version>{version.ToString()}</version> <title /> {frameworkAssembliesAndContentFiles} </metadata> </package>"; var xml = XDocument.Parse(nuspecXml); // Add the min client version if it exists if (!string.IsNullOrEmpty(packageContext.MinClientVersion)) { xml.Root.Element(XName.Get("metadata")) .Add(new XAttribute(XName.Get("minClientVersion"), packageContext.MinClientVersion)); } var dependencies = packageContext.Dependencies.Select(e => new PackageDependency( e.Id, VersionRange.Parse(e.Version), string.IsNullOrEmpty(e.Include) ? new List <string>() : e.Include.Split(',').ToList(), string.IsNullOrEmpty(e.Exclude) ? new List <string>() : e.Exclude.Split(',').ToList())); if (dependencies.Any()) { var metadata = xml.Element(XName.Get("package")).Element(XName.Get("metadata")); var dependenciesNode = new XElement(XName.Get("dependencies")); var groupNode = new XElement(XName.Get("group")); dependenciesNode.Add(groupNode); metadata.Add(dependenciesNode); foreach (var dependency in dependencies) { var node = new XElement(XName.Get("dependency")); groupNode.Add(node); node.Add(new XAttribute(XName.Get("id"), dependency.Id)); node.Add(new XAttribute(XName.Get("version"), dependency.VersionRange.ToNormalizedString())); if (dependency.Include.Count > 0) { node.Add(new XAttribute(XName.Get("include"), string.Join(",", dependency.Include))); } if (dependency.Exclude.Count > 0) { node.Add(new XAttribute(XName.Get("exclude"), string.Join(",", dependency.Exclude))); } } } if (packageContext.FrameworkReferences.Any()) { var metadata = xml.Element(XName.Get("package")).Element(XName.Get("metadata")); var frameworkReferencesNode = new XElement(XName.Get("frameworkReferences")); foreach (var kvp in packageContext.FrameworkReferences) { var groupNode = new XElement(XName.Get("group")); groupNode.SetAttributeValue("targetFramework", kvp.Key.GetFrameworkString()); frameworkReferencesNode.Add(groupNode); metadata.Add(frameworkReferencesNode); foreach (var frameworkReference in kvp.Value) { var node = new XElement(XName.Get("frameworkReference")); groupNode.Add(node); node.Add(new XAttribute(XName.Get("name"), frameworkReference)); } } } if (packageContext.PackageTypes.Count > 0) { var metadata = xml.Element("package").Element("metadata"); var packageTypes = new XElement("packageTypes"); metadata.Add(packageTypes); foreach (var packageType in packageContext.PackageTypes) { var packageTypeElement = new XElement("packageType"); packageTypeElement.Add(new XAttribute("name", packageType.Name)); if (packageType.Version != PackageType.EmptyVersion) { packageTypeElement.Add(new XAttribute("version", packageType.Version)); } packageTypes.Add(packageTypeElement); } } zip.AddEntry($"{id}.nuspec", xml.ToString(), Encoding.UTF8); } if (isUsingTempStream) { using (tempStream) #if IS_DESKTOP using (var signPackage = new SignedPackageArchive(tempStream, stream)) #endif { #if IS_DESKTOP using (var request = GetPrimarySignRequest(packageContext)) { await AddSignatureToPackageAsync(packageContext, signPackage, request, testLogger); } if (packageContext.IsRepositoryCounterSigned) { using (var request = new RepositorySignPackageRequest(new X509Certificate2(packageContext.RepositoryCountersignatureCertificate), HashAlgorithmName.SHA256, HashAlgorithmName.SHA256, packageContext.V3ServiceIndexUrl, packageContext.PackageOwners)) { await AddRepositoryCountersignatureToSignedPackageAsync(packageContext, signPackage, request, testLogger); } } #endif } } // Reset position stream.Position = 0; }
private static XElement GetRestoreGraphProjectInputItem(string path) { return(new XElement(MSBuildNamespace + "RestoreGraphProjectInputItems", new XAttribute(XName.Get("Include"), path))); }
public static WebDavRequestResult CreateObjectsFromNetworkStream(Stream data, String targetUrl, IStorageProviderService service, IStorageProviderSession session, NameBaseFilterCallback callback) { var config = session.ServiceConfiguration as WebDavConfiguration; var results = new WebDavRequestResult(); var queryLessUri = HttpUtilityEx.GetPathAndQueryLessUri(config.ServiceLocator).ToString().TrimEnd('/'); var decodedTargetUrl = HttpUtility.UrlDecode(targetUrl); var s = new StreamReader(data).ReadToEnd(); //todo: var xDoc = XDocument.Load(new StringReader(s.Replace("d:d:", "d:"))); var responses = xDoc.Descendants(XName.Get("response", DavNamespace)); foreach (var response in responses) { bool isHidden = false; bool isDirectory = false; DateTime lastModified = DateTime.Now; long contentLength = 0; var href = response.Element(XName.Get("href", DavNamespace)).ValueOrEmpty(); var propstats = response.Descendants(XName.Get("propstat", DavNamespace)); foreach (var propstat in propstats) { var prop = propstat.Element(XName.Get("prop", DavNamespace)); var status = propstat.Element(XName.Get("status", DavNamespace)).ValueOrEmpty(); if (!status.Equals(HttpOk) || prop == null) { continue; } var strLastModified = prop.Element(XName.Get("getlastmodified", DavNamespace)).ValueOrEmpty(); var strContentLength = prop.Element(XName.Get("getcontentlength", DavNamespace)).ValueOrEmpty(); var resourceType = prop.Element(XName.Get("resourcetype", DavNamespace)); var strIsHidden = prop.Element(XName.Get("ishidden", DavNamespace)).ValueOrEmpty(); if (!String.IsNullOrEmpty(strIsHidden)) { int code; if (!int.TryParse(strIsHidden, out code)) { code = 0; } isHidden = Convert.ToBoolean(code); } if (resourceType.Element(XName.Get("collection", DavNamespace)) != null) { isDirectory = true; } if (!String.IsNullOrEmpty(strContentLength)) { contentLength = Convert.ToInt64(strContentLength); } if (!String.IsNullOrEmpty(strLastModified) && DateTime.TryParse(strLastModified, out lastModified)) { lastModified = lastModified.ToUniversalTime(); } } //entry not to be encluded if (isHidden) { continue; } var nameBase = href; if (callback != null) { nameBase = callback(targetUrl, service, session, nameBase); } String nameBaseForSelfCheck; if (nameBase.StartsWith(config.ServiceLocator.ToString())) { nameBaseForSelfCheck = HttpUtility.UrlDecode(nameBase); nameBase = nameBase.Remove(0, config.ServiceLocator.ToString().Length); } else { nameBaseForSelfCheck = queryLessUri + HttpUtilityEx.PathDecodeUTF8(nameBase); } nameBase = nameBase.TrimEnd('/'); nameBaseForSelfCheck = nameBaseForSelfCheck.TrimEnd('/'); if (targetUrl.EndsWith("/")) { nameBaseForSelfCheck += "/"; } bool isSelf = nameBaseForSelfCheck.Equals(decodedTargetUrl); var ph = new PathHelper(nameBase); var resourceName = HttpUtility.UrlDecode(ph.GetFileName()); BaseFileEntry entry = !isDirectory ? new BaseFileEntry(resourceName, contentLength, lastModified, service, session) : new BaseDirectoryEntry(resourceName, contentLength, lastModified, service, session); if (isSelf) { results.Self = entry; } else { results.Childs.Add(entry); } } return(results); }
/// <summary> /// Parse the children of the 'entry' tag. /// </summary> /// <param name="package"></param> /// <param name="element"></param> private static void ReadEntryChildNode(ref PackageBase package, XElement element) { var value = element.Value.SafeTrim(); switch (element.Name.LocalName.ToLowerInvariant()) { case "id": //In manifest, <id>http://www.nuget.org/api/v2/Packages(Id='jQuery',Version='1.10.1')</id> //we here only need Id=Jquery package.Id = ExtractId(value); break; case "version": package.Version = value; break; case "minclientversion": package.MinClientVersion = string.IsNullOrWhiteSpace(value) ? null : new Version(value); break; case "author": package.Authors = value; break; case "owners": package.Owners = value; break; case "licenseurl": package.LicenseUrl = string.IsNullOrWhiteSpace(value) ? null : new Uri(value); break; case "projecturl": package.ProjectUrl = string.IsNullOrWhiteSpace(value) ? null : new Uri(value); break; case "iconurl": package.IconUrl = string.IsNullOrWhiteSpace(value) ? null : new Uri(value); break; case "gallerydetailsurl": package.GalleryDetailsUrl = string.IsNullOrWhiteSpace(value) ? null : new Uri(value); break; case "requirelicenseacceptance": package.RequireLicenseAcceptance = XmlConvert.ToBoolean(value); break; case "developmentdependency": package.DevelopmentDependency = XmlConvert.ToBoolean(value); break; case "description": package.Description = value; break; case "summary": package.Summary = value; break; case "content": var srcAttribute = element.Attributes(XName.Get("src")).FirstOrDefault(); if (srcAttribute != null) { package.ContentSrcUrl = srcAttribute.Value; } break; case "releasenotes": package.ReleaseNotes = value; break; case "copyright": package.Copyright = value; break; case "language": package.Language = value; break; case "title": package.Title = value; break; case "tags": package.Tags = value; break; case "islatestversion": package.IsLatestVersion = Convert.ToBoolean(value, CultureInfo.InvariantCulture); break; case "isabsolutelatestversion": package.IsAbsoluteLatestVersion = Convert.ToBoolean(value, CultureInfo.InvariantCulture); break; case "published": package.Published = GetDateTime(value); break; case "created": package.Created = GetDateTime(value); break; case "lastupdated": package.LastUpdated = GetDateTime(value); break; case "lastedited": package.LastEdited = GetDateTime(value); break; case "licensereporturl": package.LicenseReportUrl = string.IsNullOrWhiteSpace(value) ? null : new Uri(value); break; case "reportabuseurl": package.ReportAbuseUrl = string.IsNullOrWhiteSpace(value) ? null : new Uri(value); break; case "downloadcount": package.DownloadCount = XmlConvert.ToInt64(value); break; case "versiondownloadcount": package.VersionDownloadCount = XmlConvert.ToInt64(value); break; case "packagesize": package.PackageSize = XmlConvert.ToInt64(value); break; case "properties": var node = element.FirstNode; while (node != null) { var propertyElement = node as XElement; if (propertyElement != null) { ReadEntryChildNode(ref package, propertyElement); } node = node.NextNode; } break; case "dependencies": package.DependencySetList = ParseDependencySet(value); break; case "packagehashalgorithm": package.PackageHashAlgorithm = value; break; case "packagehash": package.PackageHash = value; break; /* case "frameworkAssemblies": * package.FrameworkAssemblies = ReadFrameworkAssemblies(element); * break; * case "references": * package.ReferenceSets = ReadReferenceSets(element); * break;*/ default: if (!String.IsNullOrWhiteSpace(value) && !String.IsNullOrWhiteSpace(element.Name.LocalName)) { package.AdditionalProperties.AddOrSet(element.Name.LocalName, value); } break; } }
/// <summary> /// Loads a .nuspec file inside the given <see cref="XDocument"/>. /// </summary> /// <param name="nuspecDocument">The .nuspec file as an <see cref="XDocument"/>.</param> /// <returns>The newly loaded <see cref="NuspecFile"/>.</returns> public static NuspecFile Load(XDocument nuspecDocument) { NuspecFile nuspec = new NuspecFile(); string nuspecNamespace = nuspecDocument.Root.GetDefaultNamespace().ToString(); XElement package = nuspecDocument.Element(XName.Get("package", nuspecNamespace)); XElement metadata = package.Element(XName.Get("metadata", nuspecNamespace)); nuspec.Id = (string)metadata.Element(XName.Get("id", nuspecNamespace)) ?? string.Empty; nuspec.Version = (string)metadata.Element(XName.Get("version", nuspecNamespace)) ?? string.Empty; nuspec.Title = (string)metadata.Element(XName.Get("title", nuspecNamespace)) ?? string.Empty; nuspec.Authors = (string)metadata.Element(XName.Get("authors", nuspecNamespace)) ?? string.Empty; nuspec.Owners = (string)metadata.Element(XName.Get("owners", nuspecNamespace)) ?? string.Empty; nuspec.LicenseUrl = (string)metadata.Element(XName.Get("licenseUrl", nuspecNamespace)) ?? string.Empty; nuspec.ProjectUrl = (string)metadata.Element(XName.Get("projectUrl", nuspecNamespace)) ?? string.Empty; nuspec.IconUrl = (string)metadata.Element(XName.Get("iconUrl", nuspecNamespace)) ?? string.Empty; nuspec.RequireLicenseAcceptance = bool.Parse((string)metadata.Element(XName.Get("requireLicenseAcceptance", nuspecNamespace)) ?? "False"); nuspec.Description = (string)metadata.Element(XName.Get("description", nuspecNamespace)) ?? string.Empty; nuspec.ReleaseNotes = (string)metadata.Element(XName.Get("releaseNotes", nuspecNamespace)) ?? string.Empty; nuspec.Copyright = (string)metadata.Element(XName.Get("copyright", nuspecNamespace)); nuspec.Tags = (string)metadata.Element(XName.Get("tags", nuspecNamespace)) ?? string.Empty; var repositoryElement = metadata.Element(XName.Get("repository", nuspecNamespace)); if (repositoryElement != null) { nuspec.RepositoryType = (string)repositoryElement.Attribute(XName.Get("type")) ?? string.Empty; nuspec.RepositoryUrl = (string)repositoryElement.Attribute(XName.Get("url")) ?? string.Empty; nuspec.RepositoryBranch = (string)repositoryElement.Attribute(XName.Get("branch")) ?? string.Empty; nuspec.RepositoryCommit = (string)repositoryElement.Attribute(XName.Get("commit")) ?? string.Empty; } nuspec.Dependencies = new List <NugetPackageIdentifier>(); var dependenciesElement = metadata.Element(XName.Get("dependencies", nuspecNamespace)); if (dependenciesElement != null) { IEnumerable <XElement> groups = dependenciesElement.Elements(XName.Get("group", nuspecNamespace)); // get groups if (groups.Count() > 0) // if there are groups { foreach (var iGroup in groups) // add dependancy in game { nuspec.addDependancies(iGroup, nuspecNamespace); } } else // no groups; add children of "dependancies" { nuspec.addDependancies(dependenciesElement, nuspecNamespace); } } nuspec.Files = new List <NuspecContentFile>(); var filesElement = package.Element(XName.Get("files", nuspecNamespace)); if (filesElement != null) { //UnityEngine.Debug.Log("Loading files!"); foreach (var fileElement in filesElement.Elements(XName.Get("file", nuspecNamespace))) { NuspecContentFile file = new NuspecContentFile(); file.Source = (string)fileElement.Attribute("src") ?? string.Empty; file.Target = (string)fileElement.Attribute("target") ?? string.Empty; nuspec.Files.Add(file); } } return(nuspec); }
//========================================================================== public SvgImageElement(SvgDocument document, SvgBaseElement parent, XElement imageElement) : base(document, parent, imageElement) { var x_attribute = imageElement.Attribute("x"); if (x_attribute != null) { X = SvgCoordinate.Parse(x_attribute.Value); } var y_attribute = imageElement.Attribute("y"); if (y_attribute != null) { Y = SvgCoordinate.Parse(y_attribute.Value); } var width_attribute = imageElement.Attribute("width"); if (width_attribute != null) { Width = SvgLength.Parse(width_attribute.Value); } var height_attribute = imageElement.Attribute("height"); if (height_attribute != null) { Height = SvgLength.Parse(height_attribute.Value); } var href_attribute = imageElement.Attribute(XName.Get("href", "http://www.w3.org/1999/xlink")); if (href_attribute != null) { var reference = href_attribute.Value.TrimStart(); if (reference.StartsWith("data:")) { reference = reference.Substring(5).TrimStart(); var index = reference.IndexOf(";"); if (index > -1) { var type = reference.Substring(0, index).Trim(); reference = reference.Substring(index + 1); index = reference.IndexOf(","); var encoding = reference.Substring(0, index).Trim(); reference = reference.Substring(index + 1).TrimStart(); switch (encoding) { case "base64": Data = Convert.FromBase64String(reference); break; default: throw new NotSupportedException($"Unsupported encoding: {encoding}"); } var type_tokens = type.Split('/'); if (type_tokens.Length != 2) { throw new NotSupportedException($"Unsupported type: {type}"); } type_tokens[0] = type_tokens[0].Trim(); if (type_tokens[0] != "image") { throw new NotSupportedException($"Unsupported type: {type}"); } switch (type_tokens[1].Trim()) { case "jpeg": DataType = "jpeg"; break; case "png": DataType = "png"; break; default: throw new NotSupportedException($"Unsupported type: {type}"); } } } } }
public async Task RestoreBuildTargetsAndProps_VerifyPropsAndTargetsGeneratedWithNoTFMConditionsAsync() { // Arrange using (var cacheContext = new SourceCacheContext()) using (var pathContext = new SimpleTestPathContext()) { var logger = new TestLogger(); var sources = new List <PackageSource> { new PackageSource(pathContext.PackageSource) }; var spec = GetProject("projectA", "net462"); spec.RestoreMetadata.CrossTargeting = false; spec.Dependencies.Add(new LibraryDependency() { LibraryRange = new LibraryRange("x", VersionRange.Parse("1.0.0"), LibraryDependencyTarget.Package) }); // Create fake projects, the real data is in the specs var projects = CreateProjectsFromSpecs(pathContext, spec); // Create dg file var dgFile = new DependencyGraphSpec(); dgFile.AddProject(spec); dgFile.AddRestore(spec.RestoreMetadata.ProjectUniqueName); dgFile.Save(Path.Combine(pathContext.WorkingDirectory, "out.dg")); var packageX = new SimpleTestPackageContext() { Id = "x", Version = "1.0.0" }; packageX.AddFile("build/x.targets"); packageX.AddFile("build/x.props"); packageX.AddFile("contentFiles/any/any/_._"); await SimpleTestPackageUtility.CreatePackagesAsync(pathContext.PackageSource, packageX); var project = projects[0]; // Act var summaries = await RunRestoreAsync(pathContext, logger, sources, dgFile, cacheContext); var success = summaries.All(s => s.Success); // Assert Assert.True(success, "Failed: " + string.Join(Environment.NewLine, logger.Messages)); var targetsXML = XDocument.Parse(File.ReadAllText(project.TargetsOutput)); var targetItemGroups = targetsXML.Root.Elements().Where(e => e.Name.LocalName == "ImportGroup").ToList(); var propsXML = XDocument.Parse(File.ReadAllText(project.PropsOutput)); var propsItemGroups = propsXML.Root.Elements().Where(e => e.Name.LocalName == "ImportGroup").ToList(); Assert.Equal("'$(ExcludeRestorePackageImports)' != 'true'", targetItemGroups[0].Attribute(XName.Get("Condition")).Value.Trim()); Assert.Equal("'$(ExcludeRestorePackageImports)' != 'true'", propsItemGroups[0].Attribute(XName.Get("Condition")).Value.Trim()); } }
public static XName GetXName([NotNull] this XElement element, [CanBeNull] string str) { if (element == null) { throw new ArgumentNullException(nameof(element)); } XName result; if (str == null) { result = null; } else { string prefix; string localName; int index; if ((index = str.IndexOf(':')) >= 0) { prefix = str.Substring(0, index); localName = str.Substring(index + 1); } else { prefix = null; localName = null; } if (prefix == null) { try { result = XName.Get(str); } catch { result = null; } } else if (localName == null) { try { result = XName.Get(str); } catch { result = null; } } else { var @namespace = element.GetNamespaceOfPrefix(prefix); if (@namespace == null) { result = null; } else { try { result = @namespace.GetName(localName); } catch { result = null; } } } } return(result); }
private static void BuildElementDictionary() { LocalElementDictionary.Add(XName.Get("Documentation", "http://schemas.microsoft.com/ado/2009/02/edm/ssdl"), typeof(Documentation)); LocalElementDictionary.Add(XName.Get("PropertyRef", "http://schemas.microsoft.com/ado/2009/02/edm/ssdl"), typeof(PropertyRef)); }
/// <summary> /// Constructor of Atom Feed Parser /// </summary> public AtomFeedParser() : base(XName.Get("feed", "http://www.w3.org/2005/Atom")) { }
private static void InitFsm() { var transitions = new Dictionary <int, Transitions>(); transitions.Add(1, new Transitions(new SingleTransition(XName.Get("Documentation", "http://schemas.microsoft.com/ado/2009/02/edm/ssdl"), 2), new SingleTransition(XName.Get("PropertyRef", "http://schemas.microsoft.com/ado/2009/02/edm/ssdl"), 4))); transitions.Add(2, new Transitions(new SingleTransition(XName.Get("PropertyRef", "http://schemas.microsoft.com/ado/2009/02/edm/ssdl"), 4))); transitions.Add(4, new Transitions(new SingleTransition(XName.Get("PropertyRef", "http://schemas.microsoft.com/ado/2009/02/edm/ssdl"), 4), new SingleTransition(new WildCard("##other", "http://schemas.microsoft.com/ado/2009/02/edm/ssdl"), 5))); transitions.Add(5, new Transitions(new SingleTransition(new WildCard("##other", "http://schemas.microsoft.com/ado/2009/02/edm/ssdl"), 5))); _validationStates = new FSM(1, new Set <int>(new[] { 4, 5 }), transitions); }
/// <summary> /// Sets IP Forwarding on a network interface. /// </summary> /// <param name='serviceName'> /// Required. /// </param> /// <param name='deploymentName'> /// Required. /// </param> /// <param name='roleName'> /// Required. /// </param> /// <param name='networkInterfaceName'> /// Required. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the Set IP Forwarding on network /// interface operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> public async Task <OperationStatusResponse> BeginSettingIPForwardingOnNetworkInterfaceAsync(string serviceName, string deploymentName, string roleName, string networkInterfaceName, IPForwardingSetParameters parameters, CancellationToken cancellationToken) { // Validate if (serviceName == null) { throw new ArgumentNullException("serviceName"); } if (deploymentName == null) { throw new ArgumentNullException("deploymentName"); } if (roleName == null) { throw new ArgumentNullException("roleName"); } if (networkInterfaceName == null) { throw new ArgumentNullException("networkInterfaceName"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.State == null) { throw new ArgumentNullException("parameters.State"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("serviceName", serviceName); tracingParameters.Add("deploymentName", deploymentName); tracingParameters.Add("roleName", roleName); tracingParameters.Add("networkInterfaceName", networkInterfaceName); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "BeginSettingIPForwardingOnNetworkInterfaceAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/services/hostedservices/"; url = url + Uri.EscapeDataString(serviceName); url = url + "/deployments/"; url = url + Uri.EscapeDataString(deploymentName); url = url + "/roles/"; url = url + Uri.EscapeDataString(roleName); url = url + "/networkinterfaces/"; url = url + Uri.EscapeDataString(networkInterfaceName); url = url + "/ipforwarding"; string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Post; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2016-07-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; XDocument requestDoc = new XDocument(); XElement iPForwardingElement = new XElement(XName.Get("IPForwarding", "http://schemas.microsoft.com/windowsazure")); requestDoc.Add(iPForwardingElement); XElement stateElement = new XElement(XName.Get("State", "http://schemas.microsoft.com/windowsazure")); stateElement.Value = parameters.State; iPForwardingElement.Add(stateElement); requestContent = requestDoc.ToString(); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result OperationStatusResponse result = null; // Deserialize Response result = new OperationStatusResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return(result); } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } }
/// <summary> /// Gets the value of an attribute of the <see cref="Element"/> in the specified namespace /// </summary> /// <param name="attributeName">The name of the attribute</param> /// <param name="namespaceName">The name of the xml namespace</param> /// <returns>A string with th etest of the attribute value, null if the attribute does not exist</returns> public string GetAttributeValue(string attributeName, string namespaceName) { XAttribute attribute = m_element.Attribute(XName.Get(attributeName, namespaceName)); return((attribute != null) ? attribute.Value : null); }
/// <summary> /// The List Dedicated Circuit Links operation retrieves a list of /// Vnets that are linked to the circuit with the specified service /// key. /// </summary> /// <param name='serviceKey'> /// Optional. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The List Dedicated Circuit Link operation response. /// </returns> public async Task <DedicatedCircuitLinkListResponse> ListAsync(string serviceKey, CancellationToken cancellationToken) { // Validate // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("serviceKey", serviceKey); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/services/networking/dedicatedcircuits/"; if (serviceKey != null) { url = url + Uri.EscapeDataString(serviceKey); } url = url + "/vnets"; List <string> queryParameters = new List <string>(); queryParameters.Add("api-version=1.0"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2011-10-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result DedicatedCircuitLinkListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new DedicatedCircuitLinkListResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement dedicatedCircuitLinksSequenceElement = responseDoc.Element(XName.Get("DedicatedCircuitLinks", "http://schemas.microsoft.com/windowsazure")); if (dedicatedCircuitLinksSequenceElement != null) { foreach (XElement dedicatedCircuitLinksElement in dedicatedCircuitLinksSequenceElement.Elements(XName.Get("DedicatedCircuitLink", "http://schemas.microsoft.com/windowsazure"))) { AzureDedicatedCircuitLink dedicatedCircuitLinkInstance = new AzureDedicatedCircuitLink(); result.DedicatedCircuitLinks.Add(dedicatedCircuitLinkInstance); XElement stateElement = dedicatedCircuitLinksElement.Element(XName.Get("State", "http://schemas.microsoft.com/windowsazure")); if (stateElement != null) { DedicatedCircuitLinkState stateInstance = ((DedicatedCircuitLinkState)Enum.Parse(typeof(DedicatedCircuitLinkState), stateElement.Value, true)); dedicatedCircuitLinkInstance.State = stateInstance; } XElement vnetNameElement = dedicatedCircuitLinksElement.Element(XName.Get("VnetName", "http://schemas.microsoft.com/windowsazure")); if (vnetNameElement != null) { string vnetNameInstance = vnetNameElement.Value; dedicatedCircuitLinkInstance.VnetName = vnetNameInstance; } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return(result); } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } }
/// <summary> /// Adds an attribute to the element /// </summary> /// <param name="localName">The name of the attribute</param> /// <param name="value">The value of the attribute</param> /// <returns>This object with the attribute added</returns> public Element AddAttribute(string localName, string value) { m_element.SetAttributeValue(XName.Get(localName, ""), value); return(this); }
private object Read(Type type, XElement element) { if (type == typeof(String)) { return(element.Value); } if (type.IsPrimitive) { return(Convert.ChangeType(element.Value, type, Culture)); } if (type == Types.DBNull) { return(DBNull.Value); } var rawValue = element.Value; if (string.IsNullOrEmpty(rawValue)) { if (type.IsNullable()) { return(null); } } if (Converter.IsPrimitiveType(type)) { if (string.IsNullOrEmpty(rawValue)) { var attribute = GetAttributeByName(element, XName.Get(type.Name)); rawValue = attribute != null ? attribute.Value : null; } if (string.IsNullOrEmpty(rawValue)) { return(ObjectCreator.Create(type)); } return(Mapper.Map(rawValue, null, type)); } if (type == Types.ByteArray) { return(Convert.FromBase64String(rawValue)); } object item = null; if (type.IsCollectionTypeExcludeStringAndDictionaryType())//.IsSubclassOf(typeof(List<>))) { item = ReadList(element, type); } else if (type.IsDictionaryType() || type == Types.NameValueCollection) { item = ReadDictionary(type, element); } else { item = ObjectCreator.Create(type); } Read(ref item, element); return(item); }
/// <summary> /// Gets elements by tag name /// </summary> /// <param name="element">Element</param> /// <param name="tag">Tag</param> /// <returns>Elementa</returns> internal static IEnumerable <XElement> GetElementsByTagNameLocal(this XElement element, string tag) { return(element.Elements(XName.Get(tag))); }
static void addPostProjectReferences(XDocument doc, string pathToBuiltProject, string extraPath, string productName, string extraRefValue) { XElement sourceElementRoot = null; foreach (var element in doc.Root.Elements()) { if (element.Name.LocalName != "ItemGroup") { continue; } foreach (var subElement in element.Elements()) { if (subElement.Name.LocalName == "Compile") { sourceElementRoot = element; break; } } if (sourceElementRoot != null) { break; } } if (sourceElementRoot != null) { var csSources = new string[] { "WinRT/EmailPlugin.cs", "WinRT/MarketingPlugin.cs", "WinRT/MessageBoxPlugin.cs", #if !WINRT_DISABLE_MS_ADS "WinRT/MicrosoftAdvertising_AdPlugin.cs", #endif #if !WINRT_DISABLE_MS_IAP "WinRT/MicrosoftStore_InAppPurchasePlugin.cs", #endif "WinRT/StreamPlugin.cs", "WinRT/SocialPlugin.cs", "WinRT/WinRTPlugin.cs", #if !WINRT_DISABLE_ADDUPLEX_ADS "WinRT/AdDuplex_AdPlugin.cs", "WinRT/AdDuplex_InterstitialAdPlugin.cs", #endif }; foreach (var source in csSources) { // copy cs file string sourcePath = string.Format("{0}/{1}/{2}", Application.dataPath, "Plugins/Reign/Platforms", source); string sourceFileName = Path.GetFileName(source); File.Copy(sourcePath, string.Format("{0}/{1}{2}/{3}", pathToBuiltProject, productName, extraPath, sourceFileName), true); // make sure we need to reference the file bool needToRefFile = true; foreach (var element in sourceElementRoot.Elements()) { if (element.Name.LocalName == "Compile") { foreach (var a in element.Attributes()) { if (a.Name.LocalName == "Include" && a.Value == (extraRefValue + sourceFileName)) { needToRefFile = false; break; } } } if (!needToRefFile) { break; } } // add reference to cs proj if (needToRefFile) { var name = XName.Get("Compile", doc.Root.GetDefaultNamespace().NamespaceName); var newSource = new XElement(name); newSource.SetAttributeValue(XName.Get("Include"), extraRefValue + sourceFileName); sourceElementRoot.Add(newSource); } } } else { Debug.LogError("Reign Post Build Error: Failed to find CS source element in proj!"); } }
/// <summary> /// The List Subscription Operations operation returns a list of /// create, update, and delete operations that were performed on a /// subscription during the specified timeframe. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/gg715318.aspx /// for more information) /// </summary> /// <param name='parameters'> /// Required. Parameters supplied to the List Subscription Operations /// operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The List Subscription Operations operation response. /// </returns> public async Task <SubscriptionListOperationsResponse> ListOperationsAsync(SubscriptionListOperationsParameters parameters, CancellationToken cancellationToken) { // Validate if (parameters == null) { throw new ArgumentNullException("parameters"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "ListOperationsAsync", tracingParameters); } // Construct URL string url = "/" + (this.Client.Credentials.SubscriptionId == null ? "" : Uri.EscapeDataString(this.Client.Credentials.SubscriptionId)) + "/operations?"; url = url + "&StartTime=" + Uri.EscapeDataString(string.Format(CultureInfo.InvariantCulture, "{0:O}", parameters.StartTime.ToUniversalTime())); url = url + "&EndTime=" + Uri.EscapeDataString(string.Format(CultureInfo.InvariantCulture, "{0:O}", parameters.EndTime.ToUniversalTime())); if (parameters.ObjectIdFilter != null) { url = url + "&ObjectIdFilter=" + Uri.EscapeDataString(parameters.ObjectIdFilter); } if (parameters.OperationStatus != null) { url = url + "&OperationResultFilter=" + Uri.EscapeDataString(parameters.OperationStatus.Value.ToString()); } if (parameters.ContinuationToken != null) { url = url + "&ContinuationToken=" + Uri.EscapeDataString(parameters.ContinuationToken); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2014-10-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result SubscriptionListOperationsResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new SubscriptionListOperationsResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement subscriptionOperationCollectionElement = responseDoc.Element(XName.Get("SubscriptionOperationCollection", "http://schemas.microsoft.com/windowsazure")); if (subscriptionOperationCollectionElement != null) { XElement continuationTokenElement = subscriptionOperationCollectionElement.Element(XName.Get("ContinuationToken", "http://schemas.microsoft.com/windowsazure")); if (continuationTokenElement != null) { string continuationTokenInstance = continuationTokenElement.Value; result.ContinuationToken = continuationTokenInstance; } XElement subscriptionOperationsSequenceElement = subscriptionOperationCollectionElement.Element(XName.Get("SubscriptionOperations", "http://schemas.microsoft.com/windowsazure")); if (subscriptionOperationsSequenceElement != null) { foreach (XElement subscriptionOperationsElement in subscriptionOperationsSequenceElement.Elements(XName.Get("SubscriptionOperation", "http://schemas.microsoft.com/windowsazure"))) { SubscriptionListOperationsResponse.SubscriptionOperation subscriptionOperationInstance = new SubscriptionListOperationsResponse.SubscriptionOperation(); result.SubscriptionOperations.Add(subscriptionOperationInstance); XElement operationIdElement = subscriptionOperationsElement.Element(XName.Get("OperationId", "http://schemas.microsoft.com/windowsazure")); if (operationIdElement != null) { string operationIdInstance = operationIdElement.Value; subscriptionOperationInstance.OperationId = operationIdInstance; } XElement operationObjectIdElement = subscriptionOperationsElement.Element(XName.Get("OperationObjectId", "http://schemas.microsoft.com/windowsazure")); if (operationObjectIdElement != null) { string operationObjectIdInstance = operationObjectIdElement.Value; subscriptionOperationInstance.OperationObjectId = operationObjectIdInstance; } XElement operationNameElement = subscriptionOperationsElement.Element(XName.Get("OperationName", "http://schemas.microsoft.com/windowsazure")); if (operationNameElement != null) { string operationNameInstance = operationNameElement.Value; subscriptionOperationInstance.OperationName = operationNameInstance; } XElement operationParametersSequenceElement = subscriptionOperationsElement.Element(XName.Get("OperationParameters", "http://schemas.microsoft.com/windowsazure")); if (operationParametersSequenceElement != null) { foreach (XElement operationParametersElement in operationParametersSequenceElement.Elements(XName.Get("OperationParameter", "http://schemas.microsoft.com/windowsazure"))) { string operationParametersKey = operationParametersElement.Element(XName.Get("Name", "http://schemas.datacontract.org/2004/07/Microsoft.WindowsAzure.ServiceManagement")).Value; string operationParametersValue = operationParametersElement.Element(XName.Get("Value", "http://schemas.datacontract.org/2004/07/Microsoft.WindowsAzure.ServiceManagement")).Value; subscriptionOperationInstance.OperationParameters.Add(operationParametersKey, operationParametersValue); } } XElement operationCallerElement = subscriptionOperationsElement.Element(XName.Get("OperationCaller", "http://schemas.microsoft.com/windowsazure")); if (operationCallerElement != null) { SubscriptionListOperationsResponse.OperationCallerDetails operationCallerInstance = new SubscriptionListOperationsResponse.OperationCallerDetails(); subscriptionOperationInstance.OperationCaller = operationCallerInstance; XElement usedServiceManagementApiElement = operationCallerElement.Element(XName.Get("UsedServiceManagementApi", "http://schemas.microsoft.com/windowsazure")); if (usedServiceManagementApiElement != null) { bool usedServiceManagementApiInstance = bool.Parse(usedServiceManagementApiElement.Value); operationCallerInstance.UsedServiceManagementApi = usedServiceManagementApiInstance; } XElement userEmailAddressElement = operationCallerElement.Element(XName.Get("UserEmailAddress", "http://schemas.microsoft.com/windowsazure")); if (userEmailAddressElement != null) { string userEmailAddressInstance = userEmailAddressElement.Value; operationCallerInstance.UserEmailAddress = userEmailAddressInstance; } XElement subscriptionCertificateThumbprintElement = operationCallerElement.Element(XName.Get("SubscriptionCertificateThumbprint", "http://schemas.microsoft.com/windowsazure")); if (subscriptionCertificateThumbprintElement != null) { string subscriptionCertificateThumbprintInstance = subscriptionCertificateThumbprintElement.Value; operationCallerInstance.SubscriptionCertificateThumbprint = subscriptionCertificateThumbprintInstance; } XElement clientIPElement = operationCallerElement.Element(XName.Get("ClientIP", "http://schemas.microsoft.com/windowsazure")); if (clientIPElement != null) { string clientIPInstance = clientIPElement.Value; operationCallerInstance.ClientIPAddress = clientIPInstance; } } XElement operationStatusElement = subscriptionOperationsElement.Element(XName.Get("OperationStatus", "http://schemas.microsoft.com/windowsazure")); if (operationStatusElement != null) { string operationStatusInstance = operationStatusElement.Value; subscriptionOperationInstance.OperationStatus = operationStatusInstance; } XElement operationStartedTimeElement = subscriptionOperationsElement.Element(XName.Get("OperationStartedTime", "http://schemas.microsoft.com/windowsazure")); if (operationStartedTimeElement != null) { DateTime operationStartedTimeInstance = DateTime.Parse(operationStartedTimeElement.Value, CultureInfo.InvariantCulture); subscriptionOperationInstance.OperationStartedTime = operationStartedTimeInstance; } XElement operationCompletedTimeElement = subscriptionOperationsElement.Element(XName.Get("OperationCompletedTime", "http://schemas.microsoft.com/windowsazure")); if (operationCompletedTimeElement != null) { DateTime operationCompletedTimeInstance = DateTime.Parse(operationCompletedTimeElement.Value, CultureInfo.InvariantCulture); subscriptionOperationInstance.OperationCompletedTime = operationCompletedTimeInstance; } } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return(result); } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } }