Exemple #1
0
        public ActionResult SaveSubscriptionInfo(List <UserSubscription> subscriptions)
        {
            try
            {
                var listOfUserSubscription = new List <UserSubscription>();
                foreach (var subscription in subscriptions)
                {
                    UserSubscription userSubscription = new UserSubscription(subscription.SubscriptionId, subscription.OrganizationId);
                    userSubscription.DisplayName = subscription.DisplayName;
                    userSubscription.OfferId     = subscription.OfferId;
                    userSubscription.Currency    = subscription.Currency;
                    userSubscription.RegionInfo  = subscription.RegionInfo;
                    listOfUserSubscription.Add(userSubscription);
                }

                var repo = new EntityRepo <UserSubscription>();
                if (listOfUserSubscription.Count > 0)
                {
                    repo.Insert(listOfUserSubscription);
                }
                return(Json(new { Message = "Success" }, JsonRequestBehavior.AllowGet));
            }
            catch (Exception exp)
            {
                Logger.Log("Subscription-Web-API", "Error", exp.Message, exp.ToString());
                return(new HttpStatusCodeResult(500, exp.Message));
            }
        }
Exemple #2
0
        private static void SaveAggregateDailyByAccount(string monthId, string runId, List <EAUsageDetailEntity> data)
        {
            var aggregateUsage = from us in data
                                 group us by new
            {
                us.PartitionKey,
                us.AccountName,
                us.Date
            }
            into fus
                select new EAUsageAccountDailySummaryEntity()
            {
                Amount       = fus.Sum(x => (string.IsNullOrEmpty(x.ExtendedCost) ? 0.00 : float.Parse(x.ExtendedCost))),
                PartitionKey = monthId,
                AccountName  = fus.Key.AccountName,
                RowKey       = fus.Key.Date.Replace("/", "-") + "_" + fus.Key.AccountName,
                RunId        = runId,
                Day          = fus.Key.Date
            };

            EntityRepo <EAUsageAccountDailySummaryEntity> usageEntityRepoAgg = new EntityRepo <EAUsageAccountDailySummaryEntity>();
            var aggData = aggregateUsage.ToList();

            usageEntityRepoAgg.Insert(aggData);
        }
Exemple #3
0
        private static void SaveAggregateMeter(string monthId, string runId, List <EAUsageDetailEntity> data)
        {
            var aggregateUsage = from us in data
                                 group us by new
            {
                us.PartitionKey,
                us.MeterId,
                us.MeterName,
                us.MeterCategory,
            }
            into fus
                select new EAUsageMeterSummaryEntity()
            {
                Amount        = fus.Sum(x => (string.IsNullOrEmpty(x.ExtendedCost) ? 0.00 : float.Parse(x.ExtendedCost))),
                PartitionKey  = monthId,
                MeterId       = fus.Key.MeterId,
                MeterCategory = fus.Key.MeterCategory,
                MeterName     = fus.Key.MeterName,
                RowKey        = monthId + "_" + fus.Key.MeterId,
                RunId         = runId
            };

            var aggData = aggregateUsage.ToList();
            EntityRepo <EAUsageMeterSummaryEntity> usageEntityRepoAgg = new EntityRepo <EAUsageMeterSummaryEntity>();

            usageEntityRepoAgg.Insert(aggData);
        }
        private void WriteUserTokenCache(UserTokenCache cache)
        {
            EntityRepo <UserTokenCache> repo = new EntityRepo <UserTokenCache>();

            repo.Insert(new List <UserTokenCache> {
                cache
            });
        }
Exemple #5
0
        public ActionResult Refresh()
        {
            try
            {
                // get all organizations and their respective subscription for a given tenant
                var orgs = AzureResourceManagerUtil.GetUserOrganizations();
                Dictionary <Organization, List <Subscription> > dictionary = new Dictionary <Organization, List <Subscription> >();
                foreach (var item in orgs)
                {
                    if (!dictionary.ContainsKey(item))
                    {
                        var subscriptions = AzureResourceManagerUtil.GetUserSubscriptions(item.Id);
                        dictionary.Add(item, subscriptions);
                    }
                }

                // check if these subscriptions are already added in the storage
                var repo = new EntityRepo <UserSubscription>();
                var list = repo.Get(USER_SUBSCRIPTION_TABLE_PARTITION_KEY, null, "");
                var existingSubscriptions = new Dictionary <string, string>();
                foreach (var item in list)
                {
                    existingSubscriptions.Add(item.SubscriptionId, item.SubscriptionId);
                }

                // list of new subscription to add
                var listOfUserSubscription = new List <UserSubscription>();
                foreach (var subscriptions in dictionary.Values)
                {
                    foreach (var subscription in subscriptions)
                    {
                        UserSubscription userSubscription = new UserSubscription(subscription.Id, subscription.OrganizationId);
                        userSubscription.DisplayName = subscription.DisplayName;

                        // if the subscription is not already in the storage add them
                        // otherwise the one in the storage should have latest info
                        if (!existingSubscriptions.ContainsKey(userSubscription.SubscriptionId))
                        {
                            listOfUserSubscription.Add(userSubscription);
                        }
                    }
                }

                // if one or more subscriptions are discovered, add them
                if (listOfUserSubscription.Count > 0)
                {
                    repo.Insert(listOfUserSubscription);
                }
                return(Json(dictionary.ToList(), JsonRequestBehavior.AllowGet));
            }
            catch (Exception exp)
            {
                Logger.Log("Subscription-Web-API", "Error", exp.Message, exp.ToString());
                return(new HttpStatusCodeResult(500, exp.Message));
            }
        }
Exemple #6
0
        private static void GetUsageData(Dictionary <string, MeterData> meterRateDictionary, string subscriptionName, string subscriptionId, string organizationId, string startTime, string endTime, string pullId, string baseUrl)
        {
            string requestUrl = String.Format("{0}/ratecard/GetUsageData?subscriptionId={1}&organizationId={2}&startDate={3}&endDate={4}",
                                              baseUrl,
                                              subscriptionId,
                                              organizationId,
                                              startTime,
                                              endTime);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUrl);
            // Read Response
            HttpWebResponse response      = (HttpWebResponse)request.GetResponse();
            Stream          receiveStream = response.GetResponseStream();

            // read stream as text
            StreamReader responseStream = new StreamReader(receiveStream);
            string       usageText      = responseStream.ReadToEnd();

            UsageDetailsTemp         usage        = JsonConvert.DeserializeObject <UsageDetailsTemp>(usageText);
            List <AzureUsageDetails> usageDetails = new List <AzureUsageDetails>();
            DateTime detailsDateTime = DateTime.Now;

            if (usage != null && usage.value != null)
            {
                foreach (Value val in usage.value)
                {
                    var instanceId = "None";
                    if (val.properties.instanceData != null)
                    {
                        var instanceKey = JToken.Parse(val.properties.instanceData);
                        instanceId = (string)instanceKey["Microsoft.Resources"]["resourceUri"];
                    }

                    var aggregateKey            = val.properties.usageStartTime + "_" + val.properties.usageEndTime;
                    var rowKey                  = GetInstanceBasedRowKey(val.properties.subscriptionId, val.properties.meterId, instanceId, aggregateKey);
                    var partitionKey            = GetMonthBasedPartitionKey(Convert.ToDateTime(val.properties.usageEndTime));
                    AzureUsageDetails newDetail = GetInstanceLevelUsageDetail(detailsDateTime, subscriptionName, pullId, val, instanceId, rowKey, partitionKey);
                    usageDetails.Add(newDetail);
                }
            }
            EntityRepo <AzureUsageDetails> usageEntityRepo = new EntityRepo <AzureUsageDetails>();

            usageEntityRepo.Insert(usageDetails);

            IEnumerable <AzureUsageDetailsDaily> aggregateUsage     = AggregateAtDailyUsage(usageDetails, meterRateDictionary);
            EntityRepo <AzureUsageDetailsDaily>  usageEntityRepoAgg = new EntityRepo <AzureUsageDetailsDaily>();

            usageEntityRepoAgg.Insert(aggregateUsage.ToList());

            IEnumerable <AzureUsageDetailsMeterAggregate> aggregateSubscription     = AggregateAtMeterWithExpense(meterRateDictionary, usageDetails);
            EntityRepo <AzureUsageDetailsMeterAggregate>  aggregateSubscriptionRepo = new EntityRepo <AzureUsageDetailsMeterAggregate>();

            aggregateSubscriptionRepo.Insert(aggregateSubscription.ToList());
        }
Exemple #7
0
        private static List <EAUsageDetailEntity> SaveDetails(string jsonData, string partitionKey, string runId)
        {
            List <EAUsageDetailEntity> usageDetailList = JsonConvert.DeserializeObject <List <EAUsageDetailEntity> >(jsonData);

            foreach (EAUsageDetailEntity entity in usageDetailList)
            {
                var refinedInstanceId = entity.InstanceId.Replace("/", "SPL_CHAR").Replace("\\", "SPL_CHAR").Replace("#", "SPL_CHAR").Replace("?", "SPL_CHAR");
                entity.PartitionKey = partitionKey;
                entity.RowKey       = partitionKey + "_" + entity.MeterId + "_" + refinedInstanceId;
                entity.RunId        = runId;
            }
            EntityRepo <EAUsageDetailEntity> usageEntityRepoAgg = new EntityRepo <EAUsageDetailEntity>();

            usageEntityRepoAgg.Insert(usageDetailList);

            return(usageDetailList);
        }
Exemple #8
0
        private static void LogWebJobRunInfo(string message, DateTime jobStartTime, DateTime jobEndTime)
        {
            string monthStr = DateTime.UtcNow.Month < 10 ? "0" + DateTime.UtcNow.Month.ToString() : DateTime.UtcNow.Month.ToString();
            string yearStr  = DateTime.UtcNow.Year.ToString();

            // Insert RunId after each successful run
            EntityRepo <WebJobRunInfo> repo = new EntityRepo <WebJobRunInfo>();

            repo.Insert(new List <WebJobRunInfo>()
            {
                new WebJobRunInfo {
                    PartitionKey = yearStr + "-" + monthStr,
                    RowKey       = Guid.NewGuid().ToString(),
                    RunId        = message,
                    StartTimeUTC = jobStartTime,
                    EndTimeUTC   = jobEndTime
                }
            });
        }
Exemple #9
0
        static void Main(string[] args)
        {
            string month = DateTime.UtcNow.Month < 10 ? "0" + DateTime.UtcNow.Month.ToString() : DateTime.UtcNow.Month.ToString();
            string year  = DateTime.UtcNow.Year.ToString();

            //EA uses YYYY-MM format
            string baseUrl    = System.Configuration.ConfigurationManager.AppSettings["API-URL"];
            string requesturl = String.Format("{0}/EaUsage/GetUsageData?yyyy={1}&mm={2}",
                                              baseUrl, year, month);

            //Build Request
            DateTime       startTime = DateTime.UtcNow;
            HttpWebRequest request   = (HttpWebRequest)WebRequest.Create(requesturl);

            // Read Response
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            Console.WriteLine(response.StatusDescription);
            StreamReader reader     = new StreamReader(response.GetResponseStream());
            var          jsonString = reader.ReadToEnd();
            DateTime     endTime    = DateTime.UtcNow;

            //Get Run Id
            JToken outer = JToken.Parse(jsonString);
            string runId = (string)outer["RunId"];

            // Insert RunId after each successful run
            EntityRepo <EAWebJobRunInfo> repo = new EntityRepo <EAWebJobRunInfo>();

            repo.Insert(new List <EAWebJobRunInfo>()
            {
                new EAWebJobRunInfo {
                    PartitionKey = year + "-" + month,
                    RowKey       = runId,
                    RunId        = runId,
                    StartTimeUTC = startTime,
                    EndTimeUTC   = endTime
                }
            });
        }