/// <summary> /// Sends a View request to the server to be executed using async/await /// </summary> /// <typeparam name="T">The Type of the body of the Views return value or row.</typeparam> /// <param name="query">An <see cref="IViewQuery" /> to be executed.</param> /// <returns> /// The result of the View request as an <see cref="Task{IViewResult}" /> to be awaited on where T is the Type of each row. /// </returns> public override async Task <IViewResult <T> > SendWithRetryAsync <T>(IViewQuery query) { IViewResult <T> viewResult = null; try { using (var cancellationTokenSource = new CancellationTokenSource(ConfigInfo.ClientConfig.ViewHardTimeout)) { var task = RetryViewEveryAsync(async(e, c) => { var server = c.GetServer(); return(await server.SendAsync <T>(query)); }, query, ConfigInfo, cancellationTokenSource.Token).ConfigureAwait(false); viewResult = await task; } } catch (Exception e) { Log.Info(e); const string message = "View request failed, check Error and Exception fields for details."; viewResult = new ViewResult <T> { Message = message, Error = e.Message, StatusCode = HttpStatusCode.BadRequest, Success = false, Exception = e }; } return(viewResult); }
/// <summary> /// Sends a View request with retry. /// </summary> /// <typeparam name="T">The Type T of the <see cref="ViewRow{T}"/> value.</typeparam> /// <param name="viewQuery">The view query.</param> /// <returns>A <see cref="IViewResult{T}"/> with the results of the query.</returns> public override IViewResult <T> SendWithRetry <T>(IViewQuery viewQuery) { IViewResult <T> viewResult = null; try { do { var server = ConfigInfo.GetServer(); viewResult = server.Send <T>(viewQuery); } while ( !viewResult.Success && !viewResult.CannotRetry() && viewQuery.RetryAttempts++ <= ConfigInfo.ClientConfig.MaxViewRetries); } catch (Exception e) { Log.Info(e); const string message = "View request failed, check Error and Exception fields for details."; viewResult = new ViewResult <T> { Message = message, Error = e.Message, StatusCode = HttpStatusCode.BadRequest, Success = false, Exception = e }; } return(viewResult); }
/* Função para demonstrar o uso do */ static void MapReduce() { Console.WriteLine("Map/Reduce"); Console.WriteLine(""); ClientConfiguration config = new ClientConfiguration() { Servers = new List <Uri>() { new Uri("http://localhost:8091") } }; config.SetAuthenticator(new PasswordAuthenticator("test", "123456")); using (Cluster cluster = new Cluster(config)) using (IBucket bucket = cluster.OpenBucket("viajanet")) { IViewQuery query = new ViewQuery().From("clients", "clientCountNavigation").GroupLevel(2); IViewResult <dynamic> clientNavigation = bucket.Query <dynamic>(query); string userToken = ""; foreach (var client in clientNavigation.Rows) { if (client.Key[0] != userToken) { Console.WriteLine("Client {0}", client.Key[0]); userToken = client.Key[0]; } Console.WriteLine(" Function: {0} -> Count: {1}", client.Key[1], client.Value); } } }
public bool Handle(IWebServerRequest request, IWebServerResponse response) { Request = request; Response = response; MethodInfo method = GetType().GetMethods().FirstOrDefault(m => m.Name == request.ControllerMethodName && SupportsHttpMethod(m, request.HttpMethod)); if (method != null) { if (UserAuthorized(method, request)) { try { object[] parameters = GetParametersFromRequest(method, request); object o = method.Invoke(this, parameters); IViewResult result = request.WebSite.ViewProvider.GetViewForRequest(request).Render(o); response.FromString(result.Content, result.ContentType); } catch (Exception exception) { response.InternalError(request, exception); } } else { response.NotAllowed(request); } } else { return(false); } return(true); }
private IEnumerable <View> DoTrainingClassification(Runtime runtime) { IViewResult result = null; // ask question if (this.Settings.QuestionMode != QuestionMode.None) { yield return(new ChoiceView(new string[] { runtime.CurrentTrial.TargetStimulus.Class.Settings.Answer1, runtime.CurrentTrial.TargetStimulus.Class.Settings.Answer2, GUIUtils.Strings.DONT_KNOW }, out result) { Text = runtime.CurrentTrial.TargetStimulus.Class.Settings.Question }); // don't log this in verify mode, since then the answer is implicit based on the behavior if (this.Settings.QuestionMode != QuestionMode.AskAndVerify) { runtime.LogLine("User answered " + result.Value); } } // try to get the trial IArrayView <EEGDataEntry> trialData; if (!this.TryGetTrialData(runtime, out trialData)) { yield return(new TextView(runtime.LogLine("Failed to get trial data: ignoring trial"), this.Settings.InstructionTime)); } // either throw out the trial or add it to the classifier else if (result != null && (string)result.Value == GUIUtils.Strings.DONT_KNOW) { yield return(new TextView(runtime.LogLine(GUIUtils.Strings.DONT_KNOW + ": ignoring trial"), this.Settings.InstructionTime)); } else if (this.Settings.QuestionMode == QuestionMode.AskAndVerify && ((string)result.Value == runtime.CurrentTrial.TargetStimulus.Class.Settings.Answer1) != runtime.CurrentTrial.TargetStimulus.Subclass.Value) { yield return(new TextView(runtime.LogLine("Answer was incorrect: ignoring trial"), this.Settings.InstructionTime)); } else if (this.Settings.ArtifactDetectionSettings.HasMotionArtifact(trialData)) { yield return(new TextView(runtime.LogLine("Motion artifact detected: ignoring trial"), this.Settings.InstructionTime)); } else if (trialData != null) { foreach (var classifier in runtime.Classifiers) { classifier.AddTrial(trialData); } runtime.LogTrial(trialData); // record the success runtime.CurrentTrial.Succeeded = true; } }
private void AddDashboardModules(IViewResult result) { if (result == null) { return; } Response.Tiles.Add(new TileDefinition("pageHeader", "~/moduleresource/Admin/Logo.ascx")); }
private async Task UpdateAvatarRankingList() { Dictionary <long, AvatarRankingEntry> prevAvatarRankingDictionary = this.m_avatarRankingList; Dictionary <long, AvatarRankingEntry> avatarRankingDictionary = new Dictionary <long, AvatarRankingEntry>(SeasonDocument.RANKING_LIST_SIZE); LogicArrayList <AvatarRankingEntry> avatarRankingList = this.AvatarRankingList; avatarRankingList.Clear(); IViewResult <JObject> result = await ServerScoring.GameDatabase.ExecuteCommand <JObject>(new ViewQuery().From("players", "leaderboard_0").Desc().Limit(SeasonDocument.RANKING_LIST_SIZE)); if (result.Success) { int orderCounter = 0; foreach (JObject value in result.Values) { AvatarRankingEntry avatarRankingEntry = new AvatarRankingEntry(); LogicLong id = new LogicLong((int)value["id_hi"], (int)value["id_lo"]); avatarRankingEntry.SetId(id); avatarRankingEntry.SetName((string)value["name"]); avatarRankingEntry.SetScore((int)value["score"]); avatarRankingEntry.SetExpLevel((int)value["xp_level"]); avatarRankingEntry.SetAttackWinCount((int)value["attackWin"]); avatarRankingEntry.SetAttackLoseCount((int)value["attackLose"]); avatarRankingEntry.SetDefenseWinCount((int)value["defenseWin"]); avatarRankingEntry.SetDefenseLoseCount((int)value["defenseLose"]); avatarRankingEntry.SetLeagueType((int)value["leagueType"]); avatarRankingEntry.SetCountry((string)value["country"]); avatarRankingEntry.SetHomeId(id); if (value.TryGetValue("allianceId_High", out JToken allianceIdHigh)) { avatarRankingEntry.SetAllianceId(new LogicLong((int)allianceIdHigh, (int)value["allianceId_Low"])); avatarRankingEntry.SetAllianceName((string)value["allianceName"]); avatarRankingEntry.SetAllianceBadgeId((int)value["badgeId"]); } avatarRankingEntry.SetOrder(++orderCounter); if (prevAvatarRankingDictionary != null && prevAvatarRankingDictionary.TryGetValue(id, out AvatarRankingEntry prevEntry)) { avatarRankingEntry.SetPreviousOrder(prevEntry.GetPreviousOrder()); } avatarRankingDictionary.Add(id, avatarRankingEntry); avatarRankingList.Add(avatarRankingEntry); } this.m_avatarRankingList = avatarRankingDictionary; } else { Logging.Warning("ScoringSeason.updateAvatarRankingList: view error: " + result.Error); } }
private void AddAccountSetupModules(IViewResult result) { if (result == null) { return; } Response.Tiles.Add(new TileDefinition("pageHeader", "~/moduleresource/Admin/Logo.ascx")); Response.Tiles.Add(new TileDefinition("middlePart", "~/moduleresource/Admin/AddUser.ascx")); }
internal CouchbaseViewQueryException(IViewResult <T> viewResult) : base("Couchbase view query returned an error: " + (viewResult.Error ?? "Unknown"), viewResult.Exception) { if (viewResult == null) { throw new ArgumentNullException("viewResult"); } _viewResult = viewResult; }
public override CacheDependency GetCacheDependency(string virtualPath, IEnumerable virtualPathDependencies, DateTime utcStart) { IViewResult result = PortalContext.Current.Request.Result as IViewResult; if (!IsRouteFile(virtualPath) || result == null) { return(Previous.GetCacheDependency(virtualPath, virtualPathDependencies, utcStart)); } PortalTrace.Write("RoutePathProvider", "GetCacheDependency", "Creating new CacheDependency for path '{0}'.", virtualPath); return(new CacheDependency(HttpContext.Current.Server.MapPath(result.DependencyPath))); }
/// <summary> /// Throws a <see cref="CouchbaseViewResponseException"/> on any error. /// </summary> /// <typeparam name="T">View result row type.</typeparam> /// <param name="result">The result.</param> public static void EnsureSuccess <T>(this IViewResult <T> result) { if (result == null) { throw new ArgumentNullException("result"); } if (!result.Success) { throw CouchbaseViewResponseException.FromResult(result); } }
private static void InitializeView(PortalView view) { IPortalContext context = PortalContext.Current; IViewResult result = context.Request.Result as IViewResult; if (result == null) { return; } view.ViewData = context.Request.Result.ViewData; view.InitializeContext(PortalContext.Current); }
private async Task UpdateAllianceRankingList(int villageType) { Dictionary <long, AllianceRankingEntry> prevAllianceRankingDictionary = this.m_allianceRankingList[villageType]; Dictionary <long, AllianceRankingEntry> allianceRankingDictionary = new Dictionary <long, AllianceRankingEntry>(SeasonDocument.RANKING_LIST_SIZE); LogicArrayList <AllianceRankingEntry> allianceRankingList = this.AllianceRankingList[villageType]; allianceRankingList.Clear(); IViewResult <JObject> result = await ServerScoring.AllianceDatabase.ExecuteCommand <JObject>(new ViewQuery().From("alliances", "leaderboard_" + villageType).Desc().Limit(SeasonDocument.RANKING_LIST_SIZE)); if (result.Success) { int orderCounter = 0; foreach (JObject value in result.Values) { AllianceRankingEntry allianceRankingEntry = new AllianceRankingEntry(); LogicLong id = new LogicLong((int)value["id_hi"], (int)value["id_lo"]); allianceRankingEntry.SetId(id); allianceRankingEntry.SetName((string)value["name"]); allianceRankingEntry.SetScore((int)value["score"]); allianceRankingEntry.SetAllianceBadgeId((int)value["badge_id"]); allianceRankingEntry.SetAllianceLevel((int)value["xp_level"]); allianceRankingEntry.SetMemberCount((int)value["member_count"]); if (value.TryGetValue("origin", out JToken originToken)) { allianceRankingEntry.SetOriginData(LogicDataTables.GetDataById((int)originToken)); } allianceRankingEntry.SetOrder(++orderCounter); if (prevAllianceRankingDictionary != null && prevAllianceRankingDictionary.TryGetValue(id, out AllianceRankingEntry prevEntry)) { allianceRankingEntry.SetPreviousOrder(prevEntry.GetPreviousOrder()); } allianceRankingDictionary.Add(id, allianceRankingEntry); allianceRankingList.Add(allianceRankingEntry); } this.m_allianceRankingList[villageType] = allianceRankingDictionary; } else { Logging.Warning("ScoringSeason.updateAllianceRankingList: view error: " + result.Error); } }
/// <summary> /// Sends a View request to the server to be executed using async/await /// </summary> /// <typeparam name="T">The Type of the body of the Views return value or row.</typeparam> /// <param name="query">An <see cref="IViewQuery" /> to be executed.</param> /// <returns> /// The result of the View request as an <see cref="Task{IViewResult}" /> to be awaited on where T is the Type of each row. /// </returns> /// <exception cref="ServiceNotSupportedException">The cluster does not support View services.</exception> public override async Task <IViewResult <T> > SendWithRetryAsync <T>(IViewQueryable query) { IViewResult <T> viewResult = null; try { //Is the cluster configured for View services? if (!ConfigInfo.IsViewCapable) { throw new ServiceNotSupportedException( ExceptionUtil.GetMessage(ExceptionUtil.ServiceNotSupportedMsg, "View")); } using (var cancellationTokenSource = new CancellationTokenSource(ConfigInfo.ClientConfig.ViewRequestTimeout)) { var task = RetryViewEveryAsync(async(e, c) => { var server = c.GetViewNode(); return(await server.SendAsync <T>(query).ContinueOnAnyContext()); }, query, ConfigInfo, cancellationTokenSource.Token).ConfigureAwait(false); viewResult = await task; } } catch (Exception e) { Log.Info(e); const string message = "View request failed, check Error and Exception fields for details."; viewResult = new ViewResult <T> { Message = message, Error = e.Message, StatusCode = HttpStatusCode.BadRequest, Success = false, Exception = e }; } return(viewResult); }
public override VirtualFile GetFile(string virtualPath) { IPortalRequest portalRequest = PortalContext.Current.Request; IViewResult result = portalRequest.Result as IViewResult; if (result != null && IsRouteFile(virtualPath)) { return(new RouteFile(virtualPath, portalRequest.Result)); } PortalTrace.Write("RoutePathProvider", "GetFile", "'{0}' is not a virtual portal file. Delegating to previous VirtualPathProvider.", virtualPath); if (Path.GetExtension(virtualPath) != ".aspx") { return(Previous.GetFile(virtualPath)); } return(portalRequest.AllowPhysicalPages ? Previous.GetFile(virtualPath) : new RouteFile(virtualPath, new FileNotFoundResult())); }
/// <summary> /// Sends a View request with retry. /// </summary> /// <typeparam name="T">The Type T of the <see cref="ViewRow{T}"/> value.</typeparam> /// <param name="viewQuery">The view query.</param> /// <returns>A <see cref="IViewResult{T}"/> with the results of the query.</returns> /// <exception cref="ServiceNotSupportedException">The cluster does not support View services.</exception> public override IViewResult <T> SendWithRetry <T>(IViewQueryable viewQuery) { IViewResult <T> viewResult = null; try { //Is the cluster configured for View services? if (!ConfigInfo.IsViewCapable) { throw new ServiceNotSupportedException( ExceptionUtil.GetMessage(ExceptionUtil.ServiceNotSupportedMsg, "View")); } do { var server = ConfigInfo.GetViewNode(); viewResult = server.Send <T>(viewQuery); } while ( !viewResult.Success && !viewResult.CannotRetry() && viewQuery.RetryAttempts++ <= ConfigInfo.ClientConfig.MaxViewRetries); } catch (Exception e) { Log.Info(e); const string message = "View request failed, check Error and Exception fields for details."; viewResult = new ViewResult <T> { Message = message, Error = e.Message, StatusCode = HttpStatusCode.BadRequest, Success = false, Exception = e }; } return(viewResult); }
public VocabView(string testStimulus, string correctAns, int displayTimeMillis, int delayTimeMillis, bool mchoice, out IViewResult result) : base() { TextView test = new TextView(testStimulus, displayTimeMillis, GUIUtils.Constants.DISPLAY_FONT_LARGE); //-1 is infinite time if (mchoice) { string[] answers = new string[1]; //Currently the only option is the correct answer //To do: Randomly select a subset of answers OR do free response answers[0] = correctAns; ChoiceView choice = new ChoiceView(answers); var timer = this.RegisterDisposable(new Timer() { Interval = delayTimeMillis, Enabled = false }); var rows = GUIUtils.CreateTable(new[] { .5, .5 }, Direction.Vertical); var testPanel = new Panel { Dock = DockStyle.Fill }; var choicePanel = new Panel { Dock = DockStyle.Fill, Enabled = false }; rows.Controls.Add(testPanel, 0, 0); timer.Tick += (sender, args) => { choicePanel.Enabled = true; rows.Controls.Add(choicePanel, 0, 1); timer.Enabled = false; }; this.DoOnDeploy(c => { c.Controls.Add(rows); this.DeploySubView(test, testPanel, causesOwnerToFinish: false); this.DeploySubView(choice, choicePanel, causesOwnerToFinish: true); timer.Enabled = true; }); this.DoOnFinishing(() => { var answer = choice.Result.HasValue ? choice.Result.Value : null; this.SetResult(((string)answer) == correctAns); }); result = this.Result; } else { FreeResponseView frView = new FreeResponseView(); var timer = this.RegisterDisposable(new Timer() { Interval = delayTimeMillis, Enabled = false }); var rows = GUIUtils.CreateTable(new[] { .5, .5 }, Direction.Vertical); var testPanel = new Panel { Dock = DockStyle.Fill }; var frPanel = new Panel { Dock = DockStyle.Fill, Enabled = false }; rows.Controls.Add(testPanel, 0, 0); timer.Tick += (sender, args) => { frPanel.Enabled = true; rows.Controls.Add(frPanel, 0, 1); timer.Enabled = false; }; this.DoOnDeploy(c => { c.Controls.Add(rows); this.DeploySubView(test, testPanel, causesOwnerToFinish: false); this.DeploySubView(frView, frPanel, causesOwnerToFinish: true); timer.Enabled = true; }); this.DoOnFinishing(() => { if (frView.Result.HasValue && (string) frView.Result.Value != "") if (Compute((string)frView.Result.Value, correctAns) < 3) if ((correctAns == "MONKEY" && (string) frView.Result.Value == "DONKEY") || (correctAns == "DONKEY" && (string) frView.Result.Value == "MONKEY")) this.SetResult(false); else if (correctAns == "MANGO" || correctAns == "MAGGOT" || correctAns == "HORSE" || correctAns == "CORPSE") this.SetResult(Compute((string)frView.Result.Value, correctAns) < 2); else this.SetResult(true); else this.SetResult(false); else this.SetResult(false); }); result = this.Result; } }
internal static CouchbaseViewResponseException FromResult <T>(IViewResult <T> result) { return(new CouchbaseViewResponseException( ExceptionUtil.GetResponseExceptionMessage(result.Message, result.StatusCode), result.StatusCode, result.Exception)); }
public VocabView(string testStimulus, string correctAns, int displayTimeMillis, int delayTimeMillis, bool mchoice, out IViewResult result) : base() { TextView test = new TextView(testStimulus, displayTimeMillis, GUIUtils.Constants.DISPLAY_FONT_LARGE); //-1 is infinite time if (mchoice) { string[] answers = new string[1]; //Currently the only option is the correct answer //To do: Randomly select a subset of answers OR do free response answers[0] = correctAns; ChoiceView choice = new ChoiceView(answers); var timer = this.RegisterDisposable(new Timer() { Interval = delayTimeMillis, Enabled = false }); var rows = GUIUtils.CreateTable(new[] { .5, .5 }, Direction.Vertical); var testPanel = new Panel { Dock = DockStyle.Fill }; var choicePanel = new Panel { Dock = DockStyle.Fill, Enabled = false }; rows.Controls.Add(testPanel, 0, 0); timer.Tick += (sender, args) => { choicePanel.Enabled = true; rows.Controls.Add(choicePanel, 0, 1); timer.Enabled = false; }; this.DoOnDeploy(c => { c.Controls.Add(rows); this.DeploySubView(test, testPanel, causesOwnerToFinish: false); this.DeploySubView(choice, choicePanel, causesOwnerToFinish: true); timer.Enabled = true; }); this.DoOnFinishing(() => { var answer = choice.Result.HasValue ? choice.Result.Value : null; this.SetResult(((string)answer) == correctAns); }); result = this.Result; } else { FreeResponseView frView = new FreeResponseView(); var timer = this.RegisterDisposable(new Timer() { Interval = delayTimeMillis, Enabled = false }); var rows = GUIUtils.CreateTable(new[] { .5, .5 }, Direction.Vertical); var testPanel = new Panel { Dock = DockStyle.Fill }; var frPanel = new Panel { Dock = DockStyle.Fill, Enabled = false }; rows.Controls.Add(testPanel, 0, 0); timer.Tick += (sender, args) => { frPanel.Enabled = true; rows.Controls.Add(frPanel, 0, 1); timer.Enabled = false; }; this.DoOnDeploy(c => { c.Controls.Add(rows); this.DeploySubView(test, testPanel, causesOwnerToFinish: false); this.DeploySubView(frView, frPanel, causesOwnerToFinish: true); timer.Enabled = true; }); this.DoOnFinishing(() => { if (frView.Result.HasValue && (string)frView.Result.Value != "") { if (Compute((string)frView.Result.Value, correctAns) < 3) { if ((correctAns == "MONKEY" && (string)frView.Result.Value == "DONKEY") || (correctAns == "DONKEY" && (string)frView.Result.Value == "MONKEY")) { this.SetResult(false); } else if (correctAns == "MANGO" || correctAns == "MAGGOT" || correctAns == "HORSE" || correctAns == "CORPSE") { this.SetResult(Compute((string)frView.Result.Value, correctAns) < 2); } else { this.SetResult(true); } } else { this.SetResult(false); } } else { this.SetResult(false); } }); result = this.Result; } }
public static void UpdatePaging(this IPageableModel model, IViewOptions options, IViewResult result) { int count = result.Rows.Count(); var limit = options.Limit.HasValue ? options.Limit.Value : 10 ; model.Limit = limit; int rowsMinusOffset = (result.TotalRows - result.OffSet); model.ShowPrev = result.OffSet != 0 && !(model.Descending && (rowsMinusOffset <= count)); model.ShowNext = (result.TotalRows > options.Limit + result.OffSet) || options.Descending.GetValueOrDefault(); string skipPrev = result.OffSet < limit ? "" : "&skip=1"; string skipNext = rowsMinusOffset < limit ? "" : "&skip=1"; JToken lastRow; JToken firstRow; if (options.Descending.HasValue && options.Descending.Value) { //descending lastRow = result.Rows.FirstOrDefault(); firstRow = result.Rows.LastOrDefault(); model.StartIndex = (rowsMinusOffset - limit) < 1 ? 1 : (rowsMinusOffset - limit+1); }else { //ascending lastRow = result.Rows.LastOrDefault(); firstRow = result.Rows.FirstOrDefault(); model.StartIndex = result.OffSet + 1; } var startIndexPlusCount = model.StartIndex + count-1; model.EndIndex =result.TotalRows == 0 ? 0 : startIndexPlusCount; if (count == 0 ) model.EndIndex = model.StartIndex = 0; model.TotalRows = result.TotalRows; string prevStartKey = firstRow != null ? "&startkey=" + HttpUtility.UrlEncode(firstRow.Value<string>("key")) + "&StartKeyDocId=" + firstRow.Value<string>("id") : ""; string nextStartKey = lastRow != null ? "&startkey=" + HttpUtility.UrlEncode(lastRow.Value<string>("key") ) + "&StartKeyDocId="+ lastRow.Value<string>("id") : ""; model.NextUrlParameters = "?limit=" + model.Limit + nextStartKey + skipNext ; model.PrevUrlParameters = "?limit=" + model.Limit + prevStartKey + skipPrev + "&descending=true"; }
public ClassifyView(Stimulus stimulus, StimulusClass stimulusClass, out IViewResult result) : base() { var table = this.RegisterDisposable(GUIUtils.CreateTable(new double[] { .7, .1, .2 }, Direction.Vertical)); Panel topPanel = new Panel() { Dock = DockStyle.Fill }, bottomPanel = new Panel() { Dock = DockStyle.Fill }; table.Controls.Add(topPanel, 0, 0); var label = new Label() { Dock = DockStyle.Fill, AutoSize = true, TextAlign = ContentAlignment.MiddleCenter, Text = "Current selection: ", Font = GUIUtils.Constants.DISPLAY_FONT }; table.Controls.Add(label, 0, 1); table.Controls.Add(bottomPanel, 0, 2); var imageView = new ImageView(-1) { ImagePath = stimulus.PathOrText }; var choiceView = new ChoiceView(new string[] { stimulusClass.Settings.Answer1, stimulusClass.Settings.Answer2, GUIUtils.Strings.UNCLASSIFIED, SKIP, BACK }); this.DoOnDeploy(c => { this.DeploySubView(imageView, topPanel); topPanel.Controls.Add(new Label() { Text = GUIUtils.Strings.ImageExtensions.Contains(Path.GetExtension(stimulus.PathOrText)) ? Path.GetFileNameWithoutExtension(stimulus.PathOrText) : stimulus.PathOrText, Dock = DockStyle.Top, TextAlign = ContentAlignment.MiddleCenter, Font = GUIUtils.Constants.DISPLAY_FONT }); if (stimulus.Subclass == null) { label.Text += GUIUtils.Strings.UNCLASSIFIED; } else { label.Text += (bool)stimulus.Subclass ? stimulusClass.Settings.Answer1 : stimulusClass.Settings.Answer2; } this.DeploySubView(choiceView, bottomPanel); c.Controls.Add(table); }); this.DoOnFinishing(() => { if (!(bool)imageView.Result.Value) { this.SetResult(null); } else if (stimulusClass.Settings.Answer1.Equals(choiceView.Result.Value)) { this.SetResult(true); } else if (stimulusClass.Settings.Answer2.Equals(choiceView.Result.Value)) { this.SetResult(false); } else if (BACK.Equals(choiceView.Result.Value)) { this.SetResult(BACK); } else if (SKIP.Equals(choiceView.Result.Value)) { this.SetResult(SKIP); } else { this.SetResult(null); } }); result = this.Result; }
/// <summary> /// Construct a view with the given options and with inline retrieval of the result. /// </summary> public FreeResponseView(out IViewResult result) { result = this.Result; }
private void Handle(IViewResult result, IHttpContext context) { wod.Render.Template(result.TemplateName, result.Parameters); }
/// <summary> /// Construct a view with the given options and with inline retrieval of the result. /// </summary> public ChoiceView(IEnumerable<string> optionsStrings, out IViewResult result) : this(optionsStrings) { result = this.Result; }
/// <summary> /// Construct an image view that displays for the specified time and returns the result /// as an out parameter /// </summary> public ImageView(int displayTimeMillis, out IViewResult result) : this(displayTimeMillis) { result = this.Result; }
public VocabView(string testStimulus, string correctAns, int displayTimeMillis, int delayTimeMillis, bool mchoice, StreamWriter anslog, out IViewResult result) : base() { TextView test = new TextView(testStimulus, displayTimeMillis, GUIUtils.Constants.DISPLAY_FONT_LARGE); //-1 is infinite time //mchoice is a bool that indicates whether the vocab view should be multiple choice or not. I haven't actually handled this properly if (mchoice) { string[] answers = new string[1]; //Currently the only option is the correct answer answers[0] = correctAns; ChoiceView choice = new ChoiceView(answers); var timer = this.RegisterDisposable(new Timer() { Interval = delayTimeMillis, Enabled = false }); var rows = GUIUtils.CreateTable(new[] { .5, .5 }, Direction.Vertical); var testPanel = new Panel { Dock = DockStyle.Fill }; var choicePanel = new Panel { Dock = DockStyle.Fill, Enabled = false }; rows.Controls.Add(testPanel, 0, 0); timer.Tick += (sender, args) => { choicePanel.Enabled = true; rows.Controls.Add(choicePanel, 0, 1); timer.Enabled = false; }; this.DoOnDeploy(c => { c.Controls.Add(rows); this.DeploySubView(test, testPanel, causesOwnerToFinish: false); this.DeploySubView(choice, choicePanel, causesOwnerToFinish: true); timer.Enabled = true; }); this.DoOnFinishing(() => { var answer = choice.Result.HasValue ? choice.Result.Value : null; this.SetResult(((string)answer) == correctAns); }); result = this.Result; } //ISSUE: In the free response version, no matter what I try, I can't get the cursor to automatically be in the text box else { FreeResponseView frView = new FreeResponseView(); var timer = this.RegisterDisposable(new Timer() { Interval = delayTimeMillis, Enabled = false }); var rows = GUIUtils.CreateTable(new[] { .5, .5 }, Direction.Vertical); var testPanel = new Panel { Dock = DockStyle.Fill }; var frPanel = new Panel { Dock = DockStyle.Fill, Enabled = false }; rows.Controls.Add(testPanel, 0, 0); timer.Tick += (sender, args) => { frPanel.Enabled = true; rows.Controls.Add(frPanel, 0, 1); timer.Enabled = false; }; this.DoOnDeploy(c => { c.Controls.Add(rows); this.DeploySubView(test, testPanel, causesOwnerToFinish: false); this.DeploySubView(frView, frPanel, causesOwnerToFinish: true); timer.Enabled = true; }); this.DoOnFinishing(() => { if (frView.Result.HasValue) this.SetResult(((string) frView.Result.Value) == correctAns); else this.SetResult(false); anslog.WriteLine("User Answer: " + (string)frView.Result.Value); anslog.WriteLine("Correct Answer: " + correctAns); }); result = this.Result; } }
public VocabView(string testStimulus, string correctAns, int displayTimeMillis, int delayTimeMillis, bool mchoice, StreamWriter anslog, out IViewResult result) : base() { TextView test = new TextView(testStimulus, displayTimeMillis, GUIUtils.Constants.DISPLAY_FONT_LARGE); //-1 is infinite time //mchoice is a bool that indicates whether the vocab view should be multiple choice or not. I haven't actually handled this properly if (mchoice) { string[] answers = new string[1]; //Currently the only option is the correct answer answers[0] = correctAns; ChoiceView choice = new ChoiceView(answers); var timer = this.RegisterDisposable(new Timer() { Interval = delayTimeMillis, Enabled = false }); var rows = GUIUtils.CreateTable(new[] { .5, .5 }, Direction.Vertical); var testPanel = new Panel { Dock = DockStyle.Fill }; var choicePanel = new Panel { Dock = DockStyle.Fill, Enabled = false }; rows.Controls.Add(testPanel, 0, 0); timer.Tick += (sender, args) => { choicePanel.Enabled = true; rows.Controls.Add(choicePanel, 0, 1); timer.Enabled = false; }; this.DoOnDeploy(c => { c.Controls.Add(rows); this.DeploySubView(test, testPanel, causesOwnerToFinish: false); this.DeploySubView(choice, choicePanel, causesOwnerToFinish: true); timer.Enabled = true; }); this.DoOnFinishing(() => { var answer = choice.Result.HasValue ? choice.Result.Value : null; this.SetResult(((string)answer) == correctAns); }); result = this.Result; } //ISSUE: In the free response version, no matter what I try, I can't get the cursor to automatically be in the text box else { FreeResponseView frView = new FreeResponseView(); var timer = this.RegisterDisposable(new Timer() { Interval = delayTimeMillis, Enabled = false }); var rows = GUIUtils.CreateTable(new[] { .5, .5 }, Direction.Vertical); var testPanel = new Panel { Dock = DockStyle.Fill }; var frPanel = new Panel { Dock = DockStyle.Fill, Enabled = false }; rows.Controls.Add(testPanel, 0, 0); timer.Tick += (sender, args) => { frPanel.Enabled = true; rows.Controls.Add(frPanel, 0, 1); timer.Enabled = false; }; this.DoOnDeploy(c => { c.Controls.Add(rows); this.DeploySubView(test, testPanel, causesOwnerToFinish: false); this.DeploySubView(frView, frPanel, causesOwnerToFinish: true); timer.Enabled = true; }); this.DoOnFinishing(() => { if (frView.Result.HasValue) { this.SetResult(((string)frView.Result.Value) == correctAns); } else { this.SetResult(false); } anslog.WriteLine("User Answer: " + (string)frView.Result.Value); anslog.WriteLine("Correct Answer: " + correctAns); }); result = this.Result; } }
/// <summary> /// Construct a view with the given options and with inline retrieval of the result. /// </summary> public ChoiceView(IEnumerable <string> optionsStrings, out IViewResult result) : this(optionsStrings) { result = this.Result; }
public void ViewResult_EnsureSuccess_Throws_ArguementNulException_When_Result_Is_Null() { IViewResult <dynamic> result = null; Assert.Throws <ArgumentNullException>(() => result.EnsureSuccess()); }
static void ProcessError <T>(Exception ex, IViewResult <T> viewResult) { viewResult.Success = false; viewResult.StatusCode = GetStatusCode(ex.Message); viewResult.Message = ex.Message; }
/// <summary> /// Constructs a fixation view that displays for the specified time period and /// returns the result as an out parameter /// </summary> public FixationView(int displayTimeMillis, out IViewResult result) : this(displayTimeMillis) { result = this.Result; }
public static void UpdatePaging(this IPageableModel model, IViewOptions options, IViewResult result) { int count = result.Rows.Count(); var limit = options.Limit.HasValue ? options.Limit.Value : 10; model.Limit = limit; int rowsMinusOffset = (result.TotalRows - result.OffSet); model.ShowPrev = result.OffSet != 0 && !(model.Descending && (rowsMinusOffset <= count)); model.ShowNext = (result.TotalRows > options.Limit + result.OffSet) || options.Descending.GetValueOrDefault(); string skipPrev = result.OffSet < limit ? "" : "&skip=1"; string skipNext = rowsMinusOffset < limit ? "" : "&skip=1"; JToken lastRow; JToken firstRow; if (options.Descending.HasValue && options.Descending.Value) { //descending lastRow = result.Rows.FirstOrDefault(); firstRow = result.Rows.LastOrDefault(); model.StartIndex = (rowsMinusOffset - limit) < 1 ? 1 : (rowsMinusOffset - limit + 1); } else { //ascending lastRow = result.Rows.LastOrDefault(); firstRow = result.Rows.FirstOrDefault(); model.StartIndex = result.OffSet + 1; } var startIndexPlusCount = model.StartIndex + count - 1; model.EndIndex = result.TotalRows == 0 ? 0 : startIndexPlusCount; if (count == 0) { model.EndIndex = model.StartIndex = 0; } model.TotalRows = result.TotalRows; string prevStartKey = firstRow != null ? "&startkey=" + HttpUtility.UrlEncode(firstRow.Value <string>("key")) + "&StartKeyDocId=" + firstRow.Value <string>("id") : ""; string nextStartKey = lastRow != null ? "&startkey=" + HttpUtility.UrlEncode(lastRow.Value <string>("key")) + "&StartKeyDocId=" + lastRow.Value <string>("id") : ""; model.NextUrlParameters = "?limit=" + model.Limit + nextStartKey + skipNext; model.PrevUrlParameters = "?limit=" + model.Limit + prevStartKey + skipPrev + "&descending=true"; }