How to call Confirm dialog on IML? - c#

I've just started to use IMl (http://incframework.com/). Does anybody know how to call confirm dialog on IML?
I mean confirm function from JavaScript.
function conf(){
confirm('text')
}

You can use confirm on conditional
#(Html.When(JqueryBind.Click)
.OnSuccess(dsl =>
{
dsl.Self().Core().JQuery.Attributes.AddClass("progress-success")
.If(r => r.Is(() => !Selector.JS.Confirm("Yes or No")));
} )
.AsHtmlAttributes()
.ToButton("Are you sure ?"))
Please look at sandbox
Also if use Break with OnBegin you can stop multiple executable.
.OnBegin(dsl => dsl.Core().Break.If(r => r.Is(() => !Selector.JS.Confirm("Yes or No")))
.OnSuccess(dsl => { // something code })

:) Please take a look at this resource - http://incframework.com/en-US/TutorialConditional#Confirm

Related

Fluent validation Db password with user input

I would like to know what can I do to have properly running my code.
I want to validate the oldPassword enter by the user in the form against the password that is stored in the db. Is they are the same is good to go if are different raise an error.
So far I have this but I have errors and don't pretty sure how to fix it.
I have the function IsSameAsOldPassword but i dont know how to send the parameters.
RuleSet(() => RuleFor(x => x.OldPassword)
.Must((x) => IsSameAsOldPassword(x.Id, x.OldPassword))
.WithMessage("Old password incorrect"), RuleSets.Update);
private bool IsSameAsOldPassword(Guid id, string oldPassword)
{
var user = _userManager.FindByIdAsync(id.ToString());
return _userManager.CheckPasswordAsync(user.Result, oldPassword).Result;
}
Any improvement to the code will be welcome.
I just found a solution, hope this help someone else, we just need to remove the field. the final solution will be like this:
RuleSet(() =>
{
RuleFor(x => x)
.MustAsync((x, cancellation) => IsSameAsOldPassword(x))
.WithMessage("Old password incorrect");
}, RuleSets.Update);
private async Task<bool> IsSameAsOldPassword(UserSetInputModel userInputModel)
{
userInputModel.fieldToUse
}

ReactiveUI: Why do I have to specify the scheduler explicitly in "...Throttle..."when using the TestScheduler

I'm new to ReactiveUI. I have the following simple setup: a path to a csv can be specified and the containing datapoints will be displayed to the user (using oxyplot).
Now I'm trying to test the following subscription:
public GraphViewModel(IScreen hostScreen)
{
HostScreen = hostScreen;
setupGraphFormatting();
// Data Loading if path is valid
this.WhenAnyValue(viewModel => viewModel.PathToDataCsv)
.ObserveOn(RxApp.MainThreadScheduler)
.Throttle(TimeSpan.FromMilliseconds(500), RxApp.TaskpoolScheduler)
.Select(csvPath => csvPath?.Trim('"'))
.Where(csvPath => !string.IsNullOrEmpty(csvPath) && File.Exists(csvPath))
.Subscribe(csvPath =>
{
csvPath = csvPath?.Trim('"');
updatePlotModel(csvPath);
}, exception => {});
/* additional Code*/
}
And that's the corresponding UnitTest:
[Test]
public void If_PathToDataCsv_has_a_valid_value()
{
new TestScheduler().With(scheduler =>
{
string pathToValidCsvFile = "data.log";
var viewModel = new GraphViewModel(null);
scheduler.AdvanceByMs(1000);
viewModel.PathToDataCsv = pathToValidCsvFile;
scheduler.AdvanceByMs(1000);
viewModel.PlotModel.Series.Count.Should().Be(6);
});
}
My first implementation of WhenAnyValue didn't set any of the Schedulers specifically ( in Throttle and lacking any ObserverOn ):
public GraphViewModel(IScreen hostScreen)
{
HostScreen = hostScreen;
setupGraphFormatting();
// Data Loading if path is valid
this.WhenAnyValue(viewModel => viewModel.PathToDataCsv)
.Throttle(TimeSpan.FromMilliseconds(500))
.Select(csvPath => csvPath?.Trim('"'))
.Where(csvPath => !string.IsNullOrEmpty(csvPath) && File.Exists(csvPath))
.Subscribe(csvPath =>
{
csvPath = csvPath?.Trim('"');
updatePlotModel(csvPath);
}, exception => {});
/* additional Code*/
}
But then my Unittest failed. My assumption was that TestScheduler was being used for Throttle behind the scenes and I didn't have to do anything. Am I doing something wrong or is this the right way: If I want to use TestScheduler/TimeTravelâ„¢ I have to specify the schedulers the way I did?
Edit in response to Glenn Watsons answer:
Ok, now it's clear: The methods in question (Throttle, ObserverOn) of course do not use ReactiveUI's Schedulers, because these are methods from the Reactive Extensions Framework. So they can't be replaced implicitly by ReactiveUI in case of a UnitTest except I tell the methods to use the RxApp Schedulers...
RxApp provides the ThreadPoolScheduler when you are in release mode, and the testing scheduler when you are in unit test mode.
By default the reactive extensions (separate to ReactiveUI) will use their own default schedulers which are unaware of unit tests.

Single command line parameter to control Topshelf windows service

I've made a topshelf windows service that starts three tasks. But since it might happen that one of those task might crash (yes, I know about EnableServiceRecovery), it would be better to use one program to create 3 services with different names and install them using command line parameters.
So in theory the code would look like:
static void Main(string[] args)
{
// *********************Below is a TopShelf code*****************************//
HostFactory.Run(hostConfigurator =>
{
hostConfigurator.Service<MyService>(serviceConfigurator =>
{
serviceConfigurator.ConstructUsing(() => new MyService(args[0])); //what service we are using
serviceConfigurator.WhenStarted(myService => myService.Start()); //what to run on start
serviceConfigurator.WhenStopped(myService => myService.Stop()); // and on stop
});
hostConfigurator.RunAsLocalSystem();
//****************Change those names for other services*******************************************//
hostConfigurator.SetDisplayName("CallForwardService"+args[0]);
hostConfigurator.SetDescription("CallForward using Topshelf"+args[0]);
hostConfigurator.SetServiceName("CallForwardService"+args[0]);
hostConfigurator.SetInstanceName(args[0]);
});
}
But of course it won't, because (from what I've read) you can't simply use args[] but apparently you can use something like
Callforward.exe install --servicename:CallForward --instancename:Workshop
I am still not sure how to pass the parameter to be used later in the program (in example above you can see it in new MyService(args[0]))
Can I use single parameter to set up all three elements (name, instance and internal use)?
Solved using help from How can I use CommandLine Arguments that is not recognized by TopShelf?
string department = null;
// *********************Below is a TopShelf code*****************************//
HostFactory.Run(hostConfigurator =>
{
hostConfigurator.AddCommandLineDefinition("department", f => { department = f; });
hostConfigurator.ApplyCommandLine();
hostConfigurator.Service<MyService>(serviceConfigurator =>
{
serviceConfigurator.ConstructUsing(() => new MyService(department)); //what service we are using
serviceConfigurator.WhenStarted(myService => myService.Start()); //what to run on start
serviceConfigurator.WhenStopped(myService => myService.Stop()); // and on stop
});
hostConfigurator.EnableServiceRecovery(r => //What to do when service crashes
{
r.RestartService(0); //First, second and consecutive times
r.RestartService(1);
r.RestartService(1);
r.SetResetPeriod(1); //Reset counter after 1 day
});
hostConfigurator.RunAsLocalSystem();
//****************Change those names for other services*******************************************//
string d = "CallForwardService_" + department;
hostConfigurator.SetDisplayName(d);
hostConfigurator.SetDescription("CallForward using Topshelf");
hostConfigurator.SetServiceName(d);
});
This answer was posted as an edit to the question Single command line parameter to control Topshelf windows service by the OP Yasskier under CC BY-SA 3.0.

How to generate new Rx events when I click on a listbox

I have a simple WPF application that contains a list of link. I would like to select few of them, add them to a an "observable list" and subscribe to it. Then the observer callback will download the link, and will proceed the next one if any of sleep.
I would also be able to update my UI to let the user know that an item has been proceeded.
Could someone give me some help doing this
Many thanks.
I would use Observable.FromEventPattern to first convert the list box of link selection events into an Observable of Uri.
Next, i would write an extension method to download link.
public static IObservable<bool> DownloadLink(this IObservable<Uri> source)
{
return Observable.Create<bool>(observer =>
{
return source
.Subscribe(onNext: async link =>
{
using (var client = new System.Net.Http.HttpClient())
{
var result = await client.GetStringAsync(link);
if (isSuccess)
observer.OnNext(true);
else
observer.OnNext(false);
}
}, onError: observer.OnError, onCompleted: observer.OnCompleted);
});
}
Finally, hook it up.
uriObservable.DownloadLink().ObserveOnDispatcher().Subscribe( // update ui logic here );

Mocking a method with conditional arguments using Moq

I have a class that I am unit testing, to verify a specific exception condition is handled gracefully. To this end, I mock the method that is called internally to throw the exception.
my mocking setup looks like this:
fr.CallBase = true;
fr.Setup(m => m.PutFile(It.IsAny<IFileConnection>(), It.IsAny<string>(), It.IsAny<string>()))
.Throws(new System.IO.IOException("Test Exception", new System.Net.Sockets.SocketException()));
this does exactly what I want it to do.
Now, however, I want to test continuity by only throwing an exception for a specific value. I thought it should look like this:
fr.Setup(m => m.PutFile(It.IsAny<IFileConnection>(), It.Is<string>(a => a == "foo2.txt"), It.IsAny<string>()))
.Throws(new System.IO.IOException("Test Exception", new System.Net.Sockets.SocketException()));
...but this doesn't seem to work. What am I doing wrong?
Per request, the entire test:
[Test]
public void ManualRouteInterruptedInDownloadContinuesOn()
{
var firstRoute = this.UnitOfWork.GetFirstRoute();
Route r = this.UnitOfWork.GetRouteByID(firstRoute.RouteID);
r.RegExMatch = "^foo\\d.txt$";
r.Manual = true;
r.NotifyOfNewFiles = "me#company.com";
this.UnitOfWork.Save();
var fr = new Mock<ManualRouting>(r.RouteID);
fr.CallBase = true;
fr.Setup(m => m.GetFile(It.IsAny<IFileConnection>(), It.Is<string>(a => a == "foo2.txt"), It.IsAny<string>()))
.Throws(new System.IO.IOException("Test Exception", new System.Net.Sockets.SocketException()));
fr.Object.ExecuteRoute(firstRoute.RouteID);
Assert.IsTrue(fr.Object.Errors.Count == 1);
Assert.IsTrue(fr.Object.Matches.Count == 3);
}
There was someone who suggested in comments that I should try
It.Is<string>(a => Equals(a, "foo2.txt"))
He cited some oddness with generics. I don't know if it had anything to do with generics, but this change did in fact work. Since the poster deleted his comment, I am making the answer in his stead.
I think that
m.PutFile(It.IsAny<IFileConnection>(), "foo2.txt")
should work
How do the internals of fr ever know to call GetFile with foo2.txt as the file name? It seems like you're setting up your test specification broadly (^foo\\d.txt$) but your mock narrowly (foo2.txt), shouldn't it be the other way around?

Categories