How to stop running process in c# - javascript

I am calling a same function in parallel using Task.WhenAll(); and I was wondering if there is any way we can stop all threads /process if stop button is clicked? Also I do not want browser to be closed. can anyone suggest me what approach I should use?
[HttpPost]
public async Task<IActionResult> Runcase(List<string> products,string runnumber,string button)
{
try
{
if (ModelState.IsValid)
{
var productinfo = products;
List<string> productids = new List<string>(productinfo);
var runnum = runnumber;
string runid = "";
int count = productids.Count();
List<Task> tasks = new List<Task>();
int rawid = 0;
for (int i = 0; i < count; i++)
{
tasks.Add(RunServiceAsync(productids[i], runnum,rawid));
}
await Task.WhenAll(tasks);
ViewBag.completed = "Success";
return View();
}
else
{
ViewBag.productinfo = new MultiSelectList(_context.inputValuesConfigurations, "ProductID", "ProductName");
ModelState.AddModelError(string.Empty, "Please enter a valid data...");
return View();
}
}
catch(Exception ex)
{
return View();
}
}

Related

bytes32 to string in javascript

currently i'm working on a ethereum dapp(voting), in my smart contract i have a function to fetch candidate list of type bytes32[] , on the java script side i'm not getting the values instead 0x only
How to parse the value , below is the code
pragma solidity ^0.4.0;
contract Voting {
mapping (bytes32 => uint8) public votesReceived;
bytes32[] public candidateList;
string myString = "someString";
function Voting(bytes32[] candidateNames) public {
candidateList = candidateNames ;
}
function totalVotesFor(bytes32 candidate) view public returns (uint8) {
return votesReceived[candidate];
}
function addCandidate(bytes32 candidate) public returns (bool){
require(isNewEntry(candidate));
candidateList.push(candidate);
return isNewEntry(candidate);
}
function voteForCandidate(bytes32 candidate) public {
require(validCandidate(candidate));
votesReceived[candidate] += 1;
}
function getCandidateList() view public returns (bytes32[]) {
return candidateList;
}
function isNewEntry(bytes32 candidate) view public returns (bool) {
for(uint i = 0; i < candidateList.length; i++) {
if (candidateList[i] == candidate) {
return false;
}
}
return true;
}
function validCandidate(bytes32 candidate) view public returns (bool) {
for(uint i = 0; i < candidateList.length; i++) {
if (candidateList[i] == candidate) {
return true;
}
}
return false;
}
}
below is the code to access the contract function
Voting.deployed().then(function(contractInstance) {
contractInstance.getCandidateList.call().then(function(v) {
console.log(v)
});
})
someone please help me
Assuming you're using web3 on the JS side, it's web3.toAscii.
Example from the docs:
var str = web3.toAscii("0x657468657265756d000000000000000000000000000000000000000000000000");
console.log(str); // "ethereum"

reset the form data after submission in struts

I am very new to struts and the application is using struts , and every time I submit the form the old values are submitted until and unless I change the values by selecting different options from drop down or I go to other tab and come back again to the same tab then in this case the values are resetting..
In my scenario what I want to achieve is to reset some of the values after they executed once.on the basis of those values I have to search some data and show it on the form, if I don't remove this value then it .
This is my execute method :
public class ListTerminalDevicesAction extends BaseQueryAction {
private RetailerService retailerService;
private DataBinder<OmposTerminalQuery> dataBinder;
private TerminalDeviceService terminalDeviceService;
private ImportCSVService importCSVService;
#Inject
public void setImportCSVService(ImportCSVService importCSVService) {
this.importCSVService = importCSVService;
}
#Inject
public void setRetailerService(final RetailerService retailerService) {
this.retailerService = retailerService;
}
#Inject
public void setTerminalDeviceService(final TerminalDeviceService terminalDeviceService) {
this.terminalDeviceService = terminalDeviceService;
}
#Inject
private DataBinder<OmposTerminalQuery> getDataBinder() {
if (dataBinder == null) {
final BeanBinder<OmposTerminalQuery> binder = BeanBinder.instance(OmposTerminalQuery.class);
binder.registerBinder("pageParameters", DataBinderHelper.pageBinder());
binder.registerBinder("retailer", PropertyBinder.instance(OmposRetailer.class, "retailer"));
binder.registerBinder("branch", PropertyBinder.instance(OmposBranch.class, "branch"));
binder.registerBinder("store", PropertyBinder.instance(OmposStore.class, "store"));
binder.registerBinder("terminalId", PropertyBinder.instance(String.class, "terminalId"));
binder.registerBinder("terminalSearchByTid",
PropertyBinder.instance(String.class, "terminalSearchByTid"));
dataBinder = binder;
}
return dataBinder;
}
#Override
protected void executeQuery(ActionContext context, QueryParameters queryParameters) {
final OmposTerminalQuery query = (OmposTerminalQuery) queryParameters;
query.setResultType(ResultType.PAGE);
// List<OmposRetailer> retailerList = retailerService.searchRetailers();
// context.getRequest().setAttribute("retailers", retailerList);
// if (query.getRetailer() != null) {
// OmposBranchQuery branchQuery = new OmposBranchQuery();
// branchQuery.setOmposRetailer(query.getRetailer());
// List<OmposBranch> branchList = retailerService.searchBranchByRetailer(branchQuery);
// context.getRequest().setAttribute("branches", branchList);
// if (query.getBranch() != null) {
// OmposStoreQuery storeQuery = new OmposStoreQuery();
// storeQuery.setOmposBranch(query.getBranch());
// List<OmposStore> storeList = retailerService.searchStore(storeQuery);
List<OmposStore> storeList = retailerService.searchStores();
context.getRequest().setAttribute("stores", storeList);
if (query.getStore() != null) {
ListTerminalDevicesForm form = context.getForm();
final FormFile uploadTerminal = form.getUploadTerminal();
if (uploadTerminal != null && uploadTerminal.getFileSize() != 0) {
try {
ImportCSVDTO uploadDtoForTerminal = new ImportCSVDTO();
// uploadDtoForTerminal.setRetailer(query.getRetailer());
// uploadDtoForTerminal.setBranch(query.getBranch());
uploadDtoForTerminal.setStore(query.getStore());
int records = importCSVService.importCSV(TMSEntity.TERMINAL, uploadDtoForTerminal,
uploadTerminal.getInputStream());
if (records > 0) {
context.getRequest().setAttribute("uploadMsgTerminal", records);
}
} catch (final UnknownColumnException | IOException e) {
// context.sendError("general.error.csv.unknownColumn",
// e.getColumn());
} finally {
uploadTerminal.destroy();
}
}
OmposTerminalQuery terminalQuery = new OmposTerminalQuery();
List<OmposTerminal> terminalList = null;
if (query.getStore() != null && query.getTerminalSearchByTid() != null) {
terminalQuery.setTerminalSearchByTid(query.getTerminalSearchByTid());
terminalQuery.setStore(query.getStore());
terminalList = terminalDeviceService.searchTerminalByTidAndStoreId(terminalQuery);
} else {
terminalQuery.setStore(query.getStore());
terminalList = terminalDeviceService.searchByStore(terminalQuery);
}
context.getRequest().setAttribute("terminals", terminalList);
if (query.getTerminalId() != null) {
OmposTerminal omposTerminal = new OmposTerminal();
omposTerminal.setTerminalId(query.getTerminalId());
OmposDeviceQuery deviceQuery = new OmposDeviceQuery();
deviceQuery.setOmposTerminal(omposTerminal);
final FormFile uploadDevice = form.getUploadDevice();
if (uploadDevice != null && uploadDevice.getFileSize() != 0) {
try {
ImportCSVDTO uploadDtoForDevice = new ImportCSVDTO();
uploadDtoForDevice.setRetailer(query.getRetailer());
uploadDtoForDevice.setBranch(query.getBranch());
uploadDtoForDevice.setStore(query.getStore());
uploadDtoForDevice.setTerminal(new OmposTerminal(null, query.getTerminalId(), null));
int records = importCSVService.importCSV(TMSEntity.DEVICE, uploadDtoForDevice,
uploadDevice.getInputStream());
if (records > 0) {
context.getRequest().setAttribute("uploadMsgDevice", records);
}
} catch (final UnknownColumnException | IOException e) {
// context.sendError("general.error.csv.unknownColumn",
// e.getColumn());
} finally {
uploadDevice.destroy();
}
}
context.getRequest().setAttribute("terminalId", query.getTerminalId());
List<OmposDevice> deviceList = terminalDeviceService.searchByTerminal(deviceQuery);
context.getRequest().setAttribute("devices", deviceList);
}
}
// }
// }
}
#Override
protected QueryParameters prepareForm(ActionContext context) {
final ListTerminalDevicesForm form = context.getForm();
final OmposTerminalQuery query = getDataBinder().readFromString(form.getQuery());
return query;
}
#Override
protected boolean willExecuteQuery(final ActionContext context,
final QueryParameters queryParameters) throws Exception {
return true;
}
}
I have to reset "terminalSearchByTid" field after the execution.
override Struts' Action reset() method

Online test system asp.net mvc

I am able to display the questions by id but dont know how to randomly display them for different users and everytime the user logs in a new random combination is initiated.
can someone guide?
My Controller:-
public ActionResult Index()
{
var question = Quiz.Instance.LoadQuiz();
return View(question);
}
[HttpPost]
public ActionResult Index(string Opt)
{
if (Quiz.Instance.IsComplete)
{
return RedirectToAction("ShowResult");
}
Quiz.Instance.SaveAnswers(Opt);
if (Quiz.Instance.MovetoNext())
{
var question = Quiz.Instance.LoadQuiz();
return View(question);
}
Quiz.Instance.IsComplete = true;
return RedirectToAction("ShowResult");
}`
Quiz repository:
public Question_OptionViewModel LoadQuiz()
{
var questions = db.Questions.Find(Q_ID);
var options = from o in db.Options
select o;
options = options.Where(o => o.Q_Id == Q_ID);
var viewmodel = new Question_OptionViewModel()
{
Question = questions,
Options = options
};
return viewmodel;
}
public void SaveAnswers(string answer)
{
Attempt at = new Attempt()
{
Q_Id = Q_ID,
Answer = answer,
Registration_number = 1312153
};
db.Attempts.Add(at);
db.SaveChanges();
var questions = db.Questions.Where(q => q.Q_Id == Q_ID).First();
if (at.Answer == questions.Correct_Ans)
{
result.Score++;
}
}
public bool MovetoNext()
{
int questions = db.Questions.Where(q => q.Test_Id == 1).Count();
bool canmove = false;
if (questions > Q_ID)
{
Q_ID++;
canmove = true;
}
return canmove;
}
My view:-
#model OnlineTestSystem.ViewModels.Question_OptionViewModel
#{
ViewBag.Title = "Quiz";
}
$("#submitButton").live("click", function () {
$.get($(this), function (response) {
$("#quiz").replaceWith($("#quiz", response));
});
return false;
});
});
<div id="quiz" style="text-align:center">
#using (Html.BeginForm("Index", "Test"))
{
<fieldset>
<legend><h2>#Model.Question.QuestionText</h2></legend>
<li>
#foreach (var opt in Model.Options)
{
<ul class="list-inline" style="font-size:17px">
#Html.RadioButton("Opt", #opt.Opt) #opt.Opt
</ul>
}
</li>
<input class="btn btn-default" type="submit" value="Next" id="submitButton" />
</fieldset>
}
</div>
``
You could just simply randomize your question by using a Shuffle algorithm. You can use Fisher-Yates algorithm to randomize your questions.
You could encapsulate the algorithm in an extension method like this:
public static class Extensions
{
private static Random rnd = new Random();
public static void Shuffle<T>(this IList<T> collection)
{
int n = collection.Count;
while (n > 1)
{
n--;
int k = rnd.Next(n + 1);
T value = collection[k];
collection[k] = collection[n];
collection[n] = value;
}
}
}
Then on your LoadQuiz method, you may call the Shuffle extension method.
var questions = db.Questions.Find(Q_ID).ToList().Shuffle();
You may also take a look on this SO post

Validating ReCaptcha (Javascript API) User Answer on Localhost with ASP.NET

I am using ReCaptcha with the javascript API on my aspx page on localhost. I read somewhere that I don't need a key as long as I use it on localhost. So, I use some random key that I found somewhere. I could render the recaptcha challenge successfully. The following is my javascript code.
Recaptcha.create("6Ld4iQsAAAAAAM3nfX_K0vXaUudl2Gk0lpTF3REf", 'captchadiv',
{
tabindex: 1,
theme: "clean",
callback: Recaptcha.focus_response_field
});
//To Validate user response
function Recaptcha_IsCorrect()
{
var xmlHttpRequest;
var PageURL = document.URL;
var xmlDoc;
if (window.XMLHttpRequest)
{
xmlHttpRequest = new XMLHttpRequest();
}
else
{
xmlHttpRequest = new ActiveXObject("Microsoft.xmlHttpRequest");
}
var challenge = Recaptcha.get_challenge();
var userResponse = Recaptcha.get_response();
var url = "../Ajax/PIAsyncAjax.asmx/ValidateReCaptcha?clientIP=127.0.0.1&privateKey=6Ld4iQsAAAAAAM3nfX_K0vXaUudl2Gk0lpTF3REf&challenge=" + challenge + "&response=" + userResponse;
xmlHttpRequest.open("GET", url);
xmlHttpRequest.onreadystatechange = function ()
{
if (xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200)
{
alert(xmlHttpRequest.responseText);
}
};
xmlHttpRequest.send();
}
The following is my code for the webservice which exposed the webmethod to validate ReCaptcha user input. I get the error "invalid-site-private-key".
namespace YADA.YADAYADA{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
public class PIAsyncAjax : System.Web.Services.WebService
{
[WebMethod]
public string ValidateReCaptcha(string clientIP, string privateKey, string challenge, string response)
{
bool isValid = false;
string validationResponse = "";
reCaptchaValidation validator =
new reCaptchaValidation(null,
clientIP,
privateKey,
challenge,
response);
isValid = validator.Validate();
if (isValid)
{
validationResponse = "true";
}
else
{
if (!validator.IsErrored)
{
validationResponse = "false";
}
else
{
// oh dear, something not right
if (validator.Exception != null) // an exception occurred while
// trying to validate
validationResponse = validator.Exception.ToString();
else if (validator.ValidationResult != null) // the validation web service
// returned an error code
// (other than an invalid captcha solution)
validationResponse = "web service error: " + validator.ValidationResult;
}
}
return validationResponse;
}
}
public class reCaptchaValidation
{
private string challenge, response, privateKey, ip;
private IWebProxy proxy;
public reCaptchaValidation(string clientIP, string privateKey,
string challenge, string response) : this(null, clientIP, privateKey,
challenge, response) { }
public reCaptchaValidation(IWebProxy proxy, string clientIP,
string privateKey, string challenge, string response)
{
this.proxy = proxy;
this.ip = clientIP;
this.privateKey = privateKey;
this.challenge = challenge;
this.response = response;
}
private bool _errored;
public bool IsErrored
{
get
{
return _errored;
}
}
private Exception _ex;
public Exception Exception
{
get
{
return _ex;
}
}
private string _vr;
public string ValidationResult
{
get
{
return _vr;
}
}
public bool Validate()
{
try
{
string post = "privatekey=" + HttpUtility.UrlEncode(privateKey) +
"&remoteip=" + HttpUtility.UrlEncode(ip) + "&challenge=" +
HttpUtility.UrlEncode(challenge) + "&response=" +
HttpUtility.UrlEncode(response);
WebRequest wr = HttpWebRequest.Create
("http://www.google.com/recaptcha/api/verify");
wr.Method = "POST";
if (proxy != null)
wr.Proxy = proxy;
wr.ContentLength = post.Length;
wr.ContentType = "application/x-www-form-urlencoded";
using (StreamWriter sw = new StreamWriter(wr.GetRequestStream()))
{
sw.Write(post);
sw.Close();
}
HttpWebResponse resp = (HttpWebResponse)wr.GetResponse();
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
string valid = sr.ReadLine();
if (valid != null)
{
if (valid.ToLower().Trim() == "false")
{
string errorcode = sr.ReadLine();
if (errorcode != null)
{
if (errorcode.ToLower().Trim() != "incorrect-captcha-sol")
{
_vr = errorcode;
_errored = true;
return false;
}
}
}
return (valid.ToLower().Trim() == "true");
}
else _vr = "empty web service response";
sr.Close();
return false;
}
}
catch (Exception caught)
{
_errored = true;
_ex = caught;
}
return false;
}
}}
What am I doing wrong? Should I have to get a private key? Any help would be great.
Thanks in advance,
Venkat.
It works with the public and private keys that I just created. Damn, I just assumed, "localhost" would not be accepted as a legal domain-name while signing up.

Get the javascript push object array in a MVC3 controller action

This is my javascript code:
var bankOptions = {};
var playerOptions = [];
bankOptions["BankTotalAmount"] = $("#totalBankAmountID").val();
bankOptions["SinglePlayerAmount"] = $("#singlePlayerAmountID").val();
while (_playerNumber != 0) {
if (_playerNumber == 1) {
var player1Option = {};
player1Option["Name"] = $("#p" + _playerNumber + "Name").val();
player1Option["Color"] = $("#p" + _playerNumber + "Color").val();
playerOptions.push(player1Option);
}
if (_playerNumber == 2) {
var player2Option = {};
player2Option["Name"] = $("#p" + _playerNumber + "Name").val();
player2Option["Color"] = $("#p" + _playerNumber + "Color").val();
playerOptions.push(player2Option);
}
if (_playerNumber == 3) {
var player3Option = {};
player3Option["Name"] = $("#p" + _playerNumber + "Name").val();
player3Option["Color"] = $("#p" + _playerNumber + "Color").val();
playerOptions.push(player3Option);
}
if (_playerNumber == 4) {
var player4Option = {};
player4Option["Name"] = $("#p" + _playerNumber + "Name").val();
player4Option["Color"] = $("#p" + _playerNumber + "Color").val();
playerOptions.push(player4Option);
}
_playerNumber--;
}
alert(playerOptions);
$.ajax({
url: "/StartOption/setOptions/",
contentType: 'application/json',
data: JSON.stringify({ bankOptions: bankOptions, playerOptions: playerOptions }),
type: "POST",
timeout: 10000,
success: function (result) {
}
});
and i have this Controller class
public class StartOptionController : Controller
{
private MonopolyDB db = new MonopolyDB();
//
// GET: /StartOption/
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult setOptions(BankOptions bankOptions, Playeroptions[] playerOptions)
{
//int length = (int)playerOptions.GetType().InvokeMember("length", BindingFlags.GetProperty, null, playerOptions, null);
BankAccount bankaccount = new BankAccount();
bankaccount.ID = 1;
bankaccount.TotalAmmount = bankOptions.BankTotalAmount;
db.BankAccount_Table.Add(bankaccount);
db.SaveChanges();
//Here i want to get each (player1Option, player2Option...) object array from that playerOptions object array
//return RedirectToAction("Index");
return View();
}
}
public class BankOptions
{
public int BankTotalAmount { get; set; }
public int SinglePlayerAmount { get; set; }
}
public class Playeroptions
{
public string Name { get; set; }
public string Color { get; set; }
}
My question is how i can get those object array that i push into playerOptions object array in my setOptions action?
as like i want to save each player info in my DB from playerOptions object array where i push each player info in my javascript code.
Well first to make it easy I would like to recommend that changes the sign of your action
from
public ActionResult setOptions(BankOptions bankOptions, Playeroptions[] playerOptions)
To
public ActionResult setOptions(BankOptions bankOptions, List<PlayerOptions> playerOptions)
That's it's going to make it easy the handle of each element of the array, and there's not problem for the framework to serialize this object.
Now to answer your question you could iterate the array like this
[HttpPost]
public ActionResult setOptions(BankOptions bankOptions, Playeroptions[] playerOptions)
{
//int length = (int)playerOptions.GetType().InvokeMember("length", BindingFlags.GetProperty, null, playerOptions, null);
BankAccount bankaccount = new BankAccount();
bankaccount.ID = 1;
bankaccount.TotalAmmount = bankOptions.BankTotalAmount;
db.BankAccount_Table.Add(bankaccount);
db.SaveChanges();
//Here i want to get each (player1Option, player2Option...) object array from that playerOptions object array
for ( int i = 0 ; i< playerOptions.Length, i++)
{
playerOptions[i]; //<-- this give's the specific element
}
//return RedirectToAction("Index");
return View();
}
Nevertheless if you follow my recommendation and changes the sign of your action you could iterate your code like this
[HttpPost]
public ActionResult setOptions(BankOptions bankOptions, List<PlayerOptions> playerOptions)
{
//int length = (int)playerOptions.GetType().InvokeMember("length", BindingFlags.GetProperty, null, playerOptions, null);
BankAccount bankaccount = new BankAccount();
bankaccount.ID = 1;
bankaccount.TotalAmmount = bankOptions.BankTotalAmount;
db.BankAccount_Table.Add(bankaccount);
db.SaveChanges();
//Here i want to get each (player1Option, player2Option...) object array from that playerOptions object array
foreach( var item in playerOptions){
item //<--- in this variable you have the element PlayerOption
}
//return RedirectToAction("Index");
return View();
}

Categories