public async Task <CustomerContainer> GetCustomerContainerWithRetryAsync(bool retry = true) { CustomerContainer container = null; try { container = await GetCustomerContainerAsync(_token); } catch (AuthorizationException) { if (retry) { await RenewAuthToken(); container = await GetCustomerContainerAsync(_token); } else { throw; } } catch (Exception) { throw; } return(container); }
public async static Task Run([TimerTrigger("0 0 * * * *")] TimerInfo myTimer, TraceWriter log, ExecutionContext context) { var config = new ConfigurationBuilder() .SetBasePath(context.FunctionAppDirectory) .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables() .Build(); string eventHubName = config["EventHubName"]; string eventHubConnectionString = config["EventHubConnectionString"]; var container = new CustomerContainer() { Currency = config["Currency"], RegionInfo = config["RegionInfo"], SubscriptionId = config["SubscriptionId"], ClientId = config["client_Id"], ClientKey = config["client_key"], TenantDomain = config["tenant"], OfferId = config["OfferId"], ArmBillingServiceUrl = config["ARMBillingServiceURL"], AdalServiceUrl = config["ADALServiceURL"] }; var invoker = new BillingInvoker(eventHubName, eventHubConnectionString); await invoker.PopulateRecentRateAndUsageInformation(container); }
static void Main(string[] args) { try { CustomerContainer ctx = new CustomerContainer(); var q = ctx.ExecuteStoreQuery<CUSTOMER_MV>("SELECT * FROM UNNEST CUSTOMER ON ORDERS"); //CUSTID is 'S' //FNAME is 'S' //PRODID is 'M' //DESCRIPTION is 'M' foreach (var item in q) { Console.WriteLine(item.CUSTID + "=>" + item.FNAME + "=>" + item.PRODID + "=>" + item.DESCRIPTION); } } catch (Exception e3) { Console.WriteLine(e3.Message); } finally { Console.WriteLine("Enter to exit:"); string line = Console.ReadLine(); } }
public async Task <IServiceResult> DetailAsync(Guid uuid) { try { var address = await _addressRepository.GetAddressesFromCustomer(uuid); var localPhones = await GetPhonesAsync(address); var phones = await _phoneRepository.GetPhonesFromCustomerAsync(uuid); var customer = await _customerRepository.GetAsync(uuid, x => x.Addresses); if (customer is null) { return(new NotFoundResult()); } var result = new CustomerContainer { Customer = customer, Addresses = address, LocalPhones = localPhones, Phones = phones }; return(new SuccessResult <CustomerContainer>(result)); } catch (Exception e) { _logger.LogError(e, "Error while retrieving data"); return(new FailResult()); } }
public async Task <CustomerContainer> GetCustomerContainerAsync(string token) { CustomerContainer container = null; HttpClient client = this.GetHttpClientToken(token); HttpResponseMessage response = await client.GetAsync(_serverUrl + "customers/"); string content = await response.Content.ReadAsStringAsync(); switch (response.StatusCode) { case System.Net.HttpStatusCode.OK: Debug.WriteLine(content); container = JsonConvert.DeserializeObject <CustomerContainer>(content); break; case System.Net.HttpStatusCode.Unauthorized: throw new AuthorizationException("Unknown token"); default: throw new Exception(content); } return(container); }
void Start () { cContainer = GameObject.Find("CustomerContainer").GetComponent<CustomerContainer>(); } // END Start
public async Task <string> MakeRequest(CustomerContainer container) { // configure the start time usage first of all and then end time in ISO8601 - time wi string usageStartTime = container.StartTime.ToString("yyyy-MM-ddTHH:00:00Z").Replace(":", "%3a"); string usageEndTime = container.EndTime.ToString("yyyy-MM-ddTHH:00:00Z").Replace(":", "%3a"); string payload = null; var issuer = new TokenIssuer(); // Build up the HttpWebRequest string requestUrl = $"{container.ArmBillingServiceUrl}/subscriptions/{container.SubscriptionId}/providers/Microsoft.Commerce/UsageAggregates?api-version=2015-06-01-preview&reportedstartTime={usageStartTime}&reportedEndTime={usageEndTime}&aggregationGranularity=Hourly&showDetails=true"; var newRequest = container.RequestNextLink ?? requestUrl; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(newRequest); // Add the OAuth Authorization header, and Content Type header request.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + await issuer.GetOAuthTokenFromAad(container)); request.ContentType = "application/json"; // TODO: check to see that a valid response code is being returned here... using (var response = new StreamReader(request.GetResponse().GetResponseStream())) { payload = await response.ReadToEndAsync(); } return(payload); }
public async Task <T> MakeObjectRequest <T>(CustomerContainer container) { var payload = await MakeRequest(container); // read this into a JSON string we're going to get each next link var conversion = JsonConvert.DeserializeObject <Usage>(payload); var nextPayload = new NextPayload(conversion.NextLink, conversion.Value); // crappy but works - boxing/unboxing get rid of return((T)(object)nextPayload); }
public DetailCustomerModel(CustomerContainer container) { Addresses = container.Addresses; Phones = container.Phones; LocalPhones = container.LocalPhones; Roomates = container.Roomates; Id = container.Customer.Id; Uuid = container.Customer.Uuid; Name = container.Customer.Name; Email = container.Customer.Email; }
// GET: Customer public ActionResult Index() { Console.WriteLine(User.Identity.Name); String name = User.Identity.Name; CustomerContainer customerContainer = new CustomerContainer(); Customer customer = new Customer(); var data = from c in customerContainer.Customers where c.EmailAddress == name select c; ViewBag.data = data.ToList(); return(View()); }
public ActionResult login(LoginFormModel newLogIn) { using (var context = new CustomerContainer()) { bool isValid = context.Customers.Any(x => x.EmailAddress == newLogIn.EmailAddress && x.Password == newLogIn.Password); if (isValid) { FormsAuthentication.SetAuthCookie(newLogIn.EmailAddress, false); return(RedirectToAction("Index", "Customer")); } } ModelState.AddModelError("", "Invalid username and password"); return(View()); }
void Start() { this.gameObject.transform.parent = GameObject.Find("CustomerContainer").gameObject.transform; cContainer = GameObject.Find("CustomerContainer").GetComponent<CustomerContainer>(); product = cContainer.GetWeapon(); difficulty = cContainer.GetDifficultyCheck(); DifficultySettings(); customerName = "Customer #" + cContainer.customerCount; this.gameObject.name = customerName; ChangePhase(1); } // END Start
/// <summary> /// Iterates through the customers and populates their data into SQL /// </summary> public async Task PopulateRecentRateAndUsageInformation(CustomerContainer container) { var connectionStringBuilder = new EventHubsConnectionStringBuilder(_eventConnectionString) { EntityPath = _eventHubName }; var eventHubClient = EventHubClient.CreateFromConnectionString(connectionStringBuilder.ToString()); var now = DateTime.UtcNow; //Set the sart and end dates to pull data into the db var lastUpdateReportedStart = DateTime.UtcNow.Subtract(TimeSpan.FromHours(6)); var reportEndDate = DateTime.UtcNow.Subtract(TimeSpan.FromHours(5)); var usage = new AzureUsage(container); var rates = await usage.GetCombinedRatesAndUsage(lastUpdateReportedStart, reportEndDate, container.OfferId); int index = 0; int count = rates.Value.Count; var customerDatas = new List <CustomerData>(); foreach (var rate in rates.Value) { string jsonOut = JsonConvert.SerializeObject(new CustomerData() { Category = rate.Properties.MeterCategory, MeterId = rate.Properties.MeterId, Price = rate.Properties.Price, Cost = rate.Properties.Cost, Unit = rate.Properties.Unit, Quantity = rate.Properties.Quantity, MeterName = rate.Properties.MeterName, StartTime = DateTime.Parse(rate.Properties.UsageStartTime), EndTime = DateTime.Parse(rate.Properties.UsageEndTime), SubscriptionId = container.SubscriptionId, ResourceGroup = rate.Properties.ResourceGroup, ReportedStartDate = rates.ReportedStartDate, ReportedEndDate = rates.ReportedEndData, ResourceProvider = rate.Properties.ResourceProvider, ResourceName = rate.Properties.ResourceName, ResourceInstanceName = rate.Properties.ResourceSubName, Tags = rate.Properties.Tags, Location = rate.Properties.Location }); await eventHubClient.SendAsync(new EventData(Encoding.UTF8.GetBytes(jsonOut))); Console.WriteLine($"Adding record {++index} of {count} "); } await eventHubClient.CloseAsync(); }
public async Task <string> GetOAuthTokenFromAad(CustomerContainer customer) { var authenticationContext = new AuthenticationContext( $"{customer.AdalServiceUrl}/{customer.TenantDomain}"); //Ask the logged in user to authenticate, so that this client app can get a token on his behalf var result = await authenticationContext.AcquireTokenAsync( $"{customer.ArmBillingServiceUrl}/", new ClientCredential(customer.ClientId, customer.ClientKey)); if (result == null) { throw new InvalidOperationException("Failed to obtain the JWT token"); } return(result.AccessToken); }
public ActionResult Register(CustomerFormModel newCustomer) { CustomerContainer customer = new CustomerContainer(); Customer c = new Customer() { FirstName = newCustomer.FirstName, LastName = newCustomer.LastName, EmailAddress = newCustomer.EmailAddress, Password = newCustomer.Password, PhoneNumber = newCustomer.PhoneNumber, isActive = "true" }; customer.Customers.Add(c); customer.SaveChanges(); return(RedirectToAction("RegisterForwardPage")); }
// https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/Microsoft.Sql/servers/{server-name}/databases/{database-name}/metrics?api-version={api-version}&$filter={metrics-filter} public async Task <List <DatabaseMetric> > GetMetrics(CustomerContainer container) { const string urlSqlDb = "(name / value eq 'blocked_by_firewall' or name / value eq 'connection_failed' or name / value eq 'connection_successful' or name / value eq 'cpu_percent' or name / value eq 'deadlock' or name / value eq 'dtu_consumption_percent' or name / value eq 'log_write_percent' or name / value eq 'log_write_percent' or name / value eq 'physical_data_read_percent' or name / value eq 'storage' or name / value eq 'storage_percent' or name / value eq 'workers_percent' or name / value eq 'sessions_percent' or name / value eq 'dtu_limit' or name / value eq 'dtu_used' or name / value eq 'dwu_limit' or name / value eq 'dwu_used' or name / value eq 'dwu_consumption_percent') and timeGrain eq '00:00:15'"; var allDataMetrics = new List <DatabaseMetric>(); _container = container; var login = new AzureLogin(container); var token = await login.AcquireToken(login.Audience); var tokenCredentials = new TokenCredentials(token); var client = new SqlManagementClient(tokenCredentials) { SubscriptionId = container.SubscriptionId }; var rgs = await login.GetSubscriptionsResourceGroups(login.GetSubscriptions); var subs = rgs.Where(subsrgs => subsrgs.Subscription.SubscriptionId == container.SubscriptionId).Select(rgs1 => rgs1.ResourceGroup); foreach (var rg in subs) { foreach (var server in client.Servers.ListByResourceGroup(rg)) { foreach (var db in await client.Databases.ListByServerAsync(rg, server.Name)) { var dbMetrics = new List <DataMetric>(new DataMetric[] { new DtuLimit(), new DtuUsed(), new DtuConsumptionPercentage(), new DwuLimit(), new DwuUsed(), new DwuConsumptionPercentage(), new BlockedByFirewall(), new CpuPercent(), new FailedConnections(), new SuccessfulConnections() }); var filteredDb = await GetMetricsQueryResponse(container.SubscriptionId, container.RunReportStartTime.Value, container.RunReportEndTime.Value, db.Name, rg, server.Name, login, token, urlSqlDb, dbMetrics, DataSourceType.SqlDb); if (filteredDb == null) { continue; } allDataMetrics.Add(filteredDb); } } } return(allDataMetrics); }
public async Task <string> MakeRequest(CustomerContainer container) { string payload = null; var issuer = new TokenIssuer(); // Build up the HttpWebRequest string requestUrl = $"{container.ArmBillingServiceUrl}/subscriptions/{container.SubscriptionId}/providers/Microsoft.Commerce/RateCard?api-version=2015-06-01-preview&$filter=OfferDurableId eq '{container.OfferId}' and Currency eq '{container.Currency}' and Locale eq 'en-GB' and RegionInfo eq '{container.RegionInfo}'"; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUrl); // Add the OAuth Authorization header, and Content Type header request.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + await issuer.GetOAuthTokenFromAad(container)); request.ContentType = "application/json"; // TODO: check to see that a valid response code is being returned here... using (var response = new StreamReader(request.GetResponse().GetResponseStream())) { payload = await response.ReadToEndAsync(); } return(payload); }
private void SearchButton_Click(object sender, EventArgs e) { //Container.BringToFront(); if (Customer.Checked) { if (!string.IsNullOrWhiteSpace(SearchTextBox.Text)) { if (p1.SearchCustomer(SearchTextBox.Text)) { CustomerContainer.BringToFront(); SearchPanel.Hide(); Registration.Hide(); AmountPayment.Hide(); amountpaymentcu.Hide(); } else { MessageBox.Show("Wrong ID"); } } } else if (Dealer.Checked) { if (p1.SearchDealer(SearchTextBox.Text)) { DealerContainer.BringToFront(); SearchPanel.Hide(); Registration.Hide(); AmountPayment.Hide(); amountpaymentcu.Hide(); } else { MessageBox.Show("Wrong ID"); } } Registration.Hide(); }
public Customer AddCustomer(Customer customer) { return(CustomerContainer.AddCustomer(customer)); }
/// <summary> /// Invoked using a subscription id - important to ensure that app service principal is at least in the read role for the "subscription" /// </summary> public AzureRateCard(IBillingRequest rateCardRequest, CustomerContainer customer) { Customer = customer; BillingRequest = rateCardRequest; }
public Customer GetById(int customerId) { return(CustomerContainer.GetById(customerId)); }
public IEnumerable <Customer> GetAll() { return(CustomerContainer.GetAll()); }
public async Task DeleteContainers() { await CustomerContainer.DeleteContainerAsync(); await OrdersContainer.DeleteContainerAsync(); }
public IEnumerable <Customer> GetStoreCustomers(int storeId) { return(CustomerContainer.GetStoreCustomers(storeId)); }
public Task <T> MakeObjectRequest <T>(CustomerContainer container) { throw new System.NotImplementedException(); }
public IEnumerable <Customer> GetUserCustomers(int userId) { return(CustomerContainer.GetUserCustomers(userId)); }
public Customer ModifyCustomer(Customer customer) { return(CustomerContainer.UpdateCustomer(customer)); }
public AzureUsage(CustomerContainer customer) : this(new AzureRateCard(customer), new UsageBillingRequest(), customer) { }
public AzureUsage(IRateCardApi rateCard, IBillingRequest request, CustomerContainer customer) { Customer = customer; RateCard = rateCard; BillingRequest = request; }
public void RemoveCustomer(int customerId) { CustomerContainer.RemoveCustomer(customerId); }
public AzureRateCard(CustomerContainer customer) : this(new RateCardBillingRequest(), customer) { }