### Install Windows Service Example Source: https://github.com/simplifynet/simplify/wiki/Simplify.WindowsServices A command-line example demonstrating how to install a Windows service. This assumes the service executable is named 'MyService.exe' and the 'install' parameter is used. This process typically registers the application as a service with the operating system. ```text MyService.exe install ``` -------------------------------- ### BasicScheduler Setup (C#) Source: https://github.com/simplifynet/simplify/wiki/Simplify.Scheduler Illustrates the basic setup and usage of the BasicScheduler to run a defined task. It requires registering the task class in the DI container and then initializing and starting the scheduler. The task class must have a `Run` method. ```csharp public class MyClass { public void Run() { // Some task } } ``` ```csharp static void Main(string[] args) { DIContainer.Current.Register(); using(var scheduler = new BasicScheduler) scheduler.Start(args); } ``` -------------------------------- ### Install Simplify.ProjectsTemplates Source: https://github.com/simplifynet/simplify/wiki/Simplify.Scheduler Installs the Simplify.ProjectsTemplates package globally, which contains templates for creating Simplify.Scheduler-based projects. ```console dotnet new -i Simplify.ProjectsTemplates ``` -------------------------------- ### Install Simplify.WindowsServices Templates Source: https://github.com/simplifynet/simplify/wiki/Simplify.WindowsServices Installs the Simplify.WindowsServices templates package globally, enabling the creation of new projects based on these templates. ```console dotnet new -i Simplify.WindowsServices.Templates ``` -------------------------------- ### Default ServiceInstallerBase Usage Source: https://github.com/simplifynet/simplify/wiki/Simplify.WindowsServices A C# example showing the default usage of the ServiceInstallerBase class for creating a Windows service installer. By decorating a class with `[RunInstaller(true)]` and inheriting from `ServiceInstallerBase`, the service can be installed using assembly information for its title and description. ```csharp [RunInstaller(true)] public class ServiceInstaller : ServiceInstallerBase { } ``` -------------------------------- ### Example appsettings.json for Job Settings Source: https://github.com/simplifynet/simplify/wiki/Simplify.Scheduler An example JSON configuration file illustrating how to set job-specific settings for Simplify.Scheduler. This includes defining a crontab expression and a processing interval. ```json { "JobSettings": { "CrontabExpression": "* * * * *", "ProcessingInterval": 30 } } ``` -------------------------------- ### BasicServiceHandler C# Example Source: https://github.com/simplifynet/simplify/wiki/Simplify.WindowsServices Demonstrates the usage of BasicServiceHandler for creating a Windows service. The service's entry point is defined in the MyClass.Run() method. ```csharp public class MyClass { public void Run() { // Some task } } ``` ```csharp static void Main(string[] args) { new BasicServiceHandler(true).Start(args); } ``` ```csharp static void Main(string[] args) { DIContainer.Current.Register(); new BasicServiceHandler().Start(args); } ``` -------------------------------- ### Configuration File Example for Database Settings (XML) Source: https://github.com/simplifynet/simplify/wiki/Simplify.FluentNHibernate An example XML configuration file snippet defining a section for database connection settings. This format is used by FluentNHibernate's `InitializeFromConfigMsSql` when not using Microsoft.Extensions.Configuration. ```xml
``` -------------------------------- ### appsettings.json Example for Database Connection Settings Source: https://github.com/simplifynet/simplify/wiki/Simplify.FluentNHibernate An example JSON structure for appsettings.json, defining the connection details for a database, including server name, database name, username, and password. This is used by the `InitializeFromConfigMsSql` extension. ```json { "MyDatabaseConnectionSettings": { "ServerName": "Server name", "DataBaseName": "database name", "UserName": "user name", "UserPassword": "password" } } ``` -------------------------------- ### Configure and Start SingleTaskScheduler (C#) Source: https://github.com/simplifynet/simplify/wiki/Simplify.Scheduler Demonstrates how to configure and start a SingleTaskScheduler in C#. It reads configuration from an appsettings.json file and initializes the scheduler with a specific class (MyClass) and the configuration. ```csharp var configuration = new ConfigurationBuilder() .AddJsonFile("appsettings.json", false) .Build(); using(var handler = new SingleTaskScheduler(configuration)) handler.Start(); ``` -------------------------------- ### Create Simplify.WindowsServices Project Source: https://github.com/simplifynet/simplify/wiki/Simplify.WindowsServices Creates a new project using the simplify.windowsservice template. This is a quick way to start a new Windows service project. ```console dotnet new simplify.windowsservice -n HelloWorld ``` -------------------------------- ### Simplify.DI with Service Exception Handling Source: https://github.com/simplifynet/simplify/wiki/Simplify.WindowsServices Illustrates how to use Simplify.DI for dependency injection in conjunction with Simplify.WindowsService's exception handling. It demonstrates registering dependencies and starting a service handler. ```csharp public interface IMyClass2 { SomeMethod(); } public class MyClass2 : IMyClass2 { public SomeMethod() { } } public class MyClass { private IMyClass2 _myclass2; public MyClass(IMyClass2 myclass2) { _myclass2 = myclass2; } public void Run() { _myclass2.SomeMethod(); } } ``` ```csharp static void Main(string[] args) { DIContainer.Current.Register(); DIContainer.Current.Register(); new SingleTaskServiceHandler().Start(args); } ``` -------------------------------- ### Create Simplify.Scheduler Project Source: https://github.com/simplifynet/simplify/wiki/Simplify.Scheduler Creates a new Simplify.Scheduler project with the specified name using the installed simplify.scheduler template. ```console dotnet new simplify.scheduler -n HelloWorld ``` -------------------------------- ### MultitaskScheduler Configuration and Job Addition (C#) Source: https://github.com/simplifynet/simplify/wiki/Simplify.Scheduler Provides an example of configuring and using the MultitaskScheduler to manage multiple tasks. It involves registering task processors in the IOC container, adding jobs with optional configuration section and method names, and starting the scheduler. Task classes can have multiple methods to be invoked. ```csharp public class TaskProcessor1 { public void Run() { Debug.WriteLine("TaskProcessor1 Run executed"); } public void RunTask2() { Debug.WriteLine("TaskProcessor1 RunTask2 executed"); } } ``` ```csharp public class TaskProcessor2 { public void Run() { Debug.WriteLine("TaskProcessor2 Run executed"); } } ``` ```csharp static void Main(string[] args) { // Registering in IOC container DIContainer.Current.Register(); DIContainer.Current.Register(); // Handler creation using(var handler = new MultitaskScheduler()) { // Jobs addition // If configuration section is not specified then 'YourClassName + Settings' section name will be used handler.AddJob(); // Manually specified section name and invoke method name handler.AddJob("TaskProcessor1SecondTaskSettings", "RunTask2"); handler.AddJob(); handler.Start(args); } } ``` -------------------------------- ### Custom Logger Initialization with Settings Source: https://github.com/simplifynet/simplify/wiki/Simplify.Log Shows how to instantiate the Logger class using a custom settings section defined in the App.config file. This allows for more flexible logger setup. ```csharp var logger = new Logger("MyLoggerSettings"); ``` ```xml
``` -------------------------------- ### SingleTaskServiceHandler C# Example Source: https://github.com/simplifynet/simplify/wiki/Simplify.WindowsServices Illustrates the implementation of a Windows service using SingleTaskServiceHandler. The Run method contains the task to be executed periodically. ```csharp public class MyClass { public void Run() { // Some task } } ``` ```csharp static void Main(string[] args) { new SingleTaskServiceHandler(true).Start(args); } ``` -------------------------------- ### Uninstall Windows Service Example Source: https://github.com/simplifynet/simplify/wiki/Simplify.WindowsServices A command-line example for uninstalling a Windows service. It uses the service executable name 'MyService.exe' with the 'uninstall' parameter. This action removes the service registration from the operating system. ```text MyService.exe uninstall ``` -------------------------------- ### Configure and Start MultitaskServiceHandler Source: https://github.com/simplifynet/simplify/wiki/Simplify.WindowsServices This C# snippet demonstrates how to instantiate and configure the MultitaskServiceHandler to manage multiple task processors. It shows adding jobs with default or custom configuration sections and method names, and starting the service handler. Dependencies include the MultitaskServiceHandler class and potentially a DIContainer. ```csharp static void Main(string[] args) { // Handler creation var handler = new MultitaskServiceHandler(); // Jobs addition // If configuration section is not specified, then 'YourClassName + Settings' section name will be used handler.AddJob(true); // Manually specified section name and invoke method name handler.AddJob("TaskProcessor1SecondTaskSettings", "RunTask2"); // Registering class manually DIContainer.Current.Register(); handler.AddJob(); handler.Start(args); } ``` -------------------------------- ### Template File Example - HTML Source: https://github.com/simplifynet/simplify/wiki/Simplify.Templates This is a simple template file that uses placeholder syntax `{PropName}` to represent properties from a model. It serves as the structure for rendering dynamic content. ```html {Prop1} {Prop2} {Prop3} ``` -------------------------------- ### SingleTaskScheduler Usage (C#) Source: https://github.com/simplifynet/simplify/wiki/Simplify.Scheduler Shows how to instantiate and start a SingleTaskScheduler. Similar to BasicScheduler, it requires registering the task class in the DI container before starting the scheduler. It's designed for scenarios where only one task needs to be managed. ```csharp static void Main(string[] args) { DIContainer.Current.Register(); using(var scheduler = new SingleTaskScheduler) scheduler.Start(args); } ``` -------------------------------- ### Register Dependencies with Simplify.DI in Global.asax.cs Source: https://github.com/simplifynet/simplify/wiki/Simplify.DI.Wcf This snippet demonstrates how to register dependencies using Simplify.DI within the Application_Start method in the Global.asax.cs file. This ensures that your IOC container is set up before the WCF application starts processing requests. ```csharp using System; using Simplify.DI; namespace MyService { public class Global : System.Web.HttpApplication { protected void Application_Start(object sender, EventArgs e) { DIContainer.Current.Register(); } } } ``` -------------------------------- ### TaskProcessor1 Class Example Source: https://github.com/simplifynet/simplify/wiki/Simplify.WindowsServices A C# example of a task processor class, TaskProcessor1, designed to be used with MultitaskServiceHandler. It includes two methods, 'Run' and 'RunTask2', which can be invoked by the service handler based on configuration. This class has no external dependencies beyond standard .NET libraries. ```csharp public class TaskProcessor1 { public void Run() { Debug.WriteLine("TaskProcessor1 Run executed"); } public void RunTask2() { Debug.WriteLine("TaskProcessor1 RunTask2 executed"); } } ``` -------------------------------- ### SingleTaskServiceHandler Configuration Example Source: https://github.com/simplifynet/simplify/wiki/Simplify.WindowsServices Shows how to configure the SingleTaskServiceHandler using App.config. It allows specifying a crontab expression or a processing interval for timer-based execution. ```xml
``` -------------------------------- ### Resolve Dependencies with DIContainer (C#) Source: https://github.com/simplifynet/simplify/wiki/Simplify.DI Shows how to retrieve an instance of a registered dependency using `DIContainer.Current.Resolve()`. This example demonstrates resolving an instance of `IBar`. ```csharp var myObj = DIContainer.Current.Resolve(); ``` -------------------------------- ### Retrieve Single Object and Filter List with SimplifyNet C# Source: https://github.com/simplifynet/simplify/wiki/Simplify.FluentNHibernate Demonstrates how to retrieve a single user object based on a name match and how to get a list of users whose names start with a specific prefix using the SimplifyNet session's GetSingleObject and GetList methods. This functionality is useful for data retrieval and filtering within applications using SimplifyNet. ```csharp var user = session.GetSingleObject(x => x.Name == "FooName"); var users = session.GetList(x => x.Name.StartsWith("A")); ``` -------------------------------- ### Configure Mail Sender with All Options in App.config Source: https://github.com/simplifynet/simplify/wiki/Simplify.Mail This XML configuration demonstrates all available settings for the MailSender, including server details, port, SSL, and anti-spam filter options. It provides a comprehensive setup for email sending. ```xml
``` -------------------------------- ### Configure Service System Account Source: https://github.com/simplifynet/simplify/wiki/Simplify.WindowsServices An XML configuration example for specifying the system account under which a Windows service will run. This allows selecting accounts like 'LocalService', 'NetworkService', or 'LocalSystem'. This setting is part of the 'ServiceInstallerSettings' and is overridden if 'RunAsUserName' and 'RunAsUserPassword' are also specified. ```xml ``` -------------------------------- ### MultitaskScheduler Configuration (JSON) Source: https://github.com/simplifynet/simplify/wiki/Simplify.Scheduler An example of an appsettings.json file used to configure the MultitaskScheduler. It specifies cron tab expressions and processing intervals for different tasks, allowing for flexible scheduling and execution parameters. ```json { "TaskProcessor1Settings": { "CrontabExpression": "*/2 * * * *" }, "TaskProcessor1SecondTaskSettings": { "ProcessingInterval": 30 }, "TaskProcessor2Settings": { "ProcessingInterval": 45 } } ``` -------------------------------- ### TaskProcessor2 Class Example Source: https://github.com/simplifynet/simplify/wiki/Simplify.WindowsServices A simple C# task processor class, TaskProcessor2, intended for use with MultitaskServiceHandler. It contains a single 'Run' method. This class relies on standard .NET functionalities. ```csharp public class TaskProcessor2 { public void Run() { Debug.WriteLine("TaskProcessor2 Run executed"); } } ``` -------------------------------- ### Custom ResourcesStringTable with Specific Assembly (C#) Source: https://github.com/simplifynet/simplify/wiki/Simplify.Resources This example shows how to instantiate a custom `ResourcesStringTable` to retrieve resources from a specific assembly. You can specify the assembly and the base name of the resource file. This is useful when the assembly containing the resources differs from the one where the code is executed. ```csharp var rst = new ResourcesStringTable(Assembly.GetAssembly(typeof(MyType)), "ProgramResources"); var str = rst["FooString"]; ``` -------------------------------- ### Rendered Output Example - HTML Source: https://github.com/simplifynet/simplify/wiki/Simplify.Templates The resulting HTML string after binding the `MyClass` model to the `MyTemplate.tpl` and applying custom formatting. It shows the placeholder values replaced with the model's data, including the formatted date. ```html Foo 5 13.09.2014 ``` -------------------------------- ### Get Generated Template String Source: https://github.com/simplifynet/simplify/wiki/Simplify.Templates Shows the process of retrieving the final, processed string from a template after data has been set. This is the output stage of template generation. ```csharp var str = tpl.Get(); ``` -------------------------------- ### App.config for MultitaskServiceHandler Source: https://github.com/simplifynet/simplify/wiki/Simplify.WindowsServices An XML configuration file example for setting up task intervals and cron expressions for MultitaskServiceHandler. It defines configuration sections for different task processors, specifying 'CrontabExpression' or 'ProcessingInterval' for each. This configuration is parsed by the service to manage task scheduling. ```xml
``` -------------------------------- ### Send Email with Anti-Spam Body Exclusion Source: https://github.com/simplifynet/simplify/wiki/Simplify.Mail This example shows how to send an email while specifying a separate body for anti-spam filtering. This is useful for excluding dynamic content like timestamps from the anti-spam check. ```csharp var message = "Some problem occurred at: "; MailSender.Default.Send("mymail@somedomain.com", "mailrecipient@somedomain.com", "Some problem occurred at: ", message + DateTime.Now, message); ``` -------------------------------- ### Get Outer XML String of XElement (C#) Source: https://github.com/simplifynet/simplify/wiki/Simplify.Xml Retrieves the outer XML string representation of an XElement, including its inner XML content and the element itself. This is a common extension method for XML processing. ```csharp public static string OuterXml(this XElement element); ``` -------------------------------- ### Use Lifetime Scope for Resolving Dependencies (C#) Source: https://github.com/simplifynet/simplify/wiki/Simplify.DI Shows how to create and use a lifetime scope for resolving dependencies. The `DIContainer.Current.BeginLifetimeScope()` method creates a scope, and `scope.Resolver.Resolve()` is used to get instances within that scope. This is particularly useful for managing short-lived objects. ```csharp // Note, what scope.Container actually it is the same container as DIContainer.Current, for example, if using SimpleInjector, but with DryIoc it will be child container. using (var scope = DIContainer.Current.BeginLifetimeScope()) { var myObject = scope.Resolver.Resolve(); } ``` -------------------------------- ### Get Inner XML String of XElement (C#) Source: https://github.com/simplifynet/simplify/wiki/Simplify.Xml Retrieves the inner XML string content of an XElement, excluding the element's tags. This extension method is useful for extracting specific XML content. ```csharp public static string InnerXml(this XElement element); ``` -------------------------------- ### Standard Registrations and Verification with Simple Injector Source: https://github.com/simplifynet/simplify/wiki/Simplify.DI Shows standard dependency registration using Simple Injector within Simplify.DI and verifies the container's configuration. This is useful for ensuring all dependencies are correctly set up before application startup. ```csharp var provider = new SimpleInjectorDIProvider(); DIContainer.Current = provider; ... DIContainer.Current.Register(); ... provider.Container.Verify(); ``` -------------------------------- ### Configure Simplify.WindowsServices with IConfiguration and JSON Source: https://github.com/simplifynet/simplify/wiki/Simplify.WindowsServices Demonstrates how to integrate Simplify.WindowsServices with Microsoft.Extensions.Configuration by building an IConfiguration object from an appsettings.json file. This allows for modern configuration management. ```csharp var configuration = new ConfigurationBuilder() .AddJsonFile("appsettings.json", false) .Build(); var handler = new SingleTaskServiceHandler(configuration); ``` ```json { "ServiceSettings": { "CrontabExpression": "* * * * *" } } ``` -------------------------------- ### Load Template from Local File and Build Source: https://github.com/simplifynet/simplify/wiki/Simplify.Templates Demonstrates loading a template from a local file using TemplateBuilder and then building the template object. This is a basic usage pattern for initializing a template. ```csharp var tpl = TemplateBuilder .FromLocalFile("TestTemplate.tpl") .Build(); ``` -------------------------------- ### Create Simplify.WindowsServices Project with Database Source: https://github.com/simplifynet/simplify/wiki/Simplify.WindowsServices Creates a new project using the simplify.windowsservicewithdatabase template. This template is pre-configured for Windows services that interact with a database. ```console dotnet new simplify.windowsservicewithdatabase -n HelloWorld ``` -------------------------------- ### Initialize MailSender with IMailSenderSettings Implementation Source: https://github.com/simplifynet/simplify/wiki/Simplify.Mail Enables dependency injection by allowing MailSender to be instantiated with any class that implements the IMailSenderSettings interface. ```csharp MailSender(IMailSenderSettings mailSenderSettings) ``` -------------------------------- ### Register Dependencies with DIContainer (C#) Source: https://github.com/simplifynet/simplify/wiki/Simplify.DI Demonstrates various ways to register dependencies using Simplify.DI's `DIContainer.Current`. This includes simple type-to-type registration, registration using a delegate for custom instantiation, and registration with delegate that resolves other dependencies and accepts parameters. ```csharp // Simple registration DIContainer.Current.Register() .Register(); // Registration with delegate DIContainer.Current.Register(p => new Bar2("test")); // Registration with delegate and type resolve DIContainer.Current.Register(p => new Foo2(p.Resolve(), "test")); ``` -------------------------------- ### Initialize MailSender with Custom Parameters Source: https://github.com/simplifynet/simplify/wiki/Simplify.Mail Provides a way to manually configure MailSender by passing individual parameters like server address, port, credentials, and SSL settings. ```csharp MailSender(string smtpServerAddress, int smtpServerPortNumber, string smtpUserName, string smtpUserPassword, bool enableSsl = false, bool antiSpamMessagesPoolOn = true, int antiSpamPoolMessageLifeTime = 120) ``` -------------------------------- ### Configure Service Settings via XML Source: https://github.com/simplifynet/simplify/wiki/Simplify.WindowsServices This XML configuration snippet shows how to define settings for a service, such as cleanup behavior and maximum parallel tasks. It uses the .NET Framework's configuration system. ```xml
``` -------------------------------- ### Template Loading Options with TemplateBuilder Source: https://github.com/simplifynet/simplify/wiki/Simplify.Templates Presents various static methods of TemplateBuilder for loading templates from different sources like strings, files, embedded resources, and specific assemblies. This highlights the flexibility in template sourcing. ```csharp // Loading template from a string: // TemplateBuilder.FromString("some string") // Loading template from a file: // TemplateBuilder.FromFile("D:\\SomeDir\\SomeFile.txt") // Loading template from a file located in the current assembly directory: // TemplateBuilder.FromLocalFile("SomeFile.txt") // Loading template from current assembly embedded resources: // TemplateBuilder.FromCurrentAssembly("FilePath.Filename.tpl") or TemplateBuilder.FromCurrentAssembly("FilePath/Filename.tpl") // Loading template from specified assembly embedded resources: // TemplateBuilder.FromAssembly("FilePath.Filename.tpl", myAssembly) ``` -------------------------------- ### Fluent Interface for DryIoc Registrations and Usage Source: https://github.com/simplifynet/simplify/wiki/Simplify.DI Illustrates the use of fluent interfaces for registering services with DryIoc and managing their lifetimes. It shows how to group registrations and resolve services within a lifetime scope. ```csharp public static class Program { public static void Main(string[] args) { var provider = new DryIocDIProvider(); provider.RegisterAll() .Verify(); using var scope = provider.BeginLifetimeScope(); scope.Resolver.Resolve().DoWork(); } private static IDIContainerProvider RegisterAll(this IDIContainerProvider provider) { provider.RegisterServicesGroup1() .RegisterServicesGroup2(); return provider; } private static IDIRegistrator RegisterServicesGroup1(this IDIRegistrator registrator) => registrator .Register() .Register(r => new MyService2("string parameter example")) .Register(r => new MyService3(r.Resolve())); private static IDIRegistrator RegisterServicesGroup2(this IDIRegistrator registrator) => registrator .Register(LifetimeType.Singleton) .Register() .Register(); } ``` -------------------------------- ### Register with PerLifetimeScope Lifetime (C#) Source: https://github.com/simplifynet/simplify/wiki/Simplify.DI Demonstrates registering dependencies with the `PerLifetimeScope` lifetime. This ensures that a single instance is created within a specific scope. It covers both simple type registration and registration using a delegate. ```csharp // Simple registration DIContainer.Current.Register(LifetimeType.PerLifetimeScope); // Any dependency while registration with delegate should be resolved with delegate parameter `p`, it is current scope resolve provider. DIContainer.Current.Register(p => new Foo2(p.Resolve(), "Test"), LifetimeType.PerLifetimeScope); ``` -------------------------------- ### Registering Types Directly with Simple Injector Source: https://github.com/simplifynet/simplify/wiki/Simplify.DI Demonstrates how to directly register singleton types with a Simple Injector container managed by Simplify.DI. It involves creating a DIProvider and setting it as the current container. ```csharp var provider = new SimpleInjectorDIProvider(); DIContainer.Current = provider; provider.Container.RegisterSingleton(); ... ``` -------------------------------- ### Model Binding and Rendering - C# Source: https://github.com/simplifynet/simplify/wiki/Simplify.Templates Demonstrates setting a model object to a template and rendering the output with custom property formatting. It uses `TemplateBuilder` to load and build the template, `.Model()` to bind the data, `.With()` to specify custom formatting for `Prop3` (converting DateTime to 'dd.MM.yyyy'), and `.Get()` to retrieve the rendered string. Dependencies include the SimplifyNet library. ```csharp var obj = new MyClass {Prop1 = "Foo", Prop2 = 5, Prop3 = new DateTime(2014, 09, 13)}; var tpl = TemplateBuilder .FromFile("MyTemplate.tpl") .Build(); tpl.Model(obj).With(x => x.Prop3, x => x.ToString("dd.MM.yyyy")).Set(); var str = tpl.Get(); ``` -------------------------------- ### Initialize MailSender with IConfiguration Source: https://github.com/simplifynet/simplify/wiki/Simplify.Mail Allows MailSender to be initialized using Microsoft.Extensions.Configuration, typically from an `appsettings.json` file. Supports specifying a custom configuration section name. ```csharp public MailSender(IConfiguration configuration, string configurationSectionName = "MailSenderSettings") ``` -------------------------------- ### Define Entities for Dependency Injection (C#) Source: https://github.com/simplifynet/simplify/wiki/Simplify.DI Defines interfaces and classes used for demonstrating dependency injection. This includes interfaces like `IFoo` and `IBar`, and their concrete implementations `Foo`, `Foo2`, `Bar`, and `Bar2`. Some implementations accept constructor parameters, showcasing constructor injection. ```csharp public interface IFoo { } public class Foo : IFoo { public Foo(IBar bar) { } } public class Foo2 : IFoo { public Foo2(IBar bar, string someParameter) { } } public interface IBar { } public class Bar : IBar { } public class Bar2 : IBar { public Bar2(string someParameter) { } } ``` -------------------------------- ### WCF Service Implementation with Dependency Injection Source: https://github.com/simplifynet/simplify/wiki/Simplify.DI.Wcf Implements a WCF service that utilizes dependency injection via Simplify.DI. The constructor accepts an instance of ISomeInterface, which is expected to be provided by the DI container. ```csharp using System; namespace MyService { public class Service : IService { public Service(ISomeInterface dependency) { } public void MyMethod() { } } } ``` -------------------------------- ### Verify Container Registrations (C#) Source: https://github.com/simplifynet/simplify/wiki/Simplify.DI Illustrates how to perform a container verification using `DIContainer.Current.Verify()`. This process checks the integrity of the registered object graph, ensuring all dependencies are met and there are no lifetime mismatches. An exception is thrown if any issues are found. ```csharp DIContainer.Current.Verify(); ``` -------------------------------- ### Configure WCF Service Host Factory with Simplify.DI.Wcf Source: https://github.com/simplifynet/simplify/wiki/Simplify.DI.Wcf This snippet shows how to configure the WCF service host factory in a .svc file to use Simplify.DI.Wcf for dependency injection. Ensure Simplify.DI.Wcf is referenced in your project. ```aspx-cs <%@ ServiceHost Language="C#" Debug="true" Service="MyNamespace.Service" CodeBehind="Service.svc.cs" Factory="Simplify.DI.Wcf.SimplifyServiceHostFactory" %> ``` -------------------------------- ### Advanced Logger Configuration Options Source: https://github.com/simplifynet/simplify/wiki/Simplify.Log Illustrates advanced logger settings that can be configured within the App.config file, including file path types, maximum file size, and trace output. These options provide granular control over logging behavior. ```xml ``` -------------------------------- ### Configure Mail Sender with appsettings.json Source: https://github.com/simplifynet/simplify/wiki/Simplify.Mail This JSON configuration defines the settings for the MailSender, intended for use with `Microsoft.Extensions.Configuration`. It specifies the SMTP server, username, and password within a dedicated section. ```json { "MailSenderSettings": { "SmtpServerAddress": "server name or IP address", "SmtpUserName": "user name", "SmtpUserPassword": "password" } } ``` -------------------------------- ### Global Exception Handling with Simplify.Scheduler (C#) Source: https://github.com/simplifynet/simplify/wiki/Simplify.Scheduler Demonstrates how to subscribe to the OnException event of Simplify.Scheduler to catch all exceptions thrown by user code. This allows for centralized error logging and handling. It requires subscribing to the handler's OnException event. ```csharp static void Main(string[] args) { ... handler.OnException += OnException; ... } static void OnException(ServiceExceptionArgs args) { Console.Write(args.ServiceName); Console.Write(args.Exception.Message); } ``` -------------------------------- ### Configure NHibernate Session Factory with Microsoft.Extensions.Configuration (C#) Source: https://github.com/simplifynet/simplify/wiki/Simplify.FluentNHibernate Sets up an NHibernate ISessionFactory using FluentNHibernate, initializing configuration from Microsoft.Extensions.Configuration. It expects a configuration section in appsettings.json and maps entities from the assembly of the calling class. ```csharp namespace MyApp.Database { public class MyDbSessionFactoryBuilder { private readonly ISessionFactory _instance; public ISessionFactory Instance => _instance; public MyDbSessionFactoryBuilder(IConfiguration cfg, string configSectionName = "MyDatabaseConnectionSettings") { var configuration = Fluently.Configure(); configuration.InitializeFromConfigMsSql(cfg, configSectionName); configuration.AddMappingsFromAssemblyOf(); _instance = configuration.BuildSessionFactory(); } } } ``` -------------------------------- ### Configure Services with Simplify.DI Provider in Startup.cs Source: https://github.com/simplifynet/simplify/wiki/Simplify.DI.Microsoft.AspNetCore This code snippet demonstrates how to initialize Simplify.DI's MicrosoftDependencyInjectionDIProvider within the ConfigureServices method of an ASP.NET Core application's Startup.cs. It replaces the default container, enabling registrations via both IServiceCollection and DIContainer.Current. The method returns the IServiceProvider, which is essential for the ASP.NET Core application's runtime. ```csharp public IServiceProvider ConfigureServices(IServiceCollection services) { var provider = new MicrosoftDependencyInjectionDIProvider { Services = services }; DIContainer.Current = provider; // Your registrations here (both via services or DIContainer.Current.Register) return provider.ServiceProvider; } ``` ```csharp public void ConfigureServices(IServiceCollection services) { DIContainer.Current = new MicrosoftDependencyInjectionDIProvider { Services = services }; // Your registrations here (both via services or DIContainer.Current.Register) } ``` -------------------------------- ### Configure NHibernate Session Factory with .config Files (C#) Source: https://github.com/simplifynet/simplify/wiki/Simplify.FluentNHibernate Sets up an NHibernate ISessionFactory using FluentNHibernate, initializing configuration from a traditional .config file. It looks for a specified configuration section and maps entities from the assembly of the calling class. ```csharp namespace MyApp.Database { public class MyDbSessionFactoryBuilder { private readonly ISessionFactory _instance; public ISessionFactory Instance => _instance; public MyDbSessionFactoryBuilder(string configSectionName = "MyDatabaseConnectionSettings") { var configuration = Fluently.Configure(); configuration.InitializeFromConfigMsSql(configSectionName); configuration.AddMappingsFromAssemblyOf(); _instance = configuration.BuildSessionFactory(); } } } ``` -------------------------------- ### Apply Localization to Template Source: https://github.com/simplifynet/simplify/wiki/Simplify.Templates Demonstrates how to make templates localizable by specifying language codes during the build process. This enables dynamic translation of template content based on specified languages. ```csharp var tpl = TemplateBuilder .FromLocalFile("FooTemplate.tpl") .Localizable("de", "en") .Build(); var str = tpl.Get(); ``` -------------------------------- ### Initialize MailSender with Configuration Section Name Source: https://github.com/simplifynet/simplify/wiki/Simplify.Mail Allows custom initialization of MailSender by specifying a different configuration section name in the config file. Defaults to 'MailSenderSettings'. ```csharp MailSender(string configurationSectionName = "MailSenderSettings") ``` -------------------------------- ### Configure Service RunAs User Source: https://github.com/simplifynet/simplify/wiki/Simplify.WindowsServices An XML configuration snippet demonstrating how to specify the 'RunAs' user credentials for a Windows service. This section within the configuration file allows setting a specific username and password for the service's execution context. The 'ServiceInstallerSettings' section is used for this purpose. ```xml
``` -------------------------------- ### Send Simple Email Source: https://github.com/simplifynet/simplify/wiki/Simplify.Mail Demonstrates the basic usage of sending an email using the default MailSender instance. This method sends an email with specified sender, recipient, subject, and body. ```csharp MailSender.Default.Send("mymail@somedomain.com", "mailrecipient@somedomain.com", "Mail subject!", "Mail message, can be a full HTML page"); ``` -------------------------------- ### Configure Mail Sender with App.config Source: https://github.com/simplifynet/simplify/wiki/Simplify.Mail This configuration defines the necessary settings for the MailSender to connect to an SMTP server. It requires the server address, username, and password. ```xml
``` -------------------------------- ### Catch Global Exceptions in Simplify.WindowsService Source: https://github.com/simplifynet/simplify/wiki/Simplify.WindowsServices Shows how to implement global exception catching within Simplify.WindowsService by subscribing to the OnException event of the service handler. This enables centralized error logging and handling. ```csharp static void Main(string[] args) { var handler = new SingleTaskServiceHandler(); handler.OnException += OnException; hander.Start(args); } static void OnException(ServiceExceptionArgs args) { Console.Write(args.ServiceName); Console.Write(args.Exception.Message); } ``` -------------------------------- ### Custom NHibernate Dialect Configuration (C#) Source: https://github.com/simplifynet/simplify/wiki/Simplify.FluentNHibernate Demonstrates how to apply custom NHibernate configuration options, such as specifying a specific dialect, using a lambda expression within the FluentNHibernate configuration fluent interface. ```csharp configuration.InitializeFromConfigMsSql(configSectionName, c => c.Dialect()); ``` -------------------------------- ### Log Simple String Message - C# Source: https://github.com/simplifynet/simplify/wiki/Simplify.Log Demonstrates how to write a simple string message to the log using the default logger instance. This is a basic logging operation for informational messages. ```csharp Logger.Default.Write("Hello world!!!"); ``` -------------------------------- ### Build Master Template with Item List Source: https://github.com/simplifynet/simplify/wiki/Simplify.Templates Shows how to construct a master template by iteratively adding generated content from child templates. This pattern is useful for building dynamic lists or repeating sections within a larger template. ```csharp class MyItem { public int ID { get; set; } } ... var items = new List { new MyItem {ID = 1}, new MyItem {ID = 2}, new MyItem {ID = 3} }; var tpl = TemplateBuilder .FromFile("Templates/MasterTemplate.tpl") .Build(); var itemTpl = TemplateBuilder .FromFile("Templates/FooLinkItem.tpl") .Build(); foreach (var item in items) { itemTpl.Set("ItemID", item.ID); // Adding our generated item data to the master template and rolling it back to initial, but localized state tpl.Add("Links", itemTpl.GetAndRoll()); } var str = tpl.Get(); ``` -------------------------------- ### Log Exception Message - C# Source: https://github.com/simplifynet/simplify/wiki/Simplify.Log Shows how to log an exception object to the log file. This captures the exception details, including the stack trace and any inner exceptions, for debugging purposes. ```csharp try { ... } catch (Exception e) { Logger.Default.Write(e); } ``` -------------------------------- ### Custom ResourcesStringTable with Namespace Override (C#) Source: https://github.com/simplifynet/simplify/wiki/Simplify.Resources This snippet illustrates creating a `ResourcesStringTable` instance while explicitly defining the default namespace. This is necessary when the assembly's default namespace does not match the assembly name, ensuring correct resource resolution. ```csharp var rst = new ResourcesStringTable(Assembly.GetAssembly(typeof(MyType)), "ProgramResources", "YourDefaultNamespace"); var str = rst["FooString"]; ``` -------------------------------- ### Set and Add Data to Template Variables Source: https://github.com/simplifynet/simplify/wiki/Simplify.Templates Illustrates how to set individual variables and add multiple values to list-type variables within a template. This is crucial for populating templates with dynamic data. ```csharp tpl.Set("SomeVariable", "footext"); tpl.Add("Items", "1") .Add("Items", "2") .Add("Items", "3"); ``` -------------------------------- ### Retrieve String from Executing Assembly (C#) Source: https://github.com/simplifynet/simplify/wiki/Simplify.Resources This snippet demonstrates how to retrieve a string from the executing assembly's resource file. The resource file should be named `ProgramResources.resx` and embedded as a resource. The default namespace of the assembly should align with the assembly name for this to work correctly. ```csharp var str = StringTable.Entry["FooString"]; ``` -------------------------------- ### App.config Logger Configuration Source: https://github.com/simplifynet/simplify/wiki/Simplify.Log Defines the basic logger section in the App.config file, specifying a default log file name. This configuration is essential for the logger functionality. ```xml
``` -------------------------------- ### Send Email with Multiple Recipients, CC, and Attachments Source: https://github.com/simplifynet/simplify/wiki/Simplify.Mail This code snippet illustrates sending an email to multiple recipients, including CC recipients, and attaching a file. It requires providing lists of email addresses and an Attachment object. ```csharp MailSender.Default.Send("mymail@somedomain.com", new List { "address1@somedomain.com", "address2@somedomain.com" }, new List { "address3@somedomain.com", "address4@somedomain.com" }, "Mail subject!", "Mail message, can be a full HTML page", null, new Attachment(ms, "Attachment title.xls", "application/vnd.ms-excel")); ``` -------------------------------- ### WCF Service Interface Definition Source: https://github.com/simplifynet/simplify/wiki/Simplify.DI.Wcf Defines a WCF service contract interface with a sample operation. This interface is used to define the methods that can be called on the WCF service. ```csharp using System.ServiceModel; namespace MyService { [ServiceContract] public interface IService { [OperationContract] void MyMethod(); } } ``` -------------------------------- ### Double Value Comparison (C#) Source: https://github.com/simplifynet/simplify/wiki/Simplify.Extensions Checks if two double values are approximately the same, considering a small epsilon for floating-point comparisons. This extension method is defined for double values. ```csharp public static bool AreSameAs(this double a, double b); ``` -------------------------------- ### String to Nullable DateTime Conversion (C#) Source: https://github.com/simplifynet/simplify/wiki/Simplify.Extensions Attempts to convert a string to a nullable DateTime object using a specified format and invariant culture. Returns null if the conversion fails. This extension method is defined for strings. ```csharp public static DateTime? TryToDateTimeExact(this string s, string format); ``` -------------------------------- ### Bytes to String Conversion (C#) Source: https://github.com/simplifynet/simplify/wiki/Simplify.Extensions Converts a byte array to its string representation. This extension method is defined for byte arrays. ```csharp public static string GetString(this byte[] bytes); ``` -------------------------------- ### Model Class Definition - C# Source: https://github.com/simplifynet/simplify/wiki/Simplify.Templates Defines a C# class `MyClass` with three properties: `Prop1` (string), `Prop2` (int), and `Prop3` (DateTime). This class represents the data structure that will be bound to the template. ```csharp public class MyClass { public string Prop1 { get; set; } public int Prop2 { get; set; } public DateTime Prop3 { get; set; } } ``` -------------------------------- ### String to Bytes Array Conversion (C#) Source: https://github.com/simplifynet/simplify/wiki/Simplify.Extensions Converts a string to its byte array representation. This extension method is defined for strings. ```csharp public static byte[] ToBytesArray(this string str); ``` -------------------------------- ### Serialize List to XML String (C#) Source: https://github.com/simplifynet/simplify/wiki/Simplify.Xml Serializes a list of objects of a generic type T into an XML string. This is a core function of the XmlSerializer provided by the library. ```csharp public static string Serialize(IList items); ```