I am working on adding Nancy Framework to my C# console application (followed the very short tutorial here and it loads a blank page when I go to http://localhost:1234 so I know it is starting, but it doesn't show my text properly. I have gone over my code various times, but don't see any issues.
I have added both Nancy and Nancy.Hosting.Self to my project.
static void Main(string[] args)
{
var nancyHost = new Nancy.Hosting.Self.NancyHost(new Uri("http://localhost:1234"));
nancyHost.Start();
Console.ReadLine();
nancyHost.Stop();
}
namespace DaemonApp
{
class MainModule : Nancy.NancyModule
{
public MainModule()
{
Get["/"] = parameters =>
{
return "Hello world!";
};
}
}
}
I added some print lines, and it never calls the module when I visit the page. Does anyone have any clue what the issue is?
I didn't make the Module class public, that fixed it instantly =/
Related
I am making an app using .NET MAUI and I am trying to implement custom handlers for specific instances of controls (ex. some entries should use a custom handler I created). To achieve this I followed the official MS docs for this. The following is the setup they tell me to use:
1.First make a subclass of the Entry control:
using Microsoft.Maui.Controls;
namespace MyMauiApp
{
public class MyEntry : Entry
{
}
}
2.I then customize the EntryHandler to perform the desired modification to MyEntry instances:
using Microsoft.Maui;
using Microsoft.Maui.Controls;
using Microsoft.Maui.Graphics;
namespace MauiApp1
{
public partial class App : Application
{
public App()
{
InitializeComponent();
Microsoft.Maui.Handlers.EntryHandler.EntryMapper[nameof(IView.Background)] = (handler, view) =>
{
if (view is MyEntry)
{
#if __ANDROID__
handler.NativeView.SetBackgroundColor(Colors.Red.ToNative());
#elif __IOS__
handler.NativeView.BackgroundColor = Colors.Red.ToNative();
handler.NativeView.BorderStyle = UIKit.UITextBorderStyle.Line;
#elif WINDOWS
handler.NativeView.Background = Colors.Red.ToNative();
#endif
}
};
}
}
}
PROBLEM: This gives me the following error:
Severity Code Description Project File Line Suppression State
Error CS0021 Cannot apply indexing with [] to an expression of type
'IPropertyMapper<IEntry, EntryHandler>' MyMauiApp (net6.0-android),
MyMauiApp (net6.0-ios), MyMauiApp
(net6.0-windows10.0.19041) C:\Users\xxxxxx\source\repos\MyMauiApp\MyMauiApp\App.xaml.cs 24 Active
As I said I followed the docs completely but still this error. I have read that other people have this issue too. Can anyone help?
It seems some breaking changes have been made in this area by the means of this pr here and here.
From what it looks like this has been done so that you can cascade customizations in mappers with AppendToMapping and PrependToMapping or modify the whole mapping altogether with ModifyMapping.
Without explaining all the variations here, let's focus on your situation. This means that instead of this line Microsoft.Maui.Handlers.EntryHandler.EntryMapper[nameof(IView.Background)] = (handler, view) =>
You should now declare this as: Microsoft.Maui.Handlers.EntryHandler.EntryMapper.AppendToMapping(nameof(IView.Background), (handler, view) =>
Note that you should now add a ) on the closing bracket too, making the full code:
Microsoft.Maui.Handlers.EntryHandler.EntryMapper.AppendToMapping(nameof(IView.Background), (handler, view) =>
{
if (view is MyEntry)
{
#if __ANDROID__
handler.NativeView.SetBackgroundColor(Colors.Red.ToNative());
#elif __IOS__
handler.NativeView.BackgroundColor = Colors.Red.ToNative();
handler.NativeView.BorderStyle = UIKit.UITextBorderStyle.Line;
#elif WINDOWS
handler.NativeView.Background = Colors.Red.ToNative();
#endif
}
});
I will see if I can update the Docs here and there and hopefully this won't break again ;)
Edit: Updated the wiki page for this
I am using extent Reports in my specflow unit tests.
I have 2 projects in 1 solution. I have a separate project for creating a hook file which will be common for both the projects.
I need to initialize my extentreports object in BeforeTestRun hook and use it in BeforeScenario.
I am not getting a way to access the same.
Here is my code so far :
public static void BeforeFeature()
{
extentReports = new ExtentReports();
htmlReporter = new ExtentHtmlReporter(FeatureContext.Current.FeatureInfo.Title + ".html");
htmlReporter.Configuration().Theme = Theme.Dark;
extentReports.AttachReporter(htmlReporter);
TestcaseConst._logger = LogManager.GetCurrentClassLogger();
FeatureContext.Current.Set<ExtentReports>(extentReports);
}
[BeforeScenario]
public static void BeforeScenario()
{
extentTest = FeatureContext.Current.Get<ExtentReports>().CreateTest(ScenarioContext.Current.ScenarioInfo.Title, "This test is to check the status of API under test");
ScenarioContext.Current.Set<ExtentTest>(extentTest);
}
Now, I need to shift this code under BeforeFeature to BeforeTestRun, but I am not getting to save something like this "FeatureContext.Current.Set(extentReports);" in BeforeTestRun.
Please help if anyone knows.
Thanks In Advance.
In the MSDN documentation for the ClaimsAuthorizationManager class, it says "You can configure your application to use a claims authorization manager ... programmatically by using the IdentityConfiguration class...". Unfortunately, neither that page nor the page for the IdentityConfiguration class have any examples of doing so. All of their examples make use of the app.config file to specify a custom ClaimsAuthorizationManager class.
I'm trying to push all of my security code into a separate library. I don't want to have to remember to copy sections of the app.config file from that library into each project that uses it.
I found a similar question regarding a custom ClaimsAuthorizationManager and DI. Sadly, that user is using something called Thinktecture.IdentityModel and their answer lies in that component and so is not available to me. However, a note on the ClaimsPrincipalPermissionAttribute class page mentions hooking into the FederationConfigurationCreated event and that appears to be how the Thinktecture.IdentityModel does it. So I tried...
class Program {
static void Main (string[] args) {
SecurityHelper s = new SecurityHelper ();
FederatedAuthentication.FederationConfigurationCreated += s.FederatedAuthentication_FederationConfigurationCreated;
SetCurrentPrincipal ();
ShowMeTheCode ();
Console.ReadLine ();
}
private static void SetCurrentPrincipal () {
WindowsPrincipal incomingPrincipal = new WindowsPrincipal (WindowsIdentity.GetCurrent ());
Thread.CurrentPrincipal = FederatedAuthentication.FederationConfiguration.IdentityConfiguration.ClaimsAuthenticationManager.Authenticate ("none", incomingPrincipal);
}
[ClaimsPrincipalPermission (SecurityAction.Demand, Operation = "List networks", Resource = "Network")]
private static void ShowMeTheCode () {
Console.WriteLine ("Console.WriteLine");
}
}
public class SecurityHelper {
public void FederatedAuthentication_FederationConfigurationCreated (object sender, System.IdentityModel.Services.Configuration.FederationConfigurationCreatedEventArgs e) {
e.FederationConfiguration.IdentityConfiguration.ClaimsAuthenticationManager = new CustomClaimsTransformer ();
e.FederationConfiguration.IdentityConfiguration.ClaimsAuthorizationManager = new CustomAuthorizationManager ();
}
}
This just throws an "InvalidOperationException" with a message of "Could not load the identity configuration because no configuration section was found." I'm guessing it's because the event occurs when the FederationConfiguration property is accessed for the first time by one of the HTTP modules in the web application and I'm testing in a console application.
I have these requirements coming from client every week for some new logic or verification. For which I have to code new logic (basically some if-else and loops) and launch a new build for him. I want to avoid it by simply coding my logic in visual studio then writing a utility to export it to XML or something and send it to client via e-mail. He just have to place this file in some appropriate folder and the application will behave considering this logic.
Please suggest some solutions. My platform is C# Asp.Net.
Thanks
Using .NET 4.6 and the NuGetPackage Microsoft.CodeAnalysis.Scripting you could implement a scripting engine to run your c# code residing in a textfile without building an assembly.
Install NuGet Package:
Install-Package Microsoft.CodeAnalysis.Scripting.CSharp
Implement TestClass with some basic C#-Code-Content:
class Program
{
static void Main(string[] args)
{
TestScript();
}
private static async void TestScript()
{
// Code snippet: a class with one string-property.
string codeContent = #" using System;
public class ScriptedClass
{
public string HelloWorld { get; set; }
public ScriptedClass()
{
HelloWorld = ""Hello Roslyn!"";
}
}
new ScriptedClass().HelloWorld";
// Instanciate CSharpScriptEngine
var engine = new CSharpScriptEngine();
// Execute code and return string property (HelloWorld)
var scriptingState = await engine.ExecuteAsync(codeContent);
// Print return value from CSharpScript
Console.WriteLine("Returned from CSharpScript: {0}", scriptingState.ReturnValue);
Console.WriteLine("Press any key to continue.");
Console.ReadKey();
}
}
Implement a ScriptingEngine:
internal sealed class CSharpScriptEngine
{
public async Task<ScriptState<object>> ExecuteAsync(string codeContent)
{
// Add references from calling assembly
ScriptOptions options = ScriptOptions.Default.AddReferences(Assembly.GetExecutingAssembly());
// Run codeContent with given options
return await CSharpScript.RunAsync(codeContent, options);
}
}
Read ScriptCode from textfile:
So basically you could read some csharpcode from a textfile of your choice and run them on the fly:
private static async void TestScript()
{
// Read in script file
string codeContent = File.ReadAllText(#"C:\Temp\CSharpScriptTest.cs");
var engine = new CSharpScriptEngine();
// Run script
var scriptingState = await engine.ExecuteAsync(codeContent);
Console.WriteLine("Returned from CSharpScript: {0}", scriptingState.ReturnValue);
Console.WriteLine("Press any key to continue.");
Console.ReadKey();
}
In case you are wondering how all of this works under the hood, Roslyn will create a so called submission from your script code. A submission is an in memory assembly containing the types generated around your script code, which can be identified among the assemblies in the current AppDomain by a ℛ prefix in the name.
The precise implementation details are not important here (though, for example, scriptcs heavily relies on understanding in detail how Roslyn works to provide its extra features), but it's important to know that submissions can be chained together. When they are chained, variables, methods or classes defined in an earlier submission are available to use in subsequent submissions, creating a feature of a C# REPL (read-evaluate-print loop).
C# and Visual Basic - Use Roslyn to Write a Live Code Analyzer for Your API
Hope it helps
I've been trying to evaluate XSockets but it appears I've hit my first stumbling block pretty early. I can connect to Generic controller just fine but custom controllers do not seem to work at all - I get a custom message: "The handler name was not found in loaded plugins". A Google search shows one other person having this problem in SE, but their solution did not work for me.
I've created a console project and installed the latest XSockets 3.03 from NuGet. My code is below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using XSockets.Core.Common.Socket;
using XSockets.Core.XSocket;
using XSockets.Core.XSocket.Helpers;
using XSockets.Core.Common.Socket.Event.Interface;
namespace XSockets2
{
class Program
{
static void Main(string[] args)
{
using (var server = XSockets.Plugin.Framework.Composable.GetExport<IXSocketServerContainer>())
{
Console.WriteLine("running!");
server.StartServers();
Console.ReadLine();
server.StopServers();
}
}
}
public class TestCont: XSocketController
{
public override void OnMessage(ITextArgs textArgs)
{
this.SendToAll(textArgs);
}
}
}
And my Javascript
function connect2() {
var host = "ws://localhost:4502/testcont";
var conn;
conn = new XSockets.WebSocket(host);
conn.on(XSockets.Events.open, function (clientInfo) {
message(clientInfo.ClientGuid); //appends message to textarea
console.log('Open', clientInfo);
});
conn.on('OnMessage', function (d) {
message(d);
console.log('Message', d);
});
conn.on(XSockets.Events.onError, function (err) {
message(err.CustomMessage);
console.log('Error', err);
});
conn.on(XSockets.Events.close, function () {
message('Closed');
console.log('Closed');
});
First of all the latest version is 3.0.2 (not 3.0.3) but that is not important :)
There is a well known and documented bug in the plugin framework for the latest version. The bug only affect you if you run a console application (or any other *.exe) project since xsockets by default only looks in *.dll and not *.exe.
The issue and work around is described here
But your code will not work anyway since you have an error (from what I can see).
Your controller is named "TestCont" but you connect to "testcont". The connectionstring is case sensitive.
EDIT: I also think you are missunderstanding the method OnMessage since you have added a subscription to that exact name.