private void DataGrid_AddingNewItem_1(object sender, AddingNewItemEventArgs e)
 {
     e.NewItem = new RelationAccountNumber()
     {
         UserId = ServiceResolver.GetService <IUserProvider>().GetUserId()
     };
 }
Esempio n. 2
0
        private void Run(string[] args)
        {
            var serviceResolver = new ServiceResolver();
            var logger          = serviceResolver.GetService <ILogger>();

            if (args.Length == 0)
            {
                Console.WriteLine("Usage: MBBSDatabase [view|convert] [files]");
            }

            var convert = (args[0] == "convert");

            foreach (string s in args.Skip(1))
            {
                BtrieveFile file = new BtrieveFile();
                try
                {
                    file.LoadFile(logger, s);
                    if (convert)
                    {
                        using var processor = new BtrieveFileProcessor();
                        processor.CreateSqliteDB(Path.ChangeExtension(s, ".DB"), file);
                    }
                }
                catch (Exception e)
                {
                    logger.Error(e, $"Failed to load Btrieve file {s}: {e.Message}\n{e.StackTrace}");
                }
            }
        }
        private void ResetCategoriesLinkPercentages(Relation entity)
        {
            double totalPercentage = entity.CategoryLinks.Sum(b => b.Percentage);

            if (totalPercentage < 100)
            {
                CategoryRelationLink categoryTransactionLink = new CategoryRelationLink();
                categoryTransactionLink.Percentage = 100 - totalPercentage;
                categoryTransactionLink.Relation   = entity;
                categoryTransactionLink.RelationID = entity.ID;
                categoryTransactionLink.UserId     = ServiceResolver.GetService <IUserProvider>().GetUserId();
                entity.CategoryLinks.Add(categoryTransactionLink);
            }
            else if (totalPercentage > 100)
            {
                double hasToBeLess = totalPercentage - 100;
                var    link        = entity.CategoryLinks.Last();
                while (link != null && entity.CategoryLinks.Sum(b => b.Percentage) > 100)
                {
                    if (hasToBeLess > link.Percentage)
                    {
                        hasToBeLess    -= link.Percentage;
                        link.Percentage = 0;
                    }
                    else
                    {
                        link.Percentage -= hasToBeLess;
                    }

                    link = entity.CategoryLinks.Skip(entity.CategoryLinks.IndexOf(link) - 1).FirstOrDefault();
                }
            }
        }
        public static IAppBuilder UseDomainAssemblyResolver(
            this IAppBuilder app)
        {
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }
            var domainAssemblyResolver = ServiceResolver.GetService <DomainAssemblyResolver>();

            if (domainAssemblyResolver == null)
            {
                throw new InvalidOperationException(
                          "Serive collection could not resolve FolderWatchdog instance, Please configure service at Startup");
            }
            OwinContext       owinContext       = new OwinContext(app.Properties);
            CancellationToken cancellationToken = owinContext.Get <CancellationToken>("host.OnAppDisposing");

            if (cancellationToken == new CancellationToken())
            {
                cancellationToken = owinContext.Get <CancellationToken>("server.OnDispose");
            }
            if (cancellationToken == new CancellationToken())
            {
                throw new InvalidOperationException("Current OWIN environment does not contain an instance of the `CancellationToken` class neither under `host.OnAppDisposing`, nor `server.OnDispose` key.\r\nPlease use another OWIN host or create an instance of the `DomainAssemblyResolver` class manually.");
            }
            cancellationToken.Register(new Action(domainAssemblyResolver.Dispose));
            domainAssemblyResolver.Start();
            return(app);
        }
        /// <summary>
        /// Creates a new instance of <see cref="IMessagingBus"/>.
        /// </summary>
        /// <returns>
        /// The created instance of <see cref="IMessagingBus"/>
        /// </returns>
        public IMessagingBus BuildSubscribers()
        {
            IMessagingConfig config = CreateConfig();

            config.Validate();

            ILoggerFactory loggerFactory =
                ServicesBuilder?.LoggerFactory?.Invoke() ?? ServiceResolver.ResolveService <ILoggerFactory>();

            JustSayingBus      bus    = CreateBus(config, loggerFactory);
            JustSayingFluently fluent = CreateFluent(bus, loggerFactory);

            if (ServicesBuilder?.NamingStrategy != null)
            {
                fluent.WithNamingStrategy(ServicesBuilder.NamingStrategy);
            }

            if (ServicesBuilder?.MessageContextAccessor != null)
            {
                fluent.WithMessageContextAccessor(ServicesBuilder.MessageContextAccessor());
            }

            if (SubscriptionBuilder != null)
            {
                SubscriptionBuilder.Configure(fluent);
            }

            return(bus);
        }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ServiceResolver serviceResolver)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                // endpoints.MapGet("/", async context => { await context.Response.WriteAsync("Hello World!"); });
                endpoints.MapGet("/create", new HomeController(serviceResolver).CreatePostEntry);
                endpoints.MapGet("/", new HomeController(serviceResolver).GetAllPosts);
                endpoints.MapPost("/home/create_post", new HomeController(serviceResolver).CreatePostEntry);
                endpoints.MapPost("/edit_post/{.}", new HomeController(serviceResolver).EditPost);
                endpoints.MapGet("/edit_post/{.}", new HomeController(serviceResolver).EditPost);
                endpoints.MapPost("/remove_post/{.}", new HomeController(serviceResolver).RemovePost);
                endpoints.MapGet("/show_comments/{.}", new HomeController(serviceResolver).ShowComments);
                endpoints.MapGet("/create_comment/{.}", new HomeController(serviceResolver).CreateComment);
                endpoints.MapPost("/create_comment/{.}", new HomeController(serviceResolver).CreateComment);
                endpoints.MapGet("/edit_comment/{.}", new HomeController(serviceResolver).EditComment);
                endpoints.MapPost("/edit_comment/{.}", new HomeController(serviceResolver).EditComment);
            });
        }
Esempio n. 7
0
        public virtual void OnInitialize()
        {
            //Registrazione della sessione di default
            SessionFactory.RegisterDefaultDataSession <MockDataSession <TScenario, TransientScenarioOption <TScenario> > >();

            //Registrazione dei servizi
            ServiceResolver.Register <IIdentityClient, MockIdentityClient>();
            ServiceResolver.Register <ICaptchaValidatorService, MockCaptchaValidatorService>();

            ServiceResolver.Register <ISemperPrecisMemoryCache, SemperPrecisMemoryCache>();

            //Creazione del controller dichiarato
            Controller = new TApiController();

            Scenario = Controller.DataSession.GetScenario <TScenario>();

            //Recupero l'utente da usare nel testa
            var defaultShooterIdentity = GetIdentityUser();

            if (defaultShooterIdentity == null)
            {
                throw new InvalidProgramException("Shooter for identity is invalid");
            }

            //Inizializzazione del controller context e impostazione dell'identity
            UpdateIdentityUser(defaultShooterIdentity);
        }
        public void ResolvedServiceGetResponseEncoder()
        {
            ServiceCollection services = new ServiceCollection();
            services
                .WithService("Test", "/")
                    .WithEndpoint("{action}")
                        .Post<Payload>((Payload p) => { });

            ResolvedService service = new ServiceResolver(services).Find(MethodType.Post, "foo");
            EncodingLookupResult result = service.GetResponseEncoder("gzip");
            Assert.IsNotNull(result);
            Assert.AreEqual(EncodingType.Empty, result.EncodingType);
            Assert.AreEqual(new IdentityEncoding(), result.Encoding);

            result = service.GetResponseEncoder("gzip, *");
            Assert.IsNotNull(result);
            Assert.AreEqual(EncodingType.Empty, result.EncodingType);
            Assert.AreEqual(new IdentityEncoding(), result.Encoding);

            services.WithHostEncoding(new GzipDeflateEncoding());
            service = new ServiceResolver(services).Find(MethodType.Post, "foo");
            result = service.GetResponseEncoder("gzip, *");
            Assert.IsNotNull(result);
            Assert.AreEqual(EncodingType.Parse("gzip"), result.EncodingType);
            Assert.AreEqual(new GzipDeflateEncoding(), result.Encoding);

            result = service.GetResponseEncoder("gzip;q=0");
            Assert.IsNotNull(result);
            Assert.AreEqual(EncodingType.Empty, result.EncodingType);
            Assert.AreEqual(new IdentityEncoding(), result.Encoding);
        }
        IActor IStewardManager.GetActor(IStewardDialogContext context, IConversationData conversationData)
        {
            if (conversationData.IsHandled())
            {
                return(new WatsonActor(context, conversationData));
            }

            if (conversationData.IsAskingForOwner())
            {
                return(new OwnerServiceActor(context
                                             , conversationData
                                             , ServiceResolver.Get <ISettings>()
                                             , ServiceResolver.Get <ILogManager>().GetLogger(typeof(OwnerServiceActor))));
            }

            if (conversationData.IsAskingForServiceCloudCase())
            {
                return(new ServiceCloudCaseActor(context
                                                 , conversationData
                                                 , ServiceResolver.Get <ISettings>()
                                                 , ServiceResolver.Get <ILogManager>().GetLogger(typeof(ServiceCloudCaseActor))));
            }

            return(new QnAMakerActor(context));
        }
        public async Task <IActionResult> Update([FromBody] TestModel model)
        {
            var testService = new ServiceResolver().Resolve <ITestService>(new TestServiceDefinition());
            var created     = await testService.UpdateAsync(model);

            return(Ok(created));
        }
        public async Task CacheLoad()
        {
            TestingResourcesHelper.PreapareTestingDirectory(ServiceResolver.GetService <IAppConfigurationService>());
            TestingResourcesHelper.InjectCachedQueriesData(ServiceResolver.GetService <IAppConfigurationService>());

            var storageService = ServiceResolver.GetService <IStorageService>();

            storageService.Load();

            var queryCacheService = ServiceResolver.GetService <IQueryCacheService>() as
                                    AOEMatchDataProvider.Services.Default.QueryCacheService;     //cast to specified service to get access for internal fields/methods

            queryCacheService.Load();

            Assert.IsTrue(queryCacheService.Queries.CachedQueries.ContainsKey(productRequest), "Cache should exists");

            //CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(5000);

            //var requestResponseWrapper = await queryCacheService.GetOrUpdate(productRequest, cancellationTokenSource.Token, DateTime.UtcNow.AddDays(1));

            //if (!requestResponseWrapper.IsSuccess)
            //    Assert.Fail("Request failed");

            //Assert.IsTrue(queryCacheService.Queries.CachedQueries.ContainsKey(productRequest), "Cache exists");
        }
Esempio n. 12
0
        async Task <QnaMakerResult> IQnAMakerService.SearchKbAsync(string question)
        {
            var kbId            = settings[QnAMakerKnowledgeBaseId];
            var subscriptionKey = settings[QnAMakerSubscriptionKey];
            var endpoint        = settings[QnAMakerEndPoint];

            //Build the URI
            var uri = new UriBuilder($"{endpoint}/knowledgebases/{kbId}/generateAnswer").Uri;

            var postBody = JsonConvert.SerializeObject(new QnaMakerQuestion
            {
                Question = question
            });

            string responseString;

            log.Debug($"postBody : {postBody}");

            //Send the POST request
            using (var client = ServiceResolver.Get <IWebClient>())
            {
                client.Headers.Add("Content-Type", "application/json");
                client.Headers.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
                responseString = await client.UploadStringTaskAsync(uri, postBody);
            }

            log.Debug($"responseString : {responseString}");

            var result = ConvertResponseFromJson(responseString);

            return(result);
        }
        public async Task SampleRequestCache()
        {
            TestingResourcesHelper.PreapareTestingDirectory(ServiceResolver.GetService <IAppConfigurationService>());
            var requestTestingService = ServiceResolver.GetService <IRequestService>() as RequestTestingService;

            //return match in progress
            requestTestingService.AddTestingRule(
                new System.Text.RegularExpressions.Regex("https://reqres.in/api/products/3"),
                RequestTestingService.RequestTestingServiceMode.ReturnPredefinedResult,
                new RequestResponseWrapper()
            {
                ResponseContent = TestingResourcesHelper.GetApiResoponses("Product3.json"),
                IsSuccess       = true
            });

            var queryCacheService = ServiceResolver.GetService <IQueryCacheService>() as AOEMatchDataProvider.Services.Default.QueryCacheService; //cast to specified service to get access for internal props

            queryCacheService.Load();

            CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(timeout);

            var requestResponseWrapper = await queryCacheService.GetOrUpdate(productRequest, cancellationTokenSource.Token, DateTime.UtcNow.AddYears(1000));

            if (!requestResponseWrapper.IsSuccess)
            {
                Assert.Fail("Request failed");
            }

            Assert.IsTrue(queryCacheService.Queries.CachedQueries.ContainsKey(productRequest), "Cache should exists");

            var requestResponseWrapperFromCache = await queryCacheService.GetOrUpdate(productRequest, cancellationTokenSource.Token, DateTime.UtcNow.AddYears(1000));

            Assert.AreEqual(requestResponseWrapper, requestResponseWrapperFromCache);
        }
Esempio n. 14
0
        static void Main(string[] args)
        {
            ServiceResolver resolver = new ServiceResolver();

            resolver.ServiceFound += new Network.ZeroConf.ObjectEvent <Network.ZeroConf.IService>(resolver_ServiceFound);
            resolver.Resolve("urn:schemas-upnp-org:service:ContentDirectory:1");

            //resolver.Resolve("upnp:rootdevice");
            //resolver.Resolve("urn:schemas-upnp-org:service:RenderingControl:1");
            //IPEndPoint server = new IPEndPoint(IPAddress.Parse("192.168.1.13"), 2869);
            //Browse browse = new Browse("http://192.168.1.13:2869/upnphost/udhisapi.dll?control=uuid:a6da68b3-3d15-4655-861f-503e63673e7d+urn:upnp-org:serviceId:ContentDirectory", null);
            //XmlDocument didlDoc = new XmlDocument();
            //XmlDocument browseResponse = browse.GetResponse().Document;
            //didlDoc.LoadXml(browseResponse.DocumentElement.ChildNodes[0].ChildNodes[0].ChildNodes[0].ChildNodes[0].Value);
            //XmlNamespaceManager xmlns = new XmlNamespaceManager(didlDoc.NameTable);
            //xmlns.AddNamespace("didl", "urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/");
            //xmlns.AddNamespace("dc", "http://purl.org/dc/elements/1.1/");
            //xmlns.AddNamespace("upnp", "urn:schemas-upnp-org:metadata-1-0/upnp/");
            //foreach (XmlNode item in didlDoc.SelectNodes("//didl:container/dc:title/text()", xmlns))
            //{
            //    Console.WriteLine(item.Value);
            //}

            Console.WriteLine("Press enter to exit");
            Console.Read();
            resolver.ServiceFound -= resolver_ServiceFound;
            resolver.Dispose();
        }
        public void Resolve_Not_Register()
        {
            var enumerable = ServiceResolver.Resolve <IEnumerable <Transient> >();

            Assert.NotNull(enumerable);
            Assert.Empty(enumerable);
        }
        public async Task <IActionResult> Delete(string key)
        {
            var testService = new ServiceResolver().Resolve <ITestService>(new TestServiceDefinition());
            await testService.DeleteAsync(key);

            return(Ok());
        }
Esempio n. 17
0
        private JustSayingBus CreateBus(IMessagingConfig config, ILoggerFactory loggerFactory)
        {
            IMessageSerializationRegister register =
                ServicesBuilder?.SerializationRegister?.Invoke() ?? ServiceResolver.ResolveService <IMessageSerializationRegister>();

            return(new JustSayingBus(config, register, loggerFactory));
        }
        async Task <MessageResponse> IWatsonConversationService.SendMessage(string message, dynamic context)
        {
            using (var client = ServiceResolver.Get <IWebClient>())
            {
                var credential = settings[WatsonCredential];
                var endpoint   = new UriBuilder(settings[WatsonEndPoint]).Uri;

                client.Headers.Add("Content-Type", "application/json");
                client.Headers.Add("Authorization", $"Basic {credential}");

                dynamic inputContext = context;

                dynamic messageObj = new ExpandoObject();

                messageObj.input      = new ExpandoObject();
                messageObj.input.text = CorrectInputMessage(message);
                messageObj.context    = inputContext;

                var data = JsonConvert.SerializeObject(messageObj);

                log.Debug($"message : {message}");
                log.Debug($"data : {data}");

                var responseMessage = await client.UploadStringTaskAsync(endpoint, data);

                log.Debug($"responseMessage : {responseMessage}");

                return(JsonConvert.DeserializeObject <MessageResponse>(responseMessage));
            }
        }
Esempio n. 19
0
        public void IncompleteUsersDataProcessingFromMatchData()
        {
            var responseRaw       = TestingResourcesHelper.GetApiResoponses("MatchDetailsValid.json");
            var processingService = ServiceResolver.GetService <IUserDataProcessingService>();

            var stringResources = JsonConvert.DeserializeObject <AoeNetAPIStringResources>(TestingResourcesHelper.GetApiResoponses("ApiStringResources.json"));

            Match match = processingService.ProcessMatch(responseRaw, stringResources);

            Assert.AreEqual(match.Users.Count, 2, "Users in match count is incorrect");

            //make sure other fields was processed as expected

            //test both players profile IDs
            Assert.IsNotNull(match.Users.First().UserGameProfileId, "Player[0] profile id wasn't processed");
            Assert.IsNotNull(match.Users.Last().UserGameProfileId, "Player[1] profile id wasn't processed");

            //test both players names
            Assert.IsNotNull(match.Users.First().Name, "Player[0] name wasn't processed");
            Assert.IsNotNull(match.Users.Last().Name, "Player[1] name wasn't processed");

            //validate color property (have to be set)
            Assert.IsNotNull(match.Users.First().Color, "Player[0] color is wasn't processed");
            Assert.IsNotNull(match.Users.Last().Color, "Player[1] color is wasn't processed");

            //validate user match types and match type
            Assert.AreEqual(match.MatchType, MatchType.RandomMap);
            Assert.AreEqual(match.Users.First().MatchType, MatchType.RandomMap);
            Assert.AreEqual(match.Users.Last().MatchType, MatchType.RandomMap);
        }
Esempio n. 20
0
 // Code à exécuter lorsque l'application est activée (affichée au premier plan)
 // Ce code ne s'exécute pas lorsque l'application est démarrée pour la première fois
 private void Application_Activated(object sender, ActivatedEventArgs e)
 {
     if (!e.IsApplicationInstancePreserved)
     {
         ServiceResolver.RegisterService <INavigationService>(new PhoneNavigationService(RootFrame));
     }
 }
Esempio n. 21
0
        protected void ExecuteTest(TestLogic testLogic)
        {
            ServiceResolver serviceResolver = new ServiceResolver(ServiceResolver.GetTestDefaults());

            //Setup Generic Database
            var resourceManager = serviceResolver.GetService <IResourceManager>();

            File.WriteAllBytes($"BBSGEN.DAT", resourceManager.GetResource("MBBSEmu.Assets.BBSGEN.VIR").ToArray());

            CopyModuleToTempPath(ResourceManager.GetTestResourceManager());

            var modules = new List <MbbsModule>
            {
                new MbbsModule(serviceResolver.GetService <IFileUtility>(), serviceResolver.GetService <ILogger>(), "MBBSEMU", _modulePath)
            };

            //Setup and Run Host
            var host = serviceResolver.GetService <IMbbsHost>();

            foreach (var m in modules)
            {
                host.AddModule(m);
            }

            host.Start();

            _session = new TestSession(host);
            host.AddSession(_session);

            testLogic(_session);

            host.Stop();

            host.WaitForShutdown();
        }
Esempio n. 22
0
        public void SaveCollectionStateTest()
        {
            var stateManager = new StateManager(ServiceResolver.GetService <IStateMachine>());

            stateManager.UserDevice = new UserDevice()
            {
                DeviceId = "100"
            };


            var syncKey   = stateManager.GetNewSyncKey("0");
            var collState = new CollectionState()
            {
                FolderId    = "12321",
                Collections = new List <SyncItemState>()
                {
                    new SyncItemState()
                    {
                        ServerId = "12334",
                        HashKey  = "3242342342"
                    },
                    new SyncItemState()
                    {
                        ServerId = "12334",
                        HashKey  = "3242342342"
                    }
                }
            };

            stateManager.SaveCollectionState(syncKey, collState);
            var savedCollState = stateManager.LoadCollectionState(syncKey, collState.FolderId);
        }
Esempio n. 23
0
        public TelnetSession(Socket telnetConnection) : base(telnetConnection.RemoteEndPoint.ToString())
        {
            SessionType        = EnumSessionType.Telnet;
            SendToClientMethod = Send;
            _host   = ServiceResolver.GetService <IMbbsHost>();
            _logger = ServiceResolver.GetService <ILogger>();

            _telnetConnection = telnetConnection;
            _telnetConnection.ReceiveTimeout    = (1000 * 60) * 5; //5 Minutes
            _telnetConnection.ReceiveBufferSize = socketReceiveBuffer.Length;
            _telnetConnection.Blocking          = false;

            SessionState = EnumSessionState.Negotiating;

            _senderThread = new Thread(SendWorker);
            _senderThread.Start();

            //Add this Session to the Host
            _host.AddSession(this);

            Send(ANSI_ERASE_DISPLAY);
            Send(ANSI_RESET_CURSOR);

            SessionState = EnumSessionState.Unauthenticated;

            ListenForData();
        }
Esempio n. 24
0
        public OfflineOrOnlineAdminstrationChoseViewmodel(IView view)
        {
            _view = view;



            OfflineCommand = new RelayCommand(async(object obj) =>
            {
                _view.Disable();

                SQLiteStarter starter             = new SQLiteStarter();
                IUserProvider desktopUserProvider = ServiceResolver.GetContainer().GetInstance <IUserProvider>();
                desktopUserProvider.SetUserId(LoginRepository.Instance.CurrentUser.ID);
                starter.CreateDBIfNotExists();
                // starter.TestSeedDb();
                Properties.Settings settings = new Properties.Settings();
                if (RememberChoice)
                {
                    settings.ChoiceIsOnline       = false;
                    settings.RememberOnlineChoice = true;
                    settings.Save();
                }
                else
                {
                    settings.RememberOnlineChoice = false;
                    settings.Save();
                }

                await RepositoryResolver.GetRepository <ITransactionRepository>().CreateInitialFilling();

                new MainWindow().Show();
                _view.Close();
            });
        }
Esempio n. 25
0
        protected override void Initialize(string xmlRequest)
        {
            if (string.IsNullOrWhiteSpace(xmlRequest))
            {
                throw new InvalidRequestException("SendMail Request Content is Empty.");
            }

            var root = XDocument.Parse(xmlRequest).Root;

            this.ClientId = root.GetElementValueAsString(ComposeMailStrings.ClientId);

            var sourceEl = root.GetElement(ComposeMailStrings.Source);

            if (sourceEl != null)
            {
                this.Source = new Source()
                {
                    FolderId   = sourceEl.GetElementValueAsString(ComposeMailStrings.FolderId),
                    ItemId     = sourceEl.GetElementValueAsString(ComposeMailStrings.ItemId),
                    LongId     = sourceEl.GetElementValueAsString(ComposeMailStrings.LongId),
                    InstanceId = sourceEl.GetElementValueAsString(ComposeMailStrings.InstanceId)
                };
            }
            this.AccountId       = root.GetElementValueAsString(ComposeMailStrings.AccountId);
            this.SaveInSentItems = root.HasChildElement(ComposeMailStrings.SaveInSentItems);

            var mimeString = root.GetElementValueAsString(ComposeMailStrings.Mime);

            mimeString = mimeString.Replace("\n", "\r\n");

            this.Mime = Encoding.UTF8.GetBytes(mimeString);

            MailService = ServiceResolver.GetService <IEmailService>();
        }
 private void DataGrid_AddingNewItem(object sender, AddingNewItemEventArgs e)
 {
     e.NewItem = new RelationDescription()
     {
         UserId = ServiceResolver.GetService <IUserProvider>().GetUserId()
     };
 }
Esempio n. 27
0
        /// <summary>
        /// Starts this instance.
        /// </summary>
        public static void Start()
        {
            ServiceResolver.SetServiceResolver(new DefaultServiceResolver());

            var config = GlobalConfiguration.Configuration;

            NuGetV2WebApiEnabler.UseNuGetV2WebApiFeed(
                config,
                "NuGetDefault",
                "nuget",
                "PackagesOData",
                enableLegacyPushRoute: true);

            config.Services.Replace(typeof(IExceptionLogger), new TraceExceptionLogger());

            // Trace.Listeners.Add(new TextWriterTraceListener(HostingEnvironment.MapPath("~/NuGet.Server.log")));
            // Trace.AutoFlush = true;

            config.Routes.MapHttpRoute(
                name: "NuGetDefault_ClearCache",
                routeTemplate: "nuget/clear-cache",
                defaults: new { controller = "PackagesOData", action = "ClearCache" },
                constraints: new { httpMethod = new HttpMethodConstraint(HttpMethod.Get) }
                );
        }
Esempio n. 28
0
        public void Resolve_Not_Register()
        {
            var many = ServiceResolver.ResolveMany <Transient>();

            Assert.NotNull(many);
            Assert.Equal(0, many.Count());
        }
Esempio n. 29
0
        public void Resolve_InstanceSimpleGeneric()
        {
            var service = ServiceResolver.Resolve <IInstanceSimpleGeneric <IService> >();

            Assert.NotNull(service);
            Assert.IsType <SimpleGeneric <IService> >(service);
        }
Esempio n. 30
0
        /// <summary>
        /// Uploads the round to the server and clears the current round. Returns null if it could not upload the round correctly.
        /// </summary>
        public static async Task <RoundModel> CompleteRoundAsync()
        {
            //Upload the current round to the server.
            var request = ServiceResolver.Resolve <IApiRequest>();

            // Note the time that the round is ending.
            CurrentRound.EndTime = DateTime.UtcNow;

            //upload the round to the server.
            var completedRound = await request.PostAsync <RoundModel>(
                Constants.Endpoints.Rounds, CurrentRound);

            if (completedRound?.Id != Guid.Empty)
            {
                //TODO: Modify the logic here to NOT complete the round if we could not delete
                //the file.

                //means the upload was a success, so continue with the deletion of the round.
                if (await DeleteCurrentRoundAsync())
                {
                    return(completedRound);
                }
            }

            //upload to the server failed, so return null.
            return(null);
        }
Esempio n. 31
0
 public static void Setup(this IServiceCollection services, AppSettings appSettings)
 {
     ConfigurationResolver.Setup(services, appSettings);
     ServiceResolver.Setup(services);
     DataResolver.Setup(services, appSettings);
     ExternalServiceResolver.Setup(services);
 }
Esempio n. 32
0
		/// <summary>
		/// Creates new instance of <see cref="Services"/>
		/// </summary>
		/// <param name="platformWebFullSectionName">platform web full section name</param>
		public Services(string platformWebFullSectionName)
		{
			if (platformWebFullSectionName == null)
				throw new MemoryPointerIsNullException("platformWebFullSectionName");

			var authCookiePropertiesProviderResolver = new ServiceResolver<IAuthCookiePropertiesProvider>(new ConfigFileAuthCookiePropertiesProvider(platformWebFullSectionName));
			this.Bundle.AddServiceResolver(authCookiePropertiesProviderResolver);
		}
Esempio n. 33
0
		/// <summary>
		/// Creates new instance of <see cref="Services"/>
		/// </summary>
		/// <param name="delegateProviderResolver">delegate provider resolver</param>
		public Services(IServiceResolver<IDelegateProvider> delegateProviderResolver)
		{
			if (delegateProviderResolver == null)
				throw new MemoryPointerIsNullException("delegateProviderResolver");

			var attendeeProviderResolver = new ServiceResolver<IAttendeeProvider>(new AttendeeProvider(delegateProviderResolver));
			var meetingProviderResolver = new ServiceResolver<IMeetingProvider>(new MeetingProvider(delegateProviderResolver, attendeeProviderResolver));
			this.Bundle.AddServiceResolver(attendeeProviderResolver);
			this.Bundle.AddServiceResolver(meetingProviderResolver);
		}
        public void ServiceResolverFindRoutePatterns()
        {
            ServiceCollection services = new ServiceCollection();
            services
                .WithService("Test", "/")
                    .WithEndpoint("foo/{param}/bar", null, new { param = @"^\d+$" })
                        .Get(() => { });

            ServiceResolver resolver = new ServiceResolver(services);
            Assert.IsNotNull(resolver.Find(MethodType.Get, "foo/42/bar"));
            Assert.IsNull(resolver.Find(MethodType.Get, "foo/baz/bar"));
        }
        public void ServiceResolverExistsForAnyMethodType()
        {
            ServiceCollection services = new ServiceCollection();
            services
                .WithService("Test", "/")
                    .WithEndpoint("foo/{param}/bar")
                        .Get(() => { });

            ServiceResolver resolver = new ServiceResolver(services);
            Assert.IsTrue(resolver.ExistsForAnyMethodType("foo/baz/bar"));
            Assert.IsFalse(resolver.ExistsForAnyMethodType("foo/bar"));
        }
        public void ServiceResolverFind()
        {
            ServiceCollection services = new ServiceCollection();
            services
                .WithService("Test", "/")
                    .WithEndpoint("foo/{param}/bar")
                        .Get(() => { });

            ServiceResolver resolver = new ServiceResolver(services);
            Assert.IsNotNull(resolver.Find(MethodType.Get, "foo/baz/bar"));
            Assert.IsNull(resolver.Find(MethodType.Post, "foo/baz/bar"));
        }
        public void ServiceResolverFindRouteTypes()
        {
            ServiceCollection services = new ServiceCollection();
            services
                .WithService("Test", "/")
                    .WithEndpoint("foo/{param}/bar", new { param = typeof(Guid) })
                        .Get(() => { });

            ServiceResolver resolver = new ServiceResolver(services);
            Assert.IsNotNull(resolver.Find(MethodType.Get, "foo/D118CE6F-36BE-4DB4-B0E7-D426809B22FE/bar"));
            Assert.IsNull(resolver.Find(MethodType.Get, "foo/42/bar"));
        }
Esempio n. 38
0
		/// <summary>
		/// Creates new instance of <see cref="Services"/>
		/// </summary>
		/// <param name="sampleFullSectionName">sample full section name</param>
		public Services(string sampleFullSectionName)
		{
			if (sampleFullSectionName == null)
				throw new MemoryPointerIsNullException("sampleFullSectionName");

			var anotherTypeSetProviderResolver = new ServiceResolver<IAnotherTypeSetProvider>(new AnotherTypeSetProvider());
			var anotherTypeStructureProviderResolver = new ServiceResolver<IAnotherTypeStructureProvider>(new ConfigFileAnotherTypeStructureProvider(sampleFullSectionName));
			var anotherTypeStructuredDataProviderResolver = new ServiceResolver<IAnotherTypeStructuredDataProvider>(
				new AnotherTypeStructuredDataProvider(anotherTypeSetProviderResolver, anotherTypeStructureProviderResolver));
			this.Bundle.AddServiceResolver(anotherTypeSetProviderResolver);
			this.Bundle.AddServiceResolver(anotherTypeStructureProviderResolver);
			this.Bundle.AddServiceResolver(anotherTypeStructuredDataProviderResolver);
		}
Esempio n. 39
0
		/// <summary>
		/// Creates new instance of <see cref="Services"/>
		/// </summary>
		/// <param name="utcTimeProviderResolver">UTC time provider resolver</param>
		public Services(IServiceResolver<IUTCTimeProvider> utcTimeProviderResolver)
		{
			if (utcTimeProviderResolver == null)
				throw new MemoryPointerIsNullException("utcTimeProviderResolver");

			var sampleUserTokenFactoryResolver = new ServiceResolver<ISampleUserTokenFactory>(new SampleUserTokenFactory(utcTimeProviderResolver));
			var userTokenProviderResolver = new ServiceResolver<IUserTokenProvider>(new SampleUserTokenProvider(sampleUserTokenFactoryResolver));
			var userDataProviderResolver = new ServiceResolver<IUserDataProvider>(new SampleUserDataProvider());
			var currentUserTokenProviderResolver = new ServiceResolver<ICurrentUserTokenProvider>(new SampleCurrentUserTokenProvider());
			this.Bundle.AddServiceResolver(sampleUserTokenFactoryResolver);
			this.Bundle.AddServiceResolver(userTokenProviderResolver);
			this.Bundle.AddServiceResolver(userDataProviderResolver);
			this.Bundle.AddServiceResolver(currentUserTokenProviderResolver);
		}
Esempio n. 40
0
		/// <summary>
		/// Creates new instance of <see cref="Services"/>
		/// </summary>
		/// <param name="platformFullSectionName">platform full section name</param>
		public Services(string platformFullSectionName)
		{
			if (platformFullSectionName == null)
				throw new MemoryPointerIsNullException("platformFullSectionName");

			var utcTimeProviderResolver = new ServiceResolver<IUTCTimeProvider>(new UTCTimeProvider());
			var localTimeOffsetProviderResolver = new ServiceResolver<ILocalTimeOffsetProvider>(new LocalTimeOffsetProvider());
			var uiCultureProviderResolver = new ServiceResolver<IUICultureProvider>(new UICultureProvider());
			var consoleProviderResolver = new ServiceResolver<IConsoleProvider>(new ConsoleProvider());
			this.Bundle.AddServiceResolver(utcTimeProviderResolver);
			this.Bundle.AddServiceResolver(localTimeOffsetProviderResolver);
			this.Bundle.AddServiceResolver(uiCultureProviderResolver);
			this.Bundle.AddServiceResolver(consoleProviderResolver);
		}
Esempio n. 41
0
		/// <summary>
		/// Creates new instance of <see cref="Services"/>
		/// </summary>
		/// <param name="sampleFullSectionName">sample full section name</param>
		public Services(string sampleFullSectionName)
		{
			if (sampleFullSectionName == null)
				throw new MemoryPointerIsNullException("sampleFullSectionName");

			var sampleTypeTestErrorFactoryResolver = new ServiceResolver<IInfoEntityFactory<TestError>>(
				new InfoEntityWithDescriptionFactory<TestError>(new ResxDescriptionProvider(Sample.Resx.SampleTypes.Resources.ResourceManager, "SampleType_TestError_Description"), descriptionProvider => new TestError(descriptionProvider)));
			var sampleTypeSetProviderResolver = new ServiceResolver<ISampleTypeSetProvider>(new SampleTypeSetProvider(sampleTypeTestErrorFactoryResolver));
			var sampleTypeStructureProviderResolver = new ServiceResolver<ISampleTypeStructureProvider>(new ConfigFileSampleTypeStructureProvider(sampleFullSectionName));
			var sampleTypeStructuredDataProviderResolver = new ServiceResolver<ISampleTypeStructuredDataProvider>(
				new SampleTypeStructuredDataProvider(sampleTypeSetProviderResolver, sampleTypeStructureProviderResolver));
			this.Bundle.AddServiceResolver(sampleTypeSetProviderResolver);
			this.Bundle.AddServiceResolver(sampleTypeStructureProviderResolver);
			this.Bundle.AddServiceResolver(sampleTypeStructuredDataProviderResolver);
		}
        public void ResolvedServiceGetRequestDeserializer()
        {
            ServiceCollection services = new ServiceCollection();
            services
                .WithService("Test", "/")
                    .WithEndpoint("{action}")
                        .Post<Payload>((Payload p) => { });

            ResolvedService service = new ServiceResolver(services).Find(MethodType.Post, "foo");
            FormatLookupResult result = service.GetRequestDeserializer("application/json");
            Assert.IsNull(result);

            result = service.GetRequestDeserializer(string.Empty);
            Assert.IsNotNull(result);
            Assert.AreEqual(MediaType.Empty, result.MediaType);
            Assert.AreEqual(new PlainTextFormat(), result.Format);

            services.WithHostFormat(new JsonFormat());
            service = new ServiceResolver(services).Find(MethodType.Post, "foo");
            result = service.GetRequestDeserializer("application/json");
            Assert.IsNotNull(result);
            Assert.AreEqual(MediaType.Parse("application/json"), result.MediaType);
            Assert.AreEqual(new JsonFormat(), result.Format);
        }
Esempio n. 43
0
		/// <summary>
		/// Creates new instance of <see cref="Services"/>
		/// </summary>
		public Services()
		{
			var delegateProviderResolver = new ServiceResolver<IDelegateProvider>(new DelegateProvider());
			this.Bundle.AddServiceResolver(delegateProviderResolver);
		}
 public ServiceFilterProvider(Func<Type, object> resolve)
 {
     _resolver = new ServiceResolver(resolve);
 }
        public void ResolvedServiceInvokeErrorActionsNoContinue()
        {
            Payload payload = new Payload()
            {
                Date = DateTime.UtcNow,
                Number = 42,
                Text = "Hello, world!"
            };

            ServiceCollection services = new ServiceCollection();
            services
                .WithService("Test", "/")
                    .WithEndpoint("{action}")
                        .Post<Payload>((Payload p) => { })
                .ErrorService<Payload>(
                    (ex, req, resp) =>
                    {
                        Assert.AreEqual(payload, req.RequestObject);
                        return false;
                    })
                .ErrorService(
                    ex =>
                    {
                        Assert.Fail();
                        return true;
                    });

            IDictionary<string, object> routeValues = new Dictionary<string, object>();
            routeValues["action"] = "foo";

            using (IRequestMessage request = new RequestMessage<Payload>("Test", routeValues, new Uri("http://example.com/foo"), payload))
            {
                using (IResponseMessage response = new ResponseMessage())
                {
                    ResolvedService service = new ServiceResolver(services).Find(MethodType.Post, "foo");
                    InvokeActionsResult result = service.InvokeErrorActions(request, response, new Exception[0]);
                    Assert.IsFalse(result.Continue);
                    Assert.IsTrue(result.Success);
                    Assert.AreEqual(1, result.Results.Count);
                }
            }
        }
        public void ResolvedServiceReadRequest()
        {
            ServiceCollection services = new ServiceCollection();
            services
                .WithHostFormat(new JsonFormat())
                .WithService("Test", "/")
                    .WithEndpoint("{action}")
                        .Get(() => { })
                        .Post<Payload>((Payload p) => { });

            ResolvedService service = new ServiceResolver(services).Find(MethodType.Get, "foo");
            ReadRequestResult result;

            using (RequestMessage request = new RequestMessage(service.Name, service.RouteValues, new Uri("http://example.com/foo")))
            {
                result = service.ReadRequest(request, 0, null, null, null);
                Assert.IsNotNull(result);
                Assert.IsTrue(result.Success);
                Assert.IsNull(result.Exception);
                Assert.AreEqual(StatusCode.None, result.StatusCode);
                Assert.IsNull(result.RequestObject);
            }

            using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes("{\"date\":\"2012-09-22T18:46:00Z\",\"number\":42,\"text\":\"Hello, world!\"}")))
            {
                using (RequestMessage request = new RequestMessage<Payload>(service.Name, service.RouteValues, new Uri("http://example.com/foo")))
                {
                    service = new ServiceResolver(services).Find(MethodType.Post, "foo");
                    result = service.ReadRequest(request, (int)stream.Length, null, "application/json", stream);
                    Assert.IsNotNull(result);
                    Assert.IsTrue(result.Success);
                    Assert.IsNull(result.Exception);
                    Assert.AreEqual(StatusCode.None, result.StatusCode);
                    Assert.IsNotNull(result.RequestObject);

                    Payload payload = result.RequestObject as Payload;
                    Assert.IsNotNull(payload);
                    Assert.AreEqual(new DateTime(2012, 9, 22, 18, 46, 0, DateTimeKind.Utc), payload.Date);
                    Assert.AreEqual(42L, payload.Number);
                    Assert.AreEqual("Hello, world!", payload.Text);
                }
            }
        }
        public void ResolvedServiceReadRequestInvalidJson()
        {
            ServiceCollection services = new ServiceCollection();
            services
                .WithHostFormat(new JsonFormat())
                .WithService("Test", "/")
                    .WithEndpoint("{action}")
                        .Post<Payload>((Payload p) => { });

            ResolvedService service = new ServiceResolver(services).Find(MethodType.Post, "foo");

            using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes("this is not JSON")))
            {
                using (RequestMessage request = new RequestMessage<Payload>(service.Name, service.RouteValues, new Uri("http://example.com/foo")))
                {
                    ReadRequestResult result = service.ReadRequest(request, (int)stream.Length, null, "application/json", stream);
                    Assert.IsNotNull(result);
                    Assert.IsFalse(result.Success);
                    Assert.IsNotNull(result.Exception);
                    Assert.AreEqual(StatusCode.BadRequest, result.StatusCode);
                    Assert.IsNull(result.RequestObject);
                }
            }
        }
        public void ResolvedServiceReadRequestMissingEncoding()
        {
            ServiceCollection services = new ServiceCollection();
            services
                .WithHostFormat(new JsonFormat())
                .WithService("Test", "/")
                    .WithEndpoint("{action}")
                        .Post<Payload>((Payload p) => { });

            byte[] encodedPayload;

            using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes("{\"date\":\"2012-09-22T18:46:00Z\",\"number\":42,\"text\":\"Hello, world!\"}")))
            {
                using (MemoryStream outputStream = new MemoryStream())
                {
                    using (GZipStream compressionStream = new GZipStream(outputStream, CompressionMode.Compress))
                    {
                        stream.CopyTo(compressionStream);
                    }

                    encodedPayload = outputStream.ToArray();
                }
            }

            ResolvedService service = new ServiceResolver(services).Find(MethodType.Post, "foo");

            using (RequestMessage request = new RequestMessage<Payload>(service.Name, service.RouteValues, new Uri("http://example.com/foo")))
            {
                request.InputStream.Write(encodedPayload, 0, encodedPayload.Length);
                request.InputStream.Position = 0;
                request.SetEncodingFilter(EncodingType.Parse("gzip"), new GzipDeflateEncoding());

                ReadRequestResult result = service.ReadRequest(request, encodedPayload.Length, "gzip", "application/json", request.InputStream);
                Assert.IsNotNull(result);
                Assert.IsFalse(result.Success);
                Assert.IsNull(result.Exception);
                Assert.AreEqual(StatusCode.UnsupportedMediaType, result.StatusCode);
                Assert.IsNull(result.RequestObject);
            }
        }
        public void ResolvedServiceReadRequestMissingFormat()
        {
            ServiceCollection services = new ServiceCollection();
            services
                .WithService("Test", "/")
                    .WithEndpoint("{action}")
                        .Post<Payload>((Payload p) => { });

            ResolvedService service = new ServiceResolver(services).Find(MethodType.Post, "foo");

            using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes("{\"date\":\"2012-09-22T18:46:00Z\",\"number\":42,\"text\":\"Hello, world!\"}")))
            {
                using (RequestMessage request = new RequestMessage<Payload>(service.Name, service.RouteValues, new Uri("http://example.com/foo")))
                {
                    ReadRequestResult result = service.ReadRequest(request, (int)stream.Length, null, "application/json", stream);
                    Assert.IsNotNull(result);
                    Assert.IsFalse(result.Success);
                    Assert.IsNull(result.Exception);
                    Assert.AreEqual(StatusCode.UnsupportedMediaType, result.StatusCode);
                    Assert.IsNull(result.RequestObject);
                }
            }
        }
        public void ResolvedServiceWriteResponse()
        {
            Payload payload = new Payload()
            {
                Date = new DateTime(2012, 9, 22, 18, 46, 0, DateTimeKind.Utc),
                Number = 42,
                Text = "Hello, world!"
            };

            ServiceCollection services = new ServiceCollection();
            services
                .WithHostFormat(new JsonFormat())
                .WithService("Test", "/")
                    .WithEndpoint("{action}")
                        .Post<Payload>((Payload p) => { });

            using (ResponseMessage response = new ResponseMessage())
            {
                response.ResponseObject = payload;

                ResolvedService service = new ServiceResolver(services).Find(MethodType.Post, "foo");
                WriteResponseResult result = service.WriteResponse(response, "gzip, *", "application/json, */*");
                Assert.IsNotNull(result);
                Assert.IsNull(result.Exception);
                Assert.AreEqual(StatusCode.None, result.StatusCode);
                Assert.IsTrue(result.Success);

                response.OutputStream.Position = 0;

                using (StreamReader reader = new StreamReader(response.OutputStream))
                {
                    Assert.AreEqual("{\"date\":\"2012-09-22T18:46:00.0000000Z\",\"number\":42,\"text\":\"Hello, world!\"}", reader.ReadToEnd());
                }
            }
        }