I recently download Nlog.dll from internet and add it into references part of project I'm writing code in C#. But even ready codes doesn't work in my simple console application. For the beginning I write it into my simple console application
As you can see here even some method of ondefined on other panel there is NLog classes located. How I can configure NLog from code?
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NLog;
using NLog.Config;
namespace ConsoleApplication1
{
class Program
{
private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
static void Main(string[] args)
{
var config = new NLog.Config.LoggingConfiguration();
var logfile = new NLog.Targets.FileTarget("logfile") { FileName = "file.txt" };
var logconsole = new NLog.Targets.ConsoleTarget("logconsole");
config.AddRule(LogLevel.Info, LogLevel.Fatal, logconsole);
config.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile);
NLog.LogManager.Configuration = config;
var logger = NLog.LogManager.GetCurrentClassLogger();
logger.Info("Hello World");
}
}
}
I get this error (in Russian language):
The code is correct for the latest version of NLog on NuGet. The .dll you downloaded seems to be an older version of NLog.
Related
Greetings stackoverflow community,
I am trying to compile and run the programcode from this website:
https://social.msdn.microsoft.com/Forums/en-US/7bdafd2a-be91-4f4f-a33d-6bea2f889e09/c-sample-for-automating-ms-edge-chromium-browser-using-edge-web-driver
I followed all the instructions listed in the link and set my paths were I wanted them.
The program and the edge driver starts running, but then an error appears.
"An error exeption "System.InvalidOperationException" appeared in WebDriver.dll.
Further Inforamtion: session not created: No matching capabilities found (SessionNotCreated)"
This is the code from my program, more or less copied from the link above:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Edge;
using OpenQA.Selenium.Remote;
using OpenQA.Selenium.Support.UI;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
var anaheimService = ChromeDriverService.CreateDefaultService(#"C:\edgedriver_win64", "msedgedriver.exe");
// user need to pass the driver path here....
var anaheimOptions = new ChromeOptions
{
// user need to pass the location of new edge app here....
BinaryLocation = #"
C: \Program Files(x86)\Microsoft\Edge\Application\msedge.exe "
};
IWebDriver driver = new ChromeDriver(anaheimService, anaheimOptions); -- error appears at this line
driver.Navigate().GoToUrl("https: //google.com/");
Console.WriteLine(driver.Title.ToString());
driver.Close();
}
}
}
I would really appreciate your help!
Best Regards
Max
The article you refer to is a bit out of date. Now we don't need to use ChromeDriver to automate Edge. You can refer to the official doc about how to use WebDriver to automate Microsoft Edge.
I recommend using Selenium 4. Here I install Selenium 4.1.0 NuGet package and the sample C# code is like below:
using System;
using OpenQA.Selenium.Edge;
namespace WebDriverTest
{
class Program
{
static void Main(string[] args)
{
var options = new EdgeOptions();
options.BinaryLocation = #"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe";
var driver = new EdgeDriver(#"C:\edgedriver_win64", options);
driver.Navigate().GoToUrl("https://www.google.com");
Console.WriteLine(driver.Title.ToString());
driver.Close();
}
}
}
I'm trying to publish a web application with below code which uses Microsoft.Build.Evaluation libraries. However below execution fails for a project with error message mentioning to enable NuGet restore. The provided link in error message is not valid since it shows how to enable NuGet restore in Visual Studio IDE.
Please let me know how to enable NuGet when programmatically publishing a web app with Microsoft.Build.Evaluation.
Build FAILED.
C:\x\Dnn.Platform-development\DNN Platform\DotNetNuke.Web\DotNetNuke.Web.csproj(419,5): error : This project references NuGet package(s) that are missing on this computer.Enable NuGet Package Restore to download them.For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is ..\..\..\Evoq.Content\\.nuget\NuGet.targets.
0 Warning(s)
1 Error(s)
The source code used to publish the web application:
using B = Microsoft.Build.Evaluation;
using Microsoft.Build.Logging;
using Microsoft.Build.Framework;
using System.IO;
using System.Collections.Generic;
namespace WebPublisherTest
{
class Program
{
static private readonly string RootTempFolder = #"C:\TST";
static private readonly string PublishDropFolderName = "PublishDrop";
static private readonly string ToolVersion = "12.0";
static void Main(string[] args)
{
string projectFilePath = #"C:\x\Dnn.Platform-development\DNN Platform\Admin Modules\Dnn.Modules.Console\Dnn.Modules.Console.csproj";
string tempLocation = Path.Combine(RootTempFolder, Path.GetRandomFileName());
string publishDrop = Path.Combine(tempLocation, PublishDropFolderName);
var globalProperty = new Dictionary<string, string>
{
{ "Configuration", "Debug" },
{ "OutputPath", publishDrop },
{ "WebPublishMethod", "FileSystem" }
};
ConsoleLogger logger = new ConsoleLogger(verbosity: LoggerVerbosity.Normal);
B.Project p = new B.Project(projectFilePath, globalProperty, ToolVersion);
p.Build(new List<ILogger>() { logger });
}
}
}
I have a WPF C# application that contains a button.
The code of the button click is written in separate text file which will be placed in the applications runtime directory.
I want to execute that code placed in the text file on the click of the button.
Any idea how to do this?
Code sample for executing compiled on fly class method:
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Net;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
string source =
#"
namespace Foo
{
public class Bar
{
public void SayHello()
{
System.Console.WriteLine(""Hello World"");
}
}
}
";
Dictionary<string, string> providerOptions = new Dictionary<string, string>
{
{"CompilerVersion", "v3.5"}
};
CSharpCodeProvider provider = new CSharpCodeProvider(providerOptions);
CompilerParameters compilerParams = new CompilerParameters
{GenerateInMemory = true,
GenerateExecutable = false};
CompilerResults results = provider.CompileAssemblyFromSource(compilerParams, source);
if (results.Errors.Count != 0)
throw new Exception("Mission failed!");
object o = results.CompiledAssembly.CreateInstance("Foo.Bar");
MethodInfo mi = o.GetType().GetMethod("SayHello");
mi.Invoke(o, null);
}
}
}
You can use Microsoft.CSharp.CSharpCodeProvider to compile code on-the-fly. In particular, see CompileAssemblyFromFile.
I recommend having a look at Microsoft Roslyn, and specifically its ScriptEngine class.
Here are a few good examples to start with:
Introduction to the Roslyn Scripting API
Using Roslyn ScriptEngine for a ValueConverter to process user input.
Usage example:
var session = Session.Create();
var engine = new ScriptEngine();
engine.Execute("using System;", session);
engine.Execute("double Sin(double d) { return Math.Sin(d); }", session);
engine.Execute("MessageBox.Show(Sin(1.0));", session);
Looks like someone created a library for this called C# Eval.
EDIT: Updated link to point to Archive.org as it seems like the original site is dead.
What you need is a CSharpCodeProvider Class
There are several samples to understand how does it work.
1 http://www.codeproject.com/Articles/12499/Run-Time-Code-Generation-I-Compile-C-Code-using-Mi
The important point of this example that you can do all things on flay in fact.
myCompilerParameters.GenerateExecutable = false;
myCompilerParameters.GenerateInMemory = false;
2 http://www.codeproject.com/Articles/10324/Compiling-code-during-runtime
This example is good coz you can create dll file and so it can be shared between other applications.
Basically you can search for http://www.codeproject.com/search.aspx?q=csharpcodeprovider&x=0&y=0&sbo=kw&pgnum=6 and get more useful links.
I want to use the Bluetooth LE functions in .NET Core (specifically, BluetoothLEAdvertisementWatcher) to write a scanner which logs information to a file. This is to run as a desktop application and preferably as a command line app.
Constructors like System.IO.StreamWriter(string) are not available, apparently. How do I create a file and write to it?
I would be just as happy to be able to do a System.Console.WriteLine(string) but that doesn't seem to be available under .NET Core either.
Update: To clarify, if I could have a program that looks like this run without error, I'll be off to the races.
using System;
using Windows.Devices.Bluetooth.Advertisement;
namespace ConsoleApplication
{
public class Program
{
public static void Main(string[] args)
{
BluetoothLEAdvertisementWatcher watcher = new BluetoothLEAdvertisementWatcher();
Console.WriteLine("Hello, world!");
}
}
}
Update 2: Here's the project.json file:
{
"dependencies": {
"Microsoft.NETCore.UniversalWindowsPlatform": "5.0.0"
},
"frameworks": {
"uap10.0": {}
},
"runtimes": {
"win10-arm": {},
"win10-arm-aot": {},
"win10-x86": {},
"win10-x86-aot": {},
"win10-x64": {},
"win10-x64-aot": {}
}
}
The output of the command dotnet -v run contains this error message:
W:\src\dotnet_helloworld>dotnet -v run
...
W:\src\dotnet_helloworld\Program.cs(2,15): error CS0234: The type or namespace name 'Devices' does not exist in the namespace 'Windows' (are you missing an assembly reference?)
...
This code is the skeleton I was looking for when I posed the question. It uses only facilities available in .NET Core.
var watcher = new BluetoothLEAdvertisementWatcher();
var logPath = System.IO.Path.GetTempFileName();
var logFile = System.IO.File.Create(logPath);
var logWriter = new System.IO.StreamWriter(logFile);
logWriter.WriteLine("Log message");
logWriter.Dispose();
This is the solution I'm using. It uses fewer lines of code and does the job just as good. It's also very compatible with .NET core 2.0
using (StreamWriter writer = System.IO.File.AppendText("logfile.txt"))
{
writer.WriteLine("log message");
}
Even better:
using System.IO;
var logPath = Path.GetTempFileName();
using (var writer = File.CreateText(logPath)) // or File.AppendText
{
writer.WriteLine("log message"); //or .Write(), if you wish
}
If writing fewer lines of code is your thing, the above can be re-written as
using (var writer = System.IO.File.CreateText(System.IO.Path.GetTempFileName()))
{
writer.WriteLine("log message"); //or .Write(), if you wish
}
As of today, with RTM, there seems to be this shorter way as well:
var watcher = new BluetoothLEAdvertisementWatcher();
var logPath = System.IO.Path.GetTempFileName();
var logWriter = System.IO.File.CreateText(logPath);
logWriter.WriteLine("Log message");
logWriter.Dispose();
To write to files in .NET Core, you can use two methods:
AppendText()
CreateText()
These two methods are static members of the File class in the System.IO namespace. The difference between them is one appends to an existing file while the other overwrites the file.
Usage examples:
AppendText
using (StreamWriter writer = System.IO.File.AppendText("file.txt"))
{
writer.WriteLine("message");
}
CreateText
using (StreamWriter writer = System.IO.File.CreateText("file.txt"))
{
writer.WriteLine("message");
}
You can get the System.IO references by using the corefx git repository. This will make the StreamWrite(string) constructor you are looking for available.
This repository will also give you the Console.WriteLine(string) function you are looking for.
Here is an async FileWriter class.
using System.IO;
public static class AsyncFileWriter
{
public static async Task WriteToFile(string content)
{
var logPath = #"SOME_PATH\log.txt";
using (var writer = File.CreateText(logPath))
{
await writer.WriteLineAsync(content);
}
}
}
I have a WPF C# application that contains a button.
The code of the button click is written in separate text file which will be placed in the applications runtime directory.
I want to execute that code placed in the text file on the click of the button.
Any idea how to do this?
Code sample for executing compiled on fly class method:
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Net;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
string source =
#"
namespace Foo
{
public class Bar
{
public void SayHello()
{
System.Console.WriteLine(""Hello World"");
}
}
}
";
Dictionary<string, string> providerOptions = new Dictionary<string, string>
{
{"CompilerVersion", "v3.5"}
};
CSharpCodeProvider provider = new CSharpCodeProvider(providerOptions);
CompilerParameters compilerParams = new CompilerParameters
{GenerateInMemory = true,
GenerateExecutable = false};
CompilerResults results = provider.CompileAssemblyFromSource(compilerParams, source);
if (results.Errors.Count != 0)
throw new Exception("Mission failed!");
object o = results.CompiledAssembly.CreateInstance("Foo.Bar");
MethodInfo mi = o.GetType().GetMethod("SayHello");
mi.Invoke(o, null);
}
}
}
You can use Microsoft.CSharp.CSharpCodeProvider to compile code on-the-fly. In particular, see CompileAssemblyFromFile.
I recommend having a look at Microsoft Roslyn, and specifically its ScriptEngine class.
Here are a few good examples to start with:
Introduction to the Roslyn Scripting API
Using Roslyn ScriptEngine for a ValueConverter to process user input.
Usage example:
var session = Session.Create();
var engine = new ScriptEngine();
engine.Execute("using System;", session);
engine.Execute("double Sin(double d) { return Math.Sin(d); }", session);
engine.Execute("MessageBox.Show(Sin(1.0));", session);
Looks like someone created a library for this called C# Eval.
EDIT: Updated link to point to Archive.org as it seems like the original site is dead.
What you need is a CSharpCodeProvider Class
There are several samples to understand how does it work.
1 http://www.codeproject.com/Articles/12499/Run-Time-Code-Generation-I-Compile-C-Code-using-Mi
The important point of this example that you can do all things on flay in fact.
myCompilerParameters.GenerateExecutable = false;
myCompilerParameters.GenerateInMemory = false;
2 http://www.codeproject.com/Articles/10324/Compiling-code-during-runtime
This example is good coz you can create dll file and so it can be shared between other applications.
Basically you can search for http://www.codeproject.com/search.aspx?q=csharpcodeprovider&x=0&y=0&sbo=kw&pgnum=6 and get more useful links.