Exemple #1
0
        /// <summary>
        /// Check if a domain name is available
        /// </summary>
        /// <param name="bearerToken">The Azure bearer token</param>
        /// <param name="subscription">Subscription Id for authorization</param>
        /// <param name="domainName">Domain name to check for availability. Note that the Azure App Service Domain only supports
        /// checking and purchase of selected domain TLDs.</param>
        /// <returns>True if available, False if not, NULL if there was an error.</returns>
        public static async Task <bool?> IsAvailable(string bearerToken, Guid subscription, string domainName)
        {
            if (string.IsNullOrWhiteSpace(bearerToken))
            {
                throw new ArgumentNullException(nameof(bearerToken));
            }
            if (subscription == Guid.Empty)
            {
                throw new ArgumentNullException(nameof(subscription));
            }

            // this will cause validation of the domainName and will throw!
            AvailabilityRequest request = new AvailabilityRequest(domainName);

            RestApiResponse response = await RestApiClient.POST(
                bearerToken,
                $"https://management.azure.com/subscriptions/{subscription:d}/providers/Microsoft.DomainRegistration/checkDomainAvailability",
                CLIENT_API_VERSION,
                null, request,
                new int[] { 200 }
                );

            if ((!response.IsExpectedSuccess) || response.WasException || string.IsNullOrWhiteSpace(response.Body))
            {
                return(null);
            }

            AvailabilityResult result = JsonConvert.DeserializeObject <AvailabilityResult>(response.Body);

            return(result.IsAvailable);
        }
        public virtual ActionResult Index(string id, SurveyResultViewModel model)
        {
            var count = Results.GetResults(CurrentResource, CurrentUser).Count;

            if (CurrentResource.MaxTimes.HasValue && count > CurrentResource.MaxTimes)
            {
                return(View("Unavailable", AvailabilityResult.No("This survey can only be taken " + CurrentResource.MaxTimes + " times.")));
            }

            // score the Survey
            var result = CurrentResource.Score(CurrentUser, model.Answers);

            // possibly award points
            if (result.PointsEarned.HasValue && result.PointsEarned > 0)
            {
                var tx = TryAwardPoints(result.PointsEarned.Value);
                if (null != tx)
                {
                    result.Transaction = tx.Document.Id;
                }
            }
            Results.Save(result);

            // show the review screen
            return(RedirectToAction(MVC.Site.Survey.Review(id, result.Document.Id)));
        }
Exemple #3
0
        private static AvailabilityResult GetFakeAvailabilityResult()
        {
            var availabilityResult = new AvailabilityResult();

            availabilityResult.AvailabilityViewList.Add("000000000000");
            availabilityResult.AvailabilityViewList.Add("000000000000");

            return(availabilityResult);
        }
        public virtual ActionResult Index(string id)
        {
            var count = Results.GetResults(CurrentResource, CurrentUser).Count;

            if (CurrentResource.MaxTimes.HasValue && count > CurrentResource.MaxTimes)
            {
                return(View("Unavailable", AvailabilityResult.No("This survey can only be taken " + CurrentResource.MaxTimes + " times.")));
            }
            return(View(SurveyViewModel.FromDomain(CurrentResource)));
        }
    public FrameworkResult(AvailabilityResult availability,
                           ObsoletionResult?obsoletion,
                           IReadOnlyList <PlatformResult?> platforms)
    {
        ArgumentNullException.ThrowIfNull(platforms);

        Availability = availability;
        Obsoletion   = obsoletion;
        Platforms    = platforms;
    }
Exemple #6
0
 public static IServiceManager SetParticipantNotAvailable()
 {
     mockCalendarService.Setup(service => service.GetUserAvailabilityAsync(It.IsAny <string>(), It.IsAny <List <string> >(), It.IsAny <DateTime>(), It.IsAny <int>())).Returns(() =>
     {
         var result = new AvailabilityResult();
         result.AvailabilityViewList.Add("222222000000");
         result.AvailabilityViewList.Add("000000000000");
         return(Task.FromResult(result));
     });
     return(mockServiceManager.Object);
 }
        public void WhenCriticalContentIsFalse_IsOkShouldReturnFalse()
        {
            var item = new AvailabilityResult(false, true, true);

            Assert.IsFalse(item.IsOk());

            item = new AvailabilityResult(true, false, true);
            Assert.IsFalse(item.IsOk());

            item = new AvailabilityResult(true, true, false);
            Assert.IsTrue(item.IsOk());

            item = new AvailabilityResult(false, false, false);
            Assert.IsFalse(item.IsOk());
        }
Exemple #8
0
 public static IServiceManager SetOrgnizerNotAvailable()
 {
     mockCalendarService.Setup(service => service.GetUserAvailabilityAsync(It.IsAny <string>(), It.IsAny <List <string> >(), It.IsAny <DateTime>(), It.IsAny <int>())).Returns((string userEmail, List <string> users, DateTime startTime, int availabilityViewInterval) =>
     {
         var result = new AvailabilityResult();
         result.AvailabilityViewList.Add("000000000000");
         result.AvailabilityViewList.Add("222222000000");
         result.MySchedule.Add(new EventModel(CalendarSkill.Models.EventSource.Microsoft)
         {
             Title     = Strings.Strings.DefaultEventName,
             StartTime = startTime,
             EndTime   = startTime.AddHours(1)
         });
         return(Task.FromResult(result));
     });
     return(mockServiceManager.Object);
 }
        public async Task <AvailabilityResult> GetUserAvailabilityAsync(string userEmail, List <string> attendees, DateTime startTime, int availabilityViewInterval)
        {
            List <bool> availability = new List <bool>();

            attendees.Add(userEmail);
            var schedules = attendees;
            var endTime   = startTime.AddDays(1);

            var intervalStartTime = new DateTimeTimeZone
            {
                DateTime = startTime.ToString(),
                TimeZone = "UTC"
            };

            var intervalEndTime = new DateTimeTimeZone
            {
                DateTime = endTime.ToString(),
                TimeZone = "UTC"
            };

            ICalendarGetScheduleCollectionPage collectionPage = await _graphClient.Me.Calendar
                                                                .GetSchedule(schedules, intervalEndTime, intervalStartTime, availabilityViewInterval)
                                                                .Request()
                                                                .PostAsync();

            var result = new AvailabilityResult();

            // set non-working time as 3 in availability view
            foreach (var collection in collectionPage)
            {
                var availabilityView = collection.AvailabilityView.ToCharArray();
                if (collection.WorkingHours != null)
                {
                    var workingTimeZone           = TimeZoneInfo.FindSystemTimeZoneById(collection.WorkingHours.TimeZone.Name);
                    var startTimeInWorkTimeZone   = TimeConverter.ConvertUtcToUserTime(startTime, workingTimeZone);
                    var workingStartTimeTimeOfDay = collection.WorkingHours.StartTime;
                    var workingStartTime          = new DateTime(
                        startTimeInWorkTimeZone.Year,
                        startTimeInWorkTimeZone.Month,
                        startTimeInWorkTimeZone.Day,
                        workingStartTimeTimeOfDay.Hour,
                        workingStartTimeTimeOfDay.Minute,
                        workingStartTimeTimeOfDay.Second);

                    var workingEndTimeTimeOfDay = collection.WorkingHours.EndTime;
                    var workingEndTime          = new DateTime(
                        startTimeInWorkTimeZone.Year,
                        startTimeInWorkTimeZone.Month,
                        startTimeInWorkTimeZone.Day,
                        workingEndTimeTimeOfDay.Hour,
                        workingEndTimeTimeOfDay.Minute,
                        workingEndTimeTimeOfDay.Second);

                    var workDays = collection.WorkingHours.DaysOfWeek.Select(li => (int)li);
                    for (int i = 0; i < availabilityView.Length; i++)
                    {
                        if (availabilityView[i] == '0')
                        {
                            var availabilityViewStartTime = startTime.AddMinutes(i * CalendarCommonUtil.AvailabilityViewInterval);
                            availabilityViewStartTime = TimeConverter.ConvertUtcToUserTime(availabilityViewStartTime, workingTimeZone);

                            if (!workDays.Contains((int)availabilityViewStartTime.DayOfWeek))
                            {
                                availabilityView[i] = '3';
                                continue;
                            }

                            var availabilityViewEndTime = availabilityViewStartTime.AddMinutes(CalendarCommonUtil.AvailabilityViewInterval);

                            if (!((availabilityViewStartTime.TimeOfDay >= workingStartTime.TimeOfDay && availabilityViewStartTime.TimeOfDay < workingEndTime.TimeOfDay) ||
                                  (availabilityViewEndTime.TimeOfDay > workingStartTime.TimeOfDay && availabilityViewEndTime.TimeOfDay <= workingEndTime.TimeOfDay)))
                            {
                                availabilityView[i] = '3';
                            }
                        }
                    }
                }

                result.AvailabilityViewList.Add(new string(availabilityView));
            }

            result.MySchedule.AddRange(collectionPage.Last().ScheduleItems.Select(li => new EventModel(EventSource.Microsoft)
            {
                Title     = li.Subject,
                StartTime = DateTime.Parse(li.Start.DateTime + "Z").ToUniversalTime(),
                EndTime   = DateTime.Parse(li.End.DateTime + "Z").ToUniversalTime(),
                Location  = li.Location
            }));

            return(result);
        }
Exemple #10
0
        static MockServiceManager()
        {
            buildinEvents               = GetFakeEvents();
            BuildinPeoples              = GetFakePeoples();
            BuildinUsers                = GetFakeUsers();
            BuildinAvailabilityResult   = GetFakeAvailabilityResult();
            BuildinCheckAvailableResult = GetFakeCheckAvailable();

            // calendar
            mockCalendarService = new Mock <ICalendarService>();
            mockCalendarService.Setup(service => service.CreateEventAsync(It.IsAny <EventModel>())).Returns((EventModel body) => Task.FromResult(body));
            mockCalendarService.Setup(service => service.GetUpcomingEventsAsync(null)).Returns(Task.FromResult(buildinEvents));
            mockCalendarService.Setup(service => service.GetEventsByTimeAsync(It.IsAny <DateTime>(), It.IsAny <DateTime>())).Returns(Task.FromResult(buildinEvents));
            mockCalendarService.Setup(service => service.GetEventsByStartTimeAsync(It.IsAny <DateTime>())).Returns(Task.FromResult(buildinEvents));
            mockCalendarService.Setup(service => service.GetEventsByTitleAsync(It.IsAny <string>())).Returns(Task.FromResult(buildinEvents));
            mockCalendarService.Setup(service => service.UpdateEventByIdAsync(It.IsAny <EventModel>())).Returns((EventModel body) => Task.FromResult(body));
            mockCalendarService.Setup(service => service.DeleteEventByIdAsync(It.IsAny <string>())).Returns(Task.CompletedTask);
            mockCalendarService.Setup(service => service.AcceptEventByIdAsync(It.IsAny <string>())).Returns(Task.CompletedTask);
            mockCalendarService.Setup(service => service.DeclineEventByIdAsync(It.IsAny <string>())).Returns(Task.CompletedTask);
            mockCalendarService.Setup(service => service.GetUserAvailabilityAsync(It.IsAny <string>(), It.IsAny <List <string> >(), It.IsAny <DateTime>(), It.IsAny <int>())).Returns(Task.FromResult(BuildinAvailabilityResult));
            mockCalendarService.Setup(service => service.CheckAvailableAsync(It.IsAny <List <string> >(), It.IsAny <DateTime>(), It.IsAny <int>())).Returns(Task.FromResult(BuildinCheckAvailableResult));

            // user
            mockUserService = new Mock <IUserService>();
            mockUserService.Setup(service => service.GetPeopleAsync(It.IsAny <string>())).Returns((string name) =>
            {
                if (name == Strings.Strings.ThrowErrorAccessDenied)
                {
                    throw new SkillException(SkillExceptionType.APIAccessDenied, Strings.Strings.ThrowErrorAccessDenied, new Exception());
                }

                return(Task.FromResult(BuildinPeoples));
            });
            mockUserService.Setup(service => service.GetUserAsync(It.IsAny <string>())).Returns((string name) =>
            {
                if (name == Strings.Strings.ThrowErrorAccessDenied)
                {
                    throw new SkillException(SkillExceptionType.APIAccessDenied, Strings.Strings.ThrowErrorAccessDenied, new Exception());
                }

                return(Task.FromResult(BuildinUsers));
            });
            mockUserService.Setup(service => service.GetContactsAsync(It.IsAny <string>())).Returns((string name) =>
            {
                return(Task.FromResult(new List <PersonModel>()));
            });
            mockUserService.Setup(service => service.GetMeAsync()).Returns(() =>
            {
                var emailAddressStr = Strings.Strings.DefaultUserEmail;
                var userNameStr     = Strings.Strings.DefaultUserName;
                var addressList     = new List <ScoredEmailAddress>();
                var emailAddress    = new ScoredEmailAddress()
                {
                    Address        = emailAddressStr,
                    RelevanceScore = 1,
                };
                addressList.Add(emailAddress);

                var people = new Person()
                {
                    UserPrincipalName    = emailAddressStr,
                    ScoredEmailAddresses = addressList,
                    DisplayName          = userNameStr,
                };

                return(Task.FromResult(new PersonModel(people)));
            });

            // manager
            mockServiceManager = new Mock <IServiceManager>();
            mockServiceManager.Setup(manager => manager.InitCalendarService(It.IsAny <string>(), It.IsAny <CalendarSkill.Models.EventSource>())).Returns(mockCalendarService.Object);
            mockServiceManager.Setup(manager => manager.InitUserService(It.IsAny <string>(), It.IsAny <CalendarSkill.Models.EventSource>())).Returns(mockUserService.Object);
        }
Exemple #11
0
    public static void Run(ApiCatalogModel catalog,
                           IReadOnlyCollection <string> filePaths,
                           IReadOnlyList <NuGetFramework> frameworks,
                           bool analyzeObsoletion,
                           IReadOnlyList <string> platforms,
                           Action <AssemblyResult> resultReceiver)
    {
        var apiByGuid           = catalog.GetAllApis().ToDictionary(a => a.Guid);
        var availabilityContext = ApiAvailabilityContext.Create(catalog);

        var platformContexts = frameworks.Select(fx => PlatformAnnotationContext.Create(availabilityContext, fx.GetShortFolderName()))
                               .ToDictionary(pc => pc.Framework);

        foreach (var api in catalog.GetAllApis())
        {
            var forwardedApi = catalog.GetForwardedApi(api);
            if (forwardedApi is not null)
            {
                apiByGuid[api.Guid] = forwardedApi.Value;
            }
        }

        var apiAvailability = new ConcurrentDictionary <ApiModel, ApiAvailability>();

        var resultSink = new BlockingCollection <AssemblyResult>();

        var resultSinkTask = Task.Run(() =>
        {
            foreach (var result in resultSink.GetConsumingEnumerable())
            {
                resultReceiver(result);
            }
        });

        Parallel.ForEach(filePaths, filePath =>
        {
            using var env    = new HostEnvironment();
            var assembly     = env.LoadAssemblyFrom(filePath);
            var assemblyName = assembly is not null
                                ? assembly.Name.Value
                                : Path.GetFileName(filePath);
            if (assembly is null)
            {
                var result = new AssemblyResult(assemblyName, "Not a valid .NET assembly", Array.Empty <ApiResult>());
                resultSink.Add(result);
            }
            else
            {
                var assemblyTfm       = assembly.GetTargetFrameworkMoniker();
                var assemblyFramework = string.IsNullOrEmpty(assemblyTfm) ? null : NuGetFramework.Parse(assemblyTfm);

                var crawler = new AssemblyCrawler();
                crawler.Crawl(assembly);

                var crawlerResults = crawler.GetResults();

                var apiResults             = new List <ApiResult>();
                var frameworkResultBuilder = new List <FrameworkResult>(frameworks.Count);
                var platformResultBuilder  = new List <PlatformResult?>(platforms.Count);

                foreach (var apiKey in crawlerResults.Data.Keys)
                {
                    if (apiByGuid.TryGetValue(apiKey.Guid, out var api))
                    {
                        var availability = apiAvailability.GetOrAdd(api, a => availabilityContext.GetAvailability(a));

                        frameworkResultBuilder.Clear();

                        foreach (var framework in frameworks)
                        {
                            // Analyze availability

                            AvailabilityResult availabilityResult;

                            var infos = availability.Frameworks.Where(fx => fx.Framework == framework).ToArray();

                            // NOTE: There are APIs that exist in multiple places in-box, e.g. Microsoft.Windows.Themes.ListBoxChrome.
                            //       It doesn't really matter for our purposes. Either way, we'll pick the first one.
                            var info = infos.FirstOrDefault(i => i.IsInBox) ?? infos.FirstOrDefault(i => !i.IsInBox);

                            if (info is null)
                            {
                                availabilityResult = AvailabilityResult.Unavailable;
                            }
                            else if (info.IsInBox)
                            {
                                availabilityResult = AvailabilityResult.AvailableInBox;
                            }
                            else
                            {
                                availabilityResult = AvailabilityResult.AvailableInPackage(info.Package.Value);
                            }

                            // Analyze obsoletion

                            ObsoletionResult?obsoletionResult;

                            if (!analyzeObsoletion || info?.Declaration.Obsoletion is null)
                            {
                                obsoletionResult = null;
                            }
                            else
                            {
                                var compiledAgainstObsoleteApi = false;

                                if (assemblyFramework is not null)
                                {
                                    var compiledAvailability = availabilityContext.GetAvailability(api, assemblyFramework);
                                    if (compiledAvailability?.Declaration.Obsoletion is not null)
                                    {
                                        compiledAgainstObsoleteApi = true;
                                    }
                                }

                                if (compiledAgainstObsoleteApi)
                                {
                                    obsoletionResult = null;
                                }
                                else
                                {
                                    var o            = info.Declaration.Obsoletion.Value;
                                    obsoletionResult = new ObsoletionResult(o.Message, o.Url);
                                }
                            }

                            // Analyze platform support

                            platformResultBuilder.Clear();

                            if (info is null)
                            {
                                for (var i = 0; i < platforms.Count; i++)
                                {
                                    platformResultBuilder.Add(null);
                                }
                            }
                            else
                            {
                                var platformContext = platformContexts[framework];
                                foreach (var platform in platforms)
                                {
                                    var annotation     = platformContext.GetPlatformAnnotation(api);
                                    var isSupported    = annotation.IsSupported(platform);
                                    var platformResult = isSupported ? PlatformResult.Supported : PlatformResult.Unsupported;
                                    platformResultBuilder.Add(platformResult);
                                }
                            }

                            var frameworkResult = new FrameworkResult(availabilityResult, obsoletionResult, platformResultBuilder.ToArray());
                            frameworkResultBuilder.Add(frameworkResult);
                        }

                        var apiResult = new ApiResult(api, frameworkResultBuilder.ToArray());
                        apiResults.Add(apiResult);
                    }
                }

                var results = new AssemblyResult(assemblyName, null, apiResults.ToArray());
                resultSink.Add(results);
            }
        });

        resultSink.CompleteAdding();
        resultSinkTask.Wait();
    }
        public void WhenAllContentIsTrue_IsOkShouldReturnTrue()
        {
            var item = new AvailabilityResult(true, true, true);

            Assert.IsTrue(item.IsOk());
        }