} // End ctor /// <summary> /// Main method that brings all new budgets /// </summary> /// <returns> an IEnumerable<> type holding all ProjectionViewModel </returns> public IEnumerable <ProjectionViewModel> NewBudgets(SessionViewModel sessionView) { //_projectionContext.Database.Log = s => System.Diagnostics.Debug.WriteLine(s); // Log in output in order to see the generated sql query SqlParameter StartDate = new SqlParameter("@StartDate", sessionView.StartDate.ToString("yyyyMMdd")); List <ProjectionViewModel> projectionList = _projectionContext.Database .SqlQuery <ProjectionViewModel>("LoadBudgets @StartDate", StartDate).ToList(); LoadDimensionsFromSAP(ref projectionList); return(projectionList); } // End newBudgets
private static async Task <bool> CheckCanOpenSolution(SessionViewModel session) { if (string.IsNullOrEmpty(session.SolutionPath)) { await session.Dialogs.MessageBox(Tr._p("Message", "The session currently open is not a Visual Studio session."), MessageBoxButton.OK, MessageBoxImage.Information); return(false); } return(true); }
public async Task Initialize(SessionViewModel session, ProjectWatcher watcher, CancellationToken token) { this.watcher = watcher; var assemblies = watcher.TrackedAssemblies.ToList(); foreach (var trackedAssembly in assemblies.Where(trackedAssembly => trackedAssembly.Project != null)) { await AnalyzeProject(session, trackedAssembly.Project, token); } }
public ActionResult Create(SessionViewModel viewModel) { if(ModelState.IsValid) { _sessionRepository.Add(viewModel.Session); return RedirectToAction("Index"); } return View(viewModel); }
private void shareButton_Click(object sender, EventArgs e) { SessionViewModel vm = this.DataContext as SessionViewModel; EmailComposeTask email = new EmailComposeTask(); email.Subject = "Check out this session at PrDC"; email.Body = string.Format("Hey, thought you might like to check out '{0}'. Visit http://www.prairiedevcon.com/sessions to see all the info.", vm.Session.Title); email.Show(); }
/// <summary> /// Initializes a new instance of the <see cref="ActionHistoryViewModel"/> class. /// </summary> /// <param name="session">The session this view model belongs to.</param> public ActionHistoryViewModel(SessionViewModel session) : base(session.SafeArgument(nameof(session)).ServiceProvider) { this.session = session; service = ServiceProvider.Get <IUndoRedoService>(); Transactions.CollectionChanged += (sender, e) => RefreshUndoRedoStatus(); UndoCommand = new AnonymousCommand(ServiceProvider, () => { service.Undo(); session.CheckConsistency(); RefreshUndoRedoStatus(); }); RedoCommand = new AnonymousCommand(ServiceProvider, () => { service.Redo(); session.CheckConsistency(); RefreshUndoRedoStatus(); }); RefreshUndoRedoStatus(); }
public static void Reload([NotNull] SessionViewModel session, ILogger log, Action postReloadAction, Action undoAction, [NotNull] Dictionary <PackageLoadedAssembly, string> modifiedAssemblies) { var loadedAssemblies = modifiedAssemblies.Where(x => File.Exists(x.Key.Path)).ToDictionary(x => x.Key, x => x.Value); var assemblyContainer = session.AssemblyContainer; using (session.CreateAssetFixupContext()) { // TODO: Filter by "modified assemblies", for now we reload everything var loadedAssembliesSet = new HashSet <Assembly>(loadedAssemblies.Select(x => x.Key.Assembly).NotNull()); // Serialize types from unloaded assemblies as Yaml, and unset them var unloadingVisitor = new UnloadingVisitor(log, loadedAssembliesSet); Dictionary <AssetViewModel, List <ItemToReload> > assetItemsToReload; try { assetItemsToReload = PrepareAssemblyReloading(session, unloadingVisitor, session.UndoRedoService); } catch (Exception e) { log.Error("Could not prepare asset for assembly reload", e); throw; } var reloadOperation = new ReloadAssembliesOperation(assemblyContainer, modifiedAssemblies, Enumerable.Empty <IDirtiable>()); session.UndoRedoService.SetName(reloadOperation, "Reload assemblies"); // Reload assemblies reloadOperation.Execute(log); session.UndoRedoService.PushOperation(reloadOperation); postReloadAction(); var postReloadOperation = new AnonymousDirtyingOperation(Enumerable.Empty <IDirtiable>(), postReloadAction, postReloadAction); session.UndoRedoService.PushOperation(postReloadOperation); session.UndoRedoService.SetName(postReloadOperation, "Post reload action"); // Restore deserialized objects (or IUnloadable if it didn't work) var reloadingVisitor = new ReloadingVisitor(log, loadedAssembliesSet); try { PostAssemblyReloading(session.UndoRedoService, session.AssetNodeContainer, reloadingVisitor, log, assetItemsToReload); } catch (Exception e) { log.Error("Could not restore asset after assembly reload", e); throw; } var undoOperation = new AnonymousDirtyingOperation(Enumerable.Empty <IDirtiable>(), undoAction, null); session.UndoRedoService.PushOperation(undoOperation); session.UndoRedoService.SetName(undoOperation, "Undo action"); } session.ActiveProperties.RefreshSelectedPropertiesAsync().Forget(); }
public async Task <ActionResult <ApiResultViewModel <AccountViewModel> > > Register( [FromBody] RegisterInputModel inputModel, CancellationToken cancellationToken) { var account = await _accountManager.FindByEmailAsync(inputModel.Email, cancellationToken); if (account != null) { return(BadRequest("invalid_email", "Email already exists")); } account = new Account { Email = inputModel.Email, PasswordHash = PasswordHash.CreateHash(inputModel.Password), StatusId = AccountStatusIds.Active, Timezone = "Asia/Tehran", ReceiveNotifications = true, SearchableByEmailAddressOrUsername = true, FriendsOnlyBattleInvitations = false }; account.Nickname = account.Email.Substring(0, account.Email.IndexOf('@')); account.RegisterDateTime = DateTime.UtcNow; account.GenderId = GenderIds.Male; account = await _accountManager.SaveAsync(account, cancellationToken); var accountStats = new AccountStatsSummary { AccountId = account.Id, Level = 1 }; await _statsManager.SaveAsync(accountStats, cancellationToken); await SetDefaultAvatar(account, cancellationToken); await _dataContext.SaveChangesAsync(cancellationToken); var token = _tokenGenerator.GenerateToken(TimeSpan.FromDays(365), new Claim(JwtRegisteredClaimNames.Jti, account.Id.ToString()), new Claim(JwtRegisteredClaimNames.Sub, account.Email), new Claim("Timezone", account.Timezone)); var session = new Session { AccessToken = token, AccountId = account.Id, CreationDateTime = DateTime.UtcNow, StateId = SessionStateIds.Created, SourceAppId = AppIds.Game }; await _sessionManager.SaveAsync(session, cancellationToken); return(CreatedData(RegisterViewModel.GetRegisterViewModel(AccountViewModel.Map(account), SessionViewModel.Map(session)))); }
public async Task <Process> Launch(SessionViewModel session) { if (process == null) { process = await VisualStudioService.StartVisualStudio(session, ideInfo); process?.WaitForInputIdle(); } return(process); }
/// <summary> /// Initializes a new instance of the <see cref="RunBatchProcessingTaskWindowViewModel"/> class. /// </summary> /// <param name="visualizationContainer">The visualization container.</param> /// <param name="sessionViewModel">The dataset view model.</param> /// <param name="batchProcessingTaskMetadata">The batch processing task metadata.</param> public RunBatchProcessingTaskWindowViewModel(VisualizationContainer visualizationContainer, SessionViewModel sessionViewModel, BatchProcessingTaskMetadata batchProcessingTaskMetadata) { this.visualizationContainer = visualizationContainer; this.sessionViewModel = sessionViewModel; this.batchProcessingTaskMetadata = batchProcessingTaskMetadata; this.Name = batchProcessingTaskMetadata.Name; this.Description = batchProcessingTaskMetadata.Description; this.Target = sessionViewModel.Name; this.DataSize = TimeSpanFormatHelper.FormatTimeSpanApproximate(sessionViewModel.OriginatingTimeInterval.Span); this.Configuration = batchProcessingTaskMetadata.GetDefaultConfiguration(); }
private void EnsureSession() { var session = PsiStudioContext.Instance.DatasetViewModel.SessionViewModels.FirstOrDefault((s) => s.Name == Session.DefaultName); if (session == null) { session = PsiStudioContext.Instance.DatasetViewModel.CreateSession(); } this.currentSessionViewModel = session; }
public override void OnActionExecuting(ActionExecutingContext context) { SessionViewModel sessionObject = HttpContext.Session.GetJson <SessionViewModel>("SessionObject") ?? new SessionViewModel(); if (sessionObject == null || sessionObject.UserId == 0) { HttpContext.Session.Clear(); context.Result = RedirectToAction(nameof(SessionController.Login), "Session"); } //base.OnActionExecuting(context); }
protected static async Task <AssetViewModel> PickupAsset([NotNull] SessionViewModel session, [NotNull] IEnumerable <Type> assetTypes) { var dialogService = session.ServiceProvider.Get <IEditorDialogService>(); var assetPicker = dialogService.CreateAssetPickerDialog(session); assetPicker.Message = "Select the asset to use for this entity"; assetPicker.AcceptedTypes.AddRange(assetTypes); var result = await assetPicker.ShowModal(); return(result == Stride.Core.Presentation.Services.DialogResult.Ok ? assetPicker.SelectedAssets.FirstOrDefault() : null); }
/// <summary> /// Creates a build step that will build all shaders from system packages. /// </summary> /// <param name="session">The session used to retrieve currently used system packages.</param> /// <returns>A <see cref="ListBuildStep"/> containing the steps to build all shaders from system packages.</returns> public ListBuildStep CreateSystemShaderBuildSteps(SessionViewModel session) { if (session == null) { throw new ArgumentNullException(nameof(session)); } // Check if there are any new system projects to preload // TODO: PDX-1251: For now, allow non-system project as well (which means they will be loaded only once at startup) // Later, they should be imported depending on what project the currently previewed/built asset is var systemPackages = session.AllPackages.Where(project => /*project.IsSystem &&*/ !systemProjectsLoaded.Contains(project.Id)).ToList(); if (systemPackages.Count == 0) { return(null); } var importShadersRootProject = new Package(); var importShadersProjectSession = new PackageSession(importShadersRootProject); foreach (var package in systemPackages) { var mapPackage = new Package { FullPath = package.PackagePath }; foreach (var asset in package.Assets) { if (typeof(EffectShaderAsset).IsAssignableFrom(asset.AssetType)) { mapPackage.Assets.Add(new AssetItem(asset.Url, asset.Asset) { SourceFolder = asset.AssetItem.SourceFolder, SourceProject = asset.AssetItem.SourceProject }); } } importShadersProjectSession.Packages.Add(mapPackage); importShadersRootProject.LocalDependencies.Add(mapPackage); } // compile the fake project (create the build steps) var assetProjectCompiler = new PackageCompiler(new PackageAssetEnumerator(importShadersRootProject)); var context = new AssetCompilerContext { CompilationContext = typeof(AssetCompilationContext) }; var dependenciesCompileResult = assetProjectCompiler.Prepare(context); context.Dispose(); var buildSteps = dependenciesCompileResult.BuildSteps; buildSteps?.Add(new UpdateImportShaderCacheBuildStep(systemProjectsLoaded, systemPackages.Select(x => x.Id).ToList())); return(buildSteps); }
protected TextureBasePreviewViewModel(SessionViewModel session) : base(session) { // Initialize texture preview PreviewAvailableMipMaps = new ObservableList <string>(); previewSelectedMipMap = "Level 0"; PreviewZoomInCommand = new AnonymousCommand(ServiceProvider, ZoomIn); PreviewZoomOutCommand = new AnonymousCommand(ServiceProvider, ZoomOut); PreviewFitOnScreenCommand = new AnonymousCommand(ServiceProvider, FitOnScreen); PreviewScaleToRealSizeCommand = new AnonymousCommand(ServiceProvider, ScaleToRealSize); }
public AssetPickerWindow(SessionViewModel session) { InitializeComponent(); Session = session; AcceptedTypes = new List <Type>(); AssetDoubleClickCommand = new AnonymousCommand(session.ServiceProvider, OnAssetDoubleClick); DataContext = this; Loaded += AssetPickerWindowLoaded; Width = Math.Min(Width, SystemParameters.WorkArea.Width); Height = Math.Min(Height, SystemParameters.WorkArea.Height); }
public static async Task <bool> StartOrToggleVisualStudio(SessionViewModel session, IDEInfo ideInfo) { if (!await CheckCanOpenSolution(session)) { return(false); } var process = await GetVisualStudio(session, true) ?? await StartVisualStudio(session, ideInfo); return(process != null); }
public void SessionId_IsNotEmpty() { var mock = new Mock <ISession>(); mock.Setup(x => x.Id).Returns(Guid.NewGuid()); mock.Setup(x => x.Analysis).Returns(new ReactiveCollection <IAnalysis>()); var sessionViewModel = new SessionViewModel(mock.Object); sessionViewModel.SessionId.Should().NotBeEmpty(); }
public object GetImageForEnum(SessionViewModel session, object value) { if (session == null) { return(null); } object image; enumImages.TryGetValue(value, out image); return(image); }
public IActionResult Index() { SimpleAdDb db = new SimpleAdDb(); SessionViewModel vm = new SessionViewModel(); vm.Posts = db.GetPosts(); if (HttpContext.Session.Get <List <int> >("adIds") != null) { vm.Ids = HttpContext.Session.Get <List <int> >("adIds"); } return(View(vm)); }
public SessionViewModel GetViewModel() { var viewModel = new SessionViewModel(); // Check and see if something is in memory if (Session["SBT"] != null) { viewModel = (SessionViewModel)Session["SBT"]; } return(viewModel); }
public IHttpActionResult TokenEncrypt(SessionViewModel model) { try { model.Value = UtilFunction.securityEncrypt(model.Param); return(Ok(model)); } catch (Exception e) { return(BadRequest("Token加密失敗:" + e.Message)); } }
public async Task <ActionResult <ApiResultViewModel <SessionViewModel> > > GetSessionById(string id, CancellationToken cancellationToken) { var session = await _sessionManager.GetAsync(int.Parse(id), cancellationToken); if (session == null) { return(NotFound()); } return(OkData(SessionViewModel.Map(session))); }
/// <summary> /// Checking session duration. /// If the session starts and ends on the same day, true is returned. /// </summary> /// <param name="model">Specified session</param> /// <returns>True or false</returns> private bool CheckDoubleModel(SessionViewModel model) { if ((model.DateSession.Date == model.DateSession.AddMinutes(model.SessionDuration.TotalMinutes).Date) || (model.DateSession.AddMinutes(model.SessionDuration.TotalMinutes).Hour == 0 && model.DateSession.AddMinutes(model.SessionDuration.TotalMinutes).Minute == 0)) { return(false); } else { return(true); } }
public void InserirSessao(SessionViewModel sessionVM, SessionCookieClaimsObjects sessionData) { sessionVM.Session.SessionData = sessionData; var session = _userSessionData.Sessions.Find(x => x.UserId == sessionVM.Session.UserId); if (session != null) { InvalidarSessao(session); } _userSessionData.userSession = sessionVM.Session; _userSessionData.Sessions.Add(sessionVM.Session); }
/// <summary> /// Reloads a project when a .csproj files changes on the hard drive. /// </summary> /// <remarks> /// In case of destructive changes (i.e. dirty files that disappeared), user confirmation will be asked to proceed. /// </remarks> private async Task ReloadProject(SessionViewModel session, Project project) { var workspace = await Workspace; // Get assets and namespace from csproj // TODO: Use roslyn list of files? not sure we could have non .cs files easily though // However, if we load from file, it might not be in sync with Roslyn state string projectNamespace; var projectFiles = Package.FindAssetsInProject(project.FilePath, out projectNamespace); // Find associated ProjectViewModel var projectViewModel = session.LocalPackages.FirstOrDefault(y => y.Name == project.Name) as ProjectViewModel; if (projectViewModel == null) { return; } // List current assets var projectAssets = new List <AssetViewModel>(); var isProjectDirty = GetAssets(projectViewModel.Code, projectAssets); // Project is dirty, ask user if he really wants to auto-reload if (isProjectDirty) { var dialogResult = projectViewModel.Session.Dialogs.BlockingMessageBox( string.Format( Tr._p("Message", "Game Studio can't auto-reload the project file {0} because you have local changes such as new or deleted scripts.\r\n\r\nClick OK to keep reloading or Cancel to keep the current version."), Path.GetFileName(project.FilePath)), MessageBoxButton.OKCancel); if (dialogResult == MessageBoxResult.Cancel) { return; } } // Remove deleted assets (and ask user if he really wants to proceed in case some of them were dirty?) bool continueReload = await DeleteRemovedProjectAssets(projectViewModel, projectAssets, project, projectFiles); if (!continueReload) { return; } // Update Roslyn project workspace.AddOrUpdateProject(project); // Add new assets AddNewProjectAssets(projectViewModel, projectAssets, project, projectFiles); // Mark project as non dirty // TODO: Does that work properly with Undo/Redo? UpdateDirtiness(projectViewModel.Code, false); }
public ActionResult Details(int sessionId) { SessionViewModel sessionVM = new SessionViewModel(); using (WSADDbContext context = new WSADDbContext()) { Session session = context.Sessions.FirstOrDefault(row => row.Id == sessionId); sessionVM = new SessionViewModel(session); } return(View(sessionVM)); }
/// <summary> /// Retrieves the view model corresponding to the asset referenced by the <paramref name="source"/> parameter. /// </summary> /// <param name="session">The session view model to use to retrieve the asset view model.</param> /// <param name="source">The source of the reference.</param> /// <returns>The view model corresponding to the referenced asset if found, null otherwise.</returns> /// <remarks>The <paramref name="source"/> parameter must either be an <see cref="AssetReference"/>, or a proxy object of an <see cref="AttachedReference"/>.</remarks> public static AssetViewModel GetReferenceTarget(SessionViewModel session, object source) { var assetReference = source as AssetReference; if (assetReference != null) { return(session.GetAssetById(assetReference.Id)); } var reference = AttachedReferenceManager.GetAttachedReference(source); return(reference != null?session.GetAssetById(reference.Id) : null); }
// GET: Assets public ActionResult Index() { SessionViewModel viewModel = GetViewModel(); // if the model is valid and there are assets (any is a null and length check condensed) if (viewModel == null || !viewModel.Assets.Any()) { return(RedirectToAction("Asset", "SecBase")); } return(View(viewModel.Assets)); }
// // GET: /Session/Create public ActionResult Create(Formation formation) { SessionViewModel sVm = new SessionViewModel(); sVm.Session = new Session(); sVm.Formateurs = repoPersonne.Personnes.Where(x => x.Role1.IdRole == 2); sVm.Session.formation = formation.IdFormation; sVm.Session.Formation1 = formation; sVm.Stagiaires = repoPersonne.Personnes.Where(x => x.Role1.IdRole == 1); return(View(sVm)); }
public SessionNodeContainer(SessionViewModel session) { if (session == null) { throw new ArgumentNullException(nameof(session)); } // Apply primitive types, commands and associated data providers that comes from plugins var pluginService = session.ServiceProvider.Get <IAssetsPluginService>(); pluginService.GetPrimitiveTypes(session).ForEach(x => NodeBuilder.RegisterPrimitiveType(x)); }
// // GET: /Sessions/Create public ActionResult Create() { var sessionViewModel = new SessionViewModel(); sessionViewModel.Session = new Session(); sessionViewModel.Locations = _locationRepository.GetAllLocations() .Select(loc => new SelectListItem { Text = loc.Name, Value = loc.Id.ToString() }); return View(sessionViewModel); }
/// <summary> /// NoteBubbleAnimation Constructor. /// </summary> /// <param name="nVM">Linked with the NoteViewModel</param> /// <param name="s">The current SessionViewModel</param> public NoteAnimation(NoteViewModel nVM, SessionViewModel s) : base() { sessionVM = s; noteVM = nVM; SVItem = nVM.SVItem; ParentSV = nVM.ParentSV; NothingAtThisPlace = true; SVItem.ContainerManipulationCompleted += new ContainerManipulationCompletedEventHandler(touchLeave); SVItem.PreviewTouchDown += new EventHandler<TouchEventArgs>(SVItem_PreviewTouchDown); }
public ActionResult Create(SessionViewModel model) { if (!ModelState.IsValid) { return View(model); } var result = commandExecutor.Execute(new CreateSessionCommand(model)); if (result.IsSuccess()) { authenticator.SetAuthCookie(model.Username, model.PersistCookie); return RedirectToAction("Index", "Home"); } ModelState.AddModelError("", result.CombinedErrors()); return View(model); }
/// <summary> /// Constructor. /// Create a SessionAnimation with the current SessionViewModel /// </summary> /// <param name="s"></param> public SessionAnimation(SessionViewModel s) : base() { SessionVM = s; Storyboard InitStb = new Storyboard(); DoubleAnimation openingAnimation = new DoubleAnimation(); initWidthAnimation = new DoubleAnimation(); DoubleAnimation initHeightAnimation = new DoubleAnimation(); ExponentialEase ease = new ExponentialEase(); ease.EasingMode = EasingMode.EaseOut; ease.Exponent = 2; openingAnimation.From = 0; openingAnimation.To = 1; openingAnimation.Duration = new Duration(TimeSpan.FromSeconds(.5)); openingAnimation.FillBehavior = FillBehavior.HoldEnd; InitStb.Children.Add(openingAnimation); Storyboard.SetTarget(openingAnimation, SessionVM.SessionSVI); Storyboard.SetTargetProperty(openingAnimation, new PropertyPath(ScatterViewItem.OpacityProperty)); initWidthAnimation.From = s.SessionSVI.Width * 0.8; initWidthAnimation.To = s.SessionSVI.Width; initWidthAnimation.Duration = new Duration(TimeSpan.FromSeconds(.6)); initWidthAnimation.EasingFunction = ease; initWidthAnimation.FillBehavior = FillBehavior.Stop; InitStb.Children.Add(initWidthAnimation); Storyboard.SetTarget(initWidthAnimation, SessionVM.SessionSVI); Storyboard.SetTargetProperty(initWidthAnimation, new PropertyPath(ScatterViewItem.WidthProperty)); initHeightAnimation.From = s.SessionSVI.Height * 0.8; initHeightAnimation.To = s.SessionSVI.Height; initHeightAnimation.Duration = new Duration(TimeSpan.FromSeconds(.6)); initHeightAnimation.EasingFunction = ease; initHeightAnimation.FillBehavior = FillBehavior.Stop; InitStb.Children.Add(initHeightAnimation); Storyboard.SetTarget(initHeightAnimation, SessionVM.SessionSVI); Storyboard.SetTargetProperty(initHeightAnimation, new PropertyPath(ScatterViewItem.HeightProperty)); initWidthAnimation.Completed += new EventHandler(marginAnimation_Completed); SessionVM.SessionSVI.TouchLeave += new EventHandler<System.Windows.Input.TouchEventArgs>(svi_TouchLeave); SessionVM.SessionSVI.TouchEnter += new EventHandler<System.Windows.Input.TouchEventArgs>(SessionSVI_TouchEnter); InitStb.Begin(); }
/// <summary> /// NoteBubbleAnimation Constructor. /// </summary> /// <param name="nbVM">Linked with the NoteBubbleVM</param> /// <param name="s">The current SessionViewModel</param> public NoteBubbleAnimation(NoteBubbleViewModel nbVM, SessionViewModel s) : base() { sessionVM = s; noteBubbleVM = nbVM; SVItem = nbVM.SVItem; ParentSV = nbVM.ParentSV; canAnimate = true; NothingAtThisPlace = true; noteBubbleDT = new DispatcherTimer(); noteBubbleDT.Tick += new EventHandler(t_Tick); SVItem.ContainerManipulationCompleted += touchLeave; SVItem.PreviewTouchDown += touchDown; Animate(); }
/// <summary> /// MelodyBubbleAnimation's Constructor. /// </summary> /// <param name="mbVM"></param> /// <param name="s"></param> public MelodyBubbleAnimation(MelodyBubbleViewModel mbVM, SessionViewModel s) : base() { melodyBubbleVM = mbVM; sessionVM = s; SVItem = mbVM.SVItem; ParentSV = mbVM.ParentSV; canAnimate = true; playUp = 0; DispatcherTimer.Tick += new EventHandler(t_Tick); SVItem.ContainerManipulationCompleted += new ContainerManipulationCompletedEventHandler(touchLeave); SVItem.PreviewTouchDown += new EventHandler<TouchEventArgs>(touchDown); SVItem.PreviewTouchUp += new EventHandler<TouchEventArgs>(SVItem_PreviewTouchUp); Animate(); }
private IHttpActionResult GetSessionResult(Session session) { var result = new SessionViewModel() { Id = session.Id, CreatedOn = session.CreatedOn, ExpiredOn = session.ExpiredOn }; return Ok(result); }
//[HttpPost] //[AllowAnonymous] //public ActionResult ImportWords() //{ // var entities = new db38bab79d27554b96b50aa57c010cd149Entities3(); // string pathToExcelFile = "" //+ @"D:\Words.xls"; // string[] SheetNames = new string[] { "Session 1, 7", "Session 2, 8", "Session 3, 9", "Session 4, 10", "Session 5, 11", "Session 6, 12" }; // string[] stringSeparators = new string[] { ", " }; // var excelFile = new ExcelQueryFactory(pathToExcelFile); // for (int i = 0; i < SheetNames.Length; i++ ) // { // var sheetName = SheetNames[i]; // var rows = from a in excelFile.Worksheet(sheetName) select a; // foreach (var r in rows) // { // var word = new Word(); // word.Arabic = r["Arabic"]; // word.English = r["English"]; // word.ListId = i; // entities.Words.Add(word); // entities.SaveChanges(); // } // } // AjaxResponse response = new AjaxResponse(); // response.Success = true; // response.Message = "It worked."; // return Json(response); //} public ActionResult UpdateSession(SessionViewModel form) { AjaxResponse response = new AjaxResponse(); response.Success = false; response.Message = "Nothing happened."; var entities = new db38bab79d27554b96b50aa57c010cd149Entities3(); Session newSession; if (form.SessionID == null || form.SessionID == string.Empty) { newSession = new Session(); entities.Sessions.Add(newSession); } else { int parsedID = Int32.Parse(form.SessionID); newSession = entities.Sessions.Where(x => x.Id == parsedID).FirstOrDefault(); } newSession.Name = form.Name; var part = entities.Participants.Where(x => x.Id == form.ParticipantID).FirstOrDefault(); var feedback = entities.FeedbackConditions.Where(x => x.Id == form.FeedbackModeID).FirstOrDefault(); newSession.FeedbackCondition = feedback; newSession.Participant = part; newSession.WordListId = form.WordListId; entities.SaveChanges(); foreach(var block in form.TrialBlocks) { TrialBlock newTB; if (block.ID == null) { newTB = new TrialBlock(); } else { newTB = entities.TrialBlocks.Where(x => x.Id == block.ID).FirstOrDefault(); newTB.FailProfiles.Clear(); newTB.PassProfiles.Clear(); } newTB.IndexInSession = block.IndexInSession; foreach (var id in block.ProfilesIDsToFail) { var profile = entities.Profiles.Where(x => x.Id == id).FirstOrDefault(); newTB.FailProfiles.Add(profile); } foreach (var id in block.ProfilesIDsToPass) { var profile = entities.Profiles.Where(x => x.Id == id).FirstOrDefault(); newTB.PassProfiles.Add(profile); } if (block.ID == null) { newSession.TrialBlocks.Add(newTB); } } entities.SaveChanges(); response.Success = true; response.Message = "Changes saved to database"; return Json(response); }
public ActionResult EditSession(int? sessionID) { var entities = new db38bab79d27554b96b50aa57c010cd149Entities3(); var sessionUser = (string)Session["User"]; if (sessionUser != null && adminPasswordsByUsername.ContainsKey(sessionUser)) { SessionViewModel viewModel; if (sessionID == null) { viewModel = new SessionViewModel(entities.FeedbackConditions, entities.Profiles, entities.Participants); } else { var existingSession = entities.Sessions.Where(x => x.Id == sessionID).FirstOrDefault(); viewModel = new SessionViewModel(entities.FeedbackConditions, entities.Profiles, entities.Participants, existingSession); } return View(viewModel); } return Index(); }
/// <summary> /// Constructor. /// </summary> /// <param name="s">The current SessionViewModel</param> /// <param name="reduced">True if the session is reduced</param> /// <param name="desktop">The DesktopView</param> public SessionAnimation(SessionViewModel s, bool reduced, DesktopView desktop) : base() { MainDesktop = desktop; SessionVM = s; SessionVM.SessionSVI.TouchLeave += new EventHandler<TouchEventArgs>(svi_TouchLeave); SessionVM.SessionSVI.PreviewTouchDown += new EventHandler<TouchEventArgs>(SessionSVI_TouchEnter); }
/// <summary> /// Provides a deterministic way to delete the Session property. /// </summary> public static void ClearSession() { _session.Cleanup(); _session = null; }
/// <summary> /// Provides a deterministic way to create the Session property. /// </summary> public static void CreateSession() { if (_session == null) { _session = new SessionViewModel(); } }
// // GET: /Sessions/Edit/5 public ActionResult Edit(int id) { var session = _sessionRepository.Get(id); var sessionViewModel = new SessionViewModel(); sessionViewModel.Locations = _locationRepository.GetAllLocations() .Select(loc => new SelectListItem { Text = loc.Name, Value = loc.Id.ToString(), Selected = session.LocationId == loc.Id }); sessionViewModel.Session = session; return View(sessionViewModel); }
public ActionResult Edit(SessionViewModel viewModel, string[] ids) { // if(ModelState.IsValid) // { // _sessionRepository.Update(viewModel.Session); // return RedirectToAction("Index"); // } try { // var context = new BdtContext(); // Retrieve the item _sessionRepository.Update(viewModel.Session); // get the entry, so we can manipulate its state // var itemEntry = context.Entry(item); // Make the entity modified // itemEntry.State = EntityState.Modified; // // Load the existing associated categories // itemEntry.Collection(i => i.Locations).Load(); // // Remove all the existing associated categories // item.Locations.Clear(); // // // Retrieve the list of ids from the form submission (comes in comma-delimited string) // string categories = string.Join(",", ids); // // Split to an array // var categoryIDs = categories.Split(','); // // Iterate through each ID // foreach (string locId in categoryIDs) // { // int lid = int.Parse(locId); // // Add Items that aren't already present // item.Locations.Add(context.Locations.Find(lid)); // } // context.SaveChanges(); return RedirectToAction("Index"); } catch (Exception) { return View(viewModel); } }