/// <summary>
        /// Add the ViewState input to the ViewBag for rendering in the view
        /// </summary>
        public static void SaveViewState(this IPersistentController inst)
        {
            inst.ViewBag.SessionStorage = ViewBagSessionStorage(inst, Storage.ViewState);
            var filter = StorageImplementation.EncryptViewState(inst.Configuration);

            inst.ViewBag.ViewState = ViewState(inst, filter);
        }
Beispiel #2
0
        public virtual IActionResult Error()
        {
            var error = this.HttpContext.Features.Get <IExceptionHandlerFeature>();

            if (error != null)
            {
                var    controller = StaticControllerExtension.GetController();
                byte[] bytes;
                if (controller != null &&
                    !StorageImplementation.GetEncryptDatabaseStorage(this.Configuration) &&
                    StorageImplementation.TryGetBytes(controller, out bytes))
                {
                    Guid session;
                    using (var db = new ASP_DBEntities())
                    {
                        // enforce new session, store unencrypted:
                        session = db.SaveMain(controller.GetType(), bytes, Guid.NewGuid());
                    }
                    var host = this.Request.Host.ToString();
                    var path = Regex.Replace(controller.GetType().Name, "Controller$", String.Empty);
                    var url  = String.Format(@"http://{0}/{1}{2}session={3}",
                                             host, path, (path.Contains("?") ? "&" : "?"),
                                             WebUtility.UrlEncode(session.ToString()));
                    this.Request.Headers.Add("_CORE_DUMP", url);

                    this.Logger.LogError(String.Format("_CORE_DUMP={0}", url));
                }
            }
            return(View());
        }
Beispiel #3
0
        /// <summary>
        /// Saves the after having been loaded within the same remote method.
        /// Reloads potentially modified members in the M object to make
        /// changes visible in WebSharper.
        /// </summary>
        /// <typeparam name="M"></typeparam>
        /// <param name="stored">The stored.</param>
        /// <returns>The VIewState string</returns>
        public static string Save <M>(ViewModel <M> stored)
            where M : class, IStored <M>, new()
        {
            stored.SaveMembers();          // Captures members directly mutable on the client side.
            stored.LoadMembers();          // Mirrors side effects of methods on M in the ViewModel.

            switch (stored.SessionStorage) // guaranteed here, whether overridden or not
            {
            case Storage.ViewState:
                var filter = StorageImplementation.EncryptViewState(Configuration);
                stored.SerializeMain(filter);     // save locally into the object
                return(stored.ViewState);

            case Storage.Session:
                StorageImplementation.SaveSession(Configuration, HttpContext, stored.Main);
                return(null);

            case Storage.Database:
                StorageImplementation.SaveDatabase(Configuration, HttpContext, stored.Main);
                return(null);

            default:
                throw new NotImplementedException(String.Format(
                                                      "Storage {0}", stored.SessionStorage));
            }
        }
Beispiel #4
0
        public void LoadFromViewstateExistingTest()
        {
            string obj       = "test value";
            var    viewstate = StorageImplementation.ViewState(obj);
            var    copy      = StorageImplementation.LoadFromViewstate(() => new String("test value"), viewstate);

            Assert.That(copy, Is.EqualTo(obj));
        }
Beispiel #5
0
        public void ViewStateTest()
        {
            string obj       = "test value";
            var    viewstate = StorageImplementation.ViewState(obj);
            var    bytes     = Convert.FromBase64String(viewstate);
            var    copy      = (string)Serialization.Deserialize(bytes);

            Assert.That(copy, Is.EqualTo(obj));
        }
Beispiel #6
0
        public void ViewStateEncryptedTest()
        {
            string obj    = "test value";
            var    secret = StorageImplementation.GetSecret("Key");
            Func <byte[], byte[]> filter = x => Crypt.Encrypt(secret, x);
            var viewstate = StorageImplementation.ViewState(obj, filter);
            var encrypted = Convert.FromBase64String(viewstate);
            var bytes     = Crypt.Decrypt(secret, encrypted);
            var copy      = (string)Serialization.Deserialize(bytes);

            Serialization.Deserialize(bytes);
            Assert.That(copy, Is.EqualTo("test value"));
        }
        public void ViewStateEncryptedTest()
        {
            this.TestProperty = "test value";
            var secret = StorageImplementation.GetSecret("Key");
            Func <byte[], byte[]> filter = x => Crypt.Encrypt(secret, x);
            var viewstate = this.ViewState(filter);
            var fields    = viewstate.Split(":");
            var encrypted = Convert.FromBase64String(fields[1]);
            var bytes     = Crypt.Decrypt(secret, encrypted);
            var copy      = (PersistentControllerExtensionTest)Serialization.Deserialize(bytes);

            Serialization.Deserialize(bytes);
            Assert.That(copy.TestProperty, Is.EqualTo("test value"));
        }
        public static void InitStorage(TestContext context)
        {
            _tempDbFilename = Path.Combine(Path.GetTempPath(), $"{Guid.NewGuid()}.db");

            //Prepare a dummy config for the temporary db file
            IConfigurationBuilder configurationBuilder = new ConfigurationBuilder()
                                                         .AddInMemoryCollection(new List <KeyValuePair <string, string> >()
            {
                new KeyValuePair <string, string>("litedb-path", _tempDbFilename)
            });

            IConfiguration config = configurationBuilder.Build();

            _storage = new StorageLiteDBFactory(config).GetStorageImplementation();
        }
 /// <summary>
 /// name:value pair for the ViewStateInputTagHelper, to be used as
 /// <input viewstate="@ViewBag.ViewState" />
 /// </summary>
 /// <returns></returns>
 internal static string ViewState(this IPersistentController inst, Func <byte[], byte[]> filter = null)
 {
     return(string.Format("{0}:{1}",
                          GetStorageID(inst),
                          StorageImplementation.ViewState(inst, filter)));
 }
Beispiel #10
0
        public void LoadFromViewstateNewTest()
        {
            var copy = StorageImplementation.LoadFromViewstate(() => new String("test value"), null);

            Assert.That(copy, Is.EqualTo("test value"));
        }
        /// <summary>
        /// Custom Controller factory method returning a serialized object if available.
        /// </summary>
        /// <param name="actionContext"></param>
        /// <returns></returns>
        public object Create(ControllerContext actionContext)
        {
            object controller         = null;
            var    controllerTypeInfo = actionContext.ActionDescriptor.ControllerTypeInfo;
            var    controllerType     = controllerTypeInfo.AsType();
            var    storageID          = StorageImplementation.GetStorageID(controllerTypeInfo.Name);
            var    sessionStorageID   = StorageImplementation.GetSessionStorageID(controllerTypeInfo.Name);

            var storage = StorageImplementation.GetStorage(this.Configuration, this.HttpContext, sessionStorageID);

            StorageImplementation.ClearIfRequested(this.HttpContext, storage, storageID);

            Guid sessionOverride;
            Guid session;

            byte[] bytes;
            Func <byte[], byte[]> filter = null;

            // ---------- Direct GET request ?session= from the Database ----------
            if (this.HttpContext.Request.Method == WebRequestMethods.Http.Get &&
                Guid.TryParse(this.HttpContext.Request.Query["session"], out sessionOverride))
            {
                using (var db = new ASP_DBEntities())
                {
                    (bytes, filter) = StorageImplementation.DatabaseBytes(Configuration, HttpContext, storageID, sessionOverride);
                    controller      = DeserializeController(actionContext, controllerTypeInfo, controllerType, bytes, filter);
                }
            }
            else
            {
                // ---------- Load from ViewState ----------
                if (storage == Storage.ViewState &&
                    this.HttpContext.Request.Method == WebRequestMethods.Http.Post &&
                    this.HttpContext.Request.Form.ContainsKey(storageID))
                {
                    // input type=hidden from <input viewstate="@ViewBag.ViewState" />
                    var controllerString = this.HttpContext.Request.Form[storageID];
                    if (!String.IsNullOrEmpty(controllerString))
                    {
                        (bytes, filter) = StorageImplementation.ViewStateBytes(this.Configuration, controllerString);
                        controller      = DeserializeController(actionContext, controllerTypeInfo, controllerType, bytes, filter);
                    }
                }

                // ---------- Load from Session ----------
                else if (storage == Storage.Session &&
                         this.HttpContext.Session.TryGetValue(storageID, out bytes))
                {
                    controller = DeserializeController(actionContext, controllerTypeInfo, controllerType, bytes);
                }

                // ---------- Load from Database ----------
                else if (storage == Storage.Database &&
                         Guid.TryParse(this.HttpContext.Request.Cookies[storageID].FromCookieString()["session"], out session))
                {
                    (bytes, filter) = StorageImplementation.DatabaseBytes(Configuration, HttpContext, storageID, session);
                    controller      = DeserializeController(actionContext, controllerTypeInfo, controllerType, bytes, filter);
                    ((IPersistentController)controller).Session = session;
                }

                // ---------- Load from X-ViewState Header ----------
                else if (storage == Storage.Header &&
                         this.HttpContext.Request.Headers.ContainsKey(StorageImplementation.HeaderName))
                {
                    // input type=hidden from <input viewstate="@ViewBag.ViewState" />
                    var controllerString = this.HttpContext.Request.Headers[StorageImplementation.HeaderName];
                    if (!String.IsNullOrEmpty(controllerString))
                    {
                        (bytes, filter) = StorageImplementation.ViewStateBytes(this.Configuration, controllerString);
                        controller      = DeserializeController(actionContext, controllerTypeInfo, controllerType, bytes, filter);
                    }
                }

                if (controller == null)
                {
                    // ASP.NET Core implementation, no persistence, just return the new controller
                    controller = actionContext.HttpContext.RequestServices.GetService(controllerType);
                }
            }

            return(controller);
        }
 /// <summary>
 /// Add the serialized controller to the session and the storage type to the ViewBag
 /// to be posted such that PersistentControllerActivator can read it.
 /// </summary>
 public static void SaveSession(this IPersistentController inst)
 {
     inst.ViewBag.SessionStorage = ViewBagSessionStorage(inst, Storage.Session);
     inst.HttpContext.Session.Set(GetStorageID(inst), StorageImplementation.Bytes(inst));
 }
 /// <summary>
 /// SessionStorageID-String unique to post/retrieve the storage type
 /// </summary>
 /// <returns></returns>
 public static string GetSessionStorageID(this IPersistentController inst)
 {
     return(StorageImplementation.GetSessionStorageID(inst.GetType().Name));
 }
 /// <summary>
 /// Store the serialized controller to the database. Reference to it is
 /// kept in a persistent cookie.
 /// </summary>
 public static void SaveDatabase(this IPersistentController inst)
 {
     inst.ViewBag.SessionStorage = ViewBagSessionStorage(inst, Storage.Database);
     StorageImplementation.SaveDatabase(inst.Configuration, inst.HttpContext, inst);
 }
Beispiel #15
0
 public void GetSessionStorageNameTest()
 {
     Assert.That(StorageImplementation.GetSessionStorageID(this.GetType().Name),
                 Is.EqualTo("_SESSIONSTORAGEID_StorageImplementationTest"));
 }
Beispiel #16
0
 public SkillController(StorageImplementation storageImplementation)
 {
     _storageImplementation = storageImplementation;
 }
Beispiel #17
0
 public static Task SetStorage(Storage storage)
 {
     StorageImplementation.SetStorage(storage);
     return(Task.FromResult(true));
 }
        public static void SaveHeader(this IPersistentController inst)
        {
            var filter = StorageImplementation.EncryptViewState(inst.Configuration);

            inst.HttpContext.Response.Headers[StorageImplementation.HeaderName] = StorageImplementation.ViewState(inst, filter);
        }
Beispiel #19
0
        /// <summary>
        ///  Mirrors the MVC PersistentControllerActivator for the WebSharper
        ///  context.
        /// </summary>
        /// <typeparam name="M"></typeparam>
        /// <param name="viewModelAccessor">non-thread safe static reference to the ViewModel</param>
        /// <returns></returns>
        // [Remote] -> Yields "Remote methods must not be generic" from WebSharper:
        // https://github.com/dotnet-websharper/core/issues/1048
        public static M Load <M, V>(string viewState, out V viewModelAccessor, Storage?sessionStorage = null)
            where M : class, IStored <M>, new()
            where V : ViewModel <M>, new()
        {
            var storage   = sessionStorage ?? StorageImplementation.GetStorage(Configuration, HttpContext);
            var storageID = StorageImplementation.GetStorageID(typeof(M).Name);
            var getQuery  = RequestQuerySessionMiddleware.Query(HttpContext);

            // Implements StorageImplementation.ClearIfRequested(HttpContext, storage, storageID)
            // for WebSharper Ajax POST requests
            if (getQuery != null &&
                getQuery.TryGetValue("clear", out string getClear) &&
                bool.TryParse(getClear, out bool _) &&
                Once(OnceAction.Clear, storageID))
            {
                getQuery.TryGetValue("storage", out string getStorage);
                Enum.TryParse <Storage>(getStorage, true, out Storage clearStorage);
                StorageImplementation.Clear(HttpContext, clearStorage, storage, storageID);
            }

            V    viewModel;
            Guid sessionOverride;
            Guid session;

            byte[] bytes;
            Func <byte[], byte[]> filter;

            if (getQuery != null &&
                getQuery.TryGetValue("session", out string getSession) &&
                Guid.TryParse(getSession, out sessionOverride) &&
                Once(OnceAction.Load, storageID))
            {
                // ---------- Direct Load Database ----------
                viewModel       = new V();
                (bytes, filter) = StorageImplementation.DatabaseBytes(Configuration, HttpContext, storageID, sessionOverride);
                viewModel.Main  = (M)StorageImplementation.LoadFromBytes(() => new M(), bytes, filter);
            }
            else
            {
                // ---------- Load ViewState ----------
                if (storage == Storage.ViewState)
                {
                    viewModel           = new V();
                    filter              = StorageImplementation.DecryptViewState(Configuration);
                    viewModel.ViewState = viewState;
                    viewModel.DeserializeMain(filter);
                }

                // ---------- Load Session ----------
                else if (storage == Storage.Session)
                {
                    HttpContext.Session.TryGetValue(storageID, out bytes);
                    viewModel = new V();
                    viewModel.SetMain(StorageImplementation.LoadFromBytes(() => new M(), bytes));
                }

                // ---------- Load Database ----------
                else if (storage == Storage.Database)
                {
                    Guid.TryParse(HttpContext.Request.Cookies[storageID].FromCookieString()["session"], out session);
                    (bytes, filter) = StorageImplementation.DatabaseBytes(Configuration, HttpContext, storageID, session);
                    viewModel       = new V();
                    viewModel.SetMain(StorageImplementation.LoadFromBytes(() => new M(), bytes, filter));
                }
                else
                {
                    throw new NotImplementedException("Storage {0} not implemented");
                }
            }

            // Now that an instance is guaranteed remember the storage type for Save() and the client.
            viewModel.SessionStorage  = storage;
            viewModel.VSessionStorage = storage.ToString();

            // An instantiated Main is now guaranteed -> make its members
            // visible to WebSharper:
            viewModel.LoadMembers();

            // Include the ViewModel instance as member of the returned Main
            viewModel.Main.ViewModel = viewModel;

            // Set a reference to the ViewModel
            viewModelAccessor = viewModel;

            return(viewModel.Main);
        }
Beispiel #20
0
 public ContactController(StorageImplementation storageImplementation)
 {
     _storageImplementation = storageImplementation;
 }