Here are the examples of the csharp api System.Console.ReadLine() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
7148 Examples
19
Source : Program.cs
with MIT License
from anupavanm
with MIT License
from anupavanm
static void Main(string[] args)
{
var teaMaker = new TeaMaker();
var teaShop = new TeaShop(teaMaker);
teaShop.TakeOrder("less sugar", 1);
teaShop.TakeOrder("more milk", 2);
teaShop.TakeOrder("without sugar", 5);
teaShop.Serve();
Console.ReadLine();
}
19
Source : Program.cs
with MIT License
from anupavanm
with MIT License
from anupavanm
static void Main(string[] args)
{
var editor = new Editor();
//Type some stuff
editor.Type("This is the first sentence.");
editor.Type("This is second.");
// Save the state to restore to : This is the first sentence. This is second.
editor.Save();
//Type some more
editor.Type("This is thrid.");
//Output the content
Console.WriteLine(editor.Content); // This is the first sentence. This is second. This is third.
//Restoring to last saved state
editor.Restore();
Console.Write(editor.Content); // This is the first sentence. This is second
Console.ReadLine();
}
19
Source : Program.cs
with MIT License
from anupavanm
with MIT License
from anupavanm
static void Main(string[] args)
{
var original = new Sheep("Jolly", "Mountain Sheep");
Console.WriteLine(original.Name); // Jolly
Console.WriteLine(original.Category); // Mountain Sheep
var cloned = original.Clone();
cloned.Name = "Dolly";
Console.WriteLine(cloned.Name); // Dolly
Console.WriteLine(cloned.Category); // Mountain Sheep
Console.WriteLine(original.Name); // Dolly
Console.ReadLine();
}
19
Source : Program.cs
with MIT License
from anupavanm
with MIT License
from anupavanm
static void Main(string[] args)
{
var unSortedList = new List<int> { 1, 10, 2, 16, 19 };
var sorter = new Sorter(new QuickSortStrategy());
sorter.Sort(unSortedList); // // Output : Sorting using Bubble Sort !
sorter = new Sorter(new QuickSortStrategy());
sorter.Sort(unSortedList); // // Output : Sorting using Quick Sort !
Console.ReadLine();
}
19
Source : Program.cs
with MIT License
from anupavanm
with MIT License
from anupavanm
static void Main(string[] args)
{
var androidBuilder = new AndroidBuilder();
androidBuilder.Build();
// Output:
// Running android tests
// Linting the android code
// replacedembling the android build
// Deploying android build to server
var iosBuilder = new IosBuilder();
iosBuilder.Build();
// Output:
// Running ios tests
// Linting the ios code
// replacedembling the ios build
// Deploying ios build to server
Console.ReadLine();
}
19
Source : Program.cs
with MIT License
from anupavanm
with MIT License
from anupavanm
static void Main(string[] args)
{
var monkey = new Monkey();
var lion = new Lion();
var dolphin = new Dolphin();
var speak = new Speak();
monkey.Accept(speak); // Ooh oo aa aa!
lion.Accept(speak); // Roaaar!
dolphin.Accept(speak); // Tuut tutt tuutt!
var jump = new Jump();
monkey.Accept(speak); // Ooh oo aa aa!
monkey.Accept(jump); // Jumped 20 feet high! on to the tree!
lion.Accept(speak); // Roaaar!
lion.Accept(jump); // Jumped 7 feet! Back on the ground!
dolphin.Accept(speak); // Tuut tutt tuutt!
dolphin.Accept(jump); // Walked on water a little and disappeared
Console.ReadLine();
}
19
Source : LoggingExample.cs
with Apache License 2.0
from apache
with Apache License 2.0
from apache
public static void Main(string[] args)
{
// Log an info level message
if (log.IsInfoEnabled) log.Info("Application [ConsoleApp] Start");
// Log a debug message. Test if debug is enabled before
// attempting to log the message. This is not required but
// can make running without logging faster.
if (log.IsDebugEnabled) log.Debug("This is a debug message");
try
{
Bar();
}
catch(Exception ex)
{
// Log an error with an exception
log.Error("Exception thrown from method Bar", ex);
}
log.Error("Hey this is an error!");
// Push a message on to the Nested Diagnostic Context stack
using(log4net.NDC.Push("NDC_Message"))
{
log.Warn("This should have an NDC message");
// Set a Mapped Diagnostic Context value
log4net.MDC.Set("auth", "auth-none");
log.Warn("This should have an MDC message for the key 'auth'");
} // The NDC message is popped off the stack at the end of the using {} block
log.Warn("See the NDC has been popped of! The MDC 'auth' key is still with us.");
// Log an info level message
if (log.IsInfoEnabled) log.Info("Application [ConsoleApp] End");
Console.Write("Press Enter to exit...");
Console.ReadLine();
}
19
Source : LoggingExample.cs
with Apache License 2.0
from apache
with Apache License 2.0
from apache
public static void Main(string[] args)
{
log4net.ThreadContext.Properties["session"] = 21;
// Hookup the FireEventAppender event
if (FireEventAppender.Instance != null)
{
FireEventAppender.Instance.MessageLoggedEvent += new MessageLoggedEventHandler(FireEventAppender_MessageLoggedEventHandler);
}
// Log an info level message
if (log.IsInfoEnabled) log.Info("Application [ConsoleApp] Start");
// Log a debug message. Test if debug is enabled before
// attempting to log the message. This is not required but
// can make running without logging faster.
if (log.IsDebugEnabled) log.Debug("This is a debug message");
// Log a custom object as the log message
log.Warn(new MsgObj(42, "So long and thanks for all the fish"));
try
{
Bar();
}
catch(Exception ex)
{
// Log an error with an exception
log.Error("Exception thrown from method Bar", ex);
}
log.Error("Hey this is an error!");
// Log an info level message
if (log.IsInfoEnabled) log.Info("Application [ConsoleApp] End");
Console.Write("Press Enter to exit...");
Console.ReadLine();
}
19
Source : LoggingExample.cs
with Apache License 2.0
from apache
with Apache License 2.0
from apache
public static void Main(string[] args)
{
// Log an info level message
if (log.IsInfoEnabled) log.Info("Application [SampleLayoutsApp] Start");
// Log a debug message. Test if debug is enabled before
// attempting to log the message. This is not required but
// can make running without logging faster.
if (log.IsDebugEnabled) log.Debug("This is a debug message");
log.Info("This is a long line of logging text. This should test if the LineWrappingLayout works. This text should be wrapped over multiple lines of output. Could you get a log message longer than this?");
log.Error("Hey this is an error!");
// Log an info level message
if (log.IsInfoEnabled) log.Info("Application [SampleLayoutsApp] End");
Console.Write("Press Enter to exit...");
Console.ReadLine();
}
19
Source : RemotingServer.cs
with Apache License 2.0
from apache
with Apache License 2.0
from apache
static void Main(string[] args)
{
// Log an info level message
if (log.IsInfoEnabled) log.Info("Application [RemotingServer] Start");
// Configure remoting. This loads the TCP channel as specified in the .config file.
RemotingConfiguration.Configure(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
// Publish the remote logging server. This is done using the log4net plugin.
log4net.LogManager.GetRepository().PluginMap.Add(new log4net.Plugin.RemoteLoggingServerPlugin("LoggingSink"));
// Wait for the user to exit
Console.WriteLine("Press 0 and ENTER to Exit");
String keyState = "";
while (String.Compare(keyState,"0", true) != 0)
{
keyState = Console.ReadLine();
}
// Log an info level message
if (log.IsInfoEnabled) log.Info("Application [RemotingServer] End");
}
19
Source : EntryPoint.cs
with Apache License 2.0
from apache
with Apache License 2.0
from apache
public static void Main()
{
// Uncomment the next line to enable log4net internal debugging
// log4net.helpers.LogLog.InternalDebugging = true;
// This will instruct log4net to look for a configuration file
// called ConsoleApp.exe.config in the application base
// directory (i.e. the directory containing ConsoleApp.exe)
log4net.Config.XmlConfigurator.Configure();
// Create a logger
ILog log = LogManager.GetLogger(typeof(EntryPoint));
// Log an info level message
if (log.IsInfoEnabled) log.Info("Application [ConsoleApp] Start");
// Invoke static LogEvents method on LoggingExample clreplaced
LoggingExample.LogEvents();
Console.Write("Press Enter to exit...");
Console.ReadLine();
if (log.IsInfoEnabled) log.Info("Application [ConsoleApp] Stop");
// It's not possible to use shutdown hooks in the .NET Compact Framework,
// so you have manually shutdown log4net to free all resoures.
LogManager.Shutdown();
}
19
Source : Analyzer.cs
with MIT License
from apexsharp
with MIT License
from apexsharp
public static void replacedyzeCSharpSources()
{
var tree = CSharpSyntaxTree.ParseText(
@"using Apex.System;
namespace ApexTest
{
clreplaced Program
{
static void Main(string[] args)
{
var map = new Map<int, string>();
map.put(1, ""Hello"");
var json = JSON.serializePretty(map);
var length = json.Length;
}
}
}");
var root = (CompilationUnitSyntax)tree.GetRoot();
var compilation = CSharpCompilation.Create("ApexTest")
.AddReferences(MetadataReference.CreateFromFile(typeof(object).replacedembly.Location))
.AddReferences(MetadataReference.CreateFromFile(typeof(Apex.System.System).replacedembly.Location))
.AddSyntaxTrees(tree);
var model = compilation.GetSemanticModel(tree);
var nameInfo = model.GetSymbolInfo(root.Usings[0].Name);
var systemSymbol = (INamespaceSymbol)nameInfo.Symbol;
foreach (var ns in systemSymbol.GetMembers()) // GetNamespaceMembers())
{
Console.WriteLine(ns.Name);
}
// decode the var type
var mapDeclaration = root.DescendantNodes().OfType<LocalDeclarationStatementSyntax>().First();
var symbolInfo = model.GetSymbolInfo(mapDeclaration.Declaration.Type);
var typeSymbol = symbolInfo.Symbol;
Console.WriteLine("The variable type: {0}", typeSymbol);
Console.WriteLine("Defined in the replacedembly: {0}", typeSymbol.Containingreplacedembly.Name);
var mapDeclarator = root.DescendantNodes().OfType<VariableDeclaratorSyntax>().FirstOrDefault();
var mapInfo = model.GetSymbolInfo(mapDeclarator.Initializer);
// display all method calls
foreach (var methodCall in root.DescendantNodes().OfType<InvocationExpressionSyntax>())
{
var mapPutSymbol = model.GetSymbolInfo(methodCall).Symbol;
Console.WriteLine("Method call: {0}", mapPutSymbol);
Console.WriteLine("Containing type: {0}", mapPutSymbol.ContainingType);
Console.WriteLine("Containing namespace: {0}", mapPutSymbol.ContainingType.ContainingNamespace);
Console.WriteLine("Containing type name: {0}", mapPutSymbol.ContainingType.Name);
Console.WriteLine("Method name: {0}", mapPutSymbol.Name);
Console.WriteLine("Method signature: {0}", mapPutSymbol.ToString().Substring(mapPutSymbol.ContainingType.ToString().Length + 1));
Console.WriteLine("Defined in the replacedembly: {0}", mapPutSymbol.Containingreplacedembly);
}
Console.ReadLine();
}
19
Source : Program.cs
with MIT License
from apexsharp
with MIT License
from apexsharp
public static void Main(string[] args)
{
Parser.Default.ParseArguments<Options>(args).WithParsed(o =>
{
if (o.ApexFolder.Length > 0)
{
try
{
DirectoryInfo apexDirectory = new DirectoryInfo(o.ApexFolder);
switch (o.Service.ToLower())
{
case "apexcodeformat":
FormatApexCode(o.ApexFolder, o.IsOutputJson);
break;
case "apextestfind":
ApexTestFined(o.ApexFolder, o.ApexFileName, o.IsOutputJson);
break;
case "caseclean":
CaseClean(o.ApexFolder);
break;
default:
Console.WriteLine($"Current Arguments: -v {o.Service}");
Console.WriteLine("Quick Start Example!");
break;
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
});
Console.WriteLine("Done, Press Any Key To Exit");
Console.ReadLine();
}
19
Source : Program.cs
with GNU General Public License v3.0
from approved
with GNU General Public License v3.0
from approved
public static void Main(string[] args)
{
if (!File.Exists(SettingsFile))
{
Directory.CreateDirectory("settings");
CurrentSettings.CreateNew(SettingsFile);
}
else
{
CurrentSettings.Load(SettingsFile);
}
ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
Client.Proxy = null;
Console.Clear();
Console.CursorVisible = false;
InputManager.Initialize();
InputManager.OnKeyboardEvent += InputManager_OnKeyboardEvent;
InputManager.OnMouseEvent += InputManager_OnMouseEvent;
OrbWalkTimer.Elapsed += OrbWalkTimer_Elapsed;
#if DEBUG
Timer callbackTimer = new Timer(16.66);
callbackTimer.Elapsed += Timer_CallbackLog;
#endif
Timer attackSpeedCacheTimer = new Timer(OrderTickRate);
attackSpeedCacheTimer.Elapsed += AttackSpeedCacheTimer_Elapsed;
attackSpeedCacheTimer.Start();
Console.WriteLine($"Press and hold '{(VirtualKeyCode)CurrentSettings.ActivationKey}' to activate the Orb Walker");
CheckLeagueProcess();
Console.ReadLine();
}
19
Source : Program.cs
with MIT License
from aquilahkj
with MIT License
from aquilahkj
static void Main(string[] args)
{
try
{
Test2(args);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
Console.ReadLine();
}
19
Source : Program.cs
with MIT License
from AquilaSands
with MIT License
from AquilaSands
static async Task Main(string[] args)
{
Console.WriteLine("Enter input file path");
string inFilePath = Console.ReadLine();
List<Setting> flattenedJson = await FlattenJson(inFilePath);
Console.WriteLine("Enter output file path");
string outFilePath = Console.ReadLine();
await WriteAppSettings(flattenedJson, outFilePath);
}
19
Source : Program.cs
with MIT License
from araditc
with MIT License
from araditc
static void Main(string[] args)
{
if (args == null || args.Length != 3 || args[0] == "-h")
{
Console.WriteLine("Usage: ./Artalk.ExtendedClient.exe HOST LOGIN PreplacedWORD");
return;
}
var host = args[0];
var login = args[1];
var preplacedword = args[2];
var client = new ExtendedXmppClient(host, login, preplacedword);
Console.Write("Message to save: ");
var message = Console.ReadLine();
var messageElement = new XmlDoreplacedent().CreateElement("message");
messageElement.InnerText = message ?? string.Empty;
client.SaveXml(messageElement);
client.Close();
Console.WriteLine("Data saved. Connection closed.");
}
19
Source : Program.cs
with MIT License
from arafattehsin
with MIT License
from arafattehsin
private static async Task Main(string[] args)
{
// STEP1: Create a model
var model = await TrainAsync();
// STEP2: Test accuracy of the model
Evaluate(model);
// STEP 3: Make a prediction
var prediction = model.Predict(CarEvalTests.Eval);
Console.WriteLine($"Predicted result: {prediction.Result:0.####}, actual result: unacceptable");
Console.ReadLine();
}
19
Source : Program.cs
with MIT License
from ArchitectNow
with MIT License
from ArchitectNow
public static async Task<int> Main(string[] args)
{
Debug.WriteLine("Starting test console app...");
var securityClient = new SecurityClient();
var token = "";
// client.BaseUrl = "";
try
{
var loginParams = new LoginVm();
loginParams.Email = "[email protected]";
loginParams.Preplacedword = "testtest";
var loginResult = await securityClient.LoginAsync(loginParams);
token = loginResult.AuthToken;
Console.WriteLine("Successful login!");
Console.WriteLine("Logged in as: " + loginResult.CurrentUser.Email);
}
catch (Exception e)
{
Console.WriteLine("Login Error: " + e.Message);
}
if (!string.IsNullOrEmpty(token))
{
var personClient = new PersonClient();
personClient.Token = token;
try
{
var result = await personClient.SecurityTestAsync();
if (result != null)
{
Console.WriteLine("Successfully called a secure endpoint");
Console.WriteLine("Validated token as user: " + result.Email);
}
}
catch (Exception e)
{
Console.WriteLine("Security Error: " + e.Message);
}
}
Console.WriteLine("Press the any key to continue...");
Console.ReadLine();
return 1;
}
19
Source : Program.cs
with MIT License
from arcus-azure
with MIT License
from arcus-azure
private static void CloseApplication()
{
Console.WriteLine(value: "\r\nPress any key to close the application...");
Console.ReadLine();
}
19
Source : App.cs
with MIT License
from ardalis
with MIT License
from ardalis
public async Task Run()
{
var testDate = new DateTime(2030, 9, 9, 14, 0, 0);
Console.WriteLine("App running.");
Console.WriteLine("Scheduling an appointment with a service.");
await _appointmentService.ScheduleAppointment("[email protected]");
Console.WriteLine();
Console.WriteLine("Creating an appointment with a repository.");
var appointment = Appointment.Create("[email protected]");
await _appointmentRepository.Save(appointment);
Console.WriteLine();
Console.WriteLine("Confirming an appointment.");
appointment.Confirm(testDate);
await _appointmentRepository.Save(appointment);
Console.WriteLine();
Console.WriteLine("Application done.");
Console.ReadLine();
}
19
Source : Program.cs
with MIT License
from ardalis
with MIT License
from ardalis
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
Console.WriteLine("Roles:");
foreach (var role in Role.List())
{
Console.WriteLine($"Role: {role.Name} ({role.Value})");
}
Console.WriteLine("Roles 2:");
foreach (var role in Role.AllRoles)
{
Console.WriteLine($"Role: {role.Name} ({role.Value})");
}
Console.WriteLine("Job replacedles:");
foreach (var replacedle in Jobreplacedle.Allreplacedles)
{
Console.WriteLine($"replacedle: {replacedle.Name} ({replacedle.Value})");
}
Console.WriteLine("--Smart Enums--");
Console.WriteLine("Smart Foo:");
foreach (var smartFoo in SmartFoo.List)
{
Console.WriteLine($"Foo: {smartFoo}");
}
Console.WriteLine("Smart Bar:");
foreach (var smartBar in SmartBar.List)
{
Console.WriteLine($"Bar: {smartBar}");
}
Console.WriteLine("Smart Baz:");
foreach (var smartBaz in SmartBaz.List)
{
Console.WriteLine($"Baz: {smartBaz}");
}
Console.ReadLine();
}
19
Source : Program.cs
with MIT License
from Arefu
with MIT License
from Arefu
private static void Main(string[] Args)
{
var RequireMeta = Args.Any(Arg => Arg.ToLower() == "-agro");
Utilities.Log("Looking For Plugins.", Utilities.Event.Information);
var Plugins = new List<string>();
foreach (var Plugin in Directory.GetFiles("Plugins/", "*.dll"))
{
if (File.Exists($"{Plugin.ToLower().Replace(".dll", string.Empty)}_info.json"))
{
Utilities.Log($"Found Plugin: {Plugin}, Reading Plugin Information.", Utilities.Event.Information);
var MetaData =
new JavaScriptSerializer().Deserialize<Meta>(
File.ReadAllText(Plugin.Replace(".dll", string.Empty) + "_info.json"));
Utilities.Log($"Name: {MetaData.Name}", Utilities.Event.Meta);
Utilities.Log($"Description: {MetaData.Description}", Utilities.Event.Meta);
foreach (var Address in MetaData.Injection_Addresses)
Utilities.Log($"Injection Address: {Address}", Utilities.Event.Meta);
foreach (var Dependancy in MetaData.Depends)
{
Utilities.Log($"Depends On: {Dependancy}", Utilities.Event.Meta);
if (!File.Exists($"Plugins/{Dependancy}") && Dependancy.ToLower() != "nothing")
Utilities.Log($"I Can't Find {Dependancy}!", Utilities.Event.Error);
}
}
if (!RequireMeta)
{
if (!File.Exists(Plugin.ToLower().Replace(".dll", string.Empty) + "_info.json"))
Utilities.Log(
$"No {Plugin.ToLower().Replace(".dll", string.Empty)}_info.json Found, Loading Anyway.",
Utilities.Event.Warning);
Plugins.Add(new FileInfo(Plugin).FullName);
}
else
{
if (!File.Exists(Plugin.ToLower().Replace(".dll", string.Empty) + "_info.json"))
Utilities.Log(
$"No {Plugin.ToLower().Replace(".dll", string.Empty)}_info.json Found, Agro Was Specified. I Won't Load This.",
Utilities.Event.Error);
}
}
Process.Start("steam://run/480650");
Thread.Sleep(TimeSpan.FromSeconds(2.5));
foreach (var Plugin in Plugins)
{
var Result = Injector.Inject("YuGiOh", Plugin);
Utilities.Log($"{new FileInfo(Plugin).Name}'s Injection Status: {Result}", Utilities.Event.Information);
}
var InputCommand = "";
do
{
Console.Write("Yu-Gi-Oh: ");
InputCommand = Console.ReadLine().ToLower();
switch (InputCommand.ToLower())
{
case "set":
Console.Write("Address / Variable: ");
//Set Address Get from List of JSON Address -> Variable File
Console.Write("Value: ");
//Set Value
break;
case "get":
Console.Write("Address / Variable: ");
var Variable = "";
switch (Variable.ToLower())
{
case "p_duel_points":
//Call Naitive Func To Return Amount Of Points.
break;
}
break;
}
} while (InputCommand.ToLower() != "quit");
}
19
Source : Entrypoint.cs
with MIT License
from Arkhist
with MIT License
from Arkhist
[MethodImpl(MethodImplOptions.NoInlining)]
internal static void Load()
{
try
{
Paths.SetExecutablePath(typeof(HN.Program).replacedembly.GetName().Name);
Logger.Listeners.Add(new ConsoleLogger());
AccessTools.PropertySetter(typeof(TraceLogSource), nameof(TraceLogSource.IsListening)).Invoke(null, new object[] { true });
ConsoleManager.Initialize(true);
// Start chainloader for plugins
var chainloader = new HacknetChainloader();
chainloader.Initialize();
chainloader.Execute();
}
catch (Exception ex)
{
Console.WriteLine("Fatal loading exception:");
Console.WriteLine(ex);
Console.ReadLine();
Environment.Exit(1);
}
}
19
Source : Program.cs
with GNU Affero General Public License v3.0
from arklumpus
with GNU Affero General Public License v3.0
from arklumpus
static int Main(string[] args)
{
bool showHelp = false;
bool showUsage = false;
string rootPath = null;
string privateKeyFile = null;
OptionSet argParser = new OptionSet()
{
{ "h|help", "Print this message and exit.", v => { showHelp = v != null; } },
{ "r|root=", "The path to the root of the repository. Required.", v => { rootPath = v; } },
{ "k|key=", "Provide the path to the private key file that will be used to sign the modules. Required.", v => { privateKeyFile = v; } },
};
List<string> unrecognised = argParser.Parse(args);
if (unrecognised.Count > 0)
{
Console.WriteLine();
Console.WriteLine("Unrecognised argument" + (unrecognised.Count > 1 ? "s" : "") + ": " + unrecognised.Aggregate((a, b) => a + " " + b));
showUsage = true;
}
if (string.IsNullOrEmpty(rootPath) && !showHelp)
{
Console.WriteLine();
Console.WriteLine("The root path is required!");
showUsage = true;
}
if (string.IsNullOrEmpty(privateKeyFile) && !showHelp)
{
Console.WriteLine();
Console.WriteLine("The private key file is required!");
showUsage = true;
}
if (showUsage || showHelp)
{
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("BuildRepositoryModuleDatabase");
Console.WriteLine();
Console.WriteLine("Usage:");
Console.WriteLine();
Console.WriteLine(" BuildRepositoryModuleDatabase {-h|--help}");
Console.WriteLine(" BuildRepositoryModuleDatabase --root <root_path> --key <key_file>");
}
if (showHelp)
{
Console.WriteLine();
Console.WriteLine("Options:");
Console.WriteLine();
argParser.WriteOptionDescriptions(Console.Out);
return 0;
}
if (showUsage)
{
return 64;
}
System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.InvariantCulture;
System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture;
Directory.SetCurrentDirectory(Path.GetDirectoryName(replacedembly.GetExecutingreplacedembly().Location));
string[] files = Directory.GetFiles(Path.Combine(rootPath, "src", "Modules"), "*.cs");
VectSharp.SVG.Parser.ParseImageURI = VectSharp.MuPDFUtils.ImageURIParser.Parser(VectSharp.SVG.Parser.ParseSVGURI);
File.Delete(Modules.ModuleListPath);
TreeViewer.ModuleMetadata[] modules = new TreeViewer.ModuleMetadata[files.Length];
if (!Directory.Exists("references"))
{
Directory.CreateDirectory("references");
}
Console.ForegroundColor = ConsoleColor.Blue;
Console.WriteLine();
Console.WriteLine("Compiling modules...");
Console.WriteLine();
Console.ForegroundColor = ConsoleColor.Gray;
for (int i = 0; i < files.Length; i++)
{
Console.WriteLine(Path.GetFileName(files[i]));
if (!File.Exists(Path.Combine(rootPath, "src", "Modules", "references", Path.GetFileName(files[i]) + ".references")))
{
References[Path.GetFileName(files[i])] = new List<string>(baseReferences);
}
else
{
References[Path.GetFileName(files[i])] = new List<string>(File.ReadAllLines(Path.Combine(rootPath, "src", "Modules", "references", Path.GetFileName(files[i]) + ".references")));
}
bool compiledWithoutErrors = false;
while (!compiledWithoutErrors)
{
try
{
modules[i] = TreeViewer.ModuleMetadata.CreateFromSource(File.ReadAllText(files[i]), References[Path.GetFileName(files[i])].ToArray());
compiledWithoutErrors = true;
}
catch (Exception e)
{
HashSet<string> newReferences = new HashSet<string>();
string msg = e.Message;
while (msg.Contains("You must add a reference to replacedembly '"))
{
msg = msg.Substring(msg.IndexOf("You must add a reference to replacedembly '") + "You must add a reference to replacedembly '".Length);
newReferences.Add(msg.Substring(0, msg.IndexOf(",")));
}
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine();
Console.WriteLine(e.Message);
Console.WriteLine();
Console.ForegroundColor = ConsoleColor.Gray;
if (newReferences.Count == 0)
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.Write("Which references should I add? ");
Console.ForegroundColor = ConsoleColor.Gray;
string[] newRefs = Console.ReadLine().Split(',');
foreach (string sr in newRefs)
{
string refName = sr.Trim();
if (refName.EndsWith(".dll"))
{
refName = refName.Substring(0, refName.Length - 4);
}
newReferences.Add(refName);
}
Console.WriteLine();
}
Console.WriteLine("Adding references: ");
foreach (string sr in newReferences)
{
References[Path.GetFileName(files[i])].Add(sr + ".dll");
Console.WriteLine("\t" + sr + ".dll");
}
}
}
File.WriteAllLines(Path.Combine(rootPath, "src", "Modules", "references", Path.GetFileName(files[i]) + ".references"), References[Path.GetFileName(files[i])]);
}
Console.ForegroundColor = ConsoleColor.Blue;
Console.WriteLine();
Console.WriteLine("Checking for unnecessary references...");
Console.WriteLine();
Console.ForegroundColor = ConsoleColor.Gray;
for (int i = 0; i < files.Length; i++)
{
Console.WriteLine(Path.GetFileName(files[i]));
List<string> toBeRemoved = new List<string>();
List<string> originalReferences = References[Path.GetFileName(files[i])];
for (int j = 0; j < originalReferences.Count; j++)
{
List<string> currentReferences = new List<string>(originalReferences);
currentReferences.Remove(originalReferences[j]);
try
{
TreeViewer.ModuleMetadata.CreateFromSource(File.ReadAllText(files[i]), currentReferences.ToArray());
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("\tRemoving " + originalReferences[j]);
Console.ForegroundColor = ConsoleColor.Gray;
toBeRemoved.Add(originalReferences[j]);
}
catch
{
}
}
for (int j = 0; j < toBeRemoved.Count; j++)
{
References[Path.GetFileName(files[i])].Remove(toBeRemoved[j]);
}
File.WriteAllLines(Path.Combine(rootPath, "src", "Modules", "references", Path.GetFileName(files[i]) + ".references"), References[Path.GetFileName(files[i])]);
}
Console.ForegroundColor = ConsoleColor.Blue;
Console.WriteLine();
Console.WriteLine("Exporting modules and rendering manuals...");
Console.WriteLine();
Console.ForegroundColor = ConsoleColor.Gray;
Directory.CreateDirectory(Path.Combine(rootPath, "Modules"));
VectSharp.Markdown.MarkdownRenderer renderer = new VectSharp.Markdown.MarkdownRenderer() { BaseFontSize = 12 };
Func<string, string, (string, bool)> imageUriResolver = renderer.ImageUriResolver;
List<string> imagesToDelete = new List<string>();
Dictionary<string, string> imageCache = new Dictionary<string, string>();
renderer.ImageUriResolver = (imageUri, baseUri) =>
{
if (!imageCache.TryGetValue(baseUri + "|||" + imageUri, out string cachedImage))
{
if (!imageUri.StartsWith("data:"))
{
bool wasDownloaded;
(cachedImage, wasDownloaded) = imageUriResolver(imageUri, baseUri);
if (wasDownloaded)
{
imagesToDelete.Add(cachedImage);
}
imageCache.Add(baseUri + "|||" + imageUri, cachedImage);
}
else
{
string tempFile = Path.GetTempFileName();
if (File.Exists(tempFile))
{
File.Delete(tempFile);
}
Directory.CreateDirectory(tempFile);
string uri = imageUri;
string mimeType = uri.Substring(uri.IndexOf(":") + 1, uri.IndexOf(";") - uri.IndexOf(":") - 1);
string type = uri.Substring(uri.IndexOf(";") + 1, uri.IndexOf(",") - uri.IndexOf(";") - 1);
if (mimeType == "image/svg+xml")
{
int offset = uri.IndexOf(",") + 1;
string data;
switch (type)
{
case "base64":
data = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(uri.Substring(offset)));
break;
}
}
VectSharp.Page pag = VectSharp.SVG.Parser.ParseImageURI(imageUri, true);
VectSharp.SVG.SVGContextInterpreter.SavereplacedVG(pag, Path.Combine(tempFile, "temp.svg"));
imagesToDelete.Add(Path.Combine(tempFile, "temp.svg"));
cachedImage = Path.Combine(tempFile, "temp.svg");
imageCache.Add(baseUri + "|||" + imageUri, cachedImage);
}
}
else
{
Console.WriteLine("Fetching {0} from cache.", imageUri);
}
return (cachedImage, false);
};
List<ModuleHeader> moduleHeaders = new List<ModuleHeader>();
foreach (TreeViewer.ModuleMetadata module in modules)
{
Directory.CreateDirectory(Path.Combine(rootPath, "Modules", module.Id));
string modulePath = Path.Combine(rootPath, "Modules", module.Id, module.Id + ".v" + module.Version.ToString() + ".json.zip");
module.Sign(privateKeyFile);
module.Export(modulePath, true, true, true);
string markdownSource = module.BuildReadmeMarkdown();
Console.WriteLine("Rendering {0} - {1}", module.Name, module.Id);
Markdig.Syntax.MarkdownDoreplacedent markdownDoreplacedent = Markdig.Markdown.Parse(markdownSource, new Markdig.MarkdownPipelineBuilder().UseGridTables().UsePipeTables().UseEmphasisExtras().UseGenericAttributes().UseAutoIdentifiers().UseAutoLinks().UseTaskLists().UseListExtras().UseCitations().UseMathematics().Build());
VectSharp.Doreplacedent doc = renderer.Render(markdownDoreplacedent, out Dictionary<string, string> linkDestinations);
VectSharp.PDF.PDFContextInterpreter.SaveAsPDF(doc, Path.Combine(rootPath, "Modules", module.Id, "Readme.pdf"), linkDestinations: linkDestinations);
TreeViewer.ModuleMetadata.Install(modulePath, true, false);
ModuleHeader header = new ModuleHeader(module);
moduleHeaders.Add(header);
}
foreach (string imageFile in imagesToDelete)
{
System.IO.File.Delete(imageFile);
System.IO.Directory.Delete(System.IO.Path.GetDirectoryName(imageFile));
}
string serializedModuleHeaders = System.Text.Json.JsonSerializer.Serialize(moduleHeaders, Modules.DefaultSerializationOptions);
using (FileStream fs = new FileStream(Path.Combine(rootPath, "Modules", "modules.json.gz"), FileMode.Create))
{
using (GZipStream compressionStream = new GZipStream(fs, CompressionLevel.Optimal))
{
using (StreamWriter sw = new StreamWriter(compressionStream))
{
sw.Write(serializedModuleHeaders);
}
}
}
using (StreamWriter sw = new StreamWriter(Path.Combine(rootPath, "Modules", "Readme.md")))
{
sw.WriteLine("# Module repository");
sw.WriteLine();
sw.WriteLine("This folder contains a collection of modules maintained by the developer(s) of TreeViewer. All the modules are signed and tested before being included in this repository.");
sw.WriteLine();
sw.WriteLine("The modules can be loaded or installed by using the `Load from repository...` or `Install from repository...` options in the module manager window.");
sw.WriteLine("Alternatively, the module `json.zip` files can be downloaded and loaded or installed manually using the `Load...` or `Install...` options.");
sw.WriteLine();
sw.WriteLine("Click on the name of any module to open the folder containing the module's manual and `json.zip` file.");
sw.WriteLine();
sw.WriteLine("## List of currently available modules");
sw.WriteLine();
foreach (ModuleHeader header in moduleHeaders)
{
sw.WriteLine("<br />");
sw.WriteLine();
sw.WriteLine("### [" + header.Name + "](" + header.Id + ")");
sw.WriteLine();
sw.WriteLine("_Version " + header.Version.ToString() + ", by " + header.Author + "_");
sw.WriteLine();
sw.WriteLine("**Description**: " + header.HelpText);
sw.WriteLine();
sw.WriteLine("**Module type**: " + header.ModuleType.ToString());
sw.WriteLine();
sw.WriteLine("**Module ID**: `" + header.Id + "`");
sw.WriteLine();
}
}
return 0;
}
19
Source : Program.cs
with MIT License
from arminreiter
with MIT License
from arminreiter
private static string EnterCsvPath()
{
Console.WriteLine("Please enter a path (folder) for the CSV files, leave empty to skip generation of CSV files:");
string csvPath = string.Empty;
do
{
if (!string.IsNullOrEmpty(csvPath))
Console.WriteLine(csvPath + " does not exist, try again: ");
csvPath = Console.ReadLine();
}
while (!System.IO.Directory.Exists(csvPath) && !String.IsNullOrEmpty(csvPath));
return csvPath;
}
19
Source : Program.cs
with Apache License 2.0
from aryice
with Apache License 2.0
from aryice
static void Main(string[] args)
{
Stopwatch sw = new Stopwatch();
int readvalue = 0;
Console.WriteLine("当前时间:" + DateTime.Now);
while (true)
{
Console.WriteLine("请输入操作选项:获取所有记录数(1),根据条件查询(2),数据写入(3),分离数据库(4),附加数据库(5),表添加索引(6),表删除索引(7),服务器缓存清除(9),检查服务器连接(11),检查数据库连接(12),检查表连接(13),删除记录(14),修改记录(15),清空某一数据结构存储(16),退出(q)");
string getread = Console.ReadLine();
if (getread.ToLower().Trim() == "q")
{
System.Environment.Exit(0);
}
readvalue = CommonHelper.ToInt(getread);
sw.Restart();
switch (readvalue)
{
case 1: TestDB.getrowallcount(); break;
case 2: TestDB.getlistcondition(); break;
case 3: TestDB.addrow(); break;
case 4: TestDB.databasedetach(); break;
case 5: TestDB.databaseattach(); break;
case 6: TestDB.tableindexadd(); break;
case 7: TestDB.tableindexdel(); break;
case 9: TestDB.servercacheclear(); break;
case 11: TestDB.serverconnectioncheck(); break;
case 12: TestDB.databaseexistsall(); break;
case 13: TestDB.tableexistsall(); break;
case 14: TestDB.delete(); break;
case 15: TestDB.update(); break;
case 16: TestDB.sqlbaseclear(); break;
}
sw.Stop();
Console.WriteLine(" 执行时间:" + sw.ElapsedMilliseconds+"毫秒");
}
Console.WriteLine("当前时间:"+DateTime.Now);
Console.ReadKey();
}
19
Source : TestDB.cs
with Apache License 2.0
from aryice
with Apache License 2.0
from aryice
public static void servercacheclear()
{
Console.WriteLine("请输入服务器编号(all:所有服务器)");
string servernumber = CommonHelper.ToStr(Console.ReadLine());
if (servernumber.ToLower().Trim() == "all")
{
new ManagerServer().ServerCacheClearAll(basemodel);
}
else
{
var item = DBConfig.GetServerXmlConfig(basemodel).SqlServerList.Where(m => m.Number == CommonHelper.ToLong(servernumber)).FirstOrDefault();
if (item != null)
{
new ManagerServer().ServerCacheClearItem(item);
}
}
}
19
Source : Program.cs
with Apache License 2.0
from asc-lab
with Apache License 2.0
from asc-lab
static void Main(string[] args)
{
string configFile = GetConfigFile(args);
var builder = new ConfigurationBuilder().AddJsonFile(configFile);
Configuration = builder.Build();
var client = new DoreplacedentClient(new Uri(Configuration["PriceDbUrl"]), Configuration["PriceDbAuthKey"]);
AddDoc(client);
GetDoreplacedent(client);
Console.ReadLine();
}
19
Source : Program.cs
with MIT License
from AshV
with MIT License
from AshV
static void Main(string[] args)
{
WeatherStation ws = new WeatherStation();
string X = "";
do
{
WriteLine("Enter the sensor values:");
float temp = Convert.ToSingle(ReadLine());
float pressure = Convert.ToSingle(ReadLine());
float humidity = Convert.ToSingle(ReadLine());
ws.notify(temp, pressure, humidity);
WriteLine("Enter to Continue, X to Exit.");
X = ReadLine();
} while (!X.Equals("X"));
}
19
Source : Program.cs
with MIT License
from AshV
with MIT License
from AshV
static void Main(string[] args)
{
WeatherStation ws = new WeatherStation();
ws.subscribe(new CurrentConditionsDisplay());
ws.subscribe(new StatisticsDisplay());
ws.subscribe(new ForecastDisplay());
string c = "C";
while (c.Equals("C"))
{
WriteLine("Enter the sensor values:");
float temp = Convert.ToSingle(ReadLine());
float pressure = Convert.ToSingle(ReadLine());
float humidity = Convert.ToSingle(ReadLine());
ws.notify(temp, pressure, humidity);
c = ReadLine();
}
}
19
Source : worker.cs
with GNU General Public License v3.0
from ashr
with GNU General Public License v3.0
from ashr
private int chooseNumber(string question)
{
string numberInput = "";
int number;
while (!int.TryParse(numberInput, out number))
{
Console.Write("[?] " + question + ":");
numberInput = Console.ReadLine();
}
return number;
}
19
Source : Program.cs
with MIT License
from AshV
with MIT License
from AshV
static void Main(string[] args)
{
int n = Convert.ToInt32(Console.ReadLine());
ICache cache = CacheFactory.getCache(n);
cache.put("abc", 100);
cache.put("def", 2000);
cache.put("xyz", 170);
cache.get("abc");
}
19
Source : Program.cs
with MIT License
from AshV
with MIT License
from AshV
static void Main(string[] args)
{
int n = Convert.ToInt32(Console.ReadLine());
ICacheFactory cacheFactory = new CacheFactory();
ICache cache = cacheFactory.getCache(n);
cache.put("abc", 100);
cache.put("def", 2000);
cache.put("xyz", 170);
cache.get("abc");
}
19
Source : Program.cs
with MIT License
from AshV
with MIT License
from AshV
public static void Main()
{
// Instanciating with base URL
FirebaseDB firebaseDB = new FirebaseDB("https://c-sharpcorner-2d7ae.firebaseio.com");
// Referring to Node with name "Teams"
FirebaseDB firebaseDBTeams = firebaseDB.Node("Teams");
var data = @"{
'Team-Awesome': {
'Members': {
'M1': {
'City': 'Hyderabad',
'Name': 'Ashish'
},
'M2': {
'City': 'Cyberabad',
'Name': 'Vivek'
},
'M3': {
'City': 'Secunderabad',
'Name': 'Pradeep'
}
}
}
}";
WriteLine("GET Request");
FirebaseResponse getResponse = firebaseDBTeams.Get();
WriteLine(getResponse.Success);
if (getResponse.Success)
WriteLine(getResponse.JSONContent);
WriteLine();
WriteLine("PUT Request");
FirebaseResponse putResponse = firebaseDBTeams.Put(data);
WriteLine(putResponse.Success);
WriteLine();
WriteLine("POST Request");
FirebaseResponse postResponse = firebaseDBTeams.Post(data);
WriteLine(postResponse.Success);
WriteLine();
WriteLine("PATCH Request");
FirebaseResponse patchResponse = firebaseDBTeams
// Use of NodePath to refer path lnager than a single Node
.NodePath("Team-Awesome/Members/M1")
.Patch("{\"Designation\":\"CRM Consultant\"}");
WriteLine(patchResponse.Success);
WriteLine();
//WriteLine("DELETE Request");
//FirebaseResponse deleteResponse = firebaseDBTeams.Delete();
//WriteLine(deleteResponse.Success);
//WriteLine();
WriteLine(firebaseDBTeams);
new Program().SocketWala(firebaseDBTeams.ToString() + "/.json");
ReadLine();
}
19
Source : Program.cs
with MIT License
from askguanyu
with MIT License
from askguanyu
static void Main(string[] args)
{
Console.WriteLine("Start...");
Console.WriteLine("Done!");
Console.ReadLine();
}
19
Source : Program.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
public static void RunServer(StartOptions options)
{
if (options == null)
{
return;
}
string boot;
if (!options.Settings.TryGetValue("boot", out boot)
|| string.IsNullOrWhiteSpace(boot))
{
options.Settings["boot"] = "Domain";
}
ResolvereplacedembliesFromDirectory(
Path.Combine(Directory.GetCurrentDirectory(), "bin"));
WriteLine("Starting with " + GetDisplayUrl(options));
IServiceProvider services = ServicesFactory.Create();
var starter = services.GetService<IHostingStarter>();
IDisposable server = starter.Start(options);
WriteLine("Started successfully");
WriteLine("Press Enter to exit");
Console.ReadLine();
WriteLine("Terminating.");
server.Dispose();
}
19
Source : Program.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
public static void Main(string[] args)
{
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
Task.Run(() => DequeueAndSendWebHooks(cancellationTokenSource.Token));
Console.WriteLine("Hit ENTER to exit!");
Console.ReadLine();
cancellationTokenSource.Cancel();
}
19
Source : Program.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
public static void Main(string[] args)
{
string baseAddress = "http://localhost:50008/";
// Start OWIN host
using (WebApp.Start<Startup>(url: baseAddress))
{
string mailChimpAddress = GetWebHookAddress(baseAddress);
Console.WriteLine("Starting MailChimp WebHooks receiver running on " + mailChimpAddress);
Console.WriteLine("For non-localhost requests, use of 'https' is required!");
Console.WriteLine("For more information about MailChimp WebHooks, please see 'https://apidocs.mailchimp.com/webhooks/'");
Console.WriteLine("Hit ENTER to exit!");
Console.ReadLine();
}
}
19
Source : Program.cs
with MIT License
from aspnetboilerplate
with MIT License
from aspnetboilerplate
public static void Main(string[] args)
{
ParseArgs(args);
using (var bootstrapper = AbpBootstrapper.Create<AbpTemplateMigratorModule>())
{
bootstrapper.IocManager.IocContainer
.AddFacility<LoggingFacility>(
f => f.UseAbpLog4Net().WithConfig("log4net.config")
);
bootstrapper.Initialize();
using (var migrateExecuter = bootstrapper.IocManager.ResolveAsDisposable<MulreplacedenantMigrateExecuter>())
{
var migrationSucceeded = migrateExecuter.Object.Run(_quietMode);
if (_quietMode)
{
// exit clean (with exit code 0) if migration is a success, otherwise exit with code 1
var exitCode = Convert.ToInt32(!migrationSucceeded);
Environment.Exit(exitCode);
}
else
{
Console.WriteLine("Press ENTER to exit...");
Console.ReadLine();
}
}
}
}
19
Source : ProgressDetails.cs
with MIT License
from aspose-pdf
with MIT License
from aspose-pdf
public static void Run()
{
try
{
// ExStart:ProgressDetails
// The path to the doreplacedents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_DoreplacedentConversion_PDFToHTMLFormat();
string licenseFile = ""; // E.g F:\_Sources\Aspose_5\trunk\testdata\License\Aspose.Total.lic
(new Aspose.Pdf.License()).SetLicense(licenseFile);
Doreplacedent doc = new Doreplacedent(dataDir + "input.pdf");
HtmlSaveOptions saveOptions = new HtmlSaveOptions();
// SaveOptions.CustomProgressHandler = new HtmlSaveOptions.ConversionProgessEventHandler(ShowProgressOnConsole);
saveOptions.SplitIntoPages = false;
doc.Save(dataDir + "ProgressDetails_out_.html", saveOptions);
Console.ReadLine();
// ExEnd:ProgressDetails
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
19
Source : SaveHTMLImageCSS.cs
with MIT License
from aspose-pdf
with MIT License
from aspose-pdf
public static void Run()
{
try
{
// ExStart:SaveHTMLImageCSS
// The path to the doreplacedents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_DoreplacedentConversion_PDFToHTMLFormat();
Doreplacedent doc = new Doreplacedent(dataDir + "input.pdf");
// Pay attention that we put non-existing path here : since we use custon resource processing it won't be in use.
// If You forget implement some of required saving strategies(CustomHtmlSavingStrategy,CustomResourceSavingStrategy,CustomCssSavingStrategy), then saving will return "Path not found" exception
string outHtmlFile = dataDir + "SaveHTMLImageCSS_out.html";
// Create HtmlSaveOption with custom saving strategies that will do all the saving job
// In such approach You can split HTML in pages if You will
HtmlSaveOptions saveOptions = new HtmlSaveOptions();
saveOptions.SplitIntoPages = true;
saveOptions.CustomHtmlSavingStrategy = new HtmlSaveOptions.HtmlPageMarkupSavingStrategy(StrategyOfSavingHtml);
saveOptions.CustomResourceSavingStrategy = new HtmlSaveOptions.ResourceSavingStrategy(CustomSaveOfFontsAndImages);
saveOptions.CustomStrategyOfCssUrlCreation = new HtmlSaveOptions.CssUrlMakingStrategy(CssUrlMakingStrategy);
saveOptions.CustomCssSavingStrategy = new HtmlSaveOptions.CssSavingStrategy(CustomSavingOfCss);
saveOptions.FontSavingMode = HtmlSaveOptions.FontSavingModes.SaveInAllFormats;
saveOptions.RasterImagesSavingMode = HtmlSaveOptions.RasterImagesSavingModes.AsEmbeddedPartsOfPngPageBackground;
doc.Save(outHtmlFile, saveOptions);
Console.WriteLine("Done");
Console.ReadLine();
// ExEnd:SaveHTMLImageCSS
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
19
Source : DetermineProgress.cs
with MIT License
from aspose-pdf
with MIT License
from aspose-pdf
public static void Run()
{
// ExStart:DetermineProgress
// The path to the doreplacedents directory.
string dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDoreplacedents();
// Open doreplacedent
Doreplacedent pdfDoreplacedent = new Doreplacedent(dataDir + "AddTOC.pdf");
DocSaveOptions saveOptions = new DocSaveOptions();
saveOptions.CustomProgressHandler = new UnifiedSaveOptions.ConversionProgressEventHandler(ShowProgressOnConsole);
dataDir = dataDir + "DetermineProgress_out.pdf";
pdfDoreplacedent.Save(dataDir, saveOptions);
Console.ReadLine();
// ExEnd:DetermineProgress
}
19
Source : GetXMPMetadata.cs
with MIT License
from aspose-pdf
with MIT License
from aspose-pdf
public static void Run()
{
// ExStart:GetXMPMetadata
// The path to the doreplacedents directory.
string dataDir = RunExamples.GetDataDir_AsposePdfFacades_WorkingDoreplacedents();
// Create PdfXmpMetadata object
PdfXmpMetadata xmpMetaData = new PdfXmpMetadata();
// Bind pdf file to the object
xmpMetaData.BindPdf( dataDir + "input.pdf");
// Get XMP Meta Data properties
Console.WriteLine(": {0}", xmpMetaData[DefaultMetadataProperties.CreateDate].ToString());
Console.WriteLine(": {0}", xmpMetaData[DefaultMetadataProperties.MetadataDate].ToString());
Console.WriteLine(": {0}", xmpMetaData[DefaultMetadataProperties.CreatorTool].ToString());
Console.WriteLine(": {0}", xmpMetaData["customNamespace:UserPropertyName"].ToString());
Console.ReadLine();
// ExEnd:GetXMPMetadata
}
19
Source : Program.cs
with Apache License 2.0
from asynkron
with Apache License 2.0
from asynkron
public static async Task Main(string[] args)
{
AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
// ThreadPool.SetMinThreads(500, 500);
Request = new HelloRequest();
Configuration.SetupLogger(LogLevel.Error);
if (args.Length > 0)
{
// InteractiveOutput = args[0] == "1";
var worker = await Configuration.SpawnMember();
AppDomain.CurrentDomain.ProcessExit += (sender, args) => { worker.ShutdownAsync().Wait(); };
Thread.Sleep(Timeout.Infinite);
return;
}
ts = new TaskCompletionSource<bool>();
// _ = DockerSupport.Run(ts.Task);
Console.WriteLine("Proto.Cluster chaos benchmark");
Console.WriteLine();
Console.WriteLine("Explanation:");
Console.WriteLine(". = 10 000 successful requests");
// Console.WriteLine("# = activation of a virtual actor");
// Console.WriteLine("+ = (deliberate) deactivation of virtual actor");
Console.WriteLine("X = NULL response, e.g. requests retried but got no response");
Console.WriteLine();
// Console.WriteLine("1) Run with interactive output");
// Console.WriteLine("2) Run silent");
//
// var res0 = Console.ReadLine();
// InteractiveOutput = res0 == "1";
Console.WriteLine("1) Run single process - graceful exit");
Console.WriteLine("2) Run single process");
Console.WriteLine("3) Run multi process - graceful exit");
Console.WriteLine("4) Run multi process");
Console.WriteLine("5) Run single process, single node, Batch(300), ProtoBuf, 10 actors, 60S");
var memberRunStrategy = Console.ReadLine();
var batchSize = 0;
string clientStrategy = "2";
if (memberRunStrategy == "5")
{
memberRunStrategy = "3";
actorCount = 10;
killTimeoutSeconds = 60;
memberCount = 1;
batchSize = 300;
}
else
{
Console.WriteLine("1) Protobuf serializer");
Console.WriteLine("2) Json serializer");
if (Console.ReadLine() == "2")
{
Request = new HelloRequestPoco();
}
Console.WriteLine("1) Run single request client");
Console.WriteLine("2) Run batch requests client");
Console.WriteLine("3) Run fire and forget client");
Console.WriteLine("4) Run single request debug client");
Console.WriteLine("5) NoOp - Stability");
clientStrategy = Console.ReadLine() ?? "";
if (clientStrategy == "2")
{
Console.WriteLine("Batch size? default is 50");
if (!int.TryParse(Console.ReadLine(), out batchSize)) batchSize = 50;
Console.WriteLine($"Using batch size {batchSize}");
}
Console.WriteLine("Number of virtual actors? default 10000");
if (!int.TryParse(Console.ReadLine(), out actorCount)) actorCount = 10_000;
Console.WriteLine($"Using {actorCount} actors");
Console.WriteLine("Number of cluster members? default is 8");
if (!int.TryParse(Console.ReadLine(), out memberCount)) memberCount = 8;
Console.WriteLine($"Using {memberCount} members");
Console.WriteLine("Seconds to run before stopping members? default is 30");
if (!int.TryParse(Console.ReadLine(), out killTimeoutSeconds)) killTimeoutSeconds = 30;
Console.WriteLine($"Using {killTimeoutSeconds} seconds");
}
Action run = clientStrategy switch
{
"1" => () => RunClient(),
"2" => () => RunBatchClient(batchSize),
"3" => () => RunFireForgetClient(),
"4" => () => RunDebugClient(),
"5" => () => RunNoopClient(),
_ => throw new ArgumentOutOfRangeException()
};
19
Source : Program.cs
with Apache License 2.0
from asynkron
with Apache License 2.0
from asynkron
static void Main(string[] args)
{
var system = new ActorSystem();
var props = Props.FromProducer(() => new ProcessActor());
var pid = system.Root.Spawn(props);
system.Root.Send(pid, new Process());
Task.Run(async () =>
{
await Task.Delay(50);
system.Root.Stop(pid);
});
Console.ReadLine();
}
19
Source : Program.cs
with Apache License 2.0
from asynkron
with Apache License 2.0
from asynkron
private static void Main(string[] args)
{
var childProps = Props.FromFunc(context => {
Console.WriteLine($"{context.Self.Id}: MSG: {context.Message.GetType()}");
switch (context.Message)
{
case Started _:
throw new Exception("child failure");
}
return Task.CompletedTask;
}
);
var rootProps = Props.FromFunc(context => {
Console.WriteLine($"{context.Self.Id}: MSG: {context.Message.GetType()}");
switch (context.Message)
{
case Started _:
context.SpawnNamed(childProps, "child");
break;
case Terminated terminated:
Console.WriteLine($"Terminated {terminated.Who}");
break;
}
return Task.CompletedTask;
}
)
.WithChildSupervisorStrategy(new OneForOneStrategy((pid, reason) => SupervisorDirective.Escalate, 0,
null
)
);
var rootContext = new RootContext(new ActorSystem());
rootContext.SpawnNamed(rootProps, "root");
Console.ReadLine();
}
19
Source : Program.cs
with Apache License 2.0
from asynkron
with Apache License 2.0
from asynkron
private static void Main()
{
var system = new ActorSystem();
//subscribe to the eventstream via type
system.EventStream.Subscribe<SomeMessage>(x => Console.WriteLine($"Got message for {x.Name}"));
//publish messages onto the eventstream
system.EventStream.Publish(new SomeMessage("ProtoActor"));
system.EventStream.Publish(new SomeMessage("Asynkron"));
//this example is local only.
//see ClusterEventStream for cluster broadcast onto the eventstream
Console.ReadLine();
}
19
Source : Program.cs
with Apache License 2.0
from asynkron
with Apache License 2.0
from asynkron
private static void Main()
{
var system = new ActorSystem();
//subscribe to the eventstream via type
system.EventStream.SubscribeToTopic<SomeMessage>("MyTopic.*", x => Console.WriteLine($"Got message for {x.Name}"));
//publish messages onto the eventstream on Subtopic1 on MyTopic root
system.EventStream.Publish(new SomeMessage("ProtoActor", "MyTopic.Subtopic1"));
//this message is published on a topic that is not subscribed to, and nothing will happen
system.EventStream.Publish(new SomeMessage("Asynkron", "AnotherTopic"));
//send a message to the same root topic, but another child topic
system.EventStream.Publish(new SomeMessage("Do we get this?", "MyTopic.Subtopic1"));
//this example is local only.
//see ClusterEventStream for cluster broadcast onto the eventstream
Console.ReadLine();
}
19
Source : Program.cs
with Apache License 2.0
from asynkron
with Apache License 2.0
from asynkron
private static async Task Main()
{
//Configure ProtoActor to use Serilog
var l = LoggerFactory.Create(x => x.AddConsole().SetMinimumLevel(LogLevel.Information));
Log.SetLoggerFactory(l);
var remoteConfig = GrpcCoreRemoteConfig
.BindToLocalhost()
.WithProtoMessages(MessagesReflection.Descriptor);
var consulProvider =
new ConsulProvider(new ConsulProviderConfig());
var clusterConfig =
ClusterConfig
.Setup("MyCluster", consulProvider, new ParreplacedionIdenreplacedyLookup());
var system = new ActorSystem()
.WithRemote(remoteConfig)
.WithCluster(clusterConfig);
await system
.Cluster()
.StartMemberAsync();
Console.WriteLine("Started");
//subscribe to the eventstream via type, just like you do locally
system.EventStream.SubscribeToTopic<MyMessage>("MyTopic.*", x => Console.WriteLine($"Got message for {x.Name}"));
//publish messages onto the eventstream on Subtopic1 on MyTopic root
//but do this using cluster broadcasting. this will publish the event
//to the event stream on all the members in the cluster
//this is best effort only, if some member is unavailable, there is no guarantee replacedociated here
system.Cluster().BroadcastEvent(new MyMessage {
Name = "ProtoActor",
Topic = "MyTopic.Subtopic1"
});
//this message is published on a topic that is not subscribed to, and nothing will happen
system.Cluster().BroadcastEvent(new MyMessage {
Name = "Asynkron",
Topic = "AnotherTopic"
});
//send a message to the same root topic, but another child topic
system.Cluster().BroadcastEvent(new MyMessage
{
Name = "Do we get this?",
Topic = "MyTopic.Subtopic1"
}
);
//this example is local only.
//see ClusterEventStream for cluster broadcast onto the eventstream
Console.WriteLine("Done");
Console.ReadLine();
}
See More Examples