private static void ApplyProvisioningTemplateToSite(ClientContext context, String siteUrl, String folder, String fileName, Dictionary<String, String> parameters = null, Handlers handlers = Handlers.All) { // Configure the XML file system provider XMLTemplateProvider provider = new XMLSharePointTemplateProvider(context, siteUrl, PnPPartnerPackConstants.PnPProvisioningTemplates + (!String.IsNullOrEmpty(folder) ? "/" + folder : String.Empty)); // Load the template from the XML stored copy ProvisioningTemplate template = provider.GetTemplate(fileName); template.Connector = provider.Connector; ProvisioningTemplateApplyingInformation ptai = new ProvisioningTemplateApplyingInformation(); // We exclude Term Groups because they are not supported in AppOnly ptai.HandlersToProcess = handlers; ptai.HandlersToProcess ^= Handlers.TermGroups; // Handle any custom parameter if (parameters != null) { foreach (var parameter in parameters) { template.Parameters.Add(parameter.Key, parameter.Value); } } // Apply the template to the target site context.Site.RootWeb.ApplyProvisioningTemplate(template, ptai); }
static void prettyPrint(int i,Handlers.Handler fizzBuzzHandler) { if (i> MAX) { return; } fizzBuzzHandler.HandleRequest(new Handlers.Request(i)); i++; prettyPrint(i, fizzBuzzHandler); }
public static void Log(string msg, params string[] args) { msg = string.Format(msg, args); if (logHandlers != null) { foreach (Action<string> i in logHandlers) { if (i != null) { i(msg); } } } else { logHandlers = new Handlers<string>(); } }
public void Can_Perform_GET_Async_Without_Async_Handle() { Uri baseUrl = new Uri("http://localhost:8888/"); const string val = "Basic async test"; ManualResetEvent resetEvent = new ManualResetEvent(false); using (SimpleServer.Create(baseUrl.AbsoluteUri, Handlers.EchoValue(val))) { RestClient client = new RestClient(baseUrl); RestRequest request = new RestRequest(""); client.ExecuteAsync(request, response => { Assert.NotNull(response.Content); Assert.AreEqual(val, response.Content); resetEvent.Set(); }); resetEvent.WaitOne(); } }
public static BindOperation AssemblyLoadContextResolving_NameMismatch() { var assemblyName = new AssemblyName(SubdirectoryAssemblyName); CustomALC alc = new CustomALC(nameof(AssemblyLoadContextResolving_NameMismatch)); using (var handlers = new Handlers(HandlerReturn.NameMismatch, alc)) { Assert.Throws <FileLoadException>(() => alc.LoadFromAssemblyName(assemblyName)); Assert.AreEqual(1, handlers.Invocations.Count); Assert.AreEqual(1, handlers.Binds.Count); return(new BindOperation() { AssemblyName = assemblyName, AssemblyLoadContext = alc.ToString(), Success = false, Cached = false, AssemblyLoadContextResolvingHandlers = handlers.Invocations, NestedBinds = handlers.Binds }); } }
public SettingPair[] GetExtensionsInstalled(ServerManager srvman) { var settings = new List<SettingPair>(); var config = srvman.GetApplicationHostConfiguration(); var handlersSection = (HandlersSection) config.GetSection(Constants.HandlersSection, typeof (HandlersSection)); var executalbesToLookFor = new[] { // Perl new KeyValuePair<string, string>(Constants.PerlPathSetting, "\\perl.exe"), // Php new KeyValuePair<string, string>(Constants.Php4PathSetting, "\\php.exe"), new KeyValuePair<string, string>(Constants.PhpPathSetting, "\\php-cgi.exe"), // Classic ASP new KeyValuePair<string, string>(Constants.AspPathSetting, @"\inetsrv\asp.dll"), // ASP.NET new KeyValuePair<string, string>(Constants.AspNet11PathSetting, @"\Framework\v1.1.4322\aspnet_isapi.dll"), new KeyValuePair<string, string>(Constants.AspNet20PathSetting, @"\Framework\v2.0.50727\aspnet_isapi.dll"), new KeyValuePair<string, string>(Constants.AspNet40PathSetting, @"\Framework\v4.0.30319\aspnet_isapi.dll"), // ASP.NET x64 new KeyValuePair<string, string>(Constants.AspNet20x64PathSetting, @"\Framework64\v2.0.50727\aspnet_isapi.dll"), new KeyValuePair<string, string>(Constants.AspNet40x64PathSetting, @"\Framework64\v4.0.30319\aspnet_isapi.dll"), }; foreach (var handler in handlersSection.Handlers) { foreach (var valuePair in executalbesToLookFor) { var key = valuePair.Key; if (handler.ScriptProcessor.EndsWith(valuePair.Value) && !settings.Exists(s => s.Name == key)) { settings.Add(new SettingPair{Name = valuePair.Key, Value = handler.ScriptProcessor}); } } } return settings.ToArray(); }
private async static Task <byte[]> UsernamePasswordEchoHandler(HttpServerRequest request) { var response = await Handlers.LoadResponse(request.Path); var authHeader = request.Headers["Authorization"]; byte[] base64 = Convert.FromBase64String(authHeader.Substring("Basic ".Length)); var parts = Encoding.UTF8.GetString(base64, 0, base64.Length).Split(':'); byte[] bodyArray = Encoding.UTF8.GetBytes(string.Join("|", parts)); string intro = String.Format("HTTP/1.1 {0} OK\r\n", response.StatusCode); string headers = Handlers.BuildHeaders(response.Headers); headers = headers + string.Format("Content-Length: {0}\r\n\r\n", bodyArray.Length); byte[] headerArray = Encoding.UTF8.GetBytes(intro + headers); byte[] result = headerArray.Concat(bodyArray).ToArray(); return(result); }
public void Passes_Default_Credentials_When_UseDefaultCredentials_Is_True() { const Method httpMethod = Method.GET; using (SimpleServer.Create(BASE_URL, Handlers.Generic <RequestHeadCapturer>(), AuthenticationSchemes.Negotiate)) { var client = new RestClient(BASE_URL); var request = new RestRequest(RequestHeadCapturer.RESOURCE, httpMethod) { UseDefaultCredentials = true }; var response = client.Execute(request); Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.NotNull(RequestHeadCapturer.CapturedHeaders); var keys = RequestHeadCapturer.CapturedHeaders.Keys.Cast <string>().ToArray(); Assert.True(keys.Contains("Authorization"), "Authorization header not present in HTTP request from client, even though UseDefaultCredentials = true"); } }
public void Does_Not_Pass_Default_Credentials_When_Server_Does_Not_Negotiate() { const Method httpMethod = Method.GET; using (SimpleServer.Create(BASE_URL, Handlers.Generic <RequestHeadCapturer>())) { var client = new RestClient(BASE_URL); var request = new RestRequest(RequestHeadCapturer.RESOURCE, httpMethod) { UseDefaultCredentials = true }; client.Execute(request); Assert.NotNull(RequestHeadCapturer.CapturedHeaders); var keys = RequestHeadCapturer.CapturedHeaders.Keys.Cast <string>().ToArray(); Assert.False(keys.Contains("Authorization"), "Authorization header was present in HTTP request from client, even though server does not use the Negotiate scheme"); } }
public void MultipartFormData_Without_File_Creates_A_Valid_RequestBody() { string expectedFormBoundary = "-------------------------------28947758029299"; using (SimpleServer.Create(BASE_URL, Handlers.Generic <RequestBodyCapturer>())) { RestClient client = new RestClient(BASE_URL); RestRequest request = new RestRequest(RequestBodyCapturer.RESOURCE, Method.POST) { AlwaysMultipartFormData = true }; const string contentType = "text/plain"; const string bodyData = "abc123 foo bar baz BING!"; const string multipartName = "mybody"; request.AddParameter(multipartName, bodyData, contentType, ParameterType.RequestBody); client.Execute(request); string expectedBody = expectedFormBoundary + Environment.NewLine + "Content-Type: " + contentType + Environment.NewLine + @"Content-Disposition: form-data; name=""" + multipartName + @"""" + Environment.NewLine + Environment.NewLine + bodyData + Environment.NewLine + expectedFormBoundary + "--" + Environment.NewLine; Console.WriteLine(RequestBodyCapturer.CapturedEntityBody); Assert.AreEqual(expectedBody, RequestBodyCapturer.CapturedEntityBody, "Empty multipart generated: " + RequestBodyCapturer.CapturedEntityBody); } }
public void IdentifyCanTimeOutSync(UpdateMode mode) { using (var server = HttpServer.Start(Handlers.Switchable(out var switchable))) { switchable.Target = SetupResponse(_flagData1, mode); var config = BaseConfig(server.Uri, mode); using (var client = TestUtil.CreateClient(config, _user)) { var req1 = VerifyRequest(server.Recorder, mode); VerifyFlagValues(client, _flagData1); switchable.Target = Handlers.Delay(TimeSpan.FromSeconds(2)) .Then(SetupResponse(_flagData1, mode)); var success = client.Identify(_otherUser, TimeSpan.FromMilliseconds(100)); Assert.False(success); Assert.False(client.Initialized); Assert.Null(client.StringVariation(_flagData1.Items.First().Key, null)); } } }
public void Can_Be_Added_To_PUT_Request() { const Method httpMethod = Method.PUT; using (SimpleServer.Create(BASE_URL, Handlers.Generic <RequestBodyCapturer>())) { RestClient client = new RestClient(BASE_URL); RestRequest request = new RestRequest(RequestBodyCapturer.RESOURCE, httpMethod); const string contentType = "text/plain"; const string bodyData = "abc123 foo bar baz BING!"; request.AddParameter(contentType, bodyData, ParameterType.RequestBody); ManualResetEvent resetEvent = new ManualResetEvent(false); client.ExecuteAsync(request, response => resetEvent.Set()); resetEvent.WaitOne(); AssertHasRequestBody(contentType, bodyData); } }
public void Can_Handle_Exception_Thrown_By_OnBeforeDeserialization_Handler() { const string baseUrl = "http://localhost:8888/"; const string exceptionMessage = "Thrown from OnBeforeDeserialization"; using (SimpleServer.Create(baseUrl, Handlers.Generic <ResponseHandler>())) { RestClient client = new RestClient(baseUrl); RestRequest request = new RestRequest("success"); request.OnBeforeDeserialization += r => { throw new Exception(exceptionMessage); }; Task <IRestResponse <Response> > task = client.ExecuteTaskAsync <Response>(request); task.Wait(); IRestResponse <Response> response = task.Result; Assert.AreEqual(exceptionMessage, response.ErrorMessage); Assert.AreEqual(ResponseStatus.Error, response.ResponseStatus); } }
public void getHeader() { // Метод генерирует шапку страницы HttpCookie cookie = Request.Cookies["cookie"]; // Пытаемся получить куки пользователя if (cookie != null) { // Если куки существует if (Handlers.getUserData(cookie.Value)[6].Equals("simple")) { // Если это простой пользователь Response.Write(String.Format(@" <div class='col text'> <a href='./pages/Basket.aspx' class='link button'>Корзина ({0})</a> </div> <div class='col right text'> <a href='./authorization/Exit.aspx' class='link button'>Выйти</a> </div> ", Handlers.getBasketSize(Request.Cookies["cookie"].Value))); } else { // Иначе это администратор Response.Write(@" <div class='col text'> <a href='./admin/Admin.aspx' class='link button'>Панель администратора</a> </div> <div class='col right text'> <a href='./authorization/Exit.aspx' class='link button'>Выйти</a> </div> "); } } else // Если у нас нет информации о пользователе { Response.Write(@" <div class='col right text'> <a href='./authorization/Login.aspx' class='link button'>Войти</a> <a href='./authorization/Registration.aspx' class='link button'>Зарегистрироваться</a> </div> "); // То предлагаем ему зарегистрироваться } }
/// <summary> /// Challenge the specified authentication scheme. /// </summary> /// <param name="context">The <see cref="HttpContext"/>.</param> /// <param name="scheme">The name of the authentication scheme.</param> /// <param name="properties">The <see cref="AuthenticationProperties"/>.</param> /// <returns>A task.</returns> public virtual async Task ChallengeAsync(HttpContext context, string scheme, AuthenticationProperties properties) { if (scheme == null) { var defaultChallengeScheme = await Schemes.GetDefaultChallengeSchemeAsync(); scheme = defaultChallengeScheme?.Name; if (scheme == null) { throw new InvalidOperationException($"No authenticationScheme was specified, and there was no DefaultChallengeScheme found."); } } var handler = await Handlers.GetHandlerAsync(context, scheme); if (handler == null) { throw new InvalidOperationException($"No authentication handler is configured to handle the scheme: {scheme}"); } await handler.ChallengeAsync(properties); }
public MucRoomMember(MucRoom room, Jid memberJid, Jid realJid, XmppStream stream, XmppHandlerContext context) { if (room == null) { throw new ArgumentNullException("room"); } if (memberJid == null) { throw new ArgumentNullException("memberJid"); } if (realJid == null) { throw new ArgumentNullException("realJid"); } if (context == null) { throw new ArgumentNullException("sender"); } this.room = room; this.stream = stream; this.context = context; this.sender = context.Sender; //Register disconect context.SessionManager.SessionUnavailable += SessionManager_SessionUnavailable; ParentService = room; RealJid = realJid; Jid = memberJid; Name = memberJid.Resource; presenceType = PresenceType.unavailable; //Create handler Handlers.Add(new MucRoomMemberStanzaHandler(this)); Handlers.Add(new MucRoomMemberDiscoHandler(Jid, RealJid)); DiscoInfo.AddIdentity(new DiscoIdentity("text", Name, "member")); DiscoInfo.AddFeature(new DiscoFeature(Core.protocol.Uri.DISCO_INFO)); DiscoInfo.AddFeature(new DiscoFeature(Core.protocol.Uri.DISCO_ITEMS)); }
public void Handles_Different_Root_Element_On_Http_Error() { _server.SetHandler(Handlers.Generic <ResponseHandler>()); RestRequest request = new RestRequest("error") { RootElement = "Success" }; request.OnBeforeDeserialization = resp => { if (resp.StatusCode == HttpStatusCode.BadRequest) { request.RootElement = "Error"; } }; IRestResponse <Response> response = _client.Execute <Response>(request); Assert.AreEqual(HttpStatusCode.BadRequest, response.StatusCode); Assert.AreEqual("Not found!", response.Data.Message); }
/// <summary> /// Forbid the specified authentication scheme. /// </summary> /// <param name="context">The <see cref="HttpContext"/>.</param> /// <param name="scheme">The name of the authentication scheme.</param> /// <param name="properties">The <see cref="AuthenticationProperties"/>.</param> /// <returns>A task.</returns> public virtual async Task ForbidAsync(HttpContext context, string?scheme, AuthenticationProperties?properties) { if (scheme == null) { var defaultForbidScheme = await Schemes.GetDefaultForbidSchemeAsync(); scheme = defaultForbidScheme?.Name; if (scheme == null) { throw new InvalidOperationException($"No authenticationScheme was specified, and there was no DefaultForbidScheme found. The default schemes can be set using either AddAuthentication(string defaultScheme) or AddAuthentication(Action<AuthenticationOptions> configureOptions)."); } } var handler = await Handlers.GetHandlerAsync(context, scheme); if (handler == null) { throw await CreateMissingHandlerException(scheme); } await handler.ForbidAsync(properties); }
protected virtual void Visit(IFragmentBuilder expression) { if (expression == null) { throw new ArgumentNullException("expression"); } var handler = default(SqlQueryWriterVisitorHandler); if (!Handlers.TryGetValue(expression.FragmentType, out handler)) { throw new NotImplementedException(); } this.AddFragmentContext(expression); try { handler(this, expression); } finally { this.RemoveFragmentContext(); } }
public static ProjFS New( string lowerdir, string mountdir, Handlers handlers, string[] argv) { IntPtr handle = _New( lowerdir, mountdir, ref handlers, (uint)Marshal.SizeOf <Handlers>(), IntPtr.Zero, argv.Length, argv); if (handle == IntPtr.Zero) { return(null); } return(new ProjFS(handle)); }
public WarehouseApp(int senderPort) { var receiverPort = senderPort + 1; Include <MartenBackedPersistence>(); Settings.Alter <StoreOptions>(_ => { _.Connection(ConnectionSource.ConnectionString); }); //Note: whether or not our event is destined for a durable queue, it will be stored durably in the outbox because of the implementation of the handlers. Publish.Message <ItemOutOfStock>().To($"tcp://localhost:{senderPort}/durable"); Transports.DurableListenerAt(receiverPort); Settings.Alter <StoreOptions>(_ => { _.Connection(ConnectionSource.ConnectionString); _.DatabaseSchemaName = "warehouse"; }); Handlers.DisableConventionalDiscovery(); Handlers.IncludeType <THandler>(); }
public void Handles_Default_Root_Element_On_No_Error() { _server.SetHandler(Handlers.Generic <ResponseHandler>()); var request = new RestRequest("success") { RootElement = "Success" }; request.OnBeforeDeserialization = resp => { if (resp.StatusCode == HttpStatusCode.NotFound) { request.RootElement = "Error"; } }; var response = _client.Execute <Response>(request); Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); Assert.AreEqual("Works!", response.Data.Message); }
/// <summary> /// Forbid the specified authentication scheme. /// </summary> /// <param name="context">The <see cref="ProtoContext"/>.</param> /// <param name="scheme">The name of the authentication scheme.</param> /// <param name="properties">The <see cref="AuthenticationProperties"/>.</param> /// <returns>A task.</returns> public virtual async Task ForbidAsync(ProtoContext context, string scheme, AuthenticationProperties properties) { if (scheme == null) { var defaultForbidScheme = await Schemes.GetDefaultForbidSchemeAsync(); scheme = defaultForbidScheme?.Name; if (scheme == null) { throw new InvalidOperationException($"No authenticationScheme was specified, and there was no DefaultForbidScheme found."); } } var handler = await Handlers.GetHandlerAsync(context, scheme); if (handler == null) { throw await CreateMissingHandlerException(scheme); } await handler.ForbidAsync(properties); }
public void Can_Perform_GET_Async() { const string val = "Basic async test"; var resetEvent = new ManualResetEvent(false); using var server = SimpleServer.Create(Handlers.EchoValue(val)); var client = new RestClient(server.Url); var request = new RestRequest(""); client.ExecuteAsync( request, (response, asyncHandle) => { Assert.NotNull(response.Content); Assert.AreEqual(val, response.Content); resetEvent.Set(); } ); resetEvent.WaitOne(); }
//this might need reworking with MulticastDelegate internal void HandleSignal(Message msg) { Signal signal = new Signal(msg); //TODO: this is a hack, not necessary when MatchRule is complete MatchRule rule = new MatchRule(); rule.MessageType = MessageType.Signal; rule.Interface = signal.Interface; rule.Member = signal.Member; rule.Path = signal.Path; Delegate dlg; if (Handlers.TryGetValue(rule, out dlg)) { //dlg.DynamicInvoke (GetDynamicValues (msg)); MethodInfo mi = dlg.Method; //signals have no return value dlg.DynamicInvoke(MessageHelper.GetDynamicValues(msg, mi.GetParameters())); } else { //TODO: how should we handle this condition? sending an Error may not be appropriate in this case if (Protocol.Verbose) { Console.Error.WriteLine("Warning: No signal handler for " + signal.Member); } if (trap_signals_ref > 0) { lock (delayed_signals_recycle) { delayed_signals_recycle.Enqueue(msg); } } } }
public async Task <ContentItem> NewAsync(string contentType) { var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(contentType); if (contentTypeDefinition == null) { contentTypeDefinition = new ContentTypeDefinitionBuilder().Named(contentType).Build(); } // create a new kernel for the model instance var context = new ActivatingContentContext { ContentType = contentTypeDefinition.Name, Definition = contentTypeDefinition, ContentItem = new ContentItem() { ContentType = contentTypeDefinition.Name } }; // invoke handlers to weld aspects onto kernel await Handlers.InvokeAsync((handler, context) => handler.ActivatingAsync(context), context, _logger); var context2 = new ActivatedContentContext(context.ContentItem); context2.ContentItem.ContentItemId = _idGenerator.GenerateUniqueId(context2.ContentItem); await ReversedHandlers.InvokeAsync((handler, context2) => handler.ActivatedAsync(context2), context2, _logger); var context3 = new InitializingContentContext(context2.ContentItem); await Handlers.InvokeAsync((handler, context3) => handler.InitializingAsync(context3), context3, _logger); await ReversedHandlers.InvokeAsync((handler, context3) => handler.InitializedAsync(context3), context3, _logger); // composite result is returned return(context3.ContentItem); }
public void Request_Handler_Async_With_Response() { ResonanceTransporter t1 = new ResonanceTransporter(new InMemoryAdapter("TST")); ResonanceTransporter t2 = new ResonanceTransporter(new InMemoryAdapter("TST")); t1.Connect(); t2.Connect(); Handlers handlers = new Handlers(); IDisposable handler = t2.CreateHandlerBuilder() .ForRequest <CalculateRequest>() .WithResponse <CalculateResponse>() .IsAsync() .Build(handlers.HandleRequestAsyncWithResponse); var request = new CalculateRequest() { A = 10, B = 15 }; var response = t1.SendRequest <CalculateRequest, CalculateResponse>(request); Assert.AreEqual(response.Sum, request.A + request.B); handler.Dispose(); Assert.ThrowsException <TimeoutException>(() => { t1.SendRequest <CalculateRequest, CalculateResponse>(request, new ResonanceRequestConfig() { Timeout = TimeSpan.FromSeconds(1) }); }); t1.Dispose(true); t2.Dispose(true); }
public void Process(PluginLoadContext context) { foreach (var commandType in context.Classes) { try { if (!typeof(ISynapseCommand).IsAssignableFrom(commandType)) { continue; } var cmdInfoAttribute = commandType.GetCustomAttribute <CommandInformation>(); if (cmdInfoAttribute == null) { continue; } object classObject; ConstructorInfo[] allCtors = commandType.GetConstructors(); ConstructorInfo diCtor = allCtors.FirstOrDefault(ctorInfo => ctorInfo.GetParameters() .Any(paramInfo => paramInfo.ParameterType == context.PluginType)); if (diCtor != null) //If DI-Ctor is found { classObject = Activator.CreateInstance(commandType, args: new object[] { context.Plugin }); } else //There is no DI-Ctor { classObject = Activator.CreateInstance(commandType); } Handlers.RegisterCommand(classObject as ISynapseCommand, true); } catch (Exception e) { Logger.Get.Error($"Error loading command {commandType.Name} from {context.Information.Name}\n{e}"); } } }
public void Handles_Default_Root_Element_On_No_Error() { const string baseUrl = "http://localhost:8080/"; using (SimpleServer.Create(baseUrl, Handlers.Generic <ResponseHandler>())) { var client = new RestClient(baseUrl); var request = new RestRequest("success"); request.RootElement = "Success"; request.OnBeforeDeserialization = resp => { if (resp.StatusCode == HttpStatusCode.NotFound) { request.RootElement = "Error"; } }; var response = client.Execute <Response>(request); Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal("Works!", response.Data.Message); } }
public async void VerifyRecoverableHttpErrorIsOnlyRetriedOnce(int status) { var handler = Handlers.Sequential( Handlers.Status(status), // initial request gets error Handlers.Status(status), // second request also gets error Handlers.Status(202) // third request would succeed if it got that far ); await WithServerAndSender(handler, async (server, es) => { var result = await es.SendEventDataAsync(EventDataKind.AnalyticsEvents, FakeData, 1); Assert.Equal(DeliveryStatus.Failed, result.Status); Assert.Null(result.TimeFromServer); var req1 = server.Recorder.RequireRequest(); var req2 = server.Recorder.RequireRequest(); Assert.Equal(req1.Body, req2.Body); Assert.Equal(req1.Headers.Get("X-LaunchDarkly-Payload-ID"), req2.Headers.Get("X-LaunchDarkly-Payload-ID")); server.Recorder.RequireNoRequests(TimeSpan.FromMilliseconds(100)); }); }
public override void Configure(IDictionary <string, string> properties) { DiscoInfo.AddIdentity(new DiscoIdentity("server", Name, "im")); Handlers.Add(new ClientNamespaceHandler()); Handlers.Add(new AuthDigestMD5Handler()); Handlers.Add(new AuthTMTokenHandler()); Handlers.Add(new BindSessionHandler()); Handlers.Add(new RosterHandler()); Handlers.Add(new VCardHandler()); Handlers.Add(new VerTimePingHandler()); Handlers.Add(new PrivateHandler()); Handlers.Add(new PresenceHandler()); Handlers.Add(new MessageHandler()); Handlers.Add(new MessageArchiveHandler()); Handlers.Add(new LastHandler()); Handlers.Add(new RegisterHandler()); Handlers.Add(new TransferHandler()); Handlers.Add(new CommandHandler()); Handlers.Add(new OfflineProvider(Jid)); Handlers.Add(new DiscoHandler(Jid)); messageAnnounceHandler = new MessageAnnounceHandler(); }
public IAsyncEventHandler CreateHandler(Func <TArg, Task> handler, [CallerFilePath] string callerFile = null, [CallerLineNumber] int line = 0) { if (handler == null) { throw new ArgumentNullException(nameof(handler)); } lock (Handlers) { RemoveHandler(handler); var result = new AsyncEventTaskHandler <TArg> { Action = handler, Event = this, Caller = Debugger.IsAttached ? $"{callerFile}:{line}" : string.Empty }; Handlers.Add(result); return(result); } }
public Receiver() { var type = GetType(); foreach (var method in type.GetMethods(BindingFlags.Instance | BindingFlags.NonPublic) .Where(p => p.ReturnType == typeof(void))) { var attribute = method.GetCustomAttribute <MessageHandlerAttribute>(); if (attribute != null) { if (Handlers.ContainsKey(attribute.Name)) { throw new ArgumentException($"Message '{attribute.Name}' already registered."); } var handler = method.CreateDelegate( Expression.GetDelegateType(method.GetParameters() .Select(p => p.ParameterType).Concat(new[] { method.ReturnType }).ToArray() ), this); Handlers.Add(attribute.Name, handler); } } }
public void Can_Timeout_PUT_TaskAsync() { const string baseUrl = "http://localhost:8080/"; using (SimpleServer.Create(baseUrl, Handlers.Generic <ResponseHandler>())) { var client = new RestClient(baseUrl); var request = new RestRequest("timeout", Method.PUT).AddBody("Body_Content"); //Half the value of ResponseHandler.Timeout request.Timeout = 500; System.AggregateException agg = Assert.Throws <System.AggregateException>( delegate { var task = client.ExecuteTaskAsync(request); task.Wait(); }); Assert.IsType(typeof(WebException), agg.InnerException); Assert.Equal("The request timed-out.", agg.InnerException.Message); } }
public void Release( Handlers.Jobs.IJobRunner runner ) { }
private string GetProvisioningTemplateXML(XMLPnPSchemaVersion schema, string path) { SelectedWeb.EnsureProperty(w => w.Url); var creationInformation = new ProvisioningTemplateCreationInformation(SelectedWeb); if (this.MyInvocation.BoundParameters.ContainsKey("Handlers")) { creationInformation.HandlersToProcess = Handlers; } if (this.MyInvocation.BoundParameters.ContainsKey("ExcludeHandlers")) { foreach (var handler in (OfficeDevPnP.Core.Framework.Provisioning.Model.Handlers[])Enum.GetValues(typeof(Handlers))) { if (!ExcludeHandlers.Has(handler) && handler != Handlers.All) { Handlers = Handlers | handler; } } creationInformation.HandlersToProcess = Handlers; } creationInformation.PersistBrandingFiles = PersistBrandingFiles || PersistComposedLookFiles; creationInformation.PersistPublishingFiles = PersistPublishingFiles; creationInformation.IncludeNativePublishingFiles = IncludeNativePublishingFiles; creationInformation.IncludeSiteGroups = IncludeSiteGroups; creationInformation.FileConnector = new FileSystemConnector(path, ""); #pragma warning disable CS0618 // Type or member is obsolete if (NoBaseTemplate) { creationInformation.BaseTemplate = null; } else { creationInformation.BaseTemplate = this.SelectedWeb.GetBaseTemplate(); } #pragma warning restore CS0618 // Type or member is obsolete creationInformation.ProgressDelegate = (message, step, total) => { WriteProgress(new ProgressRecord(0, string.Format("Extracting Template from {0}", SelectedWeb.Url), message) { PercentComplete = (100 / total) * step }); }; creationInformation.MessagesDelegate = (message, type) => { if (type == ProvisioningMessageType.Warning) { WriteWarning(message); } }; if (IncludeAllTermGroups) { creationInformation.IncludeAllTermGroups = true; } else { if (IncludeSiteCollectionTermGroup) { creationInformation.IncludeSiteCollectionTermGroup = true; } } var template = SelectedWeb.GetProvisioningTemplate(creationInformation); ITemplateFormatter formatter = null; switch (schema) { case XMLPnPSchemaVersion.LATEST: { formatter = XMLPnPSchemaFormatter.LatestFormatter; break; } case XMLPnPSchemaVersion.V201503: { #pragma warning disable CS0618 // Type or member is obsolete formatter = XMLPnPSchemaFormatter.GetSpecificFormatter(XMLConstants.PROVISIONING_SCHEMA_NAMESPACE_2015_03); #pragma warning restore CS0618 // Type or member is obsolete break; } case XMLPnPSchemaVersion.V201505: { formatter = XMLPnPSchemaFormatter.GetSpecificFormatter(XMLConstants.PROVISIONING_SCHEMA_NAMESPACE_2015_05); break; } case XMLPnPSchemaVersion.V201508: { formatter = XMLPnPSchemaFormatter.GetSpecificFormatter(XMLConstants.PROVISIONING_SCHEMA_NAMESPACE_2015_08); break; } case XMLPnPSchemaVersion.V201512: { formatter = XMLPnPSchemaFormatter.GetSpecificFormatter(XMLConstants.PROVISIONING_SCHEMA_NAMESPACE_2015_12); break; } } var _outputStream = formatter.ToFormattedTemplate(template); StreamReader reader = new StreamReader(_outputStream); return reader.ReadToEnd(); }
public void Release( Handlers.Jobs.IJobWorker performer ) { }
public void Register(string p, HandlePutRequest put, HandleGetRequest get) { Handlers h = new Handlers { put = put, get = get }; handlers.Add(p, h); }
protected override void ExecuteCmdlet() { SelectedWeb.EnsureProperty(w => w.Url); if (!System.IO.Path.IsPathRooted(Path)) { Path = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, Path); } if (!string.IsNullOrEmpty(ResourceFolder)) { if (!System.IO.Path.IsPathRooted(ResourceFolder)) { ResourceFolder = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, ResourceFolder); } } FileInfo fileInfo = new FileInfo(Path); XMLTemplateProvider provider = null; ProvisioningTemplate provisioningTemplate = null; var isOpenOfficeFile = IsOpenOfficeFile(Path); if (isOpenOfficeFile) { var fileSystemconnector = new FileSystemConnector(fileInfo.DirectoryName, ""); provider = new XMLOpenXMLTemplateProvider(new OpenXMLConnector(fileInfo.Name, fileSystemconnector)); var fileName = fileInfo.Name.Substring(0, fileInfo.Name.LastIndexOf(".")) + ".xml"; provisioningTemplate = provider.GetTemplate(fileName); } else { provider = new XMLFileSystemTemplateProvider(fileInfo.DirectoryName, ""); provisioningTemplate = provider.GetTemplate(fileInfo.Name); } if (provisioningTemplate != null) { if (isOpenOfficeFile) { provisioningTemplate.Connector = provider.Connector; } else { FileSystemConnector fileSystemConnector = null; if (ResourceFolder != null) { fileSystemConnector = new FileSystemConnector(ResourceFolder, ""); provisioningTemplate.Connector = fileSystemConnector; } else { provisioningTemplate.Connector = provider.Connector; } } if (Parameters != null) { foreach (var parameter in Parameters.Keys) { if (provisioningTemplate.Parameters.ContainsKey(parameter.ToString())) { provisioningTemplate.Parameters[parameter.ToString()] = Parameters[parameter].ToString(); } else { provisioningTemplate.Parameters.Add(parameter.ToString(), Parameters[parameter].ToString()); } } } var applyingInformation = new ProvisioningTemplateApplyingInformation(); if (this.MyInvocation.BoundParameters.ContainsKey("Handlers")) { applyingInformation.HandlersToProcess = Handlers; } if (this.MyInvocation.BoundParameters.ContainsKey("ExcludeHandlers")) { foreach (var handler in (OfficeDevPnP.Core.Framework.Provisioning.Model.Handlers[])Enum.GetValues(typeof(Handlers))) { if (!ExcludeHandlers.Has(handler) && handler != Handlers.All) { Handlers = Handlers | handler; } } applyingInformation.HandlersToProcess = Handlers; } if (ExtensibilityHandlers != null) { applyingInformation.ExtensibilityHandlers = ExtensibilityHandlers.ToList<ExtensibilityHandler>(); } applyingInformation.ProgressDelegate = (message, step, total) => { WriteProgress(new ProgressRecord(0, string.Format("Applying template to {0}", SelectedWeb.Url), message) { PercentComplete = (100 / total) * step }); }; applyingInformation.MessagesDelegate = (message, type) => { if (type == ProvisioningMessageType.Warning) { WriteWarning(message); } }; applyingInformation.OverwriteSystemPropertyBagValues = OverwriteSystemPropertyBagValues; SelectedWeb.ApplyProvisioningTemplate(provisioningTemplate, applyingInformation); } }
private void ExtractTemplate(XMLPnPSchemaVersion schema, string path, string packageName) { SelectedWeb.EnsureProperty(w => w.Url); var creationInformation = new ProvisioningTemplateCreationInformation(SelectedWeb); if (MyInvocation.BoundParameters.ContainsKey("Handlers")) { creationInformation.HandlersToProcess = Handlers; } if (MyInvocation.BoundParameters.ContainsKey("ExcludeHandlers")) { foreach (var handler in (Handlers[])Enum.GetValues(typeof(Handlers))) { if (!ExcludeHandlers.Has(handler) && handler != Handlers.All) { Handlers = Handlers | handler; } } creationInformation.HandlersToProcess = Handlers; } var extension = ""; if (packageName != null) { if (packageName.IndexOf(".", StringComparison.Ordinal) > -1) { extension = packageName.Substring(packageName.LastIndexOf(".", StringComparison.Ordinal)).ToLower(); } else { packageName += ".pnp"; extension = ".pnp"; } } var fileSystemConnector = new FileSystemConnector(path, ""); if (extension == ".pnp") { creationInformation.FileConnector = new OpenXMLConnector(packageName, fileSystemConnector); } else { creationInformation.FileConnector = fileSystemConnector; } #pragma warning disable 618 creationInformation.PersistBrandingFiles = PersistBrandingFiles || PersistComposedLookFiles; #pragma warning restore 618 creationInformation.PersistPublishingFiles = PersistPublishingFiles; creationInformation.IncludeNativePublishingFiles = IncludeNativePublishingFiles; creationInformation.IncludeSiteGroups = IncludeSiteGroups; creationInformation.IncludeTermGroupsSecurity = IncludeTermGroupsSecurity; #if !SP2013 creationInformation.PersistMultiLanguageResources = PersistMultiLanguageResources; if (!string.IsNullOrEmpty(ResourceFilePrefix)) { creationInformation.ResourceFilePrefix = ResourceFilePrefix; } else { if (Out != null) { FileInfo fileInfo = new FileInfo(Out); var prefix = fileInfo.Name.Substring(0, fileInfo.Name.LastIndexOf(".", StringComparison.Ordinal)); creationInformation.ResourceFilePrefix = prefix; } } #endif if (ExtensibilityHandlers != null) { creationInformation.ExtensibilityHandlers = ExtensibilityHandlers.ToList(); } #pragma warning disable CS0618 // Type or member is obsolete if (NoBaseTemplate) { creationInformation.BaseTemplate = null; } else { creationInformation.BaseTemplate = SelectedWeb.GetBaseTemplate(); } #pragma warning restore CS0618 // Type or member is obsolete creationInformation.ProgressDelegate = (message, step, total) => { WriteProgress(new ProgressRecord(0, $"Extracting Template from {SelectedWeb.Url}", message) { PercentComplete = (100 / total) * step }); }; creationInformation.MessagesDelegate = (message, type) => { if (type == ProvisioningMessageType.Warning) { WriteWarning(message); } }; if (IncludeAllTermGroups) { creationInformation.IncludeAllTermGroups = true; } else { if (IncludeSiteCollectionTermGroup) { creationInformation.IncludeSiteCollectionTermGroup = true; } } var template = SelectedWeb.GetProvisioningTemplate(creationInformation); // Set metadata for template, if any SetTemplateMetadata(template, TemplateDisplayName, TemplateImagePreviewUrl, TemplateProperties); if (!OutputInstance) { ITemplateFormatter formatter = null; switch (schema) { case XMLPnPSchemaVersion.LATEST: { formatter = XMLPnPSchemaFormatter.LatestFormatter; break; } case XMLPnPSchemaVersion.V201503: { #pragma warning disable CS0618 // Type or member is obsolete formatter = XMLPnPSchemaFormatter.GetSpecificFormatter(XMLConstants.PROVISIONING_SCHEMA_NAMESPACE_2015_03); #pragma warning restore CS0618 // Type or member is obsolete break; } case XMLPnPSchemaVersion.V201505: { #pragma warning disable CS0618 // Type or member is obsolete formatter = XMLPnPSchemaFormatter.GetSpecificFormatter(XMLConstants.PROVISIONING_SCHEMA_NAMESPACE_2015_05); #pragma warning restore CS0618 // Type or member is obsolete break; } case XMLPnPSchemaVersion.V201508: { #pragma warning disable CS0618 // Type or member is obsolete formatter = XMLPnPSchemaFormatter.GetSpecificFormatter(XMLConstants.PROVISIONING_SCHEMA_NAMESPACE_2015_08); #pragma warning restore CS0618 // Type or member is obsolete break; } case XMLPnPSchemaVersion.V201512: { formatter = XMLPnPSchemaFormatter.GetSpecificFormatter(XMLConstants.PROVISIONING_SCHEMA_NAMESPACE_2015_12); break; } } if (extension == ".pnp") { XMLTemplateProvider provider = new XMLOpenXMLTemplateProvider( creationInformation.FileConnector as OpenXMLConnector); var templateFileName = packageName.Substring(0, packageName.LastIndexOf(".", StringComparison.Ordinal)) + ".xml"; provider.SaveAs(template, templateFileName, formatter, TemplateProviderExtensions); } else { if (Out != null) { XMLTemplateProvider provider = new XMLFileSystemTemplateProvider(path, ""); provider.SaveAs(template, Path.Combine(path, packageName), formatter, TemplateProviderExtensions); } else { var outputStream = formatter.ToFormattedTemplate(template); var reader = new StreamReader(outputStream); WriteObject(reader.ReadToEnd()); } } } else { WriteObject(template); } }
protected override void ExecuteCmdlet() { SelectedWeb.EnsureProperty(w => w.Url); ProvisioningTemplate provisioningTemplate; FileConnectorBase fileConnector; if (MyInvocation.BoundParameters.ContainsKey("Path")) { bool templateFromFileSystem = !Path.ToLower().StartsWith("http"); string templateFileName = System.IO.Path.GetFileName(Path); if (templateFromFileSystem) { if (!System.IO.Path.IsPathRooted(Path)) { Path = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, Path); } if (!string.IsNullOrEmpty(ResourceFolder)) { if (!System.IO.Path.IsPathRooted(ResourceFolder)) { ResourceFolder = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, ResourceFolder); } } var fileInfo = new FileInfo(Path); fileConnector = new FileSystemConnector(fileInfo.DirectoryName, ""); } else { Uri fileUri = new Uri(Path); var webUrl = Microsoft.SharePoint.Client.Web.WebUrlFromFolderUrlDirect(ClientContext, fileUri); var templateContext = ClientContext.Clone(webUrl.ToString()); var library = Path.ToLower().Replace(templateContext.Url.ToLower(), "").TrimStart('/'); var idx = library.IndexOf("/", StringComparison.Ordinal); library = library.Substring(0, idx); // This syntax creates a SharePoint connector regardless we have the -InputInstance argument or not fileConnector = new SharePointConnector(templateContext, templateContext.Url, library); } // If we don't have the -InputInstance parameter, we load the template from the source connector Stream stream = fileConnector.GetFileStream(templateFileName); var isOpenOfficeFile = IsOpenOfficeFile(stream); XMLTemplateProvider provider; if (isOpenOfficeFile) { provider = new XMLOpenXMLTemplateProvider(new OpenXMLConnector(templateFileName, fileConnector)); templateFileName = templateFileName.Substring(0, templateFileName.LastIndexOf(".", StringComparison.Ordinal)) + ".xml"; } else { if (templateFromFileSystem) { provider = new XMLFileSystemTemplateProvider(fileConnector.Parameters[FileConnectorBase.CONNECTIONSTRING] + "", ""); } else { throw new NotSupportedException("Only .pnp package files are supported from a SharePoint library"); } } provisioningTemplate = provider.GetTemplate(templateFileName, TemplateProviderExtensions); if (provisioningTemplate == null) { // If we don't have the template, raise an error and exit WriteError(new ErrorRecord(new Exception("The -Path parameter targets an invalid repository or template object."), "WRONG_PATH", ErrorCategory.SyntaxError, null)); return; } if (isOpenOfficeFile) { provisioningTemplate.Connector = provider.Connector; } else { if (ResourceFolder != null) { var fileSystemConnector = new FileSystemConnector(ResourceFolder, ""); provisioningTemplate.Connector = fileSystemConnector; } else { provisioningTemplate.Connector = provider.Connector; } } } else { if (MyInvocation.BoundParameters.ContainsKey("GalleryTemplateId")) { provisioningTemplate = GalleryHelper.GetTemplate(GalleryTemplateId); } else { provisioningTemplate = InputInstance; } if (ResourceFolder != null) { var fileSystemConnector = new FileSystemConnector(ResourceFolder, ""); provisioningTemplate.Connector = fileSystemConnector; } else { if (Path != null) { if (!System.IO.Path.IsPathRooted(Path)) { Path = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, Path); } } else { Path = SessionState.Path.CurrentFileSystemLocation.Path; } var fileInfo = new FileInfo(Path); fileConnector = new FileSystemConnector(fileInfo.DirectoryName, ""); provisioningTemplate.Connector = fileConnector; } } if (Parameters != null) { foreach (var parameter in Parameters.Keys) { if (provisioningTemplate.Parameters.ContainsKey(parameter.ToString())) { provisioningTemplate.Parameters[parameter.ToString()] = Parameters[parameter].ToString(); } else { provisioningTemplate.Parameters.Add(parameter.ToString(), Parameters[parameter].ToString()); } } } var applyingInformation = new ProvisioningTemplateApplyingInformation(); if (MyInvocation.BoundParameters.ContainsKey("Handlers")) { applyingInformation.HandlersToProcess = Handlers; } if (MyInvocation.BoundParameters.ContainsKey("ExcludeHandlers")) { foreach (var handler in (Handlers[])Enum.GetValues(typeof(Handlers))) { if (!ExcludeHandlers.Has(handler) && handler != Handlers.All) { Handlers = Handlers | handler; } } applyingInformation.HandlersToProcess = Handlers; } if (ExtensibilityHandlers != null) { applyingInformation.ExtensibilityHandlers = ExtensibilityHandlers.ToList(); } applyingInformation.ProgressDelegate = (message, step, total) => { WriteProgress(new ProgressRecord(0, $"Applying template to {SelectedWeb.Url}", message) { PercentComplete = (100 / total) * step }); }; applyingInformation.MessagesDelegate = (message, type) => { if (type == ProvisioningMessageType.Warning) { WriteWarning(message); } }; applyingInformation.OverwriteSystemPropertyBagValues = OverwriteSystemPropertyBagValues; SelectedWeb.ApplyProvisioningTemplate(provisioningTemplate, applyingInformation); WriteProgress(new ProgressRecord(0, $"Applying template to {SelectedWeb.Url}", " ") { RecordType = ProgressRecordType.Completed }); }
public void Release( Handlers.Tasks.IJobTaskWorker worker ) { }
public void Release( Handlers.Tasks.IJobTaskRunner runner ) { }
/// <summary> /// /// </summary> /// <param name="a"></param> public virtual void InvokeEventFrameworkException(Handlers.EventHandlers.FrameworkExceptionEventArgs a) { Handlers.EventHandlers.FrameworkExceptionEventHandler handler = OnFrameworkException; if(handler != null) handler(this, a); }
private void topicDetailsHandler_Success(object sender, Handlers.TopicDetailsEventArgs e) { Log.Spew("Queried Topic: \"" + e.TopicPath + "\""); if (!rootTopicPath.Equals(e.TopicPath)) throw new InvalidOperationException("Topic details received for unexpected topic path."); if (null == e.TopicDetails) { // The root topic path does not yet exist so we need to create it implicitly // by creating the child nodes. Log.Spew("Creating topic tree..."); var addTopicHandler = new Handlers.AddTopicHandler(); addTopicHandler.Success += addTopicHandler_Success; AddTopic(addTopicHandler, steeringTopicPath); AddTopic(addTopicHandler, brakingTopicPath); AddTopic(addTopicHandler, accelerationTopicPath); AddTopic(addTopicHandler, gearTopicPath); AddTopic(addTopicHandler, refreshIntervalTopicPath, TopicType.RECORD); AddTopic(addTopicHandler, buttonStatesTopicPath, TopicType.RECORD); AddTopic(addTopicHandler, buttonNamesTopicPath, TopicType.RECORD); AddTopic(addTopicHandler, countOfUpdatesMetricTopicPath); AddTopic(addTopicHandler, upTimeInSecondsMetricTopicPath); AddTopic(addTopicHandler, countOfSuccessfulTopicSourceUpdatesMetricTopicPath); AddTopic(addTopicHandler, countOfFailedTopicSourceUpdatesMetricTopicPath); AddTopic(addTopicHandler, rateOfUpdatesPerSecondMetricTopicPath); AddTopic(addTopicHandler, rateOfSuccessfulTopicSourceUpdatesPerSecond); } else { // The root topic path exists so we need to start updating it. // (I am making the assumption that all of the topics I need to have added // below this root will be there... this could break if I add a new topic to the // tree in this codebase without restarting the Diffusion server or removing the // root topic first.) AddTopicSources(); } }
private void AddTopic(Handlers.AddTopicHandler handler, string path, TopicType topicType) { topicPathsPendingAddition.Add(path); topicControl.AddTopic(path, topicType, handler); }
/// <summary> /// /// </summary> /// <param name="a"></param> public virtual void InvokeEventProcessStarting(Handlers.EventHandlers.ProcessStartingEventArgs a) { Handlers.EventHandlers.ProcessStartingEventHandler handler = OnProcessStarting; if(handler != null) handler(this, a); }
/// <summary> /// /// </summary> /// <param name="a"></param> public virtual void InvokeEventProcessFinished(Handlers.EventHandlers.ProcessFinishedEventArgs a) { Handlers.EventHandlers.ProcessFinishedEventHandler handler = OnProcessFinished; if(handler != null) handler(this, a); }
public Property(Handlers h, string Name, string Category) { this.Name = Name; this.Category = Category; this.InternalHandlers = h; }
protected override void ExecuteCmdlet() { SelectedWeb.EnsureProperty(w => w.Url); bool templateFromFileSystem = !Path.ToLower().StartsWith("http"); FileConnectorBase fileConnector; string templateFileName = System.IO.Path.GetFileName(Path); if (templateFromFileSystem) { if (!System.IO.Path.IsPathRooted(Path)) { Path = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, Path); } if (!string.IsNullOrEmpty(ResourceFolder)) { if (!System.IO.Path.IsPathRooted(ResourceFolder)) { ResourceFolder = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, ResourceFolder); } } FileInfo fileInfo = new FileInfo(Path); fileConnector = new FileSystemConnector(fileInfo.DirectoryName, ""); } else { Uri fileUri = new Uri(Path); var webUrl = Microsoft.SharePoint.Client.Web.WebUrlFromFolderUrlDirect(this.ClientContext, fileUri); var templateContext = this.ClientContext.Clone(webUrl.ToString()); string library = Path.ToLower().Replace(templateContext.Url.ToLower(), "").TrimStart('/'); int idx = library.IndexOf("/"); library = library.Substring(0, idx); fileConnector = new SharePointConnector(templateContext, templateContext.Url, library); } XMLTemplateProvider provider = null; ProvisioningTemplate provisioningTemplate = null; Stream stream = fileConnector.GetFileStream(templateFileName); var isOpenOfficeFile = IsOpenOfficeFile(stream); if (isOpenOfficeFile) { provider = new XMLOpenXMLTemplateProvider(new OpenXMLConnector(templateFileName, fileConnector)); templateFileName = templateFileName.Substring(0, templateFileName.LastIndexOf(".")) + ".xml"; } else { if (templateFromFileSystem) { provider = new XMLFileSystemTemplateProvider(fileConnector.Parameters[FileConnectorBase.CONNECTIONSTRING] + "", ""); } else { throw new NotSupportedException("Only .pnp package files are supported from a SharePoint library"); } } provisioningTemplate = provider.GetTemplate(templateFileName, TemplateProviderExtensions); if (provisioningTemplate == null) return; if (isOpenOfficeFile) { provisioningTemplate.Connector = provider.Connector; } else { if (ResourceFolder != null) { var fileSystemConnector = new FileSystemConnector(ResourceFolder, ""); provisioningTemplate.Connector = fileSystemConnector; } else { provisioningTemplate.Connector = provider.Connector; } } if (Parameters != null) { foreach (var parameter in Parameters.Keys) { if (provisioningTemplate.Parameters.ContainsKey(parameter.ToString())) { provisioningTemplate.Parameters[parameter.ToString()] = Parameters[parameter].ToString(); } else { provisioningTemplate.Parameters.Add(parameter.ToString(), Parameters[parameter].ToString()); } } } var applyingInformation = new ProvisioningTemplateApplyingInformation(); if (this.MyInvocation.BoundParameters.ContainsKey("Handlers")) { applyingInformation.HandlersToProcess = Handlers; } if (this.MyInvocation.BoundParameters.ContainsKey("ExcludeHandlers")) { foreach (var handler in (OfficeDevPnP.Core.Framework.Provisioning.Model.Handlers[])Enum.GetValues(typeof(Handlers))) { if (!ExcludeHandlers.Has(handler) && handler != Handlers.All) { Handlers = Handlers | handler; } } applyingInformation.HandlersToProcess = Handlers; } if (ExtensibilityHandlers != null) { applyingInformation.ExtensibilityHandlers = ExtensibilityHandlers.ToList<ExtensibilityHandler>(); } applyingInformation.ProgressDelegate = (message, step, total) => { WriteProgress(new ProgressRecord(0, string.Format("Applying template to {0}", SelectedWeb.Url), message) { PercentComplete = (100 / total) * step }); }; applyingInformation.MessagesDelegate = (message, type) => { if (type == ProvisioningMessageType.Warning) { WriteWarning(message); } }; applyingInformation.OverwriteSystemPropertyBagValues = OverwriteSystemPropertyBagValues; SelectedWeb.ApplyProvisioningTemplate(provisioningTemplate, applyingInformation); }
public TestProvisioningTemplateResult TestProvisioningTemplate(ClientContext cc, string templateName, Handlers handlersToProcess = Handlers.All, ProvisioningTemplateApplyingInformation ptai = null, ProvisioningTemplateCreationInformation ptci = null) { try { // Read the template from XML and apply it XMLTemplateProvider provider = new XMLFileSystemTemplateProvider(string.Format(@"{0}\..\..\Framework\Functional", AppDomain.CurrentDomain.BaseDirectory), "Templates"); ProvisioningTemplate sourceTemplate = provider.GetTemplate(templateName); if (ptai == null) { ptai = new ProvisioningTemplateApplyingInformation(); ptai.HandlersToProcess = handlersToProcess; } if (ptai.ProgressDelegate == null) { ptai.ProgressDelegate = delegate (String message, Int32 progress, Int32 total) { Console.WriteLine("Applying template - {0}/{1} - {2}", progress, total, message); }; } sourceTemplate.Connector = provider.Connector; TokenParser sourceTokenParser = new TokenParser(cc.Web, sourceTemplate); cc.Web.ApplyProvisioningTemplate(sourceTemplate, ptai); // Read the site we applied the template to if (ptci == null) { ptci = new ProvisioningTemplateCreationInformation(cc.Web); ptci.HandlersToProcess = handlersToProcess; } if (ptci.ProgressDelegate == null) { ptci.ProgressDelegate = delegate (String message, Int32 progress, Int32 total) { Console.WriteLine("Getting template - {0}/{1} - {2}", progress, total, message); }; } ProvisioningTemplate targetTemplate = cc.Web.GetProvisioningTemplate(ptci); return new TestProvisioningTemplateResult() { SourceTemplate = sourceTemplate, SourceTokenParser = sourceTokenParser, TargetTemplate = targetTemplate, TargetTokenParser = new TokenParser(cc.Web, targetTemplate), }; } catch(Exception ex) { Console.WriteLine(ex.ToDetailedString()); throw; } }
private async Task HandleConnection(IHttpContext context) { string path = context.Request.Url.AbsolutePath; if (!path.StartsWith(prefix)) { throw new ApplicationException("path " + path + " should start with " + prefix); } string relativePath = path.Substring(prefix.Length); bool found = false; Handlers component = new Handlers { put=null, get=null }; foreach (var h in handlers) { if (relativePath.StartsWith(h.Key)) { found = true; component = h.Value; break; } } if (!found) { context.Response.StatusCode = (int)HttpStatusCode.BadRequest; context.Response.StatusDescription = "Unknown prefix"; await context.Response.CloseAsync(); return; } try { if (context.Request.HttpMethod.ToUpper() == "POST") { await component.put(context); } else { await component.get(context); } } catch (Exception e) { logger.Log("Got http exception " + e.ToString()); } }
/// <summary> /// /// </summary> /// <param name="a"></param> public virtual void InvokeEventAdExtracted(Handlers.EventHandlers.AdExtractedEventArgs a) { Handlers.EventHandlers.AdExtractedEventHandler handler = OnAdExtracted; if(handler != null) handler(this, a); }
private void addTopicHandler_Success(object sender, Handlers.TopicEventArgs e) { // At least one of our topics has been added. Log.Spew("Topic Added: \"" + e.TopicPath + "\""); while (topicPathsPendingAddition.Remove(e.TopicPath)); if (0 == topicPathsPendingAddition.Count) AddTopicSources(); }
public void ReleaseHandler(Handlers.IEventHandler handler) { }
/// <summary> /// /// </summary> /// <param name="a"></param> public virtual void InvokeEventUrlPointerProcessed(Handlers.EventHandlers.UrlPointerProcessedEventArgs a) { Handlers.EventHandlers.UrlPointerProcessedEventHandler handler = OnUrlPointerProcessed; if(handler != null) handler(this, a); }
/// <summary> /// /// </summary> /// <param name="a"></param> public virtual void InvokeEventSearchAnalysisStarting(Handlers.EventHandlers.SearchAnalysisStartingEventArgs a) { Handlers.EventHandlers.SearchAnalysisStartingEventHandler handler = OnSearchAnalysisStarting; if(handler != null) handler(this, a); }
/// <summary> /// /// </summary> /// <param name="a"></param> public virtual void InvokeEventSearchAnalysisFinished(Handlers.EventHandlers.SearchAnalysisFinishedEventArgs a) { Handlers.EventHandlers.SearchAnalysisFinishedEventHandler handler = OnSearchAnalysisFinished; if(handler != null) handler(this, a); }
private void AddTopic(Handlers.AddTopicHandler handler, string path) { AddTopic(handler, path, TopicType.SINGLE_VALUE); }
//主逻辑 public MainWindow() { InitializeComponent(); init(); DataFile TimeArg = new DataFile(); Args.longMilliseconds = TimeArg.RelaxSeconds * 1000; Args.shortMilliseconds = TimeArg.CorrectSeconds * 1000; var w = (MainWindow)Window.GetWindow(this); Events myDetection = new Events(w); Handlers myHandlers = new Handlers(w); myDetection.TimeToDetect += new Detection(myHandlers.EyeDetect); myDetection.TimeToDetect += new Detection(myHandlers.RunTime); myDetection.TimeToAnalyse += new AnalyseArg(myHandlers.PreAnalyse); myDetection.TimeToAnalyse += new AnalyseArg(myHandlers.Analyse); myDetection.LongTimeDetected += new Correction(myHandlers.DisplayMessage); myDetection.ShortTimeDetected += new Correction(myHandlers.DisplayMessage); myDetection.Detect(); }