Skip to content

Commit

Permalink
Example tags (#99)
Browse files Browse the repository at this point in the history
* Add example tag

* Add example tag to DelayProvider

* Add example tag to SettingsProvider

* Add example tag to WaitEventFactory

* Remove unnecessary text from examples

* Add example to ArgumentParser

* Add verb parsing example

* Fix grammar

* Add example to ProcessRunner

* Update ProcessRunner xml doc

* Add examples to Json Formatter

* Update README.md

* Add ObjectValidator examples

* Update README.md

* Update example summary

* Add SmtpClient examples

* Update README.md

* Add CsvWriter example

* Update README.md

* Add CsvReader example

* Fix grammar

* Update README.md

* Add ObjectMapper examples

* Fix example redundancy

* Add LdapConnection example

* Add MessageHub example

* Update README.md

* Update example

* Update README.md

* Add CSV string example

* Add Connection examples

* Add AppWorkerBase example

* Fix phrasing

* Add  JsonPropertyAttribute example

* Change phrasing

* Change phrasing

* Change phrasing

* Change phrasing

* Change phrasing
  • Loading branch information
jpalcala authored and geoperez committed Mar 15, 2018
1 parent f600ee7 commit 116d249
Show file tree
Hide file tree
Showing 19 changed files with 921 additions and 26 deletions.
40 changes: 20 additions & 20 deletions README.md
Expand Up @@ -274,7 +274,7 @@ var data = Json.Deserialize<BasicJson>(basicJson);

### The `CsvWriter` class

Many projects require the use of CSV files to export and import data. With `CsvWriter` you can easily write objects and data to CSV format. It also provides a useful way to save the data to a file.
Many projects require the use of CSV files to export and import data. With `CsvWriter` you can easily write objects and data to CSV format. It also provides a useful way to save data into a file.

[CsvWriter API Doc](https://unosquare.github.io/swan/api/Unosquare.Swan.Formatters.CsvWriter.html)

Expand All @@ -288,7 +288,7 @@ var basicObj = new List<BasicJson>();

using (var stream = new MemoryStream(Encoding.ASCII.GetBytes(basicObj.ToString())))
{
// The writer of the CSV
// The CSV writer
var reader = new CsvWriter(stream);
};
```
Expand All @@ -301,7 +301,7 @@ You also can write the object into a file or a temporal file.
// The list of objects to be written as CSV
var basicObj = new List<BasicJson>();
// This is where the object is save into a file
CsvWriter.SaveRecords<BasicJson>(basicObj, "C:/Users/user/Documents/CsvFile");
CsvWriter.SaveRecords(basicObj, "C:/Users/user/Documents/CsvFile");
```

### The `CsvReader` class
Expand All @@ -315,14 +315,14 @@ When you need to parse data in CSV files you'll always need an easy way to read
This is a way to read CSV formatted string.

```csharp
// The data to be readed
// The data to be read
var data = @"Company,OpenPositions,MainTechnology,Revenue
Co,2,""C#, MySQL, JavaScript, HTML5 and CSS3"","500"
Ca,2,""C#, MySQL, JavaScript, HTML5 and CSS3"","600";
Co,2,""C#, MySQL, JavaScript, HTML5 and CSS3"",500
Ca,2,""C#, MySQL, JavaScript, HTML5 and CSS3"",600";

using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(data)))
{
// The reader of the CSV
// The CSV reader
var reader = new CsvReader(stream, true, Encoding.UTF8);
};
```
Expand All @@ -335,7 +335,7 @@ From a CSV file, you can read and load the information into a generic list.
// The list of object to be written as CSV
var basicObj = new List<BasicJson>();
// This is where the object is save into a file
CsvWriter.SaveRecords<BasicJson>(basicObj, "C:/Users/user/Documents/CsvFile");
CsvWriter.SaveRecords(basicObj, "C:/Users/user/Documents/CsvFile");
// This is how you can load the records of the CSV file
var loadedRecords = CsvReader.LoadRecords<BasicJson>("C:/Users/user/Documents/CsvFile");
```
Expand Down Expand Up @@ -410,7 +410,7 @@ session.Recipients.Add("recipient@test.cm");
client.SendMailAsync(session);

```
#### Example 3: Adding an attatchment with SMTP session state
#### Example 3: Adding an attachment with SMTP session state
When using `SmtpSessionState` you have to deal with raw data manipulation, in order to parse MIME attachments [MimeKit](https://www.nuget.org/packages/MimeKit/) is recommended.
```csharp
// Create a new session state with a sender address
Expand Down Expand Up @@ -592,9 +592,9 @@ This time we'll be using both custom validators and attributes

```csharp
// using the Runtime's ObjectValidator singleton
Runtime.ObjectValidator.Value.AddValidator<Simple>(x => !x.Name.Equals("Name"), "Name must not be 'Name'");
Runtime.ObjectValidator.AddValidator<Simple>(x => !x.Name.Equals("Name"), "Name must not be 'Name'");

var res = Runtime.ObjectValidator.Value.Validate(new Simple{ Name = "name", Number = 5, Email ="email@mail.com"})
var res = Runtime.ObjectValidator.Validate(new Simple{ Name = "name", Number = 5, Email ="email@mail.com"})

```

Expand All @@ -603,7 +603,7 @@ In this example, we'll use the previous `Sample` class to validate an object usi

```csharp
// using the Runtime's ObjectValidator singleton
Runtime.ObjectValidator.Value.AddValidator<Simple>(x => !x.Name.Equals("Name"), "Name must not be 'Name'");
Runtime.ObjectValidator.AddValidator<Simple>(x => !x.Name.Equals("Name"), "Name must not be 'Name'");

// using the extension method
var res = new Simple{ Name = "name", Number = 5, Email ="email@mail.com"}.IsValid();
Expand Down Expand Up @@ -662,28 +662,28 @@ A simple [Publisher-Subscriber pattern](https://en.wikipedia.org/wiki/Publish%E2

[MessageHub API Doc](https://unosquare.github.io/swan/api/Unosquare.Swan.Components.IMessageHub.html)

In many scenarios you need a way to know when something happens to an object, there are usually two ways of achieving this: constantly checking the object's properties or using the pub-sub pattern. To avoid any problems caused by the former method like a possible modification of the object's properties it is a good practice to use the latter. With the pub-sub pattern, any object can "subscribe" to another object's event if the other object "publishes" a message the event is triggered and the custom content of the message is sent. Neither the publisher nor the subscriber knows the existence of one another, therefore the publisher does not directly notify its subscribers, instead there is another component called MessageHub which is known by both(subscriber and publisher) and that filters all incoming messages and distributes them accordingly.
In many scenarios you need a way to know when something happens to an object, there are usually two ways of achieving this: constantly checking the object's properties or using the pub-sub pattern. To avoid any problems caused by the former method like a possible modification of the object's properties it is a good practice to use the latter. With the pub-sub pattern, any object can "subscribe" to the publisher's publish event. When a message is "published" the event is triggered and the custom content of the message is sent. Neither the publisher nor the subscriber knows the existence of one another, therefore the publisher does not directly notify its subscribers, instead there is another component called MessageHub which is known by both(subscriber and publisher) and that filters all incoming messages and distributes them accordingly.

#### Example 1: Subscribing to a MessageHub

A simple example using the DependencyContainer discussed above. Keep in mind that in this example both the subscription and the message sending are done in the same place but this is only for explanatory purposes.

``` csharp
// Using DependencyContainer to create an instance of MessageHub
// use DependencyContainer to create an instance of MessageHub
var messageHub = DependencyContainer.Current.Resolve<IMessageHub>() as MessageHub;

// Here we create an instance of the publisher class which has a string as its content
// create an instance of the publisher class which has a string as its content
var message = new MessageHubGenericMessage<string>(this, "SWAN");

// Then this object subscribes to the publisher's event and just prints its content which is a string
// subscribe to the publisher's event and just print its content which is a string
// a token is returned which can be used to unsubscribe later on
var token = messageHub.Subscribe<MessageHubGenericMessage<string>>(m => m.Content.Info());

// We publish a message and SWAN should be printed on the console
//publish a message and SWAN should be printed on the console
messageHub.Publish(message);

// And lastly unsuscribe, we will no longer receive any messages
MessageHub.Unsubscribe<MessageHubGenericMessage<string>>(token);
// unsuscribe, we will no longer receive any messages
messageHub.Unsubscribe<MessageHubGenericMessage<string>>(token);
```

### The `LDAPConnection` class
Expand Down Expand Up @@ -775,7 +775,7 @@ An easy way to deal with attributes modification is by calling the Modify method
connection.Disconnect();
```
### The `ProcessRunner` class
A class that provides methods that helps us create external process and capture their output.
A class that provides methods that helps us create external processes and capture their output.

[ProcessRunner API Doc](https://unosquare.github.io/swan/api/Unosquare.Swan.Components.ProcessRunner.html)

Expand Down
28 changes: 28 additions & 0 deletions src/Unosquare.Swan.Lite/Abstractions/SettingsProvider.cs
Expand Up @@ -14,6 +14,34 @@
/// <summary>
/// Represents a provider to save and load settings using a plain JSON file
/// </summary>
/// <example>
/// The following example shows how to save and load settings.
/// <code>
/// using Unosquare.Swan.Abstractions;
///
/// public class Example
/// {
/// public static void Main()
/// {
/// // get user from settings
/// var user = SettingsProvider&lt;Settings&gt;.Instance.Global.User;
///
/// // modify the port
/// SettingsProvider&lt;Settings&gt;.Instance.Global.Port = 20;
///
/// // if we want these settings to persist
/// SettingsProvider&lt;Settings&gt;.Instance.PersistGlobalSettings();
/// }
///
/// public class Settings
/// {
/// public int Port { get; set; } = 9696;
///
/// public string User { get; set; } = "User";
/// }
/// }
/// </code>
/// </example>
/// <typeparam name="T">The type of settings model</typeparam>
public class SettingsProvider<T>
: SingletonBase<SettingsProvider<T>>
Expand Down
97 changes: 97 additions & 0 deletions src/Unosquare.Swan.Lite/Components/ArgumentParser.cs
Expand Up @@ -10,6 +10,103 @@ namespace Unosquare.Swan.Components
/// Provides methods to parse command line arguments.
/// Based on CommandLine (Copyright 2005-2015 Giacomo Stelluti Scala and Contributors.)
/// </summary>
/// <example>
/// The following example shows how to parse CLI arguments into objects.
/// <code>
/// class Example
/// {
/// using System;
/// using Unosquare.Swan;
/// using Unosquare.Swan.Attributes;
///
/// static void Main(string[] args)
/// {
/// // create an instance of the Options class
/// var options = new Options();
///
/// // parse the supplied command-line arguments into the options object
/// var res = Runtime.ArgumentParser.ParseArguments(args, options);
/// }
///
/// class Options
/// {
/// [ArgumentOption('v', "verbose", HelpText = "Set verbose mode.")]
/// public bool Verbose { get; set; }
///
/// [ArgumentOption('u', Required = true, HelpText = "Set user name.")]
/// public string Username { get; set; }
///
/// [ArgumentOption('n', "names", Separator = ',',
/// Required = true, HelpText = "A list of files separated by a comma")]
/// public string[] Files { get; set; }
///
/// [ArgumentOption('p', "port", DefaultValue = 22, HelpText = "Set port.")]
/// public int Port { get; set; }
///
/// [ArgumentOption("color", DefaultValue = ConsoleColor.Red,
/// HelpText = "Set a color.")]
/// public ConsoleColor Color { get; set; }
/// }
/// }
/// </code>
/// The following code describes how to parse CLI verbs.
/// <code>
/// class Example2
/// {
/// using Unosquare.Swan;
/// using Unosquare.Swan.Attributes;
///
/// static void Main(string[] args)
/// {
/// // create an instance of the VerbOptions class
/// var options = new VerbOptions();
///
/// // parse the supplied command-line arguments into the options object
/// var res = Runtime.ArgumentParser.ParseArguments(args, options);
///
/// // if there were no errors parsing
/// if (res)
/// {
/// if(options.Run != null)
/// {
/// // run verb was selected
/// }
///
/// if(options.Print != null)
/// {
/// // print verb was selected
/// }
/// }
///
/// // flush all error messages
/// Terminal.Flush();
/// }
///
/// class VerbOptions
/// {
/// [VerbOption("run", HelpText = "Run verb.")]
/// public RunVerbOption Run { get; set; }
///
/// [VerbOption("print", HelpText = "Print verb.")]
/// public PrintVerbOption Print { get; set; }
/// }
///
/// class RunVerbOption
/// {
/// [ArgumentOption('o', "outdir", HelpText = "Output directory",
/// DefaultValue = "", Required = false)]
/// public string OutDir { get; set; }
/// }
///
/// class PrintVerbOption
/// {
/// [ArgumentOption('t', "text", HelpText = "Text to print",
/// DefaultValue = "", Required = false)]
/// public string Text { get; set; }
/// }
/// }
/// </code>
/// </example>
public class ArgumentParser
{
private const char Dash = '-';
Expand Down
24 changes: 24 additions & 0 deletions src/Unosquare.Swan.Lite/Components/Benchmark.cs
Expand Up @@ -9,6 +9,30 @@
/// <summary>
/// A simple benchmarking class.
/// </summary>
/// <example>
/// The following code demonstrates how to create a simple benchmark.
/// <code>
/// namespace Examples.Benchmark.Simple
/// {
/// using Unosquare.Swan.Components;
///
/// public class SimpleBenchmark
/// {
/// public static void Main()
/// {
/// using (Benchmark.Start("Test"))
/// {
/// // do some logic in here
/// }
///
/// // dump results into a string
/// var results = Benchmark.Dump();
/// }
/// }
///
/// }
/// </code>
/// </example>
public static class Benchmark
{
private static readonly object SyncLock = new object();
Expand Down
63 changes: 63 additions & 0 deletions src/Unosquare.Swan.Lite/Components/ObjectMapper.cs
Expand Up @@ -13,6 +13,69 @@
///
/// The extension methods like CopyPropertiesTo use the default behaviour.
/// </summary>
/// <example>
/// The following code explains how to map an object's properties into an instance of type T
/// <code>
/// using Unosquare.Swan
///
/// class Example
/// {
/// class Person
/// {
/// public string Name { get; set; }
/// public int Age { get; set; }
/// }
///
/// static void Main()
/// {
/// var obj = new { Name = "Søren", Age = 42 };
///
/// var person = Runtime.ObjectMapper.Map&lt;Person&gt;(obj);
/// }
/// }
/// </code>
/// The following code explains how to explicitly map certain properties.
/// <code>
/// using Unosquare.Swan
///
/// class Example
/// {
/// class User
/// {
/// public string Name { get; set; }
/// public Role Role { get; set; }
/// }
///
/// public class Role
/// {
/// public string Name { get; set; }
/// }
///
/// class UserDto
/// {
/// public string Name { get; set; }
/// public string Role { get; set; }
/// }
///
/// static void Main()
/// {
/// // create a User object
/// var person =
/// new User { Name = "Phillip", Role = new Role { Name = "Admin" } };
///
/// // create an Object Mapper
/// var mapper = new ObjectMapper();
///
/// // map the User's Role.Name to UserDto's Role
/// mapper.CreateMap&lt;User, UserDto&gt;()
/// .MapProperty(d => d.Role, x => x.Role.Name);
///
/// // apply the previous map and retrieve a UserDto object
/// var destination = mapper.Map&lt;UserDto&gt;(person);
/// }
/// }
/// </code>
/// </example>
public class ObjectMapper
{
private readonly List<IObjectMap> _maps = new List<IObjectMap>();
Expand Down

0 comments on commit 116d249

Please sign in to comment.