ASP.NET is a web development platform provided by Microsoft that is used for creating web-based applications. It allows applications to be written in languages like C#, VB.Net, and J#. ASP.NET uses a request-response model where requests are handled by the web server which returns responses to the client. It has a set of standard class libraries, the most used being the Web library which contains components for developing web applications. ASP.NET applications go through a page lifecycle on each request, initializing objects and allowing events to be handled at each stage before a response is returned.
ReactJS is a JavaScript library for building user interfaces. It uses a virtual DOM and only updates parts of the real DOM that changed. React uses a component-based architecture where data flows unidirectionally via props and state. Lifecycle methods allow components to handle state changes. Components are built with JSX syntax and can be nested to build up an application from reusable pieces.
C sharp and asp.net interview questionsAkhil Mittal
The document provides summaries of common questions and answers related to ASP.NET, C#, and the .NET framework. It defines view state as storing the current property settings of an ASP.NET page and controls to detect form submissions. It explains that user controls allow reusing ASP.NET pages as controls, and validation controls perform input checking on server controls. The document also distinguishes between Response.Write and Response.Output.Write, and lists page life cycle methods like Init, Load, and Unload.
1. The document discusses using Meteor for building mobile applications. Key features of Meteor like automatic data synchronization and Cordova integration are highlighted.
2. Various patterns for structuring Meteor mobile apps are presented, including organizing the project structure, using templates, helpers, and subscriptions to keep data updated.
3. The document also provides an example of how to build a mobile approval application with Meteor that integrates with multiple backend systems and allows approving/denying requests from any device.
This document discusses working with servlets and session tracking in Java. It explores the ServletConfig and ServletContext interfaces, and how to implement session tracking using HttpSession, cookies, and URL rewriting. The objectives are to learn how to access configuration information from servlets, set and get attributes in the servlet context, and maintain state across HTTP requests using different session tracking mechanisms.
The document provides an introduction and overview of ASP.NET MVC, covering topics such as routing, controllers, actions, views, and passing data between controllers and views. It compares ASP.NET MVC to traditional ASP.NET WebForms, outlines the MVC architecture and project structure, and describes how routing maps URLs to controller actions. Key aspects of controllers, views, partial views, HTML helpers, and view engines are also summarized.
This document discusses Angular resolvers, which are used to pre-fetch data before navigating to a component. Angular resolvers implement the Resolve interface to return data via Observable or Promise before the route is activated. An example is provided demonstrating how to create a resolver service to fetch product data from an API, configure routes to use the resolver, and access the resolved data in a component. A loading spinner is also added to improve the user experience while data is loading.
To anyone interested in accelerating their Test Automation work, here's an article that could well help to point the way ahead!
It also covers the production of multi-lingual validation data.
The document provides an overview of web services in Salesforce, specifically covering SOAP and REST web services. It defines SOAP and REST, compares the two approaches, and provides guidance on when to use each. It also covers how to create and consume SOAP web services in Salesforce, including exposing a SOAP web service publicly and making callouts to external web services. Security considerations for callouts like authentication and encryption are also briefly discussed.
This document provides an introduction and overview of Struts, an MVC framework for Java web applications. It discusses Struts' main components and design patterns, including:
- Struts acts as an MVC framework, providing utilities for web app development using the MVC pattern.
- The framework has 3 main components - Controller, View, and Model.
- Struts uses the standard MVC design of separating data, presentation, and business logic into separate but interacting elements.
This document discusses the benefits of using the .NET framework for web development. It begins by explaining that .NET compiles code to intermediate language (IL) rather than machine code. This allows the common language runtime (CLR) to manage aspects like garbage collection and exception handling. ASP.NET uses dynamic compilation for improved performance. The .NET framework also includes a large set of reusable classes. Additional benefits discussed include object-oriented architecture, caching, XML configuration, code separation, mobile support, powerful data access, language preference, and easy creation of web services.
This technical article explains personalization concept in Webcenter Portal. It also provides steps to create a scenario and use it in Webcenter Portal.
The document provides a multiple choice quiz on Spring Framework concepts. It includes 10 multiple choice questions covering topics like Spring modules, bean scopes, annotation-driven configuration, Spring MVC, transactions, dependency injection, and Aspect Oriented Programming (AOP). It also includes 5 open-ended questions asking about Maven/Gradle, the web.xml file, the <annotation-driven/> tag, ViewResolvers in Spring, and descriptions of common annotations with examples.
Understanding router state in angular 7 passing data through angular router s...Katy Slemon
Understanding Router State in Angular 7: Check out this tutorial to explore the new Angular feature for passing data through Angular RouterState with a demo app
The document discusses developing custom ASP.NET AJAX client components and server controls. It covers the key steps which are:
1) Developing the reusable client component code using the ASP.NET AJAX prototype model.
2) Creating an associated server control that emits the required JavaScript to register and initialize the client component.
3) Wiring up the server control to load and instantiate the client component code.
Mvc interview questions – deep dive jinal desaijinaldesailive
Can you describe ASP.NET MVC Request Life Cycle? 1. Receive request, look up Route object in RouteTable collection and create RouteData object. 2. Create RequestContext instance. 3. Create MvcHandler and pass RequestContext to handler. 4. Identify IControllerFactory from RequestContext. 5. Create instance of class that implements ControllerBase. 6. Call MyController.Execute method. 7. The ControllerActionInvoker determines which action to invoke on the controller and executes the action on the controller, which results in calling the model and returning a view.
The document provides an overview of middleware in Node.js and Express. It defines middleware as functions that have access to the request and response objects and can run code and make changes to these objects before the next middleware in the chain. It discusses common uses of middleware like logging, authentication, parsing request bodies. It also covers Connect middleware and how Express builds on Connect by adding features like routing and views. Key aspects covered include the middleware pipeline concept, error handling with middleware, and common middleware modules.
Repository Pattern in MVC3 Application with Entity FrameworkAkhil Mittal
The document discusses implementing a repository pattern in an MVC application using Entity Framework. It begins with an introduction and roadmap of previous articles. It then discusses the benefits of a repository pattern in abstracting the data access layer from business logic. Steps are provided to create a sample repository interface and class to implement basic CRUD operations on a User entity, abstracting the data access code from the controller. The repository class uses the Entity Framework context to perform operations while resolving tight coupling issues between layers. It concludes that while this implementation works for a single entity, a generic repository will be needed to cleanly support multiple entities without duplication.
Ember is an open source JavaScript framework that uses a strict MVC pattern. It avoids boilerplate code and creates standard application architecture. Ember follows a pure MVC pattern to improve testability and keep application code modular. The document then discusses Ember's routing, templating with Handlebars, defining models and controllers, and the overall application lifecycle.
Adding a modern twist to legacy web applicationsJeff Durta
Avoid misery of working with legacy code
We will see how you can add independent and isolated components to existing pages; pages that may be difficult to change
React and Flux allow you to make self-contained additions that handle their own data access/persistence
Backbone.js is a lightweight JavaScript framework that provides structure to client-side code through an MVC pattern. It connects a single-page application to a backend via RESTful JSON and allows fetching and saving data without full page refreshes. Backbone provides models to represent data, views to handle the UI, and collections to manage groups of models. Events allow views to update dynamically when models change. It aims to increase code organization and reuse while keeping the framework lightweight.
The document outlines the requirements and topics to be covered in an Android training, including developing layouts using XML and Java, running and debugging Android applications, using intents and bundles to pass data between activities, and handling basic data storage using SQLite and memory management. It also provides references and questions for trainees to refer to for more information on Android development concepts and best practices.
Murach: How to validate data in asp.net core mvcMahmoudOHassouna
- You can validate user-input data in ASP.NET MVC using data attributes on model properties and custom validation attributes. Data attributes like Required, Range, StringLength allow property-level validation, while custom attributes can perform cross-field and custom validation logic.
- Client-side validation is enabled by default and prevents invalid submissions, but server-side validation in the controller is also needed as the only authorization. You can customize validation error messages and UI.
Ad
More Related Content
Similar to Murach : How to work with session state and cookies (20)
This document discusses Angular resolvers, which are used to pre-fetch data before navigating to a component. Angular resolvers implement the Resolve interface to return data via Observable or Promise before the route is activated. An example is provided demonstrating how to create a resolver service to fetch product data from an API, configure routes to use the resolver, and access the resolved data in a component. A loading spinner is also added to improve the user experience while data is loading.
To anyone interested in accelerating their Test Automation work, here's an article that could well help to point the way ahead!
It also covers the production of multi-lingual validation data.
The document provides an overview of web services in Salesforce, specifically covering SOAP and REST web services. It defines SOAP and REST, compares the two approaches, and provides guidance on when to use each. It also covers how to create and consume SOAP web services in Salesforce, including exposing a SOAP web service publicly and making callouts to external web services. Security considerations for callouts like authentication and encryption are also briefly discussed.
This document provides an introduction and overview of Struts, an MVC framework for Java web applications. It discusses Struts' main components and design patterns, including:
- Struts acts as an MVC framework, providing utilities for web app development using the MVC pattern.
- The framework has 3 main components - Controller, View, and Model.
- Struts uses the standard MVC design of separating data, presentation, and business logic into separate but interacting elements.
This document discusses the benefits of using the .NET framework for web development. It begins by explaining that .NET compiles code to intermediate language (IL) rather than machine code. This allows the common language runtime (CLR) to manage aspects like garbage collection and exception handling. ASP.NET uses dynamic compilation for improved performance. The .NET framework also includes a large set of reusable classes. Additional benefits discussed include object-oriented architecture, caching, XML configuration, code separation, mobile support, powerful data access, language preference, and easy creation of web services.
This technical article explains personalization concept in Webcenter Portal. It also provides steps to create a scenario and use it in Webcenter Portal.
The document provides a multiple choice quiz on Spring Framework concepts. It includes 10 multiple choice questions covering topics like Spring modules, bean scopes, annotation-driven configuration, Spring MVC, transactions, dependency injection, and Aspect Oriented Programming (AOP). It also includes 5 open-ended questions asking about Maven/Gradle, the web.xml file, the <annotation-driven/> tag, ViewResolvers in Spring, and descriptions of common annotations with examples.
Understanding router state in angular 7 passing data through angular router s...Katy Slemon
Understanding Router State in Angular 7: Check out this tutorial to explore the new Angular feature for passing data through Angular RouterState with a demo app
The document discusses developing custom ASP.NET AJAX client components and server controls. It covers the key steps which are:
1) Developing the reusable client component code using the ASP.NET AJAX prototype model.
2) Creating an associated server control that emits the required JavaScript to register and initialize the client component.
3) Wiring up the server control to load and instantiate the client component code.
Mvc interview questions – deep dive jinal desaijinaldesailive
Can you describe ASP.NET MVC Request Life Cycle? 1. Receive request, look up Route object in RouteTable collection and create RouteData object. 2. Create RequestContext instance. 3. Create MvcHandler and pass RequestContext to handler. 4. Identify IControllerFactory from RequestContext. 5. Create instance of class that implements ControllerBase. 6. Call MyController.Execute method. 7. The ControllerActionInvoker determines which action to invoke on the controller and executes the action on the controller, which results in calling the model and returning a view.
The document provides an overview of middleware in Node.js and Express. It defines middleware as functions that have access to the request and response objects and can run code and make changes to these objects before the next middleware in the chain. It discusses common uses of middleware like logging, authentication, parsing request bodies. It also covers Connect middleware and how Express builds on Connect by adding features like routing and views. Key aspects covered include the middleware pipeline concept, error handling with middleware, and common middleware modules.
Repository Pattern in MVC3 Application with Entity FrameworkAkhil Mittal
The document discusses implementing a repository pattern in an MVC application using Entity Framework. It begins with an introduction and roadmap of previous articles. It then discusses the benefits of a repository pattern in abstracting the data access layer from business logic. Steps are provided to create a sample repository interface and class to implement basic CRUD operations on a User entity, abstracting the data access code from the controller. The repository class uses the Entity Framework context to perform operations while resolving tight coupling issues between layers. It concludes that while this implementation works for a single entity, a generic repository will be needed to cleanly support multiple entities without duplication.
Ember is an open source JavaScript framework that uses a strict MVC pattern. It avoids boilerplate code and creates standard application architecture. Ember follows a pure MVC pattern to improve testability and keep application code modular. The document then discusses Ember's routing, templating with Handlebars, defining models and controllers, and the overall application lifecycle.
Adding a modern twist to legacy web applicationsJeff Durta
Avoid misery of working with legacy code
We will see how you can add independent and isolated components to existing pages; pages that may be difficult to change
React and Flux allow you to make self-contained additions that handle their own data access/persistence
Backbone.js is a lightweight JavaScript framework that provides structure to client-side code through an MVC pattern. It connects a single-page application to a backend via RESTful JSON and allows fetching and saving data without full page refreshes. Backbone provides models to represent data, views to handle the UI, and collections to manage groups of models. Events allow views to update dynamically when models change. It aims to increase code organization and reuse while keeping the framework lightweight.
The document outlines the requirements and topics to be covered in an Android training, including developing layouts using XML and Java, running and debugging Android applications, using intents and bundles to pass data between activities, and handling basic data storage using SQLite and memory management. It also provides references and questions for trainees to refer to for more information on Android development concepts and best practices.
Murach: How to validate data in asp.net core mvcMahmoudOHassouna
- You can validate user-input data in ASP.NET MVC using data attributes on model properties and custom validation attributes. Data attributes like Required, Range, StringLength allow property-level validation, while custom attributes can perform cross-field and custom validation logic.
- Client-side validation is enabled by default and prevents invalid submissions, but server-side validation in the controller is also needed as the only authorization. You can customize validation error messages and UI.
Murach: An introduction to web programming with ASP.NET Core MVCMahmoudOHassouna
Murach: An introduction to web programming with ASP.NET Core MVC
Mary Delamater, Joel Murach - Murach's ASP.NET Core MVC-Mike Murach & Associates, Inc. (2020) (1)
The document describes how to build a Movie List application using ASP.NET MVC and Entity Framework Core by explaining how to set up the model classes, controllers, views, and database context to display, add, edit and delete movie data, relating movies to genres and making the URLs more user-friendly. It provides code examples for each part of the application.
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schoolsdogden2
Algebra 1 is often described as a “gateway” class, a pivotal moment that can shape the rest of a student’s K–12 education. Early access is key: successfully completing Algebra 1 in middle school allows students to complete advanced math and science coursework in high school, which research shows lead to higher wages and lower rates of unemployment in adulthood.
Learn how The Atlanta Public Schools is using their data to create a more equitable enrollment in middle school Algebra classes.
Geography Sem II Unit 1C Correlation of Geography with other school subjectsProfDrShaikhImran
The correlation of school subjects refers to the interconnectedness and mutual reinforcement between different academic disciplines. This concept highlights how knowledge and skills in one subject can support, enhance, or overlap with learning in another. Recognizing these correlations helps in creating a more holistic and meaningful educational experience.
How to Customize Your Financial Reports & Tax Reports With Odoo 17 AccountingCeline George
The Accounting module in Odoo 17 is a complete tool designed to manage all financial aspects of a business. Odoo offers a comprehensive set of tools for generating financial and tax reports, which are crucial for managing a company's finances and ensuring compliance with tax regulations.
Envenomation is the process by which venom is injected by the bite or sting of a venomous animal such as a snake, scorpion, spider, or insect. Arthropod bite is nothing but a sharp bite or sting by ants, fruit flies, bees, beetles, moths, or hornets. Though not a serious condition, arthropod bite can be extremely painful, with redness and mild to severe swelling around the site of the bite
As of Mid to April Ending, I am building a new Reiki-Yoga Series. No worries, they are free workshops. So far, I have 3 presentations so its a gradual process. If interested visit: https://www.slideshare.net/YogaPrincess
https://ldmchapels.weebly.com
Blessings and Happy Spring. We are hitting Mid Season.
Odoo Inventory Rules and Routes v17 - Odoo SlidesCeline George
Odoo's inventory management system is highly flexible and powerful, allowing businesses to efficiently manage their stock operations through the use of Rules and Routes.
INTRO TO STATISTICS
INTRO TO SPSS INTERFACE
CLEANING MULTIPLE CHOICE RESPONSE DATA WITH EXCEL
ANALYZING MULTIPLE CHOICE RESPONSE DATA
INTERPRETATION
Q & A SESSION
PRACTICAL HANDS-ON ACTIVITY
Vitamins Chapter-7, Biochemistry and clinical pathology, D.Pharm 2nd yearARUN KUMAR
Definition and classification with examples
Sources, chemical nature, functions, coenzyme form, recommended dietary requirements, deficiency diseases of fat- and water-soluble vitamins
A measles outbreak originating in West Texas has been linked to confirmed cases in New Mexico, with additional cases reported in Oklahoma and Kansas. The current case count is 771 from Texas, New Mexico, Oklahoma, and Kansas. 72 individuals have required hospitalization, and 3 deaths, 2 children in Texas and one adult in New Mexico. These fatalities mark the first measles-related deaths in the United States since 2015 and the first pediatric measles death since 2003.
The YSPH Virtual Medical Operations Center Briefs (VMOC) were created as a service-learning project by faculty and graduate students at the Yale School of Public Health in response to the 2010 Haiti Earthquake. Each year, the VMOC Briefs are produced by students enrolled in Environmental Health Science Course 581 - Public Health Emergencies: Disaster Planning and Response. These briefs compile diverse information sources – including status reports, maps, news articles, and web content– into a single, easily digestible document that can be widely shared and used interactively. Key features of this report include:
- Comprehensive Overview: Provides situation updates, maps, relevant news, and web resources.
- Accessibility: Designed for easy reading, wide distribution, and interactive use.
- Collaboration: The “unlocked" format enables other responders to share, copy, and adapt seamlessly.
The students learn by doing, quickly discovering how and where to find critical information and presenting it in an easily understood manner.
Understanding P–N Junction Semiconductors: A Beginner’s GuideGS Virdi
Dive into the fundamentals of P–N junctions, the heart of every diode and semiconductor device. In this concise presentation, Dr. G.S. Virdi (Former Chief Scientist, CSIR-CEERI Pilani) covers:
What Is a P–N Junction? Learn how P-type and N-type materials join to create a diode.
Depletion Region & Biasing: See how forward and reverse bias shape the voltage–current behavior.
V–I Characteristics: Understand the curve that defines diode operation.
Real-World Uses: Discover common applications in rectifiers, signal clipping, and more.
Ideal for electronics students, hobbyists, and engineers seeking a clear, practical introduction to P–N junction semiconductors.
How to manage Multiple Warehouses for multiple floors in odoo point of saleCeline George
The need for multiple warehouses and effective inventory management is crucial for companies aiming to optimize their operations, enhance customer satisfaction, and maintain a competitive edge.
In this ppt I have tried to give basic idea about Diabetic peripheral and autonomic neuropathy ..from Levine textbook,IWGDF guideline etc
Hope it will b helpful for trainee and physician
Exploring Substances:
Acidic, Basic, and
Neutral
Welcome to the fascinating world of acids and bases! Join siblings Ashwin and
Keerthi as they explore the colorful world of substances at their school's
National Science Day fair. Their adventure begins with a mysterious white paper
that reveals hidden messages when sprayed with a special liquid.
In this presentation, we'll discover how different substances can be classified as
acidic, basic, or neutral. We'll explore natural indicators like litmus, red rose
extract, and turmeric that help us identify these substances through color
changes. We'll also learn about neutralization reactions and their applications in
our daily lives.
by sandeep swamy
2. How ASP.NET MVC handles
state
The data that a web app maintains for a user,
such as variables, is the state of
that app. However, HTTP is a stateless protocol. This
means that HTTP doesn’t
keep track of an app’s state between round trips.
Rather, once a browser makes a
request and receives a response, the app
terminates and its state is lost.
6. Description
State refers to the current status of the properties, variables,
and other data maintained by an app for a single user.
HTTP is a stateless protocol. That means that it doesn’t keep
track of state between round trips. Once a browser makes a
request and receives a response, the app terminates and its
state is lost.
ASP.NET Core MVC provides several ways to maintain the state
of a web app. A cookie is a key/value pair passed to the user in
an HTTP response and passed back to the server with each
subsequent HTTP request. Session state works by having the
server store the session data for a user and by
using a cookie to associate the user’s web browser with the
correct session data.
7. How to work with session
state
Session state allows you to store data that you
want to persist across multiple
HTTP requests. This feature is extremely useful and
commonly used by many
types of web apps such as shopping cart apps.
8. The ConfigureServices() method
in the Startup.cs file
public void ConfigureServices(IServiceCollection services)
{
...
// must be called before AddControllersWithViews()
services.AddMemoryCache();
services.AddSession();
services.AddControllersWithViews();
...
app.UseSession();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
9. •
# The Configure() method in the
Startup.cs file
public void Configure(IAppBuilder app, IHostingEnvironment env)
{
...
// must be called before UseEndpoints()
app.UseSession();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
...
}
10. services.AddSession(options =>
{
// change idle timeout to 5 minutes -
default is 20 minutes
options.IdleTimeout =
TimeSpan.FromSeconds(60 * 5);
options.Cookie.HttpOnly = false; //
default is true
options.Cookie.IsEssential = true; //
default is false
});
11. Description
By default, session state is not
enabled. To enable it, you can add
code to the ConfigureServices() and
Configure() methods in the Startup.cs
file that calls the AddMemoryCache(),
AddSession(), and UseSession()
methods in the correct sequence.
To change the default settings for
session state, you can use a lambda
expression to pass a SessionOptions
object to the AddSession() method.
12. Methods of the ISession interface
that set, get, and remove items
13. A using directive for session state in a
controller
using Microsoft.AspNetCore.Http;
An action method that gets and sets a
session state value
public ViewResult Index() {
int num = HttpContext.Session.GetInt32("num");
num += 1;
HttpContext.Session.SetInt32("num", num);
return View();
}
14. A using directive for session state in a
view
@using Microsoft.AspNetCore.Http
A Razor code block that gets a session
state value
@{
int num = Context.Session.GetInt32("num");
}
A Razor expression that gets a session
state value
<div>@Context.Session.GetInt32("num")</div>
15. Description
The Http Context class has a property named Session that
implements IS ession and thus provides methods for setting, getting,
and removing items in session state.
To enable all the functionality of the Session property, you must
import the Microsoft.AspNetCore.Http namespace.
A controller has an Http Context property that has a data type of
Http Context.
A view has a Context property that has a data type of HttpContext.
In ASP.NET Core MVC, session state can only store int and string
values. However, you can extend session state so it can store more
complex types as shown in the next figure.
16. How to add the New ton soft JSON
Nu Get package to your app
Use the Tools--NuGet Package Manager--Manage NuGet Packages
for Solutioncommand to open the NuGet Package Manager.
Click the Browse link.
Type “Microsoft.AspNetCore.Mvc.NewtonsoftJson” in the search
box.
Click on the appropriate package from the list that appears in the
left-hand panel.
In the right-hand panel, check the project name, select the version
that matches the version of .NET Core you’re running, and click
Install.
Review the Preview Changes dialog that comes up and click OK.
Review the License Acceptance dialog that comes up and click I
Accept.
17. How to configure your app to use
the Newtonsoft JSON library
public void ConfigureServices(IServiceCollection
services) {
...
services.AddMemoryCache();
services.AddSession();
services.AddControllersWithViews().AddNewtonsoft
Json();
...
}
18. A using directive that imports the Newtonsoft JSON
library
using Newtonsoft.Json;
Two static methods of the JsonConvert class
19. Code in an action method that sets a Team
object in session state
Team team = new Team { TeamID = "sea", Name =
"Seattle Seahawks" };
string teamJson = JsonConvert.SerializeObject(team);
HttpContext.Session.SetString("team", teamJSON);
Code in an action method that gets a Team
object from session state
string teamJson = HttpContext.Session.GetString("team");
Team team =
JsonConvert.DeserializeObject<Team>(teamJson);
20. Description
•JSON (JavaScript Object Notation) is a data
format that facilitates the transfer of data.
To serialize .NET objects to JSON strings and back
again, you can use the open-source Newtonsoft
Json.NET library.
You can use the JsonIgnore attribute of the
Newtonsoft.Json namespace to mark properties in
an object that you don’t want to serialize.
21. Two extension methods for the ISession
interface
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
public static class SessionExtensions
{
public static void SetObject<T>(this ISession session,
string key, T value)
{
session.SetString(key, JsonConvert.SerializeObject(value));
}
public static T GetObject<T>(this ISession session, string key)
{
var valueJson = session.GetString(key);
if (string.IsNullOrEmpty(value)) {
return default(T);
}
else {
return JsonConvert.DeserializeObject<T>(valueJson);
}
}
}
22. Code that uses the extension
methods towork with a single
In a controller
var team = HttpContext.Session.GetObject<Team>("team") ??
newTeam(); team.Name = "Seattle Seahawks";
HttpContext.Session.SetObject("team", team);
In a view
@{
var team = Context.Session.GetObject<Team>("team");
}
23. Code that uses the extension methods
to work with a list of teams
In a controller
var teams =
HttpContext.Session.GetObject<List<Team>>("teams") ??
new List<Team>();
teams.Add(new Team { TeamID = "gb", Name = "Green Bay
Packers" });
HttpContext.Session.SetObject("teams", teams);
In a view
@{
var teams =
Context.Session.GetObject<List<Team>>("teams");
}
24. Description
To make it easier to store objects in
session state, you can add
extension methods to the ISession
interface.
25. A wrapper class that encapsulates the
code for working with session state
26. Code that uses the wrapper class
to work with a list of teams
27. Description
To make it easier to work with
session state in your app, you can
create a wrapper class that
encapsulates the using directives,
method calls, and string keys in one
place.
A wrapper class can call extension
methods from the ISession interface
like the ones shown in the previous
figure.
28. The NFL Teams 3.0 app
The next few topics present a version of
the NFL Teams app that keeps track of a
user’s favorite teams in session state. Since
this app updates the NFL Teams app that
was presented in chapter 8, this chapter
only presents code that is new or
changed. If you haven’t read chapter 8
yet, you should at least review that
chapter before you continue.
32. Description
This version of the NFL Teams app enhances the
apps presented in chapter 8. It allows you to add a
team to your favorites and view your favorite
teams.
38. Description
The layout checks whether TempData stores
a message. If so, it displays that message.
The layout checks whether the current
page is the Favorites page. If not, it displays
a link to the Favorites page, gets the
number of favorite teams from session state,
and displays that number in a Bootstrap
badge.
39. Some code from the
Home/Index view
<div class="col-sm-9">
<ul class="list-inline">
@foreach (Team team in Model.Teams)
{
<li class="list-inline-item">
<a asp-action="Details" asp-route-id="@team.TeamID">
<img src="~/images/@team.LogoImage" alt="@team.Name"
title="@team.Name | @team.Conference.Name
@team.Division.Name" />
</a>
</li>
}
</ul>
</div>
40. Some code from theHome
/Details view
<li class="list-group-item">
<form asp-action="Add" method="post">
<a asp-action="Index" class="btn btn-primary"
asp-route-activeConf="@Model.ActiveConf"
asp-route-activeDiv="@Model.ActiveDiv">
Return to Home Page</a>
<button type="submit" class="btn btn-primary">
Add to Favorites
</button>
<input type="hidden" asp-for="Team.TeamID" />
</form>
</li>
41. Description
The Home/Index view displays the images for the teams as links.
The Home/Details view includes an “Add to Favorites” button
that uses a <form> element to post the team ID to the Add()
action method.
The Home/Details view includes a “Return to Home Page” link
that’s styled as a button. This link returns to the Home page with
the active conference and division selected.
43. Description
The Favorites controller has two action methods
.
The Index() action method is called when a user clicks the My
Favorite Teams link. This action method retrieves data from session
state and transfers it to the view for display.
The Delete() action method is called when a user clicks the Clear
Favorites button on the Favorites page. This action method
removes the favorite teams from session state and redirects the
user to the Home page using data from session state.
45. Description
The Favorites/Index view displays information
about the teams that users have added to their
favorites. In addition, it includes a button and a
link that has been styled as a button.
The “Clear Favorites” button uses a <form>
element to call the Delete() action method of the
Favorites controller with a POST request.
The “Return to Home Page” link gets the Home
page with the active conference and division
selected.
46. How to work with cookies
A cookie is a key/value pair that’s stored in the user’s browser
or on the user’s disk. A web app sends a cookie to a browser
via an HTTP response. Then,
each time the browser sends an HTTP request to the server, it
sends that cookie back.
A session cookie is stored in the browser’s memory and exists
only for the
duration of the browser session. A persistent cookie, on the other
hand, is stored on the user’s disk and is retained until the
cookie’s expiration date, or until the
user clears the cookie.
47. How to work with
persistent cookies
The second table presents some of the properties of the
CookieOptions class.
This class allows you to change some of the settings of a cookie
and is stored in the Microsoft.AspNetCore.Http namespace.
As a result, to use it, you need to include a using directive like
the one shown in the first code example below this table.
48. To set a persistent cookie, you need to set the Expires property
of the CookieOptions class. To do that, you create a
CookieOptions object, set its Expires property to a DateTime
value, and
include the CookieOptions object when you
create a cookie. This is shown by the last example in this figure. To
start, it creates a new
CookieOptions object with an Expires property of 30 days from
the current date and time. Then, it passes that object to the
Append() method as the third argument.
50. Code that sets a session cookie
Response.Cookies.Append("username",
"Grace");
Code that deletes a cookie
Response.Cookies.Delete("username");
Code that gets a cookie
string value =
Request.Cookies["username"]; //
brackets, not parentheses
51. Some of the properties of
the Cookie Options class
52. A using directive that’s necessary to work with the
Cookie Options class
using Microsoft.AspNetCore.Http;
Code that sets a persistent cookie
var options = new CookieOptions { Expires =
DateTime.Now.AddDays(30) };
Response.Cookies.Append("username", "Grace",
options);
53. Description
A cookie is a key/value pair that’s stored in the
user’s browser or on the user’s disk.
A web app sends a cookie to a browser via an HTTP
response. Then, each time the browser sends an
HTTP request to the server, it sends that cookie back.
A session cookie is stored in the browser’s memory
and exists only for the duration of the browser
session.
A persistent cookie is stored on the user’s disk and is
retained until the cookie’s expiration date or until the
user clears the cookie.
54. The NFL Teams 4.0 app
Now that you know how to work with cookies, you’re ready to
see a version of the NFL Teams app after it has been updated
to
store the IDs of the user’s favorite teams in a persistent cookie.
That way, the app
“remembers” its users’ favorite teams, even when its users close
their browsers and return to this app later.
55. The updated session class
Figure 9-15 shows the NFLSession class. This class works like the
NFLSession class shown earlier in this chapter, but its
GetMyTeamCount() method returns a nullable int type, not a
regular int type. This makes it possible to check whether a session
state
object already exists or whether you should initialize a new
object by getting data from cookies.
56. The NFL Cookies class
using Microsoft.AspNetCore.Http;
public class NFLCookies
{
private const string MyTeams = "myteams";
private const string Delimiter = "-";
private IRequestCookieCollection requestCookies { get; set; }
private IResponseCookies responseCookies { get; set; }
public NFLCookies(IRequestCookieCollection cookies) {
requestCookies = cookies;
}
public NFLCookies(IResponseCookies cookies) {
responseCookies = cookies;
}
57. The NFL Cookies class
public void SetMyTeamIds(List<Team> myteams){
List<string> ids = myteams.Select(t => t.TeamID).ToList();
string idsString = String.Join(Delimiter, ids);
CookieOptions options = new CookieOptions {
Expires = DateTime.Now.AddDays(30)
};
RemoveMyTeamIds(); // delete old cookie first
responseCookies.Append(MyTeams, idsString, options);
}
58. The NFL Cookies class
public string[] GetMyTeamsIds() {
string cookie =
requestCookies[MyTeams];
if (string.IsNullOrEmpty(cookie))
return new string[] { }; // empty
string array else
return cookie.Split(Delimiter);
}
public void RemoveMyTeamIds(){
responseCookies.Delete(MyTeams); } }
60. Description
This app stores the IDs of the user’s favorite teams in a persistent
cookie.
The NFLCookies class has an overloaded constructor that can
accept the Cookies
collection from the Request object or from the Response object.
The GetMyTeamCount() method of the NFLSession class now
returns a nullable int.
63. Description
The Index() action method uses the cookie
collection of the Request object to get the user’s
favorite teams from a persistent cookie. Then, it
stores them in session state.
The Add() action method uses the cookie
collection of the Response object to update the
data in the persistent cookie. But first, it updates
session state.
64. The updated Favorites
controller
This action method works like the Delete() action method presented
in figure
9-12. However, it also removes the persistent cookie that holds the
IDs of the
user’s favorite teams after it removes those teams from session state.
To delete the cookie, the code creates a new NFLCookies object
and passes
it the Cookies collection of the controller’s Response object. Then,
this code
calls the RemoveMyTeamIds() method of the NFLCookies object.
66. Description
The Delete() action method of the Favorites
controller removes the persistent
cookie that stores the IDs of the favorite teams.
But first, it removes the favorite teams from session
state.