/// <summary> /// Builds the <see cref="DotvvmView"/> for the specified HTTP request, resolves the master page hierarchy and performs the composition. /// </summary> public DotvvmView BuildView(DotvvmRequestContext context) { // get the page markup var markup = markupFileLoader.GetMarkupFileVirtualPath(context); // build the page var pageBuilder = controlBuilderFactory.GetControlBuilder(markup); var contentPage = pageBuilder.BuildControl(controlBuilderFactory) as DotvvmView; FillsDefaultDirectives(contentPage, context.Configuration); // check for master page and perform composition recursively while (IsNestedInMasterPage(contentPage)) { // load master page var masterPageFile = contentPage.Directives[ParserConstants.MasterPageDirective]; var masterPage = (DotvvmView)controlBuilderFactory.GetControlBuilder(masterPageFile).BuildControl(controlBuilderFactory); FillsDefaultDirectives(masterPage, context.Configuration); PerformMasterPageComposition(contentPage, masterPage); masterPage.ViewModelType = contentPage.ViewModelType; contentPage = masterPage; } // verifies the SPA request VerifySpaRequest(context, contentPage); return(contentPage); }
public void RenderPostbackUpdatedControls(DotvvmRequestContext request, DotvvmView page) { var context = new RenderContext(request); var stack = new Stack <DotvvmControl>(); stack.Push(page); do { var control = stack.Pop(); object val; if (control.properties != null && control.properties.TryGetValue(PostBack.UpdateProperty, out val) && val is bool && (bool)val) { using (var w = new StringWriter()) { control.EnsureControlHasId(); control.Render(new HtmlWriter(w, request), context); request.PostBackUpdatedControls[control.ID] = w.ToString(); } } else { foreach (var child in control.GetChildren()) { stack.Push(child); } } } while (stack.Count > 0); }
public void TestInit() { configuration = DotvvmConfiguration.CreateDefault(); configuration.Security.SigningKey = Convert.FromBase64String("Uiq1FXs016lC6QaWIREB7H2P/sn4WrxkvFkqaIKpB27E7RPuMipsORgSgnT+zJmUu8zXNSJ4BdL73JEMRDiF6A1ScRNwGyDxDAVL3nkpNlGrSoLNM1xHnVzSbocLFDrdEiZD2e3uKujguycvWSNxYzjgMjXNsaqvCtMu/qRaEGc="); configuration.Security.EncryptionKey = Convert.FromBase64String("jNS9I3ZcxzsUSPYJSwzCOm/DEyKFNlBmDGo9wQ6nxKg="); serializer = new DefaultViewModelSerializer(new DefaultViewModelProtector()); context = new DotvvmRequestContext() { Configuration = configuration, OwinContext = new Microsoft.Owin.Fakes.StubIOwinContext() { RequestGet = () => new Microsoft.Owin.Fakes.StubIOwinRequest() { UriGet = () => new Uri("http://localhost:8628/Sample1"), UserGet = () => new WindowsPrincipal(WindowsIdentity.GetAnonymous()), HeadersGet = () => new HeaderDictionary(new Dictionary <string, string[]>()), EnvironmentGet = () => new Dictionary <string, object>() { { "owin.RequestPathBase", "" } } } }, ResourceManager = new ResourceManager(configuration), Presenter = configuration.RouteTable.GetDefaultPresenter() }; }
/// <summary> /// Resolves the command for the specified post data. /// </summary> public void ResolveCommand(DotvvmRequestContext context, DotvvmView view, string serializedPostData, out ActionInfo actionInfo) { // get properties var data = JObject.Parse(serializedPostData); var path = data["currentPath"].Values <string>().ToArray(); var command = data["command"].Value <string>(); var controlUniqueId = data["controlUniqueId"]?.Value <string>(); if (string.IsNullOrEmpty(command)) { // empty command actionInfo = null; } else { // find the command target if (!string.IsNullOrEmpty(controlUniqueId)) { var target = view.FindControlByUniqueId(controlUniqueId); if (target == null) { throw new Exception(string.Format("The control with ID '{0}' was not found!", controlUniqueId)); } actionInfo = commandResolver.GetFunction(target, view, context, path, command); } else { actionInfo = commandResolver.GetFunction(view, context, path, command); } } }
public void TestInit() { configuration = DotvvmConfiguration.CreateDefault(services => { services.AddSingleton <IDataProtectionProvider>(new DpapiDataProtectionProvider("DotVVM Tests")); services.AddTransient <IViewModelProtector, DefaultViewModelProtector>(); services.AddTransient <ICsrfProtector, DefaultCsrfProtector>(); services.AddSingleton <ICookieManager, ChunkingCookieManager>(); services.AddSingleton <IDotvvmCacheAdapter, OwinDotvvmCacheAdapter>(); }); configuration.Security.SigningKey = Convert.FromBase64String("Uiq1FXs016lC6QaWIREB7H2P/sn4WrxkvFkqaIKpB27E7RPuMipsORgSgnT+zJmUu8zXNSJ4BdL73JEMRDiF6A1ScRNwGyDxDAVL3nkpNlGrSoLNM1xHnVzSbocLFDrdEiZD2e3uKujguycvWSNxYzjgMjXNsaqvCtMu/qRaEGc="); configuration.Security.EncryptionKey = Convert.FromBase64String("jNS9I3ZcxzsUSPYJSwzCOm/DEyKFNlBmDGo9wQ6nxKg="); var requestMock = new Mock <IHttpRequest>(); requestMock.SetupGet(m => m.Url).Returns(new Uri("http://localhost:8628/Sample1")); requestMock.SetupGet(m => m.Path).Returns(new DotvvmHttpPathString(new PathString("/Sample1"))); requestMock.SetupGet(m => m.PathBase).Returns(new DotvvmHttpPathString(new PathString(""))); requestMock.SetupGet(m => m.Method).Returns("GET"); requestMock.SetupGet(m => m.Headers).Returns(new DotvvmHeaderCollection(new HeaderDictionary(new Dictionary <string, string[]>()))); var contextMock = new Mock <IHttpContext>(); contextMock.SetupGet(m => m.Request).Returns(requestMock.Object); contextMock.SetupGet(m => m.User).Returns(new WindowsPrincipal(WindowsIdentity.GetAnonymous())); serializer = configuration.ServiceLocator.GetService <IViewModelSerializer>() as DefaultViewModelSerializer; context = new DotvvmRequestContext(contextMock.Object, configuration, configuration.ServiceProvider) { Presenter = configuration.RouteTable.GetDefaultPresenter(configuration.ServiceProvider), Route = new DotvvmRoute("TestRoute", "test.dothtml", new { }, p => p.GetService <DotvvmPresenter>(), configuration) }; }
public void TestInit() { configuration = DotvvmConfiguration.CreateDefault(); configuration.ServiceLocator.RegisterSingleton <IDataProtectionProvider>(() => new DpapiDataProtectionProvider("dotvvm test")); configuration.Security.SigningKey = Convert.FromBase64String("Uiq1FXs016lC6QaWIREB7H2P/sn4WrxkvFkqaIKpB27E7RPuMipsORgSgnT+zJmUu8zXNSJ4BdL73JEMRDiF6A1ScRNwGyDxDAVL3nkpNlGrSoLNM1xHnVzSbocLFDrdEiZD2e3uKujguycvWSNxYzjgMjXNsaqvCtMu/qRaEGc="); configuration.Security.EncryptionKey = Convert.FromBase64String("jNS9I3ZcxzsUSPYJSwzCOm/DEyKFNlBmDGo9wQ6nxKg="); var requestMock = new Mock <IOwinRequest>(); requestMock.SetupGet(m => m.Uri).Returns(new Uri("http://localhost:8628/Sample1")); requestMock.SetupGet(m => m.User).Returns(new WindowsPrincipal(WindowsIdentity.GetAnonymous())); requestMock.SetupGet(m => m.Headers).Returns(new HeaderDictionary(new Dictionary <string, string[]>())); requestMock.SetupGet(m => m.Environment).Returns(new Dictionary <string, object>() { { "owin.RequestPathBase", "" } }); var contextMock = new Mock <IOwinContext>(); contextMock.SetupGet(m => m.Request).Returns(requestMock.Object); serializer = new DefaultViewModelSerializer(configuration); context = new DotvvmRequestContext() { Configuration = configuration, OwinContext = contextMock.Object, ResourceManager = new ResourceManager(configuration), Presenter = configuration.RouteTable.GetDefaultPresenter(), ViewModelSerializer = serializer }; }
public async Task WriteHtmlResponse(DotvvmRequestContext context, DotvvmView view) { // return the response context.OwinContext.Response.ContentType = "text/html; charset=utf-8"; context.OwinContext.Response.Headers["Cache-Control"] = "no-cache"; var html = RenderPage(context, view); await context.OwinContext.Response.WriteAsync(html); }
public async Task WriteViewModelResponse(DotvvmRequestContext context, DotvvmView view) { // return the response context.OwinContext.Response.ContentType = "application/json; charset=utf-8"; context.OwinContext.Response.Headers["Cache-Control"] = "no-cache"; var serializedViewModel = context.GetSerializedViewModel(); await context.OwinContext.Response.WriteAsync(serializedViewModel); }
private DotvvmControl CompileMarkup(string markup, Dictionary <string, string> markupFiles = null, bool compileTwice = false, [CallerMemberName] string fileName = null) { if (markupFiles == null) { markupFiles = new Dictionary <string, string>(); } markupFiles[fileName + ".dothtml"] = markup; context = new DotvvmRequestContext(); context.Configuration = DotvvmTestHelper.CreateConfiguration(services => { services.AddSingleton <IMarkupFileLoader>(new FakeMarkupFileLoader(markupFiles)); services.AddSingleton <CustomControlFactory>((s, t) => t == typeof(TestCustomDependencyInjectionControl) ? new TestCustomDependencyInjectionControl("") { IsCorrectlyCreated = true } : throw new Exception()); }); context.Services = context.Services.GetRequiredService <IServiceScopeFactory>().CreateScope().ServiceProvider; context.Configuration.ApplicationPhysicalPath = Path.GetTempPath(); context.Configuration.Markup.Controls.Add(new DotvvmControlConfiguration() { TagPrefix = "cc", TagName = "Test1", Src = "test1.dothtml" }); context.Configuration.Markup.Controls.Add(new DotvvmControlConfiguration() { TagPrefix = "cc", TagName = "Test2", Src = "test2.dothtml" }); context.Configuration.Markup.Controls.Add(new DotvvmControlConfiguration() { TagPrefix = "cc", TagName = "Test3", Src = "test3.dothtml" }); context.Configuration.Markup.Controls.Add(new DotvvmControlConfiguration() { TagPrefix = "cc", TagName = "Test4", Src = "test4.dothtml" }); context.Configuration.Markup.Controls.Add(new DotvvmControlConfiguration() { TagPrefix = "cc", TagName = "Test5", Src = "test5.dothtml" }); context.Configuration.Markup.AddCodeControls("ff", typeof(TestControl)); context.Configuration.Markup.AddAssembly(typeof(DefaultViewCompilerTests).GetTypeInfo().Assembly.GetName().Name); var controlBuilderFactory = context.Services.GetRequiredService <IControlBuilderFactory>(); var(_, controlBuilder) = controlBuilderFactory.GetControlBuilder(fileName + ".dothtml"); var result = controlBuilder.Value.BuildControl(controlBuilderFactory, context.Services); if (compileTwice) { result = controlBuilder.Value.BuildControl(controlBuilderFactory, context.Services); } result.SetValue(Internal.RequestContextProperty, context); return(result); }
/// <summary> /// Serializes the view model. /// </summary> public string SerializeViewModel(DotvvmRequestContext context) { if (SendDiff && context.ReceivedViewModelJson != null && context.ViewModelJson["viewModel"] != null) { context.ViewModelJson["viewModelDiff"] = JsonUtils.Diff((JObject)context.ReceivedViewModelJson["viewModel"], (JObject)context.ViewModelJson["viewModel"], true); context.ViewModelJson.Remove("viewModel"); } return(context.ViewModelJson.ToString(JsonFormatting)); }
/// <summary> /// Adds the post back updated controls. /// </summary> public void AddPostBackUpdatedControls(DotvvmRequestContext context) { var result = new JObject(); foreach (var control in context.PostBackUpdatedControls) { result[control.Key] = JValue.CreateString(control.Value); } context.ViewModelJson["updatedControls"] = result; }
/// <summary> /// Builds the view model for the client. /// </summary> public void BuildViewModel(DotvvmRequestContext context) { // serialize the ViewModel var serializer = CreateJsonSerializer(); var viewModelConverter = new ViewModelJsonConverter(context.IsPostBack) { UsedSerializationMaps = new HashSet <ViewModelSerializationMap>() }; serializer.Converters.Add(viewModelConverter); var writer = new JTokenWriter(); serializer.Serialize(writer, context.ViewModel); // persist CSRF token writer.Token["$csrfToken"] = context.CsrfToken; // persist encrypted values if (viewModelConverter.EncryptedValues.Count > 0) { writer.Token["$encryptedValues"] = viewModelProtector.Protect(viewModelConverter.EncryptedValues.ToString(Formatting.None), context); } // serialize validation rules var validationRules = SerializeValidationRules(viewModelConverter); // create result object var result = new JObject(); result["viewModel"] = writer.Token; result["url"] = context.OwinContext.Request.Uri.PathAndQuery; result["virtualDirectory"] = DotvvmMiddleware.GetVirtualDirectory(context.OwinContext); if (context.IsPostBack || context.IsSpaRequest) { result["action"] = "successfulCommand"; var renderedResources = new HashSet <string>(context.ReceivedViewModelJson?["renderedResources"]?.Values <string>() ?? new string[] { }); result["resources"] = BuildResourcesJson(context, rn => !renderedResources.Contains(rn)); } else { result["renderedResources"] = JArray.FromObject(context.ResourceManager.RequiredResources); } // TODO: do not send on postbacks if (validationRules.Count > 0) { result["validationRules"] = validationRules; } context.ViewModelJson = result; }
protected string RenderPage(DotvvmRequestContext context, DotvvmView view) { // embed resource links EmbedResourceLinks(view); // prepare the render context // get the HTML using (var textWriter = new StringWriter()) { var htmlWriter = new HtmlWriter(textWriter, context); view.Render(htmlWriter, context); return(textWriter.ToString()); } }
public void CommandResolver_Valid_SimpleTest() { var path = new[] { ValueBindingExpression.CreateBinding <object>(bindingService, vm => ((Test1)vm[0]).A[0], (DataContextStack)null) }; var commandId = "someCommand"; var command = new CommandBindingExpression(bindingService, vm => { ((TestA)vm[0]).Test(((TestA)vm[0]).StringToPass, ((dynamic)vm[1]).NumberToPass); }, commandId); var testObject = new Test1 { A = new[] { new TestA() { StringToPass = "******" } }, NumberToPass = 16 }; var viewRoot = new DotvvmView() { DataContext = testObject }; viewRoot.SetBinding(Controls.Validation.TargetProperty, ValueBindingExpression.CreateBinding(bindingService, vm => vm.Last(), new ParametrizedCode("$root"))); var placeholder = new HtmlGenericControl("div"); placeholder.SetBinding(DotvvmBindableObject.DataContextProperty, path[0]); viewRoot.Children.Add(placeholder); var button = new Button(); button.SetBinding(ButtonBase.ClickProperty, command); placeholder.Children.Add(button); var resolver = new CommandResolver(); var context = new DotvvmRequestContext() { ViewModel = testObject }; context.ModelState.ValidationTargetPath = KnockoutHelper.GetValidationTargetExpression(button); resolver.GetFunction(viewRoot, context, path.Select(v => v.GetProperty <SimplePathExpressionBindingProperty>().Code.FormatKnockoutScript(button, v)).ToArray(), commandId, new object[0]).Action(); Assert.AreEqual(testObject.NumberToPass, testObject.A[0].ResultInt); Assert.AreEqual(testObject.A[0].ResultString, testObject.A[0].ResultString); }
/// <summary> /// If the request is SPA request, we need to verify that the page contains the same SpaContentPlaceHolder. /// Also we need to check that the placeholder is the same. /// </summary> private void VerifySpaRequest(DotvvmRequestContext context, DotvvmView page) { if (context.IsSpaRequest) { var spaContentPlaceHolders = page.GetAllDescendants().OfType <SpaContentPlaceHolder>().ToList(); if (spaContentPlaceHolders.Count > 1) { throw new Exception("Multiple controls of type <dot:SpaContentPlaceHolder /> found on the page! This control can be used only once!"); // TODO: exception handling } if (spaContentPlaceHolders.Count == 0 || spaContentPlaceHolders[0].GetSpaContentPlaceHolderUniqueId() != context.GetSpaContentPlaceHolderUniqueId()) { // the client has loaded different page which does not contain current SpaContentPlaceHolder - he needs to be redirected context.Redirect(context.OwinContext.Request.Uri.AbsoluteUri); } } }
public void CommandResolver_Valid_SimpleTest() { var path = new[] { new ValueBindingExpression(vm => ((dynamic)vm[0]).A[0], "A()[0]") }; var commandId = "someCommand"; var command = new CommandBindingExpression(vm => ((TestA)vm[0]).Test(((TestA)vm[0]).StringToPass, ((dynamic)vm[1]).NumberToPass), commandId); var testObject = new { A = new[] { new TestA() { StringToPass = "******" } }, NumberToPass = 16 }; var viewRoot = new DotvvmView() { DataContext = testObject }; viewRoot.SetBinding(Validate.TargetProperty, new ValueBindingExpression(vm => vm.Last(), "$root")); var placeholder = new HtmlGenericControl("div"); placeholder.SetBinding(DotvvmBindableObject.DataContextProperty, path[0]); viewRoot.Children.Add(placeholder); var button = new Button(); button.SetBinding(ButtonBase.ClickProperty, command); placeholder.Children.Add(button); var resolver = new CommandResolver(); var context = new DotvvmRequestContext() { ViewModel = testObject }; context.ModelState.ValidationTargetPath = KnockoutHelper.GetValidationTargetExpression(button); resolver.GetFunction(viewRoot, context, path.Select(v => v.Javascript).ToArray(), commandId).Action(); Assert.AreEqual(testObject.NumberToPass, testObject.A[0].ResultInt); Assert.AreEqual(testObject.A[0].ResultString, testObject.A[0].ResultString); }
private DotvvmControl CompileMarkup(string markup, Dictionary <string, string> markupFiles = null, bool compileTwice = false, [CallerMemberName] string fileName = null) { if (markupFiles == null) { markupFiles = new Dictionary <string, string>(); } markupFiles[fileName + ".dothtml"] = markup; context = new DotvvmRequestContext(); context.Configuration = DotvvmConfiguration.CreateDefault(services => { services.AddSingleton <IMarkupFileLoader>(new FakeMarkupFileLoader(markupFiles)); }); context.Configuration.ApplicationPhysicalPath = Path.GetTempPath(); context.Configuration.Markup.Controls.Add(new DotvvmControlConfiguration() { TagPrefix = "cc", TagName = "Test1", Src = "test1.dothtml" }); context.Configuration.Markup.Controls.Add(new DotvvmControlConfiguration() { TagPrefix = "cc", TagName = "Test2", Src = "test2.dothtml" }); context.Configuration.Markup.Controls.Add(new DotvvmControlConfiguration() { TagPrefix = "cc", TagName = "Test3", Src = "test3.dothtml" }); context.Configuration.Markup.Controls.Add(new DotvvmControlConfiguration() { TagPrefix = "cc", TagName = "Test4", Src = "test4.dothtml" }); context.Configuration.Markup.AddCodeControl("ff", typeof(TestControl)); context.Configuration.Markup.AddAssembly(typeof(DefaultViewCompilerTests).GetTypeInfo().Assembly.GetName().Name); var controlBuilderFactory = context.Configuration.ServiceLocator.GetService <IControlBuilderFactory>(); var controlBuilder = controlBuilderFactory.GetControlBuilder(fileName + ".dothtml"); var result = controlBuilder.BuildControl(controlBuilderFactory); if (compileTwice) { result = controlBuilder.BuildControl(controlBuilderFactory); } return(result); }
/// <summary> /// Generates the Identicon image and returns it to the client. /// </summary> public Task ProcessRequest(DotvvmRequestContext context) { // generate the identicon var identicon = new IdenticonGenerator("SHA512", new Size(180, 180), Color.White, new Size(8, 8)) { DefaultBrushGenerator = new StaticColorBrushGenerator(Color.FromArgb(255, 41, 128, 185)), DefaultBlockGenerators = IdenticonGenerator.ExtendedBlockGeneratorsConfig }; var name = Convert.ToString(context.Parameters["Identicon"]); using (var bitmap = identicon.Create(name)) { // save it in the response stream context.OwinContext.Response.ContentType = "image/png"; bitmap.Save(context.OwinContext.Response.Body, ImageFormat.Png); } return(Task.FromResult(0)); }
/// <summary> /// Populates the view model from the data received from the request. /// </summary> /// <returns></returns> public void PopulateViewModel(DotvvmRequestContext context, string serializedPostData) { // get properties var data = context.ReceivedViewModelJson = JObject.Parse(serializedPostData); var viewModelToken = (JObject)data["viewModel"]; // load CSRF token context.CsrfToken = viewModelToken["$csrfToken"].Value <string>(); ViewModelJsonConverter viewModelConverter; if (viewModelToken["$encryptedValues"] != null) { // load encrypted values var encryptedValuesString = viewModelToken["$encryptedValues"].Value <string>(); viewModelConverter = new ViewModelJsonConverter(context.IsPostBack, viewModelMapper, JObject.Parse(viewModelProtector.Unprotect(encryptedValuesString, context))); } else { viewModelConverter = new ViewModelJsonConverter(context.IsPostBack, viewModelMapper); } // get validation path context.ModelState.ValidationTargetPath = data["validationTargetPath"].Value <string>(); // populate the ViewModel var serializer = CreateJsonSerializer(); serializer.Converters.Add(viewModelConverter); try { viewModelConverter.Populate(viewModelToken, serializer, context.ViewModel); } catch (Exception ex) { throw new Exception($"Could not deserialize viewModel of type { context.ViewModel.GetType().Name }. {GeneralViewModelRecomendations}", ex); } }
private static void ConfigureAADAuthentication(IAppBuilder app) { app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions { Authority = $"https://login.microsoftonline.com/{ConfigurationManager.AppSettings["ida:TenantId"]}/", ClientId = ConfigurationManager.AppSettings["ida:ClientId"], AuthenticationMode = AuthenticationMode.Passive, TokenValidationParameters = new TokenValidationParameters() { ValidateIssuer = (ConfigurationManager.AppSettings["ida:TenantId"] != "common") }, Notifications = new OpenIdConnectAuthenticationNotifications { RedirectToIdentityProvider = context => { // determines the base URL of the application (useful when the app can run on multiple domains) var appBaseUrl = GetApplicationBaseUrl(context.Request); if (context.ProtocolMessage.RequestType == OpenIdConnectRequestType.AuthenticationRequest) { context.ProtocolMessage.RedirectUri = appBaseUrl; // we need to handle the redirect to the login page ourselves because redirects cannot use HTTP 302 in DotVVM var redirectUri = context.ProtocolMessage.CreateAuthenticationRequestUrl(); DotvvmRequestContext.SetRedirectResponse(DotvvmMiddleware.ConvertHttpContext(context.OwinContext), redirectUri, (int)HttpStatusCode.Redirect, true); context.HandleResponse(); } else if (context.ProtocolMessage.RequestType == OpenIdConnectRequestType.LogoutRequest) { context.ProtocolMessage.PostLogoutRedirectUri = appBaseUrl; // we need to handle the redirect to the logout page ourselves because redirects cannot use HTTP 302 in DotVVM var redirectUri = context.ProtocolMessage.CreateLogoutRequestUrl(); DotvvmRequestContext.SetRedirectResponse(DotvvmMiddleware.ConvertHttpContext(context.OwinContext), redirectUri, (int)HttpStatusCode.Redirect, true); context.HandleResponse(); } return(Task.FromResult(0)); }, SecurityTokenValidated = context => { var isMultiTenant = ConfigurationManager.AppSettings["ida:TenantId"] == "common"; if (isMultiTenant) { // validate allowed tenants var tenants = ConfigurationManager.AppSettings["ida:Tenants"].Split(','); var tokenTenant = context.AuthenticationTicket.Identity.FindFirstValue(AzureAdClaimTypes.TenantId); if (!tenants.Contains(tokenTenant)) { throw new SecurityTokenValidationException($"Tenant {tokenTenant} is not allowed to sign in to the application!"); } } // create user if it doesn't exists var upn = context.AuthenticationTicket.Identity.FindFirstValue(AzureAdClaimTypes.Upn); var user = LoginHelper.GetClaimsIdentityForAzure(upn); if (user == null) { var newUser = new UserInfoData { Email = context.AuthenticationTicket.Identity.FindFirstValue(AzureAdClaimTypes.Upn), FirstName = context.AuthenticationTicket.Identity.FindFirstValue(AzureAdClaimTypes.GivenName), LastName = context.AuthenticationTicket.Identity.FindFirstValue(AzureAdClaimTypes.Surname), Name = context.AuthenticationTicket.Identity.FindFirstValue(AzureAdClaimTypes.DisplayName), UserRole = UserRole.User, Password = new Guid().ToString() }; UserService.CreateOrUpdateUserInfo(newUser); // create identity for the new user user = LoginHelper.GetClaimsIdentityForAzure(upn); } context.AuthenticationTicket = new AuthenticationTicket(user, context.AuthenticationTicket.Properties); return(Task.FromResult(0)); } } }); }
/// <summary> /// Processes the request. /// </summary> public abstract Task ProcessRequest(DotvvmRequestContext context);
/// <summary> /// Processes the request. /// </summary> public override Task ProcessRequest(DotvvmRequestContext context) { context.Presenter = presenterFactory(); return(context.Presenter.ProcessRequest(context)); }
/// <summary> /// Initializes a new instance of the <see cref="RenderContext"/> class. /// </summary> public RenderContext(DotvvmRequestContext request) { CurrentPageArea = "root"; RequestContext = request; }
/// <summary> /// Resolves the command called on the ViewModel. /// </summary> public ActionInfo GetFunction(DotvvmControl viewRootControl, DotvvmRequestContext context, string[] path, string command) { return(GetFunction(null, viewRootControl, context, path, command)); }
/// <summary> /// Resolves the command called on the DotvvmControl. /// </summary> public ActionInfo GetFunction(DotvvmControl targetControl, DotvvmControl viewRootControl, DotvvmRequestContext context, string[] path, string commandId) { // event validation var validationTargetPath = context.ModelState.ValidationTargetPath; FindBindingResult findResult = null; if (targetControl == null) { findResult = eventValidator.ValidateCommand(path, commandId, viewRootControl, validationTargetPath); } else { findResult = eventValidator.ValidateControlCommand(path, commandId, viewRootControl, targetControl, validationTargetPath); } context.ModelState.ValidationTarget = findResult.Control.GetValue(Controls.Validation.TargetProperty) ?? context.ViewModel; return(new ActionInfo { Action = () => findResult.Binding.Evaluate(findResult.Control, findResult.Property), Binding = findResult.Binding, IsControlCommand = targetControl != null }); }
public Task ProcessRequest(DotvvmRequestContext context) { context.RedirectToRoute("FeatureSamples_Redirect_Redirect"); throw new Exception("This should never happen!"); }
public void TestInit() { context = new DotvvmRequestContext(); context.Configuration = DotvvmConfiguration.CreateDefault(); }