public void createOrUpdate(SubscriptionDefinition d) { var subs = getWorksheet("amps-subs"); int row = 1; if (!Subscriptions.ContainsKey(d.Name)) { // go make a new row. while (true) { if (string.IsNullOrEmpty(subs.Cells[row, 1].Value)) { break; } row++; } } else { row = Subscriptions[d.Name].Row; } subs.Cells[row, 1].Value = d.Name; subs.Cells[row, 2].Value = d.ServerName; subs.Cells[row, 3].Value = d.Topic; subs.Cells[row, 4].Value = d.Filter; subs.Cells[row, 5].Value = d.WorksheetRange; d.Row = row; Subscriptions[d.Name] = d; }
/// <summary> /// Execute the current operation /// </summary> public IEnumerable <object> Execute(SubscriptionDefinition subscription, NameValueCollection parameters, int offset, int?count, out int totalResults, Guid queryId) { if (subscription == null || subscription.ServerDefinitions.Count == 0) { throw new InvalidOperationException("Subscription does not have server definition"); } try { var preArgs = new QueryRequestEventArgs <IdentifiedData>(o => o.Key == subscription.Key, offset, count, queryId, AuthenticationContext.Current.Principal, new ModelSort <IdentifiedData> [0], parameters); this.Executing?.Invoke(this, preArgs); if (preArgs.Cancel) { this.m_tracer.TraceWarning("Pre-Event for executor failed"); totalResults = preArgs.TotalResults; return(preArgs.Results); } var persistenceType = typeof(IDataPersistenceService <>).MakeGenericType(subscription.ResourceType); var persistenceInstance = ApplicationServiceContext.Current.GetService(persistenceType) as IAdoPersistenceService; var queryService = ApplicationServiceContext.Current.GetService <IQueryPersistenceService>(); var cacheService = ApplicationServiceContext.Current.GetService <IDataCachingService>(); // Get the definition var definition = subscription.ServerDefinitions.FirstOrDefault(o => o.InvariantName == m_configuration.Provider.Invariant); if (definition == null) { throw new InvalidOperationException($"Subscription does not provide definition for provider {m_configuration.Provider.Invariant}"); } // No obsoletion time? if (typeof(IBaseEntityData).IsAssignableFrom(subscription.ResourceType) && !parameters.ContainsKey("obsoletionTime")) { parameters.Add("obsoletionTime", "null"); } // Query expression var queryExpression = typeof(QueryExpressionParser).GetGenericMethod( nameof(QueryExpressionParser.BuildLinqExpression), new Type[] { subscription.ResourceType }, new Type[] { typeof(NameValueCollection) } ).Invoke(null, new object[] { parameters }); // Query has been registered? IEnumerable <IdentifiedData> result = null; if (queryId != Guid.Empty && queryService?.IsRegistered(queryId) == true) { totalResults = (int)queryService.QueryResultTotalQuantity(queryId); result = queryService.GetQueryResults(queryId, offset, count ?? 100) .Select(o => { try { var retVal = cacheService.GetCacheItem(o); if (retVal == null) { using (var ctx = m_configuration.Provider.GetReadonlyConnection()) { ctx.Open(); ctx.LoadState = LoadState.FullLoad; retVal = persistenceInstance.Get(ctx, o) as IdentifiedData; cacheService?.Add(retVal); } } return(retVal); } catch (Exception e) { this.m_tracer.TraceError("Error fetching query results for {0}: {1}", queryId, e); throw new DataPersistenceException("Error fetching query results", e); } }).OfType <IdentifiedData>().ToList(); } else { // Now grab the context and query!!! using (var connection = m_configuration.Provider.GetReadonlyConnection()) { try { connection.Open(); connection.LoadState = LoadState.FullLoad; // First, build the query using the query build TableMapping tableMapping = null; if (typeof(Entity).IsAssignableFrom(subscription.ResourceType)) { tableMapping = TableMapping.Get(typeof(DbEntityVersion)); } else if (typeof(Act).IsAssignableFrom(subscription.ResourceType)) { tableMapping = TableMapping.Get(typeof(DbActVersion)); } else if (typeof(Concept).IsAssignableFrom(subscription.ResourceType)) { tableMapping = TableMapping.Get(typeof(DbConceptVersion)); } else { throw new InvalidOperationException("ADO Subscriptions only support Entities and Acts (or sub-types)"); } var query = (typeof(QueryBuilder).GetGenericMethod( nameof(QueryBuilder.CreateQuery), new Type[] { subscription.ResourceType }, new Type[] { queryExpression.GetType(), typeof(ColumnMapping).MakeArrayType() } ).Invoke(this.m_queryBuilder, new object[] { queryExpression, tableMapping.Columns.ToArray() }) as SqlStatement).Build(); // Now we want to remove the portions of the built query statement after FROM and before WHERE as the definition will be the source of our selection SqlStatement domainQuery = new SqlStatement(m_configuration.Provider, query.SQL.Substring(0, query.SQL.IndexOf(" FROM "))); // Append our query var definitionQuery = definition.Definition; List <Object> values = new List <object>(); definitionQuery = this.m_parmRegex.Replace(definitionQuery, (o) => { if (parameters.TryGetValue("_" + o.Groups[2].Value.Substring(1, o.Groups[2].Value.Length - 2), out List <String> qValue)) { Guid uuid = Guid.Empty; if (Guid.TryParse(qValue.First(), out uuid)) { values.AddRange(qValue.Select(v => Guid.Parse(v)).OfType <Object>()); } else { values.AddRange(qValue); } return(o.Groups[1].Value + String.Join(",", qValue.Select(v => "?"))); } return("NULL"); }); // Now we want to append domainQuery.Append(" FROM (").Append(definitionQuery, values.ToArray()).Append($") AS {tableMapping.TableName} "); domainQuery.Append(query.SQL.Substring(query.SQL.IndexOf("WHERE ")), query.Arguments.ToArray()); // Now we want to create the result type var resultType = tableMapping.OrmType; if (typeof(IDbVersionedData).IsAssignableFrom(resultType)) // type is versioned so we have to join { var fkType = tableMapping.GetColumn("Key").ForeignKey.Table; resultType = typeof(CompositeResult <,>).MakeGenericType(resultType, fkType); } // Now we want to select out our results if (count == 0) { totalResults = connection.Count(domainQuery); return(null); } else { // Fetch var domainResults = typeof(DataContext).GetGenericMethod( nameof(DataContext.Query), new Type[] { resultType }, new Type[] { typeof(SqlStatement) }).Invoke(connection, new object[] { domainQuery }) as IOrmResultSet; IEnumerable <object> resultObjects = null; // Register query if query id specified if (queryId != Guid.Empty) { var results = domainResults.Keys <Guid>().OfType <Guid>().ToArray(); this.m_tracer.TraceVerbose("Query for Keys: {0}", connection.GetQueryLiteral(domainResults.Keys <Guid>().ToSqlStatement())); totalResults = results.Count(); ApplicationServiceContext.Current.GetService <IQueryPersistenceService>()?.RegisterQuerySet(queryId, results, null, totalResults); resultObjects = results.Skip(offset).Take(count ?? 100).OfType <Object>(); } else if (m_configuration.UseFuzzyTotals || preArgs.UseFuzzyTotals) { this.m_tracer.TraceVerbose("Query for Objects: {0}", connection.GetQueryLiteral(domainResults.ToSqlStatement())); resultObjects = domainResults.Skip(offset).Take((count ?? 100) + 1).OfType <Object>(); totalResults = domainResults.Count(); } else { this.m_tracer.TraceVerbose("Query for Objects: {0}", connection.GetQueryLiteral(domainResults.ToSqlStatement())); totalResults = domainResults.Count(); resultObjects = domainResults.Skip(offset).Take(count ?? 100).OfType <Object>(); } this.m_tracer.TraceVerbose("If i show up in the log, the log is ???????? WHY?????"); // Return result = resultObjects .Take(count ?? 100) .OfType <Object>() .Select(o => { try { if (o is Guid) { var retVal = cacheService.GetCacheItem((Guid)o); if (retVal == null) { using (var subConn = connection.OpenClonedContext()) { retVal = persistenceInstance.Get(subConn, (Guid)o) as IdentifiedData; cacheService?.Add(retVal); } } return(retVal); } else { var idData = (o as CompositeResult)?.Values.OfType <IDbIdentified>().FirstOrDefault() ?? o as IDbIdentified; var retVal = cacheService.GetCacheItem(idData.Key); if (retVal == null) { using (var subConn = connection.OpenClonedContext()) { retVal = persistenceInstance.ToModelInstance(o, subConn) as IdentifiedData; cacheService?.Add(retVal); } } return(retVal); } } catch (Exception e) { this.m_tracer.TraceError("Error converting result: {0}", e); throw; } }).OfType <IdentifiedData>().ToList(); } } catch (Exception e) { #if DEBUG this.m_tracer.TraceError("Error executing subscription: {0}", e); #else this.m_tracer.TraceError("Error executing subscription: {0}", e.Message); #endif throw new DataPersistenceException($"Error executing subscription: {e.Message}", e); } } // using conn } // if var postEvt = new QueryResultEventArgs <IdentifiedData>(o => o.Key == subscription.Key, result, offset, count, totalResults, queryId, AuthenticationContext.Current.Principal); this.Executed?.Invoke(this, postEvt); // Now set the overridden data return(postEvt.Results); } catch (Exception e) { this.m_tracer.TraceError("Error executing core ADO Subscription logic for {0}: {1}", subscription.Key, e); throw new Exception($"Error executing core ADO subscription logic for {subscription.Key}", e); } }
public void createOrUpdate(SubscriptionDefinition d) { var subs = getWorksheet("amps-subs"); int row = 1; if (!Subscriptions.ContainsKey(d.Name)) { // go make a new row. while (true) { if (string.IsNullOrEmpty(subs.Cells[row, 1].Value)) break; row++; } } else { row = Subscriptions[d.Name].Row; } subs.Cells[row, 1].Value = d.Name; subs.Cells[row, 2].Value = d.ServerName; subs.Cells[row, 3].Value = d.Topic; subs.Cells[row, 4].Value = d.Filter; subs.Cells[row, 5].Value = d.WorksheetRange; d.Row = row; Subscriptions[d.Name] = d; }
/// <summary> /// Start the service /// </summary> public bool Start() { this.Starting?.Invoke(this, EventArgs.Empty); this.m_subscriptionDefinitions = new List <SubscriptionDefinition>(); // Subscribe to the applet manager EventHandler loaderFn = (o, e) => { var retVal = new List <SubscriptionDefinition>(this.m_subscriptionDefinitions?.Count ?? 10); var slns = ApplicationServiceContext.Current.GetService <IAppletSolutionManagerService>().Solutions.ToList(); slns.Add(new AppletSolution() { Meta = new AppletInfo() { Id = String.Empty } }); foreach (var s in slns) { var slnMgr = ApplicationServiceContext.Current.GetService <IAppletSolutionManagerService>().GetApplets(s.Meta.Id); // Find and load all sub defn's foreach (var am in slnMgr) { var definitions = am.Assets.Where(a => a.Name.StartsWith("subscription/")).Select <AppletAsset, SubscriptionDefinition>(a => { using (var ms = new MemoryStream(slnMgr.RenderAssetContent(a))) { this.m_tracer.TraceInfo("Attempting load of {0}", a.Name); try { return(SubscriptionDefinition.Load(ms)); } catch (Exception ex) { this.m_tracer.TraceError("Error loading {0} : {1}", a.Name, ex); return(null); } } }).OfType <SubscriptionDefinition>(); retVal.AddRange(definitions.Where(n => !retVal.Any(a => a.Key == n.Key))); } } this.m_tracer.TraceInfo("Registering applet subscriptions"); lock (m_lockObject) { this.m_subscriptionDefinitions.Clear(); this.m_subscriptionDefinitions.AddRange(retVal); } }; ApplicationServiceContext.Current.Started += (o, e) => { // Collection changed handler this.m_tracer.TraceInfo("Binding to change events"); var appletService = ApplicationServiceContext.Current.GetService <IAppletManagerService>(); if (appletService == null) { throw new InvalidOperationException("No applet manager service has been loaded!!!!"); } ApplicationServiceContext.Current.GetService <IAppletManagerService>().Changed += loaderFn; if ((ApplicationServiceContext.Current.GetService <IAppletManagerService>() as IDaemonService)?.IsRunning == false) { (ApplicationServiceContext.Current.GetService <IAppletManagerService>() as IDaemonService).Started += loaderFn; } else { loaderFn(this, EventArgs.Empty); } }; return(true); }
/// <summary> /// Save the specified definition /// </summary> public SubscriptionDefinition Save(SubscriptionDefinition data) { throw new NotSupportedException(); }
/// <summary> /// Lists the next set of subscriptions /// </summary> /// <param name='nextLink'> /// Required. URL to get the next set of results /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Result of subscription list operation /// </returns> public async Task <SubscriptionListResult> ListNextAsync(string nextLink, CancellationToken cancellationToken) { // Validate if (nextLink == null) { throw new ArgumentNullException("nextLink"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("nextLink", nextLink); TracingAdapter.Enter(invocationId, this, "ListNextAsync", tracingParameters); } // Construct URL string url = ""; url = url + Uri.EscapeDataString(nextLink); 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 // 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 SubscriptionListResult result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new SubscriptionListResult(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { SubscriptionDefinition subscriptionDefinitionInstance = new SubscriptionDefinition(); result.Subscriptions.Add(subscriptionDefinitionInstance); JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); subscriptionDefinitionInstance.Id = idInstance; } JToken subscriptionIdValue = valueValue["subscriptionId"]; if (subscriptionIdValue != null && subscriptionIdValue.Type != JTokenType.Null) { string subscriptionIdInstance = ((string)subscriptionIdValue); subscriptionDefinitionInstance.SubscriptionId = subscriptionIdInstance; } JToken displayNameValue = valueValue["displayName"]; if (displayNameValue != null && displayNameValue.Type != JTokenType.Null) { string displayNameInstance = ((string)displayNameValue); subscriptionDefinitionInstance.DisplayName = displayNameInstance; } JToken externalReferenceIdValue = valueValue["externalReferenceId"]; if (externalReferenceIdValue != null && externalReferenceIdValue.Type != JTokenType.Null) { string externalReferenceIdInstance = ((string)externalReferenceIdValue); subscriptionDefinitionInstance.ExternalReferenceId = externalReferenceIdInstance; } JToken offerIdValue = valueValue["offerId"]; if (offerIdValue != null && offerIdValue.Type != JTokenType.Null) { string offerIdInstance = ((string)offerIdValue); subscriptionDefinitionInstance.OfferId = offerIdInstance; } JToken stateValue = valueValue["state"]; if (stateValue != null && stateValue.Type != JTokenType.Null) { SubscriptionState stateInstance = ((SubscriptionState)Enum.Parse(typeof(SubscriptionState), ((string)stateValue), true)); subscriptionDefinitionInstance.State = stateInstance; } } } JToken odatanextLinkValue = responseDoc["@odata.nextLink"]; if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null) { string odatanextLinkInstance = ((string)odatanextLinkValue); result.NextLink = odatanextLinkInstance; } } } result.StatusCode = statusCode; if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return(result); } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } }
/// <summary> /// Creates or updates the subscription as a tenant /// </summary> /// <param name='parameters'> /// Required. Parameters for creating or updating the subscription /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Subscription definition object after create or update operation /// </returns> public async Task <SubscriptionCreateOrUpdateResult> CreateOrUpdateAsync(SubscriptionCreateOrUpdateParameters parameters, CancellationToken cancellationToken) { // Validate if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.Subscription == null) { throw new ArgumentNullException("parameters.Subscription"); } // 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, "CreateOrUpdateAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (parameters.Subscription.SubscriptionId != null) { url = url + Uri.EscapeDataString(parameters.Subscription.SubscriptionId); } List <string> queryParameters = new List <string>(); queryParameters.Add("api-version=" + Uri.EscapeDataString(this.Client.ApiVersion)); 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.Put; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject subscriptionCreateOrUpdateParametersValue = new JObject(); requestDoc = subscriptionCreateOrUpdateParametersValue; if (parameters.Subscription.Id != null) { subscriptionCreateOrUpdateParametersValue["id"] = parameters.Subscription.Id; } if (parameters.Subscription.SubscriptionId != null) { subscriptionCreateOrUpdateParametersValue["subscriptionId"] = parameters.Subscription.SubscriptionId; } if (parameters.Subscription.DisplayName != null) { subscriptionCreateOrUpdateParametersValue["displayName"] = parameters.Subscription.DisplayName; } if (parameters.Subscription.ExternalReferenceId != null) { subscriptionCreateOrUpdateParametersValue["externalReferenceId"] = parameters.Subscription.ExternalReferenceId; } if (parameters.Subscription.OfferId != null) { subscriptionCreateOrUpdateParametersValue["offerId"] = parameters.Subscription.OfferId; } if (parameters.Subscription.State != null) { subscriptionCreateOrUpdateParametersValue["state"] = parameters.Subscription.State.Value.ToString(); } requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // 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 && statusCode != HttpStatusCode.Created) { 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 SubscriptionCreateOrUpdateResult result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new SubscriptionCreateOrUpdateResult(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { SubscriptionDefinition subscriptionInstance = new SubscriptionDefinition(); result.Subscription = subscriptionInstance; JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); subscriptionInstance.Id = idInstance; } JToken subscriptionIdValue = responseDoc["subscriptionId"]; if (subscriptionIdValue != null && subscriptionIdValue.Type != JTokenType.Null) { string subscriptionIdInstance = ((string)subscriptionIdValue); subscriptionInstance.SubscriptionId = subscriptionIdInstance; } JToken displayNameValue = responseDoc["displayName"]; if (displayNameValue != null && displayNameValue.Type != JTokenType.Null) { string displayNameInstance = ((string)displayNameValue); subscriptionInstance.DisplayName = displayNameInstance; } JToken externalReferenceIdValue = responseDoc["externalReferenceId"]; if (externalReferenceIdValue != null && externalReferenceIdValue.Type != JTokenType.Null) { string externalReferenceIdInstance = ((string)externalReferenceIdValue); subscriptionInstance.ExternalReferenceId = externalReferenceIdInstance; } JToken offerIdValue = responseDoc["offerId"]; if (offerIdValue != null && offerIdValue.Type != JTokenType.Null) { string offerIdInstance = ((string)offerIdValue); subscriptionInstance.OfferId = offerIdInstance; } JToken stateValue = responseDoc["state"]; if (stateValue != null && stateValue.Type != JTokenType.Null) { SubscriptionState stateInstance = ((SubscriptionState)Enum.Parse(typeof(SubscriptionState), ((string)stateValue), true)); subscriptionInstance.State = stateInstance; } } } result.StatusCode = statusCode; if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return(result); } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } }
/// <summary> /// Lists the subscriptions under the user account /// </summary> /// <param name='includeDetails'> /// Required. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Result of subscription list operation /// </returns> public async Task <SubscriptionListResult> ListAsync(bool includeDetails, 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("includeDetails", includeDetails); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions"; List <string> queryParameters = new List <string>(); queryParameters.Add("api-version=" + Uri.EscapeDataString(this.Client.ApiVersion)); queryParameters.Add("includeDetails=" + Uri.EscapeDataString(includeDetails.ToString().ToLower())); 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 // 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 SubscriptionListResult result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new SubscriptionListResult(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { SubscriptionDefinition subscriptionDefinitionInstance = new SubscriptionDefinition(); result.Subscriptions.Add(subscriptionDefinitionInstance); JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); subscriptionDefinitionInstance.Id = idInstance; } JToken subscriptionIdValue = valueValue["subscriptionId"]; if (subscriptionIdValue != null && subscriptionIdValue.Type != JTokenType.Null) { string subscriptionIdInstance = ((string)subscriptionIdValue); subscriptionDefinitionInstance.SubscriptionId = subscriptionIdInstance; } JToken displayNameValue = valueValue["displayName"]; if (displayNameValue != null && displayNameValue.Type != JTokenType.Null) { string displayNameInstance = ((string)displayNameValue); subscriptionDefinitionInstance.DisplayName = displayNameInstance; } JToken externalReferenceIdValue = valueValue["externalReferenceId"]; if (externalReferenceIdValue != null && externalReferenceIdValue.Type != JTokenType.Null) { string externalReferenceIdInstance = ((string)externalReferenceIdValue); subscriptionDefinitionInstance.ExternalReferenceId = externalReferenceIdInstance; } JToken offerIdValue = valueValue["offerId"]; if (offerIdValue != null && offerIdValue.Type != JTokenType.Null) { string offerIdInstance = ((string)offerIdValue); subscriptionDefinitionInstance.OfferId = offerIdInstance; } JToken stateValue = valueValue["state"]; if (stateValue != null && stateValue.Type != JTokenType.Null) { SubscriptionState stateInstance = ((SubscriptionState)Enum.Parse(typeof(SubscriptionState), ((string)stateValue), true)); subscriptionDefinitionInstance.State = stateInstance; } } } JToken odatanextLinkValue = responseDoc["@odata.nextLink"]; if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null) { string odatanextLinkInstance = ((string)odatanextLinkValue); result.NextLink = odatanextLinkInstance; } } } result.StatusCode = statusCode; if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return(result); } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } }