public async Task MoveAsync(long id, long?parentId)
        {
            var entity = await EntityRepo.GetAsync(id);

            if (entity.ParentId == parentId)
            {
                return;
            }

            //查询当前的子项内容
            var children = await FindChildrenAsync(id, true);

            //保存当前的Code码
            var oldCode = entity.Code;

            //移动课程分类
            entity.Code = await GetNextChildCodeAsync(parentId);

            entity.ParentId = parentId;

            await ValidateCourseCategoryAsync(entity);

            //更新子项的编码
            foreach (var child in children)
            {
                child.Code = OrganizationUnit.AppendCode(entity.Code, OrganizationUnit.GetRelativeCode(child.Code, oldCode));
            }
        }
Esempio n. 2
0
        private static void PullUsageAndBillingData(string baseUrl)
        {
            string   runId        = "";
            DateTime jobStartTime = DateTime.UtcNow;
            DateTime jobEndTime   = DateTime.UtcNow;

            var missingSubscriptionIds = new List <string>();

            // pull subscription data
            EntityRepo <UserSubscription> subscriptionRepo = new EntityRepo <UserSubscription>();
            var subscriptionList = subscriptionRepo.Get(USER_SUBSCRIPTION_TABLE_PARTITION_KEY, null, "").ToList();

            foreach (var item in subscriptionList)
            {
                jobStartTime = DateTime.UtcNow;
                string subscriptionId   = item.SubscriptionId;
                string organizationId   = item.OrganizationId;
                string offerId          = item.OfferId;
                string currency         = item.Currency;
                string regionInfo       = item.RegionInfo;
                string subscriptionName = item.DisplayName;

                // pulling the month to date data
                // including the last month last date as well
                var    today                   = DateTime.UtcNow;
                var    currentMonth            = new DateTime(today.Year, today.Month, 1);
                var    lastDateOfPreviousMonth = currentMonth.AddDays(-1);
                string endTime                 = GetDateString(today);
                string startTime               = GetDateString(lastDateOfPreviousMonth);

                // if subscription data is incomplete, skip the whole data load process
                if (!IsValidData(subscriptionId, organizationId, offerId, currency, regionInfo))
                {
                    missingSubscriptionIds.Add(subscriptionId);
                    continue;
                }

                runId = Guid.NewGuid().ToString();
                string language = ConfigurationManager.AppSettings["Language"];
                // get rate card data
                Dictionary <string, MeterData> meterRateDictionary = GetMeterData(subscriptionId, organizationId, offerId, currency, language, regionInfo, baseUrl);

                // get usage data
                GetUsageData(meterRateDictionary, subscriptionName, subscriptionId, organizationId, startTime, endTime, runId, baseUrl);
                jobEndTime = DateTime.UtcNow;
            }

            // log message for yet to be configured subscriptions
            if (missingSubscriptionIds.Count > 0)
            {
                string message = "USER ACTION REQUIRED FOR Subscription(s): " + string.Join(",", missingSubscriptionIds.ToArray()) + " Visit Dashboard, go to 'My Subscription' and fill up details.";
                LogWebJobRunInfo(message, jobStartTime, jobEndTime);
            }

            // log the run info
            if (!string.IsNullOrEmpty(runId))
            {
                LogWebJobRunInfo(runId, jobStartTime, jobEndTime);
            }
        }
Esempio n. 3
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));
            }
        }
Esempio n. 4
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);
        }
Esempio n. 5
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);
        }
Esempio n. 6
0
        private UserTokenCache GetCacheFromStorage(string user)
        {
            EntityRepo <UserTokenCache> repo = new EntityRepo <UserTokenCache>();
            var list  = repo.Get("UserTokenCache", null, user);
            var first = list.FirstOrDefault();

            return(first);
        }
Esempio n. 7
0
        private void WriteUserTokenCache(UserTokenCache cache)
        {
            EntityRepo <UserTokenCache> repo = new EntityRepo <UserTokenCache>();

            repo.Insert(new List <UserTokenCache> {
                cache
            });
        }
        public async Task <CourseCategory> CreateAsync(CourseCategory entity)
        {
            entity.Code = await GetNextChildCodeAsync(entity.ParentId);
            await ValidateCourseCategoryAsync(entity);

            entity.Id = await EntityRepo.InsertAndGetIdAsync(entity);

            return(entity);
        }
Esempio n. 9
0
        public async Task ChangeStatus(Guid orderId, OrderStatusEnum orderStatus)
        {
            var entity = await EntityRepo.GetAsync(orderId);


            entity.Status = orderStatus;

            await EntityRepo.UpdateAsync(entity);
        }
Esempio n. 10
0
        // clean up the storage
        public override void Clear()
        {
            base.Clear();
            EntityRepo <UserTokenCache> repo = new EntityRepo <UserTokenCache>();

            repo.Delete(new UserTokenCache {
                RowKey = tokenOwner
            });
        }
Esempio n. 11
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));
            }
        }
 /// <summary>
 /// 根据课程分类id集合移除所有课程关系
 /// </summary>
 /// <param name="courseCategoryIds">课程分类id集合</param>
 /// <returns></returns>
 public async Task RemoveAllByCategoryIds(List <long> courseCategoryIds)
 {
     if (courseCategoryIds == null || courseCategoryIds.Count == 0)
     {
         return;
     }
     await EntityRepo.DeleteAsync(
         o => courseCategoryIds.Contains(o.CourseCategoryId)
         );
 }
        /// <summary>
        /// 从课程分类中移除所选课程 - 批量
        /// </summary>
        /// <param name="courseCategoryId">分类id</param>
        /// <param name="courseIds">课程id集合</param>
        /// <returns></returns>
        public async Task BatchRemoveCourseFromCategory(long courseCategoryId, List <long> courseIds)
        {
            if (courseIds == null || courseIds.Count == 0)
            {
                return;
            }

            await EntityRepo.DeleteAsync(o =>
                                         o.CourseCategoryId == courseCategoryId && courseIds.Contains(o.CourseId)
                                         );
        }
        public async Task BatchDelete(List <long> input)
        {
            if (input == null || input.Count == 0)
            {
                return;
            }

            await EntityRepo.DeleteAsync(a => input.Contains(a.Id));

            await _courseToCourseCategoryManager.RemoveAllByCategoryIds(input);
        }
Esempio n. 15
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());
        }
Esempio n. 16
0
        /// <summary>
        /// Get Azure expense by account (summary)
        /// </summary>
        /// <param name="monthId">month in YYYY-mm format</param>
        /// <returns>expenses for a given month in JSON format</returns>
        public JsonResult SpendingByAccount(string monthId = "")
        {
            if (string.IsNullOrEmpty(monthId))
            {
                monthId = GetMonthId();
            }
            var repo  = new EntityRepo <EAUsageAccountSummaryEntity>();
            var data  = repo.Get(monthId, new List <Tuple <string, string> > {
            });
            var array = data.Select(p => new { name = p.AccountName, y = p.Amount });

            return(Json(array.ToList(), JsonRequestBehavior.AllowGet));
        }
        /// <summary>
        /// 添加课程到分类
        /// </summary>
        /// <param name="courseCategoryId">分类id</param>
        /// <param name="courseId">课程id</param>
        /// <returns></returns>
        public async Task AddCourseToCategory(long courseCategoryId, long courseId)
        {
            if (await IsExist(courseId, courseCategoryId))
            {
                return;
            }

            await EntityRepo.InsertAsync(new CourseToCourseCategory
            {
                CourseId         = courseId,
                CourseCategoryId = courseCategoryId
            });
        }
        /// <summary>
        /// 更新课程分类
        /// </summary>
        /// <param name="courseId">课程id</param>
        /// <param name="courseCategoryIds">分类id数组</param>
        /// <returns></returns>
        public async Task UpdateCourseToCategory(long courseId, params long[] courseCategoryIds)
        {
            await this.RemoveAllByCourseId(courseId);

            foreach (var courseCategoryId in courseCategoryIds)
            {
                await EntityRepo.InsertAsync(new CourseToCourseCategory
                {
                    CourseId         = courseId,
                    CourseCategoryId = courseCategoryId
                });
            }
        }
Esempio n. 19
0
        /// <summary>
        /// Get Azure expense by subscription (summary)
        /// </summary>
        /// <param name="monthId">month in YYYY-mm format</param>
        /// <returns>expenses for a given month in JSON format</returns>
        public JsonResult SpendingBySubscription(string monthId = "")
        {
            if (string.IsNullOrEmpty(monthId))
            {
                monthId = GetMonthId();
            }

            var repo  = new EntityRepo <AzureUsageDetailsMeterAggregate>();
            var data  = repo.Get(monthId, new List <Tuple <string, string> > {
            });
            var array = data.GroupBy(x => x.SubscriptionName).Select(a => new { name = a.Key, y = Math.Max(a.Sum(w => w.Amount), 0.0) });

            return(Json(array.ToList(), JsonRequestBehavior.AllowGet));
        }
Esempio n. 20
0
        /// <summary>
        /// Get Azure expense by subscription (daily)
        /// </summary>
        /// <param name="monthId">month in YYYY-mm format</param>
        /// <returns>expenses for a given month in JSON format</returns>
        public JsonResult SpendingBySubscriptionDaily(string monthId = "")
        {
            if (string.IsNullOrEmpty(monthId))
            {
                monthId = GetMonthId();
            }
            var repo = new EntityRepo <AzureUsageDetailsDaily>();
            var data = repo.Get(monthId, new List <Tuple <string, string> > {
            });

            var aggregateUsage = data.OrderBy(x => x.UsageEndTime).GroupBy(x => new { x.SubscriptionName, x.UsageEndTime }).Select(p => new DailyBillInfo {
                Amount = Math.Max(p.Sum(y => y.Amount), 0.0), Name = p.Key.SubscriptionName, Date = p.Key.UsageEndTime.ToString("yyyy-MM-dd")
            });

            return(GetDailyBillSeries(aggregateUsage));
        }
Esempio n. 21
0
        /// <summary>
        /// Get Azure expense by account (daily)
        /// </summary>
        /// <param name="monthId">month in YYYY-mm format</param>
        /// <returns>expenses for a given month in JSON format</returns>
        public JsonResult SpendingByAccountDaily(string monthId = "")
        {
            if (string.IsNullOrEmpty(monthId))
            {
                monthId = GetMonthId();
            }
            var repo = new EntityRepo <EAUsageAccountDailySummaryEntity>();
            var data = repo.Get(monthId, new List <Tuple <string, string> > {
            });

            var aggregateUsage = data.OrderBy(x => x.Day).Select(p => new DailyBillInfo {
                Amount = p.Amount, Name = p.AccountName, Date = p.Day
            });

            return(GetDailyBillSeries(aggregateUsage));
        }
Esempio n. 22
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);
        }
        /// <summary>
        /// 查询子级分类
        /// </summary>
        /// <param name="parentId">父级分类id</param>
        /// <param name="recursive">是否无限向下查询</param>
        /// <returns></returns>
        protected async Task <List <CourseCategory> > FindChildrenAsync(long?parentId, bool recursive = false)
        {
            if (!recursive)
            {
                return(await EntityRepo.GetAllListAsync(ou => ou.ParentId == parentId));
            }

            if (!parentId.HasValue)
            {
                return(await EntityRepo.GetAllListAsync());
            }

            var code = await GetCodeAsync(parentId.Value);

            return(await EntityRepo.GetAllListAsync(
                       ou => ou.Code.StartsWith(code) && ou.Id != parentId.Value
                       ));
        }
Esempio n. 24
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
                }
            });
        }
Esempio n. 25
0
        /// <summary>
        /// Get Azure expense by azure services (daily)
        /// </summary>
        /// <param name="monthId">month in YYYY-mm format</param>
        /// <returns>expenses for a given month in JSON format</returns>
        public JsonResult SpendingByServiceDaily(string monthId = "")
        {
            var dictionary  = new Dictionary <string, Dictionary <string, double> >();
            var uniqueDates = new Dictionary <string, string>();

            if (string.IsNullOrEmpty(monthId))
            {
                monthId = GetMonthId();
            }
            var repo = new EntityRepo <AzureUsageDetailsDaily>();
            var data = repo.Get(monthId, new List <Tuple <string, string> > {
            });

            var aggregateUsage = data.OrderBy(x => x.UsageEndTime).Select(p => new DailyBillInfo {
                Amount = Math.Max(p.Amount, 0.0), Name = p.MeterCategory, Date = p.UsageEndTime.ToString("yyyy-MM-dd")
            });

            return(GetDailyBillSeries(aggregateUsage));
        }
Esempio n. 26
0
        /// <summary>
        /// Get Azure expense by azure services (daily)
        /// </summary>
        /// <param name="monthId">month in YYYY-mm format</param>
        /// <returns>expenses for a given month in JSON format</returns>
        public JsonResult SpendingByServiceDaily(string monthId = "")
        {
            var dictionary  = new Dictionary <string, Dictionary <string, double> >();
            var uniqueDates = new Dictionary <string, string>();

            if (string.IsNullOrEmpty(monthId))
            {
                monthId = GetMonthId();
            }
            var repo = new EntityRepo <EAUsageMeterDailySummaryEntity>();
            var data = repo.Get(monthId, new List <Tuple <string, string> > {
            });

            var aggregateUsage = data.OrderBy(x => x.Day).Select(p => new DailyBillInfo {
                Amount = p.Amount, Name = p.MeterCategory, Date = p.Day
            });

            return(GetDailyBillSeries(aggregateUsage));
        }
Esempio n. 27
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
                }
            });
        }
Esempio n. 28
0
        public ActionResult GetSubscriptionDetails()
        {
            try
            {
                EntityRepo <UserSubscription> subscriptionRepo = new EntityRepo <UserSubscription>();
                var list = subscriptionRepo.Get(USER_SUBSCRIPTION_TABLE_PARTITION_KEY, null, "").Select(p => new {
                    SubscriptionId = p.SubscriptionId,
                    OrganizationId = p.OrganizationId,
                    DisplayName    = p.DisplayName,
                    OfferId        = p.OfferId,
                    Currency       = p.Currency,
                    RegionInfo     = p.RegionInfo
                });;

                return(Json(list, JsonRequestBehavior.AllowGet));
            }
            catch (Exception exp)
            {
                Logger.Log("Subscription-Web-API", "Error", exp.Message, exp.ToString());
                return(new HttpStatusCodeResult(500, exp.Message));
            }
        }
        /// <summary>
        /// 添加课程到分类 - 批量
        /// </summary>
        /// <param name="courseCategoryId">分类id</param>
        /// <param name="courseIds">课程id集合</param>
        /// <returns></returns>
        public async Task BatchAddCourseToCategory(long courseCategoryId, List <long> courseIds)
        {
            if (courseIds == null || courseIds.Count == 0)
            {
                return;
            }
            var createCourseIds = courseIds.Except(this.GetCateCourses(courseCategoryId));

            if (createCourseIds.Count() == 0)
            {
                return;
            }

            foreach (var courseId in createCourseIds)
            {
                await EntityRepo.InsertAsync(new CourseToCourseCategory
                {
                    CourseId         = courseId,
                    CourseCategoryId = courseCategoryId
                });
            }
        }
        /// <summary>
        ///     更加旧数据,添加新数据到数据库中
        /// </summary>
        public async Task SychronousVideoInsertToData(List <VideoResource> newVideoInfos)
        {
            var newVideoIds = newVideoInfos.Select(a => a.VideoId).ToList();

            //已经存在的数据,
            var dataVideoInfos = await QueryAsNoTracking
                                 .Where(a => newVideoIds.Contains(a.VideoId)).ToListAsync();

            //已经存在的数据,做数据更新处理
            var updateVideos = newVideoInfos.Where(a => dataVideoInfos.Exists(d => d.VideoId == a.VideoId)).ToList();

            updateVideos.ForEach(o => newVideoInfos.Remove(o));

            foreach (var newVideoInfo in newVideoInfos)
            {
                await EntityRepo.InsertAsync(newVideoInfo);
            }

            foreach (var entity in updateVideos)
            {
                //更新数据中的数据
                var tempEntity = dataVideoInfos.Find(o => o.VideoId == entity.VideoId);

                if (tempEntity == null)
                {
                    continue;
                }

                var id = tempEntity.Id;

                tempEntity = entity;

                tempEntity.Id = id;

                await UpdateAsync(tempEntity);
            }
        }